diff --git a/AGENTS.md b/AGENTS.md index fb5a4e4..263f97f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -206,7 +206,7 @@ changing, reverting or "simplifying" a rule. - **The text replay is bounded at `MAX_REPLAY_TOTAL_CHARS` (180,000, the compaction transcript's number) and rendered NEWEST FIRST** (`renderReplay`): the oldest messages are what go, under one `[N earlier messages omitted ...]` line, because a per-message clip alone let a long session rebuild a 6.9 MB first message that the API refused as prompt-too-long and that no compaction could recover (issue #116). **The newest six messages keep 12,000 characters each, everything older 2,000**: the plan a build turn is about is often two exchanges back, not the newest reply. `test/get-claude-user-message.test.ts`. (h #g238) - **A reused Claude session, or a `--resume` of its own session, is told what the conversation said while it was away** (`findMissedMessages`, `src/conversation-gap.ts`, issue #114). The opencode agent is in the session key, so build -> plan -> build runs on two `claude` processes, and the build process's next envelope used to carry only the newest message: it carried on from its own last reply with no idea the plan existed. Now the stretch from the first user message past the recorded chain to the last assistant reply is rendered by `renderReplay`, on the replay's budget, ahead of the current message under ``, with one NOTICE. **The agent switch must still never carry the Claude session** (h #g223): a resumed conversation answers under the system prompt of its first request. Null for every ordinary turn (a reply-only tail), a chain that is not a prefix (an edit or a regeneration: nothing is invented), a replay turn, a switch, a cross-group fresh start and compaction; gated live on `getClaudeSessionId` / `getActiveProcess`, never on the prologue's earlier booleans. **A conversation an account in another `accountGroups` group has answered gets no catch-up at all** (h #g261): the messages it missed are that account's exchange, and this is the gate the fresh-start one cannot stand in for. **Neither verdict is read on a step that answers this key's own parked proxy calls** (`promptAnswersPendingCall`, h #g292): the recorded chain is written at a `result`, so every later step of a turn with proxied calls carries the turn's own user message past it and read as `missed`, one NOTICE, one INFO and a discarded render per step (measured 2026-11-04: 76 in two and a quarter hours across four sessions of one machine, none of them after a switch, and 25 to 35 ms each on an 8,454-message session), and that step writes no envelope a catch-up could ride on. Live on opencode 1.19.0 (2026-10-16): a build/plan/plan/build codeword exchange, the build process answering the plan's word on its fourth turn and its own on the fifth. `test/conversation-gap.test.ts`. (h #g239) - **The other way a conversation moves out from under a session is backwards, and there the session must GO: a `claude` conversation cannot have messages taken back out of it.** After an opencode `/undo`, an edited message or a regenerated reply, the reused process (or a `--resume` of its session) still holds the removed turns and acts on them. `classifyConversationChange` reads it off the same recorded chain: a non-empty shared prefix with user messages past it that the prompt no longer has is `rewound`, and the prologue ends the child (`deleteActiveProcessAndWait`), drops the id (`deleteClaudeSessionId`, which takes the served chain, the fork fingerprint and the resume record with it) and writes one `▌ **conversation rewound:**` note. **What replaces the session is a copy cut at the last turn the thread still has, `--resume --resume-session-at --fork-session` (`forkOnRewind`, default on, h #g282)**, and the bounded replay (h #g238, `includeHistoryContext = true`, NOTICE `reason: "history-rewound"` plus a kebab `forkRefused`) only when that is refused. h #g187's "a mid cut costs replay money" (19,625 writes on 2.1.280) does NOT reproduce: on 2.1.288, 2.1.293 and 2.1.314 the cut wrote 99, 121 and 38 tokens against the replay's 11,152 to 20,659, 6.9 to 9.7 times cheaper, faster, and the replay answered wrongly in all four runs (its clipping lost a document line and a tool result). The uuid is the newest Claude-written `assistant` frame's (`TurnState.lastReplyEntry`; one frame per content block, each a transcript record, measured), recorded at a SERVED `result` that did not end on a tool call; the fork keeps the parent's uuids (measured), so a checkpoint names its own session and a second undo further back forks the ORIGINAL transcript. **The checkpoint is anchored at the turn's last USER message, never at the chain length the turn was asked with**, because a turn with proxied calls is recorded with its in-flight step rendered as call plus result and opencode may render the finished turn as one message (refusal 2 below); matching is the newest checkpoint whose anchor is the history's last user message and whose digest of the history up to it is the same, with only the reply after it. No `uuid` on the inbound envelope, so no `command_lifecycle` (h #g184). Every refusal falls back to today's replay: `option-off`, `interactive-transport` (the CLI takes the cut in print mode only), `no-checkpoint` (another agent or model answered the turn the thread ends on, a failed turn, a turn before the CLI's own `compact_boundary`, which drops the key's checkpoints, more than 64 turns back), `cli-too-old` (a version gate at 2.1.288: the flag is hidden from `--help`), `transcript-gone` and `entry-gone` (checked BEFORE the spawn, because a cut the CLI cannot find exits `No message found with message.uuid` with nothing written; that result's id is not mapped, the key's checkpoints are dropped, and the stderr matcher clears the id, so a retry replays rather than re-forking). The checkpoints at and before the cut are restored after `deleteClaudeSessionId` with an empty chain, so the next turn reads no verdict until the fork's own `result`. A fork's first `total_cost_usd` carries the parent's whole running total, so `takeResultCost` takes the parent's last total as its baseline (`rewindForkSource` off the child's own args). `doGenerate` forks too and gets no note; a cross-group rewind keeps its fresh start and never forks (below). **Both refusals are load-bearing and both keep today's behaviour**: a shared prefix of ZERO is never a rewind, because that is what an opencode compaction looks like from here (the head replaced by a summary) and a reused session must survive one, which costs an undo back to the very first message and an edit of it; and a removed stretch with NO user message in it is never one either, because a turn after a proxied tool call can re-render one opencode message's tool-call and text halves as a single assistant message where the chain has two messages and a `tool` between them, and killing a healthy session on every such turn would be worse than the bug. Never on compaction, never in `doGenerate`'s text, never on a failover switch or a cross-group start, and never when the thread was already going to be replayed. **A rewound thread on a conversation another `accountGroups` group has answered still loses its session but replays nothing**, and writes the account-group note rather than this one (h #g261): the branch is what turns the replay back ON, below the point the fresh-start guard ran. **Measured live on opencode 1.19.0 + Claude Code 2.1.293** (h #g242): opencode's own `/session/{id}/revert` of the second exchange made the third turn spawn fresh with no `--resume` and a new Claude session id, write the note, and answer with the first codeword only. `test/conversation-gap.test.ts`. (h #g242) **A third refusal belongs to the DIGEST, not to this rule, and it is what the verdict mostly fired on: text the host injects into a message that is already in the history** (h #g262). 28 `history-rewound` NOTICEs in one day of the retained log, 22 with `removedUserMessages: 1`, `sharedMessages` climbing by two per turn, every one of them dcp's `` landing on the newest message of the turn before; `DIGEST_VERSION` 3 is the fix and the rule above is unchanged. **Read the shape before believing a verdict**: `removedMessages` ODD with `removedUserMessages: 1` means the first mismatch IS the newest recorded user message, which an operator edit almost never is, and `removedUserMessages` counts every user message in the removed tail rather than the number that changed, so ONE early mismatch reads as `shared 4 / removed 173 / removedUser 15`. A dcp compression of a mid-thread range would read as a rewind too and is deliberately unhandled: it was ruled out for both affected sessions (no compressed-block parts, no `compress` calls in either) and nothing has measured it, so the `b`-form reference it would be keyed on stays a candidate rather than a rule. -- **A new opencode session forked from a turn a sibling key served continues a copy of that key's Claude session cut at the turn (`forkFromCheckpoint`, default on, `findForkCheckpoint` in `src/conversation-gap.ts`, h #g305).** Measured through opencode 2.2.6 + Claude Code 2.1.322 on Haiku 5.5: a "fork from here" (`POST /api/session/:id/fork {before}`, `Session.fork = {sessionID, boundary: {type: "before", messageID}}`; on 1.19.4 `POST /session/:id/fork {messageID}`, title `(fork #N)`, no `parentID`) arrives as a new key holding the history before the boundary, and was replayed (`no-sibling-recorded`): 25,024 to 25,077 written, $0.00554 to $0.00559, the document clipped so the model could not quote it. The cut (`--resume --resume-session-at --fork-session`, `planRewindFork`'s plan) wrote 30 to 39, $0.00075 to $0.00081 (7.3x; 5.4x on 1.19.4) and quoted it every run. **The match is STRICT where the rewind's is a shape**, because two sessions can share every user message and differ in the replies: the checkpoint keeps `strictPrefix` (the history up to the turn's user message with assistant content; `recordServedConversation` hashes strict once and derives the shape, +10 to 14 ms per result on an 8,400-message 16.7 MB thread) and `replyTail` (the reply's last text block, `lastReplyEntry.text`), compared with `lastReplyText` of the filtered prompt. Every refusal of h #g187 holds: a sibling key only, the checkpoint's own `cliPath`, not busy (`claudeSessionIsWriting`), no tool result past the last reply. It runs only where the turn was still about to replay, after `forkSessions`, `findResumePoint` and the sibling carry, and a plan refusal sets `replayReason` to `fork-`. The parent's checkpoints up to the cut are restored onto the fork key, so an undo there past the fork point cuts the parent's session. **Default on although h #g187's snapshot caveat still holds** (measured on 2.1.322: a cut under a different appended prompt answered with the parent's codeword): a sibling key pins cwd, model and agent, and the appended prompt the parent's first spawn and the fork's spawn were handed was byte-identical (62,634 bytes), so what the snapshot can carry is the date line and an instruction file edited since, the exposure `resumeAfterRestart` and `forkOnRewind` already take by default. In memory only: a fork of a turn served before an opencode restart replays. `test/fork-from-checkpoint.test.ts`. +- **A new opencode session forked from a turn a sibling key served continues a copy of that key's Claude session cut at the turn (`forkFromCheckpoint`, default on, `findForkCheckpoint` in `src/conversation-gap.ts`, h #g305).** Measured through opencode 2.2.6 + Claude Code 2.1.322 on Haiku 5.5: a "fork from here" (`POST /api/session/:id/fork {before}`, `Session.fork = {sessionID, boundary: {type: "before", messageID}}`; on 1.19.4 `POST /session/:id/fork {messageID}`, title `(fork #N)`, no `parentID`) arrives as a new key holding the history before the boundary, and was replayed (`no-sibling-recorded`): 25,024 to 25,077 written, $0.00554 to $0.00559, the document clipped so the model could not quote it. The cut (`--resume --resume-session-at --fork-session`, `planRewindFork`'s plan) wrote 30 to 39, $0.00075 to $0.00081 (7.3x; 5.4x on 1.19.4) and quoted it every run. **The match is STRICT where the rewind's is a shape**, because two sessions can share every user message and differ in the replies: the checkpoint keeps `strictPrefix` (the history up to the turn's user message with assistant content; `recordServedConversation` hashes strict once and derives the shape, +10 to 14 ms per result on an 8,400-message 16.7 MB thread) and `replyTail` (the reply's last text block, `lastReplyEntry.text`), compared with `lastReplyText` of the filtered prompt. Every refusal of h #g187 holds: a sibling key only, the checkpoint's own `cliPath`, not busy (`claudeSessionIsWriting`), no tool result past the last reply. It runs only where the turn was still about to replay, after `forkSessions`, `findResumePoint` and the sibling carry, and a plan refusal sets `replayReason` to `fork-`. The parent's checkpoints up to the cut are restored onto the fork key, so an undo there past the fork point cuts the parent's session. **Default on although h #g187's snapshot caveat still holds** (measured on 2.1.322: a cut under a different appended prompt answered with the parent's codeword): a sibling key pins cwd, model and agent, and the appended prompt the parent's first spawn and the fork's spawn were handed was byte-identical (62,634 bytes), so what the snapshot can carry is the date line and an instruction file edited since, the exposure `resumeAfterRestart` and `forkOnRewind` already take by default. The checkpoints are in memory only, so after an opencode restart only a fork of the WHOLE conversation is continued (h #g319): `findForkResumePoint` reads the parent's resume record (a sibling key by `forkSiblingSignature`, same binary, not busy, transcript on disk, the record's STRICT chain this history continues with nothing but the reply past it, longest match wins) and starts the fork as `forkSessions` does, `--resume --fork-session`, gated on `forkFromCheckpoint` and `resumeAfterRestart` and the `--fork-session` help probe (`fork-cli-too-old`). Measured on 2026-11-15: a whole-conversation fork after three restarts replayed 2,888 messages bounded to 180,000 characters. **It is given `options.prompt`, the prompt `recordResumePoint` digests, never the `filterSideQuestionHistory` thread the checkpoints use**: that filter drops the plugin's `▌` note parts opencode stores inside a reply, and live on 2.2.6 every fork whose parent had a `usage` note was refused as `conversation-changed` until it was fixed; with it, the fork spawned with `--resume --fork-session`, wrote 29 tokens to the cache against 21,163 for the replay, and kept the parent's codewords. A fork from an earlier message after a restart still replays: the record keeps no cut. `test/fork-from-checkpoint.test.ts`. - **`forkSessions` is off by default, and the reason is one measurement: a resumed Claude conversation answers under the system prompt recorded on its FIRST request** (`--system-prompt-snapshot`, default `on`; a parent seeded with codename ZEBRA and forked while passing QUAIL answered ZEBRA on 2.1.280). `--system-prompt-snapshot off` fixes that and is deliberately NOT passed, because it also stops recording for the rest of the forked session. Everything else about the fork is strictly better: 814 cache writes and 39,710 reads against the replay's 22,355 and 17,385 on a ~13k-token thread, the parent's transcript byte-identical afterwards, and the forked `system`/`init` frame carries the NEW session id so the existing `setClaudeSessionId` maps it. `test/session-fork.test.ts`. (h #g187) **Measured on 2.1.293 (h #g241): with `--system-prompt-snapshot off` on a plain `--resume`, the CURRENT spawn's appended prompt wins** (a session seeded with ZEBRA and resumed under QUAIL answered QUAIL, and ZEBRA with snapshots on), so an agent switch could carry ONE Claude session instead of two processes plus ``; not adopted, because the cache cost of a prompt change on resume and what "stops recording" means for later resumes are unmeasured. Both transports since (h #g209): the TUI forks with `ClaudeSession({ forkOf })`, the same `--session-id --resume --fork-session` the `/btw` aside uses, and `recordForkFingerprint` runs for it too. - **A fork is never a subagent on either major, and `src/session-fork.ts` matches on CONTENT because that is the only rule both majors answer**: 1.18.34 copies every message with fresh ids and sets **no `parentID`**, leaving only the renameable title ` (fork #N)`, so `fetchSessionParentId` and the failover child-session refusal are untouched; 2.0.16 copies nothing (it is event-sourced) and records the source in `fork_session_id` / `fork_boundary`, exposed as `Session.fork = { sessionID, boundary }` beside an unset `parentID`, which `toV1Session` would pass through. The V2 field is a better signal and is deliberately unused: it is V2-only and it names a session, not a session KEY. The digest chain excludes every id, because opencode re-keys everything it copies. - **Every refusal is load-bearing**: a sibling key only (the key with its affinity blanked, which pins cwd, model, scope, agent, cache TTL and effort at once, and leaves compaction keys out because they have no fifth segment), the same `cliPath` (#g98), not busy via `claudeSessionIsBusy` and never `getActiveProcess` (a scan must not touch LRU order), the whole recorded chain a prefix of this history with only assistant or tool content past it, and no tool result in the trailing segment (that is a parked proxy call, and the issue-#29 gate stays empty for a new key). @@ -501,7 +501,7 @@ Opt-in. `spawnInteractiveProcess` returns an `ActiveProcess`-shaped shim so doSt - A retired model (`RETIRED_MODELS`: no longer registered, the replacement still is, `parseModelId` and `servedModelId` handing over `claude-sonnet-5-5` through an account marker and for the dated id, `retiredModel` pricing the replacement off the catalog, one WARN per id naming the replacement and both prices, `qualifyModelName` / `resolveAgentModel` / `resolveFallbackChain` still taking it where `isRegisteredModelName` does not, and the CLI catalog never adding it back from a picker): `test/retired-model.test.ts`, portable. The same through a fake CLI and a real `doStream` (`--model claude-sonnet-5-5` on two turns with one WARN, the spawn record naming `claude-sonnet-5-5`, a live model as the control, and a `compactionModel` naming it): `test/retired-model-stream.test.ts` (POSIX only). - The interactive transport's synthesized `result` (the real `runTurn` / `emitResult` with only `ClaudeSession.start` / `.tailTurn` stubbed, asserted through `describeResultFailure`; the completed, `max_tokens` and no-terminal-stop cases) and the transcript dir name (`encodeCwd` over real symlinks, the case rule, the missing-path fallback, the `configDir` join): `test/interactive-result.test.ts`. - Session fork (`forkSiblingSignature`, `splitForkHistory`, `conversationDigests`, dcp's references in every form left out of it and version 1 keeping them, every refusal of `findForkParent`, the `--fork-session` argv, the respawn rewrite in `appendResumeIfNeeded`, plus a fake CLI driving two real `doStream` turns over two affinities for the forked spawn, the id mapping, the replay fallback and the live-parent refusal): `test/session-fork.test.ts`. -- A new opencode session forked from a served turn (`forkFromCheckpoint`, h #g305: `findForkCheckpoint` finding a sibling's checkpoint at the first, a middle and the newest turn with the parent's earlier checkpoints kept, the strict match refusing an earlier reply, the last reply or a user message that differs, every h #g187 refusal on its own, a checkpoint with no reply text or no binary, a busy parent skipped for an idle one, `lastReplyText` leaving notes and reasoning out; then a fake CLI driving real `doStream` turns over two opencode sessions: the cut's argv, nothing replayed, no rewound note, the parent's transcript byte-identical, both sessions carrying on on their own processes, an undo in the fork past the fork point cutting the parent's session, and a reply nobody served, `forkFromCheckpoint: false` and a gone transcript all replaying): `test/fork-from-checkpoint.test.ts`. +- A new opencode session forked from a served turn (`forkFromCheckpoint`, h #g305: `findForkCheckpoint` finding a sibling's checkpoint at the first, a middle and the newest turn with the parent's earlier checkpoints kept, the strict match refusing an earlier reply, the last reply or a user message that differs, every h #g187 refusal on its own, a checkpoint with no reply text or no binary, a busy parent skipped for an idle one, `lastReplyText` leaving notes and reasoning out; then a fake CLI driving real `doStream` turns over two opencode sessions: the cut's argv, nothing replayed, no rewound note, the parent's transcript byte-identical, both sessions carrying on on their own processes, an undo in the fork past the fork point cutting the parent's session, and a reply nobody served, `forkFromCheckpoint: false` and a gone transcript all replaying; after a simulated restart a whole-conversation fork starting from the parent's resume record with `--fork-session` and no cut while the parent keeps its own session, and a fork from an earlier message, a gone transcript, `forkFromCheckpoint: false` and `resumeAfterRestart: false` still replaying, h #g319): `test/fork-from-checkpoint.test.ts`. - Resume after an opencode restart (`recordResumePoint`, `findResumePoint` and each refusal, `forgetResumePoint`, two processes writing one file, the cap, a malformed file, dcp renumbering its references across the restart and a version-1 record still compared as version 1, plus a fake CLI driving a real `doStream` before and after a simulated restart for the `--resume` argv, the same with dcp's references renumbered, the transcript-gone replay and `resumeAfterRestart: false`): `test/session-resume.test.ts`. - A model or effort change applied to the live child (`planLiveSwitch` for every change and refusal, `--effort` plus the dropped shell variable, the 2.1.288 gate, `findLiveSwitchSource` finding the one idle child and refusing a busy, interactive, unswitchable, session-less or second child and anything on another account, opencode session, TTL or the `default` affinity, `rebindProxyServer`, plus a fake CLI driving real `doStream` turns for a model switch, an effort switch, both together, a refused `set_model` and an unanswered request each falling back to `--resume` with the first child stopped, `liveModelSwitch: false`, a 2.1.287 CLI, an effort set where there was none, and a refusal fallback's model kept by an effort switch and cleared by `set_model`): `test/live-model-switch.test.ts`. - Carrying one conversation's Claude session across a model or effort change (`modelSiblingSignature`, including the blob's spawn settings it folds together and the agent it does not, every refusal of `findSiblingResumePoint`, the freshest-sibling tie-break, the refusal token's shape, `transferClaudeSession` moving the id and its resume record and refusing a taken destination, plus a fake CLI driving two real `doStream` turns with the model swapped for the `--resume`/`--model` argv, the cross-session and compaction refusals, `resumeAcrossModelChanges: false`, and the replay NOTICE read off a scratch log file): `test/session-model-switch.test.ts`. The effort half, including the argv of both switches in a high -> low -> high run: `test/effort-sessions.test.ts`. The first model, effort, combined, prompt-cache TTL (changed and dropped), `maxTurns` or `maxBudgetUsd` change after a simulated restart (the `--resume` argv and the new setting on the spawn, no replay, one owner on disk, a switch back, and the transcript-gone, edited-conversation and different-agent refusals): `test/restart-sibling-carry.test.ts`. diff --git a/TODO.md b/TODO.md index 1cd55f6..c452189 100644 --- a/TODO.md +++ b/TODO.md @@ -72,22 +72,6 @@ ## Backlog -- 2026-11-15, seen by the maintainer, not fixed: a fork of a conversation served before an opencode - restart replays it. Session `ses_e1f0664f3ffe...` is `(fork #1)` of the director session - `ses_e7198d765ffeUT1TqjM6JP7LiP`, made at 20:50:16Z through the parent's LAST message (boundary - `through`, seq 14362). Its first turn logged `replaying the conversation as text` with - `no-sibling-recorded` and 2,888 messages, bounded to 180,000 characters, so the fork lost almost all of - its context. The parent's resume record for the same model, agent and effort - (`claude-opus-5-5@appical`, build, xhigh) and its transcript were on disk, but `forkFromCheckpoint` - (h #g305) keeps its checkpoints in memory only and `forkSessions` is off and in memory too, and - opencode had restarted three times since the parent's last turn (19:56Z, 20:29Z, 20:41Z). Candidate - fix: when a new key is about to replay, look in the resume store for a record of another affinity on - the same cwd, model, scope, agent and binary whose STRICT chain this history continues with nothing - but the fork's own new message past it, and start with `--resume --fork-session` (the cut-at-end - case needs no `--resume-session-at`). Same snapshot caveat as h #g305, same refusals (busy parent, - transcript gone, tool result in the trailing segment). opencode 2's `Session.fork` names the source - session and could narrow the scan. A fork mid-thread still needs a persisted checkpoint uuid. - - 2026-11-14, found while fixing h #g312, not fixed (not in that PR's scope): dcp's `compact` message reference (`\n@1044@`) is not stripped in two places that strip its XML form. `src/claude-session-wrapper.ts` (the interactive transport types it into the TUI with the @@ -240,6 +224,9 @@ Verification still owed, copied from the vault's `Future Features.md` "Next up" ## Done +- 2026-11-15: **done** (h #g319): after an opencode restart, a fork of the WHOLE conversation starts + from the parent's saved Claude session (`--resume --fork-session`) instead of replaying it. A + fork from an earlier message after a restart still replays (no persisted checkpoint uuid). - 2026-11-15: **done** (v0.73.6, PR #190, h #g318): the wire-inactivity watchdog defaults to 90 s instead of 60, because 7 of 51 `stream timeout` closes on this machine came 0 to 2 s before Claude Code announced a retry after a stalled connection. Still open: the other 40 closes had no retry behind them and are not diagnosed. diff --git a/docs/agents-history.md b/docs/agents-history.md index e21ef89..bb5687e 100644 --- a/docs/agents-history.md +++ b/docs/agents-history.md @@ -13222,3 +13222,48 @@ Shipped as v0.73.6 on 2026-11-15 (PR #190), a patch: CI green on Linux and Windo on the merge commit `bebeccd` before the tag and on the release commit `91f80ec`, the publish confirmed by the `Publish package` step's tail and the version document's shasum (`b0c6603a`), with a GitHub Release. + + +## A fork of a whole conversation replayed it after an opencode restart (2026-11-15) + +h #g319. Seen by the maintainer on 2026-11-15: session `ses_e1f0664f3ffe...` is `(fork #1)` of the +director session `ses_e7198d765ffeUT1TqjM6JP7LiP`, made at 20:50:16Z through the parent's LAST +message (opencode 2.2.6 `Session.fork` boundary `{"type":"through"}`, seq 14362). Its first turn logged +`replaying the conversation as text` with `no-sibling-recorded` and 2,888 messages, bounded to 180,000 +characters, so the fork started with almost none of its context. + +The cause: `forkFromCheckpoint` (h #g305) keeps its checkpoints in memory and `forkSessions` (off by +default) its fingerprints, and opencode had restarted three times since the parent's last turn +(`plugin ready` at 19:56Z, 20:29Z and 20:41Z). The parent's resume record for the same model, agent +and effort (`claude-opus-5-5@appical`, build, xhigh) and its transcript were on disk. + +Change: `findForkResumePoint` (`src/session-resume-store.ts`) looks for a record of a sibling key +(`forkSiblingSignature`: the affinity free, cwd, model, scope, agent, prompt cache TTL and effort +pinned), the same binary, not being written to, its transcript on disk, and a STRICT chain this +history continues with nothing but the reply past it (`findResumePoint`'s test, so no tool result in +the trailing segment); the longest match wins. The prologue runs it after the in-memory fork lookup, +only where the turn was still about to replay, gated on `forkFromCheckpoint` and `resumeAfterRestart` +(it reads that option's records) and on the `--fork-session` help probe (`fork-cli-too-old` +otherwise), and starts the fork as `forkSessions` does: `--resume --fork-session` headless, +`forkOf` on the interactive transport. The parent keeps its record and its conversation. + +The lookup is given `options.prompt`, the prompt `recordResumePoint` digests, NOT the +`filterSideQuestionHistory` thread the in-memory checkpoints use: that filter drops the plugin's `▌` +note parts, which opencode stores inside the reply, so a reply that carried one (a `usage` note, say) +digested differently and every such fork was refused as `conversation-changed`. Found live, not by the +first fake (whose replies had no notes); the test now has a noted reply and fails with the filter. + +Live on opencode 2.2.6 with the worktree build (a private `serve` under scratch XDG dirs, Haiku 5.5 on +the default account): two turns in session A taught it OTTER-77 and HERON-12, the server was stopped +and started, and `POST /api/session/{A}/fork` with `{}` made a fork with boundary +`{"type":"through"}` like the maintainer's. Before the prompt fix the fork replayed (`no-sibling-recorded`, +21,163 tokens written to the cache); after it, the fork logged `forking the claude session of the +conversation this one was forked from, saved before the restart`, spawned with `--resume +--fork-session`, wrote 29 tokens to the cache (56,798 read) and answered `OTTER-77, HERON-12`. + +Not covered: a fork from an earlier message after a restart still replays, because the record keeps +no checkpoint uuid to cut at. Same snapshot caveat as h #g305 (the fork answers under the system +prompt the parent first ran with). `test/fork-from-checkpoint.test.ts` drives it through a fake CLI +across a simulated restart; controls with the branch off and with the filtered prompt both fail. A +refused candidate logs `not forking from a conversation saved before the restart` at INFO with its +reason. diff --git a/docs/configuration/options.md b/docs/configuration/options.md index 772351e..9e4423a 100644 --- a/docs/configuration/options.md +++ b/docs/configuration/options.md @@ -83,7 +83,7 @@ The minimum config is just the `plugin` entry above. Everything below is optiona | `forkSessions` | boolean | `false` | Branch a forked opencode session off the parent's Claude conversation with `--fork-session` instead of replaying its history as text. A fork taken from a turn this opencode process served is already continued that way, cut at the turn, by `forkFromCheckpoint`; this option adds forks of a parent whose turn left nothing to cut at, and the interactive transport. See [The prompt cache an agent writes](../configuration/subagents.md#the-prompt-cache-an-agent-writes). | | `forkCompaction` | boolean | `false` | Run `/compact` inside a fork of the chat's own Claude session (`--resume --fork-session`) on the chat's own model, so the summary reads that session's prompt cache and sees the whole thread, instead of a text transcript on `compactionModel`. Cheaper and more faithful on a warm cache with an inexpensive chat model, about even on Opus, dearer on a cold cache. Headless only; falls back to the transcript whenever it cannot fork. See [Compaction on a fork](../guides/compaction-and-thinking.md#compaction-on-a-fork). | | `forkOnRewind` | boolean | `true` | After an `/undo`, an edited message or a regenerated reply, continue a copy of the chat's Claude session cut at the last turn both versions of the thread share (`--resume --resume-session-at --fork-session`), instead of ending the session and replaying the shorter thread as text. Each answered turn records where its reply ended in Claude's transcript, and the copy holds exactly the turns that are left; the old transcript is never changed. Measured on Claude Code 2.1.288, 2.1.293 and 2.1.314 on a four-turn thread: 38 to 121 tokens written to the prompt cache against 11,152 to 20,659 for the replay, 6.9 to 9.7 times cheaper, faster every time, and the model kept a document line and a tool result that the replay's clipping had dropped. Anything it cannot match falls back to the replay: no recorded turn that the thread now ends on, a transcript or entry that is gone, the interactive transport (Claude Code takes the cut in print mode only), Claude Code older than 2.1.288, an account in another `accountGroups` group, and compaction. Like any `--resume`, the copy keeps the system prompt the conversation started with. See [Sessions](../internals/how-a-turn-works.md#sessions). | -| `forkFromCheckpoint` | boolean | `true` | When a new chat is forked from another one ("Fork from here", `/fork`), continue a copy of the parent's Claude session cut at the turn the fork was taken from (`--resume --resume-session-at --fork-session`), instead of replaying the inherited thread as text into a fresh session. The fork is recognised by content, on both opencode majors: its history has to match, reply for reply, a turn another chat in the same project served on the same model, agent and effort in this opencode process, and end on that turn's reply. The parent's transcript is never changed. Measured through opencode 2.2.6 and Claude Code 2.1.322 on Haiku 5.5, a 22 KB document and two codewords, forked before a third: 30 to 39 tokens written to the prompt cache against about 25,000 for the replay, 7.3 times cheaper (5.4 on opencode 1.19.4), and the fork quoted a line of the document that the replay's clipping had dropped. Like any `--resume`, the copy keeps the system prompt the parent started with; a chat in the same project on the same agent gets the same prompt (byte-identical in the measurement), so what can differ is the date line and an instruction file edited since. Anything it cannot match falls back to the replay: an opencode restart since the parent's turn, a turn that ended on a tool call, the parent mid-turn, another account, a transcript that is gone, the interactive transport and Claude Code older than 2.1.288. See [Sessions](../internals/how-a-turn-works.md#sessions). | +| `forkFromCheckpoint` | boolean | `true` | When a new chat is forked from another one ("Fork from here", `/fork`), continue a copy of the parent's Claude session cut at the turn the fork was taken from (`--resume --resume-session-at --fork-session`), instead of replaying the inherited thread as text into a fresh session. The fork is recognised by content, on both opencode majors: its history has to match, reply for reply, a turn another chat in the same project served on the same model, agent and effort in this opencode process, and end on that turn's reply. The parent's transcript is never changed. Measured through opencode 2.2.6 and Claude Code 2.1.322 on Haiku 5.5, a 22 KB document and two codewords, forked before a third: 30 to 39 tokens written to the prompt cache against about 25,000 for the replay, 7.3 times cheaper (5.4 on opencode 1.19.4), and the fork quoted a line of the document that the replay's clipping had dropped. Like any `--resume`, the copy keeps the system prompt the parent started with; a chat in the same project on the same agent gets the same prompt (byte-identical in the measurement), so what can differ is the date line and an instruction file edited since. After an opencode restart only a fork of the WHOLE conversation is continued (from the parent's saved session, `--resume --fork-session`, which needs `resumeAfterRestart`); a fork from an earlier message replays. Anything else it cannot match falls back to the replay too: a turn that ended on a tool call, the parent mid-turn, another account, a transcript that is gone, the interactive transport and Claude Code older than 2.1.288. See [Sessions](../internals/how-a-turn-works.md#sessions). | | `resumeAfterRestart` | boolean | `true` | After opencode restarts, resume a conversation's Claude session with `--resume` instead of replaying the whole thread as text into a fresh one. After each successful turn, and after one that failed on a usage limit or an expired login (Claude Code keeps that message in the session), the session id and a digest of the conversation are kept in `$XDG_STATE_HOME/opencode-claude-code-plugin/claude-sessions.json` (`0600`, at most 256 conversations, 30 days). It resumes only for the same opencode session, model, agent and account, when the transcript is still on disk and the conversation is exactly the one recorded plus Claude's reply; an edit, revert or compaction replays as before. [opencode-dcp](https://github.com/Opencode-DCP/opencode-dynamic-context-pruning)'s own additions to a message are left out of the digest: its `` references, because dcp renumbers them when opencode restarts and a conversation that had an undo in it would otherwise never resume, and its `` context-limit warning, because dcp appends that to messages already in the history and the message would otherwise look edited on the next turn. A digest written by an earlier plugin version is still compared the way it was written. opencode's own `` blocks are stored with the message, so they stay part of the digest. Like any `--resume`, the conversation keeps the system prompt it started with. `false` never reads or writes the file. | | `liveModelSwitch` | boolean | `true` | Apply a model or reasoning effort change to the conversation's running `claude` process, with Claude Code's own `set_model` and `apply_flag_settings` control requests, instead of stopping it and starting another with `--resume`. The conversation and the prompt cache are the same either way (measured on Claude Code 2.1.288 and 2.1.314); what it saves is starting a process, which took 4.6 to 6.6 seconds per change on a real install, against about 0.7 s for a model change and well under a second for an effort change. So that an effort change can apply, a headless spawn on Claude Code 2.1.288 or newer passes the effort as `--effort` and leaves `CLAUDE_CODE_EFFORT_LEVEL` out of the child's environment, because that variable would silently override a live change. It applies only when the process is idle and the change is to the model (on the same account and in the same fast mode) or between two explicit effort levels; a change that arrives while a turn is still running applies from the next turn, as before. Anything else, a refusal, or no answer within `CLAUDE_CODE_LIVE_SWITCH_TIMEOUT_MS`, falls back to the respawn. The interactive transport always respawns. Needs `resumeAcrossModelChanges`; `false` restores the respawn and the environment-variable effort exactly. | | `resumeAcrossModelChanges` | boolean | `true` | When you change a conversation's model or reasoning effort mid-conversation, continue the same Claude session (`--resume --model `) instead of replaying the whole thread as text. Both the model and the effort level are part of the session key, so changing either used to land a live conversation on a key nothing had answered; neither needs a new Claude conversation, because `--model` and `CLAUDE_CODE_EFFORT_LEVEL` are both applied at spawn time and the CLI accepts either on a transcript it resumes. The Claude session is moved off the old key rather than shared, so one conversation always has one owner. It refuses on everything `resumeAfterRestart` refuses on, plus a sibling whose transcript may still be written to (that turn finishes on the old process, and the change applies from the next one) and anything that is not the same request scope, opencode session and agent. A session opencode moved to another working directory (a `session_move` into a lane's worktree, say) is carried the same way: its transcript is copied from the old directory's project folder into the new one's and resumed there, and a turn that was still running when the session moved finishes in the old directory first. A change to an agent's prompt-cache TTL, `maxTurns` or `maxBudgetUsd` carries the conversation the same way; the new `maxBudgetUsd` counts from zero in the new process, as it does after any resume. Never on a compaction turn or an account switch. It reads the record `resumeAfterRestart` writes, which is also what carries the first change after an opencode restart, so `resumeAfterRestart: false` disables it too. | diff --git a/skills/claude-code-plugin/SKILL.md b/skills/claude-code-plugin/SKILL.md index 6f754e3..59afd63 100644 --- a/skills/claude-code-plugin/SKILL.md +++ b/skills/claude-code-plugin/SKILL.md @@ -185,7 +185,7 @@ Defaults below describe normal headless opencode use when the key is absent. | `forkSessions` | boolean | `false` | When a new opencode session turns out to be a fork of one this provider already served, branch the parent's Claude conversation with `claude --resume --fork-session` instead of re-rendering the whole thread as text into the first message. Measured on CLI 2.1.280 with haiku 4.5 over a ~13k-token thread: 814 cache tokens written and 39,710 read, against 22,355 written and 17,385 read for the replay, so $0.0058 against $0.0467 for that turn; the parent's transcript is byte-identical afterwards. Neither opencode major tells a provider that a session is a fork, so the parent is found by matching this prompt's history against what each sibling session key was last asked to continue. Off by default because a resumed Claude conversation reuses the system prompt recorded on its FIRST request (`--system-prompt-snapshot`, default `on`), so a forked session answers under the parent's appended system prompt rather than this turn's; measured directly, a parent seeded with codename ZEBRA and forked while passing QUAIL answered ZEBRA. Falls back to the replay, unchanged, for: another account, an unknown or released parent session id, a busy parent (live process, proxied call in flight, unanswered plan-mode question), a fork cut mid-conversation, a fork taken mid tool round trip, a different cwd / model / agent / effort / prompt-cache TTL, compaction, an account-failover switch, and a `claude` whose `--help` does not advertise `--fork-session`. Recording costs nothing while the option is off. | | `forkCompaction` | boolean | `false` | Headless `/compact` on a fork of the conversation's own Claude session: `--resume --fork-session` with the conversation's spawn args minus every MCP server, the skip flag (replaced by `--permission-mode dontAsk`, a read-only spawn keeps `--restricted`), its prompt file, caps and effort, on the conversation's own model. The fork reads that model's prompt cache, which keys on the model and the built-in tool set (h #g284). `compactionModel` is ignored when it fires. Measured on 2.1.314: 136k-token Haiku 5.5 thread $0.013 / 10 of 10 facts against $0.122 / 4 of 10 for the Haiku 4.5 transcript; 81k-token Opus 5.5 thread $0.054 against $0.055, same facts. Not strictly cheaper (chat-model prices, cold-cache rewrite), hence off. Falls back to the transcript, with one INFO `compacting from a transcript instead of a fork` and a `reason` token, on: interactive transport, `default` affinity, no matching served conversation in this cwd and session, no Claude session or no live process for it, a turn or proxied call in flight, another binary, transcript gone, CLI without `--fork-session` or `dontAsk`. The fork's transcript copy is deleted afterwards; the conversation's own is never touched. | | `forkOnRewind` | boolean | `true` | After an opencode `/undo`, an edited message or a regenerated reply (the `rewound` verdict), continue a copy of the conversation's Claude session cut at the last turn both versions of the thread share, `claude --resume --resume-session-at --fork-session`, instead of ending the session and replaying the shorter thread as text. Every served headless turn records a checkpoint (the uuid of its reply's last transcript entry, read off the `assistant` frames, against the conversation up to the turn's last user message); the fork is a NEW Claude session holding exactly the turns that are left, the old transcript byte-identical. Measured on 2.1.288 / 2.1.293 / 2.1.314 on a four-turn thread cut after its second turn: 99 / 121 / 38 tokens written to the prompt cache against the replay's 11,152 / 20,659 / 19,924 to 20,484, 6.9 to 9.7 times cheaper, faster in every run, and correct where the replay's clipping lost a document line and a tool result. Falls back to the replay, with a `forkRefused` token in the NOTICE, on: `option-off`, `interactive-transport` (`--resume-session-at` is print-mode only), `no-checkpoint` (the thread ends on a turn another agent or model answered, a failed turn, a turn from before the CLI's own `compact_boundary`, or more than 64 turns back), `cli-too-old` (below 2.1.288; hidden flag, so a version gate), `transcript-gone`, `entry-gone`. A cross-group account (`accountGroups`) keeps its fresh start with nothing replayed and no fork; compaction is never classified. The fork keeps the system prompt the conversation started with, like any `--resume`. A fork's first `total_cost_usd` carries its parent's running total, so the budget ledger and the `turnStats` footer take the parent's last total as its baseline. Log: `forking the claude session at the last turn the edited thread still has` (NOTICE). | -| `forkFromCheckpoint` | boolean | `true` | When a new opencode session is a fork of a turn another session served ("Fork from here", `/fork`, a `session.fork` with a `before` boundary), continue a copy of that session's Claude conversation cut at the turn, `claude --resume --resume-session-at --fork-session`, instead of replaying the inherited thread as text. Uses `forkOnRewind`'s checkpoints, matched STRICTLY across sessions (h #g305): a sibling key only (same cwd, model, scope, provider, agent, spawn settings and effort), the checkpoint's own `cliPath`, a parent not busy (`claudeSessionIsWriting`), no tool result past the last reply, the history up to the turn's user message equal with assistant content included, and the reply the thread ends on equal to the last text block Claude wrote for that turn. The parent's checkpoints up to the cut are carried onto the fork, so an undo there to before the fork point cuts the parent's session. Only where the turn was about to replay: the key's own session, `resumeAfterRestart`, a model-or-effort sibling and `forkSessions` come first. Measured through opencode 2.2.6 + Claude Code 2.1.322 on Haiku 5.5: 30 to 39 written / about 64,100 read and $0.00075 to $0.00081 against the replay's 25,024 to 25,077 written and $0.00554 to $0.00559 (7.3x); opencode 1.19.4: $0.00103 against $0.00560 (5.4x); the fork quoted a document line the replay's clipping dropped, every run. The copy answers under the system prompt the parent started with (measured on 2.1.322: a cut under a different appended prompt answered with the parent's); for a sibling the forwarded prompt was byte-identical, so the residual is the date line and instruction edits, as for `resumeAfterRestart`. Falls back to the replay with the replay NOTICE's usual `reason`, typically `no-sibling-recorded`, when nothing matched ( an opencode restart, a turn that ended on a tool call or failed, another model, agent or effort, the parent busy) or `fork-` (`fork-interactive-transport`, `fork-cli-too-old`, `fork-transcript-gone`, `fork-entry-gone`). Log: `found the turn this forked conversation was cut from` (INFO), `forking the claude session of the turn this conversation was forked from instead of replaying it` (NOTICE). | +| `forkFromCheckpoint` | boolean | `true` | When a new opencode session is a fork of a turn another session served ("Fork from here", `/fork`, a `session.fork` with a `before` boundary), continue a copy of that session's Claude conversation cut at the turn, `claude --resume --resume-session-at --fork-session`, instead of replaying the inherited thread as text. Uses `forkOnRewind`'s checkpoints, matched STRICTLY across sessions (h #g305): a sibling key only (same cwd, model, scope, provider, agent, spawn settings and effort), the checkpoint's own `cliPath`, a parent not busy (`claudeSessionIsWriting`), no tool result past the last reply, the history up to the turn's user message equal with assistant content included, and the reply the thread ends on equal to the last text block Claude wrote for that turn. The parent's checkpoints up to the cut are carried onto the fork, so an undo there to before the fork point cuts the parent's session. Only where the turn was about to replay: the key's own session, `resumeAfterRestart`, a model-or-effort sibling and `forkSessions` come first. Measured through opencode 2.2.6 + Claude Code 2.1.322 on Haiku 5.5: 30 to 39 written / about 64,100 read and $0.00075 to $0.00081 against the replay's 25,024 to 25,077 written and $0.00554 to $0.00559 (7.3x); opencode 1.19.4: $0.00103 against $0.00560 (5.4x); the fork quoted a document line the replay's clipping dropped, every run. The copy answers under the system prompt the parent started with (measured on 2.1.322: a cut under a different appended prompt answered with the parent's); for a sibling the forwarded prompt was byte-identical, so the residual is the date line and instruction edits, as for `resumeAfterRestart`. Falls back to the replay with the replay NOTICE's usual `reason`, typically `no-sibling-recorded`, when nothing matched (an opencode restart, unless the fork took the WHOLE conversation: then it starts from the parent's resume record, `--resume --fork-session`, NOTICE `forking the claude session of the conversation this one was forked from, saved before the restart`, needs `resumeAfterRestart`, h #g319; a turn that ended on a tool call or failed, another model, agent or effort, the parent busy) or `fork-` (`fork-interactive-transport`, `fork-cli-too-old`, `fork-transcript-gone`, `fork-entry-gone`). Log: `found the turn this forked conversation was cut from` (INFO), `forking the claude session of the turn this conversation was forked from instead of replaying it` (NOTICE). | | `resumeAfterRestart` | boolean | `true` | After an opencode restart, resume the conversation's Claude session (`--resume`) instead of replaying the thread as text. Persists session id + conversation digest per session key in `$XDG_STATE_HOME/opencode-claude-code-plugin/claude-sessions.json` (0600, 256 entries, 30 days) after each successful turn, and after one that failed on a usage limit or an account block, whose message Claude Code keeps in the session (h #g315). Resumes only on the same session key and binary, with the transcript on disk and the history equal to the recorded conversation plus Claude's reply; anything else (edit, revert, compaction, account switch, open tool round trip) replays. opencode-dcp's `` references (and its `@12@` compact form) are not part of the digest: dcp renumbers them on every opencode restart, so after an undo the same message came back under another number and the conversation was refused as `conversation-changed`. Records carry a digest `version`; one without it (written by an older plugin) is compared the old way. Not on compaction. Log: `resuming the claude session from before the restart` (NOTICE) or `not resuming ...` with a reason (INFO). `false` disables reading and writing. | | `liveModelSwitch` | boolean | `true` | Apply a model or reasoning effort change to the conversation's RUNNING `claude` with the CLI's own control requests (`set_model`, `apply_flag_settings {effortLevel}`) instead of stopping it and spawning another with `--resume`. Measured on 2.1.288 and 2.1.314 (h #g278): the conversation is kept, the next request goes out under the new model or effort, and prompt cache reads and writes match the respawn's; what it saves is the respawn, 4.6 to 6.6 s to `system`/`init` on a real install, against 0.5 to 0.7 s for `set_model` and about 25 to 140 ms for an effort change. So that an effort change can apply, a headless spawn on a CLI that can switch (2.1.288+) passes `--effort ` and drops `CLAUDE_CODE_EFFORT_LEVEL` from the child's env: the variable beats `apply_flag_settings` silently (a `success` answer and an unchanged request). Only on an IDLE headless child of the same conversation whose key differs in nothing but the model name (same `@account`, same fast mode) and the effort; an effort changes live only between two explicit levels. A change that lands mid-turn still finishes that turn on the old settings (h #g271) and applies at the next turn. Never across accounts, never on the interactive transport (no control channel; it keeps respawning), never on compaction. A refused or unanswered request (`CLAUDE_CODE_LIVE_SWITCH_TIMEOUT_MS`, default 10000) stops the child and falls back to the respawn. Needs `resumeAcrossModelChanges`. `false` restores the respawn and the env-var effort exactly. Log: `switched the live claude process to the new model or effort instead of respawning it` (NOTICE), `could not switch the live claude process; respawning it instead` (NOTICE, with `step` and `reason`). | | `resumeAcrossModelChanges` | boolean | `true` | When the operator changes a conversation's model or reasoning effort mid-conversation, continue the same Claude session (`--resume --model `) instead of replaying the thread as text. Both are in the session key, so changing either used to start a fresh Claude conversation (issue #91); neither needs one, because `--model` and `CLAUDE_CODE_EFFORT_LEVEL` are spawn-time and the CLI applies either to a resumed transcript (measured on 2.1.288). The session is MOVED off the old key, so one Claude conversation has exactly one owner. Refused on every term `resumeAfterRestart` is refused on (another account, a transcript that is gone, a conversation that changed) plus two more: a sibling whose transcript may still be written to (that turn is served on the sibling instead and the change applies at the next turn that finds it idle, h #g271), and anything that is not the same request scope, opencode session and agent. A session opencode MOVED to another working directory (`session_move`, a lane's worktree) is carried too (h #g317): the transcript is copied from the old directory's project folder into the new one's (the CLI would otherwise keep appending where it found it, which neither the restart lookup nor the interactive transport reads), the old key's child is stopped, and a step that answers a call parked in the old directory finishes there first. The shared `default` affinity never moves. An agent's prompt-cache TTL, `maxTurns` and `maxBudgetUsd` are spawn settings like the effort, so a change to one carries the conversation too, after a restart as well (h #g275); `--max-budget-usd` counts per process, so the carried process starts the new cap from zero, as any `--resume` does. Not on compaction, not on an account-failover switch. It reads the record `resumeAfterRestart` writes, which is also what carries the first change after an opencode restart (h #g274), so `resumeAfterRestart: false` turns it off too. Log: `continuing this conversation's claude session under the new model or effort` (NOTICE), or `... in the session's new directory` for a move. | @@ -1671,7 +1671,7 @@ Prefer the doctor: it needs no logging change and no restart. | On a turn that replayed the thread as text, Claude knows what tools the previous reply ran but not what it concluded | Plugin 0.49.0 or older kept each replayed message's first 2,000 characters, and Claude Code runs its own tools without ending a step, so a reply's tool calls and their output (one result alone is capped at 10,000 characters) sit in the same message ahead of the prose and the answer was cut | Upgrade. Each replayed message is clipped in the middle now, keeping the answer it ends on, and the newest reply gets a larger budget. Better still, avoid the replay: it only happens when the Claude session cannot be resumed, and the `▌` note or the plugin log names the reason | | Claude forgot the whole conversation at once | Claude Code cleared it (`/clear` sent as a message, or a plan-mode exit that clears context) | Look for the `▌ **claude code reset:**` note. The plugin does not replay history there on purpose; a new opencode session gets a clean slate | | After switching opencode agents (plan to build, build to plan) Claude ignores what was said under the other agent or answers an earlier message | Plugin older than 0.55.0: each agent runs its own `claude` process, and a reused one was sent only the newest message | Upgrade. The reused (or `--resume`d) process is now told what it missed, replayed as text ahead of the current message under ``; the log says `replaying the messages this claude session missed`. That line only follows an agent or model switch; a plugin that logs it on every step after a proxied tool call predates the fix for h #g292 and sent nothing then. The processes stay separate on purpose (a Claude session keeps the system prompt of its first request) | -| A chat forked with "Fork from here" or `/fork` lost a document or tool output from before the fork | Its first turn replayed the inherited thread as text, which clips long messages | Upgrade (`forkFromCheckpoint`, default on, continues the parent's session cut at the turn). Read the replay NOTICE's `reason`: one without a `fork-` prefix (typically `no-sibling-recorded`) means no served turn matched (the parent's turn predates an opencode restart, ended on a tool call or failed, ran on another model, agent or effort, or the parent was mid-turn); `fork-` names a refusal after the match (`fork-interactive-transport`, `fork-cli-too-old`, `fork-transcript-gone`, `fork-entry-gone`). | +| A chat forked with "Fork from here" or `/fork` lost a document or tool output from before the fork | Its first turn replayed the inherited thread as text, which clips long messages | Upgrade (`forkFromCheckpoint`, default on, continues the parent's session cut at the turn). Read the replay NOTICE's `reason`: one without a `fork-` prefix (typically `no-sibling-recorded`) means no served turn matched (the parent's turn predates an opencode restart and the fork was taken from an earlier message, ended on a tool call or failed, ran on another model, agent or effort, or the parent was mid-turn); `fork-` names a refusal after the match (`fork-interactive-transport`, `fork-cli-too-old`, `fork-transcript-gone`, `fork-entry-gone`). | | After an `/undo`, an edited message or a regenerated reply, Claude still acts on the turns that were removed | A `claude` session cannot have messages taken back out of its context, so the reused process still held them | Upgrade. The Claude session is dropped and replaced by a copy cut at the last turn the thread still has (`forkOnRewind`, log `forking the claude session at the last turn the edited thread still has`), or, where none was recorded, by a fresh session the thread as it stands now is replayed into; either way under a `▌ **conversation rewound:**` note. A replay logs `replaying the conversation as text: the thread was edited or undone` with `reason: history-rewound` and a `forkRefused` token naming why it did not fork. Not recognised when nothing of the old thread survives in place (an undo back to the first message, an edit of it), because that is also the shape of an opencode compaction, which must keep its process | | On opencode 2 a `▌ **conversation rewound:**` note appears although nothing was edited, with session warming (`warming`) or `/goal` on | opencode's `session.generate` (a warming keep-alive, the goal judge) was served as a turn: the question landed in the Claude conversation, opencode never stored it, so the next request read the conversation as rewound and forked it | Upgrade. A request opencode tags `kind: "generate"` (forwarded by the `model.request` hook as the `x-opencode-request-kind` header) with a session affinity is answered with the CLI's `side_question` on the conversation's live process, which writes nothing to the transcript and reads the conversation's prompt cache. Log `answered a session generate request off the conversation` (INFO). With no live process it is refused (`declined a session generate request`, `reason: no-live-session`) and opencode logs `failed to warm session` in its own log | | `prompt is too long` on the first turn after a restart or after a lost Claude session, and `/compact` fails the same way | Plugin older than 0.55.0: the text replay of the thread had per-message clips but no total | Upgrade. The replay is capped at 180,000 characters, newest first, with a `[N earlier messages omitted ...]` line when it had to drop | diff --git a/src/claude-code-language-model.ts b/src/claude-code-language-model.ts index 1fbb2cb..17d07cf 100644 --- a/src/claude-code-language-model.ts +++ b/src/claude-code-language-model.ts @@ -206,6 +206,7 @@ import { hasInteractiveTransport, requestedTransport, selectTransport } from "./ import { findForkParent, recordForkFingerprint, sessionKeyCwd } from "./session-fork.js" import { findForeignAccountSibling, + findForkResumePoint, findResumePoint, findSiblingResumePoint, recordResumePoint, @@ -2757,6 +2758,53 @@ export class ClaudeCodeLanguageModel implements LanguageModelV3 { } } + // The same kind of fork after an opencode RESTART (h #g319): the + // checkpoints above are in memory, so a fork of a conversation an earlier + // process served found nothing and replayed it whole. The parent's resume + // record is on disk, and when this history is that whole conversation the + // fork starts as `forkSessions` does, `--resume --fork-session`. A + // fork from an earlier message still replays: the record keeps no cut. + if ( + this.config.forkFromCheckpoint !== false && + this.config.resumeAfterRestart !== false && + includeHistoryContext && + !compactionMode && + !forkFromClaudeSessionId && + failoverAnswer?.kind !== "switch" + ) { + const configDir = resolveConfigDir(this.config.configDir) + const found = findForkResumePoint({ + sessionKey: sk, + // The prompt as `recordResumePoint` digests it, not the filtered thread + // the in-memory checkpoints above are keyed on. + prompt: options.prompt, + cliPath, + transcriptPath: (id, dir) => join(dir ?? configDir, "projects", encodeCwd(cwd), `${id}.jsonl`), + // `claudeSessionIsWriting`, not `getActiveProcess`, for the reason the + // fork lookup above gives. + isBusy: claudeSessionIsWriting, + }) + if (found) { + const supported = await Promise.race([ + detectCliSupportsFlag(cliPath, "--fork-session"), + turnAbort.whenAborted.then(() => false), + ]) + if (turnAbort.aborted) { + return abortedBeforeWork("probing --fork-session support") + } + if (supported) { + forkFromClaudeSessionId = found.claudeSessionId + includeHistoryContext = false + log.notice( + "forking the claude session of the conversation this one was forked from, saved before the restart, instead of replaying it", + { sessionKey: sk, parentKey: found.parentKey, matchedMessages: found.matched }, + ) + } else { + replayReason = "fork-cli-too-old" + } + } + } + // A turn that is about to resend the whole thread as text. It is lossy // (per-message text and tool results are clipped, images and reasoning are // dropped) and it is the expensive path, so it says so once, at NOTICE, diff --git a/src/log-messages.ts b/src/log-messages.ts index 4cf30bd..5fc67e8 100644 --- a/src/log-messages.ts +++ b/src/log-messages.ts @@ -118,6 +118,7 @@ export const PLUGIN_LOG_MESSAGES: ReadonlySet = new Set([ "finishing the turn in progress under its original settings", "forkSessions is on but this claude CLI has no --fork-session; replaying the conversation instead", "forking the claude session at the last turn the edited thread still has", + "forking the claude session of the conversation this one was forked from, saved before the restart, instead of replaying it", "forking the claude session of the turn this conversation was forked from instead of replaying it", "forking the parent conversation's claude session instead of replaying it", "holding a subagent dispatch for the operator's answer", diff --git a/src/session-resume-store.ts b/src/session-resume-store.ts index a004a5c..6b3fb45 100644 --- a/src/session-resume-store.ts +++ b/src/session-resume-store.ts @@ -8,6 +8,7 @@ import { DIGEST_VERSION, continuesRecordedConversation, conversationDigests, + forkSiblingSignature, modelSiblingSignature, sessionKeyCwd, type ForkMessageDigest, @@ -292,6 +293,78 @@ export function findResumePoint(opts: { return { claudeSessionId: record.claudeSessionId, matched: record.chain.length } } +/** + * The Claude session of the conversation a NEW opencode session was forked + * from in its entirety, when that conversation was served by an earlier + * opencode process, or `undefined` (h #g319). + * + * `forkFromCheckpoint` (h #g305) finds the parent through checkpoints kept in + * memory, so after a restart a fork of a whole conversation replayed it as + * text: on 2026-11-15, 2,888 messages bounded to 180,000 characters. This + * record is on disk and holds everything the in-memory fork lookup + * (`findForkParent`) compares, so the caller starts the fork the way + * `forkSessions` does, `--resume --fork-session`, and the parent's own + * conversation is left as it was. + * + * Only a fork of the WHOLE conversation: the record's strict chain must be a + * prefix of this history with nothing but the reply past it, which is + * `findResumePoint`'s test. A fork from an earlier message needs a checkpoint + * uuid the record does not keep, and still replays. The refusals are the fork + * lookup's: a sibling key only (`forkSiblingSignature`, which pins cwd, model, + * scope, agent, prompt cache TTL and effort and leaves the affinity free), the + * same binary, a parent that is not being written to, a transcript still on + * disk, and no tool result in the trailing segment. The longest match wins. + */ +export function findForkResumePoint(opts: { + sessionKey: string + prompt: Prompt + cliPath: string + transcriptPath: (claudeSessionId: string, configDir?: string) => string + isBusy: (sessionKey: string) => boolean +}): { claudeSessionId: string; parentKey: string; matched: number } | undefined { + const signature = forkSiblingSignature(opts.sessionKey) + if (signature === null) return undefined + let best: { claudeSessionId: string; parentKey: string; matched: number; updatedAt: number } | undefined + let refusal: string | undefined + for (const [key, record] of load()) { + if (key === opts.sessionKey || forkSiblingSignature(key) !== signature) continue + if (record.cliPath !== opts.cliPath) { + refusal = "another-claude-binary" + continue + } + if (best && (record.chain.length < best.matched || + (record.chain.length === best.matched && record.updatedAt <= best.updatedAt))) continue + if (!continuesRecordedConversation(record.chain, opts.prompt, { version: record.version ?? 1 })) { + refusal = "conversation-changed" + continue + } + if (opts.isBusy(key)) { + refusal = "parent-still-writing" + continue + } + if (!existsSync(opts.transcriptPath(record.claudeSessionId, record.configDir))) { + refusal = "transcript-gone" + continue + } + best = { + claudeSessionId: record.claudeSessionId, + parentKey: key, + matched: record.chain.length, + updatedAt: record.updatedAt, + } + } + if (!best) { + if (refusal) { + log.info("not forking from a conversation saved before the restart", { + sessionKey: opts.sessionKey, + reason: refusal, + }) + } + return undefined + } + return { claudeSessionId: best.claudeSessionId, parentKey: best.parentKey, matched: best.matched } +} + /** * The Claude session this opencode conversation was on before the operator * moved it to another model or another reasoning effort, or `undefined`. diff --git a/test/fork-from-checkpoint.test.ts b/test/fork-from-checkpoint.test.ts index 82026bd..2085188 100644 --- a/test/fork-from-checkpoint.test.ts +++ b/test/fork-from-checkpoint.test.ts @@ -25,8 +25,10 @@ import { deleteActiveProcessAndWait, deleteClaudeSessionId, getClaudeSessionId, + releaseIdleForHandover, sessionKey, } from "../src/session-manager.js" +import { _setResumeStorePath } from "../src/session-resume-store.js" import { detectCliVersion } from "../src/cli-version.js" import { encodeCwd } from "../src/claude-session-bun.js" import { TURN_STATS_MARKER } from "../src/turn-stats.js" @@ -202,7 +204,10 @@ if (args.includes("--version")) { process.stdout.write("2.1.322\\n") process.exit(0) } -if (args.includes("--help")) process.exit(0) +if (args.includes("--help")) { + process.stdout.write(" --fork-session When resuming, create a new session ID\\n") + process.exit(0) +} const arg = (name) => (args.indexOf(name) >= 0 ? args[args.indexOf(name) + 1] : undefined) const file = (id) => path.join(DIR, id + ".jsonl") const read = (id) => @@ -409,3 +414,86 @@ test("a fork of the parent's transcript gone from disk replays", E2E, async () = await f.cleanup() } }) + + +// After an opencode restart (h #g319): the checkpoints are gone with the +// process, and the parent's resume record on disk is what a fork of the WHOLE +// conversation starts from. +async function restart() { + await releaseIdleForHandover() + _resetServedConversations() +} + +test("after a restart, a fork of the whole conversation starts from the parent's saved session", E2E, async () => { + _resetServedConversations() + const f = fixture({ settings: { resumeAfterRestart: true } }) + _setResumeStorePath(join(f.transcripts, "..", "..", "resume.json")) + try { + await f.warm() + // opencode stores the plugin's notes as parts of the reply, and the record + // digests the prompt with them, so the lookup must too (measured live: a + // filtered prompt missed every fork whose parent had a `usage` note). + const t1 = [u("one")] + const r1 = await f.turn("ses_a", t1) + const noted = { + role: "assistant" as const, + content: [{ type: "text" as const, text: r1 }, { type: "text" as const, text: `${TURN_STATS_MARKER} 1 turn` }], + } + const t2 = [...t1, noted, u("two")] + const r2 = await f.turn("ses_a", t2) + const t3 = [...t2, a(r2), u("three")] + const r3 = await f.turn("ses_a", t3) + const parent = f.spawns()[0].sessionId as string + const parentTranscript = readFileSync(join(f.transcripts, `${parent}.jsonl`), "utf8") + await restart() + assert.equal(getClaudeSessionId(f.keyFor("ses_a")), undefined, "nothing survives in memory") + + const forkThread = [...t3, a(r3), u("in the fork")] + const forkReply = await f.turn("ses_b", forkThread) + const forked = f.spawns().at(-1) + assert.equal(argAfter(forked.args, "--resume"), parent, forked.args.join(" ")) + assert.ok(forked.args.includes("--fork-session")) + assert.equal(argAfter(forked.args, "--resume-session-at"), undefined, "the whole conversation, no cut") + const sent = sentText(f.inputs().at(-1).stdin) + assert.ok(!sent.includes("conversation_history"), sent.slice(0, 300)) + assert.equal(sent, "in the fork") + assert.ok(forkReply.includes("answered fork-"), forkReply) + // The parent's conversation is left as it was, and keeps its own record. + assert.equal(readFileSync(join(f.transcripts, `${parent}.jsonl`), "utf8"), parentTranscript) + assert.equal(getClaudeSessionId(f.keyFor("ses_b")), forked.sessionId) + + // The parent continues its own session, not the fork's. + await f.turn("ses_a", [...t3, a(r3), u("four")]) + assert.equal(argAfter(f.spawns().at(-1).args, "--resume"), parent) + assert.ok(!f.spawns().at(-1).args.includes("--fork-session")) + } finally { + _setResumeStorePath(null) + await f.cleanup() + } +}) + +test("after a restart, a fork from an earlier message, a gone transcript or the option off still replays", E2E, async () => { + for (const variant of ["earlier", "gone", "off", "no-resume"] as const) { + _resetServedConversations() + const settings: Record = { resumeAfterRestart: variant !== "no-resume" } + if (variant === "off") settings.forkFromCheckpoint = false + const f = fixture({ settings }) + _setResumeStorePath(join(f.transcripts, "..", "..", "resume.json")) + try { + await f.warm() + const { t2, t3, r2, r3 } = await serveA(f) + const parent = f.spawns()[0].sessionId as string + await restart() + if (variant === "gone") rmSync(join(f.transcripts, `${parent}.jsonl`)) + const thread = variant === "earlier" ? [...t2, a(r2), u("in the fork")] : [...t3, a(r3), u("in the fork")] + await f.turn("ses_b", thread) + const forked = f.spawns().at(-1) + assert.ok(!forked.args.includes("--fork-session"), `${variant}: ${forked.args.join(" ")}`) + assert.equal(argAfter(forked.args, "--resume"), undefined, variant) + assert.ok(sentText(f.inputs().at(-1).stdin).includes("conversation_history"), variant) + } finally { + _setResumeStorePath(null) + await f.cleanup() + } + } +})