refactor: replace the Claude→Codex failover with a usage-limit notice

When Claude hit a limit the run was handed to a Codex service
(codex-main/codex-review) through service_handoffs and a global owner
failover. That service does not exist in this deployment, so handoffs
stayed pending forever (2 rows since May) and the user got no answer.

Removed:
- handoff creation (message-agent-executor-handoff, paired-turn-fallback)
  and the delegated paired-execution path
- the pending-handoff poll/claim worker (message-runtime-handoffs) and the
  service_handoffs CRUD module (db/service-handoffs, db exports)
- global owner failover in service-routing, its recovery timer in index,
  the dashboard failover line, the codex-review failover prompt pack and
  prompts/codex-review-failover-platform.md
- failoverOwner in RoomRoleContext and the `failover=` ROOM_ROLE field
- OWNER_/REVIEWER_/ARBITER_FALLBACK_ENABLED and FAILOVER_MIN_DURATION_MS
- tests for the removed behaviour

Now, when a Claude run fails with a usage/rate limit (trigger reason
429 or usage-exhausted) the executor closes the open paired task as
completed/claude_usage_limit and sends the room one final notice:
"Claude 사용 한도에 도달했습니다. 21:40에 재개할 수 있습니다." The reset time
comes from the error text (CLI banner "resets 9:40pm (Asia/Seoul)", dated
banners, "try again at ...", ISO timestamps), else from the cached usage
API window at 100%, else "잠시 후 다시 시도해 주세요". Nothing retries
silently; the next user message starts a new task. Other Claude failures
(session failure, org access denied) now end as ordinary run errors.

The service_handoffs table, its columns on paired_turn_attempts and the
migrations stay untouched for the later migration squash; the runtime no
longer reads or writes them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Codex
2026-10-01 20:14:25 +09:00
parent a9eab5cb94
commit 8c68577a24
62 changed files with 719 additions and 3963 deletions

View File

@@ -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

View File

@@ -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/<n>`) 제거. 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

View File

@@ -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 기반 빠른 런타임

View File

@@ -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에 넘겨서 빌링하는 구조는 사용하지 않습니다.

View File

@@ -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`

View File

@@ -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);
});

View File

@@ -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',
);
});

View File

@@ -66,7 +66,6 @@ describe('codex reviewer runtime guard', () => {
role: 'reviewer',
ownerServiceId: 'codex-main',
reviewerServiceId: 'codex-review',
failoverOwner: false,
}),
).toBe(true);
});

View File

@@ -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',
);
});

View File

@@ -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}`;
}

View File

@@ -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 };
}

View File

@@ -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,

View File

@@ -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,
});

View File

@@ -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,
},
});
});

View File

@@ -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',
});
});
});

View File

@@ -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();
});
});

View File

@@ -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);
});
});

223
src/claude-usage-limit.ts Normal file
View File

@@ -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<string, number> = {
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);
}

View File

@@ -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

View File

@@ -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;

View File

@@ -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,

View File

@@ -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;

File diff suppressed because it is too large Load Diff

View File

@@ -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';

View File

@@ -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;

View File

@@ -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();
}

View File

@@ -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,

View File

@@ -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<string, string> {
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<string, string> = {};
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;
})();
}

View File

@@ -182,7 +182,6 @@ function buildRoleRuntimeConfigRole(
modelConfig: {
model?: string;
effort?: string;
fallbackEnabled: boolean;
},
serviceId: string | null,
): Record<string, unknown> {
@@ -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,
};
}

View File

@@ -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<void> {
runtimeState.loadState();
// Graceful shutdown handlers
let leaseRecoveryTimer: ReturnType<typeof setInterval> | 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<void> {
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);

View File

@@ -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<string, unknown>, msg: string) => void;
warn: (obj: Record<string, unknown>, 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;
}

View File

@@ -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<MessageAgentAttempt>;
@@ -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<boolean>;
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<AttemptResult> {
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<boolean> {
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 {

View File

@@ -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();

View File

@@ -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 () => {

View File

@@ -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<void>;
log: { warn: (obj: Record<string, unknown>, msg: string) => void };
},
): Promise<boolean> {
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<void>;
}): Promise<void> {
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<GroupQueue, 'registerProcess' | 'enqueueMessageCheck'> &
@@ -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,

View File

@@ -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<string, unknown> = {}) {
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<string, string> = {};
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');
});
});

View File

@@ -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>,
) => void;
processClaimedHandoff: (handoff: ServiceHandoff) => Promise<void>;
}): 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>) => void)
| undefined;
getRoomBindings: () => Record<string, RegisteredGroup>;
channels: Channel[];
executeTurn: ExecuteTurnFn;
getLastAgentTimestamps: () => Record<string, string>;
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<PairedTask, 'id' | 'status' | 'round_trip_count' | 'updated_at'>
| 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<PairedTask, 'id' | 'status' | 'round_trip_count' | 'updated_at'>
| 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<PairedTask, 'id' | 'status' | 'round_trip_count' | 'updated_at'>
| 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<string, RegisteredGroup>;
channels: Channel[];
executeTurn: ExecuteTurnFn;
lastAgentTimestamps: Record<string, string>;
saveState: () => void;
getPairedTaskById?:
| ((
id: string,
) =>
| Pick<PairedTask, 'id' | 'status' | 'round_trip_count' | 'updated_at'>
| undefined)
| undefined;
enqueueMessageCheck?: ((chatJid: string) => void) | undefined;
}): Promise<void> {
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',
);
}
}

View File

@@ -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<void> {
args.enqueuePendingHandoffs();
const roomBindings = args.getRoomBindings();
const jids = Object.keys(roomBindings);
const { messages, newSeqCursor } = getNewMessagesBySeq(

View File

@@ -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',

View File

@@ -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,

View File

@@ -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');

View File

@@ -1,34 +1,3 @@
import type { PairedRoomRole } from './types.js';
import type { ServiceHandoff } from './db.js';
export function resolveHandoffRoleOverride(
handoff: Pick<ServiceHandoff, 'target_role' | 'intended_role' | 'reason'>,
): 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';
}

View File

@@ -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,

View File

@@ -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),

View File

@@ -80,7 +80,6 @@ const ownerContext: RoomRoleContext = {
role: 'owner',
ownerServiceId: 'codex-main',
reviewerServiceId: 'claude-review',
failoverOwner: false,
};
function buildTask(overrides: Partial<PairedTask> = {}): PairedTask {

View File

@@ -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> = {}): PairedTask {

View File

@@ -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',

View File

@@ -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',

View File

@@ -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;
}

View File

@@ -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' });
});
});

View File

@@ -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<AgentTriggerReason>([
'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',
},
};
}

View File

@@ -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<string, string> = {};
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);
});
});

View File

@@ -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', () => {

View File

@@ -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,

View File

@@ -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 }

View File

@@ -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 };

View File

@@ -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',

View File

@@ -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');
}

View File

@@ -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,
});

View File

@@ -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') {

View File

@@ -98,7 +98,6 @@ export interface RoomRoleContext {
reviewerServiceId: string;
ownerAgentType?: AgentType;
reviewerAgentType?: AgentType | null;
failoverOwner: boolean;
arbiterServiceId?: string;
arbiterAgentType?: AgentType | null;
}

View File

@@ -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');