From 720223eb10070908ca3a1c3aa281bda3e337d74c Mon Sep 17 00:00:00 2001 From: Codex Date: Thu, 29 Oct 2026 15:09:47 +0900 Subject: [PATCH] fix: keep paired rooms moving when owner turn preparation fails A wargame room stalled after its owner ran npm install in a bun project: both bun.lock and package-lock.json existed, so every owner turn threw 'Ambiguous package manager' while provisioning the workspace. The queue had already claimed the turn, nothing released the claim, and the 5s backoff retry was skipped as 'already claimed elsewhere', so the room sat idle until a human wrote again (and then failed the same way). - Owner workspace provisioning and the review handoff no longer fail when the dependency install step throws; they log a warning and go on. - If preparing a paired run throws, mark the claimed turn failed and release its execution lease so the retry can run. Co-Authored-By: Claude Opus 5.5 --- src/message-agent-executor.test.ts | 36 +++++++++++++++ src/message-agent-executor.ts | 69 ++++++++++++++++++++++------ src/paired-workspace-manager.test.ts | 38 +++++++++++++++ src/paired-workspace-manager.ts | 63 ++++++++++++++++--------- 4 files changed, 171 insertions(+), 35 deletions(-) diff --git a/src/message-agent-executor.test.ts b/src/message-agent-executor.test.ts index c118f16..40e4617 100644 --- a/src/message-agent-executor.test.ts +++ b/src/message-agent-executor.test.ts @@ -717,6 +717,42 @@ describe('runAgentForGroup room memory', () => { expect(agentRunner.runAgentProcess).not.toHaveBeenCalled(); }); + it('releases the claimed paired turn when execution preparation throws', async () => { + const group = { ...makeGroup(), folder: 'test-group' }; + vi.mocked( + pairedExecutionContext.preparePairedExecutionContext, + ).mockImplementation(() => { + throw new Error('Ambiguous package manager for /ws: bun, npm'); + }); + const turnIdentity = { + turnId: 'paired-task-prepare-fail:2026-04-10T00:00:00.000Z:owner-turn', + taskId: 'paired-task-prepare-fail', + taskUpdatedAt: '2026-04-10T00:00:00.000Z', + intentKind: 'owner-turn' as const, + role: 'owner' as const, + }; + + await expect( + runAgentForGroup(makeDeps(), { + group, + prompt: 'hello', + chatJid: 'group@test', + runId: 'run-prepare-fail', + pairedTurnIdentity: turnIdentity, + }), + ).rejects.toThrow(/Ambiguous package manager/); + + expect(agentRunner.runAgentProcess).not.toHaveBeenCalled(); + expect(db.failPairedTurn).toHaveBeenCalledWith({ + turnIdentity, + error: 'Ambiguous package manager for /ws: bun, npm', + }); + expect(db.releasePairedTaskExecutionLease).toHaveBeenCalledWith({ + taskId: 'paired-task-prepare-fail', + runId: 'run-prepare-fail', + }); + }); + it('allows a claimed paired turn revision when preparation advances the task before execution', async () => { const group = { ...makeGroup(), folder: 'test-group' }; diff --git a/src/message-agent-executor.ts b/src/message-agent-executor.ts index 4d44400..a499873 100644 --- a/src/message-agent-executor.ts +++ b/src/message-agent-executor.ts @@ -1,4 +1,5 @@ import { AgentOutput } from './agent-runner.js'; +import { logger } from './logger.js'; import { GroupQueue } from './group-queue.js'; import type { AgentTriggerReason } from './agent-error-detection.js'; import { @@ -20,7 +21,11 @@ import { markRunPausedForClaudeUsage, pauseRoomForClaudeUsage, } from './claude-usage-pause.js'; -import { getPairedTaskById } from './db.js'; +import { + failPairedTurn, + getPairedTaskById, + releasePairedTaskExecutionLease, +} from './db.js'; import { formatUsageAlignmentHoldMessage, formatUsageLimitAlignedPauseMessage, @@ -314,6 +319,32 @@ async function deliverNoticeAndFailExecution(args: { args.pairedExecutionLifecycle.completeImmediately({ status: 'failed' }); } +/** + * The queue claims the paired turn (execution lease + running attempt) before + * this executor runs. If preparing the run throws, nothing else releases that + * claim, so the backoff retry is skipped as "already claimed elsewhere" and the + * room stalls until a human writes again. Release it so the retry can run. + */ +function releaseClaimedTurnAfterPrepareFailure( + turnIdentity: PairedTurnIdentity | undefined, + runId: string, + error: unknown, +): void { + if (!turnIdentity) return; + try { + failPairedTurn({ + turnIdentity, + error: error instanceof Error ? error.message : String(error), + }); + releasePairedTaskExecutionLease({ taskId: turnIdentity.taskId, runId }); + } catch (releaseError) { + logger.error( + { taskId: turnIdentity.taskId, runId, releaseError }, + 'Failed to release paired turn claim after execution prepare failure', + ); + } +} + export interface MessageAgentExecutorDeps { assistantName: string; queue: Pick & @@ -346,18 +377,30 @@ export async function runAgentForGroup( }, ): Promise<'success' | 'error'> { const { group, prompt, chatJid, runId, startSeq, endSeq, onOutput } = args; - const preparedExecution = await prepareMessageAgentExecutionTarget(deps, { - group, - prompt, - chatJid, - runId, - startSeq, - endSeq, - hasHumanMessage: args.hasHumanMessage, - forcedRole: args.forcedRole, - forcedAgentType: args.forcedAgentType, - pairedTurnIdentity: args.pairedTurnIdentity, - }); + let preparedExecution: Awaited< + ReturnType + >; + try { + preparedExecution = await prepareMessageAgentExecutionTarget(deps, { + group, + prompt, + chatJid, + runId, + startSeq, + endSeq, + hasHumanMessage: args.hasHumanMessage, + forcedRole: args.forcedRole, + forcedAgentType: args.forcedAgentType, + pairedTurnIdentity: args.pairedTurnIdentity, + }); + } catch (error) { + releaseClaimedTurnAfterPrepareFailure( + args.pairedTurnIdentity, + runId, + error, + ); + throw error; + } const { activeRole, effectiveServiceId, diff --git a/src/paired-workspace-manager.test.ts b/src/paired-workspace-manager.test.ts index 67367ee..f1e371c 100644 --- a/src/paired-workspace-manager.test.ts +++ b/src/paired-workspace-manager.test.ts @@ -289,6 +289,44 @@ describe('paired workspace manager', () => { ); }); + it('keeps provisioning and review handoff going when the owner workspace has ambiguous lockfiles', async () => { + const { db, manager } = await loadModules(); + db._initTestDatabase(); + + const canonicalDir = path.join(tempRoot, 'canonical'); + initCanonicalRepo(canonicalDir); + seedPairedTask(db, canonicalDir, { + taskId: 'paired-task-ambiguous-lockfiles', + groupFolder: 'ambiguous-lockfile-room', + }); + + const first = manager.provisionOwnerWorkspaceForPairedTask( + 'paired-task-ambiguous-lockfiles', + ); + // The owner ran `npm install` in a bun project: both lockfiles now exist. + fs.writeFileSync( + path.join(first.workspace_dir, 'package.json'), + JSON.stringify({ name: 'x', version: '1.0.0' }), + ); + fs.writeFileSync(path.join(first.workspace_dir, 'bun.lock'), '{}\n'); + fs.writeFileSync( + path.join(first.workspace_dir, 'package-lock.json'), + '{}\n', + ); + + expect(() => + manager.provisionOwnerWorkspaceForPairedTask( + 'paired-task-ambiguous-lockfiles', + ), + ).not.toThrow(); + expect( + manager.markPairedTaskReviewReady('paired-task-ambiguous-lockfiles'), + ).not.toBeNull(); + expect( + db.getPairedTaskById('paired-task-ambiguous-lockfiles')?.status, + ).toBe('review_ready'); + }); + it('leaves review_requested_at untouched when review handoff aborts before an owner workspace exists', async () => { const { db, manager } = await loadModules(); db._initTestDatabase(); diff --git a/src/paired-workspace-manager.ts b/src/paired-workspace-manager.ts index 4c06841..6a987ea 100644 --- a/src/paired-workspace-manager.ts +++ b/src/paired-workspace-manager.ts @@ -795,16 +795,26 @@ export function provisionOwnerWorkspaceForPairedTask( } } - const installResult = ensureWorkspaceDependenciesInstalled(workspaceDir); - if (installResult.installed) { - logger.info( - { - taskId, - workspaceDir, - packageManager: installResult.packageManager, - command: installResult.commandText ?? null, - }, - 'Installed owner workspace dependencies', + // Dependency install is a convenience for the owner, not a precondition: a + // bad install state (e.g. the owner left both bun.lock and package-lock.json) + // must not stop the owner turn, because the owner is the one who can fix it. + try { + const installResult = ensureWorkspaceDependenciesInstalled(workspaceDir); + if (installResult.installed) { + logger.info( + { + taskId, + workspaceDir, + packageManager: installResult.packageManager, + command: installResult.commandText ?? null, + }, + 'Installed owner workspace dependencies', + ); + } + } catch (error) { + logger.warn( + { taskId, workspaceDir, err: error }, + 'Skipped owner workspace dependency install; continuing the owner turn', ); } @@ -901,18 +911,27 @@ export function markPairedTaskReviewReady(taskId: string): { return null; } - const installResult = ensureWorkspaceDependenciesInstalled( - ownerWorkspace.workspace_dir, - ); - if (installResult.installed) { - logger.info( - { - taskId, - ownerDir: ownerWorkspace.workspace_dir, - packageManager: installResult.packageManager, - command: installResult.commandText ?? null, - }, - 'Installed owner workspace dependencies before review handoff', + // Same as owner provisioning: a broken install state must not block the + // review handoff. The reviewer's own verification surfaces it instead. + try { + const installResult = ensureWorkspaceDependenciesInstalled( + ownerWorkspace.workspace_dir, + ); + if (installResult.installed) { + logger.info( + { + taskId, + ownerDir: ownerWorkspace.workspace_dir, + packageManager: installResult.packageManager, + command: installResult.commandText ?? null, + }, + 'Installed owner workspace dependencies before review handoff', + ); + } + } catch (error) { + logger.warn( + { taskId, ownerDir: ownerWorkspace.workspace_dir, err: error }, + 'Skipped owner workspace dependency install before review handoff', ); }