Add scripts/gen-cordis-catalog.ts: a fully-generated docs/cordis-catalog/
events-and-services.md cataloging every cordis event (exact signature + @mode)
and ctx.<key> service (exact interface), modeled on gen-module-graph's
--write/--check freshness gate. The harness tier renders in full from the
interface Events / interface Context declarations and their JSDoc; the inherited
cordis-core/loader/hmr/timer surface renders tersely from a curated table.
The generator hard-errors on a missing @mode tag and on a tag that contradicts
a conclusive signature shape (a trailing next param is structurally a
waterfall). Signature blocks use a ts cordis-catalog fence that doc-typecheck
skips. Type tokens cross-link to the core-data-structures catalog.
This supersedes the hand-maintained event-taxonomy table: verify-event-taxonomy
is deleted and verify-cordis-catalog joins doc-sync. architecture.md keeps the
Event taxonomy heading (TOC anchor) but points at the catalog; the Service-map
role table stays. RFC, AGENTS.md @mode authoring rule, and dependent doc/skill
references updated. Negative gate tests cover the missing-tag and
tag/shape-contradiction paths.
Annotate all 24 harness events across the 5 event-declaring packages with
an explicit `@mode emit|waterfall|parallel` tag and self-contained JSDoc, so
the generated cordis catalog can render each entry's mode and prose from
source alone.
Co-locate the ACP feature support checklist with the bridge package
(packages/acp/acp-feature-support.md) and rewrite its relative links for
the new depth. Broaden the doc-sync globs (doc-typecheck, verify-md-wrap,
verify-md-links) from packages/*/README.md to packages/*/*.md so a
package-level doc beyond the README stays under the drift gates, and
update the AGENTS.md prose describing that scope.
- session/close: ⚠️→❌ (no handler; SDK dispatch returns method_not_found —
disconnect/disposal teardown is not the per-session method)
- Codex plan: ⚠️→✅ (CodexEventHandler.updatePlan emits the stable `plan`
update; the plan-as-text note was stale)
- Codex elicitation: ✅→⚠️ (maps onto session/request_permission; does not
call elicitation/create|complete)
- Overview: qualify the "both adapters ship" clause — neither drives the
client terminal/* family and only Claude uses fs/*
- Remove a stray </content> sentinel that rendered literally at EOF
Review found verify-type-equiv only scanned docs the manifest already named, so
a type-equiv block in an unmanifested doc was silently skipped — defeating the
1:1 guarantee. Scan all docs in the markdown glob scope instead, so an orphan
block in any doc is caught. Also parse `abstract class` in blockSymbol (matches
sourceDeclaration's class support).
persistence.md listed the SessionPersistence surface as create/append/load/list;
the abstract service also exposes has/delete. AGENTS.md's doc-sync command
summary omitted verify-md-links and verify-type-equiv.
Inventory the ACP v1 surface (stable schema 1.14.0 plus the unstable
features the claude-agent-acp and codex-acp reference adapters ship) and
mark where the dsh-acp bridge stands on each: agent methods, client
methods, capabilities, session/update variants, tool-call rendering,
content blocks, and a ranked gap summary.
Add a standing instruction in AGENTS.md and a hard-blocker check in the
dsh-code-review skill: a change that adds/removes/reshapes a type the catalog
documents must update the catalog (prose + verbatim block + manifest) in the
same diff. verify-type-equiv catches a drifted paste but cannot flag a new core
type that went undocumented — that judgment is on author and reviewer.
A new docs/core-data-structures/ folder: a self-contained core.md defining what
counts as a "core" data structure (the agent-loop spine) and covering the spine
vocabulary, plus per-seam sub-pages (llm-streaming, session, persistence, tools,
bash). Type definitions are pasted verbatim via `ts type-equiv` blocks and
drift-checked by verify-type-equiv. Cross-linked from architecture.md; the
`ts type-equiv` mechanics are documented in development.md.
Introduce a `ts type-equiv` Markdown fence: a verbatim paste of a source type
definition that `scripts/verify-type-equiv.ts` drift-checks against the source
symbol via the TypeScript parser, with provenance in a central
`scripts/type-equiv.manifest.json` kept 1:1 with the blocks. doc-typecheck
recognizes the same fence, skips compiling it (not standalone-compilable), and
excludes it from the opt-out ratio. Wired into the `doc-sync` chain.
The doc-current-state convention already forbade process-narration phrasing, but
review caught a subtler slip it did not name explicitly: comments and test
descriptions that reference the PR / stack position that introduced the code
("(PR D's teardown)", "Tests for … (PR C)", "identity no longer matters"). The
reader of the current tree has no PR D or prior design to anchor against. Add an
explicit clause: never name the unseeable change unit in a comment, JSDoc, or
test name — state the mechanism instead.
Two ownership tests narrated the change's history — "the old design fenced by
Agent object identity", "closing the old XXX(tool-bash-owner-hmr) gap". Reword
to state the current contract (ownership fences by session.header.id; the token
lives on the executor task, so a tool-bash reload preserves it) without
referencing the prior design. Per the repo doc-current-state convention.
The disconnect-mid-prompt test comment said "PR D's per-agent AgentHandle
teardown", narrating the change's origin. Per the repo doc-current-state
convention, state the mechanism (the session's AgentHandle teardown) without
naming the PR that introduced it.
The cancel.spec.ts module doc named "PR C", narrating the change's origin —
process/history a reader of the current test does not need. Per the repo
doc-current-state convention, describe only what the suite tests.
Reword the suite's module doc to describe what it IS — each scenario lives
here once and runs per backend through the fixture — rather than narrating
that the scenarios were previously duplicated in the per-backend specs. Per
the repo doc-current-state convention (no process/history in comments).
Review follow-ups on the bash owner-token PR:
- packages/acp/README.md still described task isolation in object-identity terms
("records each background task's owning agent", "a different agent"). Rewrite
to the session-token model: ownership is by `session.header.id`, stored on the
executor's task, so a different Agent object on the same session may access it
and ownership survives a tool-bash HMR reload.
- The reviewer flagged that the notice routes by `session.header.id` while the
registry only enforces unique `agent.id`, so a programmatic caller could
register two agents sharing a session token and mis-route a notice (not
reachable via ACP). Rather than bolt a session-id invariant onto the generic
registry, add a proposed RFC (2026-06-20-unify-agent-and-session-id) to remove
the precondition by construction — an agent IS its session, one id — with a
full risks discussion (forecloses multi-session-actor / fork futures, makes the
config resume-or-create policy load-bearing, migration churn). The actual
unification ships as its own Codex-converged PR. Cross-linked from the
agent-lifecycle RFC's seam-precondition note.
- Reframe the tool-bash module-doc ownership paragraph to current-state (per the
new AGENTS.md doc convention): contrast storing the token on the executor vs
in the plugin as a standing rationale, not as "closing the old gap".
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).
A reviewer found that window 2 (a cancel from a synchronous agent/status('running')
listener) had the same early-whenIdle() race that window 1 already guards: it
unconditionally `setStatus('idle')` + continue, which settles `whenIdle()`
waiters — so if the running listener cancels AND queues replacement work, the
waiter resolves while the replacement is still queued-and-unrun (the next
iteration runs it later, but the caller already observed quiescence).
Mirror window 1: after clearing the marker, only `setStatus('idle')` when
nothing new is queued; otherwise fall through to run the queued replacement
(status is already `running`), so `whenIdle()` resolves on that turn's
running→idle. Regression test reproduces the reviewer's interleaving (running
listener cancels A, sends B; whenIdle() resolves only after B ran).
Also syncs the cancellation contract in the two ACP RFCs that describe the live
behavior: `session/cancel` is the queue-aware `agent.cancel()` (drops an
about-to-start turn), not the old best-effort `agent.abort()` pre-step
limitation.
A reviewer found a cross-cwd hole: the ownerless-state claim path validated only
the seed prefix (via loadStored, any scope) and never compared the tracked
header's cwd to the live session's. So an ownerless `create(meta(id, "/a"))`
with cursor 0 (seed matches trivially) was claimed by a live session with the
same id at cwd "/b", and the "/b" events then appended under the "/a" header —
bypassing the cwd-scoped loadLive() guard that the HMR-adopt path (case 2) uses.
Add a cwd equality check before the seed check in the ownerless-claim branch: a
same-id ownerless artifact at a different cwd is a collision, not a claim. This
is a coordinator-level invariant (the live session's cwd must match the tracked
meta's cwd) and applies to both backends.
Tests (shared coordinator contract, run per backend): a live session at a
different cwd cannot claim cursor-0 ownerless state, cannot claim a
loaded-prefix even when the seed matches, and a no-cwd state cannot be claimed
by a cwd'd session. All fail without the guard.
Also documents WHY the `materialized` flag is needed (lazy create leaves no
artifact; it distinguishes registered-but-unwritten from durably-present for
has()/reclaim) and reframes the module doc to current-state, not the refactor
history (per the new AGENTS.md doc convention).
Two review findings on the AGENTS.md additions:
- Add a convention to § Type Safety and Documentation: document the CURRENT
state (what + why), never the PROCESS/HISTORY of how the code got there. No
"previously/now/used-to/replaces/the old X" in comments or JSDoc — that rots
on the next change and belongs in the commit message / PR / RFC. A standing
contrast against a live alternative is fine; a contrast against the codebase's
past is not.
- The "tests document behavior" worked example overstated the audit as "nothing
in production read or wrote" the summary. The backends DID write it (JSONL
sidecar, SQLite updated_at); what made it dead was no CONSUMER and no
update() caller. Corrected so a future reader does not infer the write path
never existed.
A reviewer noted the quiesce() comment + ACP README said `AgentHandle.dispose()`
stops the loop "with the queue-aware cancel", but the handle delegates to the
start-disposer's `stop(); await agent.done`, where `stop()` sets `disposed` and
aborts the current controller — it does NOT call `agent.cancel()`. The pre-step
teardown window is still closed (the disposed promise wakes the parked loop and
`isDisposed()` breaks before a turn starts), but the mechanism is the DISPOSED
path and a mid-flight turn ends with reason `disposed`, not `aborted`. Corrected
the comment and the README to describe the actual path.
(This commit follows the merge of PR C's `cancel(reason)` fix up into this branch.)
A reviewer found that `cancel(reason)` only preserved the caller's reason when
an active AbortController observed it (the mid-step path, via
`abort.signal.reason`). The marker-only windows (step-start at loop.ts and the
continuation gate) hardcoded `reason: 'cancelled'`, so the logged `turn/end`
reason was race-dependent on WHERE the cancel landed and the public
`cancel(reason?)` parameter was half-effective.
Capture the resolved reason (`reason ?? 'cancelled'`) on the agent when the
marker is armed, expose it on the LoopHandle as `cancelReason()`, and use it in
both marker branches so a turn dropped without a live controller records the
SAME `{kind:'aborted', reason}` the mid-step path produces.
The two existing window tests asserted `reason: 'cancelled'` while passing
`'from turn-start'` / `'from continuation'` — they documented the bug. Updated
both to assert the caller's reason (behavior + test changed together, per
AGENTS.md "tests document behavior, not golden truth").
Also fixes two stale docs the PR's contract change left behind: the
module-level ACP mapping comment and `codec.ts` both still said `session/cancel
-> agent.abort()`.
Codex flagged (C) a test-sufficiency gap: the completion-notice fake had
`agent.id === session.header.id`, so the notice test could not distinguish the
code matching on the registry KEY (agentId) from matching on the session TOKEN
(session.header.id). The production code deliberately matches on
`session.header.id` because a config agent has `agentId !== sessionId` — but a
same-value fake passes either way (the "hits the line but not the scenario"
trap).
Give the registered fake a distinct agentId (`agent-<sessionId>`). Verified the
notice test now FAILS if the match is regressed to `a.id` and passes on
`a.session.header.id` — so it actually pins the discriminating behavior.
Delete the `taskOwner: Map<string, Agent>` entirely — it served two roles
(access control AND holding a live Agent for completion notices), both now
stateless:
- Access control: `bash_output`/`bash_kill` compare `ctx.bash.ownerOf(id)` to
the caller's token (`exec.agent?.session.header.id`) with `!== undefined`
semantics (an empty-string token is still a real owner). The owner is stamped
at spawn via `resolve({ …, owner })`. Ownership now lives on the task in the
executor, so it SURVIVES a tool-bash HMR reload — closing the old
XXX(tool-bash-owner-hmr) gap.
- Completion notice: `onTaskDone` reads `ctx.bash.ownerOf(task.id)` and finds
the live agent by scanning `ctx.get('agents')?.list()` for a matching
`session.header.id` (read via `ctx.get` — the listener runs on the bash
fiber, a foreign fiber, where the `ctx.agents` proxy would throw). No
registry / owner gone → drop the notice cleanly.
Token is `session.header.id` (NOT `session.id`): every other subsystem keys off
the header id, and the test fakes populate only `session.header.id`, so reading
`session.id` would make every fake unowned and pass the isolation tests for the
wrong reason.
Tests give A and B DISTINCT real session tokens (a same-token-different-Agent
case is now ALLOWED — identity no longer matters); the HMR test inverts to
assert ownership SURVIVES a tool-bash reload; a new test covers the
owner-agent-gone-before-completion drop. Migrates the agent-lifecycle RFC
proposed->implemented (recording all three seams + the session-id-uniqueness
precondition) and updates the tool-bash README + the now-implemented RFC's
cross-links.
Background-task ownership needs a stable home that survives a consumer HMR
reload. Add an optional `owner?: string` to `BashExecRequest` and a
required-but-nullable `owner: string | undefined` to the resolved
`BashExecSpec` (mirroring how `workdir`/`timeoutMs` are required on the spec —
a forgotten owner is a visible `undefined`, never a silently-absent property
that yields an unowned, cross-session-readable task). `resolve()` carries it
through.
Expose the stored token via a new `BashExecutor.ownerOf(id): string |
undefined` seam (ONE read path — not also on the public `BashTask`). The
executor stores and returns the token verbatim and NEVER interprets it: the
access POLICY lives in the consumer (`dsh-tool-bash`). `bash-local` stores
`owner` on its `TrackedTask` and implements `ownerOf`; unknown-id and
known-but-ownerless both read as `undefined`. Because ownership lives on the
task in the executor (disposed with the `dsh-bash` fiber), it survives a
`tool-bash` HMR reload.
Updates the StubExecutor seam test and the bash/bash-local READMEs.
Codex found a real teardown-leak (A): the AgentHandle's composite effect runs
its disposers as a `.then()` chain, and the register disposer emitted
`agent/disposed` UNCONTAINED. A throwing listener rejected the chain, skipping
the LATER session-detach disposer — stranding the session in the store with
`onAppend` attached (a leak AND a durability hole, since the new composite
design relies on detach running). Verified by tracing fiber.ts:299-301
(`task = task.then(dispose)`) against the yield order in AgentLoop.start.
Wrap the disposer's `agent/disposed` emit in try/catch + logger.warn (the
store entry is already removed before the emit — the useful state is captured
— so logging and continuing is correct, mirroring the guarded `agent/status`
emit in ReactLoopAgent). The sibling `agent/created` emit stays uncontained on
purpose: its throw is MEANT to propagate and roll the registration back.
Regression test (acp dispose.spec): register a throwing `agent/disposed`
listener, drive a clean turn, dispose, assert the session was STILL removed.
Confirmed it FAILS without the guard (the throw escapes dispose and detach is
skipped) and passes with it.
Also (B): document the new `prepare`/`enter`/`announce` ordered-teardown
lifecycle primitives in the dsh-session README (they are public cross-package
methods now consumed by dsh-agent-loop).
Expand the "Test quality" reviewer check: 100% coverage proves lines ran, not
that the feature works the way it ships. Judge sufficiency on two axes —
would the test fail on a regression, and does it exercise the REAL thing
(genuine collaborator, real entry path, verify the world) rather than faking
inputs just enough to cover every line. Call out the specific trap of a
happy-path test that hits a line whose PURPOSE is a mid-flight/error/recovery
scenario it never actually drives — the exact gap a clean-turn "durability"
test would miss.
A stronger durability test (dispose MID-turn, then re-load from disk) caught
that the original two-sibling-effect design dropped the loop's closing
`turn/end` on the bare fiber-dispose path: a fiber unload disposes sibling
effects CONCURRENTLY (`Promise.all`, vendor/cordis/fiber.ts), so the
session-create effect detached `onAppend` racing the loop's final
`session/flush` — the re-loaded log showed crash-recovery's synthetic
`interrupted` closer instead of the real `disposed` reason. The disconnect
path happened to work (only `quiesce()` ran), but the contract must hold
uniformly.
Fix: fold the session lifecycle INTO the agent's single composite effect.
`SessionStore` now exposes `prepare` (validate + construct, no store entry),
`enter` (attach onAppend + store, returns detach), and `announce` (emit
session/created), replacing the sibling-effect `createOwned`. `AgentLoop.start`
builds ONE effect that yields, in order: session-detach, register, then
stop-and-`await agent.done`. LIFO disposal runs them as an ORDERED chain (the
runtime awaits each disposer's promise before the next), so the loop is
stopped and awaited to exit — its closing flush captured through the still-
attached onAppend — BEFORE the session detaches, whether the trigger is the
handle's dispose() OR a fiber unload. The config path uses prepare()+start
too, so it gets the same ordered teardown. All three factory entrypoints now
funnel through the one composite builder.
The mid-turn durability test asserts the REAL `disposed` reason lands on disk
(not a recovered `interrupted` substitute), proving the closing event was
captured rather than reconstructed.
The bridge now holds each session's `AgentHandle` disposer in its
`SessionRecord` and runs it on teardown (client disconnect or fiber dispose)
instead of the old `abort()` + `whenIdle()` drain that left agents
registered. A bare client disconnect now leaves NO registered agent and NO
session-store entry — not an idled-but-still-registered one. The queue-aware
`cancel()` inside the disposer also closes the former pre-step best-effort
window (a turn about to start is dropped), so teardown reaches true
quiescence.
The `session/load`-races-teardown leak is fixed: if the bridge closed while
`resume()` was pending, the just-resumed handle is disposed before throwing,
so it leaves no orphan (it has no SessionRecord, so quiesce() never sees it).
Tests: the disconnect test now asserts (through the SAME memoized teardown)
that the agent is unregistered AND its session removed; a durability test
re-loads the persisted log after dispose and asserts the closing turn/end is
on disk (guards the teardown-order contract); a sibling-isolation test proves
one handle's dispose() leaves other agents untouched. Docs: agent /
agent-loop / acp READMEs, architecture.md, and the stale in-code quiesce()
ownership comment updated to the per-agent disposal model; the now-resolved
TODO(rfc010-agent-disposal) / TODO(rfc010-cancel-prestep) teardown notes
removed.