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:<folder>,
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 <noreply@anthropic.com>
This commit is contained in:
Codex
2026-10-01 20:25:35 +09:00
parent 8c68577a24
commit c858b6e446
10 changed files with 307 additions and 11 deletions

View File

@@ -10,6 +10,7 @@
### Changed ### 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가 사용 한도에 도달하면 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) - 기본 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) - `@openai/codex`를 0.133.0 → 0.159.3으로 상향. 구버전이 매 실행마다 내던 `failed to decode models response: unknown variant max` 오류와 로그 폭주가 사라지고, 단순 리뷰 턴이 49초 → 5초로 단축됨 (a7f2e02)

View File

@@ -114,14 +114,14 @@ describe('config/env loading', () => {
expect(config.TIMEZONE).toBe('UTC'); 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'); 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(); 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'); 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 () => { it('defaults unsafe-host Claude reviewer fresh-session forcing to disabled and honors explicit opt-in', async () => {

View File

@@ -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. */ /** Service ID for the arbiter. Defaults to codex-review for internal routing when arbiter is enabled. */
export const ARBITER_SERVICE_ID = CONFIG.paired.arbiterServiceId; 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 = export const PAIRED_CARRY_FORWARD_LATEST_OWNER_FINAL =
CONFIG.paired.carryForwardLatestOwnerFinal; CONFIG.paired.carryForwardLatestOwnerFinal;

View File

@@ -195,9 +195,11 @@ export function loadConfig(): AppConfig {
arbiterServiceId: arbiterAgentType arbiterServiceId: arbiterAgentType
? (readText('ARBITER_SERVICE_ID') ?? codexReviewServiceId) ? (readText('ARBITER_SERVICE_ID') ?? codexReviewServiceId)
: null, : 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( carryForwardLatestOwnerFinal: readBoolean(
'PAIRED_CARRY_FORWARD_LATEST_OWNER_FINAL', 'PAIRED_CARRY_FORWARD_LATEST_OWNER_FINAL',
false, true,
), ),
forceFreshClaudeReviewerSessionInUnsafeHostMode: readBoolean( forceFreshClaudeReviewerSessionInUnsafeHostMode: readBoolean(
'PAIRED_FORCE_FRESH_CLAUDE_REVIEWER_SESSION', 'PAIRED_FORCE_FRESH_CLAUDE_REVIEWER_SESSION',

View File

@@ -23,6 +23,7 @@ import {
type PairedTurnIdentity, type PairedTurnIdentity,
} from './paired-turn-identity.js'; } from './paired-turn-identity.js';
import { buildRoomRoleContext } from './room-role-context.js'; import { buildRoomRoleContext } from './room-role-context.js';
import { resolveTaskScopedSessionId } from './paired-session-binding.js';
import { getEffectiveChannelLease } from './service-routing.js'; import { getEffectiveChannelLease } from './service-routing.js';
import { buildRoomMemoryBriefing } from './sqlite-memory-store.js'; import { buildRoomMemoryBriefing } from './sqlite-memory-store.js';
import { getCurrentClaudeToken } from './claude-oauth-token.js'; import { getCurrentClaudeToken } from './claude-oauth-token.js';
@@ -68,6 +69,8 @@ export interface PreparedMessageAgentExecution {
forceFreshClaudeReviewerSession: boolean; forceFreshClaudeReviewerSession: boolean;
shouldPersistSession: boolean; shouldPersistSession: boolean;
currentSessionId: string | undefined; currentSessionId: string | undefined;
/** Paired task the persisted session must be bound to (task-scoped sessions). */
sessionTaskId: string | undefined;
provider: 'claude' | 'codex'; provider: 'claude' | 'codex';
memoryBriefing: string | undefined; memoryBriefing: string | undefined;
canRetryClaudeCredentials: boolean; canRetryClaudeCredentials: boolean;
@@ -116,9 +119,6 @@ class MessageAgentExecutionTargetPreparer {
const pairedTask = this.resolveLatestPairedTask(currentLease); const pairedTask = this.resolveLatestPairedTask(currentLease);
const executionTarget = this.resolveTarget(currentLease, pairedTask); const executionTarget = this.resolveTarget(currentLease, pairedTask);
const roleState = this.resolveRoleExecutionState(executionTarget); const roleState = this.resolveRoleExecutionState(executionTarget);
const memoryBriefing = await this.resolveMemoryBriefing(
roleState.currentSessionId,
);
this.writeAgentSnapshots(executionTarget.roleAgentPlan.ownerAgentType); this.writeAgentSnapshots(executionTarget.roleAgentPlan.ownerAgentType);
const canRetryClaudeCredentials = this.canRetryClaudeCredentials( const canRetryClaudeCredentials = this.canRetryClaudeCredentials(
roleState.isClaudeCodeAgent, roleState.isClaudeCodeAgent,
@@ -150,6 +150,14 @@ class MessageAgentExecutionTargetPreparer {
activeRole: executionTarget.activeRole, activeRole: executionTarget.activeRole,
isClaudeCodeAgent: roleState.isClaudeCodeAgent, isClaudeCodeAgent: roleState.isClaudeCodeAgent,
}); });
const sessionTaskId = this.applyTaskScopedSession({
roleState,
pairedExecutionContext,
executionTarget,
});
const memoryBriefing = await this.resolveMemoryBriefing(
roleState.currentSessionId,
);
const log = this.createExecutionLogger({ const log = this.createExecutionLogger({
currentLease, currentLease,
pairedTask, pairedTask,
@@ -173,6 +181,7 @@ class MessageAgentExecutionTargetPreparer {
roleState.forceFreshClaudeReviewerSession, roleState.forceFreshClaudeReviewerSession,
shouldPersistSession: roleState.shouldPersistSession, shouldPersistSession: roleState.shouldPersistSession,
currentSessionId: roleState.currentSessionId, currentSessionId: roleState.currentSessionId,
sessionTaskId,
provider: roleState.provider, provider: roleState.provider,
memoryBriefing, memoryBriefing,
canRetryClaudeCredentials, 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( private async resolveMemoryBriefing(
currentSessionId: string | undefined, currentSessionId: string | undefined,
): Promise<string | undefined> { ): Promise<string | undefined> {

View File

@@ -59,6 +59,8 @@ vi.mock('./db.js', () => {
updatePairedTaskIfUnchanged: vi.fn(() => true), updatePairedTaskIfUnchanged: vi.fn(() => true),
getPairedTurnAttempts: vi.fn(() => []), getPairedTurnAttempts: vi.fn(() => []),
getPairedTurnOutputs: vi.fn(() => []), getPairedTurnOutputs: vi.fn(() => []),
getRouterState: vi.fn(() => undefined),
setRouterState: vi.fn(),
insertPairedTurnOutput: vi.fn(), insertPairedTurnOutput: vi.fn(),
markPairedTurnRunning: vi.fn(), markPairedTurnRunning: vi.fn(),
refreshPairedTaskExecutionLease: vi.fn(() => true), refreshPairedTaskExecutionLease: vi.fn(() => true),
@@ -1830,6 +1832,11 @@ describe('runAgentForGroup room memory', () => {
...makeDeps(), ...makeDeps(),
getSessions: () => ({ 'test-group:reviewer': 'reviewer-session' }), 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({ vi.mocked(serviceRouting.getEffectiveChannelLease).mockReturnValue({
chat_jid: 'group@test', 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();
});
});

View File

@@ -16,6 +16,7 @@ import { getPairedTaskById } from './db.js';
import { completePairedTaskWithReason } from './paired-task-status.js'; import { completePairedTaskWithReason } from './paired-task-status.js';
import { prepareMessageAgentExecutionTarget } from './message-agent-executor-target.js'; import { prepareMessageAgentExecutionTarget } from './message-agent-executor-target.js';
import { shouldRetryFreshSessionOnAgentFailure } from './session-recovery.js'; import { shouldRetryFreshSessionOnAgentFailure } from './session-recovery.js';
import { bindPairedSessionToTask } from './paired-session-binding.js';
import type { AgentType, PairedRoomRole, RegisteredGroup } from './types.js'; import type { AgentType, PairedRoomRole, RegisteredGroup } from './types.js';
import { import {
clearCompactRefreshIfUnchanged, clearCompactRefreshIfUnchanged,
@@ -186,6 +187,7 @@ export async function runAgentForGroup(
runtimePairedTurnIdentity, runtimePairedTurnIdentity,
log, log,
clearRoleSdkSessions, clearRoleSdkSessions,
sessionTaskId,
} = preparedExecution; } = preparedExecution;
let currentSessionId = preparedExecution.currentSessionId; let currentSessionId = preparedExecution.currentSessionId;
@@ -281,6 +283,9 @@ export async function runAgentForGroup(
fallbackWorkspaceDir: group.workDir ?? null, fallbackWorkspaceDir: group.workDir ?? null,
onPersistSession: (sessionId) => { onPersistSession: (sessionId) => {
deps.persistSession(sessionFolder, sessionId); deps.persistSession(sessionFolder, sessionId);
if (sessionTaskId) {
bindPairedSessionToTask(sessionFolder, sessionTaskId);
}
currentSessionId = sessionId; currentSessionId = sessionId;
}, },
registerProcess: (proc, processName, ipcDir) => registerProcess: (proc, processName, ipcDir) =>

View File

@@ -565,8 +565,9 @@ export function preparePairedExecutionContext(args: {
}); });
} }
} }
// Use a stable per-channel worktree (not per-task) so the Claude SDK // Use a stable per-channel worktree (not per-task). The agent session is
// session persists across tasks. Different channels still get isolation. // scoped to the paired task (see paired-session-binding.ts); different
// channels still get isolation.
try { try {
workspace = provisionOwnerWorkspaceForPairedTask(latestTask.id); workspace = provisionOwnerWorkspaceForPairedTask(latestTask.id);
} catch (error) { } catch (error) {

View File

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

View File

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