diff --git a/AGENTS.md b/AGENTS.md index 9f13429..4fc4804 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -212,7 +212,8 @@ changing, reverting or "simplifying" a rule. - **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). - **A fork spawn's argv resumes ANOTHER key's conversation, so `appendResumeIfNeeded` rewrites it on respawn**: once the key has its own id the target becomes that id and `--fork-session` is dropped, and a rewound thread's `--resume-session-at ` with it (h #g282), or the watchdog branches the parent twice (#g84). The 19,625-write mid cut measured here was 2.1.280; from 2.1.288 a cut reads the kept turns from the cache, which is what `forkOnRewind` uses. A mid-conversation fork of a NEW opencode session (`forkSessions`) still stays on the replay, because no checkpoint maps a fork's boundary to an entry. - **`resumeAfterRestart` is ON by default, and every refusal is what makes that safe** (`src/session-resume-store.ts`). Without it the first turn of an existing conversation in a new opencode process replayed the whole thread (3 replays in the retained log, mean 648,653 characters, max 981,109). A record is written only after a `result` with `is_error !== true`, never on compaction, and is forgotten wherever the in-memory id is (`deleteClaudeSessionId`, a session-id error on stderr), so a conversation one process abandoned is never resumed by the next. **The one failed turn that IS recorded is a usage limit or an account block the CLI answered with its own `` failure reply** (`TurnState.cliFailureReply`, h #g315): read off 2.1.322's transcript of a limited session, the turn's `user` record and the `rate_limit` reply are both in it, so the session is intact and holds the message. Leaving the record a turn behind is what made the by-hand switch an operator makes BECAUSE of a limit replay the whole thread (`sibling-conversation-changed`, the limited message past the record) on 2026-11-14, and a restart after a limit replay it the same way. Every other failure keeps the old rule (a too-long prompt, say, leaves a session that no model may take), and `test/account-groups.test.ts` pins both: the switch after a limit carries, the switch after a 529 replays. **A child exiting with a non-zero code is NOT one of those any more** (h #g215): measured on 2.1.288, a headless child SIGKILLed mid-answer and one killed at its `system`/`init` frame were both resumed afterwards with the conversation intact, and the transcript exists from `init` onward, which is also the first moment this plugin has an id to keep. Forgetting there turned every crash into a full replay (issue #91); the stderr `No conversation found` forget is the backstop for an id that really is unusable. A lookup runs only where the replay was about to happen, and requires the SAME session key, the same `cliPath` (#g98), the transcript file present under `configDir/projects//`, and `continuesRecordedConversation` (the fork rule: recorded chain an exact prefix, only reply content past it, no tool result in the trailing segment). A hit just calls `setClaudeSessionId`, so the existing `--resume` in `buildCliArgs` and the interactive spawn's `resumeSessionId` do the rest. It shares `forkSessions`' system-prompt-snapshot caveat (#g187) exactly as idle-eviction resume always has, which is why it is not opt-in. **The `test` script gives every run a `mktemp -d` `XDG_STATE_HOME`**, for the #g116 reason: fake-CLI turns finish successfully and would otherwise write the operator's real store; `test/isolate.ts` gives every test process its own as well, which also covers a focused run (h #g283). Live on 1.18.34 and 2.0.22. `test/session-resume.test.ts`. (h #g197) **A digest leaves out opencode-dcp's message references, and a record says which way its digests were built** (`DIGEST_VERSION`, `src/session-fork.ts`, h #g258): dcp appends `m0004` to every user text part and completed tool output it hands a provider, numbers in memory, never reuses a number and renumbers from `m0001` when opencode restarts, so after an undo (which removes a message dcp had already numbered) every later message came back under a lower number and the conversation was refused as `conversation-changed`. Measured on opencode 1.19.3 + dcp 3.2.0 with a fake `claude`: an undone conversation started a fresh Claude session after the restart on master and resumed its own on the fix, while a plain one and a compacted one resumed on both. Version 2 strips the XML tag (any attributes, `m`/`b` refs, `BLOCKED`) and the `compact` form's last `@12@` line that dcp's opencode 2 path writes (measured on opencode 2.0.31 with the same fake `claude`, h #g259: an undone message went out as `@4@` before the restart and `@3@` after it, v0.60.1 refused the conversation as `conversation-changed` and the fix resumed it). **A record with no `version` is compared as version 1**, which is why the field exists: without it every dcp conversation would replay once on the restart that installs the upgrade. A message with no reference hashes identically under both, so a non-dcp install's records are unaffected. The in-memory chains (fork fingerprints, `conversation-gap.ts`) are always the current version. **Version 3 leaves out dcp's `` block as well, and the block is also what made `rewound` misfire** (h #g262): dcp appends its MAX CONTEXT LIMIT warning to a message that is ALREADY in the history and goes on appending it to later ones, so a user message goes out on its own turn as the operator wrote it and comes back on the next turn 1,091 characters longer. Measured over 99 of this plugin's Claude CLI transcripts: 32 distinct user messages were seen both with the block and without it (the pair, read off the wire: 141 characters at 21:25:00, 1,232 at 21:27 and three times after), against 15 that differed only by a `` value and **zero by any opencode-authored block**. **Removing a block has to level the gap it leaves**, because which blocks a message carries changes per turn: one copy ends in `\n\n` and the other in `\n\n\n\n`, so when anything was removed the blank-line runs are collapsed and the ends trimmed, bounded and linear (the leading `\s*` is still avoided for #g258's reason). That levelling runs ONLY when a dcp block was actually removed, which is what keeps a dcp-free message hashing identically under versions 2 and 3. -- **`resumeAcrossModelChanges` is ON by default and is the other half of the same bug: the model is in the session key too, so changing it mid-conversation replayed the thread exactly as an effort change did** (issue #91, at least 18 replays in one ~15-hour session). `findSiblingResumePoint` reads the record `resumeAfterRestart` already writes, so `resumeAfterRestart: false` turns this off as well and nothing new is persisted. A sibling is matched on `modelSiblingSignature`, the key with its model segment blanked, its `effort=` tail dropped by NAME rather than by position and its context blob cut to `[provider, agent]` (`withoutSpawnSettings`, the same cut `spawnIdentity` makes), which is the exact opposite selection to `forkSiblingSignature`: a fork is another opencode session continuing the same content, this is the same opencode session continuing its own, so cwd, scope, affinity, provider and agent must all match and only the model, the effort and the blob's spawn settings (prompt-cache TTL, `maxTurns=`, `maxBudgetUsd=`, h #g275) may differ (and, since (h #g226), the context blob's PROVIDER element, when an account-provider map is passed in). **A `maxBudgetUsd` change carries too, and that is honest**: `--max-budget-usd` counts per process and starts again on every `--resume` (h #g245), so the carried process gets the new cap from zero, exactly as the in-process carry (h #g270) and a replay into a fresh session would, the replay at a replay's cost. Widening the signature also widens `findForeignAccountSibling`, the `accountGroups` guard's detector, which is the safe direction: before it, a TTL set on one account's provider and not another's hid a cross-group sibling from the guard. **The caller TRANSFERS, never shares**: it kills the sibling's child first and `transferClaudeSession` moves the id, so one Claude conversation has exactly one owner and two children can never append to one transcript. **After an opencode restart (or a handover, h #g269) the sibling's id is in its resume record only**, so the carry passes the id `findSiblingResumePoint` accepted as `transferClaudeSession`'s `recorded` argument (an id in memory still wins), and the record moves with it; and `invalidateOtherSpawnVariants`, with the carry on, no longer forgets the resume record of a stale key this process never held in memory (`forgetClaudeSessionInMemory`, not `deleteClaudeSessionId`), so the lookup can take it past every refusal. Measured on master before the fix: the first model change after a restart replayed as `sibling-carry-over-failed`, and the first effort change as `no-sibling-recorded`, because the old effort's record was deleted before the lookup ran. `test/restart-sibling-carry.test.ts`. (h #g274) Every `findResumePoint` refusal holds (`cliPath` #g98, the transcript on disk) plus two of its own, a sibling that may still be written to (`claudeSessionIsWriting`, never `getActiveProcess`, which touches LRU order) and a key that is not a sibling at all; compaction is out on both sides and a failover switch never takes one. **What it compares is a SECOND chain, `shape`, and the strict one can never match across a model change**: measured on 1.18.35, opencode hands a provider an assistant message's stored reasoning as a `reasoning` part for the model that produced it and FLATTENS it into a leading `text` part for every other model, and a flattened reasoning part is indistinguishable from reply text, so no content rule sees through it. `conversationDigests(prompt, { assistantContent: false })` hashes every user and tool message by content and every assistant message by position alone; `recordResumePoint` writes both and only this lookup reads `shape`. Do not make it the default: the strict chain is what `forkSessions` and `findResumePoint` compare and the only thing that catches regenerated replies under an unchanged prompt. A pre-upgrade record has no `shape` and is simply no candidate. `--resume --model ` is measured on 2.1.288: the resumed conversation answers under the new model and still knows what it was told under the old one. `test/session-model-switch.test.ts`. (h #g215) +- **A session opencode MOVES to another working directory is the same conversation, and it is carried, never replayed** (h #g317). opencode 2 moves a session (`session_move`, a lane's Code Mode `execute` into its worktree), the session's own directory is the spawn's cwd and the key's first segment, so the next turn landed on a key nothing had answered and replayed the thread, which agent-guard then refused by size (the location-switch empty turn of 2026-11-14). Measured on 2.1.322 with Haiku 5.5: `--resume ` from another directory continues the conversation and the model reports the NEW directory (the environment block is not snapshotted), only the part after it is written to the cache again (3,630 tokens against 25 for a same-directory resume, and 0 once that prefix was cached), but with no copy the CLI keeps appending to the transcript under the OLD directory's encoded name, where `findResumePoint` and the interactive transport's tail never look. So `modelSiblingSignature` blanks the cwd (never for the shared `default` affinity, which is no one conversation), `findSiblingResumePoint` checks the transcript under the sibling's own cwd and returns `siblingCwd`, and the caller copies it with `carryTranscriptToAccount`'s `sourceCwds` (same never-overwrite and longest-copy-wins rules) before the transfer. `conversationIdentity` blanks the cwd too, so a step answering the call that moved the session (parked in the old directory's child) is served there by h #g271's routing, with `cwd` set to that key's; the next turn finds it idle and carries. Live on opencode 2.2.6: `POST /api/session/{id}/move` `{"directory"}`, then the next turn spawned in the new directory with `--resume` of the same session and answered with the first turn's codeword and the new directory (38,958 read, 18,292 written: opencode's forwarded system prompt carries the directory too). It reads the resume store, so `resumeAfterRestart: false` replays a move as it replays a model change. Widening the signature also widens the `accountGroups` detector, the safe direction. `test/session-move.test.ts` (its fake resumes only a transcript under its own directory, so the copy is proven), `test/effort-sessions.test.ts`, `test/account-transcript.test.ts`. +- **`resumeAcrossModelChanges` is ON by default and is the other half of the same bug: the model is in the session key too, so changing it mid-conversation replayed the thread exactly as an effort change did** (issue #91, at least 18 replays in one ~15-hour session). `findSiblingResumePoint` reads the record `resumeAfterRestart` already writes, so `resumeAfterRestart: false` turns this off as well and nothing new is persisted. A sibling is matched on `modelSiblingSignature`, the key with its model segment blanked, its `effort=` tail dropped by NAME rather than by position and its context blob cut to `[provider, agent]` (`withoutSpawnSettings`, the same cut `spawnIdentity` makes), which is the exact opposite selection to `forkSiblingSignature`: a fork is another opencode session continuing the same content, this is the same opencode session continuing its own, so scope, affinity, provider and agent must all match and only the model, the effort, the working directory (h #g317) and the blob's spawn settings (prompt-cache TTL, `maxTurns=`, `maxBudgetUsd=`, h #g275) may differ (and, since (h #g226), the context blob's PROVIDER element, when an account-provider map is passed in). **A `maxBudgetUsd` change carries too, and that is honest**: `--max-budget-usd` counts per process and starts again on every `--resume` (h #g245), so the carried process gets the new cap from zero, exactly as the in-process carry (h #g270) and a replay into a fresh session would, the replay at a replay's cost. Widening the signature also widens `findForeignAccountSibling`, the `accountGroups` guard's detector, which is the safe direction: before it, a TTL set on one account's provider and not another's hid a cross-group sibling from the guard. **The caller TRANSFERS, never shares**: it kills the sibling's child first and `transferClaudeSession` moves the id, so one Claude conversation has exactly one owner and two children can never append to one transcript. **After an opencode restart (or a handover, h #g269) the sibling's id is in its resume record only**, so the carry passes the id `findSiblingResumePoint` accepted as `transferClaudeSession`'s `recorded` argument (an id in memory still wins), and the record moves with it; and `invalidateOtherSpawnVariants`, with the carry on, no longer forgets the resume record of a stale key this process never held in memory (`forgetClaudeSessionInMemory`, not `deleteClaudeSessionId`), so the lookup can take it past every refusal. Measured on master before the fix: the first model change after a restart replayed as `sibling-carry-over-failed`, and the first effort change as `no-sibling-recorded`, because the old effort's record was deleted before the lookup ran. `test/restart-sibling-carry.test.ts`. (h #g274) Every `findResumePoint` refusal holds (`cliPath` #g98, the transcript on disk) plus two of its own, a sibling that may still be written to (`claudeSessionIsWriting`, never `getActiveProcess`, which touches LRU order) and a key that is not a sibling at all; compaction is out on both sides and a failover switch never takes one. **What it compares is a SECOND chain, `shape`, and the strict one can never match across a model change**: measured on 1.18.35, opencode hands a provider an assistant message's stored reasoning as a `reasoning` part for the model that produced it and FLATTENS it into a leading `text` part for every other model, and a flattened reasoning part is indistinguishable from reply text, so no content rule sees through it. `conversationDigests(prompt, { assistantContent: false })` hashes every user and tool message by content and every assistant message by position alone; `recordResumePoint` writes both and only this lookup reads `shape`. Do not make it the default: the strict chain is what `forkSessions` and `findResumePoint` compare and the only thing that catches regenerated replies under an unchanged prompt. A pre-upgrade record has no `shape` and is simply no candidate. `--resume --model ` is measured on 2.1.288: the resumed conversation answers under the new model and still knows what it was told under the old one. `test/session-model-switch.test.ts`. (h #g215) - **A turn that replays the thread as text says so once, at NOTICE, naming what it refused on**, because the replay is the lossy, expensive path and before this it was invisible unless the operator read DEBUG. The reason is a kebab TOKEN, not a sentence (`no-session-recorded`, `sibling-still-writing`, `transcript-gone`), because `/claude-code-doctor bundle`'s `reason` key is allowlisted as an `enum` and `SAFE_ENUM` forbids spaces: a sentence would arrive redacted. The replay prefix in `src/message-builder.ts` no longer says the previous session "couldn't be resumed", which read as session corruption; it says the conversation is replayed as text because no Claude session was available to continue it. `test/session-model-switch.test.ts`, `test/get-claude-user-message.test.ts`. (h #g215) - **Every `▌`-led text part the plugin writes must be registered in `PLUGIN_NOTE_MARKERS`** (aside, `TURN_STATS_MARKER`, self-compaction, rate limit, failed result, doctor, `UNATTENDED_REPLAY_MARKER`, `USAGE_LIMIT_MARKER`): none was ever Claude's output. The strip is **part-level and anchored at the start**, so each note needs its **own** text part. A marker nothing writes any more stays on the list (`RATE_LIMIT_MARKER`), because a conversation opened before the upgrade still holds blocks led by it. `test/turn-stats.test.ts` asserts every marker on the list, not only the footer that file is named for, and **scans `src/` for every `export const *_MARKER = "▌` and fails on one missing from the list**: `REFUSAL_FALLBACK_MARKER` shipped in h #g300 unregistered, so its note was replayed as Claude's own words until h #g314. (h #g108, #g194, #g314) - **What a reused child said between turns is replayed led by `UNATTENDED_REPLAY_MARKER` (`▌ **between turns:**`), never as bare text.** The replay itself is right (PR #35's proxy-detach case), but unmarked it read as this turn's answer and a rebuilt transcript handed it back as Claude's reply to the wrong message. The other measured way in: a CLI-side background task finishing after the terminal `result` makes the CLI continue the conversation on its own, so **a single `-p` invocation can emit two `result` frames** (`result_index` 0 then 1, on 2.1.280 as well as 2.1.286), which corrects (h #g104)'s "exactly one terminal `result`". A default install cannot reach that route, because `Bash` and `Task` are proxied. **The block is written only when something renders** (h #g253): a buffer of frames with no narration, which is what a `/btw` asked during a parked proxy call leaves (a status frame for the side call, measured on 2.0.31), used to write the marker over nothing. Dropped lines still get their note, and the `result` handling in the loop runs either way. `test/unattended-replay.test.ts`. (h #g189) @@ -504,6 +505,7 @@ Opt-in. `spawnInteractiveProcess` returns an `ActiveProcess`-shaped shim so doSt - 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`. +- A session opencode moved to another working directory (two real `doStream` turns in two directories of one opencode session: the next child spawned in the new directory with `--resume`, the transcript copied under the new directory's name and the original untouched, one owner on disk; the same after a simulated restart; another opencode session never carried; `resumeAfterRestart: false` replaying): `test/session-move.test.ts` (POSIX only). The mid-turn half (a step answering a call parked in the old directory finishing on that child): `test/effort-sessions.test.ts`. The carry's `sourceCwds`: `test/account-transcript.test.ts`. - Spawn-env API-key stripping and CLI hygiene vars (`claudeSpawnEnv`, `cliHygieneEnv`, the refusal-fallback fill and the operator's `0` passed through on both transports): `test/spawn-env.test.ts`. - Claude Code's own fallbacks through a fake CLI and a real `doStream` (h #g300): a reply resent without streaming after a streamed call, as `assistant` alone and after a cut `message_start` / `message_stop`, rendered once; a streamed reply's own frame still not doubled; an unstreamed tool call reaching opencode; the refusal-fallback variable reaching the spawn; a kept refusal fallback's note between the refused text and the answer, the spawn record naming the fallback model on that turn and the next, both turn-history samples under it; and no note on a compaction turn: `test/cli-fallbacks.test.ts`. - What the CLI probes cache and what they forget (`detectCliVersion`, `detectCliSupportsFlag`, a deadline kill against a refusal and a missing binary): `test/cli-probe-cache.test.ts`. diff --git a/TODO.md b/TODO.md index 2333e6f..25e6d0a 100644 --- a/TODO.md +++ b/TODO.md @@ -72,6 +72,19 @@ ## Backlog +- 2026-11-15, seen by the maintainer while h #g317 was in progress, not fixed: session + `ses_e324dbf7bffeRHQIz10AIxm7dT` (the h #g314 / h #g315 session) is stuck in a blocked-replay loop. + At 02:16:22Z a turn on `claude-fable-5-2@appical` (effort high, 510 messages, bounded to 152) + replayed with reason `sibling-conversation-changed`, agent-guard blocked it ("contains secret-like + values"), and v0.73.4 dropped the empty session as designed, so every next message replays and is + blocked the same way. The note's advice (switch back to the model or account that answered before) + likely does not help here: that key's resume record was written before the two usage-limited turns + (h #g315 fixes the recording only for turns from v0.73.4 on), so its own lookup refuses as + `conversation-changed` too, unless its `claude` is still alive in memory. To check: which keys hold a + record for this session, and whether accepting a lagging record whose missing messages the + transcript itself holds (h #g315's measurement) is safe. Never by changing what the replay sends to + get past the guard. + - 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 @@ -99,9 +112,9 @@ ("agent-guard: the prompt exceeds the assignment-probe scan cap ...", `promptKept: false`) in the worktree cwd's transcript `a9e1ac0c-416d-4644-bd57-e70eae20aae6.jsonl`, so the new key replayed the history and the guard refused it by size. h #g314 turns that into a `prompt blocked` note and an - error. Still open: that a location switch replays the thread at all (a new cwd is a new session key, - and Claude's transcript lives under the old cwd's directory). The `fix/session-move` worktree - (no commits yet) is where that would go. + error. Why it replayed at all is FIXED on `fix/session-move` (h #g317): a moved session's + conversation is carried into the new directory (transcript copied, `--resume`), and a step that + answers the call that moved it finishes on the old directory's child. - 2026-11-10, found by the pr173 lane (h #g295), not measured: Claude Code 2.1.322 adds fast mode on Vertex, while `docs/models.md` says fast mode excludes Bedrock, Vertex and Foundry. Check on a Vertex diff --git a/docs/agents-history.md b/docs/agents-history.md index aa48c85..dbdc2a1 100644 --- a/docs/agents-history.md +++ b/docs/agents-history.md @@ -13096,3 +13096,88 @@ Shipped as v0.73.4 on 2026-11-15 (PR #188), a patch, together with h #g314 and h Linux and Windows on the PR head `eb00f1c`, on the merge commit `7f893c2` before the tag and on the release commit `00a4f19`, the publish confirmed by the `Publish package` step's tail and the version document's shasum (`a2d145ff`), with a GitHub Release. + + +## A session opencode moved to another directory replayed the thread instead of carrying it (2026-11-15) + +h #g317. The location-switch empty turn recorded in TODO.md on 2026-11-14: in session +`ses_e2898d33effeo0ojQzfvfWVOJK` (opencode 2.2.6), a lane ran `shell` to create its worktree, then +Code Mode `execute` (`session_move` into that worktree). opencode recorded `location-switched` at +00:14:18Z, the next step started at 00:14:21Z, and at 00:14:27.770Z Claude Code 2.1.322 wrote +`blocked_by_hook` ("agent-guard: the prompt exceeds the assignment-probe scan cap ...", +`promptKept: false`) into the WORKTREE directory's transcript `a9e1ac0c-...`: the step had replayed +the whole history as text into a fresh session, and the guard refused it by size. h #g314 turns that +block into a note; this entry is why the step replayed at all. + +The cause is the session key: `::::::::context=[...]`. opencode 2 +resolves the spawn's cwd from the session's own directory per call (`resolveSpawnCwdForSession`), +so after a move every turn lands on a key nothing has answered. `modelSiblingSignature` (the sibling +lookup over the resume store, h #g215) and `conversationIdentity` (h #g271's routing of a step to +the key whose child is still in the turn) both kept the cwd, so neither saw the old key. + +Measured on Claude Code 2.1.322, Haiku 5.5, `--setting-sources ""`, no MCP, two scratch git repos A +and B, the appical config dir (the default account was at its 5-hour limit): + +- Seeded in A (codeword ZEBRA-41): 11,160 read from the cache, 6,348 written. +- `--resume` of that session from B with nothing copied: found (the CLI searches every project + folder), the codeword kept, and the model gave B as its working directory: the environment block + is not part of the system prompt snapshot (h #g187). Cache: 14,071 read, 3,630 written. The CLI + appended to A's file (148,893 to 159,237 bytes) and wrote nothing under B's name. +- Control, a fresh seed resumed from A: 17,555 read, 25 written. +- A fresh seed whose transcript was copied under B's name first, resumed from B: 17,701 read, 0 + written (the B prefix was already cached from the first resume), appended to the copy (159,161 + bytes), A's file untouched (148,881). + +So a move needs no new Claude conversation and costs about the environment block's tail once, while +the replay rewrites the whole thread and may be refused. But a resume with no copy keeps writing +under the old directory's name, where `findResumePoint` (it checks the transcript under the turn's +own cwd) and the interactive transport (it tails the path it computes from the cwd) never look. + +What changed: + +- `modelSiblingSignature` blanks the cwd as well as the model, the effort, the spawn settings and + the account, except for the shared `default` affinity, which is no one conversation (two + `opencode run`s in two folders). So `findSiblingResumePoint` finds the old directory's record, + checks its transcript under the sibling's own cwd, and returns `siblingCwd`. +- The caller carries the transcript with `carryTranscriptToAccount`, which takes `sourceCwds` now: + every config dir is searched under the turn's cwd and the source cwds, the longest copy wins, the + copy always lands under the turn's cwd, and nothing is overwritten (a taken target path takes a + fresh id, h #g218). Then the old key's child is stopped and `transferClaudeSession` moves the id, + the resume record and the served chain, as for a model change. Its own NOTICEs: + `continuing this conversation's claude session in the session's new directory instead of + replaying it`, and `replaying this conversation rather than carrying it to the session's new + directory` with the refusal token. +- `conversationIdentity` blanks the cwd, so a step that answers the call that moved the session + (parked in the old directory's child) is served on that child, and the turn's `cwd` becomes that + key's. The rest of that turn runs in the old directory, exactly as h #g271 finishes a model change + mid-turn under the old model; the next turn finds it idle and carries. +- Widening the signature also widens `findForeignAccountSibling`, the `accountGroups` detector, + which is the safe direction for a guard. + +Live on opencode 2.2.6 with this build (a private `serve` under scratch XDG dirs, basic auth as +`opencode` with the printed server password, Haiku 5.5 on the default account): a session created in +repo A (`POST /api/session` with `{"location":{"directory":...}}`) answered "Remember the codeword +ZEBRA-41" on Claude session `ac24c30c-...`; `POST /api/session/{id}/move` with `{"directory": }` answered 204 and the session's `location.directory` became repo B; the next prompt logged +`carrying the claude conversation over to the new session key` and `continuing this conversation's +claude session in the session's new directory instead of replaying it`, spawned in repo B with +`--resume ac24c30c-...`, and answered `ZEBRA-41 | `. Cache on that turn: 38,958 read, 18,292 +written (the first turn wrote 56,776): opencode's forwarded system prompt carries the working +directory too, so more of it is rewritten than with the bare CLI, still about a third of what a +replay rewrites. The transcript: repo A's original left at 492,221 bytes, repo B's copy 502,753 after +the turn. + +Not changed: it reads the resume store, so with `resumeAfterRestart: false` a move replays, as a +model change does. A fork into another directory (`forkSessions`, `forkFromCheckpoint`) still keys +on the cwd. Not measured live: the mid-turn move (a Code Mode `execute` calling `session_move`), +which the fake-CLI test covers, and the interactive transport (the copy lands where its tail looks, +by construction). + +Tests: `test/session-move.test.ts` (two real `doStream` turns in two directories of one opencode +session, with a fake CLI that resumes only a transcript under its own directory: carried and +copied, the original untouched, one owner on disk; after a simulated restart too; another session +never carried; `resumeAfterRestart: false` replaying; the two carry tests fail with the signature +change switched off), the mid-turn step in `test/effort-sessions.test.ts` (without the routing the +step never reaches the parked child and the test times out), `sourceCwds` in +`test/account-transcript.test.ts`, and the updated signature cases in +`test/session-model-switch.test.ts` and `test/account-groups.test.ts`. diff --git a/docs/configuration/options.md b/docs/configuration/options.md index 384ec1e..772351e 100644 --- a/docs/configuration/options.md +++ b/docs/configuration/options.md @@ -86,7 +86,7 @@ The minimum config is just the `plugin` entry above. Everything below is optiona | `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). | | `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 working directory, request scope, opencode session and agent. 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. | +| `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. | | `crossAccountResume` | boolean | `true` | On an account switch, whether you pick another account's model by hand in the same session or through the [switch form](./accounts.md), and only between accounts in the same `accountGroups` group, continue the same Claude conversation on the other account instead of replaying the whole thread as text into a fresh session there. An account is a `CLAUDE_CONFIG_DIR` and a conversation is one transcript file inside it, so the switch copies that file into the target account's own `projects//` (`0600`, never overwriting, never through a symlink) and spawns it with the `--resume` that already exists. Claude Code 2.1.288 resumes a copied transcript with its context intact and resolves a session by filename, so an older copy already sitting at the target path makes the carry take a fresh session id rather than overwrite it. The source transcript is never moved, emptied or written to. Any refusal falls back to the replay and says which in the log. Does nothing on a single-account install. | | `usageWarnThresholds` | number[] | `[50, 75, 90, 95]` | Usage levels, in percent of a usage window, at which a served turn ends with one `▌ **usage:**` line: which account, which window, how much of it is used, and when it resets in your own time zone. Each threshold is said once per account per window (not again on the next turn, from another session, or after a restart) and again only after the window resets. Never on a `/compact` turn or in a subagent's session. Read from Claude Code's own usage reports, so the interactive transport (which gets none) only records a limit. `[]` turns the notes off; the readings are still kept for the sidebar and `/claude-code-doctor`. Works with one account. See [Usage before the limit](./accounts.md#usage-before-the-limit). | | `usageSwitchAt` | number \| `false` | `90` | The usage level, in percent, at which work should leave an account **before** it hits the limit, when another account in the same `accountGroups` group is configured and is not itself at that level. With `accountFailover: "auto"`, new turns move to that account until the window resets (the same account-wide switch a usage limit makes, held in memory), and the `▌ **usage:**` line says so. With `"ask"` or `"off"` nothing moves and no form is raised: the line names the other account to pick a model from. The turn that crossed is never changed. `false` or `0` turns it off. See [Usage before the limit](./accounts.md#usage-before-the-limit). | diff --git a/skills/claude-code-plugin/SKILL.md b/skills/claude-code-plugin/SKILL.md index 7c3f0ff..5f0fac8 100644 --- a/skills/claude-code-plugin/SKILL.md +++ b/skills/claude-code-plugin/SKILL.md @@ -188,7 +188,7 @@ Defaults below describe normal headless opencode use when the key is absent. | `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). | | `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 cwd, request scope, opencode session and agent. 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). | +| `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. | | `crossAccountResume` | boolean | `true` | On any account switch (a by-hand pick of another account's model in the same session, the switch form, and the switch back when the override expires), and only between accounts in the same `accountGroups` group, continue the same Claude conversation on the other account instead of replaying the thread as text. An account is a `CLAUDE_CONFIG_DIR` and a conversation is one `projects//.jsonl` inside it, so the switch copies that file into the target account's own projects dir (0600, dir 0700) and keeps the session id for the `--resume` both transports already build. Measured on CLI 2.1.288: a copied transcript resumes under another config dir with its context intact, the CLI resolves a session by FILENAME (not the `sessionId` in the records), it appends to the copy it found rather than to the cwd's path, the source comes out byte-identical, and no record holds a user, org or account id. Never overwrites: an older copy already at the target path (what a switch back finds) makes the carry take a fresh session id, and the live copy is the longest one. Refuses on nothing to carry, a non-file at the target path, or a failed copy, and each refusal falls back to the replay. Not on compaction, and inert with one account. Log: `carried this conversation's claude transcript to the other account` or `replaying this conversation as text on the other account` with a reason (both NOTICE). What is NOT verified live is a different Anthropic login answering another's conversation; `false` keeps the replay. | | `usageWarnThresholds` | number[] | `[50, 75, 90, 95]` | Percent levels of a usage window at which a SERVED turn ends with one `▌ **usage:**` note (its own text part, stripped from rebuilt transcripts): account, window, utilization, reset in local time. Read from every headless `rate_limit_event` (not only a rejected one), whose `utilization` is a FRACTION (`0.9` is 90%) and is ABSENT on an `allowed` event with headroom, which is unknown, never zero, and crosses nothing. The same event's `unifiedWindows` carries every window's own utilization and reset (measured on CLI 2.1.293), and each listed window is recorded, so the 7-day window has readings and notes while the 5-hour one limits. Readings persist per account per window in `$XDG_STATE_HOME/opencode-claude-code-plugin/account-usage.json` (`0600`, names, numbers and times only), and so does the dedup: each threshold is said once per account per window across reused processes, sessions and restarts, again only after the window's reset. A crossing in a `/compact` turn or a child session is not said there and is said by the next ordinary turn on the account. Never on `doGenerate`, never turns a served turn into a failure. `[]` turns the notes off but keeps the readings. The single-account name is `default`. Interactive transport: no event, so only a limit reply is recorded (`limited`). Log: `claude account usage crossed a warning threshold` (NOTICE). | | `usageSwitchAt` | number / `false` | `90` | Percent at which work leaves an account BEFORE the wall, when another `failoverCandidates` account (same `accountGroups` group) exists and is not itself at that level per the store. `accountFailover: "auto"`: sets the existing account override (keyed on the account, until the window's reset; in memory, lost on restart) so the NEXT turn spawns on the other account, carried like a limit switch; the note says `New turns move to the "" account until HH:MM`. `"ask"` / `"off"`: nothing moves and no form (the form only ends a FAILED turn); the note names the other account to pick a model from. The turn that crossed finishes as served. Also a threshold in its own right, so the switch is said exactly once per window. `false` or `0` never. Log: `claude account is near its usage limit; new turns move to another account until the window resets` (WARN). | diff --git a/src/account-transcript.ts b/src/account-transcript.ts index f8a91e4..c006af6 100644 --- a/src/account-transcript.ts +++ b/src/account-transcript.ts @@ -94,6 +94,12 @@ export interface CarryTranscriptInput { targetConfigDir: string /** Every configured account's absolute config dir, the target's included. */ accountConfigDirs: readonly string[] + /** + * Other working directories the conversation may be filed under, for a + * session opencode moved to `cwd` from one of them (h #g317). Searched in + * every config dir like `cwd`; the copy always lands under `cwd`. + */ + sourceCwds?: readonly string[] /** Test seam: the id a renamed copy takes. */ newSessionId?: () => string } @@ -129,14 +135,17 @@ export async function carryTranscriptToAccount( } let live: { file: string; size: number } | undefined + const cwds = [cwd, ...(input.sourceCwds ?? []).filter((other) => other !== cwd)] for (const dir of dedupe([targetConfigDir, ...input.accountConfigDirs])) { - const candidate = transcriptPath({ configDir: dir, cwd, sessionId }) - const stat = - candidate === targetOwn ? targetOwnStat : await statTranscript(candidate) - // A directory or a symlink where a transcript belongs is not a - // conversation this plugin wrote, so it is no candidate either. - if (stat.kind !== "file") continue - if (!live || stat.size > live.size) live = { file: candidate, size: stat.size } + for (const from of cwds) { + const candidate = transcriptPath({ configDir: dir, cwd: from, sessionId }) + const stat = + candidate === targetOwn ? targetOwnStat : await statTranscript(candidate) + // A directory or a symlink where a transcript belongs is not a + // conversation this plugin wrote, so it is no candidate either. + if (stat.kind !== "file") continue + if (!live || stat.size > live.size) live = { file: candidate, size: stat.size } + } } if (!live) return { kind: "refused", reason: "no-transcript-anywhere" } diff --git a/src/claude-code-language-model.ts b/src/claude-code-language-model.ts index 3e484e4..1fbb2cb 100644 --- a/src/claude-code-language-model.ts +++ b/src/claude-code-language-model.ts @@ -203,7 +203,7 @@ import { } from "./cli-version.js" import { interactivePermissionPosture, isReadOnlyPermissionMode } from "./permission-presets.js" import { hasInteractiveTransport, requestedTransport, selectTransport } from "./transport.js" -import { findForkParent, recordForkFingerprint } from "./session-fork.js" +import { findForkParent, recordForkFingerprint, sessionKeyCwd } from "./session-fork.js" import { findForeignAccountSibling, findResumePoint, @@ -1402,7 +1402,10 @@ export class ClaudeCodeLanguageModel implements LanguageModelV3 { const skipPermissions = this.config.skipPermissions !== false const scope = this.requestScope(options as any) const affinity = this.sessionAffinity(options) - const cwd = await resolveSpawnCwdForSession(this.config.cwd, affinity) + // `let` for one reason: a step that finishes a turn begun in the directory + // opencode has since moved this session out of is served in that one + // (h #g317, below). + let cwd = await resolveSpawnCwdForSession(this.config.cwd, affinity) const compactionMode = this.isCompactionCall(options) // What a dispatch form chose for THIS session, when it is a subagent one // chose for (h #g227). Resolved here because the model and the effort it @@ -1520,6 +1523,11 @@ export class ClaudeCodeLanguageModel implements LanguageModelV3 { const sk = compactionMode ? sessionKey(cwd, `${effectiveModelId}::compaction::${affinity}`) : (busyVariant ?? requestedKey) + // The busy key may be in the directory opencode moved this session OUT of + // mid-turn (a `session_move` from a proxied `execute`): its child is parked + // in that call there, and the rest of its turn runs there too. The next + // turn finds it idle and carries the conversation over (h #g317). + if (busyVariant) cwd = sessionKeyCwd(busyVariant) ?? cwd const toUsage = this.toUsage.bind(this) const toFinishReason = this.toFinishReason.bind(this) const handleControlRequest = this.handleControlRequest.bind(this) @@ -2535,8 +2543,10 @@ export class ClaudeCodeLanguageModel implements LanguageModelV3 { // account's on a by-hand switch (h #g226). Omitted everywhere else, so // every existing caller asks about this account's directory exactly as // it did before. - const transcriptPath = (id: string, dir?: string) => - join(dir ?? configDir, "projects", encodeCwd(cwd), `${id}.jsonl`) + // `from` is a sibling's own working directory when opencode moved the + // session out of it (h #g317). + const transcriptPath = (id: string, dir?: string, from?: string) => + join(dir ?? configDir, "projects", encodeCwd(from ?? cwd), `${id}.jsonl`) const resumePoint = findResumePoint({ sessionKey: sk, prompt: options.prompt, @@ -2588,9 +2598,18 @@ export class ClaudeCodeLanguageModel implements LanguageModelV3 { // so the FILE has to be here before `--resume` means anything // (h #g218). A refused carry falls through to the replay exactly as // the failover switch's does. + // + // A sibling in another WORKING DIRECTORY is the same kind of step + // (h #g317): opencode moved this session, and its transcript is filed + // under the old directory's encoded name. Measured on 2.1.322, a + // plain `--resume` from the new directory would find it there and + // keep appending there, where neither the restart lookup above nor + // the interactive transport's tail would ever look, so it is copied + // under this turn's directory first, as an account switch does. let carriedSessionId: string | undefined let carryRefused: string | undefined - if (sibling.siblingAccount && sibling.siblingConfigDir) { + const crossAccount = !!(sibling.siblingAccount && sibling.siblingConfigDir) + if (crossAccount || sibling.siblingCwd) { const carry = await carryTranscriptToAccount({ sessionId: sibling.claudeSessionId, cwd, @@ -2600,13 +2619,16 @@ export class ClaudeCodeLanguageModel implements LanguageModelV3 { // rewritten only when a turn succeeds), so the conventional // directories are what make a stale record recoverable rather // than a refusal. - accountConfigDirs: [ - sibling.siblingConfigDir, - ...accountsInGroupOf(sourceAccount, this.config.failoverAccounts, groups).map( - configDirForAccount, - ), - configDir, - ], + accountConfigDirs: crossAccount + ? [ + sibling.siblingConfigDir!, + ...accountsInGroupOf(sourceAccount, this.config.failoverAccounts, groups).map( + configDirForAccount, + ), + configDir, + ] + : [configDir], + ...(sibling.siblingCwd ? { sourceCwds: [sibling.siblingCwd] } : {}), }) if (carry.kind === "carried" || carry.kind === "already-there") { carriedSessionId = carry.sessionId @@ -2616,13 +2638,21 @@ export class ClaudeCodeLanguageModel implements LanguageModelV3 { } if (carryRefused) { replayReason = `sibling-${carryRefused}` - log.notice("replaying this conversation rather than carrying it across accounts", { - sessionKey: sk, - siblingKey: sibling.siblingKey, - reason: carryRefused, - account: sourceAccount, - from: sibling.siblingAccount, - }) + if (crossAccount) { + log.notice("replaying this conversation rather than carrying it across accounts", { + sessionKey: sk, + siblingKey: sibling.siblingKey, + reason: carryRefused, + account: sourceAccount, + from: sibling.siblingAccount, + }) + } else { + log.notice("replaying this conversation rather than carrying it to the session's new directory", { + sessionKey: sk, + siblingKey: sibling.siblingKey, + reason: carryRefused, + }) + } } else { // The sibling's own child, if it still has one, is holding the // transcript this turn is about to resume. It goes first, so one @@ -2641,17 +2671,25 @@ export class ClaudeCodeLanguageModel implements LanguageModelV3 { setClaudeSessionId(sk, carriedSessionId) } includeHistoryContext = false - log.notice( - "continuing this conversation's claude session under the new model or effort instead of replaying it", - { - sessionKey: sk, - siblingKey: sibling.siblingKey, - matchedMessages: sibling.matched, - ...(sibling.siblingAccount - ? { from: sibling.siblingAccount, account: sourceAccount } - : {}), - }, - ) + const carriedFields = { + sessionKey: sk, + siblingKey: sibling.siblingKey, + matchedMessages: sibling.matched, + ...(sibling.siblingAccount + ? { from: sibling.siblingAccount, account: sourceAccount } + : {}), + } + if (sibling.siblingCwd) { + log.notice( + "continuing this conversation's claude session in the session's new directory instead of replaying it", + carriedFields, + ) + } else { + log.notice( + "continuing this conversation's claude session under the new model or effort instead of replaying it", + carriedFields, + ) + } } else { replayReason = "sibling-carry-over-failed" } diff --git a/src/log-messages.ts b/src/log-messages.ts index 1c6a870..4cf30bd 100644 --- a/src/log-messages.ts +++ b/src/log-messages.ts @@ -77,6 +77,7 @@ export const PLUGIN_LOG_MESSAGES: ReadonlySet = new Set([ "cleanup-stale: could not record the sweep marker", "cleanup-stale: error processing cache root", "cleanup-stale: rmSync failed", + "continuing this conversation's claude session in the session's new directory instead of replaying it", "continuing this conversation's claude session under the new model or effort instead of replaying it", "conversation budget reached; turn not started", "conversation budget threshold crossed", @@ -171,6 +172,7 @@ export const PLUGIN_LOG_MESSAGES: ReadonlySet = new Set([ "replaying the messages this claude session missed: the conversation continued under another session key", "replaying this conversation as text on the other account", "replaying this conversation rather than carrying it across accounts", + "replaying this conversation rather than carrying it to the session's new directory", "result fallback timer fired — closing stream without result event", "resuming the claude session from before the restart instead of replaying it", "shared Claude capability already exists; leaving untouched", diff --git a/src/session-fork.ts b/src/session-fork.ts index 04e9ac2..9562960 100644 --- a/src/session-fork.ts +++ b/src/session-fork.ts @@ -420,8 +420,9 @@ export function withoutSpawnSettings(segment: string): string { * reason. A fork is a DIFFERENT opencode session continuing the same content, * so the affinity is what varies and the model must not. This is the SAME * opencode session continuing its own conversation after the operator moved - * it to another model or another effort level, so cwd, request scope, session - * affinity, provider and opencode agent all have to match and the model and + * it to another model or another effort level, so request scope, session + * affinity, provider and opencode agent all have to match (the cwd need not, + * below) and the model and * effort are exactly what may differ. Both are spawn-time choices (`--model`, * `CLAUDE_CODE_EFFORT_LEVEL`) and the CLI applies either to a transcript it * resumes, measured on 2.1.288. @@ -451,6 +452,19 @@ export function withoutSpawnSettings(segment: string): string { * Blanking is keyed on that map rather than on the shape of a provider id, so a * provider the operator named themselves is never mistaken for an account. * + * The WORKING DIRECTORY is the fourth (h #g317). opencode 2 moves a session to + * another directory (`session_move`, a worktree a lane created), the session's + * own directory is the spawn's cwd and the key's first segment, so the next + * turn landed on a key nothing had answered and replayed the thread, where a + * guard hook could refuse it by size. Measured on 2.1.322, a cwd is no reason + * for a new Claude conversation either: `--resume` from another directory + * continues it, the model reports the new directory, and only the part of the + * prompt after the environment block is written to the cache again. Like an + * account it moves a FILE (the transcript lives under the old directory's + * encoded name), so the caller carries it before resuming. The affinity is + * what makes this one conversation, so the shared `default` affinity keeps its + * directory: two `opencode run`s in two folders are not one conversation. + * * The effort tail is dropped by name rather than by position, and nothing is * truncated, so a context blob that somehow contained `::` still compares * whole. `null` for a compaction key and for anything too short to be a real @@ -468,6 +482,7 @@ export function modelSiblingSignature( : parts if (withoutEffort.length < 5) return null const blanked = [...withoutEffort] + if (blanked[3] !== "default") blanked[0] = "*" blanked[1] = "*" blanked[blanked.length - 1] = withoutSpawnSettings(blanked[blanked.length - 1]) const signature = blanked.join("::") @@ -476,6 +491,12 @@ export function modelSiblingSignature( : signature } +/** The working directory a session key was built for: its first segment. */ +export function sessionKeyCwd(sessionKey: string): string | undefined { + const end = sessionKey.indexOf("::") + return end > 0 ? sessionKey.slice(0, end) : undefined +} + /** Move what was remembered for one key onto another, for a key that is * taking over its Claude conversation (`transferClaudeSession`). */ export function moveForkFingerprint(fromKey: string, toKey: string): void { diff --git a/src/session-manager.ts b/src/session-manager.ts index b88940a..0f3db9c 100644 --- a/src/session-manager.ts +++ b/src/session-manager.ts @@ -1256,21 +1256,27 @@ function spawnHasPendingWork(key: string): boolean { } /** - * `spawnIdentity` with the model name blanked too, its `@account` marker kept: - * one opencode conversation, agent, scope, cwd and account on any model. - * Undefined for compaction keys, keys of another shape, and the shared - * `default` affinity, which is no one conversation. + * `spawnIdentity` with the model name and the working directory blanked too, + * its `@account` marker kept: one opencode conversation, agent, scope and + * account on any model, in any directory. The directory goes because opencode + * moves a session between directories mid-turn (a lane's `session_move` into + * its worktree), and the step answering the call that moved it must reach the + * child parked in that call, in the old one (h #g317). The affinity is what + * makes it one conversation. Undefined for compaction keys, keys of another + * shape, and the shared `default` affinity, which is no one conversation. */ function conversationIdentity(key: string): string | undefined { const parts = spawnIdentity(key).split("::") if (parts.length !== 5 || parts[2] === "compaction" || parts[3] === "default") return undefined + parts[0] = "*" parts[1] = parts[1].replace(/^[^@]*/, "*") return parts.join("::") } /** * Another spawn of this conversation that is still inside a turn, under - * another model, effort, prompt cache TTL or CLI cap, or `undefined`. The + * another model, effort, prompt cache TTL, CLI cap or working directory + * (h #g317), or `undefined`. The * caller serves the turn on it, so work in flight finishes under the settings * it started with and the change applies at the first turn that finds it * idle. Before this an effort or TTL change mid-turn was refused, and a model diff --git a/src/session-resume-store.ts b/src/session-resume-store.ts index 2b9285b..a004a5c 100644 --- a/src/session-resume-store.ts +++ b/src/session-resume-store.ts @@ -9,6 +9,7 @@ import { continuesRecordedConversation, conversationDigests, modelSiblingSignature, + sessionKeyCwd, type ForkMessageDigest, } from "./session-fork.js" @@ -328,8 +329,10 @@ export function findResumePoint(opts: { * this hands the id to a key that is about to spawn a child on it, and two * children appending to one transcript is not a thing to find out later, * - the match must be a sibling and not this key, so an unrelated - * conversation in another directory, scope, agent or opencode session is - * never a candidate however well its content lines up. + * conversation in another scope, agent or opencode session is never a + * candidate however well its content lines up. Another working directory + * is allowed, because opencode moves one session between directories + * (h #g317), and the caller carries the transcript across. * * The caller TRANSFERS the id rather than copying it, so one Claude * conversation is owned by exactly one session key at a time. @@ -345,6 +348,13 @@ export interface SiblingResumePoint { */ siblingAccount?: string siblingConfigDir?: string + /** + * The working directory the sibling ran in, for a sibling in ANOTHER one + * (h #g317): its transcript is under that directory's encoded name, so the + * caller carries it into this turn's before resuming. Undefined when the + * directory is this turn's own. + */ + siblingCwd?: string } export function findSiblingResumePoint(opts: { @@ -355,9 +365,10 @@ export function findSiblingResumePoint(opts: { * The transcript file a session id names. Given the sibling's own recorded * `configDir` when it has one, because a cross-account sibling's transcript * is under the OTHER account's directory and asking for this account's would - * refuse every real candidate. + * refuse every real candidate. Given the sibling's own `cwd` for the same + * reason when it ran in another working directory (h #g317). */ - transcriptPath: (claudeSessionId: string, configDir?: string) => string + transcriptPath: (claudeSessionId: string, configDir?: string, cwd?: string) => string /** `claudeSessionIsWriting`, injected so this module stays free of the * session manager. True while a key's transcript may still be written. */ isBusy: (sessionKey: string) => boolean @@ -430,7 +441,13 @@ export function findSiblingResumePoint(opts: { refusal = "sibling-still-writing" continue } - if (!existsSync(opts.transcriptPath(record.claudeSessionId, record.configDir))) { + // A sibling in another working directory wrote its transcript under that + // directory's encoded name (h #g317). + const keyCwd = sessionKeyCwd(key) + const siblingCwd = keyCwd !== undefined && keyCwd !== sessionKeyCwd(opts.sessionKey) + ? keyCwd + : undefined + if (!existsSync(opts.transcriptPath(record.claudeSessionId, record.configDir, siblingCwd))) { refusal = "sibling-transcript-gone" continue } @@ -447,6 +464,7 @@ export function findSiblingResumePoint(opts: { ...(crossAccount ? { siblingAccount, siblingConfigDir: record.configDir } : {}), + ...(siblingCwd ? { siblingCwd } : {}), } } } @@ -468,12 +486,13 @@ export function findSiblingResumePoint(opts: { * would have been refused anyway, because the thing it blocks is the REPLAY, * and the replay happens exactly when the carry does not. So nothing about * content, transcripts, binaries or busy-ness is consulted. The one test is - * the sibling signature, which already pins cwd, request scope, opencode - * session and agent, and leaves only the model, the effort, the spawn settings - * (prompt-cache TTL, `maxTurns`, `maxBudgetUsd`) and the account free. Leaving - * the spawn settings free (h #g275) only widens what this sees, which is the - * safe direction for a guard: an account in another group that answered this - * conversation under another TTL is still that group's exchange. + * the sibling signature, which already pins request scope, opencode session + * and agent, and leaves only the model, the effort, the spawn settings + * (prompt-cache TTL, `maxTurns`, `maxBudgetUsd`), the working directory and the + * account free. Leaving the spawn settings (h #g275) and the directory + * (h #g317) free only widens what this sees, which is the safe direction for a + * guard: an account in another group that answered this conversation under + * another TTL, or before the session moved, is still that group's exchange. * * `extraKeys` is the in-memory session-key set (`listClaudeSessionKeys`), so * the guard still works with `resumeAfterRestart: false`, where nothing is diff --git a/test/account-groups.test.ts b/test/account-groups.test.ts index 6c78801..6c7f549 100644 --- a/test/account-groups.test.ts +++ b/test/account-groups.test.ts @@ -199,10 +199,14 @@ test("modelSiblingSignature treats a model, an effort and an account as one conv other, ) } + // The same session in another directory is the same conversation (h #g317). + assert.equal( + modelSiblingSignature(keyFor("beta", "claude-haiku-4-5", "ses_groups", "/elsewhere"), providers), + modelSiblingSignature(alpha, providers), + ) // Everything else still has to match exactly. for (const other of [ keyFor("beta", "claude-haiku-4-5", "ses_other"), - keyFor("beta", "claude-haiku-4-5", "ses_groups", "/elsewhere"), sessionKey("/work", `claude-haiku-4-5::no-tools::ses_groups::${contextFor("claude-code-beta")}`), sessionKey( "/work", diff --git a/test/account-transcript.test.ts b/test/account-transcript.test.ts index 498fe57..10ea75f 100644 --- a/test/account-transcript.test.ts +++ b/test/account-transcript.test.ts @@ -305,3 +305,59 @@ test("a copy that cannot be made is a refusal, not a throw", async () => { s.cleanup() } }) + +// A session opencode moved to another working directory (h #g317): same +// config dir, the transcript filed under the old directory's encoded name. +test("a moved session's transcript is copied from the old directory into the new one", async () => { + const s = scratch() + try { + const oldCwd = join(s.root, "before-move") + mkdirSync(oldCwd) + const old = interactiveTranscriptPath({ configDir: s.target, cwd: oldCwd, sessionId: SESSION }) + mkdirSync(dirname(old), { recursive: true }) + writeFileSync(old, '{"type":"user"}\n{"type":"assistant"}\n') + + // Without the old directory named, there is nothing to carry. + const blind = await carryTranscriptToAccount({ + sessionId: SESSION, + cwd: s.cwd, + targetConfigDir: s.target, + accountConfigDirs: [s.target], + }) + assert.deepEqual(blind, { kind: "refused", reason: "no-transcript-anywhere" }) + + const carry = await carryTranscriptToAccount({ + sessionId: SESSION, + cwd: s.cwd, + targetConfigDir: s.target, + accountConfigDirs: [s.target], + sourceCwds: [oldCwd], + }) + assert.equal(carry.kind, "carried") + if (carry.kind !== "carried") return + assert.equal(carry.from, old) + assert.equal(carry.to, s.path(s.target), "under the new directory's own name") + assert.equal(carry.sessionId, SESSION) + assert.equal(readFileSync(carry.to, "utf8"), readFileSync(old, "utf8")) + if (process.platform !== "win32") assert.equal(statSync(carry.to).mode & 0o777, 0o600) + + // Moving back finds the longer copy where the session now lives, so the + // stale original is never what is resumed. + writeFileSync(carry.to, readFileSync(carry.to, "utf8") + '{"type":"user"}\n') + const back = await carryTranscriptToAccount({ + sessionId: SESSION, + cwd: oldCwd, + targetConfigDir: s.target, + accountConfigDirs: [s.target], + sourceCwds: [s.cwd], + newSessionId: () => "renamed-after-move", + }) + assert.equal(back.kind, "carried") + if (back.kind !== "carried") return + assert.equal(back.from, carry.to) + assert.equal(back.renamed, true, "the stale original is never overwritten") + assert.equal(back.sessionId, "renamed-after-move") + } finally { + s.cleanup() + } +}) diff --git a/test/effort-sessions.test.ts b/test/effort-sessions.test.ts index af87d44..a64ed60 100644 --- a/test/effort-sessions.test.ts +++ b/test/effort-sessions.test.ts @@ -599,9 +599,12 @@ test("effort changes leave other agent, provider, account, model and conversatio const key = effortSessionKey(other, "high") const fake = fakeActive() // A busy child on another model of this same conversation would take the - // turn instead (h #g271), so that one is idle here. It must survive the - // effort change all the same. - if (!other.includes("::claude-opus-5::")) fake.active.lineEmitter.on("line", () => {}) + // turn instead (h #g271), and so would one in the directory opencode moved + // this session out of (h #g317), so those two are idle here. They must + // survive the effort change all the same. + if (!other.includes("::claude-opus-5::") && !other.startsWith(`${cwd}/other::`)) { + fake.active.lineEmitter.on("line", () => {}) + } setActiveProcess(key, fake.active) setClaudeSessionId(key, "untouched") return { key, ...fake } @@ -630,6 +633,44 @@ test("effort changes leave other agent, provider, account, model and conversatio } }) +test("doStream: a step after opencode moved the session mid-turn finishes on the old directory's child (h #g317)", { timeout: 60_000 }, async () => { + // A lane's Code Mode `execute` moved its session into a worktree, so the + // step carrying that call's result arrives for the new directory while the + // child that made the call is parked in it, in the old one. + const { cwd, modelId, provider, base, options } = fixture() + const oldDir = `${cwd}-before-move` + const parked = base.replace(cwd, oldDir) + const first = scriptedActive() + setActiveProcess(parked, first.active) + setClaudeSessionId(parked, "pending-before-move") + const id = "pending-session-move" + let answer!: (result: unknown) => void + const answered = new Promise((resolve) => { answer = resolve }) + queuePendingProxyCall(parked, { + id, toolName: "execute", input: {}, channel: { closed: false }, + resolve(result) { answer(result) }, reject() {}, + }) + markPendingProxyCallEmitted(id) + options.prompt.push( + { role: "assistant", content: [{ type: "tool-call", toolCallId: id, toolName: "execute", input: {} }] }, + { role: "tool", content: [{ type: "tool-result", toolCallId: id, toolName: "execute", output: { type: "text", value: "moved" } }] }, + ) + try { + await answerParkedCall(() => provider.languageModel(modelId).doStream(options), first.active, answered) + assert.equal(first.killed(), false) + assert.equal(getActiveProcess(parked), first.active) + assert.equal(getActiveProcess(base), undefined, "no child spawned in the new directory mid-turn") + assert.equal(getClaudeSessionId(base), undefined, "the conversation stays with the parked child") + } finally { + resolvePendingProxyCallById(id, { kind: "text", text: "cleanup" }) + deleteActiveProcess(parked) + deleteClaudeSessionId(parked) + await deleteActiveProcessAndWait(base) + deleteClaudeSessionId(base) + rmSync(cwd, { recursive: true, force: true }) + } +}) + test("doStream: a model change mid-turn finishes that turn on the old model's child (h #g271)", { timeout: 60_000 }, async () => { const { cwd, modelId, provider, base, options } = fixture() const otherModel = base.replace(`::${modelId}::`, "::claude-sonnet-4-5::") diff --git a/test/session-model-switch.test.ts b/test/session-model-switch.test.ts index 19efda8..54540b5 100644 --- a/test/session-model-switch.test.ts +++ b/test/session-model-switch.test.ts @@ -92,11 +92,22 @@ test("modelSiblingSignature blanks the model and drops the effort tail, and noth ) } + // The same opencode session after opencode moved it to another directory is + // the same conversation (h #g317); the shared `default` affinity is not one + // conversation, so it keeps its directory. + assert.equal( + modelSiblingSignature(sessionKey("/elsewhere", `claude-haiku-4-5::tools::ses_switch::${CONTEXT}`)), + modelSiblingSignature(haiku), + ) + assert.notEqual( + modelSiblingSignature(sessionKey("/elsewhere", `claude-haiku-4-5::tools::default::${CONTEXT}`)), + modelSiblingSignature(sessionKey("/work", `claude-haiku-4-5::tools::default::${CONTEXT}`)), + ) + // Everything else still has to match, which is what keeps an unrelated // conversation out however well its content lines up. for (const other of [ keyFor("claude-haiku-4-5", "ses_other"), - sessionKey("/elsewhere", `claude-haiku-4-5::tools::ses_switch::${CONTEXT}`), sessionKey("/work", `claude-haiku-4-5::no-tools::ses_switch::${CONTEXT}`), sessionKey("/work", `claude-haiku-4-5::tools::ses_switch::context=["claude-code","worker"]`), // The agent is not a spawn setting, with or without one beside it. @@ -124,7 +135,7 @@ function scratchStore(): { dir: string; transcript: (id: string) => string } { function findSibling( key: string, prompt: any, - transcript: (id: string) => string, + transcript: (id: string, dir?: string, from?: string) => string, overrides: { cliPath?: string; isBusy?: (key: string) => boolean } = {}, ) { return findSiblingResumePoint({ @@ -187,10 +198,21 @@ test("every refusal falls back to the replay", () => { "a busy sibling", ) - // Never another opencode session, directory, scope or agent. + // Never another opencode session, scope or agent. Another directory is the + // same session moved (h #g317): found, named, and its transcript is looked + // for under the directory it ran in. + const moved = sessionKey("/elsewhere", `claude-sonnet-4-5::tools::ses_switch::${CONTEXT}`) + const asked: (string | undefined)[] = [] + const found = findSibling(moved, AFTER, (id, dir, from) => { + asked.push(from) + return transcript(id) + }) + assert.equal(found?.siblingKey, sibling) + assert.equal(found?.siblingCwd, "/work") + assert.deepEqual(asked, ["/work"]) + assert.equal(findSibling(current, AFTER, transcript)?.siblingCwd, undefined, "same directory") for (const foreign of [ keyFor("claude-sonnet-4-5", "ses_other"), - sessionKey("/elsewhere", `claude-sonnet-4-5::tools::ses_switch::${CONTEXT}`), sessionKey("/work", `claude-sonnet-4-5::no-tools::ses_switch::${CONTEXT}`), ]) { assert.equal(findSibling(foreign, AFTER, transcript), undefined, foreign) diff --git a/test/session-move.test.ts b/test/session-move.test.ts new file mode 100644 index 0000000..a1ce4f1 --- /dev/null +++ b/test/session-move.test.ts @@ -0,0 +1,268 @@ +/** + * A session opencode moved to another working directory (h #g317). + * + * opencode 2 moves one session between directories (`session_move`, a lane's + * worktree), and the session's directory is the spawn's cwd and the first + * segment of its session key. Before this the next turn landed on a key + * nothing had answered and replayed the whole thread as text. These drive real + * `doStream` turns through a fake CLI, with two providers pinned to directory A + * and directory B standing in for the move: same opencode session, same model, + * same agent, another directory. + * + * The fake resumes a session only from a transcript filed under ITS OWN + * directory's encoded name. The real CLI (2.1.322) also finds one filed under + * another directory, but then keeps appending there, where neither the + * restart lookup nor the interactive transport looks; refusing it here is what + * proves the plugin copied the file across before resuming. + * + * POSIX only, like the other fake-CLI files. + */ +import "./isolate.js" +import assert from "node:assert/strict" +import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { test } from "node:test" +import type { LanguageModelV3CallOptions } from "@ai-sdk/provider" + +import { encodeCwd } from "../src/claude-session-bun.js" +import { detectCliVersion } from "../src/cli-version.js" +import { createClaudeCode } from "../src/index.js" +import { _setResumeStorePath, resumeStorePath } from "../src/session-resume-store.js" +import { + deleteActiveProcessAndWait, + deleteClaudeSessionId, + getActiveProcess, + getClaudeSessionId, + releaseIdleForHandover, + sessionKey, +} from "../src/session-manager.js" + +const POSIX = { skip: process.platform === "win32" ? "fake CLI is a POSIX script" : false } + +const MODEL = "claude-test-session-move" +const SESSION = "claude-before-move" +const userText = (text: string) => ({ role: "user", content: [{ type: "text", text }] }) as any +const assistantText = (text: string) => ({ role: "assistant", content: [{ type: "text", text }] }) as any + +const BEFORE = [ + { role: "system", content: "You are a helpful assistant." }, + userText("The project codename is OSPREY. Reply OK."), +] as any +const AFTER = [...BEFORE, assistantText("OSPREY"), userText("What is the codename?")] as any + +function createMoveCli(opts: { resumeAfterRestart?: boolean } = {}) { + const root = realpathSync(mkdtempSync(join(tmpdir(), "opencode-session-move-"))) + const dirA = join(root, "main") + const dirB = join(root, "worktree") + mkdirSync(dirA) + mkdirSync(dirB) + const configDir = join(root, "claude-config") + const cliPath = join(root, "fake-claude.cjs") + const eventsPath = join(root, "events.jsonl") + writeFileSync(eventsPath, "") + writeFileSync( + cliPath, + `#!${process.execPath} +const fs = require("node:fs") +const path = require("node:path") +const readline = require("node:readline") +const args = process.argv.slice(2) +const record = (event) => fs.appendFileSync(${JSON.stringify(eventsPath)}, JSON.stringify(event) + "\\n") +const emit = (message) => process.stdout.write(JSON.stringify(message) + "\\n") +if (args.includes("--version")) { process.stdout.write("2.1.322\\n"); process.exit(0) } +if (args.includes("--help")) { process.stdout.write("\\n"); process.exit(0) } +const cwd = fs.realpathSync.native(process.cwd()) +const transcript = (id) => + path.join(${JSON.stringify(configDir)}, "projects", cwd.replace(/[^A-Za-z0-9]/g, "-"), id + ".jsonl") +const at = args.indexOf("--resume") +const sessionId = at >= 0 ? args[at + 1] : ${JSON.stringify(SESSION)} +record({ type: "spawn", args, cwd, sessionId }) +if (at >= 0 && !fs.existsSync(transcript(sessionId))) { + emit({ type: "result", subtype: "error_during_execution", is_error: true, session_id: sessionId, + result: "No conversation found with session ID: " + sessionId }) + process.exit(1) +} +emit({ type: "system", subtype: "init", session_id: sessionId }) +readline.createInterface({ input: process.stdin }).on("line", (line) => { + const envelope = JSON.parse(line) + if (envelope.type !== "user") return + record({ type: "input", sessionId, cwd, envelope }) + fs.mkdirSync(path.dirname(transcript(sessionId)), { recursive: true }) + fs.appendFileSync(transcript(sessionId), JSON.stringify({ type: "user", cwd }) + "\\n") + emit({ type: "assistant", session_id: sessionId, message: { role: "assistant", stop_reason: "end_turn", content: [{ type: "text", text: "OSPREY" }] } }) + emit({ type: "result", subtype: "success", session_id: sessionId, is_error: false, usage: { input_tokens: 9, output_tokens: 4 } }) +}) +`, + { mode: 0o755 }, + ) + _setResumeStorePath(join(root, "state", "claude-sessions.json")) + + const providerFor = (cwd: string) => + createClaudeCode({ + cliPath, + cwd, + configDir, + bridgeOpencodeMcp: false, + proxyOpencodeMcpTools: false, + proxyTools: [], + interactive: false, + autoContinueIncompleteTurns: false, + liveModelSwitch: false, + ...(opts.resumeAfterRestart === false ? { resumeAfterRestart: false } : {}), + } as any) + const providers = { [dirA]: providerFor(dirA), [dirB]: providerFor(dirB) } + const key = (cwd: string, affinity = "ses_moved") => + sessionKey(cwd, `${MODEL}::tools::${affinity}::context=["claude-code",null]`) + const transcriptIn = (cwd: string, id = SESSION) => + join(configDir, "projects", encodeCwd(cwd), `${id}.jsonl`) + const events = () => + readFileSync(eventsPath, "utf8").trim().split("\n").filter(Boolean).map((line) => JSON.parse(line) as any) + + return { + dirA, + dirB, + key, + transcriptIn, + spawns: () => events().filter((event) => event.type === "spawn"), + inputs: () => events().filter((event) => event.type === "input"), + records: (): Record => { + try { + return JSON.parse(readFileSync(resumeStorePath(), "utf8")).sessions ?? {} + } catch { + return {} + } + }, + async turn(cwd: string, prompt: any[], affinity = "ses_moved") { + const call: LanguageModelV3CallOptions = { + prompt, + headers: { "x-session-affinity": affinity }, + tools: [{ type: "function", name: "read", inputSchema: { type: "object", properties: {} } }], + abortSignal: AbortSignal.timeout(30_000), + } as any + const response = await providers[cwd].languageModel(MODEL).doStream(call) + for await (const part of response.stream) { + if (part.type === "error") throw (part as any).error + } + }, + async warm() { + for (let attempt = 1; attempt <= 4; attempt++) { + if (await detectCliVersion(cliPath)) return + } + throw new Error("the fake CLI never answered --version") + }, + async cleanup() { + for (const cwd of [dirA, dirB]) { + for (const affinity of ["ses_moved", "ses_other", "default"]) { + await deleteActiveProcessAndWait(key(cwd, affinity)) + deleteClaudeSessionId(key(cwd, affinity)) + } + } + _setResumeStorePath(null) + rmSync(root, { recursive: true, force: true }) + }, + } +} + +const resumedId = (args: string[]) => { + const at = args.indexOf("--resume") + return at >= 0 ? args[at + 1] : undefined +} + +const owners = (records: Record) => + Object.entries(records) + .filter(([, record]) => record.claudeSessionId === SESSION) + .map(([k]) => k) + +test("a session opencode moved to another directory continues its claude session there", { + ...POSIX, + timeout: 60_000, +}, async () => { + const fake = createMoveCli() + try { + await fake.warm() + await fake.turn(fake.dirA, [...BEFORE]) + const original = readFileSync(fake.transcriptIn(fake.dirA), "utf8") + assert.ok(original.length > 0) + + await fake.turn(fake.dirB, [...AFTER]) + + const spawns = fake.spawns() + assert.equal(spawns.length, 2) + assert.equal(spawns[1].cwd, fake.dirB, "the next child runs in the new directory") + assert.equal(resumedId(spawns[1].args), SESSION, JSON.stringify(spawns[1].args)) + const sent = JSON.stringify(fake.inputs().at(-1)?.envelope) + assert.ok(!sent.includes("conversation_history"), sent.slice(0, 400)) + assert.ok(sent.includes("What is the codename?")) + + // A copy under the new directory's name, appended to there; the original + // is left exactly as it was. + assert.equal(readFileSync(fake.transcriptIn(fake.dirA), "utf8"), original) + const moved = readFileSync(fake.transcriptIn(fake.dirB), "utf8") + assert.ok(moved.startsWith(original)) + assert.ok(moved.length > original.length) + + // One owner: the old directory's child is gone and its key keeps no claim. + assert.equal(getActiveProcess(fake.key(fake.dirA)), undefined) + assert.equal(getClaudeSessionId(fake.key(fake.dirA)), undefined) + assert.equal(getClaudeSessionId(fake.key(fake.dirB)), SESSION) + assert.deepEqual(owners(fake.records()), [fake.key(fake.dirB)]) + } finally { + await fake.cleanup() + } +}) + +test("the move is carried after an opencode restart too", { ...POSIX, timeout: 60_000 }, async () => { + const fake = createMoveCli() + try { + await fake.warm() + await fake.turn(fake.dirA, [...BEFORE]) + await releaseIdleForHandover() + assert.equal(getClaudeSessionId(fake.key(fake.dirA)), undefined, "nothing survives in memory") + + await fake.turn(fake.dirB, [...AFTER]) + + const spawns = fake.spawns() + assert.equal(spawns.at(-1).cwd, fake.dirB) + assert.equal(resumedId(spawns.at(-1).args), SESSION) + assert.ok(!JSON.stringify(fake.inputs().at(-1)?.envelope).includes("conversation_history")) + assert.ok(existsSync(fake.transcriptIn(fake.dirB))) + assert.deepEqual(owners(fake.records()), [fake.key(fake.dirB)]) + } finally { + await fake.cleanup() + } +}) + +test("another opencode session in another directory is never carried", { ...POSIX, timeout: 60_000 }, async () => { + const fake = createMoveCli() + try { + await fake.warm() + await fake.turn(fake.dirA, [...BEFORE]) + await fake.turn(fake.dirB, [...AFTER], "ses_other") + + const last = fake.spawns().at(-1) + assert.equal(resumedId(last.args), undefined, JSON.stringify(last.args)) + assert.ok(JSON.stringify(fake.inputs().at(-1)?.envelope).includes("conversation_history")) + assert.equal(getClaudeSessionId(fake.key(fake.dirA)), SESSION, "the other session keeps its own") + assert.ok(getActiveProcess(fake.key(fake.dirA)), "and its child") + } finally { + await fake.cleanup() + } +}) + +test("with resumeAfterRestart off the move still replays, as a model change does", { + ...POSIX, + timeout: 60_000, +}, async () => { + const fake = createMoveCli({ resumeAfterRestart: false }) + try { + await fake.warm() + await fake.turn(fake.dirA, [...BEFORE]) + await fake.turn(fake.dirB, [...AFTER]) + const last = fake.spawns().at(-1) + assert.equal(resumedId(last.args), undefined) + assert.ok(JSON.stringify(fake.inputs().at(-1)?.envelope).includes("conversation_history")) + } finally { + await fake.cleanup() + } +})