feat: skip or slim down the owner finalize turn

(a) When the reviewer approves the owner's first TASK_DONE answer on the
first review (one review round, outputs are exactly owner -> reviewer, no
revision or arbiter turns) and the owner workspace still matches the
approved tree with a clean working tree, no owner run happens: the task is
completed as done and the reviewed answer (status line stripped) is posted
as the final message. If the review was requested with a bare "검토해줘"
after a review-skipped answer, a one-line confirmation is posted instead of
repeating the answer.

(b) Every other finalize turn runs in a fresh, non-persisted session (no
resume of the task's long working session, no room memory briefing) with a
self-contained prompt: this task's user messages, the latest six turn
outputs and the finalize instructions/format. All three finalize entry
points (pending turn, inline bot-only follow-up, queued turn) use it.

The owner prompt now states that the first TASK_DONE answer must already
follow the final-message format because it may be posted as the final
message unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Codex
2026-10-01 20:42:12 +09:00
parent 7f54c47e64
commit 0283abbb56
14 changed files with 604 additions and 39 deletions

View File

@@ -150,14 +150,20 @@ class MessageAgentExecutionTargetPreparer {
activeRole: executionTarget.activeRole,
isClaudeCodeAgent: roleState.isClaudeCodeAgent,
});
const isFinalizeTurn =
runtimeTurn.runtimePairedTurnIdentity?.intentKind ===
'finalize-owner-turn';
const sessionTaskId = this.applyTaskScopedSession({
roleState,
pairedExecutionContext,
executionTarget,
isFinalizeTurn,
});
const memoryBriefing = await this.resolveMemoryBriefing(
roleState.currentSessionId,
);
// A finalize turn only consolidates the outputs in its prompt; it does not
// need the room memory briefing.
const memoryBriefing = isFinalizeTurn
? undefined
: await this.resolveMemoryBriefing(roleState.currentSessionId);
const log = this.createExecutionLogger({
currentLease,
pairedTask,
@@ -269,16 +275,26 @@ 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.
*
* The owner finalize turn runs in a throwaway session: its prompt carries
* the request and the turn outputs, so it never resumes (or replaces) the
* task's long working session.
*/
private applyTaskScopedSession(args: {
roleState: ResolvedRoleExecutionState;
pairedExecutionContext: PreparedPairedExecutionContext | undefined;
executionTarget: ResolvedExecutionTarget;
isFinalizeTurn: boolean;
}): string | undefined {
const { roleState, pairedExecutionContext, executionTarget } = args;
if (!pairedExecutionContext || !roleState.shouldPersistSession) {
return undefined;
}
if (args.isFinalizeTurn) {
roleState.currentSessionId = undefined;
roleState.shouldPersistSession = false;
return undefined;
}
const taskId = pairedExecutionContext.task.id;
roleState.currentSessionId = resolveTaskScopedSessionId({
sessionFolder: executionTarget.sessionFolder,

View File

@@ -198,6 +198,11 @@ vi.mock('./sqlite-memory-store.js', () => ({
buildRoomMemoryBriefing: vi.fn(),
}));
vi.mock('./paired-finalize.js', () => ({
resolveFastFinalizeText: vi.fn(() => null),
completeTaskWithoutFinalizeRun: vi.fn(() => true),
}));
vi.mock('./paired-execution-context.js', () => ({
completePairedExecutionContext: vi.fn(),
preparePairedExecutionContext: vi.fn(() => undefined),
@@ -211,6 +216,8 @@ import { buildRoomMemoryBriefing } from './sqlite-memory-store.js';
import { runAgentForGroup } from './message-agent-executor.js';
import { resetPairedFollowUpScheduleState } from './paired-follow-up-scheduler.js';
import * as pairedExecutionContext from './paired-execution-context.js';
import * as pairedFinalize from './paired-finalize.js';
import { buildPairedTurnIdentity } from './paired-turn-identity.js';
import * as sessionRecovery from './session-recovery.js';
import * as serviceRouting from './service-routing.js';
import * as tokenRefresh from './token-refresh.js';
@@ -3655,3 +3662,125 @@ describe('runAgentForGroup owner review-skip marker', () => {
expect(delivered.join('\n')).not.toContain('검토 생략');
});
});
describe('runAgentForGroup owner finalize turn', () => {
const task = {
id: 'task-fin',
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: 1,
review_requested_at: null,
status: 'merge_ready' 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:05:00.000Z',
};
const finalizeTurn = buildPairedTurnIdentity({
taskId: task.id,
taskUpdatedAt: task.updated_at,
intentKind: 'finalize-owner-turn',
role: 'owner',
});
beforeEach(() => {
vi.resetAllMocks();
resetPairedFollowUpScheduleState();
vi.mocked(buildRoomMemoryBriefing).mockResolvedValue('memory');
vi.mocked(db.getLatestOpenPairedTaskForChat).mockReturnValue(task);
vi.mocked(db.getPairedTaskById).mockReturnValue(task);
vi.mocked(db.getRouterState).mockReturnValue(task.id);
vi.mocked(
pairedExecutionContext.preparePairedExecutionContext,
).mockReturnValue({
task,
workspace: null,
envOverrides: { EJCLAW_PAIRED_TASK_ID: task.id },
});
vi.mocked(agentRunner.runAgentProcess).mockImplementation(
async (_group, _input, _onProcess, onOutput) => {
await onOutput?.({
status: 'success',
result: 'TASK_DONE\n\n정리',
output: { visibility: 'public', text: 'TASK_DONE\n\n정리' },
phase: 'final',
newSessionId: 'finalize-session',
});
return { status: 'success', result: null };
},
);
});
async function runFinalize(deps = makeDeps()): Promise<string[]> {
const delivered: string[] = [];
await runAgentForGroup(deps, {
group: { ...makeGroup(), folder: 'test-group' },
prompt: 'finalize',
chatJid: 'group@test',
runId: 'run-finalize',
forcedRole: 'owner',
pairedTurnIdentity: finalizeTurn,
onOutput: async (output) => {
if (output.output?.visibility === 'public') {
delivered.push(output.output.text);
}
},
});
return delivered;
}
it('posts the reviewed first answer without running the owner when it qualifies', async () => {
vi.mocked(pairedFinalize.resolveFastFinalizeText).mockReturnValue(
'결론입니다.',
);
vi.mocked(pairedFinalize.completeTaskWithoutFinalizeRun).mockReturnValue(
true,
);
const delivered = await runFinalize();
expect(agentRunner.runAgentProcess).not.toHaveBeenCalled();
expect(pairedFinalize.completeTaskWithoutFinalizeRun).toHaveBeenCalledWith(
task,
);
expect(delivered).toEqual(['결론입니다.']);
expect(db.insertPairedTurnOutput).toHaveBeenCalledWith(
task.id,
1,
'owner',
'결론입니다.',
);
expect(db.completePairedTurn).toHaveBeenCalledWith(
expect.objectContaining({ turnId: finalizeTurn.turnId }),
);
});
it('runs a lightweight finalize in a fresh session that is not persisted', async () => {
const deps = {
...makeDeps(),
getSessions: () => ({ 'test-group': 'long-task-session' }),
};
await runFinalize(deps);
expect(agentRunner.runAgentProcess).toHaveBeenCalledWith(
expect.any(Object),
expect.objectContaining({
sessionId: undefined,
memoryBriefing: undefined,
}),
expect.any(Function),
expect.any(Function),
expect.any(Object),
);
expect(deps.persistSession).not.toHaveBeenCalled();
expect(db.setRouterState).not.toHaveBeenCalled();
expect(buildRoomMemoryBriefing).not.toHaveBeenCalled();
});
});

View File

@@ -17,6 +17,10 @@ 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 {
completeTaskWithoutFinalizeRun,
resolveFastFinalizeText,
} from './paired-finalize.js';
import type { AgentType, PairedRoomRole, RegisteredGroup } from './types.js';
import {
clearCompactRefreshIfUnchanged,
@@ -106,6 +110,39 @@ async function reportClaudeUsageLimitToRoom(
return true;
}
/**
* Owner finalize without an agent run (see paired-finalize.ts): close the task
* and deliver the already-reviewed answer as the final message. Returns false
* when the finalize turn must run normally.
*/
async function deliverFinalizeWithoutRun(args: {
taskId: string;
pairedExecutionLifecycle: PairedExecutionLifecycle;
onOutput?: (output: AgentOutput) => Promise<void>;
log: { info: (obj: Record<string, unknown>, msg: string) => void };
}): Promise<boolean> {
const task = getPairedTaskById(args.taskId);
const text = task ? resolveFastFinalizeText(task) : null;
if (!task || !text || !completeTaskWithoutFinalizeRun(task)) return false;
args.log.info(
{ pairedTaskId: task.id, textLength: text.length },
'Reviewer approved the first answer unchanged; finalized without an owner run',
);
const { pairedExecutionLifecycle } = args;
pairedExecutionLifecycle.updateSummary({ outputText: text });
if (pairedExecutionLifecycle.recordFinalOutputBeforeDelivery(text)) {
await args.onOutput?.({
status: 'success',
result: text,
output: { visibility: 'public', text },
phase: 'final',
});
}
pairedExecutionLifecycle.markSawOutput(true);
pairedExecutionLifecycle.markStatus('succeeded');
return true;
}
/** Send a final notice to the room and record the execution as failed. */
async function deliverNoticeAndFailExecution(args: {
notice: string;
@@ -265,6 +302,28 @@ export async function runAgentForGroup(
return 'success';
}
if (
pairedExecutionContext &&
runtimePairedTurnIdentity?.intentKind === 'finalize-owner-turn'
) {
let finalizedWithoutRun = false;
try {
finalizedWithoutRun = await deliverFinalizeWithoutRun({
taskId: pairedExecutionContext.task.id,
pairedExecutionLifecycle,
onOutput,
log,
});
} catch (err) {
await pairedExecutionLifecycle.asyncFinalize();
throw err;
}
if (finalizedWithoutRun) {
await pairedExecutionLifecycle.asyncFinalize();
return 'success';
}
}
const runAttempt = (currentProvider: 'claude' | 'codex') =>
runMessageAgentAttempt({
provider: currentProvider,

View File

@@ -163,6 +163,7 @@ export async function processQueuedGroupDispatch(args: {
await executeBotOnlyPairedFollowUpAction({
action: botOnlyFollowUpAction,
chatJid,
timezone: args.timezone,
group,
runId: botOnlyFollowUpRunId,
channel,

View File

@@ -67,6 +67,7 @@ describe('executeBotOnlyPairedFollowUpAction', () => {
const first = await executeBotOnlyPairedFollowUpAction({
action,
chatJid: 'group@test',
timezone: 'UTC',
group: {
name: 'Test Group',
folder: 'test-group',
@@ -88,6 +89,7 @@ describe('executeBotOnlyPairedFollowUpAction', () => {
const second = await executeBotOnlyPairedFollowUpAction({
action,
chatJid: 'group@test',
timezone: 'UTC',
group: {
name: 'Test Group',
folder: 'test-group',
@@ -167,6 +169,7 @@ describe('executeBotOnlyPairedFollowUpAction', () => {
cursor: 42,
},
chatJid: 'group@test',
timezone: 'UTC',
group: {
name: 'Test Group',
folder: 'test-group',

View File

@@ -167,7 +167,12 @@ export function buildPendingPairedTurn(args: {
if (nextTurnAction.kind === 'finalize-owner-turn') {
return {
prompt: buildFinalizePendingPrompt({ turnOutputs }),
prompt: buildFinalizePendingPrompt({
chatJid,
timezone,
turnOutputs,
taskHumanMessages: taskContextMessages,
}),
channel: resolveChannel(taskStatus),
cursor,
taskId: task.id,
@@ -340,6 +345,7 @@ export function resolveBotOnlyPairedFollowUpAction(args: {
export async function executeBotOnlyPairedFollowUpAction(args: {
action: BotOnlyPairedFollowUpAction;
chatJid: string;
timezone: string;
group: RegisteredGroup;
runId: string;
channel: Channel;
@@ -366,6 +372,7 @@ export async function executeBotOnlyPairedFollowUpAction(args: {
const {
action,
chatJid,
timezone,
group,
runId,
channel,
@@ -446,7 +453,10 @@ export async function executeBotOnlyPairedFollowUpAction(args: {
const { deliverySucceeded } = await executeTurn({
group,
prompt: buildFinalizePendingPrompt({
chatJid,
timezone,
turnOutputs: getPairedTurnOutputs(action.task.id),
taskHumanMessages: getTaskContextMessages(chatJid, action.task),
}),
chatJid,
runId,

View File

@@ -576,30 +576,29 @@ describe('message-runtime-prompts prompt hygiene', () => {
expect(prompt).not.toContain('#129');
});
it('does not reinject reviewer output into finalize prompts', () => {
it('gives the fresh-session finalize turn the request, the latest outputs and the format', () => {
const outputs = Array.from({ length: 8 }, (_, index) =>
makeTurnOutput(`STEP_DONE\nR-0${index + 1}`, 'owner', {
turn_number: index + 1,
created_at: `2026-04-20T01:0${index}:00.000Z`,
}),
);
const prompt = buildFinalizePendingPrompt({
turnOutputs: [
makeTurnOutput(
`TASK_DONE
현재 검증:
- build pass
다음 단계:
- unrelated cleanup
누적 배포 대기 상태:
#131 pending`,
'reviewer',
),
chatJid: 'group@test',
timezone: 'UTC',
turnOutputs: outputs,
taskHumanMessages: [
makeHumanMessage('로그인 버그 고쳐줘', '2026-04-20T00:59:30.000Z'),
],
});
expect(prompt).not.toContain("Reviewer's final assessment:");
expect(prompt).not.toContain('현재 검증:');
expect(prompt).not.toContain('build pass');
expect(prompt).not.toContain('다음 단계');
expect(prompt).not.toContain('unrelated cleanup');
expect(prompt).not.toContain('누적 배포 대기 상태');
expect(prompt).not.toContain('#131');
expect(prompt).toContain('로그인 버그 고쳐줘');
expect(prompt).toContain('R-08');
expect(prompt).toContain('R-03');
expect(prompt).not.toContain('R-02');
expect(prompt).toContain('Earlier paired turn outputs omitted: 2');
expect(prompt).toContain('fresh session');
expect(prompt).toContain('사용자 액션 아이템');
expect(prompt).toContain('your first line must be TASK_DONE');
});
});

View File

@@ -315,10 +315,28 @@ export function buildArbiterPromptForTask(args: {
});
}
export function buildFinalizePendingPrompt(_args: {
/**
* Owner finalize prompt. The finalize turn runs in a fresh session (it does not
* resume the task's working session), so the prompt carries everything it
* needs: this task's user messages and the latest turn outputs.
*/
export function buildFinalizePendingPrompt(args: {
chatJid: string;
timezone: string;
turnOutputs: PairedTurnOutput[];
taskHumanMessages: NewMessage[];
}): string {
return `The reviewer approved the current task scope (TASK_DONE / legacy DONE). Finalize and report the result.
const context = turnOutputsOnlyPrompt(
args.chatJid,
args.timezone,
args.turnOutputs,
args.taskHumanMessages.filter((message) => !message.is_bot_message),
);
return `${context}
The reviewer approved the current task scope (TASK_DONE / legacy DONE). Finalize and report the result.
This finalize turn runs in a fresh session: the user's request and the latest owner/reviewer/arbiter outputs above are your context, together with the current workspace. Do not redo the work; inspect the workspace only to confirm something the outputs leave unclear.
Write the user-facing final message in the finalize message format: status line, direct answer, summary of what was done, 사용자 액션 아이템. Use reviewer or arbiter outputs only to correct the answer; do not copy their checklists, ledgers, or backlogs.
If you intend to close this paired turn now, your first line must be TASK_DONE.
Do not use STEP_DONE only because a broader roadmap still has remaining work; close the approved slice and continue the next slice in a new owner turn.
Use STEP_DONE only when this same approved scope still needs additional owner changes and another review pass.

View File

@@ -2,6 +2,7 @@ import { getPairedTurnOutputs } from './db.js';
import { logger } from './logger.js';
import {
buildArbiterPromptForTask,
buildFinalizePendingPrompt,
buildPairedTurnPrompt,
} from './message-runtime-prompts.js';
import { resolveOwnerTaskForHumanMessage } from './paired-execution-context.js';
@@ -85,6 +86,7 @@ function isHumanMessageFreshForTask(
function buildQueuedGroupTurnPrompt(args: {
turnRole: 'owner' | 'reviewer' | 'arbiter';
intentKind: PairedTurnReservationIntentKind | null;
currentTask: PairedTask | null | undefined;
chatJid: string;
timezone: string;
@@ -112,6 +114,15 @@ function buildQueuedGroupTurnPrompt(args: {
});
}
if (args.currentTask && args.intentKind === 'finalize-owner-turn') {
return buildFinalizePendingPrompt({
chatJid: args.chatJid,
timezone: args.timezone,
turnOutputs: args.turnOutputs,
taskHumanMessages: getTaskContextMessages(args.chatJid, args.currentTask),
});
}
if (args.currentTask) {
return buildPairedTurnPrompt({
taskId: args.currentTask.id,
@@ -365,6 +376,7 @@ export async function runQueuedGroupTurn(args: {
const prompt = buildQueuedGroupTurnPrompt({
turnRole,
intentKind: queuedIntentKind,
currentTask,
chatJid,
timezone: args.timezone,

View File

@@ -1614,7 +1614,7 @@ describe('createMessageRuntime', () => {
);
});
it('uses a compact finalize prompt without reinjecting reviewer output', async () => {
it('gives the fresh-session finalize turn the latest outputs and finalize instructions', async () => {
const chatJid = 'group@test';
const group = makeGroup('codex');
const channel = makeChannel(chatJid);
@@ -1667,16 +1667,18 @@ describe('createMessageRuntime', () => {
]);
vi.mocked(agentRunner.runAgentProcess).mockImplementation(
async (_group, input, _onProcess, onOutput) => {
expect(input.prompt).toBe(
'The reviewer approved the current task scope (TASK_DONE / legacy DONE). Finalize and report the result.\n' +
'If you intend to close this paired turn now, your first line must be TASK_DONE.\n' +
'Do not use STEP_DONE only because a broader roadmap still has remaining work; close the approved slice and continue the next slice in a new owner turn.\n' +
'Use STEP_DONE only when this same approved scope still needs additional owner changes and another review pass.\n' +
'If your first line is DONE_WITH_CONCERNS, the system will reopen review instead of finishing.',
expect(input.prompt).toContain(
'The reviewer approved the current task scope (TASK_DONE / legacy DONE). Finalize and report the result.',
);
expect(input.prompt).toContain('fresh session');
expect(input.prompt).toContain(
'If your first line is DONE_WITH_CONCERNS, the system will reopen review instead of finishing.',
);
expect(input.prompt).not.toContain("Reviewer's final assessment:");
expect(input.prompt).not.toContain(longReviewerOutput);
expect(input.prompt).not.toContain('이전 reviewer 요약');
expect(input.prompt).toContain(longReviewerOutput);
expect(input.prompt).toContain('owner 중간 응답');
expect(input.prompt).toContain('이전 reviewer 요약');
expect(input.sessionId).toBeUndefined();
await onOutput?.({
status: 'success',
phase: 'final',
@@ -1778,10 +1780,11 @@ describe('createMessageRuntime', () => {
]);
vi.mocked(agentRunner.runAgentProcess).mockImplementation(
async (_group, input, _onProcess, onOutput) => {
expect(input.prompt).toBe(
'The reviewer approved the current task scope (TASK_DONE / legacy DONE). Finalize and report the result.\nIf you intend to close this paired turn now, your first line must be TASK_DONE.\nDo not use STEP_DONE only because a broader roadmap still has remaining work; close the approved slice and continue the next slice in a new owner turn.\nUse STEP_DONE only when this same approved scope still needs additional owner changes and another review pass.\nIf your first line is DONE_WITH_CONCERNS, the system will reopen review instead of finishing.',
expect(input.prompt).toContain(
'The reviewer approved the current task scope (TASK_DONE / legacy DONE). Finalize and report the result.',
);
expect(input.prompt).not.toContain('리뷰 승인 요약');
expect(input.prompt).toContain('리뷰 승인 요약');
// Bot chat messages are not re-sent; only stored turn outputs are.
expect(input.prompt).not.toContain('DONE\n승인합니다.');
await onOutput?.({
status: 'success',

209
src/paired-finalize.test.ts Normal file
View File

@@ -0,0 +1,209 @@
import { execFileSync } from 'child_process';
import fs from 'fs';
import os from 'os';
import path from 'path';
import { beforeEach, describe, expect, it, vi } from 'vitest';
vi.mock('./db.js', () => ({
getMessagesSince: vi.fn(() => []),
getRecentChatMessages: vi.fn(() => []),
getPairedTurnOutputs: vi.fn(() => []),
getPairedWorkspace: vi.fn(),
getPairedTaskById: vi.fn(),
updatePairedTaskIfUnchanged: vi.fn(() => true),
}));
vi.mock('./logger.js', () => ({
logger: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() },
}));
import * as db from './db.js';
import {
completeTaskWithoutFinalizeRun,
REVIEW_REQUEST_APPROVED_NOTE,
resolveFastFinalizeText,
} from './paired-finalize.js';
import type { NewMessage, PairedTask, PairedTurnOutput } from './types.js';
function git(repoDir: string, ...args: string[]): string {
return execFileSync('git', args, {
cwd: repoDir,
encoding: 'utf-8',
stdio: ['ignore', 'pipe', 'pipe'],
}).trim();
}
function createRepo(): string {
const repoDir = fs.mkdtempSync(path.join(os.tmpdir(), 'ejclaw-finalize-'));
git(repoDir, 'init');
git(repoDir, 'config', 'user.name', 'Test');
git(repoDir, 'config', 'user.email', 'test@example.com');
fs.writeFileSync(path.join(repoDir, 'a.txt'), 'a\n');
git(repoDir, 'add', 'a.txt');
git(repoDir, 'commit', '-m', 'init');
return repoDir;
}
function output(
role: PairedTurnOutput['role'],
text: string,
turn: number,
): PairedTurnOutput {
return {
id: turn,
task_id: 'task-1',
turn_number: turn,
role,
output_text: text,
created_at: `2026-03-28T00:0${turn}:00.000Z`,
};
}
function human(content: string, timestamp: string): NewMessage {
return {
id: `m-${timestamp}`,
chat_jid: 'dc:test',
sender: 'user',
sender_name: 'User',
content,
timestamp,
is_bot_message: false,
is_from_me: false,
};
}
describe('resolveFastFinalizeText', () => {
let repoDir: string;
let task: PairedTask;
beforeEach(() => {
vi.resetAllMocks();
repoDir = createRepo();
task = {
id: 'task-1',
chat_jid: 'dc:test',
group_folder: 'room',
owner_service_id: 'claude',
reviewer_service_id: 'codex-review',
title: null,
source_ref: git(repoDir, 'rev-parse', 'HEAD^{tree}'),
plan_notes: null,
review_requested_at: null,
round_trip_count: 1,
status: 'merge_ready',
arbiter_verdict: null,
arbiter_requested_at: null,
completion_reason: null,
created_at: '2026-03-28T00:00:00.000Z',
updated_at: '2026-03-28T00:05:00.000Z',
};
vi.mocked(db.getPairedWorkspace).mockReturnValue({
id: 'task-1:owner',
task_id: 'task-1',
role: 'owner',
workspace_dir: repoDir,
snapshot_source_dir: null,
snapshot_ref: null,
status: 'ready',
snapshot_refreshed_at: null,
created_at: '2026-03-28T00:00:00.000Z',
updated_at: '2026-03-28T00:00:00.000Z',
});
vi.mocked(db.getMessagesSince).mockReturnValue([
human('설정 확인해줘', '2026-03-28T00:00:01.000Z'),
]);
vi.mocked(db.getPairedTurnOutputs).mockReturnValue([
output(
'owner',
'[Carried forward context from the previous task: latest owner final]\nold',
0,
),
output(
'owner',
'TASK_DONE\n\n결론입니다.\n\n사용자 액션 아이템: 없음',
1,
),
output('reviewer', 'TASK_DONE\n\n확인했습니다.', 2),
]);
});
it('returns the reviewed first answer without its status line', () => {
expect(resolveFastFinalizeText(task)).toBe(
'결론입니다.\n\n사용자 액션 아이템: 없음',
);
});
it('accepts a PROCEED approval from the reviewer', () => {
vi.mocked(db.getPairedTurnOutputs).mockReturnValue([
output('owner', 'TASK_DONE\n\n결론', 1),
output('reviewer', 'PROCEED\n좋습니다', 2),
]);
expect(resolveFastFinalizeText(task)).toBe('결론');
});
it('needs a finalize run after more than one review round', () => {
expect(resolveFastFinalizeText({ ...task, round_trip_count: 2 })).toBe(
null,
);
});
it('needs a finalize run when the owner revised the answer', () => {
vi.mocked(db.getPairedTurnOutputs).mockReturnValue([
output('owner', 'TASK_DONE\n\n초안', 1),
output('reviewer', 'DONE_WITH_CONCERNS\n고칠 점', 2),
output('owner', 'TASK_DONE\n\n수정본', 3),
output('reviewer', 'TASK_DONE\n좋음', 4),
]);
expect(resolveFastFinalizeText(task)).toBeNull();
});
it('needs a finalize run when the first answer was only a STEP_DONE', () => {
vi.mocked(db.getPairedTurnOutputs).mockReturnValue([
output('owner', 'STEP_DONE\n\n1단계', 1),
output('reviewer', 'TASK_DONE\n좋음', 2),
]);
expect(resolveFastFinalizeText(task)).toBeNull();
});
it('needs a finalize run when the workspace changed after approval', () => {
fs.writeFileSync(path.join(repoDir, 'a.txt'), 'changed\n');
expect(resolveFastFinalizeText(task)).toBeNull();
git(repoDir, 'commit', '-am', 'after approval');
expect(resolveFastFinalizeText(task)).toBeNull();
});
it('needs a finalize run when the task is not merge_ready', () => {
expect(resolveFastFinalizeText({ ...task, status: 'in_review' })).toBe(
null,
);
});
it('confirms instead of repeating the answer when the user asked for this review', () => {
vi.mocked(db.getMessagesSince).mockReturnValue([
human('설정 확인해줘', '2026-03-28T00:00:01.000Z'),
human('검토해줘', '2026-03-28T00:01:30.000Z'),
]);
expect(resolveFastFinalizeText(task)).toBe(REVIEW_REQUEST_APPROVED_NOTE);
});
});
describe('completeTaskWithoutFinalizeRun', () => {
it('closes the merge_ready task as done', () => {
vi.mocked(db.updatePairedTaskIfUnchanged).mockReturnValue(true);
const task = {
id: 'task-1',
status: 'merge_ready',
updated_at: '2026-03-28T00:05:00.000Z',
} as PairedTask;
expect(completeTaskWithoutFinalizeRun(task)).toBe(true);
expect(db.updatePairedTaskIfUnchanged).toHaveBeenCalledWith(
'task-1',
'2026-03-28T00:05:00.000Z',
expect.objectContaining({
status: 'completed',
completion_reason: 'done',
}),
);
});
});

103
src/paired-finalize.ts Normal file
View File

@@ -0,0 +1,103 @@
import { getPairedTurnOutputs, getPairedWorkspace } from './db.js';
import { getTaskContextMessages } from './message-runtime-task-context.js';
import {
hasCodeChangesSinceRef,
isWorkingTreeClean,
} from './paired-source-ref.js';
import { transitionPairedTaskStatus } from './paired-task-status.js';
import {
parseReviewerVerdict,
parseVisibleVerdict,
stripLeadingStatusLine,
} from './paired-verdict.js';
import { isReviewRequestMessage } from './review-skip.js';
import type { PairedTask, PairedTurnOutput } from './types.js';
/**
* Finalize without an agent run when nothing needs consolidating: the reviewer
* approved the owner's first answer on the first review, there were no
* revision or arbiter turns, and the workspace is exactly what was reviewed.
* The owner's first answer is already a user-ready final message (owner prompt
* "Finalize message format"), so it becomes the final message as-is.
*/
/** Posted instead of repeating the answer when the user asked for this review. */
export const REVIEW_REQUEST_APPROVED_NOTE =
'-# 검토 완료: 수정할 점이 없어 위 답변을 그대로 유지합니다';
const CARRIED_FORWARD_PREFIX =
'[Carried forward context from the previous task:';
function isApproval(verdict: string): boolean {
return verdict === 'task_done' || verdict === 'done';
}
function taskTurnOutputs(taskId: string): PairedTurnOutput[] {
return getPairedTurnOutputs(taskId).filter(
(output) => !output.output_text.startsWith(CARRIED_FORWARD_PREFIX),
);
}
/**
* The text to post as the final message when the finalize turn can be skipped,
* or null when a (lightweight) finalize run is needed.
*/
export function resolveFastFinalizeText(task: PairedTask): string | null {
if (task.status !== 'merge_ready' || task.round_trip_count !== 1) {
return null;
}
const outputs = taskTurnOutputs(task.id);
if (outputs.length !== 2) return null;
const [owner, reviewer] = outputs;
if (owner.role !== 'owner' || reviewer.role !== 'reviewer') return null;
if (
!isApproval(parseVisibleVerdict(owner.output_text)) ||
!isApproval(parseReviewerVerdict(reviewer.output_text))
) {
return null;
}
// source_ref is the owner workspace tree recorded at reviewer approval.
const workspaceDir = getPairedWorkspace(task.id, 'owner')?.workspace_dir;
if (
!workspaceDir ||
hasCodeChangesSinceRef(workspaceDir, task.source_ref) !== false ||
isWorkingTreeClean(workspaceDir) !== true
) {
return null;
}
// "검토해줘" after a review-skipped answer: the answer is already the last
// thing the user read as final, so confirm instead of repeating it.
const ownerAnsweredAt = Date.parse(owner.created_at);
const reviewRequestedAfterAnswer = getTaskContextMessages(
task.chat_jid,
task,
).some(
(message) =>
!message.is_bot_message &&
Date.parse(message.timestamp) > ownerAnsweredAt &&
isReviewRequestMessage(message.content),
);
if (reviewRequestedAfterAnswer) return REVIEW_REQUEST_APPROVED_NOTE;
const answer = stripLeadingStatusLine(owner.output_text).trim();
return answer || null;
}
/** Close a merge_ready task as done without a finalize run. */
export function completeTaskWithoutFinalizeRun(task: PairedTask): boolean {
return transitionPairedTaskStatus({
taskId: task.id,
currentStatus: task.status,
nextStatus: 'completed',
expectedUpdatedAt: task.updated_at,
updatedAt: new Date().toISOString(),
patch: {
completion_reason: 'done',
owner_failure_count: 0,
owner_step_done_streak: 0,
empty_step_done_streak: 0,
},
});
}