Cordis 框架
Cordis 是 Shi, Zhang & Cui (2026) 提出的时空可组合性 (spatiotemporal composability) 元框架的 TypeScript 实现。它由两部分组成:(1) 核心库 提供 effect tracking + coeffect resolution 的运行原语;(2) 声明式 component loader,支持配置 reconciliation 与 hot module replacement。已在 Koishi 聊天机器人框架(4000+ 社区插件,4 年生产)验证。
模块结构
| 部件 |
文件 / 包 |
功能 |
| Core library |
@cordis/core |
ctx.effect(fn, dispose) 注册 effect+inverse;ctx.set/ctx.get 读写 coeffect;ctx[key] 通过 Proxy 走声明式访问;fiber 生命周期 |
| Component loader |
@cordis/core/loader |
声明式 entry 树(id / url / isolate / intercept / config / disabled);增量 reconciliation |
| HMR 引擎 |
@cordisjs/hmr |
classify → detect → transactional reload 三阶段;自动回滚到 backup |
| Group / Include |
@cordisjs/group、@cordisjs/include |
子树加载 / 外部 YAML/JSON 配置导入 |
核心 API 速查(TypeScript)
import { Context } from '@cordis/core'
interface Config { apiKey: string }
class MyService extends Context {
constructor(ctx: Context) {
super(ctx, 'my-service')
// 注册 effect + inverse
ctx.effect(async () => {
const conn = await openConnection(this.config.apiKey)
ctx.set('db', conn) // 写入 coeffect
return () => { // 返回 inverse
conn.close()
}
})
}
}
// 声明依赖
class MyConsumer extends Context {
inject = ['db'] // 声明 coeffect specification
constructor(ctx: Context) {
super(ctx, 'my-consumer')
this.logger.info(ctx.db) // 通过 Proxy 访问;走 Algorithm 6
}
}
Lifecycle States
| 状态 |
进入条件 |
退出条件 |
Inactive |
刚注册或 deactivation 完成 |
L-Reload(依赖就绪) |
Reloading |
L-Begin,开始 effect 迭代 |
L-Finish(iter 耗尽) |
Active |
L-Finish 完成 |
L-Leave(target 改变 / retire) |
Unloading |
L-Leave 已标记 |
L-Unload(relied 守卫释放后) |
Inactive(error) |
L-Raise(effect 抛错) |
不会自动复活 |
关键算法
- Algorithm 1 effect execution——迭代式 effect iterator,每步 yield 修改后 state、inverse、continuation。
- Algorithm 3 / 4 notify / register——
relied 守卫 + 注册/退役。
- Algorithm 6 proxy-mediated access——沿 fiber 链向上 walk,命中 committed view 即返回;inject 已被声明但未 commit 时抛
INACTIVE_ACCESS。
- Algorithm 7 isolation realm reassignment——delta 化重写 realm 表。
- Algorithm 8-10 HMR 三阶段:classify (stashed/externals 闭包) → detect (stale entries) → transactional reload(失败回滚 backup)。
设计取舍(与同类)
- vs OSGi / Spring:OSGi 的 service registry 概念等价于 coeffect key,但缺少 reactive notification;切换实现需要每个 consumer 主动 re-bind。
- vs Webpack / Vite HMR:传统 HMR 需要开发者标注 module.accept 边界;Cordis 的 effect 累加器使任何 fiber 都可被替换,无需 annotation。
- vs React fiber + hooks:hooks 是 imperative useEffect,effect target 和注册机制不显式出现;Cordis 的 effect 显式携带 inverse 并自动追踪。
- vs Java service locator:运行时拉取、无类型检查、依赖关系散落代码各处;Cordis 的 inject 声明是显式 capability request,proxy 做 capability 调解。
生产案例:Koishi
- Koishi 是基于 Cordis v3 的开源聊天机器人框架;论文呈现的 v4 重设计 loader、细化 effect/coeffect 语义。
- 4000+ 社区插件:IM 适配器、数据库 driver、admin console、终端用户功能,全跑在 Section 5.1 的原语上。
- HMR 实战:开发时改 plugin 代码保存即生效,缓存与现有连接不丢。
- 同套原语在浏览器:Koishi Web Console 是另一个 Cordis 实例,插件组合浏览器端 UI 原语而非服务器原语——证明模型域无关。
与 quant-wiki 主题的接口
引用本页