Commit Graph

291 Commits

Author SHA1 Message Date
Tianyi Cui
07048983e0 build(doc-sync): add verify-type-equiv gate for verbatim type pastes
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.
2026-06-20 16:24:37 +08:00
Tianyi Cui
0b0486796b Merge pull request #70 from deepseek-ai/worktree-bash-owner-token
feat(bash): owner token in the executor seam
2026-06-20 14:23:37 +08:00
Tianyi Cui
5314f7cbda Merge remote-tracking branch 'origin/master' into worktree-bash-owner-token 2026-06-20 14:21:34 +08:00
Tianyi Cui
5e3f0f6d18 Merge pull request #69 from deepseek-ai/worktree-agent-handle
feat(agent): AgentHandle async per-agent disposer
2026-06-20 14:21:08 +08:00
Tianyi Cui
5f355fbc7c Merge remote-tracking branch 'origin/master' into worktree-agent-handle 2026-06-20 14:18:42 +08:00
Tianyi Cui
3556f3bb4f Merge pull request #68 from deepseek-ai/worktree-cancel-primitive
feat(agent): add queue-aware Agent.cancel() primitive
2026-06-20 14:18:03 +08:00
Tianyi Cui
05ef69f253 Merge remote-tracking branch 'origin/master' into worktree-cancel-primitive 2026-06-20 14:15:35 +08:00
Tianyi Cui
265b6ceb19 Merge pull request #67 from deepseek-ai/worktree-persistence-coordinator
refactor(session-persistence): extract a shared write coordinator
2026-06-20 14:14:59 +08:00
Tianyi Cui
8927691eb8 Merge remote-tracking branch 'origin/master' into worktree-persistence-coordinator 2026-06-20 14:12:18 +08:00
Tianyi Cui
1017ebbc74 Merge pull request #66 from deepseek-ai/worktree-drop-session-summary
refactor(session): drop the dead mutable SessionSummary
2026-06-20 14:11:37 +08:00
Tianyi Cui
fd9ecdce40 Merge remote-tracking branch 'origin/worktree-agent-handle' into worktree-bash-owner-token 2026-06-20 13:57:14 +08:00
Tianyi Cui
29ce64b8bd Merge remote-tracking branch 'origin/worktree-cancel-primitive' into worktree-agent-handle 2026-06-20 13:56:35 +08:00
Tianyi Cui
d2b26325e2 Merge remote-tracking branch 'origin/worktree-persistence-coordinator' into worktree-cancel-primitive 2026-06-20 13:55:58 +08:00
Tianyi Cui
d06c75d68f Merge remote-tracking branch 'origin/worktree-drop-session-summary' into worktree-persistence-coordinator 2026-06-20 13:54:59 +08:00
Tianyi Cui
38cc62b644 docs(AGENTS): forbid naming the change unit (PR/commit) in comments & test names (review)
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.
2026-06-20 13:53:56 +08:00
Tianyi Cui
8597cc2c58 docs(tool-bash): state ownership tests as current fact (review)
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.
2026-06-20 13:52:02 +08:00
Tianyi Cui
44762efbd7 docs(acp): drop PR-letter ref from dispose test comment (review)
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.
2026-06-20 13:51:42 +08:00
Tianyi Cui
16304872e1 docs(agent-loop): drop PR-letter ref from cancel test header (review)
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.
2026-06-20 13:51:30 +08:00
Tianyi Cui
329e5c3e2e docs(session-persistence): state coordinator-contract role as current fact (review)
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).
2026-06-20 13:51:09 +08:00
Tianyi Cui
90a19f072d docs(acp,rfc): fix stale ownership wording + propose unifying agent/session id (review)
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".
2026-06-20 13:38:48 +08:00
Tianyi Cui
b9725e8602 Merge remote-tracking branch 'origin/worktree-agent-handle' into worktree-bash-owner-token 2026-06-20 13:07:44 +08:00
Tianyi Cui
083a6fc990 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).
2026-06-20 13:06:28 +08:00
Tianyi Cui
3814ffc5b0 Merge remote-tracking branch 'origin/worktree-cancel-primitive' into worktree-agent-handle 2026-06-20 12:58:45 +08:00
Tianyi Cui
f58b031465 fix(agent): close the window-2 early-whenIdle race + sync cancellation RFC docs (review)
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.
2026-06-20 12:57:32 +08:00
Tianyi Cui
7507ca0c70 Merge remote-tracking branch 'origin/worktree-persistence-coordinator' into worktree-cancel-primitive 2026-06-20 12:52:18 +08:00
Tianyi Cui
301a3d1233 fix(session-persistence): scope the ownerless-state claim to the cwd (review)
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).
2026-06-20 12:50:55 +08:00
Tianyi Cui
a3e90bb31c Merge remote-tracking branch 'origin/worktree-drop-session-summary' into worktree-persistence-coordinator 2026-06-20 12:43:44 +08:00
Tianyi Cui
1bb201365d docs(agents): add doc-current-state convention + sharpen the summary worked example (review)
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.
2026-06-20 12:42:53 +08:00
Tianyi Cui
e8634a0495 Merge remote-tracking branch 'origin/worktree-agent-handle' into worktree-bash-owner-token 2026-06-20 11:57:15 +08:00
Tianyi Cui
de0c4605bd docs(acp): correct teardown wording — dispose uses the disposed path, not cancel() (review)
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.)
2026-06-20 11:55:56 +08:00
Tianyi Cui
15335f74ba Merge remote-tracking branch 'origin/worktree-cancel-primitive' into worktree-agent-handle 2026-06-20 11:52:45 +08:00
Tianyi Cui
6a1e381e38 fix(agent): carry cancel(reason) through the marker-only windows (review)
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()`.
2026-06-20 11:51:32 +08:00
Tianyi Cui
be6cf4510b test(tool-bash): make the notice fake's agentId differ from its session token (Codex review)
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.
2026-06-20 09:57:05 +08:00
Tianyi Cui
b58f1dd5c8 refactor(tool-bash): own background tasks by session token, not a plugin-local Map
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.
2026-06-20 08:14:27 +08:00
Tianyi Cui
d1b7c3bf95 feat(bash): add an opaque owner token to the executor seam
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.
2026-06-20 08:12:49 +08:00
Tianyi Cui
5a5b7d19c3 fix(agent): contain a throwing agent/disposed listener in the register disposer (Codex review)
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).
2026-06-20 07:47:24 +08:00
Tianyi Cui
7a94d36c46 docs(dsh-code-review): test sufficiency — real usage, not just 100% coverage
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.
2026-06-20 07:12:52 +08:00
Tianyi Cui
a53a56ff48 fix(agent-loop): fold session lifecycle into the agent effect for ordered teardown
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.
2026-06-20 07:12:29 +08:00
Tianyi Cui
ee4cad3ada feat(acp): dispose each session's agent on disconnect/teardown
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.
2026-06-20 06:44:58 +08:00
Tianyi Cui
2a4d89a4bd feat(agent): return an AgentHandle with an async per-agent disposer
The agent factory (`ctx.agents.create`/`resume`, the `AgentFactory` seam)
now returns `AgentHandle = { agent; dispose(): Promise<void> }` instead of a
bare `Agent`. The disposer is a capability: only the holder can tear down
exactly this agent — stop its loop, await the loop's exit (true quiescence,
not just the `disposed` status flip), unregister it, and remove its session
from the store.

The teardown ORDER is load-bearing for durability. The loop appends its
final `turn/end` + runs `session/flush` AFTER an abort, delivered through
`session.onAppend` → `session/event`; if the session-store effect (which
detaches `onAppend`) were torn down first, those closing events would never
reach persistence. So `dispose()`:
  1. runs the register+start effect disposer (sync: request loop stop),
  2. `await agent.done` (loop exits, final flush captured), THEN
  3. runs the session disposer (detach onAppend + delete store entry).

`SessionStore.createOwned()` exposes the session-create effect's disposer
(plain `create()` discards it — fiber-owned). `AgentLoop` funnels both
factory entrypoints (`createAgent`, `resumeWith`) through a shared
`startOwned` that composes the ordered teardown; the config path keeps a
fiber-owned agent by discarding the handle.

`ctx.agents.get(id)` still returns a bare `Agent` — the handle is only for
the owner that created it.
2026-06-20 06:44:35 +08:00
Tianyi Cui
9ee22bc6f6 fix(agent): don't resolve whenIdle() early on pre-step cancel + requeue (Codex review)
Codex's converge pass found a quiescence-contract violation: a whenIdle() waiter
registered for prompt A, then cancel() clears A, then prompt B is queued BEFORE
the loop resumes from the idle wait. The window-1 cancel branch called
settleIdle() UNCONDITIONALLY, resolving the waiter while B was still
queued-and-unrun — whenIdle() resolved with zero events, then B ran afterward.

Fix: in window 1, only settleIdle() + re-park when NO new work is queued. If a
send() raced in after the cancel, the marker was for the cancelled work only —
clear it and fall through to run the new prompt's turn, letting THAT turn's
running→idle settle the waiter (so whenIdle() waits for B to actually run).

Adds a regression test reproducing the exact interleaving (send A → whenIdle →
cancel → send B): whenIdle() now resolves only after B's turn ran (B's user
message + a turn/end in the log), and A was dropped.
2026-06-20 05:10:16 +08:00
Tianyi Cui
c4bc6e0e38 feat(agent): add queue-aware Agent.cancel() primitive
abort() only kills the in-flight step, so a queued-but-not-yet-started prompt
ran to completion after a cancel and a prompt accepted right after could be
batched into the cancelled turn (the loop merges queued messages into one turn).
This closes TODO(rfc010-cancel-prestep) with a distinct cancel() verb.

cancel() clears the queued + steering FIFOs, aborts the in-flight step, and
drives a turn-scoped marker on the LoopHandle that the driver checks at EVERY
point a turn could start or continue:
- right after the idle wait (window 1): drop the about-to-run turn and settle
  whenIdle() waiters directly (no running→idle transition fires, and no
  agent/status is emitted, so an ACP listener can't see a spurious idle that
  resolves a freshly-queued prompt as cancelled);
- after the synchronous setStatus('running') emit (window 2): a running listener
  can cancel in the gap before runTurn;
- in the step-start window (before runStep, after setAbort): a synchronous
  turn-start/step-start listener can cancel before any AbortController exists;
- at the continuation gate: a cancel during the continuation waterfall (the
  finished step's controller already cleared) ends the turn aborted.

The marker is ARMED only when there is something to cancel (running, an
in-flight step, or queued/steering work) — an idle no-op cancel cannot leave it
set to drop a later prompt — and RESET unconditionally once per loop iteration,
so it governs exactly one turn and never leaks onto the next prompt (even when a
send() lands in the cancelled turn's flush window).

ACP session/cancel now maps to agent.cancel() (keeping the synchronous
settlePrompt). Teardown/disconnect still use abort('disposed') until PR D, so
the ACP README narrows the remaining best-effort window to teardown only.

Tests (agent-loop/cancel.spec.ts) cover every window unit-level (the F1 hang
guard: a whenIdle() waiter registered before a pre-step cancel resolves; the F2
leak guard: idle cancel then a prompt runs; mid-step, continuation, both
pre-step windows, turn-start-listener, steering-cleared, marker-reset). ACP
turns.spec.ts adds the through-bridge tests with NO intervening whenIdle (idle
cancel→prompt runs; mid-stream cancel→immediate next prompt runs) and updates
the stale pre-step test to the queue-aware guarantee. The existing cancel
snapshot golden is byte-identical (it drives the new cancel() path end-to-end
through the real subprocess), so no new golden is needed. 100% coverage.
2026-06-20 04:51:32 +08:00
Tianyi Cui
3d67a98291 fix(session-persistence-jsonl): make loadLive cwd-scope-exact (Codex review)
Codex's converge pass on PR B found a cross-cwd adoption hole: the coordinator
calls loadLive(id, session.header.cwd) for HMR live-adoption, but JSONL's
loadLive delegated to findLog(id, cwd) which, for cwd === undefined, scanned
ALL cwd buckets. So a live NO-CWD session could adopt a same-id log from a real
cwd bucket, ending with a live cwd: undefined but a persisted meta.cwd: '/w'.

loadLive must treat `undefined` as the DEFINITE no-cwd bucket, not "unknown":
it now goes straight to logPath(cwd, id) (which maps undefined -> _no-cwd),
never the all-buckets scan. loadStored/deleteStored keep the any-cwd scan
(resume/removal identify by id alone), so findLog is now a pure scan-all and
loses its dead cwd-direct branch.

The coordinator's has() relied on loadLive(id, undefined) meaning "any scope"
for an untracked id — fixed to use loadStored for the untracked (unknown-cwd)
case and loadLive only for a tracked session's known cwd.

Adds a regression test: a no-cwd live session reusing an id persisted in a real
cwd bucket no longer cross-cwd-adopts — it falls through to createCore's
any-cwd collision probe and REJECTS, leaving the original log untouched. Also
fixes the README to say `tornMarker !== undefined` (a marker may be falsy, 0).
2026-06-20 04:19:12 +08:00
Tianyi Cui
ab02e9acec refactor(session-persistence): extract a shared write coordinator
The JSONL and SQLite backends were byte-identical (or same-algorithm) for ALL
of their write-path orchestration — the four maps (states/buffers/chains/inits),
installWritePath, initFor, onCreated's four adoption cases, flush, drain,
serialize, adopt/adoptLivePrefix, assertVersion, and the create/append/load/
has/delete skeletons. Only the storage primitives (write bytes vs INSERT rows)
differed, so every fix landed twice.

Extract that orchestration into a PersistenceCoordinator in the seam package.
Each backend composes one (new PersistenceCoordinator(ctx, this)), implements a
small PersistenceBackend hook interface (loadStored, loadLive, appendBatch,
commitRepair, deleteStored, list, optional close), and delegates its six public
service methods to it. Composition, not inheritance — a backend exposes only the
hooks, can't reach the coordinator's private state, and the public
SessionPersistence API is unchanged so a third-party backend may still implement
it directly.

The crash-repair torn-tail token is OPAQUE: the coordinator computes the
synthetic closers (it owns interruptedTurnClosers) but only tests
`tornMarker !== undefined` and round-trips it to commitRepair, never inspecting
it (JSONL = byte offset, SQLite = seq). loadStored vs loadLive stay distinct so
HMR adoption is cwd-scoped (a same-id log at a different cwd is a collision, not
a resume). appendBatch carries meta so lazy-materialize + first-batch commit
atomically (no separate materialize hook).

Tests: the duplicated orchestration tests (adoption, HMR, collision,
dispose-drain, crash-tail) move into one runCoordinatorContract suite run once
per backend (memory + jsonl + sqlite) via hook fixtures; per-backend specs keep
only storage mechanics. A through-coordinator torn-tail test per real backend
keeps the commitRepair-with-marker branch covered under the 100% gate.

Net -112 lines (the dedup outweighs the new coordinator + shared suite); 100%
coverage; backends shrank ~1200 lines of duplicated churn. Migrates the
write-coordinator RFC proposed -> implemented.
2026-06-20 03:47:28 +08:00
Tianyi Cui
31af23b4fe docs(session): fix stale sidecar/migration references (Codex review)
Codex's converge pass on PR A flagged three now-false references the deletion
left behind:
- the proposed write-coordinator RFC still listed an "update summary" backend
  hook and "sidecar behavior" in its test focus;
- the JSONL README's format-version note still said a format change needs a
  "version bump + migration" (contradicting the no-migration pre-release stance);
- a stale "sidecar pathing" comment in findLog's cwd-recovery branch.

All three corrected to current truth.
2026-06-20 01:30:33 +08:00
Tianyi Cui
815bac7de9 refactor(session): drop the dead mutable SessionSummary
SessionSummary (updatedAt/title/firstPrompt) and SessionPersistence.update()
were dead state: zero production callers of update(), no production reader of
updatedAt/firstPrompt, and ACP's title comes from a tool-call presenter, not
storage. The live Session.header was already typed SessionHeader, so the
summary only ever existed in the persistence layer, written and read by nothing
but its own contract test.

Delete it entirely (no SessionMeta alias — SessionMeta collapses to
SessionHeader everywhere). This removes the JSONL .summary.json sidecar
machinery, the SQLite title/first_prompt/updated_at columns and per-append
updated_at bump, and the update() method from the abstract service and both
backends. SQLite SCHEMA_VERSION goes 1->2 and openDatabase now rejects any
non-current user_version (older or newer) — no migration, unreleased software.

Net -400 lines, and it erases the JSONL-sidecar-vs-SQLite-column durability
divergence that the upcoming write coordinator would otherwise have to model.

Records the decision in docs/rfc/implemented/2026-06-19-drop-mutable-session-summary.md
and migrates the 2026-06-14 session-persistence RFC's facts to current truth.
Adds a standalone AGENTS.md section "Tests document behavior, not golden truth"
(a passing test pins current behavior, not necessarily correct behavior) with
the summary-drop as its worked example, and reinforces the no-migration
pre-release stance.
2026-06-20 01:03:57 +08:00
Tianyi Cui
0561fb47b6 Merge pull request #64 from deepseek-ai/worktree-e2e-real-api-workflow
ci: add real-API e2e workflow against external DeepSeek API
2026-06-19 18:53:32 +08:00
Tianyi Cui
27721f9f45 docs(rfc): record real-API e2e CI decision + security model
Adds docs/rfc/implemented/2026-06-19-real-api-e2e-ci.md covering the rationale
for running the real-API e2e suite in a separate secret-consuming workflow, the
fork/Dependabot/secret threat model, the residual exposure of the pull_request
trigger, and what changes when the repo goes public. Indexes it in the RFC
README.

Also adds a SECURITY comment on the pull_request trigger forbidding a switch to
pull_request_target (an untrusted-code-with-secrets leak vector, especially once
public), pointing at the RFC.
2026-06-19 18:42:27 +08:00
Tianyi Cui
6306239e6d Merge pull request #63 from deepseek-ai/worktree-extract-examples-logic
refactor(examples): extract reusable logic into tested packages (ui-stdio, llm-replay)
2026-06-19 18:42:19 +08:00
Tianyi Cui
c4d0e07488 ci(e2e): move nightly schedule to 08:17 China time (00:17 UTC) 2026-06-19 18:29:48 +08:00