fix(server): auto-settle on merge waits for a pending Claude wake turn #26108
Problem#
With sidebarAutoSettleOnMerge on, a Claude thread whose linked pull request has merged is settled the moment an awaited background task finishes: the empty task list triggers a settlement sweep, thread.auto-settle settles the thread, and settling detaches and closes the Claude session before Claude's wake turn attaches. The agent never runs its post-merge steps. Reproduced with real Claude 2.1.304: background sleep + t3_background_wait on a thread linked to a merged PR, then end the turn (transcripts below).
Change#
- The provider session runtime gets an optional
hasPendingWakeForThreadprobe. Only the Claude adapter implements it: true while a finished background task is waiting for its wake turn, i.e. a wake-eligible task has left the roster or itstask_notificationis buffered, from whichever came first until the wake run claims the buffer, the task is stopped, or the query is replaced. It expires after the adapter's existingCLAUDE_WAKE_TURN_START_DEADLINE(2 minutes), and each new wake gets its own window. A task still on the roster (a dev server) never counts. - The
thread.auto-settledecider asks each live session of the thread and refuses while a wake is pending, the same way it already refuses when the thread changed. When the wake run completes, the existingrun.updatedsweep settles the thread; a probe that fails lets the thread settle. hasPendingBackgroundWorkForThread, manual settle, other providers, and the settlement service are unchanged, so threads running only a dev server still auto-settle on merge (Claude and Codex).
Scope and approval#
Fixes pingdotgg/t3code#26083
Verification#
Focused tests, each confirmed to fail before its fix:
ClaudeAdapterV2.test.ts: a pending wake is reported once the buffered notification arrives (with and without a dev server on the roster), once the finished task leaves the roster before its notification, stops after 2 minutes when no wake turn opens, and a later wake gets its own deadline.BackgroundWorkStop.integration.test.ts(real Orchestrator and effect worker): auto-settle waits for a pending wake turn (empty roster, and beside a dev server); settles a thread running only a dev server; settles when the wake probe fails.ClaudeAdapterV2,BackgroundWorkStop.integration,ThreadSettlementService,ProviderSessionManager,RunExecutionService,ClaudeAutomaticDelivery.integration,ClaudeReplayFixtures.integration: 425/425 passed.vp run check:changedpasses.
Runtime transcript, real T3 server per side on a fresh database (T3CODE_DEV_SEED=0), Claude CLI 2.1.304, claude-sonnet-4-6, the same driver both sides, 3 runs each. Before = bc1ea26cc0 (main), after = 27b71881c7 (this branch before its last commit, which only gives successive wakes their own deadline). The linked PR is a real merged PR (https://git.cafe/pingdotgg/t3code/pulls/26057) resolved through PullRequestService; because it merged before the fresh thread existed, the driver moved the thread link's cached mergedAt after thread creation through RPC (settlement only honours merges after the user's last message). Times UTC, 2026-10-27:
| Before (main) | |
|---|---|
19:51:20.221 | background task completes (exit 0) |
19:51:20.242 | thread settled, session detached: "Thread settled." |
| +20 s | no wake run, no DONE; one completed run |
| After (this branch) | |
|---|---|
19:51:21.608 | background task completes (exit 0) |
19:51:21.652 | automatic thread settlement skipped: "… is waiting for a provider wake turn." |
19:51:21.777 | wake run starts |
19:51:22.525 | assistant replies DONE |
19:51:22.577 | wake run completes |
19:51:23.005 | thread settled, session detached; two completed runs |
Driver script (synthetic data; not committed)
import fs from 'node:fs';
import path from 'node:path';
import {createRequire} from 'node:module';
import {pathToFileURL} from 'node:url';
import {spawn,execFileSync} from 'node:child_process';
import http from 'node:http';
import {randomUUID as uuid} from 'node:crypto';
const [side, root, runNumber='1'] = process.argv.slice(2);
if (!['before','after'].includes(side) || !root) throw Error('usage: node driver.mjs before|after CHECKOUT [RUN]');
const dir = `/tmp/issue-lead-26083-r1/capture/${new Date().toISOString().replaceAll(/[:.]/g,'-')}-${side}-${runNumber}`;
fs.mkdirSync(dir,{recursive:true});
const require = createRequire(path.join(root,'apps/server/package.json'));
const imp = name => import(pathToFileURL(require.resolve(name)).href);
const [Effect,Layer,Stream,{Socket},{RpcClient,RpcSerialization},contracts] = await Promise.all([
imp('effect/Effect'),imp('effect/Layer'),imp('effect/Stream'),imp('effect/socket'),imp('effect/rpc'),import(pathToFileURL(path.join(root,'packages/contracts/src/index.ts')).href)
]);
const {WsRpcGroup,ORCHESTRATION_PROTOCOL_VERSION,ORCHESTRATION_PROTOCOL_HEADER}=contracts;
const transcript=path.join(dir,'transcript.txt');
function log(kind,data) {const line=`${new Date().toISOString()} ${kind} ${typeof data==='string'?data:JSON.stringify(data)}\n`;fs.appendFileSync(transcript,line);process.stdout.write(line);}
log('COMMANDS',{checkout:root,revision:execFileSync('git',['rev-parse','HEAD'],{cwd:root,encoding:'utf8'}).trim(),install:'vp install',server:'T3CODE_DEV_SEED=0 node apps/server/src/bin.ts --bootstrap-fd 3 --log-level debug',driver:`node driver.mjs ${side} ${root} ${runNumber}`,home:path.join(dir,'home'),cli:execFileSync('claude',['--version'],{encoding:'utf8'}).trim()});
const project=path.join(dir,'project');fs.mkdirSync(project);
execFileSync('git',['init','-q',project]);execFileSync('git',['-C',project,'-c','user.name=Capture','-c','user.email=capture@localhost','commit','--allow-empty','-qm','Synthetic capture']);
execFileSync('git',['-C',project,'remote','add','origin','https://github.com/pingdotgg/t3code.git']);
const reservation=http.createServer();await new Promise(r=>reservation.listen(0,'127.0.0.1',r));const port=reservation.address().port;await new Promise(r=>reservation.close(r));
const origin=`http://127.0.0.1:${port}`;const bootstrap=uuid();
const env={...process.env,T3CODE_DEV_SEED:'0',T3CODE_HOME:path.join(dir,'home'),T3CODE_TELEMETRY_ENABLED:'false'};
delete env.T3_SERVICE_LAUNCHER_CONTEXT;delete env.T3_BOOT_SERVICE_UNIT;delete env.VITE_HTTP_URL;delete env.VITE_WS_URL;
const server=spawn(process.execPath,['apps/server/src/bin.ts','--bootstrap-fd','3','--log-level','debug'],{cwd:root,env,detached:true,stdio:['ignore','pipe','pipe','pipe']});
fs.writeFileSync(path.join(dir,'server.pid'),String(server.pid));log('SERVER_SPAWN',{pid:server.pid,port});
server.stdio[3].end(JSON.stringify({mode:'desktop',noBrowser:true,port,t3Home:path.join(dir,'home'),host:'127.0.0.1',desktopBootstrapToken:bootstrap,tailscaleServeEnabled:false,tailscaleServePort:443}));
const ready=Promise.withResolvers();let startup='';
for(const pipe of [server.stdout,server.stderr])pipe.on('data',data=>{const s=data.toString().replaceAll(bootstrap,'[REDACTED]');fs.appendFileSync(path.join(dir,'server.log'),s);startup=(startup+s).slice(-20000);if(startup.includes('startup phase: complete'))ready.resolve();});
server.once('exit',code=>ready.reject(Error(`Server exited ${code}`)));
const startupTimer=setTimeout(()=>ready.reject(Error('startup deadline')),90000);
let markerWatcher;let verdict={status:'incomplete'};const abort=new AbortController();
const onSignal=()=>abort.abort();process.on('SIGTERM',onSignal);process.on('SIGINT',onSignal);
try {
await ready.promise;clearTimeout(startupTimer);log('SERVER_READY',{port,freshDatabase:true});
const tokenResponse=await fetch(`${origin}/oauth/token`,{method:'POST',body:new URLSearchParams({grant_type:'urn:ietf:params:oauth:grant-type:token-exchange',subject_token:bootstrap,subject_token_type:'urn:t3:params:oauth:token-type:environment-bootstrap',requested_token_type:'urn:ietf:params:oauth:token-type:access_token'})});
if(!tokenResponse.ok)throw Error(`Auth ${tokenResponse.status}: ${await tokenResponse.text()}`);
const {access_token}=await tokenResponse.json();const headers={Authorization:`Bearer ${access_token}`,'Content-Type':'application/json',[ORCHESTRATION_PROTOCOL_HEADER]:String(ORCHESTRATION_PROTOCOL_VERSION)};
const projectId=uuid(),threadId=uuid();
const created=await fetch(`${origin}/api/projects/mutate`,{method:'POST',headers,body:JSON.stringify({type:'project.create',commandId:uuid(),projectId,title:'Synthetic wake capture',workspaceRoot:project})});
if(!created.ok)throw Error(`Project ${created.status}: ${await created.text()}`);
const ticketResponse=await fetch(`${origin}/api/auth/websocket-ticket`,{method:'POST',headers});const {ticket}=await ticketResponse.json();
const layerSocket=Socket.layerWebSocket(`${origin.replace('http:','ws:')}/ws?orchestrationProtocol=${ORCHESTRATION_PROTOCOL_VERSION}&wsTicket=${encodeURIComponent(ticket)}`).pipe(Layer.provide(Socket.layerWebSocketConstructorGlobal));
const layerProtocol=RpcClient.layerProtocolSocket().pipe(Layer.provide(layerSocket),Layer.provide(RpcSerialization.layerJson));
const marker=path.join(project,'background-exited.txt');let markerSeen=false;
markerWatcher=fs.watch(project,()=>{if(!markerSeen && fs.existsSync(marker)){const content=fs.readFileSync(marker,'utf8').trim();if(content){markerSeen=true;log('BACKGROUND_PROCESS_EXIT_MARKER',content);}}});
const program=Effect.gen(function*(){
const client=yield* RpcClient.make(WsRpcGroup);
yield* client['server.refreshProviders']({instanceId:'claudeAgent',fresh:true});
const config=yield* client['server.getConfig']({});
const provider=config.providers.find(p=>p.instanceId==='claudeAgent');
log('CLAUDE_PROVIDER',provider && {instanceId:provider.instanceId,driver:provider.driver,installed:provider.installed,version:provider.version,status:provider.status,auth:provider.auth,models:provider.models.map(m=>m.slug)});
if(!provider?.installed)throw Error('Claude provider not installed');
const selected=provider.models.find(m=>m.slug==='claude-sonnet-4-6')??provider.models.find(m=>m.slug.includes('sonnet'))??provider.models[0];
if(!selected)throw Error('Claude provider lists no models');const modelSelection={instanceId:provider.instanceId,model:selected.slug};log('MODEL',modelSelection);
const settings=yield* client['server.updateSettings']({patch:{sidebarAutoSettleOnMerge:false,enableProviderUpdateChecks:false}});log('SETTINGS',{sidebarAutoSettleOnMerge:settings.sidebarAutoSettleOnMerge});
const ref={projectId,host:'github.com',repository:'pingdotgg/t3code',number:26057};
const summary=yield* client['pullRequests.summary'](ref);log('PULL_REQUEST_LOOKUP',{...ref,url:summary.url,state:summary.state,title:summary.title,mergedAt:summary.mergedAt,closedAt:summary.closedAt});if(summary.state!=='merged')throw Error('Fixture PR is not merged');
const dispatch=command=>client['orchestration.dispatchCommand']({commandId:uuid(),...command});
yield* dispatch({type:'thread.create',threadId,projectId,title:`Synthetic ${side} wake ${runNumber}`,modelSelection,runtimeMode:'full-access',interactionMode:'default',branch:null,worktreePath:project,createdBy:'user',creationSource:'web'});
yield* dispatch({type:'thread.pull-request.link',threadId,host:ref.host,repository:ref.repository,number:ref.number,url:'https://github.com/pingdotgg/t3code/pull/26057',source:'manual'});log('THREAD_LINKED',{threadId,...ref});
const command=`sleep 45; date -u +%Y-%m-%dT%H:%M:%SZ > ${marker}; printf 'BACKGROUND_SLEEP_FINISHED\\n'`;
const prompt=`This is an authorized runtime reproduction with synthetic data. Use your native Bash tool to execute exactly this command with run_in_background=true: ${command}\nAfter Bash returns its background task id, register that id with T3's t3_background_wait MCP tool (discover it with ToolSearch if deferred). Do not delegate, use TaskOutput, poll, or wait in the foreground. After t3_background_wait returns, end this initial turn with exactly WAITING. When the actual completion notification arrives after the sleep finishes, reply with the single word DONE and no tools. The command's timestamp file is only evidence; do not read or change it yourself. Do not inspect other files or change settings or pull requests.`;
fs.writeFileSync(path.join(dir,'prompt.txt'),prompt);log('PROMPT',prompt);
yield* dispatch({type:'message.dispatch',threadId,messageId:uuid(),text:prompt,attachments:[],dispatchMode:{type:'start_immediately'},createdBy:'user',creationSource:'web'});
yield* client['server.updateSettings']({patch:{sidebarAutoSettleOnMerge:true}});log('SETTINGS',{sidebarAutoSettleOnMerge:true});
let last='';let firstSettledAt=null;let done=false;let waitRegistered=false;let finalProjection;let fixtureSynced=false;
const end=Promise.withResolvers();let quietTimer;const deadline=setTimeout(()=>end.resolve('observation deadline (180 seconds)'),180000);
const observer=client['orchestration.subscribeThread']({threadId}).pipe(Stream.runForEach(Effect.fn(function*(item){
fs.appendFileSync(path.join(dir,'events.ndjson'),JSON.stringify({observedAt:new Date().toISOString(),item})+'\n');
const p=item.kind==='snapshot'?item.projection:yield* client['orchestration.getThreadProjection']({threadId});finalProjection=p;
fs.writeFileSync(path.join(dir,'projection.json'),JSON.stringify(p,null,2));
if(!fixtureSynced && p.turnItems.some(t=>t.toolName==='mcp__t3-code__t3_background_wait' && t.status==='completed') && ['completed','waiting'].includes(p.runs[0]?.status)){
fixtureSynced=true;const syntheticMergedAt=new Date().toISOString();const snapshot=p.thread.pullRequests[0]?.snapshot;
if(!snapshot)throw Error('Real PR snapshot missing after background wait registration');
yield* dispatch({type:'thread.pull-request-link.sync',threadId,host:ref.host,repository:ref.repository,number:ref.number,snapshot:{...snapshot,mergedAt:syntheticMergedAt,syncedAt:syntheticMergedAt},stack:null});
log('SYNTHETIC_FIXTURE_TIMESTAMP',{reason:'Production requires PR terminalAt >= thread createdAt/latest user-authored message. Real public PR predates freshly created synthetic thread. Only cached link snapshot changed through RPC after initial run; no external PR mutation.',actualMergedAt:summary.mergedAt,syntheticMergedAt});
}
const view={thread:{id:p.thread.id,updatedAt:p.thread.updatedAt,settledOverride:p.thread.settledOverride,settledAt:p.thread.settledAt,pullRequests:p.thread.pullRequests},runs:p.runs.map(r=>({id:r.id,status:r.status,startedAt:r.startedAt,completedAt:r.completedAt,source:r.source})),providerSessions:p.providerSessions.map(s=>({id:s.id,status:s.status,lastError:s.lastError})),providerThreads:p.providerThreads.map(t=>({id:t.id,providerSessionId:t.providerSessionId,status:t.status,pendingBackgroundTasks:t.pendingBackgroundTasks})),messages:p.messages.filter(m=>m.role==='assistant').map(m=>({id:m.id,text:m.text,createdAt:m.createdAt})),turnItems:p.turnItems.filter(t=>['tool_call','dynamic_tool','command_execution','notification'].includes(t.type)).map(t=>({id:t.id,type:t.type,status:t.status,name:t.name,toolName:t.toolName,input:t.input,output:t.output,content:t.content}))};
const serialized=JSON.stringify(view);if(serialized!==last){last=serialized;log('PROJECTION',view);}
if(!done && p.messages.some(m=>m.role==='assistant' && m.text.trim()==='DONE')){done=true;log('WAKE_REPLY_DONE',{runCount:p.runs.length});}
waitRegistered=waitRegistered||JSON.stringify(p.turnItems).includes('t3_background_wait');
if(p.thread.settledOverride==='settled' && !firstSettledAt){firstSettledAt=new Date().toISOString();log('THREAD_SETTLED',{done,runCount:p.runs.length});quietTimer=setTimeout(()=>end.resolve('settled; observed 20 additional seconds'),20000);}
})),Effect.forkScoped);
yield* observer;
const reason=yield* Effect.promise(()=>end.promise);clearTimeout(deadline);clearTimeout(quietTimer);
if(!finalProjection)throw Error('No projection');
verdict={side,threadId,modelSelection,reason,markerSeen,waitRegistered,done,firstSettledAt,settled:finalProjection.thread.settledOverride,runCount:finalProjection.runs.length,runs:finalProjection.runs.map(r=>({id:r.id,status:r.status})),outcome:done?'kept wake':markerSeen&&firstSettledAt?'lost wake':'n/a'};log('VERDICT',verdict);return verdict;
}).pipe(Effect.scoped,Effect.provide(layerProtocol));
await Effect.runPromise(program,{signal:abort.signal});
} catch(e) {verdict={...verdict,status:'error',error:String(e)};log('ERROR',String(e));process.exitCode=1;}
finally {
clearTimeout(startupTimer);markerWatcher?.close();
log('STOP_SERVER',{pid:server.pid});
if(server.exitCode===null&&server.signalCode===null){const stopped=new Promise(r=>server.once('exit',r));server.kill('SIGTERM');const hard=setTimeout(()=>server.kill('SIGKILL'),10000);await stopped;clearTimeout(hard);}
try{process.kill(-server.pid,'SIGKILL');}catch(e){if(e.code!=='ESRCH')log('STOP_ERROR',String(e));}
fs.writeFileSync(path.join(dir,'verdict.json'),JSON.stringify(verdict,null,2));
log('SERVER_STOPPED',{pid:server.pid,exitCode:server.exitCode,signal:server.signalCode});
process.off('SIGTERM',onSignal);process.off('SIGINT',onSignal);
}
Not checked: Claude CLI versions other than 2.1.304 (the roster-first frame order is covered by the adapter test from the recorded SDK fixture).
Model and harness: Claude Opus 5.5 (lead, reproduce-test, implement) and GPT-6.1 Sol (review, runtime capture), via T3 Code.
🤖 Generated with Claude Code
- 1
github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:L
Approvability#
Verdict: Approved at
07f6b43Macroscope's review found this PR approvable — Automatic settlement now waits briefly when Claude has evidence of a pending wake turn. The wait is bounded by the existing two-minute deadline, leaves manual settlement unchanged, and does not block settlement when the probe fails.
You can add or adjust custom eligibility rules. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).Thread transfer impact#
✅ Thread transfer remains within every enforced ceiling.
Provider Metric Main baseline This PR Impact PR ceiling Codex Total thread wire 5.0 KiB 5.0 KiB +6 B (+0.1%) 6.8 KiB ✅ Codex Thread snapshot wire 3.8 KiB 3.8 KiB 0 B (0.0%) 4.9 KiB ✅ Codex Live turn WebSocket wire 1.2 KiB 1.3 KiB +6 B (+0.5%) 2.0 KiB ✅ Codex Live turn WebSocket decoded 21.6 KiB 21.6 KiB 0 B (0.0%) 24.4 KiB ✅ Codex Live turn messages 2 2 0 (0.0%) 8 ✅ Claude Total thread wire 5.1 KiB 5.0 KiB −6 B (−0.1%) 6.8 KiB ✅ Claude Thread snapshot wire 3.8 KiB 3.8 KiB 0 B (0.0%) 4.9 KiB ✅ Claude Live turn WebSocket wire 1.3 KiB 1.3 KiB −6 B (−0.5%) 2.0 KiB ✅ Claude Live turn WebSocket decoded 21.9 KiB 21.9 KiB 0 B (0.0%) 24.4 KiB ✅ Claude Live turn messages 2 2 0 (0.0%) 8 ✅ Baseline:
07242ab· PR result:07f6b43· Source CI: successScenario and decoded snapshot size
10 historical turns, 5 command tools per turn, 878.9 KiB retained MCP result per historical turn, and a 1.05 MiB retained result in the measured turn.
- Codex decoded thread snapshot: 108.5 KiB
- Claude decoded thread snapshot: 108.8 KiB
Updated in place by a trusted workflow. PR artifacts are strictly validated and never executed.
No actionable comments were generated in the recent review.
Recent review info-
Run configuration-
- Source mode: Auto
- Repository: pingdotgg/t3code
- Branch: fix/issue-26083
- File: .coderabbit.config.ts
- Commit: 07f6b43
- Layers: Repository TS config
- Review profile: CHILL
- Plan: Team
- Run ID:
d683d776-94b1-4cc0-8a60-46dc0ff7f670
Commits-
Reviewing files that changed from the base of the PR and between 07242abff3cf2004a703ae631eae1416574a5f30 and 07f6b43d85ae2f9711d976a72c2ef17f21152293.
Files selected for processing: 5-
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.tsapps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.tsapps/server/src/orchestration-v2/BackgroundWorkStop.integration.test.tsapps/server/src/orchestration-v2/Orchestrator.tspackages/provider-core/src/server/ProviderAdapter.ts
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 5 remain after this review.
-
Walkthrough
-
The Claude adapter now tracks pending wake expectations and exposes a per-thread probe. Before automatic settlement, the orchestrator checks available provider-session probes and rejects settlement when any reports a pending wake.
Changes: Pending Wake Protection
Priority:Layer / File(s) Summary Track and expose Claude pending wakes
packages/provider-core/src/server/ProviderAdapter.ts,apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts,apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.tsThe session runtime adds an optional pending-wake probe. The Claude adapter records wake expectations from roster changes and buffered notifications, and expires them after the configured deadline. Tests cover buffered notifications, successive wakes, and deadline behavior. Guard automatic settlement
apps/server/src/orchestration-v2/Orchestrator.ts,apps/server/src/orchestration-v2/BackgroundWorkStop.integration.test.tsBefore settling, the orchestrator checks available provider-session probes and rejects settlement when a probe reports a pending wake. Integration tests cover pending wakes, dev-server tasks, and probe failures. NormalEstimated code review effort: 3 (Moderate) | ~25 minutes
Change: Bug fix · Severity of issue fixed: Medium
Sequence Diagram(s)#
sequenceDiagram participant Orchestrator participant ProviderAdapterV2SessionRuntime participant ClaudeAdapterV2 Orchestrator->>ProviderAdapterV2SessionRuntime: Check pending wake for provider thread ProviderAdapterV2SessionRuntime->>ClaudeAdapterV2: Check pending wake evidence for native thread ClaudeAdapterV2-->>ProviderAdapterV2SessionRuntime: Return pending-wake status ProviderAdapterV2SessionRuntime-->>Orchestrator: Return pending-wake status Orchestrator->>Orchestrator: Reject settlement if a wake is pendingPossibly related issues
pingdotgg/t3code#17625— The changes add a pending-wake guard to auto-settlement for background work that can trigger a Claude wake.
Suggested reviewers:
t3dotgg
Merge Risk:
Minimal · up to07f6b-
Pending Claude wakes defer automatic settlement, while a wake that never opens does not leave the thread indefinitely unsettled. The change is mergeable after normal checks.
Pre-merge checks:
4-
Check name Status Explanation Title check The title "fix(server): auto-settle on merge waits for a pending Claude wake turn" matches the main change. The diff adds a Claude-specific pending-wake probe (hasPendingWakeForThread) and makes threa… Description check The description follows the repository template. It has Problem, Change, Scope and approval, and Verification sections. The Problem section gives the race, expected behavior, and reproduction steps wi… Linked Issues check Issue #26083requires automatic merge settlement to avoid closing a Claude session before an awaited background-task wake runs. The Claude adapter records wake evidence, applies the two-minute deadlin…Out of Scope Changes check The changed production files implement the #26083wake probe, the provider runtime contract, and the automatic-settlement guard. The added unit and integration tests verify those changes. No unrelated…Full details: Title check
-
Explanation
The title "fix(server): auto-settle on merge waits for a pending Claude wake turn" matches the main change. The diff adds a Claude-specific pending-wake probe (hasPendingWakeForThread) and makes thread.auto-settle defer while a wake turn is pending, which is what the title describes. It uses a conventional commit prefix and plain language, and it is specific enough for a teammate scanning history. The title is 70 characters, within normal limits.
Full details: Description check
-
Explanation
The description follows the repository template. It has Problem, Change, Scope and approval, and Verification sections. The Problem section gives the race, expected behavior, and reproduction steps with transcripts. The Change section explains the probe, the auto-settle decider guard, and the unchanged paths. Scope links issue
#26083as the fixed issue. Verification lists focused tests, the pass counts, and a runtime before/after transcript with a driver script. It also states what was not checked (other Claude CLI versions) and names the model and harness. The Scope and approval section is brief. It cites the linked issue but does not link an explicit maintainer approval comment, which the template asks for. The template asks for explicit approval or an exemption rationale, and the description does not give one. This is a minor gap, so the check passes.
Full details: Linked Issues check
-
Explanation
Issue
#26083requires automatic merge settlement to avoid closing a Claude session before an awaited background-task wake runs. The Claude adapter records wake evidence, applies the two-minute deadline, and exposeshasPendingWakeForThread.thread.auto-settlechecks live provider sessions and defers settlement when the probe reports a pending wake. Focused adapter and integration tests cover buffered notifications, roster removal, deadlines, dev-server behavior, and probe failure.
Full details: Out of Scope Changes check
-
Explanation
The changed production files implement the
#26083wake probe, the provider runtime contract, and the automatic-settlement guard. The added unit and integration tests verify those changes. No unrelated production behavior or unrelated tests appear in the reviewed change set.
-
Finishing Touches
-
📝 Generate docstrings
-
- Commit to this branch
- Create a new PR
🧪 Generate unit tests (beta)
-
- Commit to this branch
- Create a new PR
-
- Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
-
juliusmarminge added labelsbugfix
juliusmarminge added labelspr:gate-failed
Note
Written by
claude-opus-5-5on behalf of eyeveilWe hit #26083 on a fork and fixed it in the Claude adapter, in https://github.com/issuelt/t3code/pull/62. These frame orders also lost the wake turn for us, so they may be worth checking against this PR:
- The empty
background_tasks_changedarrives before thetask_notification, so the task is already off the roster when the notification lands. - A task finishes during a user turn, and the CLI runs its notification as a separate turn after that turn's
result. - Two tasks finish while idle. The first wake turn's
resultreleases both, so the second wake turn races settlement again. The SDK binds each wake result to one notification:result.origin.runIdequalstask_notification.run_id. Releasing only the matching hold fixed this case.
Our fix keeps a notified task on the roster, marked awaited, until the result of its own wake turn. It ends the hold after the existing 2-minute wake-turn start deadline when no turn starts. The fork PR has a failing-first test for each case. We're glad to open any part of it here from a personal fork if that would help.
- The empty
Thanks for the earlier work on this wake race. Closing in favor of #30837 by @HarryMattocks, which addresses the same auto-settle race and currently merges cleanly. This older PR now conflicts with main.
juliusmarminge closed this
juliusmarminge removed labelspr:gate-failed
Sign in to join this conversation.
macroscopeapp[bot](GitHub profile, opens in a new tab) approved these changes