Skip to content

fix(daemon): only resume Claude turn when a real transcript exists - #22

Merged
jasonkneen merged 1 commit into
mainfrom
polly/claude-resume-transcript-guard
Jul 15, 2026
Merged

jasonkneen merged 1 commit into
mainfrom
polly/claude-resume-transcript-guard

Conversation

@jasonkneen

@jasonkneen jasonkneen commented Jun 16, 2026 •

Copy link
Copy Markdown
Owner

Problem (proven from on-disk evidence)

In packages/codesurf-daemon/bin/chat-jobs.mjs, runClaudeJob set the Claude Agent SDK resume option unconditionally from request.sessionId with no check that the id refers to a real, resumable Claude session.

When a card switches provider (e.g. 6 codex/gpt-5.5 turns then a claude turn), the daemon is handed a codex-format UUIDv7 thread id (e.g. 019ecd2c-…-7580-…). The Claude SDK tries to resume a session with no transcript on disk and returns num_turns:0, cost:0, zero assistant content — the user sees an empty reply.

Fix — defense-in-depth guard

findClaudeResumeTranscript(sessionId) confirms a real transcript exists before resume is set. Only then does runClaudeJob pass resume: request.sessionId; otherwise it omits resume and starts a fresh turn so the model runs normally (and logs a warn).

Confirmed transcript path layout (from installed @anthropic-ai/claude-agent-sdk)

<CLAUDE_CONFIG_DIR | ~/.claude>/projects/<encoded-cwd>/<sessionId>.jsonl   (size > 0)

where <encoded-cwd> = realpath(cwd) → NFC-normalized → replace(/[^a-zA-Z0-9]/g, '-') (paths > 200 chars get a hash suffix).

The guard scans every project dir for <sessionId>.jsonl instead of reconstructing the encoded key — this deliberately sidesteps the SDK's realpath + NFC + hash-suffix encoding (replicating it is the brittle part). A foreign/stale id has no transcript anywhere → returns null → fresh start. A valid same-provider Claude id always has its transcript on disk → resume preserved unchanged. Includes a path-traversal guard on the id and the SDK's own size > 0 check.

Test

test/daemon/chat-jobs-claude-resume-guard.test.mjs (drives runClaudeJob via injected claudeQuery, sets CLAUDE_CONFIG_DIR to a temp dir):

  • no transcript (codex-style UUIDv7) → options.resume === undefined, turn still runs, job completes.
  • transcript present → options.resume === sessionId.

Gates

  • node --test test/daemon/chat-jobs-claude-resume-guard.test.mjs → 2/2 pass
  • npm run test:daemon → 220 pass / 3 fail. All 3 failures pre-existing and unrelated: two assert an outdated error string (…OpenCode, and Hermes) the recent Omnigent provider work changed to …Hermes, and Omnigent; one is a renderer ChatTileComposer pills test.
  • npm run typecheck → 16 errors, all pre-existing baseline, none in the changed file (chat-jobs.mjs is .mjs, outside the tsc program).

Scope: 2 files, +188/-3.

Summary by CodeRabbit

  • Bug Fixes

    • The daemon now validates chat session integrity before attempting to resume, preventing errors from stale or invalid session identifiers.
  • Tests

    • Added test coverage for the new session validation guard behavior.

Defense-in-depth guard in runClaudeJob. Previously the SDK `resume`
option was set unconditionally from request.sessionId. When a card
switches provider (e.g. codex/gpt-5.5 turns then a claude turn), the
daemon was handed a foreign codex-format UUIDv7 thread id with no
Claude transcript on disk. The Claude Agent SDK then returned
num_turns:0 with zero assistant content — the user saw an empty reply.

Now findClaudeResumeTranscript() scans
<CLAUDE_CONFIG_DIR|~/.claude>/projects/*/<sessionId>.jsonl for a
non-empty transcript before setting `resume`. Scan-all (rather than
reconstructing the encoded-cwd project key) sidesteps the SDK's
realpath + NFC + 200-char hash-suffix encoding. Foreign/stale ids match
nothing → start fresh so the model runs normally; valid same-provider
Claude ids keep resuming unchanged. Also covers the symmetric case (a
Claude id handed to a codex/omnigent resume path elsewhere).

Adds regression test: a sessionId with no transcript must NOT pass
`resume` (and still runs the turn); one with a transcript must pass it.
Copilot AI review requested due to automatic review settings June 16, 2026 02:00
@coderabbitai

coderabbitai Bot commented Jun 16, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Adds a findClaudeResumeTranscript helper in the daemon that scans the Claude SDK projects directory for a non-empty <sessionId>.jsonl file before passing the resume option to the Claude SDK. If no such transcript exists, runClaudeJob logs a warning and omits the resume option. Two new tests cover both the missing and present transcript paths.

Changes

Claude Resume Guard

Layer / File(s) Summary
Transcript scanner and resume wiring
packages/codesurf-daemon/bin/chat-jobs.mjs
Adds existsSync to the node:fs import, introduces findClaudeResumeTranscript(sessionId) that iterates project subdirectories for a non-empty JSONL transcript, derives willResume in runClaudeJob with a console warning when no transcript is found, and changes the SDK resume option to use willResume instead of the raw sessionId.
Resume guard tests
test/daemon/chat-jobs-claude-resume-guard.test.mjs
New test file with temp-dir and polling helpers, a runClaudeTurn fixture that captures options.resume from an injected claudeQuery, and two tests: one verifying resume is undefined when no transcript exists, and one verifying resume equals the sessionId when a non-empty transcript is present.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

  • jasonkneen/codesurf#9: Modifies the same runClaudeJob Claude execution path in chat-jobs.mjs, including the options.resume wiring that this PR now gates behind the transcript-existence check.

Poem

🐇 Hop, hop — no ghost sessions allowed!
Before resuming, I sniff the .jsonl ground,
If no transcript lives in the projects tree,
I skip the resume key and run fresh and free.
Stale IDs beware: the guard hops proud! 🌿

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title directly summarizes the main change: preventing Claude Agent SDK session resumption with stale/foreign sessionIds by adding a transcript-existence check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch polly/claude-resume-transcript-guard

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR hardens the daemon’s Claude job execution to avoid attempting to resume Claude sessions when the provided sessionId doesn’t correspond to a real on-disk Claude transcript (e.g., after switching providers and receiving a non-Claude thread id). This prevents “empty reply” turns caused by the Claude Agent SDK resuming a session with zero turns.

Changes:

  • Add a transcript-existence guard (findClaudeResumeTranscript) and only set the Claude SDK resume option when a real transcript file exists.
  • Emit a warning and start a fresh Claude turn when the sessionId is foreign/stale.
  • Add a node test covering both “missing transcript” and “transcript present” cases by injecting claudeQuery.

Reviewed changes

Copilot reviewed 1 out of 2 changed files in this pull request and generated 1 comment.

File Description
packages/codesurf-daemon/bin/chat-jobs.mjs Adds transcript-based resume guard and updates Claude job options to only resume when a transcript exists.
test/daemon/chat-jobs-claude-resume-guard.test.mjs Adds regression tests validating resume is omitted for foreign ids and preserved for valid Claude transcripts.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@@ -0,0 +1,126 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises'

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
test/daemon/chat-jobs-claude-resume-guard.test.mjs (1)

26-32: 💤 Low value

Test helper should also wait for 'queued' status.

The daemon can start jobs in 'queued' status when concurrency slots are full. The current check only waits while status === 'running', so a queued job would be treated as complete. This doesn't affect current tests (single job, 4 slots), but would cause flaky failures if tests ever run concurrent jobs.

♻️ Suggested fix
 async function waitForCompletedJob(manager, jobId) {
   return await waitFor(async () => {
     const state = await manager.getJobState(jobId)
-    if (!state || state.status === 'running') return null
+    if (!state || state.status === 'running' || state.status === 'queued') return null
     return state
   })
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@test/daemon/chat-jobs-claude-resume-guard.test.mjs` around lines 26 - 32, The
waitForCompletedJob helper function only waits while status === 'running', but
jobs can also be in 'queued' status when concurrency slots are full. Modify the
condition in the waitFor callback to also check for 'queued' status, so the
function returns null (continues waiting) for both 'running' and 'queued'
statuses instead of treating queued jobs as complete.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@test/daemon/chat-jobs-claude-resume-guard.test.mjs`:
- Around line 26-32: The waitForCompletedJob helper function only waits while
status === 'running', but jobs can also be in 'queued' status when concurrency
slots are full. Modify the condition in the waitFor callback to also check for
'queued' status, so the function returns null (continues waiting) for both
'running' and 'queued' statuses instead of treating queued jobs as complete.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 801583e4-0fe4-4868-b76c-67900e9c2b0f

📥 Commits

Reviewing files that changed from the base of the PR and between 00df0c2 and b7fbe3f.

📒 Files selected for processing (2)
  • packages/codesurf-daemon/bin/chat-jobs.mjs
  • test/daemon/chat-jobs-claude-resume-guard.test.mjs

@jasonkneen
jasonkneen merged commit 8f441e1 into main Jul 15, 2026
1 of 2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants