fix(agent): re-check id in enter() + memoize AgentHandle.dispose() (review)

Two blocking lifecycle findings from the deep review:

- `SessionStore.enter()` is a public cross-package primitive that a caller can
  separate from `prepare()` by arbitrary work, so it must re-check the id: a
  stale prepared session could otherwise overwrite a live store entry of the
  same id, and the stale session's detach disposer would later delete the REAL
  session. Re-add the duplicate-id throw (removed earlier on a coverage
  rationale that only held for the back-to-back internal caller). Tests cover
  the stale-overwrite rejection and the prepare/enter/announce lifecycle (which
  also covers the throw branch).

- `AgentHandle.dispose()` exposed the raw single-shot cordis effect disposer, so
  a concurrent/second dispose() returned immediately (effect epoch already
  cleared) instead of awaiting the in-flight teardown — violating the
  dispose(): Promise<void> contract that every caller observes the same
  quiescence boundary. Memoize the disposal promise in startOwned. Regression
  test gates the loop's final flush, fires two dispose() calls, and asserts the
  second stays pending until the first's teardown completes (fails without the
  memo).
This commit is contained in:
Tianyi Cui
2026-06-20 13:06:28 +08:00
parent 3814ffc5b0
commit 083a6fc990
4 changed files with 99 additions and 8 deletions

View File

@@ -285,14 +285,18 @@ export class SessionStore extends Service {
* {@link announce}, so a throwing `session/created` listener rolls the attach
* back instead of leaking it.
*
* The id was already validated by {@link prepare}, which runs in the SAME
* synchronous sequence as `enter` (a config/factory caller does
* `prepare()` → `ctx.effect(generator)`, and a synchronous generator effect
* iterates inline — no await between them), so no concurrent create can claim
* the id in the gap. `enter` therefore does not re-check; it is not a public
* reservation primitive.
* Re-checks the id for a duplicate: `prepare` and `enter` are public
* cross-package primitives and a caller may interleave arbitrary work (or
* another create) between them, so a stale prepared session must NOT overwrite
* a live store entry of the same id — its detach disposer would later delete
* the REAL session. The {@link create} convenience and the agent factory call
* the two back-to-back so they never trip this, but the public seam cannot
* assume that.
*
* @throws if a session with this id is already in the store.
*/
enter(session: Session): () => void {
if (this.store.has(session.id)) throw new Error(`session "${session.id}" already exists`)
session.onAppend = (event) => { this.ctx.emit('session/event', session, event) }
this.store.set(session.id, session)
return () => {