diff --git a/.env.example b/.env.example index cea8b9d..126eab4 100644 --- a/.env.example +++ b/.env.example @@ -57,15 +57,12 @@ STATUS_CHANNEL_ID= # Discord channel ID for live status updat # Model is injected based on each role's agent type (claude-code → CLAUDE_MODEL, codex → CODEX_MODEL). # OWNER_MODEL=gpt-5.5 # Owner model override # OWNER_EFFORT=xhigh # Owner effort override -# OWNER_FALLBACK_ENABLED=true # Fall back to codex on Claude failure (default: true) # # REVIEWER_MODEL=claude-opus-5-5 # Reviewer model override # REVIEWER_EFFORT=high # Reviewer effort override -# REVIEWER_FALLBACK_ENABLED=true # Fall back to codex on Claude failure (default: true) # # ARBITER_MODEL=gpt-5.5 # Arbiter model override when ARBITER_AGENT_TYPE=codex # ARBITER_EFFORT=xhigh # Arbiter effort override -# ARBITER_FALLBACK_ENABLED=true # Fall back to codex on Claude failure (default: true) # --- Advanced --- # MAX_CONCURRENT_AGENTS=5 # Max parallel agent processes diff --git a/CHANGELOG.md b/CHANGELOG.md index 5ad0432..39be084 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ ### Changed +- Claude가 사용 한도에 도달하면 Codex로 넘기는 대신 방에 "Claude 사용 한도에 도달했습니다. 21:40에 재개할 수 있습니다."처럼 재개 시각(KST)을 바로 알리고, 열린 paired task를 `claude_usage_limit`으로 닫음. 재개 시각은 오류 문구(`resets 9:40pm (Asia/Seoul)` 등)에서 읽고, 없으면 사용량 API 캐시에서, 그것도 없으면 "잠시 후 다시 시도해 주세요"로 안내. 조용한 자동 재시도는 하지 않음 - 기본 Claude 모델을 Claude Opus 5.5(`claude-opus-5-5`)로 상향. Opus 5.5는 Claude Code CLI 2.1.280 이상이 필요해 `@anthropic-ai/claude-agent-sdk`를 0.3.153 → 0.3.286(번들 CLI 2.1.286)으로 올림 (8b68885) - `@openai/codex`를 0.133.0 → 0.159.3으로 상향. 구버전이 매 실행마다 내던 `failed to decode models response: unknown variant max` 오류와 로그 폭주가 사라지고, 단순 리뷰 턴이 49초 → 5초로 단축됨 (a7f2e02) @@ -25,6 +26,7 @@ - main(관리) 방 개념과 그것이 열어 주던 방 간 기능. 모든 방의 `is_main`이 0이라 실제로 쓰이지 않았음. 이제 각 방의 에이전트는 자기 방만 다룸: 다른 방 예약 작업 생성/수정/일시정지/취소(`target_group_jid`), 다른 방으로 메시지 전송·inbound 주입, 전체 방 범위의 DB 증거 조회, IPC `assign_room`/`refresh_groups`와 에이전트용 `assign_room` 도구, `available_groups.json` 스냅샷, main 방 전용 global memory 제외, `EJCLAW_IS_MAIN` 환경 변수, main 방으로 보내던 추론 재시작 알림, `setup --step register`의 `--is-main`, `scripts/deregister-room.ts`의 main 방 보호(`--force`), `groups/main/` 템플릿 제거. `room_settings.is_main` 컬럼은 스키마에 남아 있으나 더 이상 읽거나 쓰지 않음 - 기본 비활성이던 주기적 Codex warm-up 루프와 `CODEX_WARMUP_ENABLED`/`CODEX_WARMUP_INTERVAL_MS`. 고정 슬롯 usage primer는 그대로 동작 - 다중 계정 로테이션. Claude·Codex 모두 계정 1개 고정으로 동작: 한도·인증 오류 시 다음 계정으로 넘어가기, 계정별 쿨다운·상태 파일(`token-rotation-state.json`, `codex-rotation-state.json`), Codex 1시간 전체 계정 사용량 스캔, `CLAUDE_ACCOUNTS_DIR`(`~/.claude-accounts/`) 제거. Codex는 `~/.codex-accounts/0/auth.json`(없으면 `~/.codex/auth.json`)을 매 실행마다 확인하므로 재로그인 후 재시작이 필요 없음. 계정 잠금(동시 실행 1개, 최대 15분 대기)과 세션 토큰 write-back, Claude 토큰 자동 갱신(만료 시 1회 강제 갱신 후 재시도)은 유지. `CLAUDE_CODE_OAUTH_TOKENS`는 첫 번째 값만 사용 +- Claude→Codex failover/handoff 체인: 한도·인증 오류 시 `service_handoffs`에 작업을 넘기던 생성 경로, 핸드오프 폴링·claim 워커, 전역 owner failover(`codex-review`가 owner 대행)와 그 프롬프트(`prompts/codex-review-failover-platform.md`), 대시보드 failover 표시, `ROOM_ROLE` 헤더의 `failover=` 필드, `OWNER_/REVIEWER_/ARBITER_FALLBACK_ENABLED` 설정. 이 배포에는 받을 Codex 서비스가 없어 넘긴 작업이 `pending`으로 남기만 했음. `service_handoffs` 테이블과 마이그레이션은 그대로 두며(다음 마이그레이션 정리 때 처리), 런타임은 더 이상 읽거나 쓰지 않음(방 등록 해제 스크립트의 행 정리만 남김). `.env`에 남은 `*_FALLBACK_ENABLED`는 무시됨 ### Fixed diff --git a/README.md b/README.md index f05db3c..10c22ce 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,7 @@ EJClaw는 Discord 위에서 동작하는 Tribunal 멀티에이전트 개발 보 - role-fixed Discord 봇 3개 체계 - reviewer host runtime + read-only guard - 승인 후 변경 감지와 재리뷰 -- Claude 장애 시 Codex로 넘기는 global failover +- Claude 사용 한도 도달 시 재개 시각을 방에 바로 안내 - `room_settings` 기반 명시적 room assignment - 자연어 중단: 작업 중인 방에 "그만", "멈춰", "중단해", "취소", "stop" 같은 짧은 메시지만 보내면 실행 중인 에이전트를 끝내고 열린 paired task를 닫음 - Bun + SQLite 기반 빠른 런타임 diff --git a/docs/configuration.md b/docs/configuration.md index 0bef733..e0161a1 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -40,15 +40,12 @@ CODEX_EFFORT=xhigh # 역할별 override OWNER_MODEL=gpt-5.5 OWNER_EFFORT=xhigh -OWNER_FALLBACK_ENABLED=true REVIEWER_MODEL=claude-opus-5-5 REVIEWER_EFFORT=high -REVIEWER_FALLBACK_ENABLED=true ARBITER_MODEL=gpt-5.5 ARBITER_EFFORT=xhigh -ARBITER_FALLBACK_ENABLED=true ``` 설명: @@ -77,6 +74,7 @@ ANTHROPIC_BASE_URL= - `CLAUDE_CODE_OAUTH_TOKEN`: runner에 주입하는 Claude 토큰. 예전 `CLAUDE_CODE_OAUTH_TOKENS`(쉼표 구분)가 남아 있으면 첫 번째 값만 씁니다 - `CLAUDE_CREDENTIALS_PATH`: 이 서비스의 Claude OAuth credentials 파일. `CLAUDE_TOKEN_REFRESH_USE_CREDENTIALS=true`면 만료 전에 자동 갱신하고 새 토큰을 `.env`에도 기록합니다 +- Claude가 사용 한도에 도달하면 다른 provider로 넘기지 않습니다. 방에 `Claude 사용 한도에 도달했습니다. 21:40에 재개할 수 있습니다.`처럼 재개 시각을 보내고(시각을 모르면 `잠시 후 다시 시도해 주세요`), 열린 paired task를 `claude_usage_limit`으로 닫습니다. 다음 메시지부터 새 작업으로 처리됩니다 Codex 쪽은 **OAuth 세션 파일** 기준으로 동작합니다. `~/.codex-accounts/0/auth.json`을 쓰고, 없으면 `~/.codex/auth.json`을 씁니다. Codex 실행은 계정 잠금으로 한 번에 하나만 돌고, 잠겨 있으면 최대 15분 기다립니다. `OPENAI_API_KEY`를 Codex child process에 넘겨서 빌링하는 구조는 사용하지 않습니다. diff --git a/prompts/codex-review-failover-platform.md b/prompts/codex-review-failover-platform.md deleted file mode 100644 index a8089a1..0000000 --- a/prompts/codex-review-failover-platform.md +++ /dev/null @@ -1,11 +0,0 @@ -# Codex Review Failover Rules - -You are `codex-review`, and in this chat you are currently acting as `클코`, the owner-side failover agent. - -## Role - -- Answer as the primary owner for the chat, not as a reviewer -- Do not describe yourself as the review-side Codex service while this failover prompt is active -- `codex-main` is a separate Codex participant and is not you -- The visible bot name or nickname in chat history may vary by room; do not infer your role from the visible name -- Do not claim to be `codex-main` diff --git a/runners/agent-runner/test/reviewer-runtime.test.ts b/runners/agent-runner/test/reviewer-runtime.test.ts index 4ff8a25..34bc3fc 100644 --- a/runners/agent-runner/test/reviewer-runtime.test.ts +++ b/runners/agent-runner/test/reviewer-runtime.test.ts @@ -80,7 +80,6 @@ describe('claude reviewer runtime guard', () => { role: 'reviewer', ownerServiceId: 'codex-main', reviewerServiceId: 'codex-review', - failoverOwner: false, }), ).toBe(true); }); @@ -95,7 +94,6 @@ describe('claude reviewer runtime guard', () => { role: 'reviewer', ownerServiceId: 'codex-main', reviewerServiceId: 'claude', - failoverOwner: false, }), ).toBe(true); expect( @@ -104,7 +102,6 @@ describe('claude reviewer runtime guard', () => { role: 'owner', ownerServiceId: 'codex-main', reviewerServiceId: 'claude', - failoverOwner: false, }), ).toBe(false); }); diff --git a/runners/agent-runner/test/room-role-context.test.ts b/runners/agent-runner/test/room-role-context.test.ts index 4ada0d4..5e1b305 100644 --- a/runners/agent-runner/test/room-role-context.test.ts +++ b/runners/agent-runner/test/room-role-context.test.ts @@ -10,10 +10,9 @@ describe('claude runner room role header', () => { role: 'owner', ownerServiceId: 'codex-review', reviewerServiceId: 'codex-main', - failoverOwner: true, }), ).toBe( - '[ROOM_ROLE self=codex-review role=owner owner=codex-review reviewer=codex-main failover=1]\n\nhello', + '[ROOM_ROLE self=codex-review role=owner owner=codex-review reviewer=codex-main]\n\nhello', ); }); diff --git a/runners/codex-runner/test/reviewer-runtime.test.ts b/runners/codex-runner/test/reviewer-runtime.test.ts index 04df0a0..19022f7 100644 --- a/runners/codex-runner/test/reviewer-runtime.test.ts +++ b/runners/codex-runner/test/reviewer-runtime.test.ts @@ -66,7 +66,6 @@ describe('codex reviewer runtime guard', () => { role: 'reviewer', ownerServiceId: 'codex-main', reviewerServiceId: 'codex-review', - failoverOwner: false, }), ).toBe(true); }); diff --git a/runners/codex-runner/test/room-role-context.test.ts b/runners/codex-runner/test/room-role-context.test.ts index 2d5b9c0..cb62f31 100644 --- a/runners/codex-runner/test/room-role-context.test.ts +++ b/runners/codex-runner/test/room-role-context.test.ts @@ -10,10 +10,9 @@ describe('codex runner room role header', () => { role: 'reviewer', ownerServiceId: 'claude', reviewerServiceId: 'codex-main', - failoverOwner: false, }), ).toBe( - '[ROOM_ROLE self=codex-main role=reviewer owner=claude reviewer=codex-main failover=0]\n\nhello', + '[ROOM_ROLE self=codex-main role=reviewer owner=claude reviewer=codex-main]\n\nhello', ); }); diff --git a/runners/shared/src/room-role-context.ts b/runners/shared/src/room-role-context.ts index e32fa33..91089f1 100644 --- a/runners/shared/src/room-role-context.ts +++ b/runners/shared/src/room-role-context.ts @@ -8,7 +8,6 @@ export interface RoomRoleContext { reviewerServiceId: string; ownerAgentType?: RunnerAgentType; reviewerAgentType?: RunnerAgentType | null; - failoverOwner: boolean; arbiterServiceId?: string; arbiterAgentType?: RunnerAgentType | null; } @@ -23,8 +22,7 @@ export function prependRoomRoleHeader( const header = `[ROOM_ROLE self=${roomRoleContext.serviceId} role=${roomRoleContext.role} ` + - `owner=${roomRoleContext.ownerServiceId} reviewer=${roomRoleContext.reviewerServiceId} ` + - `failover=${roomRoleContext.failoverOwner ? 1 : 0}]`; + `owner=${roomRoleContext.ownerServiceId} reviewer=${roomRoleContext.reviewerServiceId}]`; return `${header}\n\n${prompt}`; } diff --git a/src/agent-attempt-orchestration.ts b/src/agent-attempt-orchestration.ts index d5ac4ab..9d86135 100644 --- a/src/agent-attempt-orchestration.ts +++ b/src/agent-attempt-orchestration.ts @@ -8,7 +8,6 @@ import { type AgentTriggerReason, } from './agent-error-detection.js'; import { logger } from './logger.js'; -import { clearGlobalFailover } from './service-routing.js'; import { forceRefreshToken } from './token-refresh.js'; import { getErrorMessage } from './utils.js'; @@ -106,7 +105,6 @@ function evaluateRetriedClaudeAttempt( return { type: 'error', ...(trigger ? { trigger } : {}) }; } - clearGlobalFailover(); return { type: 'success', sawOutput: attempt.sawOutput }; } diff --git a/src/agent-runner-environment.test.ts b/src/agent-runner-environment.test.ts index 8eec343..6b1cf06 100644 --- a/src/agent-runner-environment.test.ts +++ b/src/agent-runner-environment.test.ts @@ -60,7 +60,6 @@ vi.mock('./service-routing.js', () => ({ owner_service_id: 'claude', reviewer_service_id: 'codex-main', arbiter_service_id: null, - owner_failover_active: false, activated_at: null, reason: null, explicit: false, @@ -130,7 +129,6 @@ function resetRoutingMocks(): void { owner_service_id: 'claude', reviewer_service_id: 'codex-main', arbiter_service_id: null, - owner_failover_active: false, activated_at: null, reason: null, explicit: false, @@ -328,67 +326,6 @@ describe('prepareGroupEnvironment prompt stacks', () => { fs.rmSync(tempRoot, { recursive: true, force: true }); }); - it('uses the failover owner prompt pack for codex-review when it owns an explicit failover lease', () => { - vi.mocked(config.isReviewService).mockReturnValue(true); - vi.mocked(serviceRouting.hasReviewerLease).mockReturnValue(true); - vi.mocked(serviceRouting.getEffectiveChannelLease).mockReturnValue({ - chat_jid: 'dc:test', - owner_service_id: 'codex-review', - reviewer_service_id: 'claude', - arbiter_service_id: null, - owner_failover_active: true, - activated_at: '2026-03-28T00:00:00.000Z', - reason: 'claude-429', - explicit: true, - }); - mockReadEnvFile.mockReturnValue({}); - - const promptsDir = path.join(tempRoot, 'prompts'); - fs.mkdirSync(promptsDir, { recursive: true }); - fs.writeFileSync( - path.join(promptsDir, 'codex-review-platform.md'), - 'review platform prompt\n', - ); - fs.writeFileSync( - path.join(promptsDir, 'owner-common-platform.md'), - 'owner common platform prompt\n', - ); - fs.writeFileSync( - path.join(promptsDir, 'owner-common-paired-room.md'), - 'owner common paired prompt\n', - ); - fs.writeFileSync( - path.join(promptsDir, 'codex-review-failover-platform.md'), - 'failover platform prompt\n', - ); - prepareGroupEnvironment( - { ...group, workDir: path.join(tempRoot, 'workdir') }, - 'dc:test', - { - memoryBriefing: 'memory briefing', - }, - ); - - const agentsPath = path.join( - tempRoot, - 'sessions', - group.folder, - 'services', - 'codex-main', - '.codex', - 'AGENTS.md', - ); - const agents = fs.readFileSync(agentsPath, 'utf-8'); - const segments = agents.trim().split('\n\n---\n\n'); - - expect(segments).toEqual([ - 'owner common platform prompt', - 'failover platform prompt', - 'owner common paired prompt', - 'memory briefing', - ]); - }); - it('adds only the shared owner prompt fragments to Claude session prompts', () => { vi.mocked(serviceRouting.hasReviewerLease).mockReturnValue(true); mockReadEnvFile.mockReturnValue({}); @@ -442,7 +379,7 @@ describe('prepareGroupEnvironment prompt stacks', () => { expect(prepared.env.CLAUDE_CODE_OAUTH_TOKEN).toBe('token-a'); }); - it('returns to the normal owner prompt stack after failover is cleared', () => { + it('uses the normal Codex prompt stack for a review service', () => { vi.mocked(config.isReviewService).mockReturnValue(true); vi.mocked(serviceRouting.hasReviewerLease).mockReturnValue(true); vi.mocked(serviceRouting.getEffectiveChannelLease).mockReturnValue({ @@ -450,7 +387,6 @@ describe('prepareGroupEnvironment prompt stacks', () => { owner_service_id: 'claude', reviewer_service_id: 'codex-main', arbiter_service_id: null, - owner_failover_active: false, activated_at: null, reason: null, explicit: false, @@ -748,7 +684,6 @@ describe('prepareGroupEnvironment Codex goals handling', () => { owner_service_id: 'claude', reviewer_service_id: 'codex-main', arbiter_service_id: null, - owner_failover_active: false, activated_at: null, reason: null, explicit: false, diff --git a/src/agent-runner-environment.ts b/src/agent-runner-environment.ts index 2728d82..424e399 100644 --- a/src/agent-runner-environment.ts +++ b/src/agent-runner-environment.ts @@ -3,13 +3,7 @@ import os from 'os'; import path from 'path'; import { EJCLAW_ENV } from 'ejclaw-runners-shared'; -import { - GROUPS_DIR, - SERVICE_ID, - SERVICE_SESSION_SCOPE, - TIMEZONE, - isReviewService, -} from './config.js'; +import { GROUPS_DIR, SERVICE_SESSION_SCOPE, TIMEZONE } from './config.js'; import { logger } from './logger.js'; import { readEnvFile } from './env.js'; import { @@ -36,10 +30,7 @@ import { readPairedRoomPrompt, readPlatformPrompt, } from './platform-prompts.js'; -import { - getEffectiveChannelLease, - hasReviewerLease, -} from './service-routing.js'; +import { hasReviewerLease } from './service-routing.js'; import type { AgentType, PairedRoomRole, RegisteredGroup } from './types.js'; import type { StoredRoomSkillOverride } from './db/rooms.js'; @@ -477,7 +468,6 @@ function prepareCodexSessionEnvironment(args: { chatJid: string; roomRole?: PairedRoomRole; isPairedRoom: boolean; - useFailoverPromptPack: boolean; memoryBriefing?: string; skillOverrides?: StoredRoomSkillOverride[]; }): PreparedCodexSessionAuth | null { @@ -529,30 +519,13 @@ function prepareCodexSessionEnvironment(args: { } const sessionAgentsPath = path.join(sessionCodexDir, 'AGENTS.md'); - const sessionAgents = ( - args.useFailoverPromptPack - ? [ - readOptionalPromptFile(args.projectRoot, 'owner-common-platform.md'), - readOptionalPromptFile( - args.projectRoot, - 'codex-review-failover-platform.md', - ), - args.isPairedRoom - ? readOptionalPromptFile( - args.projectRoot, - 'owner-common-paired-room.md', - ) - : undefined, - args.memoryBriefing, - ] - : [ - readPlatformPrompt('codex', args.projectRoot), - args.isPairedRoom - ? readPairedRolePrompt(args.projectRoot, args.roomRole) - : undefined, - args.memoryBriefing, - ] - ) + const sessionAgents = [ + readPlatformPrompt('codex', args.projectRoot), + args.isPairedRoom + ? readPairedRolePrompt(args.projectRoot, args.roomRole) + : undefined, + args.memoryBriefing, + ] .filter((value): value is string => Boolean(value)) .join('\n\n---\n\n') .trim(); @@ -707,12 +680,6 @@ export function prepareGroupEnvironment( const globalDir = path.join(GROUPS_DIR, 'global'); const globalClaudeMdPath = path.join(globalDir, 'CLAUDE.md'); const isPairedRoom = hasReviewerLease(chatJid); - const effectiveLease = getEffectiveChannelLease(chatJid); - // Canonical lease state now exposes owner failover directly, so prefer the - // explicit flag over the older CODEX_REVIEW_SERVICE_ID shadow heuristic. - const useCodexReviewFailoverPromptPack = - isReviewService(SERVICE_ID) && - effectiveLease.owner_failover_active === true; const ownerCommonPlatformPrompt = readOptionalPromptFile( projectRoot, @@ -789,7 +756,6 @@ export function prepareGroupEnvironment( chatJid, roomRole: options?.roomRole, isPairedRoom, - useFailoverPromptPack: useCodexReviewFailoverPromptPack, memoryBriefing: options?.memoryBriefing, skillOverrides: options?.skillOverrides, }); diff --git a/src/agent-runner.test.ts b/src/agent-runner.test.ts index a7d7d11..bdb3d4e 100644 --- a/src/agent-runner.test.ts +++ b/src/agent-runner.test.ts @@ -417,7 +417,6 @@ describe('agent-runner environment wiring', () => { role: 'reviewer', ownerServiceId: 'codex-main', reviewerServiceId: 'claude', - failoverOwner: false, }, }, () => {}, @@ -461,7 +460,6 @@ describe('agent-runner environment wiring', () => { role: 'reviewer', ownerServiceId: 'codex-main', reviewerServiceId: 'codex-review', - failoverOwner: false, }, }, () => {}, @@ -511,7 +509,6 @@ describe('agent-runner environment wiring', () => { role: 'reviewer', ownerServiceId: 'codex-main', reviewerServiceId: 'codex-review', - failoverOwner: false, }, }, () => {}, @@ -550,7 +547,6 @@ describe('agent-runner environment wiring', () => { role: 'reviewer', ownerServiceId: 'claude', reviewerServiceId: 'codex-main', - failoverOwner: false, }, }, () => {}, @@ -567,7 +563,6 @@ describe('agent-runner environment wiring', () => { role: 'reviewer', ownerServiceId: 'claude', reviewerServiceId: 'codex-main', - failoverOwner: false, }, }); }); diff --git a/src/arbiter-service-shadow.test.ts b/src/arbiter-service-shadow.test.ts index 0d8036e..5f0ceab 100644 --- a/src/arbiter-service-shadow.test.ts +++ b/src/arbiter-service-shadow.test.ts @@ -8,13 +8,11 @@ import { } from './config.js'; import { _initTestDatabase, - createServiceHandoff, getChannelOwnerLease, setChannelOwnerLease, } from './db.js'; import { resolveRoleServiceShadow } from './role-service-shadow.js'; import { - clearGlobalFailover, getEffectiveChannelLease, refreshChannelOwnerCache, } from './service-routing.js'; @@ -25,7 +23,6 @@ const customArbiterEnabled = describe.skipIf(!customArbiterEnabled)('custom arbiter service shadow', () => { beforeEach(() => { _initTestDatabase(); - clearGlobalFailover(); refreshChannelOwnerCache(true); }); @@ -61,25 +58,4 @@ describe.skipIf(!customArbiterEnabled)('custom arbiter service shadow', () => { arbiter_agent_type: 'codex', }); }); - - it('uses the configured arbiter service id for derived arbiter handoffs', () => { - const handoff = createServiceHandoff({ - chat_jid: 'dc:custom-arbiter-handoff', - group_folder: 'custom-arbiter-handoff', - source_role: 'owner', - source_agent_type: 'codex', - target_role: 'arbiter', - target_agent_type: 'codex', - prompt: 'arbiter please decide', - intended_role: 'arbiter', - }); - - expect(handoff).toMatchObject({ - source_service_id: CODEX_MAIN_SERVICE_ID, - target_service_id: ARBITER_SERVICE_ID, - source_role: 'owner', - target_role: 'arbiter', - target_agent_type: 'codex', - }); - }); }); diff --git a/src/claude-usage-backoff.test.ts b/src/claude-usage-backoff.test.ts index de22456..af179dd 100644 --- a/src/claude-usage-backoff.test.ts +++ b/src/claude-usage-backoff.test.ts @@ -148,3 +148,38 @@ describe('Claude usage 429 Retry-After backoff', () => { expect(resumed!.usageRateLimited).toBe(false); }); }); + +describe('getCachedClaudeUsageLimitResetAt', () => { + it('returns the later reset of the exhausted windows', async () => { + readJsonFileMock.mockReturnValue({ + 'account-0': { + fetchedAt: 1, + usage: { + five_hour: { utilization: 100, resets_at: '2026-10-01T12:00:00Z' }, + seven_day: { utilization: 0.4, resets_at: '2026-10-05T00:00:00Z' }, + }, + }, + }); + const { getCachedClaudeUsageLimitResetAt } = + await import('./claude-usage.js'); + expect( + getCachedClaudeUsageLimitResetAt(Date.parse('2026-10-01T10:00:00Z')), + ).toEqual(new Date('2026-10-01T12:00:00Z')); + }); + + it('returns null when no window is exhausted', async () => { + readJsonFileMock.mockReturnValue({ + 'account-0': { + fetchedAt: 1, + usage: { + five_hour: { utilization: 42, resets_at: '2026-10-01T12:00:00Z' }, + }, + }, + }); + const { getCachedClaudeUsageLimitResetAt } = + await import('./claude-usage.js'); + expect( + getCachedClaudeUsageLimitResetAt(Date.parse('2026-10-01T10:00:00Z')), + ).toBeNull(); + }); +}); diff --git a/src/claude-usage-limit.test.ts b/src/claude-usage-limit.test.ts new file mode 100644 index 0000000..9902ab8 --- /dev/null +++ b/src/claude-usage-limit.test.ts @@ -0,0 +1,111 @@ +import { describe, expect, it, vi } from 'vitest'; + +vi.mock('./config.js', () => ({ + DATA_DIR: '/tmp/ejclaw-usage-limit-test', + TIMEZONE: 'Asia/Seoul', +})); + +const { cachedResetAt } = vi.hoisted(() => ({ + cachedResetAt: vi.fn<() => Date | null>(() => null), +})); +vi.mock('./claude-usage.js', () => ({ + getCachedClaudeUsageLimitResetAt: cachedResetAt, +})); + +import { + buildClaudeUsageLimitMessage, + formatClaudeUsageLimitMessage, + isClaudeUsageLimitReason, + parseClaudeLimitResetTime, +} from './claude-usage-limit.js'; + +// 2026-10-01 19:00 KST +const NOW = Date.parse('2026-10-01T10:00:00Z'); + +describe('parseClaudeLimitResetTime', () => { + it('reads a same-day banner time in the named zone', () => { + expect( + parseClaudeLimitResetTime( + "You've hit your limit · resets 9:40pm (Asia/Seoul)", + NOW, + )?.toISOString(), + ).toBe('2026-10-01T12:40:00.000Z'); + }); + + it('rolls a banner time that already passed today over to tomorrow', () => { + expect( + parseClaudeLimitResetTime( + "You're out of extra usage · resets 4am (Asia/Seoul)", + NOW, + )?.toISOString(), + ).toBe('2026-10-01T19:00:00.000Z'); + }); + + it('reads a banner with a date', () => { + expect( + parseClaudeLimitResetTime( + "You've hit your limit · resets Oct 3, 1pm (Asia/Seoul)", + NOW, + )?.toISOString(), + ).toBe('2026-10-03T04:00:00.000Z'); + }); + + it('reads an ISO reset timestamp', () => { + expect( + parseClaudeLimitResetTime( + 'rate limited; resets_at=2026-10-01T13:30:00Z', + NOW, + )?.toISOString(), + ).toBe('2026-10-01T13:30:00.000Z'); + }); + + it('returns null without a reset time', () => { + expect( + parseClaudeLimitResetTime('API Error: 429 rate_limit_error', NOW), + ).toBeNull(); + expect(parseClaudeLimitResetTime(null, NOW)).toBeNull(); + }); +}); + +describe('Claude usage limit message', () => { + it('shows HH:mm for a reset later today and the date otherwise', () => { + expect( + formatClaudeUsageLimitMessage(new Date('2026-10-01T12:40:00Z'), NOW), + ).toBe('Claude 사용 한도에 도달했습니다. 21:40에 재개할 수 있습니다.'); + expect( + formatClaudeUsageLimitMessage(new Date('2026-10-01T19:00:00Z'), NOW), + ).toBe( + 'Claude 사용 한도에 도달했습니다. 10월 2일 04:00에 재개할 수 있습니다.', + ); + }); + + it('asks to retry later without a reset time', () => { + expect(formatClaudeUsageLimitMessage(null, NOW)).toBe( + 'Claude 사용 한도에 도달했습니다. 잠시 후 다시 시도해 주세요.', + ); + }); + + it('falls back to the cached usage reset time', () => { + cachedResetAt.mockReturnValueOnce(new Date('2026-10-01T11:15:00Z')); + expect(buildClaudeUsageLimitMessage('API Error: 429', NOW)).toBe( + 'Claude 사용 한도에 도달했습니다. 20:15에 재개할 수 있습니다.', + ); + }); + + it('prefers the reset time in the error text', () => { + cachedResetAt.mockReturnValueOnce(new Date('2026-10-01T11:15:00Z')); + expect( + buildClaudeUsageLimitMessage( + "You've hit your limit · resets 9:40pm (Asia/Seoul)", + NOW, + ), + ).toBe('Claude 사용 한도에 도달했습니다. 21:40에 재개할 수 있습니다.'); + }); + + it('treats only rate-limit and usage-exhausted triggers as usage limits', () => { + expect(isClaudeUsageLimitReason('429')).toBe(true); + expect(isClaudeUsageLimitReason('usage-exhausted')).toBe(true); + expect(isClaudeUsageLimitReason('auth-expired')).toBe(false); + expect(isClaudeUsageLimitReason('overloaded')).toBe(false); + }); +}); diff --git a/src/claude-usage-limit.ts b/src/claude-usage-limit.ts new file mode 100644 index 0000000..ac7bd44 --- /dev/null +++ b/src/claude-usage-limit.ts @@ -0,0 +1,223 @@ +/** + * User-facing notice for a Claude run that hit the account usage limit. + * + * There is a single Claude account and no fallback provider, so the room is + * told when Claude becomes available again instead of the work being handed + * off or retried silently. + */ + +import type { AgentTriggerReason } from './agent-error-detection.js'; +import { getCachedClaudeUsageLimitResetAt } from './claude-usage.js'; +import { TIMEZONE } from './config.js'; + +const LIMIT_PREFIX = 'Claude 사용 한도에 도달했습니다.'; +const RETRY_LATER = '잠시 후 다시 시도해 주세요.'; + +const MONTHS: Record = { + jan: 1, + feb: 2, + mar: 3, + apr: 4, + may: 5, + jun: 6, + jul: 7, + aug: 8, + sep: 9, + oct: 10, + nov: 11, + dec: 12, +}; + +/** Trigger reasons that mean "the Claude account is out of usage". */ +export function isClaudeUsageLimitReason(reason: AgentTriggerReason): boolean { + return reason === '429' || reason === 'usage-exhausted'; +} + +function isValidTimeZone(timeZone: string): boolean { + try { + new Intl.DateTimeFormat('en-US', { timeZone }); + return true; + } catch { + return false; + } +} + +function zonedParts( + instantMs: number, + timeZone: string, +): { year: number; month: number; day: number; hour: number; minute: number } { + const parts = new Intl.DateTimeFormat('en-US', { + timeZone, + hourCycle: 'h23', + year: 'numeric', + month: 'numeric', + day: 'numeric', + hour: 'numeric', + minute: 'numeric', + }).formatToParts(new Date(instantMs)); + const get = (type: string) => + Number(parts.find((part) => part.type === type)?.value ?? 0); + return { + year: get('year'), + month: get('month'), + day: get('day'), + hour: get('hour'), + minute: get('minute'), + }; +} + +/** UTC instant of a wall-clock time in `timeZone`. */ +function zonedTimeToUtc( + wall: { + year: number; + month: number; + day: number; + hour: number; + minute: number; + }, + timeZone: string, +): number { + const asUtc = Date.UTC( + wall.year, + wall.month - 1, + wall.day, + wall.hour, + wall.minute, + ); + const shown = zonedParts(asUtc, timeZone); + const offset = + Date.UTC(shown.year, shown.month - 1, shown.day, shown.hour, shown.minute) - + asUtc; + return asUtc - offset; +} + +function addDays( + wall: { year: number; month: number; day: number }, + days: number, +): { year: number; month: number; day: number } { + const date = new Date(Date.UTC(wall.year, wall.month - 1, wall.day + days)); + return { + year: date.getUTCFullYear(), + month: date.getUTCMonth() + 1, + day: date.getUTCDate(), + }; +} + +/** + * Claude CLI banner: "You've hit your limit · resets 9:40pm (Asia/Seoul)", + * optionally with a date ("resets Oct 2, 4am (Asia/Seoul)"). The time is in + * the named zone (the service timezone when none is given); without a date it + * is the next occurrence of that clock time. + */ +function parseBannerResetTime(text: string, nowMs: number): Date | null { + const match = text.match( + /resets?\s+(?:at\s+)?(?:([a-z]{3})[a-z]*\.?\s+(\d{1,2})(?:st|nd|rd|th)?,?\s+(?:at\s+)?)?(\d{1,2})(?::(\d{2}))?\s*(am|pm)\b(?:\s*\(([^)]+)\))?/i, + ); + if (!match) return null; + const [, monthName, dayText, hourText, minuteText, meridiem, zoneText] = + match; + const timeZone = + zoneText && isValidTimeZone(zoneText.trim()) ? zoneText.trim() : TIMEZONE; + + let hour = Number(hourText) % 12; + if (meridiem.toLowerCase() === 'pm') hour += 12; + const minute = minuteText ? Number(minuteText) : 0; + if (hour > 23 || minute > 59) return null; + + const today = zonedParts(nowMs, timeZone); + if (monthName && dayText) { + const month = MONTHS[monthName.toLowerCase()]; + if (!month) return null; + let resetMs = zonedTimeToUtc( + { year: today.year, month, day: Number(dayText), hour, minute }, + timeZone, + ); + if (resetMs <= nowMs) { + resetMs = zonedTimeToUtc( + { year: today.year + 1, month, day: Number(dayText), hour, minute }, + timeZone, + ); + } + return new Date(resetMs); + } + + let resetMs = zonedTimeToUtc({ ...today, hour, minute }, timeZone); + if (resetMs <= nowMs) { + resetMs = zonedTimeToUtc({ ...addDays(today, 1), hour, minute }, timeZone); + } + return new Date(resetMs); +} + +/** "try again at Mar 26th, 2026 9:00 AM" / "resets at Mar 26, 2026 9:00 AM". */ +function parseFullDateResetTime(text: string): Date | null { + const match = text.match( + /(?:try again at|resets?\s+(?:at\s+)?)\s*(\w+ \d{1,2}(?:st|nd|rd|th)?,?\s+\d{4}\s+\d{1,2}:\d{2}\s*(?:AM|PM)?)/i, + ); + if (!match) return null; + const ts = new Date( + match[1].replace(/(\d+)(?:st|nd|rd|th)/i, '$1'), + ).getTime(); + return Number.isNaN(ts) ? null : new Date(ts); +} + +/** An ISO-8601 timestamp in a message that talks about a reset. */ +function parseIsoResetTime(text: string): Date | null { + if (!/reset/i.test(text)) return null; + const match = text.match( + /\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})/, + ); + if (!match) return null; + const ts = Date.parse(match[0]); + return Number.isFinite(ts) ? new Date(ts) : null; +} + +/** Reset time named in a Claude limit error, or null when none is found. */ +export function parseClaudeLimitResetTime( + text: string | null | undefined, + nowMs: number = Date.now(), +): Date | null { + if (!text) return null; + const candidates = [ + parseFullDateResetTime(text), + parseIsoResetTime(text), + parseBannerResetTime(text, nowMs), + ]; + return candidates.find((date) => date && date.getTime() > nowMs) ?? null; +} + +function formatResetTime(resetAt: Date, nowMs: number): string { + const reset = zonedParts(resetAt.getTime(), TIMEZONE); + const today = zonedParts(nowMs, TIMEZONE); + const time = `${String(reset.hour).padStart(2, '0')}:${String( + reset.minute, + ).padStart(2, '0')}`; + const sameDay = + reset.year === today.year && + reset.month === today.month && + reset.day === today.day; + return sameDay ? time : `${reset.month}월 ${reset.day}일 ${time}`; +} + +export function formatClaudeUsageLimitMessage( + resetAt: Date | null, + nowMs: number = Date.now(), +): string { + if (!resetAt || resetAt.getTime() <= nowMs) { + return `${LIMIT_PREFIX} ${RETRY_LATER}`; + } + return `${LIMIT_PREFIX} ${formatResetTime(resetAt, nowMs)}에 재개할 수 있습니다.`; +} + +/** + * Notice for the room: the reset time comes from the error text, else from + * the cached usage API data, else the user is asked to retry later. + */ +export function buildClaudeUsageLimitMessage( + errorText: string | null | undefined, + nowMs: number = Date.now(), +): string { + const resetAt = + parseClaudeLimitResetTime(errorText, nowMs) ?? + getCachedClaudeUsageLimitResetAt(nowMs); + return formatClaudeUsageLimitMessage(resetAt, nowMs); +} diff --git a/src/claude-usage.ts b/src/claude-usage.ts index ff24365..288658c 100644 --- a/src/claude-usage.ts +++ b/src/claude-usage.ts @@ -115,6 +115,30 @@ function tokenSuffix(token: string): string { return token.slice(-8); } +function utilizationPct(utilization: number): number { + return utilization > 1 ? utilization : utilization * 100; +} + +/** + * Reset time of the exhausted usage window (5h or 7d, whichever ends later) + * from the last successful usage fetch, or null when no cached window is at + * 100% with a future reset. + */ +export function getCachedClaudeUsageLimitResetAt( + now: number = Date.now(), +): Date | null { + loadUsageDiskCache(); + const usage = usageDiskCache[USAGE_CACHE_KEY]?.usage; + let latest: number | null = null; + for (const window of [usage?.five_hour, usage?.seven_day]) { + if (!window || utilizationPct(window.utilization) < 100) continue; + const resetMs = Date.parse(window.resets_at); + if (!Number.isFinite(resetMs) || resetMs <= now) continue; + if (latest == null || resetMs > latest) latest = resetMs; + } + return latest == null ? null : new Date(latest); +} + // Rate limit: at most one API call per 5 minutes. // The 1-minute cadence existed for the 95% auto-paired-mode gate, which is no // longer wired into the runtime. The dashboard only needs coarse numbers, and diff --git a/src/config.ts b/src/config.ts index b052967..4574628 100644 --- a/src/config.ts +++ b/src/config.ts @@ -34,9 +34,6 @@ export function isReviewService(serviceId: string = SERVICE_ID): boolean { export const POLL_INTERVAL = CONFIG.runtime.pollInterval; export const SCHEDULER_POLL_INTERVAL = CONFIG.runtime.schedulerPollInterval; -/** Minimum time (ms) a failover lease stays active before Claude can reclaim it. */ -export const FAILOVER_MIN_DURATION_MS = CONFIG.runtime.failoverMinDurationMs; - export const SENDER_ALLOWLIST_PATH = CONFIG.paths.senderAllowlistPath; export const STORE_DIR = CONFIG.paths.storeDir; export const GROUPS_DIR = CONFIG.paths.groupsDir; diff --git a/src/config/load-config.ts b/src/config/load-config.ts index 7d206c5..301f399 100644 --- a/src/config/load-config.ts +++ b/src/config/load-config.ts @@ -66,7 +66,6 @@ function buildRoleModelConfig(envPrefix: string): RoleModelConfig { return { model: readNonEmptyText(`${envPrefix}_MODEL`), effort: readNonEmptyText(`${envPrefix}_EFFORT`), - fallbackEnabled: readText(`${envPrefix}_FALLBACK_ENABLED`) !== 'false', }; } @@ -171,7 +170,6 @@ export function loadConfig(): AppConfig { runtime: { pollInterval: 2000, schedulerPollInterval: 60000, - failoverMinDurationMs: 3 * 60 * 60 * 1000, agentTimeout: readInteger('AGENT_TIMEOUT', 1_800_000), agentMaxOutputSize: readInteger('AGENT_MAX_OUTPUT_SIZE', 10_485_760), ipcPollInterval: 1000, diff --git a/src/config/schema.ts b/src/config/schema.ts index 02d4692..d37b008 100644 --- a/src/config/schema.ts +++ b/src/config/schema.ts @@ -3,7 +3,6 @@ import type { AgentType } from '../types.js'; export interface RoleModelConfig { model?: string; effort?: string; - fallbackEnabled: boolean; } export interface AppConfig { @@ -32,7 +31,6 @@ export interface AppConfig { runtime: { pollInterval: number; schedulerPollInterval: number; - failoverMinDurationMs: number; agentTimeout: number; agentMaxOutputSize: number; ipcPollInterval: number; diff --git a/src/db.test.ts b/src/db.test.ts index 30bdfe2..87e8c64 100644 --- a/src/db.test.ts +++ b/src/db.test.ts @@ -11,16 +11,12 @@ import { _setMemoryTimestampsForTests, _setRegisteredGroupForTests, assignRoom, - claimServiceHandoff, - completeServiceHandoffAndAdvanceTargetCursor, createPairedTask, createTask, - createServiceHandoff, createProducedWorkItem, clearExplicitRoomMode, claimPairedTurnReservation, failPairedTurn, - failServiceHandoff, deleteSession, deleteTask, getAllChats, @@ -38,7 +34,6 @@ import { getNewMessagesBySeq, getOpenWorkItem, getOpenWorkItemForChat, - getPendingServiceHandoffs, recallMemories, getRegisteredAgentTypesForJid, getMessagesSince, @@ -3449,181 +3444,7 @@ describe('paired room registration', () => { }); }); -describe('service handoff completion', () => { - it('atomically completes the handoff and advances the target cursor', () => { - storeChatMetadata('dc:handoff', '2024-01-01T00:00:00.000Z'); - store({ - id: 'handoff-msg-1', - chat_jid: 'dc:handoff', - sender: 'user', - sender_name: 'User', - content: 'hello', - timestamp: '2024-01-01T00:00:01.000Z', - }); - const handoff = createServiceHandoff({ - chat_jid: 'dc:handoff', - group_folder: 'test-group', - source_service_id: 'claude', - target_service_id: 'codex-review', - target_agent_type: 'codex', - prompt: 'hello', - end_seq: 1, - }); - - expect(claimServiceHandoff(handoff.id)).toBe(true); - - const appliedCursor = completeServiceHandoffAndAdvanceTargetCursor({ - id: handoff.id, - chat_jid: 'dc:handoff', - end_seq: 1, - }); - - expect(appliedCursor).toBe('1'); - expect(getPendingServiceHandoffs('codex-review')).toEqual([]); - expect(JSON.parse(getRouterState('last_agent_seq') || '{}')).toMatchObject({ - 'dc:handoff': '1', - }); - }); - - it('does not move the target cursor backwards when a newer cursor already exists', () => { - storeChatMetadata('dc:handoff', '2024-01-01T00:00:00.000Z'); - setRouterState('last_agent_seq', JSON.stringify({ 'dc:handoff': '5' })); - const handoff = createServiceHandoff({ - chat_jid: 'dc:handoff', - group_folder: 'test-group', - source_service_id: 'claude', - target_service_id: 'codex-review', - target_agent_type: 'codex', - prompt: 'hello', - end_seq: 3, - }); - - expect(claimServiceHandoff(handoff.id)).toBe(true); - - const appliedCursor = completeServiceHandoffAndAdvanceTargetCursor({ - id: handoff.id, - chat_jid: 'dc:handoff', - end_seq: 3, - }); - - expect(appliedCursor).toBe('5'); - expect(JSON.parse(getRouterState('last_agent_seq') || '{}')).toMatchObject({ - 'dc:handoff': '5', - }); - }); - - it('stores the intended handoff role when provided', () => { - const handoff = createServiceHandoff({ - chat_jid: 'dc:handoff-role', - group_folder: 'test-group', - source_service_id: 'claude', - target_service_id: 'codex-review', - source_role: 'owner', - target_role: 'reviewer', - target_agent_type: 'codex', - prompt: 'please review', - reason: 'reviewer-claude-429', - intended_role: 'reviewer', - }); - - expect(handoff.intended_role).toBe('reviewer'); - expect(handoff.source_role).toBe('owner'); - expect(handoff.target_role).toBe('reviewer'); - expect(getPendingServiceHandoffs('codex-review')).toEqual([ - expect.objectContaining({ - id: handoff.id, - source_role: 'owner', - target_role: 'reviewer', - intended_role: 'reviewer', - reason: 'reviewer-claude-429', - }), - ]); - }); - - it('derives handoff service shadows from role and agent metadata when raw service ids are omitted', () => { - const handoff = createServiceHandoff({ - chat_jid: 'dc:handoff-derived-shadow', - group_folder: 'handoff-derived-shadow', - source_role: 'owner', - source_agent_type: 'codex', - target_role: 'reviewer', - target_agent_type: 'claude-code', - prompt: 'review this', - intended_role: 'reviewer', - }); - - expect(handoff).toMatchObject({ - source_service_id: CODEX_MAIN_SERVICE_ID, - target_service_id: CLAUDE_SERVICE_ID, - source_role: 'owner', - target_role: 'reviewer', - target_agent_type: 'claude-code', - }); - }); - - it('stores handoff cursors under the provided role-scoped cursor key', () => { - storeChatMetadata('dc:handoff-role-cursor', '2024-01-01T00:00:00.000Z'); - const handoff = createServiceHandoff({ - chat_jid: 'dc:handoff-role-cursor', - group_folder: 'test-group', - source_service_id: 'claude', - target_service_id: 'codex-review', - source_role: 'owner', - target_role: 'reviewer', - target_agent_type: 'codex', - prompt: 'hello reviewer', - end_seq: 7, - intended_role: 'reviewer', - }); - - expect(claimServiceHandoff(handoff.id)).toBe(true); - - const appliedCursor = completeServiceHandoffAndAdvanceTargetCursor({ - id: handoff.id, - chat_jid: 'dc:handoff-role-cursor', - cursor_key: 'dc:handoff-role-cursor:reviewer', - end_seq: 7, - }); - - expect(appliedCursor).toBe('7'); - expect(JSON.parse(getRouterState('last_agent_seq') || '{}')).toMatchObject({ - 'dc:handoff-role-cursor:reviewer': '7', - }); - }); - - it('derives owner handoff service ids as stable role-slot shadows when raw ids are omitted', () => { - assignRoom('dc:handoff-owner-shadow', { - name: 'Owner Handoff Shadow', - roomMode: 'tribunal', - ownerAgentType: 'codex', - folder: 'owner-handoff-shadow', - }); - - const handoff = createServiceHandoff({ - chat_jid: 'dc:handoff-owner-shadow', - group_folder: 'owner-handoff-shadow', - source_role: 'owner', - target_role: 'owner', - source_agent_type: 'codex', - target_agent_type: 'codex', - prompt: 'owner fallback', - reason: 'claude-usage-exhausted', - intended_role: 'owner', - }); - - expect(handoff.source_service_id).toBe(CODEX_MAIN_SERVICE_ID); - expect(handoff.target_service_id).toBe(CODEX_MAIN_SERVICE_ID); - expect(getPendingServiceHandoffs(CODEX_MAIN_SERVICE_ID)).toEqual([ - expect.objectContaining({ - id: handoff.id, - source_service_id: CODEX_MAIN_SERVICE_ID, - target_service_id: CODEX_MAIN_SERVICE_ID, - source_role: 'owner', - target_role: 'owner', - }), - ]); - }); - +describe('legacy service handoff rows', () => { it('preserves stored owner handoff service ids during init when service id columns already exist', () => { const tempDir = fs.mkdtempSync('/tmp/ejclaw-handoff-shadow-'); const dbPath = path.join(tempDir, 'messages.db'); @@ -3730,7 +3551,15 @@ describe('service handoff completion', () => { _initTestDatabaseFromFile(dbPath); - expect(getPendingServiceHandoffs(CODEX_REVIEW_SERVICE_ID)).toEqual([ + const rawDb = new Database(dbPath); + const storedHandoffs = rawDb + .prepare( + `SELECT chat_jid, source_service_id, target_service_id, source_role, target_role + FROM service_handoffs`, + ) + .all(); + rawDb.close(); + expect(storedHandoffs).toEqual([ expect.objectContaining({ chat_jid: 'dc:handoff-owner-shadow', source_service_id: CLAUDE_SERVICE_ID, @@ -3873,137 +3702,6 @@ describe('service handoff completion', () => { ); }); - it('fails fast when a service handoff row loses canonical target metadata after init', () => { - const tempDir = fs.mkdtempSync('/tmp/ejclaw-handoff-strict-read-'); - const dbPath = path.join(tempDir, 'messages.db'); - - try { - const fileDb = new Database(dbPath); - initializeDatabaseSchema(fileDb); - fileDb.close(); - - _initTestDatabaseFromFile(dbPath); - const handoff = createServiceHandoff({ - chat_jid: 'dc:handoff-strict-read', - group_folder: 'handoff-strict-read', - source_service_id: CLAUDE_SERVICE_ID, - target_service_id: CODEX_REVIEW_SERVICE_ID, - source_role: 'owner', - target_role: 'reviewer', - source_agent_type: 'claude-code', - target_agent_type: 'codex', - prompt: 'strict read handoff', - intended_role: 'reviewer', - }); - - const rawDb = new Database(dbPath); - rawDb - .prepare( - `UPDATE service_handoffs - SET target_agent_type = '' - WHERE id = ?`, - ) - .run(handoff.id); - rawDb.close(); - - expect(() => getPendingServiceHandoffs(CODEX_REVIEW_SERVICE_ID)).toThrow( - /cannot read target_agent_type from stored row metadata/, - ); - } finally { - fs.rmSync(tempDir, { recursive: true, force: true }); - _initTestDatabase(); - } - }); - - it('preserves an explicit reviewer target service id when creating a new handoff', () => { - const handoff = createServiceHandoff({ - chat_jid: 'dc:handoff-stored-reviewer', - group_folder: 'handoff-stored-reviewer', - paired_task_id: 'task-stored-reviewer-handoff', - paired_task_updated_at: '2026-04-10T00:00:00.000Z', - turn_intent_kind: 'reviewer-turn', - turn_role: 'reviewer', - source_service_id: CLAUDE_SERVICE_ID, - target_service_id: 'stale-reviewer-shadow', - source_role: 'owner', - target_role: 'reviewer', - source_agent_type: 'claude-code', - target_agent_type: 'codex', - prompt: 'stored reviewer service id', - intended_role: 'reviewer', - }); - - expect(handoff.target_service_id).toBe('stale-reviewer-shadow'); - expect(handoff.turn_id).toBe( - 'task-stored-reviewer-handoff:2026-04-10T00:00:00.000Z:reviewer-turn', - ); - expect(handoff.turn_attempt_no).toBe(1); - expect(handoff.turn_role).toBe('reviewer'); - expect( - getPairedTurnById( - 'task-stored-reviewer-handoff:2026-04-10T00:00:00.000Z:reviewer-turn', - ), - ).toMatchObject({ - turn_id: - 'task-stored-reviewer-handoff:2026-04-10T00:00:00.000Z:reviewer-turn', - task_id: 'task-stored-reviewer-handoff', - role: 'reviewer', - intent_kind: 'reviewer-turn', - state: 'delegated', - executor_service_id: 'stale-reviewer-shadow', - executor_agent_type: 'codex', - }); - expect(getPendingServiceHandoffs('stale-reviewer-shadow')).toEqual([ - expect.objectContaining({ - id: handoff.id, - paired_task_id: 'task-stored-reviewer-handoff', - paired_task_updated_at: '2026-04-10T00:00:00.000Z', - turn_id: - 'task-stored-reviewer-handoff:2026-04-10T00:00:00.000Z:reviewer-turn', - turn_attempt_no: 1, - turn_intent_kind: 'reviewer-turn', - turn_role: 'reviewer', - source_service_id: CLAUDE_SERVICE_ID, - target_service_id: 'stale-reviewer-shadow', - source_role: 'owner', - target_role: 'reviewer', - }), - ]); - }); - - it('marks a delegated logical turn failed when its handoff fails', () => { - const handoff = createServiceHandoff({ - chat_jid: 'dc:handoff-failed-turn', - group_folder: 'handoff-failed-turn', - paired_task_id: 'task-failed-reviewer-handoff', - paired_task_updated_at: '2026-04-10T00:00:00.000Z', - turn_intent_kind: 'reviewer-turn', - turn_role: 'reviewer', - source_service_id: CLAUDE_SERVICE_ID, - target_service_id: CODEX_REVIEW_SERVICE_ID, - source_role: 'owner', - target_role: 'reviewer', - source_agent_type: 'claude-code', - target_agent_type: 'codex', - prompt: 'failed reviewer handoff', - intended_role: 'reviewer', - }); - - failServiceHandoff(handoff.id, 'Group not registered on target service'); - - expect( - getPairedTurnById( - 'task-failed-reviewer-handoff:2026-04-10T00:00:00.000Z:reviewer-turn', - ), - ).toMatchObject({ - turn_id: - 'task-failed-reviewer-handoff:2026-04-10T00:00:00.000Z:reviewer-turn', - state: 'failed', - last_error: 'Group not registered on target service', - }); - expect(getPendingServiceHandoffs(CODEX_REVIEW_SERVICE_ID)).toEqual([]); - }); - it('records queued and running logical turn state across reservation and lease claims', () => { const task: PairedTask = { id: 'task-paired-turn-state', @@ -4095,133 +3793,6 @@ describe('service handoff completion', () => { } }); - it('records execution attempt history across delegated failure and retry', () => { - const task: PairedTask = { - id: 'task-paired-turn-attempt-history', - chat_jid: 'group@test', - group_folder: 'test-group', - owner_service_id: CLAUDE_SERVICE_ID, - reviewer_service_id: CODEX_REVIEW_SERVICE_ID, - owner_agent_type: 'claude-code', - reviewer_agent_type: 'codex', - arbiter_agent_type: null, - title: null, - source_ref: 'HEAD', - plan_notes: null, - review_requested_at: '2026-04-10T00:00:00.000Z', - round_trip_count: 1, - status: 'review_ready' as const, - arbiter_verdict: null, - arbiter_requested_at: null, - completion_reason: null, - created_at: '2026-04-10T00:00:00.000Z', - updated_at: '2026-04-10T00:00:00.000Z', - }; - createPairedTask(task); - - expect( - reservePairedTurnReservation({ - chatJid: task.chat_jid, - taskId: task.id, - taskStatus: task.status, - roundTripCount: task.round_trip_count, - taskUpdatedAt: task.updated_at, - intentKind: 'reviewer-turn', - runId: 'run-attempt-history-queued-1', - }), - ).toBe(true); - expect( - claimPairedTurnReservation({ - chatJid: task.chat_jid, - taskId: task.id, - taskStatus: task.status, - roundTripCount: task.round_trip_count, - taskUpdatedAt: task.updated_at, - intentKind: 'reviewer-turn', - runId: 'run-attempt-history-running-1', - }), - ).toBe(true); - - const handoff = createServiceHandoff({ - chat_jid: task.chat_jid, - group_folder: task.group_folder, - paired_task_id: task.id, - paired_task_updated_at: task.updated_at, - turn_intent_kind: 'reviewer-turn', - turn_role: 'reviewer', - source_service_id: CLAUDE_SERVICE_ID, - target_service_id: CODEX_REVIEW_SERVICE_ID, - source_role: 'owner', - target_role: 'reviewer', - source_agent_type: 'claude-code', - target_agent_type: 'codex', - prompt: 'retry reviewer via delegated handoff', - intended_role: 'reviewer', - }); - - failServiceHandoff(handoff.id, 'delegated reviewer handoff failed'); - releasePairedTaskExecutionLease({ - taskId: task.id, - runId: 'run-attempt-history-running-1', - }); - - expect( - reservePairedTurnReservation({ - chatJid: task.chat_jid, - taskId: task.id, - taskStatus: task.status, - roundTripCount: task.round_trip_count, - taskUpdatedAt: task.updated_at, - intentKind: 'reviewer-turn', - runId: 'run-attempt-history-queued-2', - }), - ).toBe(true); - expect( - claimPairedTurnReservation({ - chatJid: task.chat_jid, - taskId: task.id, - taskStatus: task.status, - roundTripCount: task.round_trip_count, - taskUpdatedAt: task.updated_at, - intentKind: 'reviewer-turn', - runId: 'run-attempt-history-running-2', - }), - ).toBe(true); - - expect( - getPairedTurnAttempts(`${task.id}:${task.updated_at}:reviewer-turn`), - ).toMatchObject([ - { - attempt_no: 1, - parent_handoff_id: null, - continuation_handoff_id: handoff.id, - task_id: task.id, - task_updated_at: task.updated_at, - role: 'reviewer', - intent_kind: 'reviewer-turn', - state: 'failed', - executor_service_id: CODEX_REVIEW_SERVICE_ID, - executor_agent_type: 'codex', - last_error: 'delegated reviewer handoff failed', - }, - { - attempt_no: 2, - parent_handoff_id: handoff.id, - task_id: task.id, - task_updated_at: task.updated_at, - role: 'reviewer', - intent_kind: 'reviewer-turn', - state: 'running', - executor_service_id: normalizeServiceId(SERVICE_ID), - executor_agent_type: - normalizeServiceId(SERVICE_ID) === CLAUDE_SERVICE_ID - ? 'claude-code' - : 'codex', - last_error: null, - }, - ]); - }); - it('reopens a completed reservation from the latest failed attempt even when paired_turns state is stale', () => { const tempDir = fs.mkdtempSync('/tmp/ejclaw-paired-turn-failed-reopen-'); const dbPath = path.join(tempDir, 'messages.db'); @@ -4352,316 +3923,6 @@ describe('service handoff completion', () => { } }); - it('keeps delegated continuation on attempt 1 even when paired_turns attempt_no is stale', () => { - const tempDir = fs.mkdtempSync( - '/tmp/ejclaw-paired-turn-attempt-cache-drift-', - ); - const dbPath = path.join(tempDir, 'messages.db'); - - try { - _initTestDatabaseFromFile(dbPath); - - const task: PairedTask = { - id: 'task-paired-turn-attempt-cache-drift', - chat_jid: 'group@test', - group_folder: 'test-group', - owner_service_id: CLAUDE_SERVICE_ID, - reviewer_service_id: CODEX_REVIEW_SERVICE_ID, - owner_agent_type: 'claude-code', - reviewer_agent_type: 'codex', - arbiter_agent_type: null, - title: null, - source_ref: 'HEAD', - plan_notes: null, - review_requested_at: '2026-04-10T00:00:00.000Z', - round_trip_count: 1, - status: 'review_ready' as const, - arbiter_verdict: null, - arbiter_requested_at: null, - completion_reason: null, - created_at: '2026-04-10T00:00:00.000Z', - updated_at: '2026-04-10T00:00:00.000Z', - }; - createPairedTask(task); - - expect( - reservePairedTurnReservation({ - chatJid: task.chat_jid, - taskId: task.id, - taskStatus: task.status, - roundTripCount: task.round_trip_count, - taskUpdatedAt: task.updated_at, - intentKind: 'reviewer-turn', - runId: 'run-attempt-cache-drift-queued-1', - }), - ).toBe(true); - expect( - claimPairedTurnReservation({ - chatJid: task.chat_jid, - taskId: task.id, - taskStatus: task.status, - roundTripCount: task.round_trip_count, - taskUpdatedAt: task.updated_at, - intentKind: 'reviewer-turn', - runId: 'run-attempt-cache-drift-running-1', - }), - ).toBe(true); - - const turnId = `${task.id}:${task.updated_at}:reviewer-turn`; - const rawDb = new Database(dbPath); - rawDb.exec( - `ALTER TABLE paired_turns ADD COLUMN attempt_no INTEGER NOT NULL DEFAULT 0`, - ); - rawDb - .prepare( - ` - UPDATE paired_turns - SET attempt_no = 99 - WHERE turn_id = ? - `, - ) - .run(turnId); - rawDb.close(); - - const handoff = createServiceHandoff({ - chat_jid: task.chat_jid, - group_folder: task.group_folder, - paired_task_id: task.id, - paired_task_updated_at: task.updated_at, - turn_intent_kind: 'reviewer-turn', - turn_role: 'reviewer', - source_service_id: CLAUDE_SERVICE_ID, - target_service_id: CODEX_REVIEW_SERVICE_ID, - source_role: 'owner', - target_role: 'reviewer', - source_agent_type: 'claude-code', - target_agent_type: 'codex', - prompt: 'delegate reviewer with stale aggregate attempt cache', - intended_role: 'reviewer', - }); - - expect(handoff.turn_attempt_no).toBe(1); - expect(getPairedTurnById(turnId)).toMatchObject({ - state: 'delegated', - attempt_no: 1, - executor_service_id: CODEX_REVIEW_SERVICE_ID, - }); - expect(getPairedTurnAttempts(turnId)).toMatchObject([ - { - attempt_no: 1, - continuation_handoff_id: handoff.id, - state: 'delegated', - executor_service_id: CODEX_REVIEW_SERVICE_ID, - executor_agent_type: 'codex', - }, - ]); - } finally { - fs.rmSync(tempDir, { recursive: true, force: true }); - _initTestDatabase(); - } - }); - - it('drops legacy next_parent_handoff_id scratch state on re-init and keeps retry lineage on attempt rows', () => { - const tempDir = fs.mkdtempSync('/tmp/ejclaw-attempt-parent-lineage-'); - const dbPath = path.join(tempDir, 'messages.db'); - - _initTestDatabaseFromFile(dbPath); - - const task: PairedTask = { - id: 'task-attempt-parent-lineage', - chat_jid: 'group@test', - group_folder: 'test-group', - owner_service_id: CLAUDE_SERVICE_ID, - reviewer_service_id: CODEX_REVIEW_SERVICE_ID, - owner_agent_type: 'claude-code', - reviewer_agent_type: 'codex', - arbiter_agent_type: null, - title: null, - source_ref: 'HEAD', - plan_notes: null, - review_requested_at: '2026-04-10T00:00:00.000Z', - round_trip_count: 1, - status: 'review_ready' as const, - arbiter_verdict: null, - arbiter_requested_at: null, - completion_reason: null, - created_at: '2026-04-10T00:00:00.000Z', - updated_at: '2026-04-10T00:00:00.000Z', - }; - createPairedTask(task); - - expect( - reservePairedTurnReservation({ - chatJid: task.chat_jid, - taskId: task.id, - taskStatus: task.status, - roundTripCount: task.round_trip_count, - taskUpdatedAt: task.updated_at, - intentKind: 'reviewer-turn', - runId: 'run-attempt-parent-lineage-queued-1', - }), - ).toBe(true); - expect( - claimPairedTurnReservation({ - chatJid: task.chat_jid, - taskId: task.id, - taskStatus: task.status, - roundTripCount: task.round_trip_count, - taskUpdatedAt: task.updated_at, - intentKind: 'reviewer-turn', - runId: 'run-attempt-parent-lineage-running-1', - }), - ).toBe(true); - - const handoff = createServiceHandoff({ - chat_jid: task.chat_jid, - group_folder: task.group_folder, - paired_task_id: task.id, - paired_task_updated_at: task.updated_at, - turn_intent_kind: 'reviewer-turn', - turn_role: 'reviewer', - source_service_id: CLAUDE_SERVICE_ID, - target_service_id: CODEX_REVIEW_SERVICE_ID, - source_role: 'owner', - target_role: 'reviewer', - source_agent_type: 'claude-code', - target_agent_type: 'codex', - prompt: 'derive retry parent from previous attempt row', - intended_role: 'reviewer', - }); - - failServiceHandoff(handoff.id, 'delegated reviewer handoff failed'); - releasePairedTaskExecutionLease({ - taskId: task.id, - runId: 'run-attempt-parent-lineage-running-1', - }); - - const turnId = `${task.id}:${task.updated_at}:reviewer-turn`; - const rawDb = new Database(dbPath); - rawDb.exec( - `ALTER TABLE paired_turns ADD COLUMN next_parent_handoff_id INTEGER`, - ); - rawDb - .prepare( - ` - UPDATE paired_turns - SET next_parent_handoff_id = ? - WHERE turn_id = ? - `, - ) - .run(handoff.id + 9999, turnId); - rawDb.close(); - - _initTestDatabaseFromFile(dbPath); - - const rebuiltDb = new Database(dbPath); - const pairedTurnColumns = rebuiltDb - .prepare(`PRAGMA table_info(paired_turns)`) - .all() as Array<{ name: string }>; - rebuiltDb.close(); - - expect( - pairedTurnColumns.some( - (column) => column.name === 'next_parent_handoff_id', - ), - ).toBe(false); - - expect( - reservePairedTurnReservation({ - chatJid: task.chat_jid, - taskId: task.id, - taskStatus: task.status, - roundTripCount: task.round_trip_count, - taskUpdatedAt: task.updated_at, - intentKind: 'reviewer-turn', - runId: 'run-attempt-parent-lineage-queued-2', - }), - ).toBe(true); - expect( - claimPairedTurnReservation({ - chatJid: task.chat_jid, - taskId: task.id, - taskStatus: task.status, - roundTripCount: task.round_trip_count, - taskUpdatedAt: task.updated_at, - intentKind: 'reviewer-turn', - runId: 'run-attempt-parent-lineage-running-2', - }), - ).toBe(true); - - expect(getPairedTurnAttempts(turnId)).toMatchObject([ - { - attempt_no: 1, - continuation_handoff_id: handoff.id, - state: 'failed', - }, - { - attempt_no: 2, - parent_handoff_id: handoff.id, - state: 'running', - }, - ]); - }); - - it('keeps attempt 1 when a delegated handoff continues on the target executor', () => { - const handoff = createServiceHandoff({ - chat_jid: 'dc:handoff-attempt-continuation', - group_folder: 'handoff-attempt-continuation', - paired_task_id: 'task-handoff-attempt-continuation', - paired_task_updated_at: '2026-04-10T00:00:00.000Z', - turn_intent_kind: 'reviewer-turn', - turn_role: 'reviewer', - source_service_id: CLAUDE_SERVICE_ID, - target_service_id: CODEX_REVIEW_SERVICE_ID, - source_role: 'owner', - target_role: 'reviewer', - source_agent_type: 'claude-code', - target_agent_type: 'codex', - prompt: 'continue delegated reviewer handoff', - intended_role: 'reviewer', - }); - - expect(handoff.turn_id).toBe( - 'task-handoff-attempt-continuation:2026-04-10T00:00:00.000Z:reviewer-turn', - ); - - markPairedTurnRunning({ - turnIdentity: { - turnId: handoff.turn_id!, - taskId: 'task-handoff-attempt-continuation', - taskUpdatedAt: '2026-04-10T00:00:00.000Z', - intentKind: 'reviewer-turn', - role: 'reviewer', - }, - executorServiceId: CODEX_REVIEW_SERVICE_ID, - executorAgentType: 'codex', - runId: 'run-handoff-continuation-1', - }); - - expect(getPairedTurnById(handoff.turn_id!)).toMatchObject({ - state: 'running', - attempt_no: 1, - executor_service_id: CODEX_REVIEW_SERVICE_ID, - executor_agent_type: 'codex', - }); - expect(getPairedTurnAttempts(handoff.turn_id!)).toMatchObject([ - { - attempt_no: 1, - parent_handoff_id: null, - continuation_handoff_id: handoff.id, - task_id: 'task-handoff-attempt-continuation', - task_updated_at: '2026-04-10T00:00:00.000Z', - role: 'reviewer', - intent_kind: 'reviewer-turn', - state: 'running', - executor_service_id: CODEX_REVIEW_SERVICE_ID, - executor_agent_type: 'codex', - active_run_id: 'run-handoff-continuation-1', - last_error: null, - }, - ]); - }); - it('drops legacy paired_turn active_run_id scratch state on re-init and keeps same-run continuation on attempt rows', () => { const tempDir = fs.mkdtempSync('/tmp/ejclaw-current-run-write-drift-'); const dbPath = path.join(tempDir, 'messages.db'); @@ -5151,150 +4412,6 @@ describe('service handoff completion', () => { } }); - it('keeps latest attempt hydration when a paired_turn aggregate current attempt lags the latest attempt row', () => { - const tempDir = fs.mkdtempSync('/tmp/ejclaw-current-attempt-drift-'); - const dbPath = path.join(tempDir, 'messages.db'); - - try { - _initTestDatabaseFromFile(dbPath); - - const task: PairedTask = { - id: 'task-current-attempt-drift', - chat_jid: 'group@test', - group_folder: 'test-group', - owner_service_id: CLAUDE_SERVICE_ID, - reviewer_service_id: CODEX_REVIEW_SERVICE_ID, - owner_agent_type: 'claude-code', - reviewer_agent_type: 'codex', - arbiter_agent_type: null, - title: null, - source_ref: 'HEAD', - plan_notes: null, - review_requested_at: '2026-04-10T00:00:00.000Z', - round_trip_count: 1, - status: 'review_ready' as const, - arbiter_verdict: null, - arbiter_requested_at: null, - completion_reason: null, - created_at: '2026-04-10T00:00:00.000Z', - updated_at: '2026-04-10T00:00:00.000Z', - }; - createPairedTask(task); - - expect( - reservePairedTurnReservation({ - chatJid: task.chat_jid, - taskId: task.id, - taskStatus: task.status, - roundTripCount: task.round_trip_count, - taskUpdatedAt: task.updated_at, - intentKind: 'reviewer-turn', - runId: 'run-current-attempt-drift-queued-1', - }), - ).toBe(true); - expect( - claimPairedTurnReservation({ - chatJid: task.chat_jid, - taskId: task.id, - taskStatus: task.status, - roundTripCount: task.round_trip_count, - taskUpdatedAt: task.updated_at, - intentKind: 'reviewer-turn', - runId: 'run-current-attempt-drift-running-1', - }), - ).toBe(true); - - const handoff = createServiceHandoff({ - chat_jid: task.chat_jid, - group_folder: task.group_folder, - paired_task_id: task.id, - paired_task_updated_at: task.updated_at, - turn_intent_kind: 'reviewer-turn', - turn_role: 'reviewer', - source_service_id: CLAUDE_SERVICE_ID, - target_service_id: CODEX_REVIEW_SERVICE_ID, - source_role: 'owner', - target_role: 'reviewer', - source_agent_type: 'claude-code', - target_agent_type: 'codex', - prompt: 'drift latest attempt row away from aggregate', - intended_role: 'reviewer', - }); - - failServiceHandoff(handoff.id, 'delegated reviewer handoff failed'); - releasePairedTaskExecutionLease({ - taskId: task.id, - runId: 'run-current-attempt-drift-running-1', - }); - - expect( - reservePairedTurnReservation({ - chatJid: task.chat_jid, - taskId: task.id, - taskStatus: task.status, - roundTripCount: task.round_trip_count, - taskUpdatedAt: task.updated_at, - intentKind: 'reviewer-turn', - runId: 'run-current-attempt-drift-queued-2', - }), - ).toBe(true); - expect( - claimPairedTurnReservation({ - chatJid: task.chat_jid, - taskId: task.id, - taskStatus: task.status, - roundTripCount: task.round_trip_count, - taskUpdatedAt: task.updated_at, - intentKind: 'reviewer-turn', - runId: 'run-current-attempt-drift-running-2', - }), - ).toBe(true); - - const turnId = `${task.id}:${task.updated_at}:reviewer-turn`; - const rawDb = new Database(dbPath); - rawDb.exec( - `ALTER TABLE paired_turns ADD COLUMN attempt_no INTEGER NOT NULL DEFAULT 0`, - ); - rawDb - .prepare( - ` - UPDATE paired_turns - SET attempt_no = 1 - WHERE turn_id = ? - `, - ) - .run(turnId); - rawDb.close(); - - _initTestDatabaseFromFile(dbPath); - - expect(getPairedTurnById(turnId)).toMatchObject({ - turn_id: turnId, - task_id: task.id, - task_updated_at: task.updated_at, - role: 'reviewer', - intent_kind: 'reviewer-turn', - state: 'running', - attempt_no: 2, - }); - expect(getPairedTurnAttempts(turnId)).toMatchObject([ - { - attempt_no: 1, - state: 'failed', - continuation_handoff_id: handoff.id, - }, - { - attempt_no: 2, - state: 'running', - active_run_id: 'run-current-attempt-drift-running-2', - }, - ]); - } finally { - fs.rmSync(tempDir, { recursive: true, force: true }); - _initTestDatabase(); - } - }); - it('keeps latest attempt hydration when a paired_turn aggregate state drifts from a running attempt row', () => { const tempDir = fs.mkdtempSync('/tmp/ejclaw-current-state-drift-'); const dbPath = path.join(tempDir, 'messages.db'); @@ -8619,109 +7736,6 @@ describe('message seq cursors', () => { { id: 'legacy-missing-seq', seq: 2 }, ]); }); - - it('creates new service handoffs after init on a legacy handoff schema', () => { - const tempDir = fs.mkdtempSync('/tmp/ejclaw-legacy-handoff-write-'); - const dbPath = path.join(tempDir, 'messages.db'); - const legacyDb = new Database(dbPath); - - legacyDb.exec(` - CREATE TABLE service_handoffs ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - chat_jid TEXT NOT NULL, - group_folder TEXT NOT NULL, - source_service_id TEXT NOT NULL, - target_service_id TEXT NOT NULL, - source_role TEXT, - target_role TEXT, - target_agent_type TEXT NOT NULL, - prompt TEXT NOT NULL, - status TEXT NOT NULL DEFAULT 'pending', - start_seq INTEGER, - end_seq INTEGER, - reason TEXT, - intended_role TEXT, - created_at TEXT NOT NULL DEFAULT (datetime('now')), - claimed_at TEXT, - completed_at TEXT, - last_error TEXT - ); - `); - legacyDb.close(); - - _initTestDatabaseFromFile(dbPath); - - const handoff = createServiceHandoff({ - chat_jid: 'dc:legacy-write-handoff', - group_folder: 'legacy-write-handoff', - source_service_id: CLAUDE_SERVICE_ID, - target_service_id: CODEX_REVIEW_SERVICE_ID, - source_role: 'owner', - target_role: 'reviewer', - target_agent_type: 'codex', - prompt: 'legacy handoff write', - intended_role: 'reviewer', - }); - - expect(handoff.target_service_id).toBe(CODEX_REVIEW_SERVICE_ID); - expect(getPendingServiceHandoffs(CODEX_REVIEW_SERVICE_ID)).toEqual([ - expect.objectContaining({ - id: handoff.id, - target_service_id: CODEX_REVIEW_SERVICE_ID, - }), - ]); - }); - - it('creates new service handoffs after init on a canonical handoff schema without service id columns', () => { - const tempDir = fs.mkdtempSync('/tmp/ejclaw-canonical-handoff-write-'); - const dbPath = path.join(tempDir, 'messages.db'); - const legacyDb = new Database(dbPath); - - legacyDb.exec(` - CREATE TABLE service_handoffs ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - chat_jid TEXT NOT NULL, - group_folder TEXT NOT NULL, - source_role TEXT, - source_agent_type TEXT, - target_role TEXT, - target_agent_type TEXT NOT NULL, - prompt TEXT NOT NULL, - status TEXT NOT NULL DEFAULT 'pending', - start_seq INTEGER, - end_seq INTEGER, - reason TEXT, - intended_role TEXT, - created_at TEXT NOT NULL DEFAULT (datetime('now')), - claimed_at TEXT, - completed_at TEXT, - last_error TEXT - ); - `); - legacyDb.close(); - - _initTestDatabaseFromFile(dbPath); - - const handoff = createServiceHandoff({ - chat_jid: 'dc:canonical-write-handoff', - group_folder: 'canonical-write-handoff', - source_role: 'owner', - source_agent_type: 'claude-code', - target_role: 'reviewer', - target_agent_type: 'codex', - prompt: 'canonical handoff write', - intended_role: 'reviewer', - }); - - expect(handoff.source_service_id).toBe(CLAUDE_SERVICE_ID); - expect(handoff.target_service_id).toBe(CODEX_REVIEW_SERVICE_ID); - expect(getPendingServiceHandoffs(CODEX_REVIEW_SERVICE_ID)).toEqual([ - expect.objectContaining({ - id: handoff.id, - target_service_id: CODEX_REVIEW_SERVICE_ID, - }), - ]); - }); }); describe('legacy schema writes after init', () => { diff --git a/src/db.ts b/src/db.ts index ebb7afe..b014e05 100644 --- a/src/db.ts +++ b/src/db.ts @@ -70,18 +70,12 @@ export { _clearPairedTurnReservationsForTests, cancelPairedTurn, claimPairedTurnReservation, - claimServiceHandoff, clearChannelOwnerLease, completePairedTurn, - completeServiceHandoff, - completeServiceHandoffAndAdvanceTargetCursor, createPairedTask, - createServiceHandoff, failPairedTurn, - failServiceHandoff, getAllOpenPairedTasks, getAllChannelOwnerLeases, - getAllPendingServiceHandoffs, getChannelOwnerLease, getLastBotFinalMessage, getLatestOpenPairedTaskForChat, @@ -98,7 +92,6 @@ export { getLatestPairedTurnForTask, updatePairedTurnProgressText, getPairedWorkspace, - getPendingServiceHandoffs, insertPairedTurnOutput, listPairedWorkspacesForTask, markPairedTurnRunning, @@ -129,4 +122,3 @@ export type { PairedTurnRecord } from './db/paired-turns.js'; export type { ChatInfo } from './db/messages.js'; export type { WorkItem } from './db/work-items.js'; export type { ChannelOwnerLeaseRow } from './db/channel-owner-leases.js'; -export type { ServiceHandoff } from './db/service-handoffs.js'; diff --git a/src/db/canonical-role-metadata.ts b/src/db/canonical-role-metadata.ts index 739927c..ab8f0cf 100644 --- a/src/db/canonical-role-metadata.ts +++ b/src/db/canonical-role-metadata.ts @@ -480,120 +480,6 @@ export function fillCanonicalServiceHandoffMetadata(input: { }; } -function readStoredHandoffAgentType(args: { - context: string; - field: 'source_agent_type' | 'target_agent_type'; - serviceField: 'source_service_id' | 'target_service_id'; - storedAgentType?: string | null; - storedServiceId?: string | null; -}): AgentType { - const persistedAgentType = normalizeStoredAgentType(args.storedAgentType); - const inferredAgentType = inferAgentTypeFromServiceShadow( - args.storedServiceId, - ); - if ( - persistedAgentType && - inferredAgentType && - persistedAgentType !== inferredAgentType - ) { - throw new Error( - `${args.context}: ${args.field} conflicts with ${args.serviceField}`, - ); - } - - if (persistedAgentType) { - return persistedAgentType; - } - - throw new Error( - `${args.context}: cannot read ${args.field} from stored row metadata`, - ); -} - -function readStoredHandoffServiceId(args: { - context: string; - field: 'source_service_id' | 'target_service_id'; - storedServiceId?: string | null; -}): string { - if (args.storedServiceId) { - return args.storedServiceId; - } - - throw new Error( - `${args.context}: cannot read ${args.field} from stored row metadata`, - ); -} - -export function readCanonicalServiceHandoffMetadata(input: { - id: number | string; - chat_jid: string; - source_service_id?: string | null; - target_service_id?: string | null; - source_role?: string | null; - target_role?: string | null; - intended_role?: string | null; - source_agent_type?: string | null; - target_agent_type?: string | null; -}): CanonicalServiceHandoffMetadata { - const context = `service_handoffs(${input.id})`; - const sourceRole = - normalizePairedRoomRoleOrNull(input.source_role) ?? - normalizePairedRoomRoleOrNull(input.intended_role); - const targetRole = - normalizePairedRoomRoleOrNull(input.target_role) ?? - normalizePairedRoomRoleOrNull(input.intended_role); - const sourceServiceId = readStoredHandoffServiceId({ - context, - field: 'source_service_id', - storedServiceId: input.source_service_id, - }); - const targetServiceId = readStoredHandoffServiceId({ - context, - field: 'target_service_id', - storedServiceId: input.target_service_id, - }); - const sourceAgentType = readStoredHandoffAgentType({ - context, - field: 'source_agent_type', - serviceField: 'source_service_id', - storedAgentType: input.source_agent_type, - storedServiceId: sourceServiceId, - }); - const targetAgentType = readStoredHandoffAgentType({ - context, - field: 'target_agent_type', - serviceField: 'target_service_id', - storedAgentType: input.target_agent_type, - storedServiceId: targetServiceId, - }); - - assertStoredRoleMatchesServiceShadow({ - context, - storedRole: sourceRole, - agentType: sourceAgentType, - serviceId: sourceServiceId, - roleField: 'source_role', - serviceField: 'source_service_id', - }); - assertStoredRoleMatchesServiceShadow({ - context, - storedRole: targetRole, - agentType: targetAgentType, - serviceId: targetServiceId, - roleField: 'target_role', - serviceField: 'target_service_id', - }); - - return { - sourceRole, - targetRole, - sourceAgentType, - targetAgentType, - sourceServiceId, - targetServiceId, - }; -} - interface ExecutionLeaseMetadataRow { rowid: number; role: string; diff --git a/src/db/paired-turn-attempts.ts b/src/db/paired-turn-attempts.ts index 10220d0..d6e3d68 100644 --- a/src/db/paired-turn-attempts.ts +++ b/src/db/paired-turn-attempts.ts @@ -591,29 +591,6 @@ export function getOwnerCodexBadRequestFailureSummaryForTaskFromDatabase( }; } -export function setPairedTurnAttemptContinuationHandoffIdInDatabase( - database: Database, - args: { - turnId: string; - attemptNo: number; - handoffId: number | null; - }, -): void { - if (args.attemptNo < 1) { - return; - } - database - .prepare( - ` - UPDATE paired_turn_attempts - SET continuation_handoff_id = ? - WHERE turn_id = ? - AND attempt_no = ? - `, - ) - .run(args.handoffId, args.turnId, args.attemptNo); -} - export function clearPairedTurnAttemptsInDatabase(database: Database): void { database.prepare('DELETE FROM paired_turn_attempts').run(); } diff --git a/src/db/runtime-paired.ts b/src/db/runtime-paired.ts index 2e0de67..e9317aa 100644 --- a/src/db/runtime-paired.ts +++ b/src/db/runtime-paired.ts @@ -1,4 +1,3 @@ -import { SERVICE_SESSION_SCOPE } from '../config.js'; import { type PairedTurnIdentity } from '../paired-turn-identity.js'; import { AgentType, @@ -69,18 +68,6 @@ import { type PairedTurnRecord, } from './paired-turns.js'; import { requireDatabase } from './runtime-database.js'; -import { - type CompleteServiceHandoffCursorInput, - type CreateServiceHandoffInput, - type ServiceHandoff, - claimServiceHandoffInDatabase, - completeServiceHandoffAndAdvanceTargetCursorInDatabase, - completeServiceHandoffInDatabase, - createServiceHandoffInDatabase, - failServiceHandoffInDatabase, - getAllPendingServiceHandoffsFromDatabase, - getPendingServiceHandoffsFromDatabase, -} from './service-handoffs.js'; export function upsertPairedProject(project: PairedProject): void { upsertPairedProjectInDatabase(requireDatabase(), project); @@ -326,46 +313,6 @@ export function clearChannelOwnerLease(chatJid: string): void { clearChannelOwnerLeaseInDatabase(requireDatabase(), chatJid); } -export function createServiceHandoff( - input: CreateServiceHandoffInput, -): ServiceHandoff { - return createServiceHandoffInDatabase(requireDatabase(), input); -} - -export function getPendingServiceHandoffs( - targetServiceId: string = SERVICE_SESSION_SCOPE, -): ServiceHandoff[] { - return getPendingServiceHandoffsFromDatabase( - requireDatabase(), - targetServiceId, - ); -} - -export function getAllPendingServiceHandoffs(): ServiceHandoff[] { - return getAllPendingServiceHandoffsFromDatabase(requireDatabase()); -} - -export function claimServiceHandoff(id: number): boolean { - return claimServiceHandoffInDatabase(requireDatabase(), id); -} - -export function completeServiceHandoff(id: number): void { - completeServiceHandoffInDatabase(requireDatabase(), id); -} - -export function failServiceHandoff(id: number, error: string): void { - failServiceHandoffInDatabase(requireDatabase(), id, error); -} - -export function completeServiceHandoffAndAdvanceTargetCursor( - input: CompleteServiceHandoffCursorInput, -): string | null { - return completeServiceHandoffAndAdvanceTargetCursorInDatabase( - requireDatabase(), - input, - ); -} - export function insertPairedTurnOutput( taskId: string, turnNumber: number, diff --git a/src/db/service-handoffs.ts b/src/db/service-handoffs.ts deleted file mode 100644 index 024b7b9..0000000 --- a/src/db/service-handoffs.ts +++ /dev/null @@ -1,480 +0,0 @@ -import { Database } from 'bun:sqlite'; - -import { - normalizeServiceId, - SERVICE_ID, - SERVICE_SESSION_SCOPE, -} from '../config.js'; -import { - buildPairedTurnIdentity, - type PairedTurnIdentity, -} from '../paired-turn-identity.js'; -import { AgentType, PairedRoomRole } from '../types.js'; -import { setPairedTurnAttemptContinuationHandoffIdInDatabase } from './paired-turn-attempts.js'; -import { - failPairedTurnInDatabase, - markPairedTurnDelegatedInDatabase, -} from './paired-turns.js'; -import { - getLatestMessageSeqAtOrBeforeFromDatabase, - normalizeSeqCursor, -} from './messages.js'; -import { - fillCanonicalServiceHandoffMetadata, - readCanonicalServiceHandoffMetadata, -} from './canonical-role-metadata.js'; -import { - getRouterStateFromDatabase, - setRouterStateInDatabase, -} from './router-state.js'; - -export interface ServiceHandoff { - id: number; - chat_jid: string; - group_folder: string; - paired_task_id?: string | null; - paired_task_updated_at?: string | null; - turn_id?: string | null; - turn_attempt_id?: string | null; - turn_attempt_no?: number | null; - turn_intent_kind?: PairedTurnIdentity['intentKind'] | null; - turn_role?: PairedRoomRole | null; - source_service_id: string; - target_service_id: string; - source_role: PairedRoomRole | null; - source_agent_type?: AgentType | null; - target_role: PairedRoomRole | null; - target_agent_type: AgentType; - prompt: string; - status: 'pending' | 'claimed' | 'completed' | 'failed'; - start_seq: number | null; - end_seq: number | null; - reason: string | null; - intended_role: PairedRoomRole | null; - created_at: string; - claimed_at: string | null; - completed_at: string | null; - last_error: string | null; -} - -export interface CreateServiceHandoffInput { - chat_jid: string; - group_folder: string; - paired_task_id?: string | null; - paired_task_updated_at?: string | null; - turn_id?: string | null; - turn_attempt_id?: string | null; - turn_intent_kind?: PairedTurnIdentity['intentKind'] | null; - turn_role?: PairedRoomRole | null; - source_service_id?: string; - target_service_id?: string; - source_role?: PairedRoomRole | null; - target_role?: PairedRoomRole | null; - source_agent_type?: AgentType | null; - target_agent_type: AgentType; - prompt: string; - start_seq?: number | null; - end_seq?: number | null; - reason?: string | null; - intended_role?: PairedRoomRole | null; -} - -export interface CompleteServiceHandoffCursorInput { - id: number; - chat_jid: string; - cursor_key?: string; - end_seq?: number | null; -} - -interface StoredServiceHandoffRow extends Omit< - ServiceHandoff, - | 'source_service_id' - | 'target_service_id' - | 'source_agent_type' - | 'target_agent_type' -> { - source_service_id?: string | null; - target_service_id?: string | null; - source_agent_type?: string | null; - target_agent_type: string; -} - -function hydrateStoredTurnIdentity( - row: Pick< - StoredServiceHandoffRow, - | 'paired_task_id' - | 'paired_task_updated_at' - | 'turn_id' - | 'turn_intent_kind' - | 'turn_role' - >, -): PairedTurnIdentity | null { - if ( - !row.paired_task_id || - !row.paired_task_updated_at || - !row.turn_intent_kind - ) { - return null; - } - - return buildPairedTurnIdentity({ - taskId: row.paired_task_id, - taskUpdatedAt: row.paired_task_updated_at, - intentKind: row.turn_intent_kind, - role: row.turn_role ?? undefined, - turnId: row.turn_id ?? undefined, - }); -} - -function hydrateServiceHandoffRow( - row: StoredServiceHandoffRow, -): ServiceHandoff { - const { - sourceRole, - targetRole, - sourceAgentType, - targetAgentType, - sourceServiceId, - targetServiceId, - } = readCanonicalServiceHandoffMetadata({ - id: row.id, - chat_jid: row.chat_jid, - source_service_id: row.source_service_id, - target_service_id: row.target_service_id, - source_role: row.source_role, - target_role: row.target_role, - intended_role: row.intended_role, - source_agent_type: row.source_agent_type, - target_agent_type: row.target_agent_type, - }); - const turnIdentity = hydrateStoredTurnIdentity(row); - - return { - ...row, - paired_task_id: turnIdentity?.taskId ?? row.paired_task_id ?? null, - paired_task_updated_at: - turnIdentity?.taskUpdatedAt ?? row.paired_task_updated_at ?? null, - turn_id: turnIdentity?.turnId ?? row.turn_id ?? null, - turn_attempt_id: row.turn_attempt_id ?? null, - turn_attempt_no: row.turn_attempt_no ?? null, - turn_intent_kind: turnIdentity?.intentKind ?? row.turn_intent_kind ?? null, - turn_role: turnIdentity?.role ?? row.turn_role ?? null, - source_role: sourceRole, - target_role: targetRole, - source_agent_type: sourceAgentType ?? null, - target_agent_type: targetAgentType, - source_service_id: sourceServiceId, - target_service_id: targetServiceId, - }; -} - -function getPendingServiceHandoffRows( - database: Database, -): StoredServiceHandoffRow[] { - return database - .prepare( - `SELECT * - FROM service_handoffs - WHERE status = 'pending' - ORDER BY created_at ASC, id ASC`, - ) - .all() as StoredServiceHandoffRow[]; -} - -function normalizeStoredLastAgentSeqCursor( - database: Database, - cursor: string | number | null | undefined, - chatJid: string, -): number { - if (typeof cursor === 'number') { - return Number.isFinite(cursor) && cursor > 0 ? cursor : 0; - } - if (!cursor) return 0; - const trimmed = cursor.trim(); - if (/^\d+$/.test(trimmed)) { - return normalizeSeqCursor(trimmed); - } - return getLatestMessageSeqAtOrBeforeFromDatabase(database, trimmed, chatJid); -} - -function parseLastAgentSeqState( - raw: string | undefined, - serviceId: string, -): Record { - if (!raw) return {}; - - let parsed: unknown; - try { - parsed = JSON.parse(raw); - } catch (err) { - throw new Error( - `Invalid last_agent_seq JSON for ${serviceId}: ${ - err instanceof Error ? err.message : String(err) - }`, - { cause: err }, - ); - } - - if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { - throw new Error( - `Invalid last_agent_seq JSON for ${serviceId}: not an object`, - ); - } - - const cursors: Record = {}; - for (const [chatJid, cursor] of Object.entries(parsed)) { - if (typeof cursor === 'string' || typeof cursor === 'number') { - cursors[chatJid] = String(cursor); - } - } - return cursors; -} - -export function createServiceHandoffInDatabase( - database: Database, - input: CreateServiceHandoffInput, -): ServiceHandoff { - const turnIdentity = - input.paired_task_id && - input.paired_task_updated_at && - input.turn_intent_kind - ? buildPairedTurnIdentity({ - taskId: input.paired_task_id, - taskUpdatedAt: input.paired_task_updated_at, - intentKind: input.turn_intent_kind, - role: input.turn_role ?? undefined, - turnId: input.turn_id ?? undefined, - }) - : null; - const { - sourceRole, - targetRole, - sourceAgentType, - targetAgentType, - sourceServiceId, - targetServiceId, - } = fillCanonicalServiceHandoffMetadata({ - id: 'new', - chat_jid: input.chat_jid, - source_service_id: input.source_service_id, - target_service_id: input.target_service_id, - source_role: input.source_role, - target_role: input.target_role, - intended_role: input.intended_role, - source_agent_type: input.source_agent_type, - target_agent_type: input.target_agent_type, - }); - - const currentAttempt = turnIdentity - ? markPairedTurnDelegatedInDatabase(database, { - turnIdentity, - executorServiceId: targetServiceId, - executorAgentType: targetAgentType, - }) - : undefined; - if (turnIdentity) { - if (!currentAttempt) { - throw new Error( - `paired_turns(${turnIdentity.turnId}) did not materialize a delegated attempt row`, - ); - } - } - const turnAttemptNo = currentAttempt?.attempt_no ?? null; - const turnAttemptId = currentAttempt?.attempt_id ?? null; - - database - .prepare( - `INSERT INTO service_handoffs ( - chat_jid, - group_folder, - paired_task_id, - paired_task_updated_at, - turn_id, - turn_attempt_id, - turn_attempt_no, - turn_intent_kind, - turn_role, - source_service_id, - target_service_id, - source_role, - source_agent_type, - target_role, - target_agent_type, - prompt, - start_seq, - end_seq, - reason, - intended_role - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, - ) - .run( - input.chat_jid, - input.group_folder, - turnIdentity?.taskId ?? null, - turnIdentity?.taskUpdatedAt ?? null, - turnIdentity?.turnId ?? null, - turnAttemptId, - turnAttemptNo, - turnIdentity?.intentKind ?? null, - turnIdentity?.role ?? null, - sourceServiceId, - targetServiceId, - sourceRole, - sourceAgentType ?? null, - targetRole, - targetAgentType, - input.prompt, - input.start_seq ?? null, - input.end_seq ?? null, - input.reason ?? null, - input.intended_role ?? null, - ); - - const lastId = ( - database.prepare('SELECT last_insert_rowid() as id').get() as { id: number } - ).id; - if (turnIdentity && currentAttempt) { - setPairedTurnAttemptContinuationHandoffIdInDatabase(database, { - turnId: turnIdentity.turnId, - attemptNo: currentAttempt.attempt_no, - handoffId: lastId, - }); - } - return hydrateServiceHandoffRow( - database - .prepare('SELECT * FROM service_handoffs WHERE id = ?') - .get(lastId) as StoredServiceHandoffRow, - ); -} - -export function getPendingServiceHandoffsFromDatabase( - database: Database, - targetServiceId: string = SERVICE_SESSION_SCOPE, -): ServiceHandoff[] { - return getPendingServiceHandoffRows(database) - .map((row) => hydrateServiceHandoffRow(row)) - .filter( - (handoff) => - normalizeServiceId(handoff.target_service_id) === - normalizeServiceId(targetServiceId), - ); -} - -export function getAllPendingServiceHandoffsFromDatabase( - database: Database, -): ServiceHandoff[] { - return getPendingServiceHandoffRows(database).map((row) => - hydrateServiceHandoffRow(row), - ); -} - -export function claimServiceHandoffInDatabase( - database: Database, - id: number, -): boolean { - database - .prepare( - `UPDATE service_handoffs - SET status = 'claimed', - claimed_at = datetime('now') - WHERE id = ? - AND status = 'pending'`, - ) - .run(id); - return ( - (database.prepare('SELECT changes() as c').get() as { c: number }).c > 0 - ); -} - -export function completeServiceHandoffInDatabase( - database: Database, - id: number, -): void { - database - .prepare( - `UPDATE service_handoffs - SET status = 'completed', - completed_at = datetime('now'), - last_error = NULL - WHERE id = ?`, - ) - .run(id); -} - -export function failServiceHandoffInDatabase( - database: Database, - id: number, - error: string, -): void { - database.transaction(() => { - const row = database - .prepare('SELECT * FROM service_handoffs WHERE id = ?') - .get(id) as StoredServiceHandoffRow | undefined; - let turnIdentity: PairedTurnIdentity | null = null; - if (row) { - try { - turnIdentity = hydrateStoredTurnIdentity(row); - } catch { - turnIdentity = null; - } - } - - database - .prepare( - `UPDATE service_handoffs - SET status = 'failed', - completed_at = datetime('now'), - last_error = ? - WHERE id = ?`, - ) - .run(error, id); - - if (turnIdentity) { - failPairedTurnInDatabase(database, { - turnIdentity, - error, - }); - } - })(); -} - -export function completeServiceHandoffAndAdvanceTargetCursorInDatabase( - database: Database, - input: CompleteServiceHandoffCursorInput, -): string | null { - return database.transaction(() => { - let appliedCursor: string | null = null; - - if (input.end_seq != null) { - const cursorKey = input.cursor_key ?? input.chat_jid; - const currentState = parseLastAgentSeqState( - getRouterStateFromDatabase(database, 'last_agent_seq', SERVICE_ID), - 'last_agent_seq', - ); - const existingSeq = normalizeStoredLastAgentSeqCursor( - database, - currentState[cursorKey], - input.chat_jid, - ); - currentState[cursorKey] = String(Math.max(existingSeq, input.end_seq)); - setRouterStateInDatabase( - database, - 'last_agent_seq', - JSON.stringify(currentState), - ); - appliedCursor = currentState[cursorKey]; - } - - database - .prepare( - `UPDATE service_handoffs - SET status = 'completed', - completed_at = datetime('now'), - last_error = NULL - WHERE id = ?`, - ) - .run(input.id); - - return appliedCursor; - })(); -} diff --git a/src/host-evidence.ts b/src/host-evidence.ts index 79a9a71..dd1b8a7 100644 --- a/src/host-evidence.ts +++ b/src/host-evidence.ts @@ -182,7 +182,6 @@ function buildRoleRuntimeConfigRole( modelConfig: { model?: string; effort?: string; - fallbackEnabled: boolean; }, serviceId: string | null, ): Record { @@ -194,7 +193,6 @@ function buildRoleRuntimeConfigRole( configured_model: modelConfig.model ?? null, effective_model: effectiveModelForAgentType(agentType, modelConfig.model), effort: modelConfig.effort ?? null, - fallback_enabled: modelConfig.fallbackEnabled, }; } diff --git a/src/index.ts b/src/index.ts index 569e01a..d4f3c56 100644 --- a/src/index.ts +++ b/src/index.ts @@ -55,7 +55,6 @@ import { import { startUsagePrimer } from './usage-primer.js'; import { Channel, NewMessage } from './types.js'; import { logger } from './logger.js'; -import { getCurrentClaudeToken } from './claude-oauth-token.js'; import { isBotMessageSourceKind, resolveInjectedMessageSourceKind, @@ -69,13 +68,8 @@ import { startTokenRefreshLoop, stopTokenRefreshLoop, } from './token-refresh.js'; -import { - clearGlobalFailover, - getGlobalFailoverInfo, -} from './service-routing.js'; import { resolveStartupFailureExitCode } from './startup-preconditions.js'; import { createRuntimeState } from './runtime-state.js'; -import { FAILOVER_MIN_DURATION_MS } from './config.js'; // Token rotation is initialized lazily on first use or at startup below @@ -261,14 +255,9 @@ async function main(): Promise { runtimeState.loadState(); // Graceful shutdown handlers - let leaseRecoveryTimer: ReturnType | null = null; const shutdown = async (signal: string) => { logger.info({ signal }, 'Shutdown signal received'); stopTokenRefreshLoop(); - if (leaseRecoveryTimer) { - clearInterval(leaseRecoveryTimer); - leaseRecoveryTimer = null; - } const roomBindings = runtimeState.getRoomBindings(); const interruptedGroups = queue .getStatuses(Object.keys(roomBindings)) @@ -505,22 +494,6 @@ async function main(): Promise { queue.setOnActivityChange(requestImmediateStatusUpdate); startUsagePrimer(); - leaseRecoveryTimer = setInterval(() => { - const failover = getGlobalFailoverInfo(); - if (!failover.active) return; - if (!getCurrentClaudeToken()) return; - const activatedMs = failover.activatedAt - ? new Date(failover.activatedAt).getTime() - : NaN; - if (Number.isNaN(activatedMs)) return; - const elapsed = Date.now() - activatedMs; - if (elapsed < FAILOVER_MIN_DURATION_MS) return; - clearGlobalFailover(); - logger.info( - { elapsedMin: Math.round(elapsed / 60_000) }, - 'Claude token available and hold period elapsed, global failover cleared', - ); - }, 5_000); runtime.startMessageLoop().catch((err) => { logger.fatal({ err }, 'Message loop crashed unexpectedly'); process.exit(1); diff --git a/src/message-agent-executor-handoff.ts b/src/message-agent-executor-handoff.ts deleted file mode 100644 index 1818afa..0000000 --- a/src/message-agent-executor-handoff.ts +++ /dev/null @@ -1,71 +0,0 @@ -import { getRoleModelConfig } from './config.js'; -import { createServiceHandoff } from './db.js'; -import type { AgentTriggerReason } from './agent-error-detection.js'; -import { resolveCodexFallbackHandoff } from './paired-turn-fallback.js'; -import { activateCodexFailover } from './service-routing.js'; -import type { PairedTurnIdentity } from './paired-turn-identity.js'; -import type { AgentType, PairedRoomRole, RegisteredGroup } from './types.js'; - -interface MessageAgentExecutorHandoffArgs { - activeRole: PairedRoomRole; - effectiveAgentType: AgentType; - hasReviewer: boolean; - reason: AgentTriggerReason; - sawVisibleOutput: boolean; - prompt: string; - startSeq?: number | null; - endSeq?: number | null; - chatJid: string; - group: RegisteredGroup; - pairedTurnIdentity?: PairedTurnIdentity; - markDelegated: () => void; - log: { - info: (obj: Record, msg: string) => void; - warn: (obj: Record, msg: string) => void; - }; -} - -export function handoffMessageAgentExecutionToCodex( - args: MessageAgentExecutorHandoffArgs, -): boolean { - const handoffResolution = resolveCodexFallbackHandoff({ - activeRole: args.activeRole, - effectiveAgentType: args.effectiveAgentType, - hasReviewer: args.hasReviewer, - fallbackEnabled: getRoleModelConfig(args.activeRole).fallbackEnabled, - reason: args.reason, - sawVisibleOutput: args.sawVisibleOutput, - prompt: args.prompt, - startSeq: args.startSeq, - endSeq: args.endSeq, - }); - - if (handoffResolution.type === 'none') { - return false; - } - - if (handoffResolution.type === 'skip') { - args.log.info({ reason: args.reason }, handoffResolution.logMessage); - return false; - } - - if (handoffResolution.plan.activateOwnerFailoverReason) { - activateCodexFailover( - args.chatJid, - handoffResolution.plan.activateOwnerFailoverReason, - ); - } - createServiceHandoff({ - chat_jid: args.chatJid, - group_folder: args.group.folder, - paired_task_id: args.pairedTurnIdentity?.taskId, - paired_task_updated_at: args.pairedTurnIdentity?.taskUpdatedAt, - turn_id: args.pairedTurnIdentity?.turnId, - turn_intent_kind: args.pairedTurnIdentity?.intentKind, - turn_role: args.pairedTurnIdentity?.role, - ...handoffResolution.plan.handoff, - }); - args.markDelegated(); - args.log.warn({ reason: args.reason }, handoffResolution.plan.logMessage); - return true; -} diff --git a/src/message-agent-executor-lifecycle.ts b/src/message-agent-executor-lifecycle.ts index a0e82da..601663f 100644 --- a/src/message-agent-executor-lifecycle.ts +++ b/src/message-agent-executor-lifecycle.ts @@ -34,6 +34,16 @@ function isRetryableCodexSessionFailureAttempt(args: { }); } +/** Best available error text of a failed attempt (for reset-time parsing). */ +function describeAttemptError(attempt: MessageAgentAttempt): string | null { + return ( + attempt.streamedTriggerReason?.message ?? + attempt.output?.error ?? + (attempt.error != null ? getErrorMessage(attempt.error) : null) ?? + null + ); +} + interface ExecuteMessageAgentAttemptLifecycleArgs { provider: 'claude' | 'codex'; runAttempt: (provider: 'claude' | 'codex') => Promise; @@ -42,10 +52,14 @@ interface ExecuteMessageAgentAttemptLifecycleArgs { clearStoredSession: () => void; clearRoleSdkSessions: () => void; sessionFolder: string; - maybeHandoffToCodex: ( - reason: AgentTriggerReason, - sawVisibleOutput: boolean, - ) => boolean; + /** + * Tell the room that Claude hit its usage limit and close the work. Returns + * false when the failure is not a usage limit. + */ + reportClaudeUsageLimit: (args: { + reason: AgentTriggerReason; + errorText: string | null; + }) => Promise; hasDirectTerminalDelivery: () => boolean; pairedExecutionLifecycle: Pick< PairedExecutionLifecycle, @@ -129,14 +143,16 @@ class MessageAgentAttemptLifecycleRunner { }); } - private maybeHandoffAfterError( + private async reportUsageLimitAfterError( reason: AgentTriggerReason, attempt: MessageAgentAttempt, - ): AttemptResult { - if (this.args.maybeHandoffToCodex(reason, attempt.sawVisibleOutput)) { - return 'success'; - } - return 'error'; + errorText?: string | null, + ): Promise { + const reported = await this.args.reportClaudeUsageLimit({ + reason, + errorText: errorText ?? describeAttemptError(attempt), + }); + return reported ? 'success' : 'error'; } private async retryClaudeAttemptIfNeeded( @@ -155,7 +171,11 @@ class MessageAgentAttemptLifecycleRunner { } if (retry.result === 'error') { - return this.maybeHandoffAfterError(retry.trigger.reason, attempt); + return this.reportUsageLimitAfterError( + retry.trigger.reason, + attempt, + retry.errorMessage, + ); } this.args.pairedExecutionLifecycle.markStatus('succeeded'); @@ -196,10 +216,7 @@ class MessageAgentAttemptLifecycleRunner { clearStoredSession(); log.warn('Fresh Claude retry also hit a retryable session failure'); log.error('Retryable Claude session failure persisted after fresh retry'); - return { - attempt: freshAttempt, - resolved: this.maybeHandoffAfterError('session-failure', freshAttempt), - }; + return { attempt: freshAttempt, resolved: 'error' }; } private async recoverRetryableCodexSessionFailure( @@ -303,7 +320,7 @@ class MessageAgentAttemptLifecycleRunner { } if (attempt.streamedTriggerReason) { - if (this.resolveStreamedTriggerHandoff(attempt)) { + if (await this.reportStreamedUsageLimit(attempt)) { return 'success'; } log.error( @@ -386,14 +403,16 @@ class MessageAgentAttemptLifecycleRunner { } } - private resolveStreamedTriggerHandoff(attempt: MessageAgentAttempt): boolean { + private async reportStreamedUsageLimit( + attempt: MessageAgentAttempt, + ): Promise { if (!attempt.streamedTriggerReason || !this.args.isClaudeCodeAgent) { return false; } - return this.args.maybeHandoffToCodex( - attempt.streamedTriggerReason.reason, - attempt.sawVisibleOutput, - ); + return this.args.reportClaudeUsageLimit({ + reason: attempt.streamedTriggerReason.reason, + errorText: describeAttemptError(attempt), + }); } private isSuccessWithoutVisibleOutput(attempt: MessageAgentAttempt): boolean { diff --git a/src/message-agent-executor-paired.ts b/src/message-agent-executor-paired.ts index 5d14694..47e62f5 100644 --- a/src/message-agent-executor-paired.ts +++ b/src/message-agent-executor-paired.ts @@ -166,7 +166,6 @@ export interface PairedExecutionLifecycle { attachments?: OutboundAttachment[], ): boolean; completeImmediately(args: { status: 'succeeded' | 'failed' }): void; - markDelegated(): void; markStatus(status: 'succeeded' | 'failed'): void; markSawOutput(sawOutput: boolean): void; getSummary(): string | null; @@ -202,7 +201,6 @@ class PairedExecutionLifecycleController implements PairedExecutionLifecycle { private pairedFinalAttachments: OutboundAttachment[] = []; private pairedSummaryLocked = false; private pairedExecutionCompleted = false; - private pairedExecutionDelegated = false; private pairedSawOutput = false; private pairedTurnOutputPersisted = false; private pairedTurnStateFinalized = false; @@ -276,10 +274,6 @@ class PairedExecutionLifecycleController implements PairedExecutionLifecycle { this.pairedExecutionCompleted = true; } - markDelegated(): void { - this.pairedExecutionDelegated = true; - } - markStatus(status: PairedExecutionStatus): void { this.pairedExecutionStatus = status; } @@ -299,10 +293,6 @@ class PairedExecutionLifecycleController implements PairedExecutionLifecycle { return; } - if (this.releaseDelegatedExecutionIfNeeded()) { - return; - } - const state = this.resolveFinalizeState(); this.completeStoredExecutionIfNeeded(state); this.finalizePairedTurnState( @@ -528,30 +518,6 @@ class PairedExecutionLifecycleController implements PairedExecutionLifecycle { return outputText; } - private releaseDelegatedExecutionIfNeeded(): boolean { - const { log, pairedExecutionContext, runId } = this.args; - if (!pairedExecutionContext || !this.pairedExecutionDelegated) { - return false; - } - try { - releasePairedTaskExecutionLease({ - taskId: pairedExecutionContext.task.id, - runId, - }); - } catch (err) { - log.warn( - { - pairedTaskId: pairedExecutionContext.task.id, - runId, - err, - }, - 'Failed to release paired execution lease for delegated fallback handoff', - ); - } - this.pairedExecutionCompleted = true; - return true; - } - private resolveFinalizeState(): FinalizeState { const directTerminalOutput = this.adoptDirectTerminalDeliveryIfNeeded(); const missingVisibleVerdict = this.resolveMissingVisibleVerdict(); diff --git a/src/message-agent-executor.test.ts b/src/message-agent-executor.test.ts index cf3aa0b..8efaa88 100644 --- a/src/message-agent-executor.test.ts +++ b/src/message-agent-executor.test.ts @@ -25,7 +25,6 @@ vi.mock('./config.js', () => ({ getRoleModelConfig: vi.fn(() => ({ model: undefined, effort: undefined, - fallbackEnabled: true, })), TIMEZONE: 'Asia/Seoul', })); @@ -51,13 +50,13 @@ vi.mock('./db.js', () => { return { completePairedTurn: vi.fn(), - createServiceHandoff: vi.fn(), failPairedTurn: vi.fn(), getAllTasks: vi.fn(() => []), getLastHumanMessageSender: vi.fn(() => null), getLatestOpenPairedTaskForChat: vi.fn(() => undefined), getLatestTurnNumber: vi.fn(() => 0), getPairedTaskById: vi.fn(() => undefined), + updatePairedTaskIfUnchanged: vi.fn(() => true), getPairedTurnAttempts: vi.fn(() => []), getPairedTurnOutputs: vi.fn(() => []), insertPairedTurnOutput: vi.fn(), @@ -96,8 +95,6 @@ vi.mock('./db.js', () => { }); vi.mock('./service-routing.js', () => ({ - activateCodexFailover: vi.fn(), - clearGlobalFailover: vi.fn(), getEffectiveChannelLease: vi.fn(() => ({ chat_jid: 'group@test', owner_agent_type: 'claude-code', @@ -119,16 +116,11 @@ vi.mock('./service-routing.js', () => ({ owner_agent_type?: 'claude-code' | 'codex'; reviewer_agent_type?: 'claude-code' | 'codex' | null; arbiter_agent_type?: 'claude-code' | 'codex' | null; - owner_failover_active?: boolean; }, role: 'owner' | 'reviewer' | 'arbiter', ) => { if (role === 'owner') { - return lease.owner_failover_active - ? lease.owner_service_id - : lease.owner_agent_type === 'codex' - ? 'codex-main' - : 'claude'; + return lease.owner_agent_type === 'codex' ? 'codex-main' : 'claude'; } if (role === 'reviewer') { if (lease.reviewer_agent_type === 'codex') { @@ -381,7 +373,6 @@ describe('runAgentForGroup room memory', () => { role: 'owner', ownerServiceId: 'claude', reviewerServiceId: 'codex-review', - failoverOwner: false, }), }), expect.any(Function), @@ -471,7 +462,6 @@ describe('runAgentForGroup room memory', () => { role: 'reviewer', ownerServiceId: 'claude', reviewerServiceId: 'claude', - failoverOwner: false, }), }), expect.any(Function), @@ -529,7 +519,6 @@ describe('runAgentForGroup room memory', () => { role: 'reviewer', ownerServiceId: 'codex-main', reviewerServiceId: 'claude', - failoverOwner: false, }), }), expect.any(Function), @@ -538,7 +527,7 @@ describe('runAgentForGroup room memory', () => { ); }); - it('honors a forced agent type for reviewer failover handoffs', async () => { + it('honors a forced agent type for reviewer turns', async () => { const group: RegisteredGroup = { ...makeGroup(), agentType: 'codex', @@ -637,7 +626,6 @@ describe('runAgentForGroup room memory', () => { vi.mocked(config.getRoleModelConfig).mockReturnValue({ model: 'claude-opus-4-8', effort: 'high', - fallbackEnabled: true, }); await runAgentForGroup(makeDeps(), { @@ -2934,7 +2922,6 @@ describe('runAgentForGroup Claude failure recovery', () => { expect(result).toBe('error'); expect(agentRunner.runAgentProcess).toHaveBeenCalledTimes(1); expect(outputs).toEqual([]); - expect(db.createServiceHandoff).not.toHaveBeenCalled(); }); it('clears the Claude session and retries fresh when a retryable thinking 400 is surfaced as text', async () => { @@ -2989,7 +2976,7 @@ describe('runAgentForGroup Claude failure recovery', () => { expect(outputs).toEqual(['fresh Claude retry success']); }); - it('hands off to codex when the fresh Claude retry also hits the same retryable thinking 400', async () => { + it('returns error when the fresh Claude retry also hits the same retryable thinking 400', async () => { const outputs: string[] = []; const deps = makeDeps(); @@ -3033,28 +3020,13 @@ describe('runAgentForGroup Claude failure recovery', () => { }, }); - expect(result).toBe('success'); + expect(result).toBe('error'); expect(agentRunner.runAgentProcess).toHaveBeenCalledTimes(2); expect(deps.clearSession).toHaveBeenCalledTimes(2); expect(outputs).toEqual([]); - expect(serviceRouting.activateCodexFailover).toHaveBeenCalledWith( - 'group@test', - 'claude-session-failure', - ); - expect(db.createServiceHandoff).toHaveBeenCalledWith( - expect.objectContaining({ - chat_jid: 'group@test', - source_role: 'owner', - target_role: 'owner', - source_agent_type: 'claude-code', - target_agent_type: 'codex', - reason: 'claude-session-failure', - intended_role: 'owner', - }), - ); }); - it('does not retry when Claude is usage-exhausted', async () => { + it('tells the room when Claude resets instead of retrying on usage exhaustion', async () => { const outputs: string[] = []; vi.mocked(agentRunner.runAgentProcess).mockImplementationOnce( @@ -3080,33 +3052,100 @@ describe('runAgentForGroup Claude failure recovery', () => { startSeq: 10, endSeq: 12, onOutput: async (output) => { - if (typeof output.result === 'string') outputs.push(output.result); + const text = + output.output && 'text' in output.output + ? output.output.text + : output.result; + if (typeof text === 'string') outputs.push(text); }, }); expect(result).toBe('success'); expect(agentRunner.runAgentProcess).toHaveBeenCalledTimes(1); - expect(outputs).toEqual([]); - expect(serviceRouting.activateCodexFailover).toHaveBeenCalledWith( - 'group@test', - 'claude-usage-exhausted', - ); - expect(db.createServiceHandoff).toHaveBeenCalledWith( - expect.objectContaining({ - chat_jid: 'group@test', - source_role: 'owner', - source_agent_type: 'claude-code', - target_role: 'owner', - target_agent_type: 'codex', - start_seq: 10, - end_seq: 12, - reason: 'claude-usage-exhausted', - intended_role: 'owner', - }), + expect(outputs).toHaveLength(1); + expect(outputs[0]).toMatch( + /^Claude 사용 한도에 도달했습니다\. (\d+월 \d+일 )?04:00에 재개할 수 있습니다\.$/, ); }); - it('hands off to codex after repeated retryable Claude session failures', async () => { + it('closes the paired task when the Claude owner hits its usage limit', async () => { + const outputs: string[] = []; + const pairedTask = { + id: 'paired-task-usage-limit', + chat_jid: 'group@test', + group_folder: 'test-claude', + owner_service_id: 'claude', + reviewer_service_id: 'codex-review', + title: null, + source_ref: 'HEAD', + plan_notes: null, + round_trip_count: 0, + review_requested_at: null, + status: 'active' as const, + arbiter_verdict: null, + arbiter_requested_at: null, + completion_reason: null, + created_at: '2026-04-06T00:00:00.000Z', + updated_at: '2026-04-06T00:00:00.000Z', + }; + vi.mocked( + pairedExecutionContext.preparePairedExecutionContext, + ).mockReturnValue({ task: pairedTask, workspace: null, envOverrides: {} }); + vi.mocked(db.getPairedTaskById).mockReturnValue(pairedTask); + vi.mocked(db.updatePairedTaskIfUnchanged).mockReturnValue(true); + vi.mocked(agentRunner.runAgentProcess).mockImplementationOnce( + async (_group, _input, _onProcess, onOutput) => { + await onOutput?.({ + status: 'error', + result: null, + error: 'API Error: 429 rate_limit_error', + }); + return { + status: 'error', + result: null, + error: 'API Error: 429 rate_limit_error', + }; + }, + ); + + const result = await runAgentForGroup(makeDeps(), { + group: makeGroup(), + prompt: 'hello', + chatJid: 'group@test', + runId: 'run-paired-usage-limit', + onOutput: async (output) => { + const text = + output.output && 'text' in output.output + ? output.output.text + : output.result; + if (typeof text === 'string') outputs.push(text); + }, + }); + + expect(result).toBe('success'); + expect(agentRunner.runAgentProcess).toHaveBeenCalledTimes(1); + expect(db.updatePairedTaskIfUnchanged).toHaveBeenCalledWith( + 'paired-task-usage-limit', + '2026-04-06T00:00:00.000Z', + expect.objectContaining({ + status: 'completed', + completion_reason: 'claude_usage_limit', + }), + ); + expect( + pairedExecutionContext.completePairedExecutionContext, + ).toHaveBeenCalledWith( + expect.objectContaining({ + taskId: 'paired-task-usage-limit', + status: 'failed', + }), + ); + expect(outputs).toEqual([ + expect.stringMatching(/^Claude 사용 한도에 도달했습니다\. /), + ]); + }); + + it('returns error after repeated retryable Claude session failures', async () => { vi.mocked( sessionRecovery.shouldRetryFreshSessionOnAgentFailure, ).mockReturnValue(true); @@ -3135,129 +3174,9 @@ describe('runAgentForGroup Claude failure recovery', () => { onOutput: async () => {}, }); - expect(result).toBe('success'); + expect(result).toBe('error'); expect(agentRunner.runAgentProcess).toHaveBeenCalledTimes(2); expect(deps.clearSession).toHaveBeenCalledTimes(2); - expect(serviceRouting.activateCodexFailover).toHaveBeenCalledWith( - 'group@test', - 'claude-session-failure', - ); - expect(db.createServiceHandoff).toHaveBeenCalledWith( - expect.objectContaining({ - chat_jid: 'group@test', - source_role: 'owner', - target_role: 'owner', - source_agent_type: 'claude-code', - target_agent_type: 'codex', - start_seq: 3, - end_seq: 7, - reason: 'claude-session-failure', - intended_role: 'owner', - }), - ); - }); - - it('does not enqueue generic paired reviewer recovery after delegating to a fallback handoff', async () => { - vi.mocked( - sessionRecovery.shouldRetryFreshSessionOnAgentFailure, - ).mockReturnValue(true); - vi.mocked(serviceRouting.getEffectiveChannelLease).mockReturnValue({ - chat_jid: 'group@test', - owner_agent_type: 'claude-code', - reviewer_agent_type: 'claude-code', - arbiter_agent_type: null, - owner_service_id: 'claude', - reviewer_service_id: 'claude', - arbiter_service_id: null, - activated_at: null, - reason: null, - explicit: false, - }); - vi.mocked( - pairedExecutionContext.preparePairedExecutionContext, - ).mockReturnValue({ - task: { - id: 'paired-task-reviewer-handoff-delegated', - chat_jid: 'group@test', - group_folder: 'test-group', - owner_service_id: 'claude', - reviewer_service_id: 'claude', - title: null, - source_ref: 'HEAD', - plan_notes: null, - round_trip_count: 1, - review_requested_at: '2026-03-31T00:00:00.000Z', - status: 'in_review', - arbiter_verdict: null, - arbiter_requested_at: null, - completion_reason: null, - created_at: '2026-03-31T00:00:00.000Z', - updated_at: '2026-03-31T00:00:00.000Z', - }, - workspace: null, - envOverrides: {}, - }); - vi.mocked(db.getPairedTaskById).mockReturnValue({ - id: 'paired-task-reviewer-handoff-delegated', - chat_jid: 'group@test', - group_folder: 'test-group', - owner_service_id: 'claude', - reviewer_service_id: 'claude', - title: null, - source_ref: 'HEAD', - plan_notes: null, - round_trip_count: 1, - review_requested_at: '2026-03-31T00:00:00.000Z', - status: 'review_ready', - arbiter_verdict: null, - arbiter_requested_at: null, - completion_reason: null, - created_at: '2026-03-31T00:00:00.000Z', - updated_at: '2026-03-31T00:00:00.000Z', - }); - vi.mocked(agentRunner.runAgentProcess).mockImplementation( - async (_group, _input, _onProcess, onOutput) => { - await onOutput?.({ - status: 'success', - phase: 'final', - result: null, - }); - return { - status: 'success', - result: null, - }; - }, - ); - - const deps = makeDeps(); - const result = await runAgentForGroup(deps, { - group: makeGroup(), - prompt: 'please review', - chatJid: 'group@test', - runId: 'run-reviewer-delegated-handoff', - forcedRole: 'reviewer', - onOutput: async () => {}, - }); - - expect(result).toBe('success'); - expect(db.createServiceHandoff).toHaveBeenCalledWith( - expect.objectContaining({ - chat_jid: 'group@test', - paired_task_id: 'paired-task-reviewer-handoff-delegated', - paired_task_updated_at: '2026-03-31T00:00:00.000Z', - turn_id: - 'paired-task-reviewer-handoff-delegated:2026-03-31T00:00:00.000Z:reviewer-turn', - turn_intent_kind: 'reviewer-turn', - turn_role: 'reviewer', - source_role: 'reviewer', - target_role: 'reviewer', - intended_role: 'reviewer', - }), - ); - expect( - pairedExecutionContext.completePairedExecutionContext, - ).not.toHaveBeenCalled(); - expect(deps.queue.enqueueMessageCheck).not.toHaveBeenCalled(); }); it('drops a stale Claude session id before retrying a fresh session', async () => { @@ -3367,7 +3286,7 @@ describe('runAgentForGroup Claude failure recovery', () => { expect(deps.clearSession).toHaveBeenCalledWith('test-codex'); }); - it('suppresses a usage-exhausted banner even when Claude already emitted progress text', async () => { + it('replaces a usage-exhausted banner with the reset notice even after progress text', async () => { const outputs: string[] = []; vi.mocked(agentRunner.runAgentProcess).mockImplementationOnce( @@ -3395,13 +3314,21 @@ describe('runAgentForGroup Claude failure recovery', () => { chatJid: 'group@test', runId: 'run-progress-before-usage-banner', onOutput: async (output) => { - if (typeof output.result === 'string') outputs.push(output.result); + const text = + output.output && 'text' in output.output + ? output.output.text + : output.result; + if (typeof text === 'string') outputs.push(text); }, }); - expect(result).toBe('error'); - expect(outputs).toEqual(['대화 요약 중...']); - expect(db.createServiceHandoff).not.toHaveBeenCalled(); + // The banner itself stays hidden; the room gets the reset notice instead + // of a generic failure. + expect(result).toBe('success'); + expect(outputs).toEqual([ + '대화 요약 중...', + expect.stringMatching(/^Claude 사용 한도에 도달했습니다\. .*02:00에/), + ]); }); it('does not retry when Claude org access is denied', async () => { @@ -3432,24 +3359,9 @@ describe('runAgentForGroup Claude failure recovery', () => { }, }); - expect(result).toBe('success'); + expect(result).toBe('error'); expect(agentRunner.runAgentProcess).toHaveBeenCalledTimes(1); expect(outputs).toEqual([]); - expect(serviceRouting.activateCodexFailover).toHaveBeenCalledWith( - 'group@test', - 'claude-org-access-denied', - ); - expect(db.createServiceHandoff).toHaveBeenCalledWith( - expect.objectContaining({ - chat_jid: 'group@test', - source_role: 'owner', - source_agent_type: 'claude-code', - target_role: 'owner', - target_agent_type: 'codex', - reason: 'claude-org-access-denied', - intended_role: 'owner', - }), - ); }); it('does not mistake a normal response quoting the banner text for a usage error', async () => { diff --git a/src/message-agent-executor.ts b/src/message-agent-executor.ts index 00c844f..403c41b 100644 --- a/src/message-agent-executor.ts +++ b/src/message-agent-executor.ts @@ -1,11 +1,19 @@ import { AgentOutput } from './agent-runner.js'; import { GroupQueue } from './group-queue.js'; import type { AgentTriggerReason } from './agent-error-detection.js'; -import { createPairedExecutionLifecycle } from './message-agent-executor-paired.js'; +import { + createPairedExecutionLifecycle, + type PairedExecutionLifecycle, +} from './message-agent-executor-paired.js'; import type { PairedTurnIdentity } from './paired-turn-identity.js'; import { executeMessageAgentAttemptLifecycle } from './message-agent-executor-lifecycle.js'; import { runMessageAgentAttempt } from './message-agent-executor-attempt-runner.js'; -import { handoffMessageAgentExecutionToCodex } from './message-agent-executor-handoff.js'; +import { + buildClaudeUsageLimitMessage, + isClaudeUsageLimitReason, +} from './claude-usage-limit.js'; +import { getPairedTaskById } from './db.js'; +import { completePairedTaskWithReason } from './paired-task-status.js'; import { prepareMessageAgentExecutionTarget } from './message-agent-executor-target.js'; import { shouldRetryFreshSessionOnAgentFailure } from './session-recovery.js'; import type { AgentType, PairedRoomRole, RegisteredGroup } from './types.js'; @@ -17,6 +25,9 @@ import { // ── Main executor ───────────────────────────────────────────────── +/** completion_reason of a paired task closed because Claude ran out of usage. */ +export const CLAUDE_USAGE_LIMIT_COMPLETION_REASON = 'claude_usage_limit'; + function buildPromptWithCompactRefresh(args: { prompt: string; sessionFolder: string; @@ -47,6 +58,73 @@ function clearAppliedCompactRefreshAfterSuccess(args: { }); } +interface ClaudeUsageLimitFailure { + reason: AgentTriggerReason; + errorText: string | null; +} + +/** + * When a Claude run failed because the account is out of usage, close the + * paired task (nothing should retry against the exhausted account; the next + * user message starts a new task) and tell the room when Claude resets. + * Returns false for any other failure. + */ +async function reportClaudeUsageLimitToRoom( + args: ClaudeUsageLimitFailure & { + isClaudeCodeAgent: boolean; + activeRole: PairedRoomRole; + pairedTaskId?: string; + pairedExecutionLifecycle: Pick< + PairedExecutionLifecycle, + 'updateSummary' | 'completeImmediately' + >; + onOutput?: (output: AgentOutput) => Promise; + log: { warn: (obj: Record, msg: string) => void }; + }, +): Promise { + if (!args.isClaudeCodeAgent || !isClaudeUsageLimitReason(args.reason)) { + return false; + } + const notice = buildClaudeUsageLimitMessage(args.errorText); + const task = args.pairedTaskId + ? getPairedTaskById(args.pairedTaskId) + : undefined; + if (task) { + completePairedTaskWithReason(task, CLAUDE_USAGE_LIMIT_COMPLETION_REASON); + } + args.log.warn( + { reason: args.reason, role: args.activeRole, notice }, + 'Claude usage limit reached; told the room when it resets', + ); + await deliverNoticeAndFailExecution({ + notice, + summary: args.errorText ?? notice, + pairedExecutionLifecycle: args.pairedExecutionLifecycle, + onOutput: args.onOutput, + }); + return true; +} + +/** Send a final notice to the room and record the execution as failed. */ +async function deliverNoticeAndFailExecution(args: { + notice: string; + summary: string; + pairedExecutionLifecycle: Pick< + PairedExecutionLifecycle, + 'updateSummary' | 'completeImmediately' + >; + onOutput?: (output: AgentOutput) => Promise; +}): Promise { + args.pairedExecutionLifecycle.updateSummary({ outputText: args.summary }); + await args.onOutput?.({ + status: 'success', + result: null, + output: { visibility: 'public', text: args.notice }, + phase: 'final', + }); + args.pairedExecutionLifecycle.completeImmediately({ status: 'failed' }); +} + export interface MessageAgentExecutorDeps { assistantName: string; queue: Pick & @@ -92,7 +170,6 @@ export async function runAgentForGroup( pairedTurnIdentity: args.pairedTurnIdentity, }); const { - currentLease, activeRole, effectiveServiceId, effectiveAgentType, @@ -147,24 +224,14 @@ export async function runAgentForGroup( runtimePairedTurnIdentity?.role ?? activeRole, ); - const maybeHandoffToCodex = ( - reason: AgentTriggerReason, - sawVisibleOutput: boolean, - ): boolean => - isClaudeCodeAgent && - handoffMessageAgentExecutionToCodex({ + const reportClaudeUsageLimit = (limit: ClaudeUsageLimitFailure) => + reportClaudeUsageLimitToRoom({ + ...limit, + isClaudeCodeAgent, activeRole, - effectiveAgentType, - hasReviewer: currentLease.reviewer_agent_type !== null, - reason, - sawVisibleOutput, - prompt, - startSeq, - endSeq, - chatJid, - group, - pairedTurnIdentity: runtimePairedTurnIdentity, - markDelegated: () => pairedExecutionLifecycle.markDelegated(), + pairedTaskId: pairedExecutionContext?.task.id, + pairedExecutionLifecycle, + onOutput, log, }); @@ -180,9 +247,6 @@ export async function runAgentForGroup( }; if (pairedExecutionContext?.blockMessage) { - pairedExecutionLifecycle.updateSummary({ - outputText: pairedExecutionContext.blockMessage, - }); log.warn( { roomRoleServiceId: roomRoleContext?.serviceId, @@ -190,16 +254,12 @@ export async function runAgentForGroup( }, 'Blocked paired execution before runner start', ); - await onOutput?.({ - status: 'success', - result: null, - output: { - visibility: 'public', - text: pairedExecutionContext.blockMessage, - }, - phase: 'final', + await deliverNoticeAndFailExecution({ + notice: pairedExecutionContext.blockMessage, + summary: pairedExecutionContext.blockMessage, + pairedExecutionLifecycle, + onOutput, }); - pairedExecutionLifecycle.completeImmediately({ status: 'failed' }); return 'success'; } @@ -242,7 +302,7 @@ export async function runAgentForGroup( }, clearRoleSdkSessions, sessionFolder, - maybeHandoffToCodex, + reportClaudeUsageLimit, hasDirectTerminalDelivery, pairedExecutionLifecycle, shouldRetryFreshSessionOnAgentFailure, diff --git a/src/message-runtime-handoffs.test.ts b/src/message-runtime-handoffs.test.ts deleted file mode 100644 index 33b752b..0000000 --- a/src/message-runtime-handoffs.test.ts +++ /dev/null @@ -1,372 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest'; - -vi.mock('./config.js', () => ({ - SERVICE_SESSION_SCOPE: 'codex-main', -})); - -vi.mock('./db.js', () => ({ - claimServiceHandoff: vi.fn(() => true), - claimPairedTurnReservation: vi.fn(() => true), - completeServiceHandoffAndAdvanceTargetCursor: vi.fn(() => null), - failServiceHandoff: vi.fn(), - getPairedTaskById: vi.fn(), - getPairedTurnOutputs: vi.fn(() => []), - getPendingServiceHandoffs: vi.fn(() => []), - reservePairedTurnReservation: vi.fn(() => true), - _clearPairedTurnReservationsForTests: vi.fn(), -})); - -vi.mock('./logger.js', () => ({ - logger: { - info: vi.fn(), - warn: vi.fn(), - error: vi.fn(), - }, -})); - -import * as db from './db.js'; -import { - enqueueMessageRuntimePendingHandoffs, - enqueuePendingHandoffs, - processClaimedHandoff, -} from './message-runtime-handoffs.js'; -import type { Channel, RegisteredGroup } from './types.js'; - -function makeGroup(): RegisteredGroup { - return { - name: 'Test Group', - folder: 'test-group', - trigger: '@Andy', - added_at: '2026-04-10T00:00:00.000Z', - requiresTrigger: false, - agentType: 'codex', - }; -} - -function makeChannel(name: string, ownsChatJid = false): Channel { - return { - name, - connect: vi.fn(), - disconnect: vi.fn(), - isConnected: vi.fn(() => true), - ownsJid: vi.fn((jid: string) => ownsChatJid && jid === 'group@test'), - sendMessage: vi.fn(), - } as unknown as Channel; -} - -function makeClaimedHandoff(overrides: Record = {}) { - return { - id: 13, - chat_jid: 'group@test', - group_folder: 'test-group', - source_service_id: 'claude', - target_service_id: 'codex-main', - source_role: 'reviewer', - source_agent_type: 'claude-code', - target_role: 'owner', - target_agent_type: 'codex', - prompt: 'owner handoff', - status: 'claimed', - start_seq: 13, - end_seq: 14, - reason: 'owner-follow-up', - intended_role: 'owner', - created_at: '2026-04-10T00:00:00.000Z', - claimed_at: '2026-04-10T00:00:01.000Z', - completed_at: null, - last_error: null, - ...overrides, - } as any; -} - -describe('enqueueMessageRuntimePendingHandoffs', () => { - beforeEach(() => { - vi.clearAllMocks(); - }); - - it('enqueues pending handoffs with runtime-bound processing dependencies', async () => { - const handoff = makeClaimedHandoff(); - vi.mocked(db.getPendingServiceHandoffs).mockReturnValue([handoff]); - vi.mocked(db.claimServiceHandoff).mockReturnValue(true); - vi.mocked(db.completeServiceHandoffAndAdvanceTargetCursor).mockReturnValue( - '14', - ); - const enqueueTask = vi.fn(); - const executeTurn = vi.fn(async () => ({ - outputStatus: 'success' as const, - deliverySucceeded: true, - visiblePhase: 'final', - })); - const lastAgentTimestamps: Record = {}; - const getLastAgentTimestamps = vi.fn(() => lastAgentTimestamps); - const saveState = vi.fn(); - const enqueueMessageCheck = vi.fn(); - - enqueueMessageRuntimePendingHandoffs({ - enqueueTask, - getRoomBindings: () => ({ - 'group@test': makeGroup(), - }), - channels: [makeChannel('discord-main', true)], - executeTurn, - getLastAgentTimestamps, - saveState, - enqueueMessageCheck, - }); - - expect(db.getPendingServiceHandoffs).toHaveBeenCalledWith('codex-main'); - expect(db.claimServiceHandoff).toHaveBeenCalledWith(13); - expect(getLastAgentTimestamps).not.toHaveBeenCalled(); - expect(enqueueTask).toHaveBeenCalledWith( - 'group@test', - 'handoff:13', - expect.any(Function), - ); - - const queuedTask = vi.mocked(enqueueTask).mock.calls[0]?.[2]; - await queuedTask?.(); - - expect(getLastAgentTimestamps).toHaveBeenCalledTimes(1); - expect(executeTurn).toHaveBeenCalledWith( - expect.objectContaining({ - chatJid: 'group@test', - runId: 'handoff-13', - forcedRole: 'owner', - forcedAgentType: 'codex', - }), - ); - expect(lastAgentTimestamps['group@test']).toBe('14'); - expect(saveState).toHaveBeenCalledTimes(1); - expect(enqueueMessageCheck).not.toHaveBeenCalled(); - }); -}); - -describe('message-runtime-handoffs', () => { - beforeEach(() => { - vi.clearAllMocks(); - }); - - it('does not expose reviewer-targeted handoffs to the codex-main poller', () => { - vi.mocked(db.getPendingServiceHandoffs).mockImplementation( - (targetServiceId?: string) => - targetServiceId === 'codex-main' - ? [] - : ([ - { - id: 1, - chat_jid: 'group@test', - group_folder: 'test-group', - source_service_id: 'claude', - target_service_id: 'codex-review', - source_role: 'reviewer', - source_agent_type: 'claude-code', - target_role: 'reviewer', - target_agent_type: 'codex', - prompt: 'review retry', - status: 'pending', - start_seq: 1, - end_seq: 2, - reason: 'reviewer-auth-failure', - intended_role: 'reviewer', - created_at: '2026-04-10T00:00:00.000Z', - claimed_at: null, - completed_at: null, - last_error: null, - }, - ] as any), - ); - - const enqueueTask = vi.fn(); - - enqueuePendingHandoffs({ - enqueueTask, - processClaimedHandoff: vi.fn(), - }); - - expect(db.getPendingServiceHandoffs).toHaveBeenCalledWith('codex-main'); - expect(db.claimServiceHandoff).not.toHaveBeenCalled(); - expect(enqueueTask).not.toHaveBeenCalled(); - }); - - it('fails a claimed handoff closed when its intended role cannot be resolved', async () => { - const executeTurn = vi.fn(); - - await processClaimedHandoff({ - handoff: { - id: 7, - chat_jid: 'group@test', - group_folder: 'test-group', - source_service_id: 'claude', - target_service_id: 'codex-main', - source_role: 'reviewer', - source_agent_type: 'claude-code', - target_role: null, - target_agent_type: 'codex', - prompt: 'review retry', - status: 'claimed', - start_seq: 3, - end_seq: 4, - reason: 'unknown-failure', - intended_role: null, - created_at: '2026-04-10T00:00:00.000Z', - claimed_at: '2026-04-10T00:00:01.000Z', - completed_at: null, - last_error: null, - }, - getRoomBindings: () => ({ - 'group@test': makeGroup(), - }), - channels: [makeChannel('discord-main', true)], - executeTurn, - lastAgentTimestamps: {}, - saveState: vi.fn(), - }); - - expect(db.failServiceHandoff).toHaveBeenCalledWith( - 7, - 'Cannot resolve intended handoff role', - ); - expect(executeTurn).not.toHaveBeenCalled(); - }); - - it('executes a reviewer handoff with a fixed reviewer role and channel', async () => { - const executeTurn = vi.fn(async () => ({ - outputStatus: 'success' as const, - deliverySucceeded: true, - visiblePhase: 'final', - })); - - await processClaimedHandoff({ - handoff: { - id: 9, - chat_jid: 'group@test', - group_folder: 'test-group', - paired_task_id: 'task-reviewer-handoff', - paired_task_updated_at: '2026-04-10T00:00:00.000Z', - turn_id: 'task-reviewer-handoff:2026-04-10T00:00:00.000Z:reviewer-turn', - turn_intent_kind: 'reviewer-turn', - turn_role: 'reviewer', - source_service_id: 'claude', - target_service_id: 'codex-review', - source_role: 'reviewer', - source_agent_type: 'claude-code', - target_role: 'reviewer', - target_agent_type: 'codex', - prompt: 'review retry', - status: 'claimed', - start_seq: 5, - end_seq: 6, - reason: 'reviewer-auth-failure', - intended_role: 'reviewer', - created_at: '2026-04-10T00:00:00.000Z', - claimed_at: '2026-04-10T00:00:01.000Z', - completed_at: null, - last_error: null, - }, - getRoomBindings: () => ({ - 'group@test': makeGroup(), - }), - channels: [ - makeChannel('discord-main', true), - makeChannel('discord-review'), - ], - executeTurn, - lastAgentTimestamps: {}, - saveState: vi.fn(), - }); - - expect(executeTurn).toHaveBeenCalledWith( - expect.objectContaining({ - chatJid: 'group@test', - forcedRole: 'reviewer', - forcedAgentType: 'codex', - pairedTurnIdentity: { - turnId: - 'task-reviewer-handoff:2026-04-10T00:00:00.000Z:reviewer-turn', - taskId: 'task-reviewer-handoff', - taskUpdatedAt: '2026-04-10T00:00:00.000Z', - intentKind: 'reviewer-turn', - role: 'reviewer', - }, - channel: expect.objectContaining({ - name: 'discord-review', - }), - }), - ); - expect(db.failServiceHandoff).not.toHaveBeenCalled(); - }); - - it('recreates a pending reviewer retry after a claimed handoff delivery failure', async () => { - const executeTurn = vi.fn(async () => ({ - outputStatus: 'error' as const, - deliverySucceeded: false, - visiblePhase: 'final', - })); - const enqueueMessageCheck = vi.fn(); - const getPairedTaskById = vi.fn(() => ({ - id: 'task-reviewer-handoff-retry', - status: 'review_ready' as const, - round_trip_count: 1, - updated_at: '2026-04-10T00:00:00.000Z', - })); - - await processClaimedHandoff({ - handoff: { - id: 11, - chat_jid: 'group@test', - group_folder: 'test-group', - paired_task_id: 'task-reviewer-handoff-retry', - paired_task_updated_at: '2026-04-10T00:00:00.000Z', - turn_id: - 'task-reviewer-handoff-retry:2026-04-10T00:00:00.000Z:reviewer-turn', - turn_intent_kind: 'reviewer-turn', - turn_role: 'reviewer', - source_service_id: 'claude', - target_service_id: 'codex-review', - source_role: 'reviewer', - source_agent_type: 'claude-code', - target_role: 'reviewer', - target_agent_type: 'codex', - prompt: 'review retry after claimed handoff failure', - status: 'claimed', - start_seq: 7, - end_seq: 8, - reason: 'reviewer-auth-failure', - intended_role: 'reviewer', - created_at: '2026-04-10T00:00:00.000Z', - claimed_at: '2026-04-10T00:00:01.000Z', - completed_at: null, - last_error: null, - }, - getRoomBindings: () => ({ - 'group@test': makeGroup(), - }), - channels: [ - makeChannel('discord-main', true), - makeChannel('discord-review'), - ], - executeTurn, - lastAgentTimestamps: {}, - saveState: vi.fn(), - getPairedTaskById, - enqueueMessageCheck, - }); - - expect(db.failServiceHandoff).toHaveBeenCalledWith( - 11, - 'Handoff delivery failed', - ); - expect(getPairedTaskById).toHaveBeenCalledWith( - 'task-reviewer-handoff-retry', - ); - expect(db.reservePairedTurnReservation).toHaveBeenCalledWith( - expect.objectContaining({ - chatJid: 'group@test', - taskId: 'task-reviewer-handoff-retry', - taskUpdatedAt: '2026-04-10T00:00:00.000Z', - intentKind: 'reviewer-turn', - }), - ); - expect(enqueueMessageCheck).toHaveBeenCalledWith('group@test'); - }); -}); diff --git a/src/message-runtime-handoffs.ts b/src/message-runtime-handoffs.ts deleted file mode 100644 index e442a02..0000000 --- a/src/message-runtime-handoffs.ts +++ /dev/null @@ -1,429 +0,0 @@ -import { SERVICE_SESSION_SCOPE } from './config.js'; -import { getErrorMessage } from './utils.js'; -import { - claimServiceHandoff, - completeServiceHandoffAndAdvanceTargetCursor, - failServiceHandoff, - getPairedTaskById, - getPendingServiceHandoffs, - type ServiceHandoff, -} from './db.js'; -import { findChannel, findChannelByName } from './router.js'; -import { logger } from './logger.js'; -import { schedulePairedFollowUpWithMessageCheck } from './message-runtime-follow-up.js'; -import { - getFixedRoleChannelName, - getMissingRoleChannelMessage, - resolveHandoffCursorKey, - resolveHandoffRoleOverride, -} from './message-runtime-shared.js'; -import { buildPairedTurnIdentity } from './paired-turn-identity.js'; -import type { ScheduledPairedFollowUpIntentKind } from './paired-follow-up-scheduler.js'; -import type { ExecuteTurnFn } from './message-runtime-types.js'; -import type { - Channel, - PairedRoomRole, - PairedTask, - RegisteredGroup, -} from './types.js'; - -export function enqueuePendingHandoffs(args: { - enqueueTask: ( - chatJid: string, - taskId: string, - task: () => Promise, - ) => void; - processClaimedHandoff: (handoff: ServiceHandoff) => Promise; -}): void { - for (const handoff of getPendingServiceHandoffs(SERVICE_SESSION_SCOPE)) { - if (!claimServiceHandoff(handoff.id)) { - continue; - } - - args.enqueueTask(handoff.chat_jid, `handoff:${handoff.id}`, async () => { - await args.processClaimedHandoff(handoff); - }); - } -} - -export function enqueueMessageRuntimePendingHandoffs(args: { - enqueueTask?: - | ((chatJid: string, taskId: string, task: () => Promise) => void) - | undefined; - getRoomBindings: () => Record; - channels: Channel[]; - executeTurn: ExecuteTurnFn; - getLastAgentTimestamps: () => Record; - saveState: () => void; - enqueueMessageCheck: (chatJid: string) => void; -}): void { - enqueuePendingHandoffs({ - enqueueTask: (chatJid, taskId, task) => { - args.enqueueTask?.(chatJid, taskId, task); - }, - processClaimedHandoff: async (handoff) => { - await processClaimedHandoff({ - handoff, - getRoomBindings: args.getRoomBindings, - channels: args.channels, - executeTurn: args.executeTurn, - lastAgentTimestamps: args.getLastAgentTimestamps(), - saveState: args.saveState, - getPairedTaskById, - enqueueMessageCheck: args.enqueueMessageCheck, - }); - }, - }); -} - -function requeueFailedClaimedPairedTurn(args: { - handoff: ServiceHandoff; - error: string; - getPairedTaskById?: - | (( - id: string, - ) => - | Pick - | undefined) - | undefined; - enqueueMessageCheck?: ((chatJid: string) => void) | undefined; -}): void { - const { handoff, error, getPairedTaskById, enqueueMessageCheck } = args; - if ( - !handoff.paired_task_id || - !handoff.paired_task_updated_at || - !handoff.turn_intent_kind || - !getPairedTaskById || - !enqueueMessageCheck - ) { - return; - } - - const task = getPairedTaskById(handoff.paired_task_id); - if (!task) { - logger.warn( - { - chatJid: handoff.chat_jid, - handoffId: handoff.id, - taskId: handoff.paired_task_id, - error, - }, - 'Skipped paired turn retry after claimed service handoff failure because the paired task no longer exists', - ); - return; - } - - if (!isScheduledPairedFollowUpIntentKind(handoff.turn_intent_kind)) { - logger.warn( - { - chatJid: handoff.chat_jid, - handoffId: handoff.id, - taskId: handoff.paired_task_id, - intentKind: handoff.turn_intent_kind, - error, - }, - 'Skipped paired turn retry after claimed service handoff failure because the persisted turn intent is not schedulable', - ); - return; - } - - if (task.updated_at !== handoff.paired_task_updated_at) { - logger.warn( - { - chatJid: handoff.chat_jid, - handoffId: handoff.id, - taskId: handoff.paired_task_id, - expectedTaskUpdatedAt: handoff.paired_task_updated_at, - actualTaskUpdatedAt: task.updated_at, - error, - }, - 'Skipped paired turn retry after claimed service handoff failure because the paired task revision changed', - ); - return; - } - - const scheduled = schedulePairedFollowUpWithMessageCheck({ - chatJid: handoff.chat_jid, - runId: `handoff-${handoff.id}-retry`, - task, - intentKind: handoff.turn_intent_kind, - enqueueMessageCheck: () => enqueueMessageCheck(handoff.chat_jid), - }); - logger.info( - { - chatJid: handoff.chat_jid, - handoffId: handoff.id, - taskId: task.id, - taskStatus: task.status, - taskUpdatedAt: task.updated_at, - intentKind: handoff.turn_intent_kind, - turnId: handoff.turn_id ?? null, - scheduled, - error, - }, - scheduled - ? 'Queued paired turn retry after claimed service handoff failure' - : 'Skipped duplicate paired turn retry after claimed service handoff failure while task state was unchanged', - ); -} - -function isScheduledPairedFollowUpIntentKind( - intentKind: ServiceHandoff['turn_intent_kind'], -): intentKind is ScheduledPairedFollowUpIntentKind { - return ( - intentKind === 'reviewer-turn' || - intentKind === 'arbiter-turn' || - intentKind === 'owner-follow-up' || - intentKind === 'finalize-owner-turn' - ); -} - -function failClaimedHandoff(args: { - handoff: ServiceHandoff; - error: string; - getPairedTaskById?: - | (( - id: string, - ) => - | Pick - | undefined) - | undefined; - enqueueMessageCheck?: ((chatJid: string) => void) | undefined; -}): void { - failServiceHandoff(args.handoff.id, args.error); - requeueFailedClaimedPairedTurn(args); -} - -function resolveHandoffDeliveryChannel(args: { - handoff: ServiceHandoff; - handoffRole: PairedRoomRole; - fallbackChannel: Channel; - channels: Channel[]; - getPairedTaskById?: - | (( - id: string, - ) => - | Pick - | undefined) - | undefined; - enqueueMessageCheck?: ((chatJid: string) => void) | undefined; -}): Channel | undefined { - const { handoff, handoffRole } = args; - if (handoffRole === 'owner') { - return args.fallbackChannel; - } - - const roleChannel = findChannelByName( - args.channels, - getFixedRoleChannelName(handoffRole), - ); - if (!roleChannel) { - failClaimedHandoff({ - handoff, - error: getMissingRoleChannelMessage(handoffRole), - getPairedTaskById: args.getPairedTaskById, - enqueueMessageCheck: args.enqueueMessageCheck, - }); - return undefined; - } - return roleChannel; -} - -function buildHandoffPairedTurnIdentity( - handoff: ServiceHandoff, - handoffRole: PairedRoomRole, -) { - if ( - !handoff.paired_task_id || - !handoff.paired_task_updated_at || - !handoff.turn_intent_kind - ) { - return undefined; - } - return buildPairedTurnIdentity({ - taskId: handoff.paired_task_id, - taskUpdatedAt: handoff.paired_task_updated_at, - intentKind: handoff.turn_intent_kind, - role: handoff.turn_role ?? handoffRole, - turnId: handoff.turn_id, - }); -} - -export async function processClaimedHandoff(args: { - handoff: ServiceHandoff; - getRoomBindings: () => Record; - channels: Channel[]; - executeTurn: ExecuteTurnFn; - lastAgentTimestamps: Record; - saveState: () => void; - getPairedTaskById?: - | (( - id: string, - ) => - | Pick - | undefined) - | undefined; - enqueueMessageCheck?: ((chatJid: string) => void) | undefined; -}): Promise { - const { handoff } = args; - const group = args.getRoomBindings()[handoff.chat_jid]; - if (!group) { - failClaimedHandoff({ - handoff, - error: 'Group not registered on target service', - getPairedTaskById: args.getPairedTaskById, - enqueueMessageCheck: args.enqueueMessageCheck, - }); - return; - } - - const channel = findChannel(args.channels, handoff.chat_jid); - if (!channel) { - failClaimedHandoff({ - handoff, - error: 'No channel owns handoff jid', - getPairedTaskById: args.getPairedTaskById, - enqueueMessageCheck: args.enqueueMessageCheck, - }); - return; - } - - const handoffRole = resolveHandoffRoleOverride(handoff); - if (!handoffRole) { - failClaimedHandoff({ - handoff, - error: 'Cannot resolve intended handoff role', - getPairedTaskById: args.getPairedTaskById, - enqueueMessageCheck: args.enqueueMessageCheck, - }); - logger.error( - { - chatJid: handoff.chat_jid, - handoffId: handoff.id, - targetServiceId: handoff.target_service_id, - targetRole: handoff.target_role ?? null, - intendedRole: handoff.intended_role ?? null, - reason: handoff.reason ?? null, - }, - 'Failed claimed service handoff because its intended role could not be resolved', - ); - return; - } - if (handoff.turn_role && handoff.turn_role !== handoffRole) { - failClaimedHandoff({ - handoff, - error: `Stored handoff turn_role ${handoff.turn_role} conflicts with resolved role ${handoffRole}`, - getPairedTaskById: args.getPairedTaskById, - enqueueMessageCheck: args.enqueueMessageCheck, - }); - logger.error( - { - chatJid: handoff.chat_jid, - handoffId: handoff.id, - turnId: handoff.turn_id ?? null, - turnRole: handoff.turn_role, - resolvedRole: handoffRole, - targetServiceId: handoff.target_service_id, - }, - 'Failed claimed service handoff because its persisted logical turn role conflicts with the resolved role', - ); - return; - } - - const handoffChannel = resolveHandoffDeliveryChannel({ - handoff, - handoffRole, - fallbackChannel: channel, - channels: args.channels, - getPairedTaskById: args.getPairedTaskById, - enqueueMessageCheck: args.enqueueMessageCheck, - }); - if (!handoffChannel) { - return; - } - - const runId = `handoff-${handoff.id}`; - const pairedTurnIdentity = buildHandoffPairedTurnIdentity( - handoff, - handoffRole, - ); - try { - logger.info( - { - chatJid: handoff.chat_jid, - handoffId: handoff.id, - runId, - turnId: pairedTurnIdentity?.turnId ?? handoff.turn_id ?? null, - handoffRole, - targetRole: handoff.target_role ?? null, - targetServiceId: handoff.target_service_id, - targetAgentType: handoff.target_agent_type, - reason: handoff.reason, - intendedRole: handoff.intended_role ?? null, - channelName: handoffChannel.name, - }, - 'Dispatching claimed service handoff', - ); - const result = await args.executeTurn({ - group, - prompt: handoff.prompt, - chatJid: handoff.chat_jid, - runId, - channel: handoffChannel, - startSeq: handoff.start_seq, - endSeq: handoff.end_seq, - forcedRole: handoffRole, - forcedAgentType: handoff.target_agent_type, - pairedTurnIdentity, - }); - - if (!result.deliverySucceeded) { - failClaimedHandoff({ - handoff, - error: 'Handoff delivery failed', - getPairedTaskById: args.getPairedTaskById, - enqueueMessageCheck: args.enqueueMessageCheck, - }); - return; - } - - const cursorKey = resolveHandoffCursorKey(handoff.chat_jid, handoffRole); - const appliedCursor = completeServiceHandoffAndAdvanceTargetCursor({ - id: handoff.id, - chat_jid: handoff.chat_jid, - cursor_key: cursorKey, - end_seq: handoff.end_seq, - }); - if (appliedCursor) { - args.lastAgentTimestamps[cursorKey] = appliedCursor; - args.saveState(); - } - logger.info( - { - chatJid: handoff.chat_jid, - handoffId: handoff.id, - runId, - outputStatus: result.outputStatus, - visiblePhase: result.visiblePhase, - appliedCursor, - cursorKey: - appliedCursor != null - ? resolveHandoffCursorKey(handoff.chat_jid, handoffRole) - : null, - }, - 'Completed claimed service handoff', - ); - } catch (err) { - const errorMessage = getErrorMessage(err); - failClaimedHandoff({ - handoff, - error: errorMessage, - getPairedTaskById: args.getPairedTaskById, - enqueueMessageCheck: args.enqueueMessageCheck, - }); - logger.error( - { chatJid: handoff.chat_jid, handoffId: handoff.id, err }, - 'Claimed service handoff failed', - ); - } -} diff --git a/src/message-runtime-loop.ts b/src/message-runtime-loop.ts index 37cd4c0..b1a7085 100644 --- a/src/message-runtime-loop.ts +++ b/src/message-runtime-loop.ts @@ -32,7 +32,6 @@ export async function processMessageLoopTick(args: { messages: NewMessage[], ) => boolean; executeTurn: ExecuteTurnFn; - enqueuePendingHandoffs: () => void; schedulePairedFollowUpWithMessageCheck: typeof schedulePairedFollowUpWithMessageCheck; enqueueScopedGroupMessageCheck: ( chatJid: string, @@ -44,7 +43,6 @@ export async function processMessageLoopTick(args: { roomStopControls: RoomStopControls; labelPairedSenders: (chatJid: string, messages: NewMessage[]) => NewMessage[]; }): Promise { - args.enqueuePendingHandoffs(); const roomBindings = args.getRoomBindings(); const jids = Object.keys(roomBindings); const { messages, newSeqCursor } = getNewMessagesBySeq( diff --git a/src/message-runtime-progress-entry.test.ts b/src/message-runtime-progress-entry.test.ts index 66f0876..940821c 100644 --- a/src/message-runtime-progress-entry.test.ts +++ b/src/message-runtime-progress-entry.test.ts @@ -23,10 +23,7 @@ import { storeMessage, } from './db.js'; import { createMessageRuntime } from './message-runtime.js'; -import { - clearGlobalFailover, - refreshChannelOwnerCache, -} from './service-routing.js'; +import { refreshChannelOwnerCache } from './service-routing.js'; import type { Channel, RegisteredGroup } from './types.js'; const chatJid = 'group@test'; @@ -60,7 +57,6 @@ describe('message-runtime progress entry path', () => { beforeEach(() => { _initTestDatabase(); refreshChannelOwnerCache(true); - clearGlobalFailover(); runtimeMocks.executeTurn.mockClear(); runtimeMocks.executeTurn.mockResolvedValue({ outputStatus: 'success', diff --git a/src/message-runtime-rules.test.ts b/src/message-runtime-rules.test.ts index d4631a7..d6bd8ab 100644 --- a/src/message-runtime-rules.test.ts +++ b/src/message-runtime-rules.test.ts @@ -41,7 +41,6 @@ const baseLease: EffectiveChannelLease = { owner_service_id: 'svc-owner', reviewer_service_id: 'svc-reviewer', arbiter_service_id: 'svc-arbiter', - owner_failover_active: false, activated_at: null, reason: null, explicit: true, diff --git a/src/message-runtime-shared.test.ts b/src/message-runtime-shared.test.ts index ce3eab5..8634d87 100644 --- a/src/message-runtime-shared.test.ts +++ b/src/message-runtime-shared.test.ts @@ -3,46 +3,9 @@ import { describe, expect, it } from 'vitest'; import { getFixedRoleChannelName, getMissingRoleChannelMessage, - resolveHandoffCursorKey, - resolveHandoffRoleOverride, } from './message-runtime-shared.js'; describe('message-runtime-shared', () => { - it('prefers explicit target role over inferred handoff metadata', () => { - expect( - resolveHandoffRoleOverride({ - target_role: 'arbiter', - intended_role: 'reviewer', - reason: 'reviewer-follow-up', - }), - ).toBe('arbiter'); - }); - - it('falls back from intended role to reason prefix when needed', () => { - expect( - resolveHandoffRoleOverride({ - target_role: null, - intended_role: 'reviewer', - reason: 'arbiter-follow-up', - }), - ).toBe('reviewer'); - expect( - resolveHandoffRoleOverride({ - target_role: null, - intended_role: null, - reason: 'arbiter-follow-up', - }), - ).toBe('arbiter'); - }); - - it('builds owner and role-scoped cursor keys', () => { - expect(resolveHandoffCursorKey('room-1')).toBe('room-1'); - expect(resolveHandoffCursorKey('room-1', 'owner')).toBe('room-1'); - expect(resolveHandoffCursorKey('room-1', 'reviewer')).toBe( - 'room-1:reviewer', - ); - }); - it('returns fixed role channel names and user-facing missing-channel errors', () => { expect(getFixedRoleChannelName('reviewer')).toBe('discord-review'); expect(getFixedRoleChannelName('arbiter')).toBe('discord-arbiter'); diff --git a/src/message-runtime-shared.ts b/src/message-runtime-shared.ts index 8df6de6..2122d83 100644 --- a/src/message-runtime-shared.ts +++ b/src/message-runtime-shared.ts @@ -1,34 +1,3 @@ -import type { PairedRoomRole } from './types.js'; -import type { ServiceHandoff } from './db.js'; - -export function resolveHandoffRoleOverride( - handoff: Pick, -): PairedRoomRole | undefined { - if (handoff.target_role) { - return handoff.target_role; - } - if (handoff.intended_role) { - return handoff.intended_role; - } - if (handoff.reason?.startsWith('reviewer-')) { - return 'reviewer'; - } - if (handoff.reason?.startsWith('arbiter-')) { - return 'arbiter'; - } - return undefined; -} - -export function resolveHandoffCursorKey( - chatJid: string, - role?: PairedRoomRole, -): string { - if (!role || role === 'owner') { - return chatJid; - } - return `${chatJid}:${role}`; -} - export function getFixedRoleChannelName(role: 'reviewer' | 'arbiter'): string { return role === 'reviewer' ? 'discord-review' : 'discord-arbiter'; } diff --git a/src/message-runtime.test.ts b/src/message-runtime.test.ts index b7bc837..23adf53 100644 --- a/src/message-runtime.test.ts +++ b/src/message-runtime.test.ts @@ -15,7 +15,6 @@ const makeCodexLease = (chatJid: string): EffectiveChannelLease => ({ owner_service_id: 'codex', reviewer_service_id: null, arbiter_service_id: null, - owner_failover_active: false, activated_at: null, reason: null, explicit: false, @@ -223,7 +222,6 @@ vi.mock('./service-routing.js', () => ({ owner_service_id: 'claude', reviewer_service_id: 'codex-main', arbiter_service_id: 'claude-arbiter', - owner_failover_active: false, activated_at: null, reason: null, explicit: false, @@ -237,7 +235,6 @@ vi.mock('./service-routing.js', () => ({ owner_service_id: string; reviewer_service_id: string | null; arbiter_service_id?: string | null; - owner_failover_active?: boolean; }, role: 'owner' | 'reviewer' | 'arbiter', ) => { @@ -3567,7 +3564,6 @@ describe('createMessageRuntime', () => { owner_service_id: 'claude', reviewer_service_id: 'claude', arbiter_service_id: null, - owner_failover_active: false, activated_at: null, reason: null, explicit: false, @@ -3682,7 +3678,6 @@ describe('createMessageRuntime', () => { owner_service_id: 'claude', reviewer_service_id: 'claude', arbiter_service_id: 'claude-arbiter', - owner_failover_active: false, activated_at: null, reason: null, explicit: false, @@ -3966,7 +3961,6 @@ describe('createMessageRuntime', () => { owner_service_id: 'codex', reviewer_service_id: null, arbiter_service_id: null, - owner_failover_active: false, activated_at: null, reason: null, explicit: false, diff --git a/src/message-runtime.ts b/src/message-runtime.ts index 7633407..8d96c71 100644 --- a/src/message-runtime.ts +++ b/src/message-runtime.ts @@ -1,6 +1,5 @@ import { updatePairedTurnProgressText } from './db.js'; import { GroupQueue, GroupRunContext } from './group-queue.js'; -import { enqueueMessageRuntimePendingHandoffs } from './message-runtime-handoffs.js'; import { buildScopedMessageCheckEnqueuer, processMessageLoopTick, @@ -189,18 +188,6 @@ export function createMessageRuntime(deps: MessageRuntimeDeps): { }, }); - const enqueuePendingHandoffs = (): void => { - enqueueMessageRuntimePendingHandoffs({ - enqueueTask: deps.queue.enqueueTask?.bind(deps.queue), - getRoomBindings: deps.getRoomBindings, - channels: deps.channels, - executeTurn, - getLastAgentTimestamps: deps.getLastAgentTimestamps, - saveState: deps.saveState, - enqueueMessageCheck: (chatJid) => deps.queue.enqueueMessageCheck(chatJid), - }); - }; - const processGroupMessages = createProcessGroupMessages({ assistantName: deps.assistantName, failureFinalText: FAILURE_FINAL_TEXT, @@ -233,7 +220,6 @@ export function createMessageRuntime(deps: MessageRuntimeDeps): { saveState: deps.saveState, hasImplicitContinuationWindow: continuationTracker.has, executeTurn, - enqueuePendingHandoffs, schedulePairedFollowUpWithMessageCheck, enqueueScopedGroupMessageCheck, sendQueuedMessage: deps.queue.sendMessage.bind(deps.queue), diff --git a/src/paired-execution-context-carry-forward.test.ts b/src/paired-execution-context-carry-forward.test.ts index d9831ba..42a9f65 100644 --- a/src/paired-execution-context-carry-forward.test.ts +++ b/src/paired-execution-context-carry-forward.test.ts @@ -80,7 +80,6 @@ const ownerContext: RoomRoleContext = { role: 'owner', ownerServiceId: 'codex-main', reviewerServiceId: 'claude-review', - failoverOwner: false, }; function buildTask(overrides: Partial = {}): PairedTask { diff --git a/src/paired-execution-context-owner-follow-up.test.ts b/src/paired-execution-context-owner-follow-up.test.ts index 3586491..75d67b7 100644 --- a/src/paired-execution-context-owner-follow-up.test.ts +++ b/src/paired-execution-context-owner-follow-up.test.ts @@ -64,7 +64,6 @@ const ownerContext: RoomRoleContext = { role: 'owner', ownerServiceId: config.CODEX_MAIN_SERVICE_ID, reviewerServiceId: config.REVIEWER_SERVICE_ID_FOR_TYPE, - failoverOwner: false, }; function buildPairedTask(overrides: Partial = {}): PairedTask { diff --git a/src/paired-execution-context.test.ts b/src/paired-execution-context.test.ts index b2c396a..104602b 100644 --- a/src/paired-execution-context.test.ts +++ b/src/paired-execution-context.test.ts @@ -92,7 +92,6 @@ const ownerContext: RoomRoleContext = { role: 'owner', ownerServiceId: config.CODEX_MAIN_SERVICE_ID, reviewerServiceId: config.REVIEWER_SERVICE_ID_FOR_TYPE, - failoverOwner: false, }; const reviewerContext: RoomRoleContext = { @@ -100,15 +99,6 @@ const reviewerContext: RoomRoleContext = { role: 'reviewer', ownerServiceId: config.CODEX_MAIN_SERVICE_ID, reviewerServiceId: config.REVIEWER_SERVICE_ID_FOR_TYPE, - failoverOwner: false, -}; - -const failoverOwnerContext: RoomRoleContext = { - serviceId: config.CODEX_REVIEW_SERVICE_ID, - role: 'owner', - ownerServiceId: config.CODEX_REVIEW_SERVICE_ID, - reviewerServiceId: config.REVIEWER_SERVICE_ID_FOR_TYPE, - failoverOwner: true, }; const ORIGINAL_UNSAFE_HOST_PAIRED_MODE = @@ -444,25 +434,6 @@ describe('paired execution context', () => { ); }); - it('persists stable role-slot service shadow instead of the transient failover owner lease', () => { - preparePairedExecutionContext({ - group, - chatJid: 'dc:test', - runId: 'run-failover-owner', - roomRoleContext: failoverOwnerContext, - hasHumanMessage: true, - }); - - expect(db.createPairedTask).toHaveBeenCalledWith( - expect.objectContaining({ - owner_service_id: config.CODEX_MAIN_SERVICE_ID, - reviewer_service_id: config.REVIEWER_SERVICE_ID_FOR_TYPE, - owner_agent_type: 'codex', - reviewer_agent_type: config.REVIEWER_AGENT_TYPE, - }), - ); - }); - it('uses the reviewer snapshot after lazy auto-refresh and marks the task in_review', () => { vi.mocked(db.getLatestOpenPairedTaskForChat).mockReturnValue({ id: 'task-1', diff --git a/src/paired-follow-up-scheduler.test.ts b/src/paired-follow-up-scheduler.test.ts index b35a996..1b02709 100644 --- a/src/paired-follow-up-scheduler.test.ts +++ b/src/paired-follow-up-scheduler.test.ts @@ -16,8 +16,6 @@ import { _initTestDatabase, _initTestDatabaseFromFile, createPairedTask, - createServiceHandoff, - failServiceHandoff, getPairedTaskById, getPairedTurnAttempts, getPairedTurnById, @@ -513,137 +511,6 @@ describe('paired follow-up scheduler', () => { expect(enqueue).toHaveBeenCalledTimes(1); }); - it('requeues the same reviewer logical turn after a failed fallback handoff', () => { - const firstEnqueue = vi.fn(); - const secondEnqueue = vi.fn(); - const currentReviewerServiceId = - CURRENT_AGENT_TYPE === 'codex' - ? CODEX_REVIEW_SERVICE_ID - : CLAUDE_SERVICE_ID; - const otherReviewerServiceId = - OTHER_AGENT_TYPE === 'codex' - ? CODEX_REVIEW_SERVICE_ID - : CLAUDE_SERVICE_ID; - const task = { - id: 'task-reviewer-handoff-retry', - chat_jid: 'group@test', - group_folder: 'test-group', - owner_service_id: CURRENT_SERVICE_ID, - reviewer_service_id: OTHER_SERVICE_ID, - title: null, - source_ref: 'HEAD', - plan_notes: null, - review_requested_at: null, - arbiter_verdict: null, - arbiter_requested_at: null, - completion_reason: null, - created_at: '2026-04-10T00:00:00.000Z', - status: 'review_ready', - round_trip_count: 1, - updated_at: '2026-04-10T00:00:00.000Z', - } as const; - createPairedTask(task as any); - - expect( - schedulePairedFollowUpOnce({ - chatJid: task.chat_jid, - runId: 'run-reviewer-schedule-1', - task, - intentKind: 'reviewer-turn', - enqueue: firstEnqueue, - }), - ).toBe(true); - expect( - claimPairedTurnExecution({ - chatJid: task.chat_jid, - runId: 'run-reviewer-claim-1', - task, - intentKind: 'reviewer-turn', - }), - ).toBe(true); - - const handoff = createServiceHandoff({ - chat_jid: task.chat_jid, - group_folder: task.group_folder, - paired_task_id: task.id, - paired_task_updated_at: task.updated_at, - turn_intent_kind: 'reviewer-turn', - turn_role: 'reviewer', - source_service_id: currentReviewerServiceId, - target_service_id: otherReviewerServiceId, - source_role: 'reviewer', - target_role: 'reviewer', - source_agent_type: CURRENT_AGENT_TYPE, - target_agent_type: OTHER_AGENT_TYPE, - prompt: 'review retry after fallback', - intended_role: 'reviewer', - }); - - failServiceHandoff(handoff.id, 'fallback handoff failed'); - releasePairedTaskExecutionLease({ - taskId: task.id, - runId: 'run-reviewer-claim-1', - }); - - expect( - getPairedTurnById( - 'task-reviewer-handoff-retry:2026-04-10T00:00:00.000Z:reviewer-turn', - ), - ).toMatchObject({ - state: 'failed', - attempt_no: 1, - last_error: 'fallback handoff failed', - }); - - expect( - schedulePairedFollowUpOnce({ - chatJid: task.chat_jid, - runId: 'run-reviewer-schedule-2', - task, - intentKind: 'reviewer-turn', - enqueue: secondEnqueue, - }), - ).toBe(true); - expect(secondEnqueue).toHaveBeenCalledTimes(1); - expect( - getPairedTurnById( - 'task-reviewer-handoff-retry:2026-04-10T00:00:00.000Z:reviewer-turn', - ), - ).toMatchObject({ - state: 'failed', - attempt_no: 1, - last_error: 'fallback handoff failed', - }); - expect( - getPairedTurnAttempts( - 'task-reviewer-handoff-retry:2026-04-10T00:00:00.000Z:reviewer-turn', - ), - ).toMatchObject([ - { - attempt_no: 1, - state: 'failed', - last_error: 'fallback handoff failed', - }, - ]); - - expect( - claimPairedTurnExecution({ - chatJid: task.chat_jid, - runId: 'run-reviewer-claim-2', - task, - intentKind: 'reviewer-turn', - }), - ).toBe(true); - expect( - getPairedTurnById( - 'task-reviewer-handoff-retry:2026-04-10T00:00:00.000Z:reviewer-turn', - ), - ).toMatchObject({ - state: 'running', - attempt_no: 2, - }); - }); - it('blocks a fresh-refetched task revision from reclaiming the same turn while the execution lease is active', () => { const task = { id: 'task-1', diff --git a/src/paired-task-status.ts b/src/paired-task-status.ts index f4f1a30..a5cae2d 100644 --- a/src/paired-task-status.ts +++ b/src/paired-task-status.ts @@ -1,6 +1,6 @@ -import { updatePairedTaskIfUnchanged } from './db.js'; +import { getPairedTaskById, updatePairedTaskIfUnchanged } from './db.js'; import { logger } from './logger.js'; -import type { PairedTaskStatus } from './types.js'; +import type { PairedTask, PairedTaskStatus } from './types.js'; export const ALLOWED_PAIRED_STATUS_TRANSITIONS: Record< PairedTaskStatus, @@ -143,3 +143,29 @@ export function applyPairedTaskPatch(args: { } return updated; } + +/** + * Close a paired task as completed with the given reason, re-reading the task + * when a concurrent update moved it. Returns false when the task was already + * completed (or kept changing). + */ +export function completePairedTaskWithReason( + task: PairedTask, + completionReason: string, +): boolean { + let current: PairedTask | undefined = task; + for (let attempt = 0; attempt < 3; attempt += 1) { + if (!current || current.status === 'completed') return false; + const transitioned = transitionPairedTaskStatus({ + taskId: current.id, + currentStatus: current.status, + nextStatus: 'completed', + expectedUpdatedAt: current.updated_at, + updatedAt: new Date().toISOString(), + patch: { completion_reason: completionReason }, + }); + if (transitioned) return true; + current = getPairedTaskById(task.id); + } + return false; +} diff --git a/src/paired-turn-fallback.test.ts b/src/paired-turn-fallback.test.ts deleted file mode 100644 index 7a9143a..0000000 --- a/src/paired-turn-fallback.test.ts +++ /dev/null @@ -1,146 +0,0 @@ -import { describe, expect, it } from 'vitest'; - -import { resolveCodexFallbackHandoff } from './paired-turn-fallback.js'; - -describe('resolveCodexFallbackHandoff', () => { - it('returns a reviewer codex handoff plan for reviewer auth failures', () => { - const result = resolveCodexFallbackHandoff({ - activeRole: 'reviewer', - effectiveAgentType: 'claude-code', - hasReviewer: true, - fallbackEnabled: true, - reason: 'auth-expired', - sawVisibleOutput: false, - prompt: 'please review', - startSeq: 10, - endSeq: 12, - }); - - expect(result).toEqual({ - type: 'handoff', - plan: { - handoff: { - source_role: 'reviewer', - target_role: 'reviewer', - source_agent_type: 'claude-code', - target_agent_type: 'codex', - prompt: 'please review', - start_seq: 10, - end_seq: 12, - reason: 'reviewer-claude-auth-expired', - intended_role: 'reviewer', - }, - logMessage: - 'Claude reviewer unavailable, handed off review turn to codex-review', - }, - }); - }); - - it('returns an arbiter codex handoff plan for arbiter auth failures', () => { - const result = resolveCodexFallbackHandoff({ - activeRole: 'arbiter', - effectiveAgentType: 'claude-code', - hasReviewer: true, - fallbackEnabled: true, - reason: '429', - sawVisibleOutput: false, - prompt: 'please arbitrate', - }); - - expect(result).toEqual({ - type: 'handoff', - plan: { - handoff: { - source_role: 'arbiter', - target_role: 'arbiter', - source_agent_type: 'claude-code', - target_agent_type: 'codex', - prompt: 'please arbitrate', - start_seq: null, - end_seq: null, - reason: 'arbiter-claude-429', - intended_role: 'arbiter', - }, - logMessage: - 'Claude arbiter unavailable, handed off arbiter turn to codex', - }, - }); - }); - - it('returns an owner codex handoff plan and failover activation for owner failures', () => { - const result = resolveCodexFallbackHandoff({ - activeRole: 'owner', - effectiveAgentType: 'claude-code', - hasReviewer: true, - fallbackEnabled: true, - reason: 'session-failure', - sawVisibleOutput: false, - prompt: 'please continue', - }); - - expect(result).toEqual({ - type: 'handoff', - plan: { - handoff: { - source_role: 'owner', - target_role: 'owner', - source_agent_type: 'claude-code', - target_agent_type: 'codex', - prompt: 'please continue', - start_seq: null, - end_seq: null, - reason: 'claude-session-failure', - intended_role: 'owner', - }, - activateOwnerFailoverReason: 'claude-session-failure', - logMessage: - 'Claude unavailable, handed off current owner turn to codex fallback', - }, - }); - }); - - it('skips handoff when fallback is disabled for the role', () => { - const result = resolveCodexFallbackHandoff({ - activeRole: 'owner', - effectiveAgentType: 'claude-code', - hasReviewer: true, - fallbackEnabled: false, - reason: 'usage-exhausted', - sawVisibleOutput: false, - prompt: 'please continue', - }); - - expect(result).toEqual({ - type: 'skip', - logMessage: 'Fallback disabled for role, skipping handoff', - }); - }); - - it('returns none when visible output was already emitted', () => { - const result = resolveCodexFallbackHandoff({ - activeRole: 'reviewer', - effectiveAgentType: 'claude-code', - hasReviewer: true, - fallbackEnabled: true, - reason: 'auth-expired', - sawVisibleOutput: true, - prompt: 'please review', - }); - - expect(result).toEqual({ type: 'none' }); - }); - - it('returns none when no reviewer is configured for the room', () => { - const result = resolveCodexFallbackHandoff({ - activeRole: 'owner', - effectiveAgentType: 'claude-code', - hasReviewer: false, - fallbackEnabled: true, - reason: '429', - sawVisibleOutput: false, - prompt: 'please continue', - }); - - expect(result).toEqual({ type: 'none' }); - }); -}); diff --git a/src/paired-turn-fallback.ts b/src/paired-turn-fallback.ts deleted file mode 100644 index 5edabbe..0000000 --- a/src/paired-turn-fallback.ts +++ /dev/null @@ -1,116 +0,0 @@ -import type { AgentTriggerReason } from './agent-error-detection.js'; -import type { AgentType, PairedRoomRole } from './types.js'; - -const CODEX_HANDOFF_REASONS = new Set([ - '429', - 'usage-exhausted', - 'auth-expired', - 'org-access-denied', - 'session-failure', -]); - -export interface CodexFallbackHandoffRecord { - source_role: PairedRoomRole; - target_role: PairedRoomRole; - source_agent_type: AgentType; - target_agent_type: 'codex'; - prompt: string; - start_seq: number | null; - end_seq: number | null; - reason: string; - intended_role: PairedRoomRole; -} - -export interface CodexFallbackHandoffPlan { - handoff: CodexFallbackHandoffRecord; - activateOwnerFailoverReason?: string; - logMessage: string; -} - -export type CodexFallbackResolution = - | { type: 'none' } - | { type: 'skip'; logMessage: string } - | { type: 'handoff'; plan: CodexFallbackHandoffPlan }; - -export function resolveCodexFallbackHandoff(args: { - activeRole: PairedRoomRole; - effectiveAgentType: AgentType; - hasReviewer: boolean; - fallbackEnabled: boolean; - reason: AgentTriggerReason; - sawVisibleOutput: boolean; - prompt: string; - startSeq?: number | null; - endSeq?: number | null; -}): CodexFallbackResolution { - if (args.sawVisibleOutput || !CODEX_HANDOFF_REASONS.has(args.reason)) { - return { type: 'none' }; - } - - if (!args.hasReviewer) { - return { type: 'none' }; - } - - if (!args.fallbackEnabled) { - return { - type: 'skip', - logMessage: 'Fallback disabled for role, skipping handoff', - }; - } - - const baseHandoff = { - source_role: args.activeRole, - source_agent_type: args.effectiveAgentType, - target_agent_type: 'codex' as const, - prompt: args.prompt, - start_seq: args.startSeq ?? null, - end_seq: args.endSeq ?? null, - }; - - if (args.activeRole === 'arbiter') { - return { - type: 'handoff', - plan: { - handoff: { - ...baseHandoff, - target_role: 'arbiter', - intended_role: 'arbiter', - reason: `arbiter-claude-${args.reason}`, - }, - logMessage: - 'Claude arbiter unavailable, handed off arbiter turn to codex', - }, - }; - } - - if (args.activeRole === 'reviewer') { - return { - type: 'handoff', - plan: { - handoff: { - ...baseHandoff, - target_role: 'reviewer', - intended_role: 'reviewer', - reason: `reviewer-claude-${args.reason}`, - }, - logMessage: - 'Claude reviewer unavailable, handed off review turn to codex-review', - }, - }; - } - - return { - type: 'handoff', - plan: { - handoff: { - ...baseHandoff, - target_role: args.activeRole, - intended_role: args.activeRole, - reason: `claude-${args.reason}`, - }, - activateOwnerFailoverReason: `claude-${args.reason}`, - logMessage: - 'Claude unavailable, handed off current owner turn to codex fallback', - }, - }; -} diff --git a/src/paired-turn-invariants.test.ts b/src/paired-turn-invariants.test.ts index dec6a36..cea677c 100644 --- a/src/paired-turn-invariants.test.ts +++ b/src/paired-turn-invariants.test.ts @@ -4,15 +4,6 @@ vi.mock('./config.js', () => ({ SERVICE_SESSION_SCOPE: 'codex-main', })); -vi.mock('./db.js', () => ({ - claimServiceHandoff: vi.fn(() => true), - completeServiceHandoffAndAdvanceTargetCursor: vi.fn( - () => '2026-04-15T00:00:09.000Z', - ), - failServiceHandoff: vi.fn(), - getPendingServiceHandoffs: vi.fn(() => []), -})); - vi.mock('./logger.js', () => ({ logger: { info: vi.fn(), @@ -21,42 +12,13 @@ vi.mock('./logger.js', () => ({ }, })); -import * as db from './db.js'; -import { processClaimedHandoff } from './message-runtime-handoffs.js'; import { buildPairedTurnIdentity, resolveRuntimePairedTurnIdentity, } from './paired-turn-identity.js'; -import type { Channel, RegisteredGroup } from './types.js'; - -function makeGroup(): RegisteredGroup { - return { - name: 'Test Group', - folder: 'test-group', - trigger: '@Andy', - added_at: '2026-04-15T00:00:00.000Z', - requiresTrigger: false, - agentType: 'codex', - }; -} - -function makeChannel(name: string, ownsChatJid = false): Channel { - return { - name, - connect: vi.fn(), - disconnect: vi.fn(), - isConnected: vi.fn(() => true), - ownsJid: vi.fn((jid: string) => ownsChatJid && jid === 'group@test'), - sendMessage: vi.fn(), - } as unknown as Channel; -} - describe('paired turn invariants', () => { beforeEach(() => { vi.clearAllMocks(); - vi.mocked(db.completeServiceHandoffAndAdvanceTargetCursor).mockReturnValue( - '2026-04-15T00:00:09.000Z', - ); }); it('rejects a persisted turn identity when the explicit role conflicts with its intent kind', () => { @@ -112,110 +74,4 @@ describe('paired turn invariants', () => { role: 'arbiter', }); }); - - it('fails closed when a claimed handoff resolves to a different logical role than the stored turn', async () => { - const executeTurn = vi.fn(); - - await processClaimedHandoff({ - handoff: { - id: 13, - chat_jid: 'group@test', - group_folder: 'test-group', - turn_id: 'task-review:2026-04-15T00:00:00.000Z:reviewer-turn', - turn_intent_kind: 'reviewer-turn', - turn_role: 'reviewer', - source_service_id: 'claude', - target_service_id: 'codex-main', - source_role: 'reviewer', - source_agent_type: 'claude-code', - target_role: 'owner', - target_agent_type: 'codex', - prompt: 'review retry', - status: 'claimed', - start_seq: 3, - end_seq: 4, - reason: 'reviewer-auth-failure', - intended_role: 'owner', - created_at: '2026-04-15T00:00:00.000Z', - claimed_at: '2026-04-15T00:00:01.000Z', - completed_at: null, - last_error: null, - }, - getRoomBindings: () => ({ - 'group@test': makeGroup(), - }), - channels: [makeChannel('discord-main', true)], - executeTurn, - lastAgentTimestamps: {}, - saveState: vi.fn(), - }); - - expect(db.failServiceHandoff).toHaveBeenCalledWith( - 13, - 'Stored handoff turn_role reviewer conflicts with resolved role owner', - ); - expect(executeTurn).not.toHaveBeenCalled(); - }); - - it('advances reviewer handoff cursors in the reviewer-scoped namespace', async () => { - const executeTurn = vi.fn(async () => ({ - outputStatus: 'success' as const, - deliverySucceeded: true, - visiblePhase: 'final', - })); - const lastAgentTimestamps: Record = {}; - const saveState = vi.fn(); - - await processClaimedHandoff({ - handoff: { - id: 17, - chat_jid: 'group@test', - group_folder: 'test-group', - paired_task_id: 'task-reviewer-handoff', - paired_task_updated_at: '2026-04-15T00:00:00.000Z', - turn_id: 'task-reviewer-handoff:2026-04-15T00:00:00.000Z:reviewer-turn', - turn_intent_kind: 'reviewer-turn', - turn_role: 'reviewer', - source_service_id: 'claude', - target_service_id: 'codex-review', - source_role: 'reviewer', - source_agent_type: 'claude-code', - target_role: 'reviewer', - target_agent_type: 'codex', - prompt: 'review retry', - status: 'claimed', - start_seq: 5, - end_seq: 6, - reason: 'reviewer-auth-failure', - intended_role: 'reviewer', - created_at: '2026-04-15T00:00:00.000Z', - claimed_at: '2026-04-15T00:00:01.000Z', - completed_at: null, - last_error: null, - }, - getRoomBindings: () => ({ - 'group@test': makeGroup(), - }), - channels: [ - makeChannel('discord-main', true), - makeChannel('discord-review'), - ], - executeTurn, - lastAgentTimestamps, - saveState, - }); - - expect( - db.completeServiceHandoffAndAdvanceTargetCursor, - ).toHaveBeenCalledWith({ - id: 17, - chat_jid: 'group@test', - cursor_key: 'group@test:reviewer', - end_seq: 6, - }); - expect(lastAgentTimestamps).toEqual({ - 'group@test:reviewer': '2026-04-15T00:00:09.000Z', - }); - expect(saveState).toHaveBeenCalledTimes(1); - }); }); diff --git a/src/platform-prompts.test.ts b/src/platform-prompts.test.ts index c658f42..5aa9840 100644 --- a/src/platform-prompts.test.ts +++ b/src/platform-prompts.test.ts @@ -61,7 +61,7 @@ describe('platform-prompts', () => { expect(readPairedRoomPrompt('claude-code')).toBe(expected); }); - it('maps Codex paired-room prompts to the shared reviewer prompt while preserving failover identity wording', () => { + it('maps Codex paired-room prompts to the shared reviewer prompt', () => { const repoRoot = path.resolve( path.dirname(fileURLToPath(import.meta.url)), '..', @@ -90,12 +90,6 @@ describe('platform-prompts', () => { expect(codexPairedPrompt).toContain('Keep reviewer output owner-facing'); expect(codexPairedPrompt).toContain('prefer 3-6 lines'); expect(codexPairedPrompt).not.toContain('owner-side paired agent'); - - const failoverPlatformPrompt = fs.readFileSync( - path.join(repoRoot, 'prompts', 'codex-review-failover-platform.md'), - 'utf-8', - ); - expect(failoverPlatformPrompt).toContain('acting as `클코`'); }); it('keeps the superpowers-derived debugging guidance compressed and role-scoped', () => { diff --git a/src/room-role-context.test.ts b/src/room-role-context.test.ts index 5589586..2e2db18 100644 --- a/src/room-role-context.test.ts +++ b/src/room-role-context.test.ts @@ -11,7 +11,6 @@ describe('buildRoomRoleContext', () => { owner_service_id: 'claude', reviewer_service_id: 'codex-main', arbiter_service_id: null, - owner_failover_active: false, activated_at: null, reason: null, explicit: false, @@ -23,7 +22,6 @@ describe('buildRoomRoleContext', () => { role: 'reviewer', ownerServiceId: 'claude', reviewerServiceId: 'codex-main', - failoverOwner: false, arbiterServiceId: undefined, }); }); @@ -38,7 +36,6 @@ describe('buildRoomRoleContext', () => { owner_service_id: 'claude', reviewer_service_id: 'stale-reviewer-shadow', arbiter_service_id: null, - owner_failover_active: false, activated_at: null, reason: null, explicit: true, @@ -52,7 +49,6 @@ describe('buildRoomRoleContext', () => { reviewerServiceId: 'stale-reviewer-shadow', ownerAgentType: 'claude-code', reviewerAgentType: 'codex', - failoverOwner: false, arbiterServiceId: undefined, }); }); @@ -67,7 +63,6 @@ describe('buildRoomRoleContext', () => { owner_service_id: 'codex-review', reviewer_service_id: 'claude', arbiter_service_id: null, - owner_failover_active: true, activated_at: '2026-03-28T10:00:00.000Z', reason: 'claude-429', explicit: true, @@ -81,7 +76,6 @@ describe('buildRoomRoleContext', () => { reviewerServiceId: 'claude', ownerAgentType: 'claude-code', reviewerAgentType: 'claude-code', - failoverOwner: true, arbiterServiceId: undefined, }); }); @@ -94,7 +88,6 @@ describe('buildRoomRoleContext', () => { owner_service_id: 'codex-main', reviewer_service_id: 'claude', arbiter_service_id: 'codex-review', - owner_failover_active: false, activated_at: null, reason: null, explicit: false, @@ -106,7 +99,6 @@ describe('buildRoomRoleContext', () => { role: 'arbiter', ownerServiceId: 'codex-main', reviewerServiceId: 'claude', - failoverOwner: false, arbiterServiceId: 'codex-review', }); }); @@ -119,7 +111,6 @@ describe('buildRoomRoleContext', () => { owner_service_id: 'claude', reviewer_service_id: 'claude', arbiter_service_id: null, - owner_failover_active: false, activated_at: null, reason: null, explicit: false, @@ -132,7 +123,6 @@ describe('buildRoomRoleContext', () => { role: 'reviewer', ownerServiceId: 'claude', reviewerServiceId: 'claude', - failoverOwner: false, arbiterServiceId: undefined, }); }); @@ -145,7 +135,6 @@ describe('buildRoomRoleContext', () => { owner_service_id: 'codex-main', reviewer_service_id: 'claude', arbiter_service_id: 'codex-review', - owner_failover_active: false, activated_at: null, reason: null, explicit: false, @@ -158,7 +147,6 @@ describe('buildRoomRoleContext', () => { role: 'reviewer', ownerServiceId: 'codex-main', reviewerServiceId: 'claude', - failoverOwner: false, arbiterServiceId: 'codex-review', }); }); @@ -171,7 +159,6 @@ describe('buildRoomRoleContext', () => { owner_service_id: 'codex-main', reviewer_service_id: null, arbiter_service_id: null, - owner_failover_active: false, activated_at: null, reason: null, explicit: false, diff --git a/src/room-role-context.ts b/src/room-role-context.ts index e242f45..0639729 100644 --- a/src/room-role-context.ts +++ b/src/room-role-context.ts @@ -57,7 +57,6 @@ export function buildRoomRoleContext( ...(lease.reviewer_agent_type !== undefined ? { reviewerAgentType: lease.reviewer_agent_type } : {}), - failoverOwner: Boolean(lease.owner_failover_active), arbiterServiceId, ...(lease.arbiter_agent_type !== undefined ? { arbiterAgentType: lease.arbiter_agent_type } diff --git a/src/room-stop.ts b/src/room-stop.ts index c832002..9013280 100644 --- a/src/room-stop.ts +++ b/src/room-stop.ts @@ -2,7 +2,6 @@ import { cancelPairedTurn, getLatestOpenPairedTaskForChat, getMessagesSinceSeq, - getPairedTaskById, getPairedTurnsForTask, releasePairedTaskExecutionLeasesForTask, } from './db.js'; @@ -13,7 +12,7 @@ import { isExternalHumanMessage, resolveCursorKeyForRole, } from './message-runtime-rules.js'; -import { transitionPairedTaskStatus } from './paired-task-status.js'; +import { completePairedTaskWithReason } from './paired-task-status.js'; import { buildPairedTurnIdentity } from './paired-turn-identity.js'; import { hasReviewerLease } from './service-routing.js'; import { isStopIntent, USER_STOP_REPLY } from './stop-intent.js'; @@ -97,24 +96,6 @@ function advanceRoomCursorsPast(args: { } } -function completeTaskAsStopped(task: PairedTask): boolean { - let current: PairedTask | undefined = task; - for (let attempt = 0; attempt < 3; attempt += 1) { - if (!current || current.status === 'completed') return false; - const transitioned = transitionPairedTaskStatus({ - taskId: current.id, - currentStatus: current.status, - nextStatus: 'completed', - expectedUpdatedAt: current.updated_at, - updatedAt: new Date().toISOString(), - patch: { completion_reason: USER_STOP_COMPLETION_REASON }, - }); - if (transitioned) return true; - current = getPairedTaskById(task.id); - } - return false; -} - function cancelOpenTurns(taskId: string): number { let cancelled = 0; for (const turn of getPairedTurnsForTask(taskId)) { @@ -146,7 +127,10 @@ function closePairedTaskForStop(task: PairedTask): { cancelledTurns: number; releasedLeases: number; } { - const completed = completeTaskAsStopped(task); + const completed = completePairedTaskWithReason( + task, + USER_STOP_COMPLETION_REASON, + ); const cancelledTurns = cancelOpenTurns(task.id); const releasedLeases = releasePairedTaskExecutionLeasesForTask(task.id); return { completed, cancelledTurns, releasedLeases }; diff --git a/src/service-routing.test.ts b/src/service-routing.test.ts index 0289b44..ada834f 100644 --- a/src/service-routing.test.ts +++ b/src/service-routing.test.ts @@ -10,10 +10,7 @@ import { setExplicitRoomMode, } from './db.js'; import { - activateCodexFailover, - clearGlobalFailover, getEffectiveChannelLease, - getGlobalFailoverInfo, refreshChannelOwnerCache, resolveLeaseServiceId, } from './service-routing.js'; @@ -21,107 +18,9 @@ import { beforeEach(() => { _initTestDatabase(); refreshChannelOwnerCache(true); - clearGlobalFailover(); }); -describe('service-routing global failover', () => { - it('uses codex-review as owner during global failover without rewriting the reviewer lease', () => { - _setRegisteredGroupForTests('dc:paired', { - name: 'Paired Room', - folder: 'paired-room', - trigger: '@Andy', - added_at: '2024-01-01T00:00:00.000Z', - agentType: 'claude-code', - }); - _setRegisteredGroupForTests('dc:paired', { - name: 'Paired Room', - folder: 'paired-room', - trigger: '@Codex', - added_at: '2024-01-01T00:00:00.000Z', - agentType: 'codex', - }); - - activateCodexFailover('dc:paired', 'claude-429'); - - // Global failover applies to ALL channels - expect(getGlobalFailoverInfo().active).toBe(true); - expect(getEffectiveChannelLease('dc:paired')).toMatchObject({ - chat_jid: 'dc:paired', - owner_service_id: 'codex-review', - reviewer_service_id: 'codex-review', - owner_failover_active: true, - reason: 'claude-429', - explicit: true, - }); - // Any other channel is also affected - expect(getEffectiveChannelLease('dc:other')).toMatchObject({ - owner_service_id: 'codex-review', - reviewer_service_id: null, - owner_failover_active: true, - explicit: true, - }); - }); - - it('preserves reviewer and arbiter leases for tribunal rooms during global failover', () => { - _setRegisteredGroupForTests('dc:tribunal', { - name: 'Tribunal Room', - folder: 'tribunal-room', - trigger: '@Andy', - added_at: '2024-01-01T00:00:00.000Z', - agentType: 'claude-code', - }); - _setRegisteredGroupForTests('dc:tribunal', { - name: 'Tribunal Room', - folder: 'tribunal-room', - trigger: '@Codex', - added_at: '2024-01-01T00:00:00.000Z', - agentType: 'codex', - }); - setExplicitRoomMode('dc:tribunal', 'tribunal'); - const baseLease = getEffectiveChannelLease('dc:tribunal'); - - activateCodexFailover('dc:tribunal', 'claude-429'); - - expect(getEffectiveChannelLease('dc:tribunal')).toMatchObject({ - chat_jid: 'dc:tribunal', - owner_service_id: 'codex-review', - reviewer_service_id: baseLease.reviewer_service_id, - arbiter_service_id: baseLease.arbiter_service_id, - owner_failover_active: true, - reason: 'claude-429', - explicit: true, - }); - }); - - it('restores default lease after global failover is cleared', () => { - _setRegisteredGroupForTests('dc:paired', { - name: 'Paired Room', - folder: 'paired-room', - trigger: '@Andy', - added_at: '2024-01-01T00:00:00.000Z', - agentType: 'claude-code', - }); - _setRegisteredGroupForTests('dc:paired', { - name: 'Paired Room', - folder: 'paired-room', - trigger: '@Codex', - added_at: '2024-01-01T00:00:00.000Z', - agentType: 'codex', - }); - - activateCodexFailover('dc:paired', 'claude-429'); - clearGlobalFailover(); - - expect(getGlobalFailoverInfo().active).toBe(false); - expect(getEffectiveChannelLease('dc:paired')).toMatchObject({ - chat_jid: 'dc:paired', - owner_service_id: 'claude', - reviewer_service_id: 'codex-review', - owner_failover_active: false, - explicit: false, - }); - }); - +describe('service-routing room leases', () => { it('uses explicit single room mode to suppress reviewer lease on dual registration', () => { _setRegisteredGroupForTests('dc:explicit-single', { name: 'Explicit Single', @@ -143,7 +42,6 @@ describe('service-routing global failover', () => { chat_jid: 'dc:explicit-single', owner_service_id: 'claude', reviewer_service_id: null, - owner_failover_active: false, explicit: false, }); }); @@ -173,7 +71,6 @@ describe('service-routing global failover', () => { chat_jid: 'dc:stored-owner-claude', owner_service_id: 'claude', reviewer_service_id: null, - owner_failover_active: false, explicit: false, }); }); @@ -192,7 +89,6 @@ describe('service-routing global failover', () => { chat_jid: 'dc:stored-owner-fallback', owner_service_id: 'codex-main', reviewer_service_id: null, - owner_failover_active: false, explicit: false, }); }); @@ -211,7 +107,6 @@ describe('service-routing global failover', () => { chat_jid: 'dc:explicit-tribunal', owner_service_id: 'claude', reviewer_service_id: 'codex-review', - owner_failover_active: false, explicit: false, }); }); @@ -232,7 +127,6 @@ describe('service-routing global failover', () => { chat_jid: 'dc:explicit-tribunal-codex', owner_service_id: 'codex-main', reviewer_service_id: 'codex-review', - owner_failover_active: false, explicit: false, }); }); @@ -255,7 +149,6 @@ describe('service-routing global failover', () => { owner_service_id: 'claude', reviewer_service_id: 'codex-review', arbiter_service_id: 'claude', - owner_failover_active: false, explicit: false, }); }); @@ -265,7 +158,6 @@ describe('service-routing global failover', () => { chat_jid: 'dc:unregistered', owner_service_id: 'claude', reviewer_service_id: null, - owner_failover_active: false, explicit: false, }); }); @@ -291,7 +183,6 @@ describe('service-routing global failover', () => { chat_jid: 'dc:legacy-only', owner_service_id: 'claude', reviewer_service_id: null, - owner_failover_active: false, explicit: false, }); }); @@ -308,32 +199,12 @@ describe('resolveLeaseServiceId', () => { owner_service_id: 'claude', reviewer_service_id: 'stale-reviewer-shadow', arbiter_service_id: null, - owner_failover_active: false, }, 'reviewer', ), ).toBe('stale-reviewer-shadow'); }); - it('keeps the explicit owner failover service instead of recomputing the stable shadow', () => { - expect( - resolveLeaseServiceId( - { - owner_agent_type: 'claude-code', - reviewer_agent_type: 'codex', - arbiter_agent_type: null, - owner_service_id: 'codex-review', - reviewer_service_id: 'claude', - arbiter_service_id: null, - owner_failover_active: true, - }, - 'owner', - ), - ).toBe('codex-review'); - }); -}); - -describe('stored lease ids as SSOT', () => { it('preserves a stored reviewer service id instead of recomputing it from role metadata', () => { setChannelOwnerLease({ chat_jid: 'dc:stored-reviewer-ssot', diff --git a/src/service-routing.ts b/src/service-routing.ts index 60d0bf3..21bb6b6 100644 --- a/src/service-routing.ts +++ b/src/service-routing.ts @@ -1,7 +1,6 @@ import { ARBITER_AGENT_TYPE, ARBITER_SERVICE_ID, - CODEX_REVIEW_SERVICE_ID, OWNER_AGENT_TYPE, REVIEWER_AGENT_TYPE, SERVICE_ID, @@ -15,7 +14,6 @@ import { getStoredRoomSettings, type ChannelOwnerLeaseRow, } from './db.js'; -import { logger } from './logger.js'; import { inferAgentTypeFromServiceShadow, resolveRoleServiceShadow, @@ -31,7 +29,6 @@ export interface EffectiveChannelLease { owner_service_id: string; reviewer_service_id: string | null; arbiter_service_id: string | null; - owner_failover_active?: boolean; activated_at: string | null; reason: string | null; explicit: boolean; @@ -99,7 +96,6 @@ function normalizeLeaseRow( ? resolveRoleServiceShadow('arbiter', arbiterAgentType) : null) ?? (isArbiterEnabled() ? ARBITER_SERVICE_ID : null), - owner_failover_active: false, activated_at: row.activated_at, reason: row.reason, explicit, @@ -138,7 +134,6 @@ function getDefaultLease(chatJid: string): EffectiveChannelLease { 'arbiter', rolePlan.arbiterAgentType, ), - owner_failover_active: false, activated_at: null, reason: null, explicit: false, @@ -193,19 +188,6 @@ export function refreshChannelOwnerCache(force = false): void { export function getEffectiveChannelLease( chatJid: string, ): EffectiveChannelLease { - // Global failover overrides the owner execution backend for all channels, - // while preserving the room's reviewer/arbiter role assignments. - if (globalFailoverActive) { - const baseLease = getStoredOrDefaultLease(chatJid); - return { - ...baseLease, - owner_service_id: CODEX_REVIEW_SERVICE_ID, - owner_failover_active: true, - activated_at: globalFailoverActivatedAt, - reason: globalFailoverReason, - explicit: true, - }; - } return getStoredOrDefaultLease(chatJid); } @@ -218,7 +200,6 @@ export function resolveLeaseServiceId( | 'owner_service_id' | 'reviewer_service_id' | 'arbiter_service_id' - | 'owner_failover_active' >, role: PairedRoomRole, ): string | null { @@ -265,40 +246,3 @@ export function shouldServiceProcessChat( ): boolean { return true; } - -// ── Global failover ────────────────────────────────────────────── -// Claude API limits are account-level, so owner failover applies to all channels. - -let globalFailoverActive = false; -let globalFailoverReason: string | null = null; -let globalFailoverActivatedAt: string | null = null; - -export function activateCodexFailover(_chatJid: string, reason: string): void { - globalFailoverActive = true; - globalFailoverReason = reason; - globalFailoverActivatedAt = new Date().toISOString(); - logger.warn( - { reason, activatedAt: globalFailoverActivatedAt }, - 'Global failover activated — owner execution switching to codex across all channels', - ); -} - -export function getGlobalFailoverInfo(): { - active: boolean; - reason: string | null; - activatedAt: string | null; -} { - return { - active: globalFailoverActive, - reason: globalFailoverReason, - activatedAt: globalFailoverActivatedAt, - }; -} - -export function clearGlobalFailover(): void { - if (!globalFailoverActive) return; - globalFailoverActive = false; - globalFailoverReason = null; - globalFailoverActivatedAt = null; - logger.info('Global failover cleared — resuming normal owner routing'); -} diff --git a/src/streamed-output-evaluator.test.ts b/src/streamed-output-evaluator.test.ts index b989b58..9a1bb4a 100644 --- a/src/streamed-output-evaluator.test.ts +++ b/src/streamed-output-evaluator.test.ts @@ -167,8 +167,11 @@ describe('evaluateStreamedOutput', () => { claudeOpts, ); expect(result.shouldForwardOutput).toBe(false); - expect(result.newTrigger).toEqual({ reason: 'usage-exhausted' }); - expect(result.state.streamedTriggerReason).toEqual({ + expect(result.newTrigger).toEqual({ + reason: 'usage-exhausted', + message: "You're out of extra usage. Resets at 5pm.", + }); + expect(result.state.streamedTriggerReason).toMatchObject({ reason: 'usage-exhausted', }); }); @@ -214,8 +217,8 @@ describe('evaluateStreamedOutput', () => { claudeOpts, ); expect(result.shouldForwardOutput).toBe(false); - expect(result.newTrigger).toEqual({ reason: 'usage-exhausted' }); - expect(result.state.streamedTriggerReason).toEqual({ + expect(result.newTrigger).toMatchObject({ reason: 'usage-exhausted' }); + expect(result.state.streamedTriggerReason).toMatchObject({ reason: 'usage-exhausted', }); }); @@ -286,7 +289,7 @@ describe('evaluateStreamedOutput', () => { claudeOpts, ); expect(result.shouldForwardOutput).toBe(false); - expect(result.newTrigger).toEqual({ reason: 'auth-expired' }); + expect(result.newTrigger).toMatchObject({ reason: 'auth-expired' }); }); }); @@ -304,8 +307,8 @@ describe('evaluateStreamedOutput', () => { claudeOpts, ); expect(result.shouldForwardOutput).toBe(false); - expect(result.newTrigger).toEqual({ reason: 'overloaded' }); - expect(result.state.streamedTriggerReason).toEqual({ + expect(result.newTrigger).toMatchObject({ reason: 'overloaded' }); + expect(result.state.streamedTriggerReason).toMatchObject({ reason: 'overloaded', }); }); @@ -323,8 +326,8 @@ describe('evaluateStreamedOutput', () => { claudeOpts, ); expect(result.shouldForwardOutput).toBe(false); - expect(result.newTrigger).toEqual({ reason: 'org-access-denied' }); - expect(result.state.streamedTriggerReason).toEqual({ + expect(result.newTrigger).toMatchObject({ reason: 'org-access-denied' }); + expect(result.state.streamedTriggerReason).toMatchObject({ reason: 'org-access-denied', }); }); @@ -341,8 +344,8 @@ describe('evaluateStreamedOutput', () => { claudeOpts, ); expect(result.shouldForwardOutput).toBe(false); - expect(result.newTrigger).toEqual({ reason: 'org-access-denied' }); - expect(result.state.streamedTriggerReason).toEqual({ + expect(result.newTrigger).toMatchObject({ reason: 'org-access-denied' }); + expect(result.state.streamedTriggerReason).toMatchObject({ reason: 'org-access-denied', }); }); @@ -364,7 +367,7 @@ describe('evaluateStreamedOutput', () => { expect(result.shouldForwardOutput).toBe(false); expect(result.newTrigger).toBeUndefined(); // Existing trigger preserved - expect(result.state.streamedTriggerReason).toEqual({ + expect(result.state.streamedTriggerReason).toMatchObject({ reason: 'usage-exhausted', }); }); @@ -451,11 +454,11 @@ describe('evaluateStreamedOutput error handling', () => { freshState(), claudeOpts, ); - expect(result.newTrigger).toEqual({ + expect(result.newTrigger).toMatchObject({ reason: '429', retryAfterMs: 30000, }); - expect(result.state.streamedTriggerReason).toEqual({ + expect(result.state.streamedTriggerReason).toMatchObject({ reason: '429', retryAfterMs: 30000, }); @@ -474,7 +477,7 @@ describe('evaluateStreamedOutput error handling', () => { shortCircuitTriggeredErrors: true, }); expect(result.shouldForwardOutput).toBe(false); - expect(result.newTrigger).toEqual({ reason: '429' }); + expect(result.newTrigger).toMatchObject({ reason: '429' }); }); it('skips rotation check when output was already seen', () => { @@ -524,11 +527,11 @@ describe('evaluateStreamedOutput error handling', () => { freshState(), codexOpts, ); - expect(result.newTrigger).toEqual({ + expect(result.newTrigger).toMatchObject({ reason: '429', message: errorMessage, }); - expect(result.state.streamedTriggerReason).toEqual({ + expect(result.state.streamedTriggerReason).toMatchObject({ reason: '429', message: errorMessage, }); diff --git a/src/streamed-output-evaluator.ts b/src/streamed-output-evaluator.ts index caa5027..c0b6e07 100644 --- a/src/streamed-output-evaluator.ts +++ b/src/streamed-output-evaluator.ts @@ -75,7 +75,7 @@ export function evaluateStreamedOutput( if (triggerReason) { const newTrigger = nextState.streamedTriggerReason ? undefined - : { reason: triggerReason }; + : { reason: triggerReason, message: outputText }; nextState.streamedTriggerReason = nextState.streamedTriggerReason ?? newTrigger; return { @@ -143,6 +143,7 @@ export function evaluateStreamedOutput( newTrigger = { reason: trigger.reason, retryAfterMs: trigger.retryAfterMs, + ...(output.error ? { message: output.error } : {}), }; } } else if (primaryAgent === 'codex') { diff --git a/src/types.ts b/src/types.ts index 60448a4..4ff32b5 100644 --- a/src/types.ts +++ b/src/types.ts @@ -98,7 +98,6 @@ export interface RoomRoleContext { reviewerServiceId: string; ownerAgentType?: AgentType; reviewerAgentType?: AgentType | null; - failoverOwner: boolean; arbiterServiceId?: string; arbiterAgentType?: AgentType | null; } diff --git a/src/unified-dashboard.ts b/src/unified-dashboard.ts index 61ceb41..f140dee 100644 --- a/src/unified-dashboard.ts +++ b/src/unified-dashboard.ts @@ -15,7 +15,6 @@ import { STATUS_SHOW_ROOMS, USAGE_DASHBOARD_ENABLED, } from './config.js'; -import { getGlobalFailoverInfo } from './service-routing.js'; import { fetchClaudeProfile, fetchClaudeUsage, @@ -760,7 +759,6 @@ function buildModelConfigSection(): string { }, ]; - const failover = getGlobalFailoverInfo(); const lines = ['🤖 *모델 구성*']; for (const role of roleConfigs) { if (!role.agentType && role.label === 'Arbiter') continue; @@ -769,18 +767,7 @@ function buildModelConfigSection(): string { type === 'codex' ? DEFAULT_CODEX_MODEL : DEFAULT_CLAUDE_MODEL; const model = role.model || defaultModel; - // Show fallback status for claude-code roles when global failover is active - const isFallback = failover.active && type === 'claude-code'; - if (isFallback) { - const fallbackModel = DEFAULT_CODEX_MODEL; - lines.push(` **${role.label}** — codex \`${fallbackModel}\` (fallback)`); - } else { - lines.push(` **${role.label}** — ${type} \`${model}\``); - } - } - - if (failover.active) { - lines.push(` ⚠️ **Failover 활성** — ${failover.reason || '알 수 없음'}`); + lines.push(` **${role.label}** — ${type} \`${model}\``); } return lines.join('\n');