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
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write
2026-07-19-package-invariant-runtime-contracts.md: 65986fc0b3aab695d8512d9e221052e1db83445f
2026-07-19-package-invariant-runtime-contracts.zh.md: 0ae0bd305692ee71359c5500e477dee22575a9ef
2026-07-19-package-invariant-runtime-contracts.md: 4e15842d1228d82621f91caa18cbe02fd5407dd8
2026-07-19-package-invariant-runtime-contracts.zh.md: 88b1eb1a79d88865515617d6737fbded10a13b6e
@@ -1,4 +1,4 @@
# Agent Note: Executable package invariant contracts
# Agent Note: Meaningful package invariant contracts
Status: implemented
@@ -6,60 +6,70 @@ English | [中文](2026-07-19-package-invariant-runtime-contracts.zh.md)
## Problem
The package-owned invariant seam made registration and publication exhaustive, but its generated baseline treated package-name ownership as sufficient. An empty installer could satisfy the repository gate while observing no runtime state and rejecting no invalid state. That made the exhaustive count a wiring claim rather than protection for the package contract.
The package-owned invariant seam made publication and registration exhaustive, but its first generated baseline accepted empty installers. A follow-up then replaced those empties with generic assertions about plugin names, injections, effects, service methods, and fixed pure-library examples. Those assertions made every companion executable without making the system safer: TypeScript, Cordis startup, package tests, and module-load tests already enforce those shapes, while the invariant service should detect impossible runtime state.
Every package shape cannot use the same invariant. Cordis plugins own fibers, injections, effects, and services; service seams admit structural third-party implementations; stateful domains need event relations; pure libraries and bin packages expose algebra, parsing, normalization, or entrypoint constraints. The repository needs one enforceable obligation without moving those contracts back into a central product-aware package.
A useful runtime invariant relates observations over time or across a mutable data structure. Examples include a terminal event without its start, an LLM delta for a block that is not open, or a durable result whose identity differs from its request. Merely confirming that a declared method exists, that a plugin has its expected name, or that a constant example still returns a known value is not such a relation.
Vitest mounts each package test's owning companion globally, and one exhaustive topology mounts every companion. Companion modules therefore cannot eagerly import every product entrypoint before a test module establishes its hoisted mocks, and a name-based observer cannot mistake an anonymous child fiber that inherits its parent's display name for the package plugin itself.
Some packages genuinely own no continuously observable relation. Pure utilities, composition-only packages, thin adapters, binaries, and test-support packages may have important contracts, but those contracts are better enforced by types, load checks, focused unit tests, or integration tests. Requiring a synthetic runtime assertion for those packages would optimize for satisfying a gate instead of detecting corruption.
## Decision
### Every companion executes a package contract
### Registration is exhaustive; assertions must be meaningful
Every workspace package keeps its separately published `./invariant` companion and exact npm-name registration, but the installer must execute at least one package-specific check through the bound `fail(message)` reporter. The ownership-baseline generator and its root script entry are removed; generated markers, empty installers, and installers that never reference the reporter are repository errors.
Every workspace package publishes a separately built `./invariant` companion and registers its exact npm package name. A companion does one of two things:
The implemented contracts use four forms:
- installs a package-owned check over an event stream or relevant mutable data structure and reports violations through its bound `fail(message)` reporter; or
- uses an empty installer whose declaration has an owner-specific `No runtime invariant:` comment explaining why the package has no plausible runtime relation to observe.
| Owner shape | Runtime contract |
The empty form is an explicit architectural conclusion, not a generated placeholder. A future package change that introduces mutable state or an event protocol must replace the explanation with the corresponding check.
The central `dsh-invariants` service owns only configuration, registration uniqueness, child-fiber lifecycle, rollback, disposal, and package-attributed failure. It exposes no generic plugin-shape, service-shape, or startup-assertion helpers and imports no product package.
### Implemented checks
The current 91-package workspace has 18 executable companions and 73 justified empty companions.
| Owner | Runtime relationship |
|---|---|
| Stateful session, agent, scope, and agent-loop owners | Validate event ordering, enclosure, status transitions, scoped subjects, and reconstructable model requests. |
| Cordis plugin owners | Validate the plugin's own declared runtime name, required injections, owned effects, provided services, and package-specific all-or-none or config-dependent relations. |
| Cordis service seams | Validate the structural method and descriptor surface of current and future implementations. |
| Pure libraries, bins, and support packages | Validate stable parser mapping, protocol precedence, retention and timeout algebra, path resolution, normalization, environment scrubbing, or deliberately empty runtime entrypoints. |
| `dsh-session` | Strict sequence growth, turn/step enclosure, and same-step tool call/result pairing. |
| `dsh-agent` | Non-repeating agent status and terminal disposal transitions. |
| `dsh-scope` | Scoped-event carrier presence and routed-subject consistency. |
| `dsh-agent-loop` | Frozen loop request reconstruction from the session event log. |
| `dsh-llm` | Stream block grammar, delta type/index matching, single usage, closed blocks, and terminal finish. |
| `dsh-tools` | Monotonic pre/execute/post stages and immutable final execution/result snapshots. |
| `dsh-system-prompt` | Authoritative assembly section, tool, and variable data constraints. |
| `dsh-compact` | Compaction start/summary/end pairing, range endpoints, token counts, and successful-summary presence. |
| `dsh-hook-protocol` | Hook invocation/result correlation, dialect, identity, and duration constraints. |
| `dsh-bash` | Durable sandbox-mode events use the closed sandbox-mode vocabulary. |
| `dsh-fs` | Filesystem decision/observation events carry usable target and version identities. |
| `dsh-subagent` | Provider add/remove and child start/end events preserve identity and pairing. |
| `dsh-permission` | Durable permission decisions name a preset in the active permission table. |
| `dsh-user-approval` | Approval asked/decided records pair by call and use valid outcomes and policies. |
| `dsh-workflow` | Workflow and child-agent start/end events preserve run metadata, identity, outcome, count, and error relations. |
| `dsh-tasks` | Current and terminal task snapshots preserve id/kind, owner, status, and timestamp relationships. |
| `dsh-tool-todo` | Durable whole-list snapshots use unique trimmed items, closed statuses, and at most one active item. |
| `dsh-time-context` | Plugin-attributed clock readings agree across turn, step, elapsed baseline, rendered time, and event time. |
At implementation time this covers all 91 workspace packages: four stateful companions, 62 plugin-fiber companions, eight service-shape companions, and 17 pure/bin/support companions.
Session-backed companions reconstruct their trace from existing durable events when they load. Other checks observe the authoritative live event boundary or mutable service result. Validation runs before publication where accepting an invalid event would otherwise commit bad state.
### Product-independent observers
### Repository gate and tests
`observePluginInvariant` checks existing fibers immediately and future active fibers through a callback/name index behind one root-shared Cordis lifecycle listener pair. A contract may supply an exact callback when that import is safe. Otherwise it matches `fiber.runtime.name`, the name declared by that fiber's own plugin runtime, rather than the inherited `fiber.name`; anonymous `ctx.inject()` children are therefore not misidentified as their parent package. The observer checks required injection keys, recursively collected effect labels, services provided by that exact fiber, and an optional owner validator. Config-dependent packages encode symmetric relations, such as automatic compaction owning both listeners or neither when disabled.
`verify-package-invariants` discovers every workspace package and enforces companion source, exact-name registration, `./invariant` exports, publication files, dependencies, TypeScript references, and bundle entries. Its AST rule rejects generated markers and unexplained empty installers. A non-empty installer must accept and use the failure reporter. The gate deliberately does not infer semantic quality from method names or helper calls.
`observeServiceInvariant` checks the current service and every later binding. `serviceShapeViolation` validates callable members and non-empty string descriptors structurally instead of using `instanceof`, so conforming third-party backends and complete test doubles remain valid while incomplete stand-ins fail.
`assertInvariant` handles package algebra. Pure-package companions return an asynchronous installer promise and dynamically import their owner during child startup. The service joins that promise for atomic rollback while allowing the test module, Loader, or deployment to establish mocks and module resolution before the invariant samples the owner.
### Gate and test execution
`verify-package-invariants` discovers every workspace package and retains the publication checks for the exact registration name, `./invariant` export, published files, invariant peer and development dependencies, TypeScript reference, and bundle entry. Its source check additionally parses the local `install` function, rejects a generated marker or empty body, requires a second failure-reporter parameter and its use, and rejects duplicate name-based plugin observers across packages. These AST checks are a minimum acceptance rule, not a claim that source shape proves semantic quality.
The Vitest setup host mounts `InvariantService` with `{ enabled: true }` before an ordinary Cordis root's first plugin and adds the current test package's companion. The host joins companion startup to the test's root-level composition boundary, so asynchronous pure checks and plugin-observer setup fail the test rather than becoming background diagnostics. One exhaustive topology mounts all 91 companions once to prove runtime registration and coverage; focused selection, lifecycle, and owner suites build their own enabled topology to avoid duplicate registrations while still testing invariants.
Helper tests reject invalid plugin names, missing injections, effects, services, custom relations, malformed service shapes, and failed assertions. Package suites then activate real plugins across their existing config and HMR paths. Test-only service stand-ins must implement the complete checked seam rather than bypass global invariants.
Vitest mounts `InvariantService` with `{ enabled: true }` for every package test topology and loads the owning companion. The invariant subpath path mapping resolves source companions instead of stale built output. Focused suites cover every executable companion's valid and invalid observations, and the exhaustive topology loads all companions to prove registration and disposal wiring. Tests that synthesize event streams must produce a valid surrounding lifecycle unless the test is intentionally asserting a violation.
## Alternatives considered
- **Keep generated ownership-only companions.** Rejected because registration without an executable assertion cannot reject a broken package and makes the exhaustive gate misleading.
- **Generate one synthetic assertion into every package.** Rejected because a universal assertion would again optimize for satisfying the gate instead of protecting an owner-specific contract.
- **Move the per-package contract matrix into `dsh-invariants`.** Rejected because product imports, vocabulary, and change ownership would return to the central service.
- **Import every owner entrypoint statically from its companion.** Rejected because owning and exhaustive test hosts would preload packages before hoisted mocks and shipped compositions would pay unrelated module initialization costs.
- **Require first-party service-class identity.** Rejected because service seams are structural extension boundaries; `instanceof` would reject valid external implementations and test doubles.
- **Register invariants implicitly from package root entrypoints.** Rejected for the composition-order and hidden-effect reasons in the package-owned service RFC.
- **Keep generated empty companions.** Rejected because an unexplained placeholder can survive after a package gains a meaningful runtime relation.
- **Require an assertion from every package.** Rejected because method-presence, plugin-shape, and fixed-example assertions duplicate stronger type, load, and unit-test contracts without checking runtime consistency.
- **Keep generic shape helpers in the service.** Rejected because they blur compile-time API validation with runtime invariants and encourage centrally defined product assumptions.
- **Move the product checks into the service.** Rejected because product vocabulary, dependencies, tests, and change ownership belong with the package that emits the data.
- **Register companions implicitly from root entrypoints.** Rejected because composition order and optional service presence would create hidden effects.
## Consequences
- Every package contributes an executable check; adding a package without one fails the top-level gate.
- The invariant service remains product-independent while providing reusable lifecycle and shape observers.
- Ordinary unit, snapshot, and e2e roots run with global invariant enablement and the test package's companion; one exhaustive topology registers every companion.
- Plugin names used for name-based observation must be unique within one Cordis root; packages may opt into exact callback identity when safe.
- Pure-package checks sample stable startup contracts. Mutable behavior must use an event, service, or plugin-fiber observer.
- Relevant companion work runs during package tests and selected deployments, trading bounded startup cost for immediate package-attributed failures.
- The original regex selection, blocklist precedence, registration uniqueness, rollback, disposal, and HMR contracts remain unchanged.
- Every package has visible ownership and publication wiring, but only packages with a plausible runtime relation add listeners or trace state.
- Empty companions remain reviewable decisions with package-specific explanations and fail the gate if the explanation is removed.
- Type declarations, Cordis loadability, plugin metadata, service method surfaces, and pure algebra remain covered by their owning compile, load, unit, or integration gates.
- Runtime failures identify the owning npm package and point to an inconsistent observation rather than restating a required API shape.
- The original selection, blocklist precedence, duplicate ownership, rollback, disposal, and HMR service contracts remain unchanged.
@@ -1,65 +1,75 @@
# Agent Note: 可执行的包不变契约
# Agent Note:有意义的包不变契约
Status: implemented
状态:已实施
[English](2026-07-19-package-invariant-runtime-contracts.md) | 中文
## 问题
拥有的不变接缝让注册与发布覆盖完整,但生成基线把包名所有权视为充分条件。空 installer 可以通过仓库门禁,却不观察任何运行时状态,也不拒绝任何无效状态。这样一来,完整计数只能证明接线存在,不能保护包契约
自有不变接缝让发布和注册实现了全覆盖,但最初的生成基线允许空安装器。后续方案又用针对插件名称、注入、effect、服务方法和固定纯函数示例的通用断言替代这些空实现。这些断言虽然让每个 companion 都能执行,却没有提高系统安全性:TypeScript、Cordis 启动、包测试和模块加载测试已经约束这些形状,而不变量服务应当发现不可能出现的运行时状态
不同包形态不能使用同一种不变式。Cordis 插件拥有 fiber、注入、effect 与服务;服务接缝允许结构兼容的第三方实现;有状态领域需要事件关系;纯库和 bin 包暴露代数、解析、规范化或入口约束。仓库需要一个可执行的统一义务,同时不能把这些契约重新移回了解产品语义的中央包
有用的运行时不变量会关联时间上的多个观测,或关联可变数据结构中的多个部分。例如:终止事件没有对应的开始事件、LLM delta 指向未打开的 block,或持久化结果的身份与请求不同。仅确认声明的方法存在、插件名称符合预期,或常量示例仍返回已知值,都不属于这种关系
Vitest 会为每个包测试全局挂载其所有者伴随插件,并由一个完整拓扑挂载全部伴随插件。因此伴随模块不能在测试模块建立 hoisted mock 之前急切导入所有产品入口;按名称观察时,也不能把继承父级显示名的匿名子 fiber 误认为包插件本身
有些包确实没有可持续观测的关系。纯工具、仅负责组合的包、薄适配器、可执行入口和测试支持包可能仍有重要契约,但类型检查、加载检查、聚焦单元测试或集成测试更适合执行这些契约。强迫这些包添加合成运行时断言,只会让实现围绕通过门禁优化,而不是检测损坏
## 决策
### 每个伴随插件都执行包契约
### 注册必须全覆盖;断言必须有意义
每个工作区包保留独立发布的 `./invariant` 伴随插件和准确 npm 包名注册,但 installer 必须通过绑定的 `fail(message)` 报告器执行至少一个包专属检查。删除所有权基线生成器及其根脚本入口;生成标记、空 installer 和从不引用报告器的 installer 都属于仓库错误。
每个 workspace 包都发布单独构建的 `./invariant` companion,并用完整 npm 包名注册。companion 只能采用以下两种形式之一:
实现后的契约采用四种形态:
- 安装包自有的事件流或相关可变数据结构检查,并通过绑定的 `fail(message)` 报告器报告违规;或
- 使用空安装器,并在其声明前写一条该包专属的 `No runtime invariant:` 注释,说明为什么该包没有合理的运行时关系可供观测。
| 所有者形态 | 运行时契约 |
空形式是明确的架构结论,不是生成占位符。如果后续包变更引入可变状态或事件协议,就必须用相应检查替换该说明。
中央 `dsh-invariants` 服务只负责配置、注册唯一性、子 fiber 生命周期、回滚、释放和归属到包的失败。它不暴露通用插件形状、服务形状或启动断言 helper,也不导入产品包。
### 已实施的检查
当前 91 个包的 workspace 包含 18 个可执行 companion 和 73 个有理由的空 companion。
| 所有者 | 运行时关系 |
|---|---|
| 有状态的 session、agent、scope 与 agent-loop 所有者 | 验证事件顺序、包围关系、状态转换、作用域主体和可重建的模型请求。 |
| Cordis 插件所有者 | 验证插件自身声明的运行时名称、必要注入、拥有的 effect、提供的服务,以及包专属的全有或全无关系或配置依赖关系。 |
| Cordis 服务接缝 | 验证当前和未来实现的结构化方法与描述字段表面。 |
| 纯库、bin 与支持包 | 验证稳定的解析映射、协议优先级、保留与超时代数、路径解析、规范化、环境清理或刻意为空的运行时入口。 |
| `dsh-session` | 序号严格递增、turn/step 包围关系,以及同一 step 内的工具调用/结果配对。 |
| `dsh-agent` | agent 状态不得重复,并且不能离开终态 disposed。 |
| `dsh-scope` | scoped event 必须携带 carrier,且路由 subject 保持一致。 |
| `dsh-agent-loop` | 从 session 事件日志重建冻结的 loop 请求。 |
| `dsh-llm` | stream block 文法、delta 类型/索引匹配、单次 usage、block 闭合和终止 finish。 |
| `dsh-tools` | pre/execute/post 阶段单调推进,以及最终 execution/result 快照不可变。 |
| `dsh-system-prompt` | 权威 assembly 中 section、tool 和 variable 的数据约束。 |
| `dsh-compact` | compaction start/summary/end 配对、范围端点、token 数量和成功时必须存在 summary。 |
| `dsh-hook-protocol` | hook invocation/result 的关联、dialect、身份和 duration 约束。 |
| `dsh-bash` | 持久化 sandbox-mode 事件必须使用封闭的 sandbox-mode 词表。 |
| `dsh-fs` | 文件系统决策/观测事件必须携带可用的 target 和 version 身份。 |
| `dsh-subagent` | provider add/remove 和 child start/end 事件必须保持身份与配对。 |
| `dsh-permission` | 持久化 permission 决策必须引用当前 permission 表中的 preset。 |
| `dsh-user-approval` | approval asked/decided 记录按 call 配对,并使用有效 outcome 和 policy。 |
| `dsh-workflow` | workflow 和 child-agent start/end 事件保持 run metadata、身份、outcome、数量和 error 关系。 |
| `dsh-tasks` | 当前与终态 task snapshot 保持 id/kind、owner、status 和 timestamp 关系。 |
| `dsh-tool-todo` | 持久化全量 snapshot 使用唯一且已 trim 的条目、封闭 status,并且最多有一个活动条目。 |
| `dsh-time-context` | 标注插件来源的时钟 reading 在 turn、step、elapsed baseline、渲染时间和事件时间之间保持一致。 |
实现时覆盖全部 91 个工作区包:四个有状态伴随插件、62 个插件 fiber 伴随插件、八个服务形状伴随插件和 17 个纯库、bin 或支持包伴随插件
基于 session 的 companion 在加载时从已有持久化事件重建 trace。其他检查观测权威 live event 边界或可变服务结果。如果接受无效事件会提交错误状态,验证就在发布前执行
### 与产品无关的观察器
### 仓库门禁与测试
`observePluginInvariant` 会立即检查已有 fiber,并通过根上下文共享的一对 Cordis 生命周期监听器背后的 callback/名称索引检查未来进入活跃状态的 fiber。安全导入时,契约可以提供准确 callback;否则匹配 `fiber.runtime.name`,即该 fiber 自身插件运行时声明的名称,而不是继承而来的 `fiber.name`,因此匿名 `ctx.inject()` 子级不会被误认成父包。观察器检查必要注入键、递归收集的 effect 标签、由该 fiber 准确提供的服务,以及可选的所有者验证器。依赖配置的包使用对称关系,例如自动压缩要么同时拥有两个监听器,要么在关闭时两个都没有
`verify-package-invariants` 发现每个 workspace 包,并强制 companion 源文件、完整名称注册、`./invariant` export、发布文件、依赖、TypeScript reference 和 bundle entry 完整。其 AST 规则拒绝生成标记和没有解释的空安装器。非空安装器必须接收并使用失败报告器。门禁不会通过方法名或 helper 调用推断语义质量
`observeServiceInvariant` 检查当前服务及之后的每次绑定。`serviceShapeViolation` 以结构方式验证可调用成员和非空字符串描述字段,而不使用 `instanceof`;因此符合契约的第三方后端和完整测试替身有效,不完整替身会失败
`assertInvariant` 处理包代数。纯包伴随插件返回异步 installer promise,并在子 fiber 启动期间动态导入所有者。服务会等待该 promise 以保证原子回滚,同时允许测试模块、Loader 或部署先建立 mock 和模块解析,再由不变式采样所有者。
### 门禁与测试执行
`verify-package-invariants` 发现每个工作区包,并保留准确注册名、`./invariant` export、发布文件、不变式 peer 与开发依赖、TypeScript 引用和 bundle 入口的发布检查。源码检查还会解析本地 `install` 函数,拒绝生成标记或空函数体,要求第二个失败报告器参数及其使用,并拒绝跨包重复的按名称插件观察器。这些 AST 检查只是最低接收规则,并不宣称源码形状足以证明语义质量。
Vitest setup host 会在普通 Cordis 根上下文启动第一个插件前,以 `{ enabled: true }` 挂载 `InvariantService`,并添加当前测试包的伴随插件。host 会把伴随插件启动加入测试的根级组合边界,因此异步纯检查和插件观察器安装会让测试失败,而不会变成后台诊断。一个完整拓扑会一次挂载全部 91 个伴随插件,以证明运行时注册与覆盖率;选择、生命周期和所有者聚焦套件自行构建启用的不变式拓扑,在避免重复注册的同时继续测试不变式。
辅助测试会拒绝错误插件名、缺失注入、effect、服务或自定义关系、错误服务形状和失败断言。随后,包套件在已有配置与 HMR 路径上激活真实插件。测试专用服务替身必须实现完整的已检查接缝,不能绕过全局不变式。
Vitest 为每个包测试拓扑使用 `{ enabled: true }` 挂载 `InvariantService`,并加载所有者 companion。不变量 subpath 的 path mapping 会解析源 companion,而不是陈旧的构建输出。聚焦 suite 覆盖每个可执行 companion 的有效和无效观测;穷举拓扑加载全部 companion,以证明注册和释放 wiring。合成事件流的测试必须构造有效的外围生命周期,除非测试本身就是在断言违规
## 考虑过的替代方案
- **保留生成的仅声明所有权伴随插件。** 不予采纳,因为没有可执行断言的注册无法拒绝损坏的包,也会让完整门禁产生误导
- **每个包生成一个合成断言。** 不予采纳,因为通用断言仍是在优化如何通过门禁,而不是保护所有者专属契约
- **把逐包契约矩阵移入 `dsh-invariants`。** 不予采纳,因为产品导入、词汇和变更所有权会重新回到中央服务
- **从伴随插件静态导入每个所有者入口。** 不予采纳,因为所有者测试 host 与完整测试 host 会在 hoisted mock 之前预加载包,发布组合也会支付无关模块初始化成本
- **要求第一方服务类身份。** 不予采纳,因为服务接缝是结构化扩展边界;`instanceof` 会拒绝有效的外部实现和测试替身
- **从包根入口隐式注册不变式。** 因包拥有服务 RFC 中的组合顺序与隐藏 effect 问题而不予采纳。
- **保留生成的空 companion。** 拒绝,因为包获得有意义的运行时关系后,没有解释的占位符仍可能继续存在
- **要求每个包都执行断言。** 拒绝,因为方法存在性、插件形状和固定示例断言会重复更强的类型、加载和单元测试契约,却没有检查运行时一致性
- **在服务中保留通用形状 helper。** 拒绝,因为这会混淆编译期 API 验证和运行时不变量,并鼓励在中央定义产品假设
- **把产品检查移入服务。** 拒绝,因为产品词汇、依赖、测试和变更所有权应归属于产生这些数据的包
- **从根入口隐式注册 companion。** 拒绝,因为组合顺序和可选服务存在性会产生隐藏 effect
## 后果
- 每个包都贡献可执行检查;新增包若没有检查,会在顶层门禁失败
- 不变式服务保持与产品无关,同时提供可复用的生命周期与形状观察器
- 普通单元、snapshot 与 e2e 根上下文均全局启用不变式并注册当前测试包的伴随插件;一个完整拓扑注册全部伴随插件
- 用于按名称观察的插件名在一个 Cordis 根上下文内必须唯一;安全时包可以选择准确 callback 身份
- 纯包检查对稳定启动契约采样;可变行为必须使用事件、服务或插件 fiber 观察器
- 包测试和被选部署会执行相关伴随工作,以有界启动成本换取即时且带包归属的失败。
- 原有正则选择、blocklist 优先级、注册唯一性、回滚、dispose 与 HMR 契约保持不变。
- 每个包都有可见的所有权与发布 wiring,但只有具备合理运行时关系的包才会增加 listener 或 trace 状态
- 空 companion 是带包专属说明、可评审的决策;删除说明后门禁会失败
- 类型声明、Cordis 可加载性、插件 metadata、服务方法形状和纯代数继续由所属的编译、加载、单元或集成门禁覆盖
- 运行时失败会标明所属 npm 包,并指出不一致的观测,而不是复述必要的 API 形状
- 原有 selection、blocklist 优先级、重复所有权、回滚、释放和 HMR 服务契约保持不变
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write
2026-07-19-package-owned-invariant-service.md: 552b088c1cafc2fa762487f57fa1d4ad64390f7e
2026-07-19-package-owned-invariant-service.zh.md: 84bdc6a6a3baefe95713f8ce5b8a4e2af49b64eb
2026-07-19-package-owned-invariant-service.md: bd167f8da1e855b703b75a60e2dbd8959f5bf9b3
2026-07-19-package-owned-invariant-service.zh.md: 6bd4f30123b7c7ba39266d5d31dd4b378604fd5a
@@ -18,7 +18,7 @@ Package ownership must also be exhaustive. Without a mechanical repository rule,
`@deepseek-ai/dsh-invariants` is a product-independent Cordis service plugin that registers `ctx.invariants`. It owns configuration, registration uniqueness, child-fiber lifecycle, and package-attributed failures. It imports no session, agent, scope, or agent-loop package and contains none of their checks.
Every workspace package publishes a `./invariant` companion plugin that registers its exact full npm name and installs an executable package-specific contract. Generated ownership-only installers are forbidden by the follow-up [runtime-contract Agent Note](2026-07-19-package-invariant-runtime-contracts.md). Package root entrypoints do not import or register diagnostics implicitly, so loading a root package does not change runtime checking or require the invariant service.
Every workspace package publishes a `./invariant` companion plugin that registers its exact full npm name. A companion checks a meaningful event or mutable-data relationship when its owner has one; otherwise it carries an owner-specific explanation for its empty installer. Generated ownership placeholders and synthetic API-shape assertions are forbidden by the follow-up [runtime-contract Agent Note](2026-07-19-package-invariant-runtime-contracts.md). Package root entrypoints do not import or register diagnostics implicitly, so loading a root package does not change runtime checking or require the invariant service.
### Configuration and selection
@@ -55,7 +55,7 @@ Registration setup is transactional. If an installer fails after registering lis
The former functional-plugin entrypoint and one-argument `InvariantError` constructor are not retained as compatibility surfaces. The repository is pre-release and all call sites move to the service and package-attributed error together.
### Stateful companions and exhaustive ownership
### Initial stateful companions and exhaustive ownership
| Companion entry | Registration name | Owned checks |
|---|---|---|
@@ -64,9 +64,9 @@ The former functional-plugin entrypoint and one-argument `InvariantError` constr
| `@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` | model-request reconstruction |
These four owners contain stateful checks and focused tests. Other owners check their plugin fibers and effects, structural service implementations, or stable pure-library algebra. Every companion is a separately bundled `./invariant` export with its own declarations and Loader-safe namespace plugin shape; the service package's own companion imports its local service type to avoid a self-dependency.
These four owners supplied the initial stateful checks. The follow-up runtime-contract decision adds checks for fourteen more owners with real event or mutable-data relationships and records justified empty companions for the rest. Every companion is a separately bundled `./invariant` export with its own declarations and Loader-safe namespace plugin shape; the service package's own companion imports its local service type to avoid a self-dependency.
`verify-package-invariants` discovers every workspace package and rejects missing companion source, generated markers, empty or reporter-free installers, foreign or unresolved registration names, missing `./invariant` exports or published files, missing invariant peer/development dependencies and project references, and bundle overrides that omit the companion entry.
`verify-package-invariants` discovers every workspace package and rejects missing companion source, generated markers, unexplained empty installers, non-empty installers that omit or ignore the reporter, foreign or unresolved registration names, missing `./invariant` exports or published files, missing invariant peer/development dependencies and project references, and bundle overrides that omit the companion entry.
### Scoped-event semantic map
@@ -80,7 +80,7 @@ Workspace constraints recognize the separate invariant bundle, and package expor
## Testing
Service tests cover defaults, global disablement, allow/block selection, blocklist precedence, anchoring, unanchored matching, case sensitivity, invalid configuration, zero-match patterns, late registration, duplicate ownership, disposal, rollback, and HMR re-registration. Owner tests keep each invariant's positive and negative behavior beside its source.
Service tests cover defaults, global disablement, allow/block selection, blocklist precedence, anchoring, unanchored matching, case sensitivity, invalid configuration, zero-match patterns, late registration, duplicate ownership, disposal, rollback, and HMR re-registration. Owners with executable checks keep positive and negative behavior beside the companion source.
Composition tests cover standard-spine forwarding and generated SDK entries. Loader tests preserve each companion namespace, while built plain-Node smokes exercise the compiled subpath exports. The scoped-event freshness gate reruns its semantic Program analysis.
@@ -96,10 +96,10 @@ Every Vitest configuration loads a test host that mounts an explicitly enabled s
## Consequences
- Product packages own and test their relational assertions while the service stays product-independent.
- Every package pays the publication, dependency, and runtime-check cost of an executable invariant companion.
- Every package pays the publication and dependency cost of a companion; only owners with a meaningful runtime relationship add listener or trace-state cost.
- Standard compositions can disable all checks or select package names without changing their plugin tree.
- Explicit companion entries make diagnostic cost and ownership visible in Cordis config and package exports.
- One selected contribution adds one child fiber and its listener/state cost; filtered registrations retain only name ownership.
- One selected executable contribution adds one child fiber and its listener/state cost; a selected empty contribution has no listener or trace-state cost, while filtered registrations retain only name ownership.
- Regex sources are deployment configuration and remain fixed until the service reloads.
- Ordinary Vitest roots install the owning test package's selected companion; one exhaustive topology pays the full child-fiber cost once for repository-wide registration coverage.
- Session storage validation, snapshotting, freezing, provenance, and surface acceptance remain always on and are not affected by invariant selection.
@@ -18,7 +18,7 @@ Status: implemented
`@deepseek-ai/dsh-invariants` 是与产品无关的 Cordis 服务插件,注册 `ctx.invariants`。它只负责配置、注册唯一性、子 fiber 生命周期和带包归属的失败;不导入 session、agent、scope 或 agent-loop 包,也不包含这些包的检查。
工作区内的每个包都发布 `./invariant` 伴随插件,注册自己完整且准确的 npm 包名,并安装可执行的包专属契约。后续的[运行时契约 Agent Note](2026-07-19-package-invariant-runtime-contracts.md) 禁止生成的仅声明所有权 installer。包的根入口不会隐式导入或注册诊断,因此加载根包不会改变运行时检查,也不要求不变式服务存在。
工作区内的每个包都发布 `./invariant` 伴随插件,注册自己完整且准确的 npm 包名。如果所有者具备有意义的事件或可变数据关系,companion 就检查该关系;否则空 installer 必须携带该所有者专属的说明。后续的[运行时契约 Agent Note](2026-07-19-package-invariant-runtime-contracts.md) 禁止生成的所有权占位符和合成 API 形状断言。包的根入口不会隐式导入或注册诊断,因此加载根包不会改变运行时检查,也不要求不变式服务存在。
### 配置与选择
@@ -55,7 +55,7 @@ blocklist 匹配优先于 allowlist 匹配。每个条目都是区分大小写
原有函数式插件入口与单参数 `InvariantError` 构造函数不作为兼容表面保留。仓库尚未发布,所有调用方会一起迁移到服务和带包归属的错误。
### 有状态伴随插件与完整所有权
### 首批有状态伴随插件与完整所有权
| 伴随入口 | 注册名 | 所属检查 |
|---|---|---|
@@ -64,9 +64,9 @@ blocklist 匹配优先于 allowlist 匹配。每个条目都是区分大小写
| `@deepseek-ai/dsh-scope/invariant` | `@deepseek-ai/dsh-scope` | scoped event carrier 存在性与主体一致性 |
| `@deepseek-ai/dsh-agent-loop/invariant` | `@deepseek-ai/dsh-agent-loop` | 模型请求重建 |
这四个所有者保存有状态检查与聚焦测试。其他所有者检查自己的插件 fiber 与 effect、结构化服务实现或稳定的纯库代数。每个伴随入口都是单独打包的 `./invariant` export,具有独立声明和对 Loader 安全的命名空间插件形态;服务包自身的伴随插件导入本地服务类型,避免形成自依赖。
这四个所有者提供了首批有状态检查。后续运行时契约决策为另外十四个确有事件或可变数据关系的所有者增加检查,并为其余包记录有理由的空 companion。每个伴随入口都是单独打包的 `./invariant` export,具有独立声明和对 Loader 安全的命名空间插件形态;服务包自身的伴随插件导入本地服务类型,避免形成自依赖。
`verify-package-invariants` 会发现每个工作区包,并拒绝缺失的伴随插件源码、生成标记、空 installer、不使用失败报告器的 installer、外部或无法解析的注册名、缺失的 `./invariant` export 或发布文件、缺失的不变式对等依赖(peer dependency)、开发依赖及项目引用,以及遗漏伴随入口的自定义构建配置。
`verify-package-invariants` 会发现每个工作区包,并拒绝缺失的伴随插件源码、生成标记、没有解释的空 installer、缺少或不使用失败报告器的非空 installer、外部或无法解析的注册名、缺失的 `./invariant` export 或发布文件、缺失的不变式对等依赖(peer dependency)、开发依赖及项目引用,以及遗漏伴随入口的自定义构建配置。
### Scoped event 语义映射
@@ -80,7 +80,7 @@ Workspace 约束识别独立的不变式 bundle;包 exports、项目引用、
## 测试
服务测试覆盖默认值、全局关闭、allow/block 选择、blocklist 优先级、锚定与非锚定匹配、大小写敏感、无效配置、零匹配模式、延迟注册、重复所有权、dispose、回滚和 HMR 重新注册。所有者测试把各不变式的正向与负向行为保留在其源码旁边。
服务测试覆盖默认值、全局关闭、allow/block 选择、blocklist 优先级、锚定与非锚定匹配、大小写敏感、无效配置、零匹配模式、延迟注册、重复所有权、dispose、回滚和 HMR 重新注册。具备可执行检查的所有者会把正向与负向行为保留在 companion 源码旁边。
组合测试覆盖标准 spine 转发和生成的 SDK 条目。Loader 测试固定每个伴随命名空间,构建后的纯 Node smoke 覆盖编译子路径 export。scoped event 新鲜度门禁会重新执行语义 Program 分析。
@@ -96,10 +96,10 @@ Workspace 约束识别独立的不变式 bundle;包 exports、项目引用、
## 后果
- 产品包拥有并测试自己的关系断言,服务保持与产品无关。
- 每个包都承担可执行不变式伴随插件带来的发布依赖与运行时检查成本。
- 每个包都承担 companion 的发布依赖成本;只有具备有意义运行时关系的所有者才增加 listener 或 trace 状态成本。
- 标准组合无需改变插件树即可关闭全部检查或按包名选择。
- 显式伴随条目让诊断成本和所有权在 Cordis 配置与包 export 中可见。
- 每个选中贡献增加一个子 fiber 及其监听器和状态成本;被过滤注册只保留包名占用。
- 每个选中的可执行贡献增加一个子 fiber 及其 listener/状态成本;选中的空贡献不增加 listener 或 trace 状态成本,被过滤注册只保留包名占用。
- 正则表达式源属于部署配置,在服务重载前保持固定。
- 普通 Vitest 根上下文会安装当前测试包中被选中的伴随插件;一个完整拓扑只支付一次全部子 fiber 成本,用于覆盖整个仓库的注册。
- 会话存储验证、快照、冻结、provenance 与 surface 接受规则始终启用,不受不变式选择影响。
+1 -1
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:
+13 -16
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 */
+13 -18
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 */
+14 -8
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.
*/
@@ -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"/)
})
})
+13 -22
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 */
@@ -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 */
@@ -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 */
@@ -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)
})
})
+13 -34
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 */
@@ -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', () => {
+91 -9
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.
*/
@@ -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,
}
}
@@ -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)
})
})
+48 -14
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.
*/
@@ -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()
})
})
@@ -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 */
+13 -16
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 */
+34 -15
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.
*/
@@ -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)
})
})
+51 -18
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.
*/
@@ -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/)
})
})
+13 -12
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 */
@@ -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 */
+13 -12
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 */
@@ -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.
+13 -12
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 */
+13 -15
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 */
+13 -14
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 */
+21 -8
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.
*/
+44
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/)
})
})
+13 -17
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 */
+13 -17
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 */
@@ -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 */
+81 -22
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 */
@@ -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/)
})
})
+13 -28
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 */
@@ -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/)
})
})
+13 -26
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 */
@@ -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/)
})
})
+13 -15
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 */
+13 -15
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 */
+77 -14
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.
*/
+86
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')
})
})
+3 -1
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 })
})
+13 -16
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 */
+13 -16
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 */
+13 -15
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 */
+13 -9
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 */
@@ -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"/)
})
})
+11 -22
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.
+11 -16
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.
+11 -18
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.
+11 -15
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.
@@ -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 */
@@ -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 */
@@ -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 */
@@ -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 */
+13 -15
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 */
+13 -15
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 */
+13 -17
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 */
+13 -15
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 */
+13 -19
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 */
+13 -9
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 */
+13 -15
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 */
@@ -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 */
@@ -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.
@@ -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 */
@@ -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.
+74 -15
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.
*/
@@ -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/)
})
})
@@ -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 */
+11 -21
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.
@@ -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.
+23 -23
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.
+2 -296
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>
+13 -16
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 */
@@ -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)
})
})
+13 -18
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 */
+11 -19
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.
+40 -16
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.
*/
@@ -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/)
})
})
+13 -17
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 */
@@ -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 */
+33 -14
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.
*/
@@ -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()
})
})
+13 -22
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 */
+11 -15
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.
+13 -15
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 */
+15 -20
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.
*/
@@ -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"/)
})
})
+13 -17
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 */
+13 -16
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 */
+13 -18
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 */

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