From bff2d40dee9b29756685193ccc1b80ccfbdfd0b3 Mon Sep 17 00:00:00 2001 From: _Kerman Date: Thu, 8 Oct 2026 15:13:50 +0800 Subject: [PATCH] fix(agent-loop): keep shutdown ownership local to the loop --- docs/cordis-api/fiber.i18n.yaml | 68 +++++++++---------- docs/cordis-api/fiber.md | 34 +++++----- docs/cordis-api/fiber.zh.md | 34 +++++----- packages/core/agent-loop/README.i18n.yaml | 8 +-- packages/core/agent-loop/README.md | 3 +- packages/core/agent-loop/README.zh.md | 3 +- packages/core/agent-loop/src/index.ts | 27 ++++++-- packages/core/scope/tests/scope.spec.ts | 34 +--------- .../tests/cordis-lifecycle.spec.ts | 19 ------ .../session-projection/README.i18n.yaml | 4 +- packages/session/session-projection/README.md | 2 +- .../session/session-projection/README.zh.md | 2 +- .../session/session-projection/src/index.ts | 3 +- vendor/README.md | 2 +- vendor/cordis/src/fiber.ts | 6 +- 15 files changed, 104 insertions(+), 145 deletions(-) diff --git a/docs/cordis-api/fiber.i18n.yaml b/docs/cordis-api/fiber.i18n.yaml index 4936b0e926..acc84e2f3a 100644 --- a/docs/cordis-api/fiber.i18n.yaml +++ b/docs/cordis-api/fiber.i18n.yaml @@ -9,56 +9,56 @@ en: b5b3510f4b6dd13a zh: a0c70471b6d779b5 /fiber/ctx-effect-execute-label: - en: 49e7a90726351489 - zh: 4db6bc88e42f016e + en: ef3418fd5ffbe86d + zh: c98935435da8bc7e /fiber/ctx-fiber: en: a10e38bf26b4ecfe zh: 7c91817984c95c99 /fiber/the-fiber-class: - en: 0236f94c618945af - zh: 49653ee34995ff85 + en: 0e0fcb134ed44957 + zh: 326f4232aa0e65d1 /fiber/the-fiber-class/fiber-uid: - en: 79c8967b6a2cdd2d - zh: 0f8742c72403678f + en: 2f0eb3658bb8497e + zh: 65d3c17ca8bd4f95 /fiber/the-fiber-class/fiber-ctx: - en: 336ae46a13dcd6d7 - zh: 8de906a115e8d89b + en: 1b527d85759324f9 + zh: 54aa40db2705b95c /fiber/the-fiber-class/fiber-config: - en: b6602e675fbc5a6c - zh: b57d551306265ead + en: ee804c03c39e7806 + zh: 4353ba7817ec61ec /fiber/the-fiber-class/fiber-state: - en: 3cf3270ab93ac5a9 - zh: cbe060dc345d0727 + en: 999ad29dfc29661b + zh: 20245d11c338e3f1 /fiber/the-fiber-class/fiber-dispose: - en: aae5e01bce1c0d26 - zh: 8efb2b510eb97ad6 + en: 29e304d183eb9104 + zh: 9ac5023f518e06c4 /fiber/the-fiber-class/fiber-store: - en: dd95f75be5d5801c - zh: c684954d453f69c0 + en: c4185e5d051136a2 + zh: 5714d9e4f5461ca3 /fiber/the-fiber-class/fiber-inertia: - en: e14d839e4ebe6093 - zh: df5ba69c211360b3 + en: 2a3b1d3bc37bf986 + zh: 83bd257ee685d38b /fiber/the-fiber-class/fiber-name: - en: e4f962090c7ec2d8 - zh: 09d98a9d8cc42d24 + en: e5c2ecca13167a32 + zh: 284a461f0f1cd35b /fiber/the-fiber-class/fiber-assertactive: - en: 41f16c6770cb4a42 - zh: 78e5a409fcb8b51d + en: cceb503899634d09 + zh: a8381af1a23436f3 /fiber/the-fiber-class/fiber-effect-execute-label: - en: b5dcba51da82bb48 - zh: 102779d0a7033a83 + en: 55dcfacf295bbcf2 + zh: 6e3ec27bb8da5a3d /fiber/the-fiber-class/fiber-geteffects: - en: 2681d305e49df146 - zh: c376155efa901cee + en: 4d739a9c186fd9c2 + zh: f80fd3b87e79b004 /fiber/the-fiber-class/fiber-await: - en: 8b60c045fea02941 - zh: b9f3e1fcaffa2208 + en: 1d6258cbea61cd18 + zh: 2f10dda8918dadc5 /fiber/the-fiber-class/fiber-restart: - en: 5bd67e068f3a4a66 - zh: 93c5abb9bc677abd + en: 62d68dedb20b4fa9 + zh: 5a735ae0ff1266f4 /fiber/the-fiber-class/fiber-update-config-nosave: - en: 2d77e40537926a7b - zh: 334b4e91d1ef9f39 + en: b57ce0f6260c2cb8 + zh: 3bfb6c5bc252a2c2 /fiber/effect: en: 007d5b214e8a8610 zh: d74c26fbb1b8aeb6 @@ -69,8 +69,8 @@ en: 849aa91b8e67809f zh: 4b31d7e2acd2a008 /fiber/cordiserror: - en: 36c9d46499342212 - zh: 82e4012ae4efab4b + en: d276771958d3c05f + zh: 0141656ade938d55 /fiber/validationerror: en: 178782124cc15210 zh: 2b226f43f48af555 diff --git a/docs/cordis-api/fiber.md b/docs/cordis-api/fiber.md index cc31600bb9..3044301eff 100644 --- a/docs/cordis-api/fiber.md +++ b/docs/cordis-api/fiber.md @@ -34,7 +34,7 @@ Register a cleanup-aware effect on this fiber. **Returns** a disposer that tears the effect down and settles once done. -[Source](../../vendor/cordis/src/fiber.ts#L417) +[Source](../../vendor/cordis/src/fiber.ts#L415) ### ctx.fiber @@ -53,7 +53,7 @@ Runtime instance of one plugin application. A fiber tracks dependency state, validated config, lifecycle effects, and cleanup for the plugin context returned by `ctx.plugin()`. -[Source](../../vendor/cordis/src/fiber.ts#L186) +[Source](../../vendor/cordis/src/fiber.ts#L184) ### fiber.uid @@ -64,7 +64,7 @@ public uid: number | null Unique id within the registry; 0 for the root fiber, `null` once disposed. -[Source](../../vendor/cordis/src/fiber.ts#L188) +[Source](../../vendor/cordis/src/fiber.ts#L186) ### fiber.ctx @@ -75,7 +75,7 @@ public readonly ctx: Context The context this fiber's plugin runs in (extends the parent context). -[Source](../../vendor/cordis/src/fiber.ts#L190) +[Source](../../vendor/cordis/src/fiber.ts#L188) ### fiber.config @@ -86,7 +86,7 @@ public config: any The validated plugin config (updated by `update()`). -[Source](../../vendor/cordis/src/fiber.ts#L192) +[Source](../../vendor/cordis/src/fiber.ts#L190) ### fiber.state @@ -97,7 +97,7 @@ public state Current lifecycle state; transitions emit `internal/status`. -[Source](../../vendor/cordis/src/fiber.ts#L196) +[Source](../../vendor/cordis/src/fiber.ts#L194) ### fiber.dispose @@ -108,7 +108,7 @@ public readonly dispose: () => Promise Dispose this fiber: unload the plugin, then settle once cleanup finished. -[Source](../../vendor/cordis/src/fiber.ts#L198) +[Source](../../vendor/cordis/src/fiber.ts#L196) ### fiber.store @@ -119,7 +119,7 @@ public store: Dict | undefined Snapshot of required service implementations while loaded; `undefined` otherwise. -[Source](../../vendor/cordis/src/fiber.ts#L200) +[Source](../../vendor/cordis/src/fiber.ts#L198) ### fiber.inertia @@ -130,7 +130,7 @@ public inertia: Promise | undefined The in-flight load/unload transition, if one is currently running. -[Source](../../vendor/cordis/src/fiber.ts#L202) +[Source](../../vendor/cordis/src/fiber.ts#L200) ### fiber.name @@ -141,7 +141,7 @@ get name() The plugin's display name, inherited from the nearest named ancestor, else `'root'`. -[Source](../../vendor/cordis/src/fiber.ts#L338) +[Source](../../vendor/cordis/src/fiber.ts#L336) ### fiber.assertActive() @@ -159,7 +159,7 @@ Throw if the fiber has already been disposed. **Returns** nothing when the fiber is still active. -[Source](../../vendor/cordis/src/fiber.ts#L353) +[Source](../../vendor/cordis/src/fiber.ts#L351) ### fiber.effect(execute, label?) @@ -190,7 +190,7 @@ Register a cleanup-aware effect on this fiber. **Returns** a disposer that tears the effect down and settles once done. -[Source](../../vendor/cordis/src/fiber.ts#L417) +[Source](../../vendor/cordis/src/fiber.ts#L415) ### fiber.getEffects() @@ -207,7 +207,7 @@ Return metadata for currently registered effects. **Returns** one `EffectMeta` tree per labeled live effect. -[Source](../../vendor/cordis/src/fiber.ts#L572) +[Source](../../vendor/cordis/src/fiber.ts#L568) ### fiber.await() @@ -225,7 +225,7 @@ Wait for current lifecycle work and rethrow startup errors. **Returns** this fiber, once it has settled into a stable state. -[Source](../../vendor/cordis/src/fiber.ts#L708) +[Source](../../vendor/cordis/src/fiber.ts#L704) ### fiber.restart() @@ -243,7 +243,7 @@ Dispose and immediately reload this plugin with its current config. **Returns** a promise resolving once the reload settled. -[Source](../../vendor/cordis/src/fiber.ts#L722) +[Source](../../vendor/cordis/src/fiber.ts#L718) ### fiber.update(config, noSave?) @@ -271,7 +271,7 @@ Runs the `internal/update` waterfall first, so update hooks (and HMR) can veto o **Returns** nothing; the restart runs behind the `internal/update` waterfall. -[Source](../../vendor/cordis/src/fiber.ts#L740) +[Source](../../vendor/cordis/src/fiber.ts#L736) ## Effect @@ -352,7 +352,7 @@ namespace CordisError { } ``` -[Source](../../vendor/cordis/src/fiber.ts#L159) +[Source](../../vendor/cordis/src/fiber.ts#L157) ## ValidationError diff --git a/docs/cordis-api/fiber.zh.md b/docs/cordis-api/fiber.zh.md index 1d5dc3cee5..bee2f523f1 100644 --- a/docs/cordis-api/fiber.zh.md +++ b/docs/cordis-api/fiber.zh.md @@ -36,7 +36,7 @@ effect(execute: () => Effect, label?: string): AsyncDisposable> **返回**一个用于撤销该作用的清理函数,并在清理完成后结算。 -[源码](../../vendor/cordis/src/fiber.ts#L417) +[源码](../../vendor/cordis/src/fiber.ts#L415) ### ctx.fiber @@ -55,7 +55,7 @@ fiber: Fiber fiber 会跟踪 `ctx.plugin()` 返回的插件上下文所对应的依赖状态、经过校验的配置、生命周期作用和清理操作。 -[源码](../../vendor/cordis/src/fiber.ts#L186) +[源码](../../vendor/cordis/src/fiber.ts#L184) ### fiber.uid @@ -66,7 +66,7 @@ public uid: number | null 在注册表中的唯一 id;根 fiber 的 id 为 0,dispose 后为 `null`。 -[源码](../../vendor/cordis/src/fiber.ts#L188) +[源码](../../vendor/cordis/src/fiber.ts#L186) ### fiber.ctx @@ -77,7 +77,7 @@ public readonly ctx: Context 此 fiber 的插件运行所在的上下文(扩展自父上下文)。 -[源码](../../vendor/cordis/src/fiber.ts#L190) +[源码](../../vendor/cordis/src/fiber.ts#L188) ### fiber.config @@ -88,7 +88,7 @@ public config: any 经过校验的插件配置(由 `update()` 更新)。 -[源码](../../vendor/cordis/src/fiber.ts#L192) +[源码](../../vendor/cordis/src/fiber.ts#L190) ### fiber.state @@ -99,7 +99,7 @@ public state 当前生命周期状态;状态转换会发出 `internal/status`。 -[源码](../../vendor/cordis/src/fiber.ts#L196) +[源码](../../vendor/cordis/src/fiber.ts#L194) ### fiber.dispose @@ -110,7 +110,7 @@ public readonly dispose: () => Promise dispose 此 fiber:卸载插件,并在清理完成后结算。 -[源码](../../vendor/cordis/src/fiber.ts#L198) +[源码](../../vendor/cordis/src/fiber.ts#L196) ### fiber.store @@ -121,7 +121,7 @@ public store: Dict | undefined 加载期间所需服务实现的快照;其他情况下为 `undefined`。 -[源码](../../vendor/cordis/src/fiber.ts#L200) +[源码](../../vendor/cordis/src/fiber.ts#L198) ### fiber.inertia @@ -132,7 +132,7 @@ public inertia: Promise | undefined 当前正在进行的加载或卸载转换;如果没有此类转换,则为 undefined。 -[源码](../../vendor/cordis/src/fiber.ts#L202) +[源码](../../vendor/cordis/src/fiber.ts#L200) ### fiber.name @@ -143,7 +143,7 @@ get name() 插件的显示名称,继承自最近的具名祖先;如果不存在,则为 `'root'`。 -[源码](../../vendor/cordis/src/fiber.ts#L338) +[源码](../../vendor/cordis/src/fiber.ts#L336) ### fiber.assertActive() @@ -161,7 +161,7 @@ assertActive() **返回**:fiber 仍处于活动状态时不返回任何内容。 -[源码](../../vendor/cordis/src/fiber.ts#L353) +[源码](../../vendor/cordis/src/fiber.ts#L351) ### fiber.effect(execute, label?) @@ -192,7 +192,7 @@ effect(execute: () => Effect, label?: string): AsyncDisposable> **返回**一个用于撤销该作用的清理函数,并在清理完成后结算。 -[源码](../../vendor/cordis/src/fiber.ts#L417) +[源码](../../vendor/cordis/src/fiber.ts#L415) ### fiber.getEffects() @@ -209,7 +209,7 @@ getEffects() **返回**:每个带标签的活动作用对应一棵 `EffectMeta` 树。 -[源码](../../vendor/cordis/src/fiber.ts#L572) +[源码](../../vendor/cordis/src/fiber.ts#L568) ### fiber.await() @@ -227,7 +227,7 @@ async await() **返回**:进入稳定状态后的此 fiber。 -[源码](../../vendor/cordis/src/fiber.ts#L708) +[源码](../../vendor/cordis/src/fiber.ts#L704) ### fiber.restart() @@ -245,7 +245,7 @@ dispose 此插件,并立即使用其当前配置重新加载。 **返回**一个在重新加载完成后兑现的 promise。 -[源码](../../vendor/cordis/src/fiber.ts#L722) +[源码](../../vendor/cordis/src/fiber.ts#L718) ### fiber.update(config, noSave?) @@ -273,7 +273,7 @@ update(config: any, noSave = false) **返回**无返回值;重启由 `internal/update` waterfall 执行。 -[源码](../../vendor/cordis/src/fiber.ts#L740) +[源码](../../vendor/cordis/src/fiber.ts#L736) ## Effect @@ -354,7 +354,7 @@ namespace CordisError { } ``` -[源码](../../vendor/cordis/src/fiber.ts#L159) +[源码](../../vendor/cordis/src/fiber.ts#L157) ## ValidationError diff --git a/packages/core/agent-loop/README.i18n.yaml b/packages/core/agent-loop/README.i18n.yaml index 3f5297a571..93de892642 100644 --- a/packages/core/agent-loop/README.i18n.yaml +++ b/packages/core/agent-loop/README.i18n.yaml @@ -39,8 +39,8 @@ en: 2a8b93869eb5a2f9 zh: ddab8e738d188a61 /deepseek-ai-dsh-agent-loop/understand-the-implementation/creation-and-teardown: - en: 26b047d8ab4a93f8 - zh: 6624a3e794ebeb2d + en: 1c8564a06f9409ba + zh: 6ff14b442a191341 /deepseek-ai-dsh-agent-loop/understand-the-implementation/persistence-integration: en: da056b9f0dde4ab3 zh: ba9ce3b19c17ca22 @@ -105,8 +105,8 @@ en: 83531f2a13cc1f0e zh: 81a780d637dd8c5d /deepseek-ai-dsh-agent-loop/known-limitations-and-deferred-work: - en: 7f93fa258b0e39ba - zh: 819075791542b01c + en: 93cbef12ed438ae7 + zh: 1b9213fc61eab201 /deepseek-ai-dsh-agent-loop/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: 3bb0c20c93f16f98 diff --git a/packages/core/agent-loop/README.md b/packages/core/agent-loop/README.md index c954dace6b..bdafe92de5 100644 --- a/packages/core/agent-loop/README.md +++ b/packages/core/agent-loop/README.md @@ -109,7 +109,7 @@ The loop deep-freezes each derived message identity on its first request and reu Creation is one rollback-covered transaction: construct a private session, concrete agent, and scoped context; await optional setup; enter both registries; announce `session/created`; await serial `agent/created` listeners; then release queued input. A caller creating a runtime child sets `options.parentAgent`; the caller Context separately owns the transaction and live handle. Setup, commit, or listener failure and owner disposal roll back the prepared resources. Announcements already delivered remain observable and receive matching disposal notifications. Teardown stops and drains the driver, unwinds the scope, closes the session's write path, detaches the agent, then detaches the session. Every detach binds the exact entered object, so a stale disposer cannot remove a later same-id replacement. -Factory unload retains the inbox and turn-boundary projections until every Agent teardown and startup task settles, including when another teardown fails. Their registration disposers belong to the same ordered effect as factory teardown. Each Agent scope inherits the factory's dependencies, but its disposer belongs to the caller's lifecycle effect; caller unload, factory unload, and handle disposal await the same teardown. Independent Cordis effects unload concurrently, so registration order alone cannot provide these guarantees. +Factory unload retains the inbox and turn-boundary projections until every Agent teardown and startup task settles, even when cleanup fails. Caller unload, factory unload, and handle disposal await the same teardown. ### Persistence integration @@ -213,6 +213,7 @@ Recovery results append after the existing history and preserve its reusable pre These limits define when the loop needs special care. They are current package constraints, not a task backlog. - **Classification is unary** — calls whose safety depends on comparing siblings or resources must remain exclusive ([rationale](../../../.agents/notes/implemented/feature/2026-07-10-parallel-tool-call-execution.md)). +- **Root shutdown persistence** — shutting down the root context with an active background child can leave its final `turn/end` in memory but absent from the persisted log. Agent teardown completing does not guarantee that this event was saved. - **Previously closed inconsistent history** — failed-step recovery does not rewrite unanswered calls in already-closed historical turns. - **Config labels are fresh by default** — omitting `sessionId` creates a fresh `${id}-session-` on every startup; exact resume-or-create behavior requires an explicit stable `sessionId`, while `resumeSessionId` requires existing persisted history. - **Config agents have no per-agent persona field or setup hook** — they use the deployment persona; scoped persona and tool composition are available only through the programmatic `ctx.agents.create()` / `resume()` factory options. diff --git a/packages/core/agent-loop/README.zh.md b/packages/core/agent-loop/README.zh.md index 446a142b8f..324735aa09 100644 --- a/packages/core/agent-loop/README.zh.md +++ b/packages/core/agent-loop/README.zh.md @@ -109,7 +109,7 @@ const handle = await ctx.agents.create({ 创建是同一个受回滚保护的事务:构造私有会话、具象 agent 与带作用域上下文;等待可选 setup;进入两个注册表;宣告 `session/created`;等待串行 `agent/created` 监听器;随后释放已排队输入。创建运行时子 Agent 的调用方设置 `options.parentAgent`;调用方 Context 则单独拥有事务和存活句柄。Setup、commit、监听器失败或所有者 dispose 都会回滚已准备的资源。已送达的宣告仍可被观察,并有配对的销毁通知。Teardown 停止并排空驱动器、撤销作用域、关闭会话写路径、detach agent,再 detach 会话。每次 detach 都绑定到确切进入的对象,因此陈旧 disposer 无法移除之后出现的同 id 替代项。 -工厂卸载时保留 inbox 投影与轮次边界投影,直到所有 Agent teardown 和启动任务结算,即使其他 teardown 已失败也如此。投影的注册 disposer 与工厂 teardown 属于同一个有序 effect。每个 Agent 作用域继承工厂的依赖,但其 disposer 属于调用方的生命周期 effect;调用方卸载、工厂卸载和句柄释放等待同一次 teardown。独立的 Cordis effect 并发卸载,因此仅靠注册顺序无法提供这些保证。 +工厂卸载时保留 inbox 投影与轮次边界投影,直到所有 Agent teardown 和启动任务结束,即使清理失败也如此。调用方卸载、工厂卸载和句柄释放等待同一次 teardown。 ### 持久化集成 @@ -213,6 +213,7 @@ const handle = await ctx.agents.create({ 这些限制说明循环何时需要特别留意。它们是当前包约束,不是任务积压。 - **分类是一元的**:安全性取决于比较同级调用或资源的调用必须保持独占([原理](../../../.agents/notes/implemented/feature/2026-07-10-parallel-tool-call-execution.zh.md))。 +- **根上下文关停的持久化**:存在活跃后台子 Agent 时,关停根上下文可能使最终的 `turn/end` 仅留在内存中,未写入持久化日志。Agent teardown 完成不保证该事件已保存。 - **此前已关闭的不一致历史**:失败步骤恢复不会改写已关闭历史轮次中尚无结果的调用。 - **配置标签默认对应新会话**:省略 `sessionId` 时,每次启动都会创建新的 `${id}-session-`;如需确切的恢复或创建行为,必须显式提供稳定的 `sessionId`,而 `resumeSessionId` 要求已有持久化历史。 - **配置 agent 没有逐 agent persona 字段或 setup 钩子**:它们使用部署 persona;只有编程式 `ctx.agents.create()` / `resume()` 工厂选项支持带作用域的 persona 与工具组合。 diff --git a/packages/core/agent-loop/src/index.ts b/packages/core/agent-loop/src/index.ts index fe55e31e7a..bbb5feffdd 100644 --- a/packages/core/agent-loop/src/index.ts +++ b/packages/core/agent-loop/src/index.ts @@ -374,7 +374,6 @@ export class AgentLoop extends Service implements AgentFactory { // rejected constructor leaves no projection unit behind. const ownership = this.ownership = new FactoryOwnership(ctx.fiber) this.runtime = { ctx } - // Independent effects unload concurrently; projections must outlive Agents. ctx.effect(function* () { const unregisterTurnBoundary = ctx.sessionProjections.register(turnBoundaryProjectionDefinition) yield unregisterTurnBoundary @@ -543,7 +542,9 @@ export class AgentLoop extends Service implements AgentFactory { // stop the machine, unwind the scope, drain and close the session's write // path, leave the registries, release bookkeeping. const teardown = (): Promise => (disposing ??= (async () => { - abort.abort(new Error(`agent "${id}" lifecycle disposed`)) + abort.abort(new Error(this.ownership.isActive() + ? `agent "${id}" lifecycle disposed` + : 'agent loop is not active')) callerSignal?.removeEventListener('abort', onCallerAbort) this.ownership.signal.removeEventListener('abort', onFactoryTeardown) // Teardown failures are collected, never swallowed: registry, scope, @@ -588,23 +589,35 @@ export class AgentLoop extends Service implements AgentFactory { } throwCollectedFailures(failures, `agent "${id}" disposal failed`) })()) + let unfollowScope: (() => Promise | void) | undefined let unfollowOwner: () => Promise | void const dispose = async (): Promise => { try { await teardown() } finally { - await unfollowOwner() + await Promise.all([unfollowOwner(), unfollowScope?.()]) } } const untrack = this.ownership.track(dispose) try { unfollowOwner = ownerCtx.effect(function* () { - machine = new ReactLoopAgent(loopCtx, id, options, session) + const created = machine = new ReactLoopAgent(loopCtx, id, options, session) machineReady.resolve() - yield machine.scope.rawDispose - yield () => { + // Adopt the scope on its original fiber so it cannot unload before teardown. + // A loop already unloading during minting owns the provisional scope itself. + if (!INACTIVE_STATES.has(loopCtx.fiber.state)) { + unfollowScope = loopCtx.effect(function* () { + yield created.scope.rawDispose + yield () => teardown() + }, `agentLoop.scope(${id})`) + } + yield async () => { abort.abort(new Error(`agent "${id}" setup aborted: owner disposed during setup`)) - return teardown() + try { + await teardown() + } finally { + await unfollowScope?.() + } } }, `agentLoop.lifecycle(${id})`) /* v8 ignore start -- ctx.effect throws only on an inactive fiber, which assertActive() above already rejected */ diff --git a/packages/core/scope/tests/scope.spec.ts b/packages/core/scope/tests/scope.spec.ts index 13942fdf9d..fa9c1dc705 100644 --- a/packages/core/scope/tests/scope.spec.ts +++ b/packages/core/scope/tests/scope.spec.ts @@ -1,4 +1,4 @@ -import { describe, expect, expectTypeOf, it, onTestFinished } from 'vitest' +import { describe, expect, expectTypeOf, it } from 'vitest' import { Context } from '@deepseek-ai/cordis' import { bindScopeParent, carrierKeyOf, createScope, isScopeCarrier, scopeChainOf, scopeOf, scopeParentOf, scopeTarget } from '@deepseek-ai/dsh-scope' import type { Scope, Scoped } from '@deepseek-ai/dsh-scope' @@ -87,38 +87,6 @@ describe('createScope', () => { await dispose() expect(order).toEqual(['inner', 'scope', 'outer']) }) - - it('moves scope cleanup to a composite on another fiber', async () => { - const ctx = new Context() - const release = Promise.withResolvers() - onTestFinished(async () => { - release.resolve(undefined) - await ctx.fiber.dispose() - }) - let originCtx!: Context - const origin = await ctx.plugin((inner: Context) => { originCtx = inner }) - const scope = createScope(originCtx, { name: 'cross-fiber' }) - const order: string[] = [] - scope.ctx.effect(() => () => { order.push('scope') }) - const draining = Promise.withResolvers() - const owner = await ctx.plugin((inner: Context) => { - inner.effect(function* () { - yield scope.rawDispose - yield async () => { - draining.resolve(undefined) - await release.promise - order.push('drained') - } - }) - }) - const disposal = owner.dispose() - await draining.promise - await origin.dispose() - expect(order).toEqual([]) - release.resolve(undefined) - await disposal - expect(order).toEqual(['drained', 'scope']) - }) }) describe('scopeTarget', () => { diff --git a/packages/extensions/tool-cordis/tests/cordis-lifecycle.spec.ts b/packages/extensions/tool-cordis/tests/cordis-lifecycle.spec.ts index 3fdd9f119e..cf29a922af 100644 --- a/packages/extensions/tool-cordis/tests/cordis-lifecycle.spec.ts +++ b/packages/extensions/tool-cordis/tests/cordis-lifecycle.spec.ts @@ -95,25 +95,6 @@ describe('Cordis effect ownership', () => { expect(ctx.fiber.getEffects()).toEqual([]) }) - it('adopts a yielded plain effect disposer away from its creating fiber', async () => { - const ctx = new Context() - const order: string[] = [] - let originCtx!: Context - const origin = await ctx.plugin((inner: Context) => { originCtx = inner }) - const adopted = originCtx.effect(() => () => { order.push('adopted') }, 'adopted-effect') - const owner = await ctx.plugin((inner: Context) => { - inner.effect(function* () { - yield adopted - yield () => { order.push('owner') } - }, 'composite-effect') - }) - - await origin.dispose() - expect(order).toEqual([]) - await owner.dispose() - expect(order).toEqual(['owner', 'adopted']) - }) - it('rejects cleanup-time registration while a restart is unloading', async () => { const ctx = new Context() let registrationError: unknown diff --git a/packages/session/session-projection/README.i18n.yaml b/packages/session/session-projection/README.i18n.yaml index 2de0a0b1ef..c6305ff877 100644 --- a/packages/session/session-projection/README.i18n.yaml +++ b/packages/session/session-projection/README.i18n.yaml @@ -24,8 +24,8 @@ en: 09758d1475fad86e zh: 473637cb34aebe72 /deepseek-ai-dsh-session-projection/use-this-package/register-and-read: - en: 9430eb1210648030 - zh: 280428f2ff1c71c1 + en: 6a19c075f826b3f7 + zh: c200277cb58062be /deepseek-ai-dsh-session-projection/use-this-package/persisted-checkpoints: en: 45f1c05fb7e08180 zh: f8d62c749899651a diff --git a/packages/session/session-projection/README.md b/packages/session/session-projection/README.md index e0cfd0252a..79c5e0b213 100644 --- a/packages/session/session-projection/README.md +++ b/packages/session/session-projection/README.md @@ -55,7 +55,7 @@ const definition = { ### Register and read -`register(definition)` installs the unit; registrants with the same key and `stateVersion` share its cells, while an incompatible version or invalid `stateVersion` throws. Registration is an effect on the calling fiber, so the last unload removes the key and its cached cells. The returned Cordis disposer can be yielded into a composite `ctx.effect()` to keep the projection available through dependent cleanup. Carriers read a consistent synchronous cut over every client-visible unit with `snapshot(session)` — `{ asOfSeq, values }`, where `asOfSeq` is the seq of the last event every value reflects — and subscribe to per-change notifications with `onChanged(listener)`. `stateOf(session, key)` reads one unit's live read-only host state without computing unrelated views. +`register(definition)` installs the unit; registrants with the same key and `stateVersion` share its cells, while an incompatible version or invalid `stateVersion` throws. Registration is an effect on the calling fiber, so the last unload removes the key and its cached cells. The returned disposer can be yielded into a composite `ctx.effect()` on the same fiber to keep the unit available through dependent cleanup. Carriers read a consistent synchronous cut over every client-visible unit with `snapshot(session)` — `{ asOfSeq, values }`, where `asOfSeq` is the seq of the last event every value reflects — and subscribe to per-change notifications with `onChanged(listener)`. `stateOf(session, key)` reads one unit's live read-only host state without computing unrelated views. ```text const dispose = ctx.sessionProjections.register(definition) diff --git a/packages/session/session-projection/README.zh.md b/packages/session/session-projection/README.zh.md index 35610554bf..cb44e32ef9 100644 --- a/packages/session/session-projection/README.zh.md +++ b/packages/session/session-projection/README.zh.md @@ -55,7 +55,7 @@ const definition = { ### 注册与读取 -`register(definition)` 安装单元;具有相同 key 和 `stateVersion` 的注册方共享其 cell,版本不兼容或 `stateVersion` 非法时会 throw。注册是挂在调用方 fiber 上的 effect,因此最后一个注册方卸载后会移除 key 及其缓存 cell。返回的 Cordis disposer 可以 yield 到复合 `ctx.effect()` 中,让依赖它的清理完成前投影始终可用。载体用 `snapshot(session)` 对每个客户端可见单元读取一致的同步切面——`{ asOfSeq, values }`,其中 `asOfSeq` 是所有值共同反映到的最后一个事件的 seq——并用 `onChanged(listener)` 订阅逐变更通知。`stateOf(session, key)` 读取一个单元的实时只读 host 状态,不计算无关视图。 +`register(definition)` 安装单元;具有相同 key 和 `stateVersion` 的注册方共享其 cell,版本不兼容或 `stateVersion` 非法时会 throw。注册是挂在调用方 fiber 上的 effect,因此最后一个注册方卸载后会移除 key 及其缓存 cell。返回的 disposer 可以 yield 到同一 fiber 上的复合 `ctx.effect()` 中,使单元在依赖它的清理完成前保持可用。载体用 `snapshot(session)` 对每个客户端可见单元读取一致的同步切面——`{ asOfSeq, values }`,其中 `asOfSeq` 是所有值共同反映到的最后一个事件的 seq——并用 `onChanged(listener)` 订阅逐变更通知。`stateOf(session, key)` 读取一个单元的实时只读 host 状态,不计算无关视图。 ```text const dispose = ctx.sessionProjections.register(definition) diff --git a/packages/session/session-projection/src/index.ts b/packages/session/session-projection/src/index.ts index 515418cee3..ac6e63458f 100644 --- a/packages/session/session-projection/src/index.ts +++ b/packages/session/session-projection/src/index.ts @@ -306,8 +306,7 @@ export class SessionProjectionRegistry extends Service { this.listeners.delete(listener) } }, 'sessionProjections.onChanged()') - // oxlint-disable-next-line typescript/no-misused-promises -- synchronous cleanup; keep the Cordis disposer so effects can adopt it. - return dispose + return () => void dispose() } /** diff --git a/vendor/README.md b/vendor/README.md index 1de68b02bd..71cd648b03 100644 --- a/vendor/README.md +++ b/vendor/README.md @@ -35,7 +35,7 @@ Keep this log exhaustive — every divergence from upstream must be listed. 3. **All `tsconfig.json` files**: regenerated to extend the repo-root `tsconfig.base.json`, emit TypeScript intermediates to `lib/types`, and declare project references. 4. **Vendored TypeScript source internal specifiers**: changed local relative imports/exports from upstream's specifier shape to explicit `.ts` specifiers so TypeScript rewrites emitted JS to `.js` while declarations keep explicit, NodeNext-safe `.ts` specifiers. This includes `loader/src/config/isolate.ts` using `declare module './entry.ts'`. Type-only dependencies use `import type` or inline `type` modifiers so ESM output does not retain erased interfaces. 5. **`schemastery/tsdown.config.ts` and `logger-console/tsdown.config.ts`**: ours, not upstream files — per-package build-shape overrides (dual ESM+CJS output; separate node/browser entries) for the repo-root tsdown build. They read the JS emitted under `lib/types` and then write the publish runtime entries under `lib/`. Like the regenerated tsconfigs, they are not part of the upstream sync surface. -6. **`cordis/src/fiber.ts` lifecycle hardening**: locally hardens reentrant and composed disposal. An effect's owner-list wrapper is registered before its setup body runs, so an unload begun from inside setup awaits setup and every collected cleanup; synchronous setup failure removes the wrapper and rolls back collected cleanup. Async cleanup stays owner-visible until quiescence, and Cordis's internal effect composition joins an already-running cleanup while repeated public disposer calls retain their upstream single-shot result. A composite effect adopts each returned or yielded Cordis disposer from its original fiber, including when the dependency context and cleanup owner are different fibers; the original fiber cannot independently dispose the adopted resource. Effect creation is rejected while the owner is `UNLOADING` (while `PENDING` and `LOADING` remain legal), preventing cleanup-time registrations from escaping the unload snapshot. Child fibers register and receive their parent-owned disposer before `internal/plugin` publication, resolve dependency declarations added by that notification before activation, drain effects attached while pending, skip plugin execution when reentrant disposal invalidates the load epoch before its first checkpoint, and contain teardown-notification failures per observer so one callback cannot starve peers or interrupt ownership cleanup. +6. **`cordis/src/fiber.ts` lifecycle hardening**: locally closes three reentrant disposal gaps. An effect's owner-list wrapper is registered before its setup body runs, so an unload begun from inside setup awaits setup and every collected cleanup; synchronous setup failure removes the wrapper and rolls back collected cleanup. Async cleanup stays owner-visible until quiescence, and Cordis's internal effect composition joins an already-running cleanup while repeated public disposer calls retain their upstream single-shot result. Effect creation is rejected while the owner is `UNLOADING` (while `PENDING` and `LOADING` remain legal), preventing cleanup-time registrations from escaping the unload snapshot. Child fibers register and receive their parent-owned disposer before `internal/plugin` publication, resolve dependency declarations added by that notification before activation, drain effects attached while pending, skip plugin execution when reentrant disposal invalidates the load epoch before its first checkpoint, and contain teardown-notification failures per observer so one callback cannot starve peers or interrupt ownership cleanup. 7. **Cordis and Loader JSDoc enrichment**: added `@param`/`@returns` tags and contract documentation (disposal semantics, waterfall veto, bail conditions, error cases) across the public plugin-author surface — `Context` (class, statics, and the `Context` interface properties incl. `root`), module re-exports, shared utility helpers, `EventsService`, `Fiber`, `RegistryService`, `ReflectService`, `Service`, `LoggerService` and their `declare module './context.ts'` overloads. Loader documentation covers `loader/src/{index,internal,config/entry,config/group,config/isolate,config/tree,config/utils}.ts`, including entry ownership, tree mutation methods, and the `!!js` discriminator. Comment-only; no code changes. Motivation: the website API-reference generator renders these docs and hard-errors on undocumented members. Retire this entry when the enrichment is upstreamed to the fork. 8. **`include/src/index.ts` resilient file refresh and patch reapplication**: [#514](https://github.com/deepseek-harness/deepseek-harness/pull/514) validates a top-level entry array before caching parsed content, logs refresh failures, reapplies patches after file or Include-config edits, updates the Include config when it vetoes a restart, and uses `initial` only after `ENOENT`. These parse protections retain the running tree after an invalid file; plugin activation failures can leave a partially applied tree. Loader entry/group/tree mutations follow the pinned eager, non-transactional implementation and do not restore previous plugins or options. Covered by `packages/boot/app-boot/tests/{config-reload,user-patches}.spec.ts`. 9. **`hmr/src/index.ts` module-watcher readiness and native paths**: realpath the existing watch base, classify framework modules and attach listeners before reporting readiness, and compare config paths using both canonical and configured spellings. This preserves Node module-cache identity across Windows short-name paths and filesystem aliases. The main watcher uses `ignoreInitial: true` so startup reads do not trigger another refresh; exact profile patch watching is owned by `packages/boot/hmr/src/watch-config.ts`. Covered by `packages/boot/hmr/tests/watch-config.spec.ts`. diff --git a/vendor/cordis/src/fiber.ts b/vendor/cordis/src/fiber.ts index 7ae2649dd5..6bb1caa7a5 100644 --- a/vendor/cordis/src/fiber.ts +++ b/vendor/cordis/src/fiber.ts @@ -110,8 +110,6 @@ interface EffectRunner { // Public effect disposers remain single-shot, but structural owners and outer // effects must still be able to join a cleanup that another caller started. const effectInertia = new WeakMap void | Promise>() -// Composites can adopt effects created through another fiber's dependency context. -const effectOwners = new WeakMap() function runDisposable(dispose: Disposable) { const result = dispose() @@ -449,8 +447,7 @@ export class Fiber { epoch: true, collect: (dispose) => { disposables.push(dispose) - const owner = effectOwners.get(dispose) ?? this - owner._disposables.delete(dispose) + this._disposables.delete(dispose) if (dispose[symbols.effect]) { meta.children.push(dispose[symbols.effect]) } @@ -516,7 +513,6 @@ export class Fiber { }) }, symbols.effect, meta) as AsyncDisposable effectInertia.set(wrapper, () => inFlight) - effectOwners.set(wrapper, this) // Make the effect visible to a reentrant owner unload before execute() // runs any plugin code. Async teardown stays owner-visible until it