From c858b6e446b095343fb7827cbf26a818f7ef76f6 Mon Sep 17 00:00:00 2001 From: Codex Date: Thu, 1 Oct 2026 20:25:35 +0900 Subject: [PATCH] feat: scope paired owner/reviewer sessions to one paired task Each paired room used to resume one owner (and one reviewer) session for weeks, so every call re-read a huge unrelated history (median ~260k input tokens). A stored session is now resumed only while it belongs to the running paired task; the first turn of a new task starts fresh and the new session is bound to that task (router_state paired_session_task:, survives restarts). Later turns of the same task (revisions, follow-up human messages while the task is open) keep resuming it. Arbiter was already fresh per call; single rooms are unchanged. The previous task's final answer still reaches the new session through the carried-forward turn-0 output, so PAIRED_CARRY_FORWARD_LATEST_OWNER_FINAL now defaults to true. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + src/config.test.ts | 8 +- src/config.ts | 2 +- src/config/load-config.ts | 4 +- src/message-agent-executor-target.ts | 38 ++++++- src/message-agent-executor.test.ts | 150 +++++++++++++++++++++++++++ src/message-agent-executor.ts | 5 + src/paired-execution-context.ts | 5 +- src/paired-session-binding.test.ts | 60 +++++++++++ src/paired-session-binding.ts | 45 ++++++++ 10 files changed, 307 insertions(+), 11 deletions(-) create mode 100644 src/paired-session-binding.test.ts create mode 100644 src/paired-session-binding.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 39be084..763ae89 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ ### Changed +- paired 방의 owner·리뷰어 세션을 paired task 단위로 새로 시작. 같은 task 안의 후속 턴(리뷰 반영, 같은 task에 들어온 사용자 후속 메시지)은 그 세션을 이어 쓰고, 새 task의 첫 턴은 이전 세션을 resume하지 않음. 세션이 어느 task 것인지는 `router_state`의 `paired_session_task:<세션 폴더>`에 기록. 이전 task의 마지막 최종 답변은 새 task의 turn 0(carry-forward)으로 계속 전달되며, 이를 위해 `PAIRED_CARRY_FORWARD_LATEST_OWNER_FINAL` 기본값을 `true`로 변경. single 방은 그대로 - 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) diff --git a/src/config.test.ts b/src/config.test.ts index 29dd5ad..f746d14 100644 --- a/src/config.test.ts +++ b/src/config.test.ts @@ -114,14 +114,14 @@ describe('config/env loading', () => { expect(config.TIMEZONE).toBe('UTC'); }); - it('defaults latest-owner-final carry-forward to disabled and honors explicit opt-in', async () => { + it('defaults latest-owner-final carry-forward to enabled and honors explicit opt-out', async () => { let config = await import('./config.js'); - expect(config.PAIRED_CARRY_FORWARD_LATEST_OWNER_FINAL).toBe(false); + expect(config.PAIRED_CARRY_FORWARD_LATEST_OWNER_FINAL).toBe(true); vi.resetModules(); - process.env.PAIRED_CARRY_FORWARD_LATEST_OWNER_FINAL = 'true'; + process.env.PAIRED_CARRY_FORWARD_LATEST_OWNER_FINAL = 'false'; config = await import('./config.js'); - expect(config.PAIRED_CARRY_FORWARD_LATEST_OWNER_FINAL).toBe(true); + expect(config.PAIRED_CARRY_FORWARD_LATEST_OWNER_FINAL).toBe(false); }); it('defaults unsafe-host Claude reviewer fresh-session forcing to disabled and honors explicit opt-in', async () => { diff --git a/src/config.ts b/src/config.ts index 4574628..d13555e 100644 --- a/src/config.ts +++ b/src/config.ts @@ -68,7 +68,7 @@ export const ARBITER_AGENT_TYPE = CONFIG.paired.arbiterAgentType; /** Service ID for the arbiter. Defaults to codex-review for internal routing when arbiter is enabled. */ export const ARBITER_SERVICE_ID = CONFIG.paired.arbiterServiceId; -/** Whether to re-inject the previous task's latest owner final into a superseding task. Default: false. */ +/** Whether to re-inject the previous task's latest owner final into the next paired task. Default: true. */ export const PAIRED_CARRY_FORWARD_LATEST_OWNER_FINAL = CONFIG.paired.carryForwardLatestOwnerFinal; diff --git a/src/config/load-config.ts b/src/config/load-config.ts index 301f399..80ff309 100644 --- a/src/config/load-config.ts +++ b/src/config/load-config.ts @@ -195,9 +195,11 @@ export function loadConfig(): AppConfig { arbiterServiceId: arbiterAgentType ? (readText('ARBITER_SERVICE_ID') ?? codexReviewServiceId) : null, + // Default on: owner/reviewer sessions are scoped to one paired task, so + // the carried-forward final is how a new task keeps the previous answer. carryForwardLatestOwnerFinal: readBoolean( 'PAIRED_CARRY_FORWARD_LATEST_OWNER_FINAL', - false, + true, ), forceFreshClaudeReviewerSessionInUnsafeHostMode: readBoolean( 'PAIRED_FORCE_FRESH_CLAUDE_REVIEWER_SESSION', diff --git a/src/message-agent-executor-target.ts b/src/message-agent-executor-target.ts index 68fd905..0c9f795 100644 --- a/src/message-agent-executor-target.ts +++ b/src/message-agent-executor-target.ts @@ -23,6 +23,7 @@ import { type PairedTurnIdentity, } from './paired-turn-identity.js'; import { buildRoomRoleContext } from './room-role-context.js'; +import { resolveTaskScopedSessionId } from './paired-session-binding.js'; import { getEffectiveChannelLease } from './service-routing.js'; import { buildRoomMemoryBriefing } from './sqlite-memory-store.js'; import { getCurrentClaudeToken } from './claude-oauth-token.js'; @@ -68,6 +69,8 @@ export interface PreparedMessageAgentExecution { forceFreshClaudeReviewerSession: boolean; shouldPersistSession: boolean; currentSessionId: string | undefined; + /** Paired task the persisted session must be bound to (task-scoped sessions). */ + sessionTaskId: string | undefined; provider: 'claude' | 'codex'; memoryBriefing: string | undefined; canRetryClaudeCredentials: boolean; @@ -116,9 +119,6 @@ class MessageAgentExecutionTargetPreparer { const pairedTask = this.resolveLatestPairedTask(currentLease); const executionTarget = this.resolveTarget(currentLease, pairedTask); const roleState = this.resolveRoleExecutionState(executionTarget); - const memoryBriefing = await this.resolveMemoryBriefing( - roleState.currentSessionId, - ); this.writeAgentSnapshots(executionTarget.roleAgentPlan.ownerAgentType); const canRetryClaudeCredentials = this.canRetryClaudeCredentials( roleState.isClaudeCodeAgent, @@ -150,6 +150,14 @@ class MessageAgentExecutionTargetPreparer { activeRole: executionTarget.activeRole, isClaudeCodeAgent: roleState.isClaudeCodeAgent, }); + const sessionTaskId = this.applyTaskScopedSession({ + roleState, + pairedExecutionContext, + executionTarget, + }); + const memoryBriefing = await this.resolveMemoryBriefing( + roleState.currentSessionId, + ); const log = this.createExecutionLogger({ currentLease, pairedTask, @@ -173,6 +181,7 @@ class MessageAgentExecutionTargetPreparer { roleState.forceFreshClaudeReviewerSession, shouldPersistSession: roleState.shouldPersistSession, currentSessionId: roleState.currentSessionId, + sessionTaskId, provider: roleState.provider, memoryBriefing, canRetryClaudeCredentials, @@ -256,6 +265,29 @@ class MessageAgentExecutionTargetPreparer { }; } + /** + * Paired owner/reviewer sessions are scoped to one paired task: resume the + * stored session only when it belongs to the running task, otherwise start + * fresh. Returns the task id a newly persisted session must be bound to. + */ + private applyTaskScopedSession(args: { + roleState: ResolvedRoleExecutionState; + pairedExecutionContext: PreparedPairedExecutionContext | undefined; + executionTarget: ResolvedExecutionTarget; + }): string | undefined { + const { roleState, pairedExecutionContext, executionTarget } = args; + if (!pairedExecutionContext || !roleState.shouldPersistSession) { + return undefined; + } + const taskId = pairedExecutionContext.task.id; + roleState.currentSessionId = resolveTaskScopedSessionId({ + sessionFolder: executionTarget.sessionFolder, + taskId, + storedSessionId: roleState.currentSessionId, + }); + return taskId; + } + private async resolveMemoryBriefing( currentSessionId: string | undefined, ): Promise { diff --git a/src/message-agent-executor.test.ts b/src/message-agent-executor.test.ts index 8efaa88..981a3e7 100644 --- a/src/message-agent-executor.test.ts +++ b/src/message-agent-executor.test.ts @@ -59,6 +59,8 @@ vi.mock('./db.js', () => { updatePairedTaskIfUnchanged: vi.fn(() => true), getPairedTurnAttempts: vi.fn(() => []), getPairedTurnOutputs: vi.fn(() => []), + getRouterState: vi.fn(() => undefined), + setRouterState: vi.fn(), insertPairedTurnOutput: vi.fn(), markPairedTurnRunning: vi.fn(), refreshPairedTaskExecutionLease: vi.fn(() => true), @@ -1830,6 +1832,11 @@ describe('runAgentForGroup room memory', () => { ...makeDeps(), getSessions: () => ({ 'test-group:reviewer': 'reviewer-session' }), }; + vi.mocked(db.getRouterState).mockImplementation((key: string) => + key === 'paired_session_task:test-group:reviewer' + ? 'paired-task-review' + : undefined, + ); vi.mocked(serviceRouting.getEffectiveChannelLease).mockReturnValue({ chat_jid: 'group@test', @@ -3398,3 +3405,146 @@ describe('runAgentForGroup Claude failure recovery', () => { ]); }); }); + +describe('runAgentForGroup task-scoped paired sessions', () => { + const pairedTask = (id: string) => ({ + id, + chat_jid: 'group@test', + group_folder: 'test-group', + 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-03-28T00:00:00.000Z', + updated_at: '2026-03-28T00:00:00.000Z', + }); + + function prepareOwnerTask(taskId: string) { + vi.mocked( + pairedExecutionContext.preparePairedExecutionContext, + ).mockReturnValue({ + task: pairedTask(taskId), + workspace: null, + envOverrides: { + EJCLAW_PAIRED_TASK_ID: taskId, + EJCLAW_PAIRED_ROLE: 'owner', + }, + }); + } + + beforeEach(() => { + vi.resetAllMocks(); + resetPairedFollowUpScheduleState(); + vi.mocked(buildRoomMemoryBriefing).mockResolvedValue(undefined as never); + vi.mocked(agentRunner.runAgentProcess).mockImplementation( + async (_group, _input, _onProcess, onOutput) => { + await onOutput?.({ + status: 'success', + result: 'TASK_DONE\n\nok', + output: { visibility: 'public', text: 'TASK_DONE\n\nok' }, + phase: 'final', + newSessionId: 'session-new', + }); + return { + status: 'success', + result: null, + newSessionId: 'session-new', + }; + }, + ); + }); + + it('starts a fresh owner session for a new paired task and binds it to that task', async () => { + const group = { ...makeGroup(), folder: 'test-group' }; + const deps = { + ...makeDeps(), + getSessions: () => ({ 'test-group': 'session-of-old-task' }), + }; + vi.mocked(db.getRouterState).mockImplementation((key: string) => + key === 'paired_session_task:test-group' ? 'old-task' : undefined, + ); + prepareOwnerTask('new-task'); + + await runAgentForGroup(deps, { + group, + prompt: 'new request', + chatJid: 'group@test', + runId: 'run-new-task', + hasHumanMessage: true, + }); + + expect(agentRunner.runAgentProcess).toHaveBeenCalledWith( + group, + expect.objectContaining({ sessionId: undefined }), + expect.any(Function), + expect.any(Function), + expect.any(Object), + ); + expect(deps.persistSession).toHaveBeenCalledWith( + 'test-group', + 'session-new', + ); + expect(db.setRouterState).toHaveBeenCalledWith( + 'paired_session_task:test-group', + 'new-task', + ); + }); + + it('resumes the owner session for later turns of the same paired task', async () => { + const group = { ...makeGroup(), folder: 'test-group' }; + const deps = { + ...makeDeps(), + getSessions: () => ({ 'test-group': 'session-of-task' }), + }; + vi.mocked(db.getRouterState).mockImplementation((key: string) => + key === 'paired_session_task:test-group' ? 'same-task' : undefined, + ); + prepareOwnerTask('same-task'); + + await runAgentForGroup(deps, { + group, + prompt: 'follow-up', + chatJid: 'group@test', + runId: 'run-same-task', + }); + + expect(agentRunner.runAgentProcess).toHaveBeenCalledWith( + group, + expect.objectContaining({ sessionId: 'session-of-task' }), + expect.any(Function), + expect.any(Function), + expect.any(Object), + ); + }); + + it('keeps resuming the room session for single (non-paired) rooms', async () => { + const group = { ...makeGroup(), folder: 'test-group' }; + const deps = { + ...makeDeps(), + getSessions: () => ({ 'test-group': 'single-room-session' }), + }; + + await runAgentForGroup(deps, { + group, + prompt: 'hello', + chatJid: 'group@test', + runId: 'run-single', + }); + + expect(agentRunner.runAgentProcess).toHaveBeenCalledWith( + group, + expect.objectContaining({ sessionId: 'single-room-session' }), + expect.any(Function), + expect.any(Function), + undefined, + ); + expect(db.setRouterState).not.toHaveBeenCalled(); + }); +}); diff --git a/src/message-agent-executor.ts b/src/message-agent-executor.ts index 403c41b..0210de4 100644 --- a/src/message-agent-executor.ts +++ b/src/message-agent-executor.ts @@ -16,6 +16,7 @@ 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 { bindPairedSessionToTask } from './paired-session-binding.js'; import type { AgentType, PairedRoomRole, RegisteredGroup } from './types.js'; import { clearCompactRefreshIfUnchanged, @@ -186,6 +187,7 @@ export async function runAgentForGroup( runtimePairedTurnIdentity, log, clearRoleSdkSessions, + sessionTaskId, } = preparedExecution; let currentSessionId = preparedExecution.currentSessionId; @@ -281,6 +283,9 @@ export async function runAgentForGroup( fallbackWorkspaceDir: group.workDir ?? null, onPersistSession: (sessionId) => { deps.persistSession(sessionFolder, sessionId); + if (sessionTaskId) { + bindPairedSessionToTask(sessionFolder, sessionTaskId); + } currentSessionId = sessionId; }, registerProcess: (proc, processName, ipcDir) => diff --git a/src/paired-execution-context.ts b/src/paired-execution-context.ts index 43da02d..1bda987 100644 --- a/src/paired-execution-context.ts +++ b/src/paired-execution-context.ts @@ -565,8 +565,9 @@ export function preparePairedExecutionContext(args: { }); } } - // Use a stable per-channel worktree (not per-task) so the Claude SDK - // session persists across tasks. Different channels still get isolation. + // Use a stable per-channel worktree (not per-task). The agent session is + // scoped to the paired task (see paired-session-binding.ts); different + // channels still get isolation. try { workspace = provisionOwnerWorkspaceForPairedTask(latestTask.id); } catch (error) { diff --git a/src/paired-session-binding.test.ts b/src/paired-session-binding.test.ts new file mode 100644 index 0000000..729ae04 --- /dev/null +++ b/src/paired-session-binding.test.ts @@ -0,0 +1,60 @@ +import { beforeEach, describe, expect, it } from 'vitest'; + +import { _initTestDatabase } from './db.js'; +import { + bindPairedSessionToTask, + getPairedSessionTaskId, + resolveTaskScopedSessionId, +} from './paired-session-binding.js'; + +describe('paired session task binding', () => { + beforeEach(() => { + _initTestDatabase(); + }); + + it('starts fresh when the stored session has no task binding (pre-existing room session)', () => { + expect( + resolveTaskScopedSessionId({ + sessionFolder: 'room', + taskId: 'task-1', + storedSessionId: 'weeks-old-session', + }), + ).toBeUndefined(); + }); + + it('resumes only while the session belongs to the running task', () => { + bindPairedSessionToTask('room', 'task-1'); + expect( + resolveTaskScopedSessionId({ + sessionFolder: 'room', + taskId: 'task-1', + storedSessionId: 'session-a', + }), + ).toBe('session-a'); + expect( + resolveTaskScopedSessionId({ + sessionFolder: 'room', + taskId: 'task-2', + storedSessionId: 'session-a', + }), + ).toBeUndefined(); + }); + + it('keeps owner and reviewer bindings separate', () => { + bindPairedSessionToTask('room', 'task-1'); + bindPairedSessionToTask('room:reviewer', 'task-0'); + expect(getPairedSessionTaskId('room')).toBe('task-1'); + expect(getPairedSessionTaskId('room:reviewer')).toBe('task-0'); + }); + + it('returns undefined without a stored session', () => { + bindPairedSessionToTask('room', 'task-1'); + expect( + resolveTaskScopedSessionId({ + sessionFolder: 'room', + taskId: 'task-1', + storedSessionId: undefined, + }), + ).toBeUndefined(); + }); +}); diff --git a/src/paired-session-binding.ts b/src/paired-session-binding.ts new file mode 100644 index 0000000..df5b78b --- /dev/null +++ b/src/paired-session-binding.ts @@ -0,0 +1,45 @@ +import { getRouterState, setRouterState } from './db.js'; + +/** + * Paired-room agent sessions are scoped to one paired task. + * + * Owner and reviewer sessions used to be resumed for weeks across every task + * in a room, so each call re-read hundreds of thousands of tokens of unrelated + * history. Now a stored session is resumed only while it belongs to the task + * that is running; the first turn of a new task starts a fresh session (the + * previous task's final answer reaches it as a carried-forward turn output). + * + * The task a session belongs to is kept in router_state, keyed by the session + * folder, so the scope survives a restart. + */ +const SESSION_TASK_KEY_PREFIX = 'paired_session_task:'; + +function bindingKey(sessionFolder: string): string { + return `${SESSION_TASK_KEY_PREFIX}${sessionFolder}`; +} + +export function getPairedSessionTaskId( + sessionFolder: string, +): string | undefined { + return getRouterState(bindingKey(sessionFolder)) || undefined; +} + +export function bindPairedSessionToTask( + sessionFolder: string, + taskId: string, +): void { + if (getPairedSessionTaskId(sessionFolder) === taskId) return; + setRouterState(bindingKey(sessionFolder), taskId); +} + +/** The stored session id when it belongs to `taskId`, otherwise undefined. */ +export function resolveTaskScopedSessionId(args: { + sessionFolder: string; + taskId: string; + storedSessionId: string | undefined; +}): string | undefined { + if (!args.storedSessionId) return undefined; + return getPairedSessionTaskId(args.sessionFolder) === args.taskId + ? args.storedSessionId + : undefined; +}