From 7f54c47e641f146460bb5b8a6ff32ef71cb80a43 Mon Sep 17 00:00:00 2001 From: Codex Date: Thu, 1 Oct 2026 20:36:53 +0900 Subject: [PATCH] feat: let the owner skip review for change-free explanation answers MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The owner may end a TASK_DONE answer with "리뷰 불필요: ". The host treats it as a request and honors it only when every guard holds: - workspace content equals the task base (hasCodeChangesSinceRef), the working tree is clean, and HEAD did not move during the owner run - the run used no file-mutating tool (Edit/Write/MultiEdit/NotebookEdit), no subagent (Agent/Task) and no state-changing or unknown MCP tool - every Bash command is classified read-only by a conservative quote-aware classifier (src/bash-command-classifier.ts); anything unknown counts as mutating - tool usage was reported and not truncated (agent-runner now reports tool names and Bash commands as toolUsage on its terminal output) - the user did not ask for a review in this task When honored the task completes as review_skipped with no reviewer or finalize turn; the answer is delivered with the marker line removed and a small "-# 검토 생략 …" note. Otherwise the marker is stripped and the normal review runs. A bare "검토해줘"-style message right after a review-skipped answer reopens that task for the reviewer. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + prompts/owner-common-paired-room.md | 6 + .../agent-runner/src/claude-query-runner.ts | 9 + runners/agent-runner/src/index.ts | 1 + runners/agent-runner/src/output-protocol.ts | 3 + runners/agent-runner/src/tool-usage.ts | 69 ++ runners/agent-runner/test/tool-usage.test.ts | 58 ++ src/agent-runner.ts | 2 + src/bash-command-classifier.test.ts | 173 +++++ src/bash-command-classifier.ts | 716 ++++++++++++++++++ src/message-agent-executor-attempt-runner.ts | 29 +- src/message-agent-executor-paired.ts | 62 +- src/message-agent-executor.test.ts | 117 ++- src/message-runtime-group-processing.ts | 54 ++ src/paired-completion-signals.ts | 14 +- src/paired-execution-context-owner.ts | 85 ++- src/paired-execution-context.ts | 31 +- src/paired-review-skip-flow.test.ts | 356 +++++++++ src/paired-source-ref.ts | 30 + src/review-request-gate.ts | 104 +++ src/review-skip.test.ts | 228 ++++++ src/review-skip.ts | 189 +++++ 22 files changed, 2323 insertions(+), 14 deletions(-) create mode 100644 runners/agent-runner/src/tool-usage.ts create mode 100644 runners/agent-runner/test/tool-usage.test.ts create mode 100644 src/bash-command-classifier.test.ts create mode 100644 src/bash-command-classifier.ts create mode 100644 src/paired-review-skip-flow.test.ts create mode 100644 src/review-request-gate.ts create mode 100644 src/review-skip.test.ts create mode 100644 src/review-skip.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 763ae89..05980f8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ ### Added +- owner가 "리뷰 불필요" 표시: 설명·조사만 하고 아무것도 바꾸지 않은 TASK_DONE 답변 끝에 owner가 `리뷰 불필요: <이유>` 한 줄을 붙이면, 시스템이 다시 확인해 리뷰어·마무리 턴 없이 그 답변을 최종 답변으로 보내고 task를 `review_skipped`로 닫음. 표시 줄은 사용자에게 보이지 않고, 답변 끝에 `-# 검토 생략(변경 없는 설명형 답변) · "검토해줘"라고 하면 검토합니다`가 붙음. 다음 중 하나라도 해당하면 표시를 무시하고 평소처럼 리뷰: task 기준 이후 작업 폴더 내용 변경, 커밋되지 않은 변경, owner 실행 중 HEAD 이동, 파일 수정 도구(Edit/Write/MultiEdit/NotebookEdit)·서브에이전트(Agent/Task)·상태를 바꾸는 MCP 도구(schedule_task 등)·알 수 없는 도구 사용, 읽기 전용으로 확실히 분류되지 않는 셸 명령(`src/bash-command-classifier.ts`), 도구 사용 기록이 없거나 잘림(Codex owner 포함), 이번 task에서 사용자가 검토를 요청함. agent-runner는 실행 중 호출한 도구 이름과 Bash 명령을 최종 출력의 `toolUsage`로 보고함. 검토가 생략된 직후 사용자가 "검토해줘" 같은 짧은 검토 요청만 보내면 그 task를 다시 열어 리뷰어가 그 답변을 검토함 - 자연어 작업 중단: 작업이 실행 중이거나 대기 중인 방에 "그만", "멈춰", "중단해", "취소", "stop" 같은 중단 의도만 담긴 짧은 메시지를 보내면 실행 중인 에이전트를 종료하고, 열린 paired task를 `user_stopped`로 닫고(남은 turn 취소·lease 해제), 중단 메시지까지 처리된 것으로 넘긴 뒤 "진행 중이던 작업을 중단했습니다."라고 답함. 다른 지시가 섞인 메시지는 중단으로 보지 않음 ### Changed diff --git a/prompts/owner-common-paired-room.md b/prompts/owner-common-paired-room.md index 027b628..868027c 100644 --- a/prompts/owner-common-paired-room.md +++ b/prompts/owner-common-paired-room.md @@ -48,6 +48,12 @@ Use short Markdown notes when they materially help handoff or continuity across - **BLOCKED** — Cannot proceed. State what is stopping you - **NEEDS_CONTEXT** — Missing information needed to continue +### Review not needed (`리뷰 불필요`) + +- If this turn was pure explanation or investigation and you changed nothing — no file edits, no commits, no state-changing commands (restart, kill, DB write, crontab, API write, install, …), no scheduled tasks — you may end a **TASK_DONE** answer with one final line: `리뷰 불필요: <한 줄 이유>`. The answer then goes to the user without review +- Do not add it when unsure, when anything changed, or when factual accuracy is critical (a diagnosis the user will act on, numbers, security, money). The default is review +- The system re-checks the workspace, your tool calls, and your shell commands, ignores the line if anything could have changed, and never shows the line to the user + ### Finalize semantics - When the reviewer already approved and you are finalizing, **TASK_DONE** closes the paired turn diff --git a/runners/agent-runner/src/claude-query-runner.ts b/runners/agent-runner/src/claude-query-runner.ts index d3d586c..10dcbeb 100644 --- a/runners/agent-runner/src/claude-query-runner.ts +++ b/runners/agent-runner/src/claude-query-runner.ts @@ -27,6 +27,7 @@ import { buildTaskProgressOutput, buildTaskStartedOutput, } from './task-progress-mapping.js'; +import { ToolUsageRecorder, type RunnerToolUsage } from './tool-usage.js'; export interface ClaudeQueryPaths { groupDir: string; @@ -56,11 +57,13 @@ export interface ClaudeQueryResult { closedDuringQuery: boolean; terminalResultObserved: boolean; compaction?: RunnerCompaction; + toolUsage: RunnerToolUsage; } class ClaudeQueryRunner { private readonly stream: MessageStream; private readonly trackedAgentTasks = new TopLevelAgentTaskTracker(); + private readonly toolUsage = new ToolUsageRecorder(); private readonly extraDirs: string[] = []; private readonly effectiveCwd: string; private ipcPolling = true; @@ -119,6 +122,7 @@ class ClaudeQueryRunner { closedDuringQuery: this.closedDuringQuery, terminalResultObserved: this.terminalResultObserved, compaction: this.compaction, + toolUsage: this.toolUsage.snapshot(), }; } @@ -154,6 +158,7 @@ class ClaudeQueryRunner { status: 'success', ...normalizeStructuredOutput(this.pendingProgressText), newSessionId: this.newSessionId, + toolUsage: this.toolUsage.snapshot(), }); this.pendingProgressText = null; this.terminalResultObserved = true; @@ -523,11 +528,13 @@ class ClaudeQueryRunner { ...normalizeStructuredOutput(textResult || null), newSessionId: this.newSessionId, ...buildCompactionOutput(this.compaction), + toolUsage: this.toolUsage.snapshot(), }); } private handleAssistantMessage(message: unknown): boolean { this.trackedAgentTasks.rememberAssistantMessage(message); + this.toolUsage.recordAssistantMessage(message); const stopReason = (message as { stop_reason?: string }).stop_reason; const textResult = extractAssistantText(message); if (textResult || stopReason === 'end_turn') { @@ -545,6 +552,7 @@ class ClaudeQueryRunner { ...normalizeStructuredOutput(textResult), newSessionId: this.newSessionId, ...buildCompactionOutput(this.compaction), + toolUsage: this.toolUsage.snapshot(), }); this.terminalResultObserved = true; this.ipcPolling = false; @@ -582,6 +590,7 @@ class ClaudeQueryRunner { ...normalizeStructuredOutput(this.pendingProgressText), newSessionId: this.newSessionId, ...buildCompactionOutput(this.compaction), + toolUsage: this.toolUsage.snapshot(), }); this.terminalResultObserved = true; this.resultCount++; diff --git a/runners/agent-runner/src/index.ts b/runners/agent-runner/src/index.ts index be8f9b2..6e50ecb 100644 --- a/runners/agent-runner/src/index.ts +++ b/runners/agent-runner/src/index.ts @@ -168,6 +168,7 @@ async function main(): Promise { result: null, newSessionId: sessionId, ...buildCompactionOutput(queryResult.compaction), + toolUsage: queryResult.toolUsage, }); } else if (queryResult.terminalResultObserved) { log('Terminal result already emitted, exiting single-turn runtime'); diff --git a/runners/agent-runner/src/output-protocol.ts b/runners/agent-runner/src/output-protocol.ts index 0ebf446..4de3f6c 100644 --- a/runners/agent-runner/src/output-protocol.ts +++ b/runners/agent-runner/src/output-protocol.ts @@ -12,6 +12,8 @@ import { writeProtocolOutput, } from 'ejclaw-runners-shared'; +import type { RunnerToolUsage } from './tool-usage.js'; + export interface RunnerOutput { status: 'success' | 'error'; phase?: 'progress' | 'final' | 'tool-activity' | 'intermediate'; @@ -26,6 +28,7 @@ export interface RunnerOutput { completed: boolean; trigger?: string | null; }; + toolUsage?: RunnerToolUsage; } export type RunnerCompaction = NonNullable; diff --git a/runners/agent-runner/src/tool-usage.ts b/runners/agent-runner/src/tool-usage.ts new file mode 100644 index 0000000..7dd46b7 --- /dev/null +++ b/runners/agent-runner/src/tool-usage.ts @@ -0,0 +1,69 @@ +/** + * Records which tools an agent run called, so the host can tell whether an + * owner turn could have changed anything (see src/review-skip.ts). The shape + * mirrors the host's AgentToolUsage. + */ +export interface RunnerToolUsage { + tools: string[]; + bashCommands: string[]; + truncated?: boolean; +} + +const MAX_TOOL_ENTRIES = 500; +const MAX_BASH_COMMANDS = 200; +const MAX_BASH_COMMAND_CHARS = 4000; + +type ToolUseBlock = { + type?: unknown; + name?: unknown; + input?: { command?: unknown } | null; +}; + +export class ToolUsageRecorder { + private readonly tools: string[] = []; + private readonly bashCommands: string[] = []; + private truncated = false; + + /** Record every tool_use block of an SDK assistant message. */ + recordAssistantMessage(message: unknown): void { + const blocks = (message as { message?: { content?: unknown } }).message + ?.content; + if (!Array.isArray(blocks)) return; + for (const block of blocks as ToolUseBlock[]) { + if (block?.type !== 'tool_use' || typeof block.name !== 'string') { + continue; + } + this.recordTool(block.name, block.input?.command); + } + } + + private recordTool(name: string, command: unknown): void { + if (this.tools.length >= MAX_TOOL_ENTRIES) { + this.truncated = true; + } else { + this.tools.push(name); + } + if (name !== 'Bash') return; + if (typeof command !== 'string') { + // A Bash call whose command cannot be read must not look read-only. + this.truncated = true; + return; + } + if ( + this.bashCommands.length >= MAX_BASH_COMMANDS || + command.length > MAX_BASH_COMMAND_CHARS + ) { + this.truncated = true; + return; + } + this.bashCommands.push(command); + } + + snapshot(): RunnerToolUsage { + return { + tools: [...this.tools], + bashCommands: [...this.bashCommands], + ...(this.truncated ? { truncated: true } : {}), + }; + } +} diff --git a/runners/agent-runner/test/tool-usage.test.ts b/runners/agent-runner/test/tool-usage.test.ts new file mode 100644 index 0000000..4e54a74 --- /dev/null +++ b/runners/agent-runner/test/tool-usage.test.ts @@ -0,0 +1,58 @@ +import { describe, expect, it } from 'vitest'; + +import { ToolUsageRecorder } from '../src/tool-usage.js'; + +function assistant(blocks: unknown[]) { + return { type: 'assistant', message: { content: blocks } }; +} + +describe('ToolUsageRecorder', () => { + it('records tool names and Bash commands from assistant tool_use blocks', () => { + const recorder = new ToolUsageRecorder(); + recorder.recordAssistantMessage( + assistant([ + { type: 'text', text: 'checking' }, + { type: 'tool_use', name: 'Read', input: { file_path: '/a' } }, + { type: 'tool_use', name: 'Bash', input: { command: 'git status' } }, + ]), + ); + recorder.recordAssistantMessage( + assistant([{ type: 'tool_use', name: 'Edit', input: {} }]), + ); + + expect(recorder.snapshot()).toEqual({ + tools: ['Read', 'Bash', 'Edit'], + bashCommands: ['git status'], + }); + }); + + it('marks the report truncated when a Bash command cannot be read', () => { + const recorder = new ToolUsageRecorder(); + recorder.recordAssistantMessage( + assistant([{ type: 'tool_use', name: 'Bash', input: {} }]), + ); + expect(recorder.snapshot().truncated).toBe(true); + }); + + it('marks the report truncated instead of keeping oversized commands', () => { + const recorder = new ToolUsageRecorder(); + recorder.recordAssistantMessage( + assistant([ + { + type: 'tool_use', + name: 'Bash', + input: { command: 'x'.repeat(5000) }, + }, + ]), + ); + const usage = recorder.snapshot(); + expect(usage.bashCommands).toEqual([]); + expect(usage.truncated).toBe(true); + }); + + it('ignores messages without content blocks', () => { + const recorder = new ToolUsageRecorder(); + recorder.recordAssistantMessage({ type: 'assistant' }); + expect(recorder.snapshot()).toEqual({ tools: [], bashCommands: [] }); + }); +}); diff --git a/src/agent-runner.ts b/src/agent-runner.ts index 7d1fe2e..a0251d6 100644 --- a/src/agent-runner.ts +++ b/src/agent-runner.ts @@ -60,6 +60,8 @@ export interface AgentOutput { completed: boolean; trigger?: string | null; }; + /** Tool calls of the run, reported with the terminal output (Claude runner). */ + toolUsage?: import('./review-skip.js').AgentToolUsage; } function readRoomSkillOverridesForRunner( diff --git a/src/bash-command-classifier.test.ts b/src/bash-command-classifier.test.ts new file mode 100644 index 0000000..7fafcff --- /dev/null +++ b/src/bash-command-classifier.test.ts @@ -0,0 +1,173 @@ +import { describe, expect, it } from 'vitest'; + +import { classifyBashCommand } from './bash-command-classifier.js'; + +const READ_ONLY = [ + 'ls -la', + 'cat src/index.ts', + 'head -50 README.md | tail -20', + 'grep -rn "foo" src --include=*.ts | head', + 'rg -n "a > b" src', + 'wc -l src/*.ts', + 'cd /home/claude/EJClaw && git status', + 'git log --oneline -10', + 'git -C /repo diff --stat HEAD~1', + 'git --no-pager show HEAD:src/a.ts', + 'git branch --show-current', + 'git branch -a', + 'git rev-parse HEAD^{tree}', + 'git stash list', + 'git remote -v', + 'git config --get user.name', + 'git tag', + 'systemctl --user status ejclaw', + 'systemctl --user show -p MainPID --value ejclaw.service', + 'systemctl --user is-active ejclaw', + 'journalctl --user -u ejclaw -n 50 --no-pager', + 'docker ps', + 'docker --context default ps -a', + 'docker logs --tail 20 web', + 'docker compose -f /root/x.yml ps', + 'docker stats --no-stream', + 'curl -s https://example.com/api', + 'curl -sS -X GET https://example.com', + 'curl -I https://example.com', + 'wget -qO- https://example.com', + 'sqlite3 -readonly store/messages.db "select count(*) from paired_tasks"', + 'find . -name "*.ts" -type f', + "sed -n '1,20p' file.txt", + 'sort file.txt | uniq -c', + "awk '{print $1}' file", + 'gh pr view 12', + 'gh run list --limit 5', + 'gh api repos/o/r/pulls', + 'kill -0 1234', + 'crontab -l', + 'ps aux | grep ejclaw', + 'pgrep -f agent-runner', + 'nvidia-smi', + 'free -h', + 'df -h /', + 'du -sh data/*', + 'echo hello', + 'ls missing 2>/dev/null', + 'ls >/dev/null 2>&1', + 'cat a.txt 2>&1 | head', + 'FOO=1 ls', + 'timeout 10 curl -s https://example.com', + 'echo "$PW" | sudo -S systemctl status nvidia', + 'ls | xargs grep -l foo', + 'tsc --noEmit', + 'ip addr show', + 'ping -c 1 192.168.10.5', + 'stat -c %y file', + 'test -f /etc/passwd && echo yes', + 'env', + 'printenv HOME', + '', +]; + +const MUTATING = [ + 'rm -rf data/tmp', + 'mv a b', + 'cp a b', + 'mkdir -p out', + 'touch file', + 'ln -s a b', + 'chmod +x run.sh', + 'chown claude file', + 'echo hi > file.txt', + 'echo hi >> file.txt', + 'cat a | tee b', + 'ls &> out.log', + "sed -i 's/a/b/' file", + "sed -ni 's/a/b/p' file", + "sed -n 's/a/b/w out.txt' file", + 'git commit -m "x"', + 'git push origin main', + 'git reset --hard HEAD~1', + 'git checkout -b feature', + 'git merge other', + 'git rebase main', + 'git stash push -m x', + 'git stash', + 'git branch new-branch', + 'git branch -D old', + 'git tag v1.0', + 'git fetch origin', + 'git -c core.hooksPath=x status', + 'git add .', + 'systemctl --user restart ejclaw', + 'systemctl --user stop ejclaw', + 'systemctl --user start ejclaw', + 'systemctl --user daemon-reload', + 'kill 1234', + 'kill -HUP 1234', + 'kill -HUP "$(systemctl --user show -p MainPID --value ejclaw.service)"', + 'pkill -f runner', + 'crontab -e', + 'crontab file', + 'sqlite3 store/messages.db "select 1"', + 'sqlite3 -readonly store/messages.db "delete from t"', + 'sqlite3 -readonly db "drop table t"', + 'sqlite3 -readonly db "insert into t values (1)"', + 'curl -X POST https://example.com/api', + 'curl -XPOST https://example.com/api', + 'curl --request DELETE https://example.com/x', + 'curl -d "a=1" https://example.com', + 'curl --data-binary @f https://example.com', + 'curl -F file=@a https://example.com', + 'curl -T file https://example.com', + 'curl -o out.html https://example.com', + 'curl -sSLO https://example.com/file', + 'wget https://example.com/file', + 'wget --post-data=a https://example.com', + 'npm install left-pad', + 'bun install', + 'pip install requests', + 'bun run build', + 'docker run --rm alpine', + 'docker rm web', + 'docker stop web', + 'docker compose up -d', + 'docker compose down', + 'docker exec web ls', + 'ssh root@192.168.10.5 "docker ps"', + 'find . -name "*.tmp" -delete', + 'find . -exec rm {} \\;', + 'sort -o out.txt in.txt', + 'echo $(rm -rf x)', + 'echo `whoami`', + 'cat <(ls)', + 'cat < f\nhello\nEOF', + 'bun -e "console.log(1)"', + 'python3 -c "print(1)"', + 'node script.js', + 'bash -c "ls"', + 'nohup ./run.sh &', + 'ls; rm x', + 'ls && rm x', + 'ls || rm x', + 'ls | xargs rm', + 'gh pr merge 12', + 'gh api -X POST repos/o/r/issues', + 'gh api repos/o/r/issues -f title=x', + 'tsc', + 'for f in *; do rm $f; done', + 'awk \'{ system("rm x") }\' f', + "echo 'unterminated", + 'unknown-tool --flag', + './scripts/deploy.sh', + 'source .env', + 'echo hi >| file', +]; + +describe('classifyBashCommand', () => { + it.each(READ_ONLY)('treats %j as read-only', (command) => { + expect(classifyBashCommand(command)).toBe('read_only'); + }); + + it.each(MUTATING)('treats %j as mutating', (command) => { + expect(classifyBashCommand(command)).toBe('mutating'); + }); +}); diff --git a/src/bash-command-classifier.ts b/src/bash-command-classifier.ts new file mode 100644 index 0000000..72857c3 --- /dev/null +++ b/src/bash-command-classifier.ts @@ -0,0 +1,716 @@ +/** + * Conservative read-only classifier for shell commands an agent ran. + * + * Used to decide whether an owner turn changed anything. A command counts as + * read-only only when every part of it is clearly read-only; anything unknown, + * unparsable, or ambiguous counts as mutating. False "mutating" results only + * cost a review; a false "read-only" would skip a needed one. + */ + +export type BashCommandClass = 'read_only' | 'mutating'; + +type Token = + | { kind: 'word'; value: string } + | { kind: 'op'; value: string } + | { kind: 'redirect'; target: string | null }; + +/** Redirect targets that write nothing. */ +const HARMLESS_REDIRECT_TARGETS = new Set(['/dev/null', '&1', '&2', '-']); + +// Commands that never modify state, whatever their arguments. +const ALWAYS_READ_ONLY = new Set([ + ':', + '[', + '[[', + 'basename', + 'cat', + 'cd', + 'cksum', + 'cmp', + 'column', + 'comm', + 'cut', + 'date', + 'df', + 'diff', + 'dig', + 'dirname', + 'du', + 'echo', + 'egrep', + 'expr', + 'false', + 'fgrep', + 'file', + 'fold', + 'free', + 'getent', + 'grep', + 'groups', + 'head', + 'hexdump', + 'host', + 'hostname', + 'id', + 'jq', + 'less', + 'ls', + 'lsblk', + 'lsof', + 'md5sum', + 'more', + 'nl', + 'nproc', + 'nslookup', + 'nvidia-smi', + 'od', + 'paste', + 'pgrep', + 'printf', + 'ps', + 'pwd', + 'readlink', + 'realpath', + 'rev', + 'rg', + 'sha1sum', + 'sha256sum', + 'sha512sum', + 'sleep', + 'ss', + 'stat', + 'strings', + 'tac', + 'tail', + 'test', + 'tr', + 'tree', + 'true', + 'type', + 'uname', + 'uniq', + 'uptime', + 'wc', + 'whereis', + 'which', + 'whoami', + 'xxd', +]); + +// Prefixes that run the following command; classify what they run. +const COMMAND_WRAPPERS = new Set(['sudo', 'timeout', 'nice', 'time', 'env']); + +const GIT_READ_ONLY_SUBCOMMANDS = new Set([ + 'blame', + 'cat-file', + 'describe', + 'diff', + 'grep', + 'log', + 'ls-files', + 'ls-remote', + 'ls-tree', + 'merge-base', + 'reflog', + 'rev-list', + 'rev-parse', + 'shortlog', + 'show', + 'show-ref', + 'status', + 'whatchanged', +]); + +const SYSTEMCTL_READ_ONLY = new Set([ + 'cat', + 'is-active', + 'is-enabled', + 'is-failed', + 'list-dependencies', + 'list-timers', + 'list-unit-files', + 'list-units', + 'show', + 'status', +]); + +const DOCKER_READ_ONLY = new Set([ + 'images', + 'info', + 'inspect', + 'logs', + 'port', + 'ps', + 'top', + 'version', +]); + +const SQL_WRITE_PATTERN = + /\b(?:insert|update|delete|drop|create|alter|replace|attach|detach|vacuum|reindex|begin|commit)\b|\.(?:import|restore|save|backup|output|once)\b|pragma\s+\w+\s*=/i; + +/** Split a command line into words, operators and redirects (quote-aware). */ +function tokenize(command: string): Token[] | null { + const tokens: Token[] = []; + let current = ''; + let hasCurrent = false; + let pendingRedirect = false; + const pushWord = () => { + if (!hasCurrent) return; + if (pendingRedirect) { + tokens.push({ kind: 'redirect', target: current }); + pendingRedirect = false; + } else { + tokens.push({ kind: 'word', value: current }); + } + current = ''; + hasCurrent = false; + }; + const pushOp = (value: string) => { + pushWord(); + if (pendingRedirect) return false; + tokens.push({ kind: 'op', value }); + return true; + }; + + for (let i = 0; i < command.length; i += 1) { + const ch = command[i]; + if (ch === "'") { + const end = command.indexOf("'", i + 1); + if (end < 0) return null; + current += command.slice(i + 1, end); + hasCurrent = true; + i = end; + continue; + } + if (ch === '"') { + let j = i + 1; + let value = ''; + for (; j < command.length && command[j] !== '"'; j += 1) { + if (command[j] === '\\' && j + 1 < command.length) { + value += command[j + 1]; + j += 1; + continue; + } + // Command substitution inside double quotes still runs a command. + if (command[j] === '`' || command.startsWith('$(', j)) return null; + value += command[j]; + } + if (j >= command.length) return null; + current += value; + hasCurrent = true; + i = j; + continue; + } + if (ch === '\\' && i + 1 < command.length) { + if (command[i + 1] !== '\n') { + current += command[i + 1]; + hasCurrent = true; + } + i += 1; + continue; + } + if ( + ch === '`' || + command.startsWith('$(', i) || + command.startsWith('<(', i) + ) + return null; + if (ch === ' ' || ch === '\t') { + pushWord(); + continue; + } + if (ch === '\n' || ch === ';') { + if (!pushOp(';')) return null; + continue; + } + if (ch === '&') { + if (command[i + 1] === '&') { + if (!pushOp('&&')) return null; + i += 1; + continue; + } + if (command[i + 1] === '>') { + // &> / &>> redirect stdout+stderr. + pushWord(); + pendingRedirect = true; + i += command[i + 2] === '>' ? 2 : 1; + continue; + } + // A trailing/background "&" — treat like a separator. + if (!pushOp(';')) return null; + continue; + } + if (ch === '|') { + if (command[i + 1] === '|') { + if (!pushOp('||')) return null; + i += 1; + continue; + } + if (!pushOp('|')) return null; + continue; + } + if (ch === '>') { + // An fd number glued to the operator ("2>") is part of the redirect. + if (/^\d+$/.test(current)) { + current = ''; + hasCurrent = false; + } + pushWord(); + pendingRedirect = true; + if (command[i + 1] === '>' || command[i + 1] === '|') i += 1; + if (command[i + 1] === '&') { + // 2>&1 style: the target is the fd that follows. + let j = i + 2; + let fd = '&'; + while (j < command.length && /[\d-]/.test(command[j])) { + fd += command[j]; + j += 1; + } + tokens.push({ kind: 'redirect', target: fd }); + pendingRedirect = false; + i = j - 1; + } + continue; + } + if (ch === '<') { + // Input redirects and here-docs read only; the following word is input. + pushWord(); + if (command[i + 1] === '<') return null; // here-doc bodies are opaque + continue; + } + if (ch === '(' || ch === ')' || ch === '{' || ch === '}') { + if (!hasCurrent) return null; // subshells / groups + current += ch; + continue; + } + current += ch; + hasCurrent = true; + } + pushWord(); + if (pendingRedirect) tokens.push({ kind: 'redirect', target: null }); + return tokens; +} + +function hasFlag(args: string[], ...flags: string[]): boolean { + return args.some((arg) => + flags.some( + (flag) => + arg === flag || + (flag.startsWith('--') && arg.startsWith(`${flag}=`)) || + // Bundled short flags like "-iE" for "-i". + (flag.length === 2 && + flag.startsWith('-') && + /^-[a-zA-Z]+$/.test(arg) && + arg.includes(flag[1])), + ), + ); +} + +function positional(args: string[]): string[] { + return args.filter((arg) => !arg.startsWith('-')); +} + +/** First non-option argument, skipping the values of options that take one. */ +function firstPositional( + args: string[], + optionsWithValue: ReadonlySet, +): string | undefined { + for (let i = 0; i < args.length; i += 1) { + const arg = args[i]; + if (!arg.startsWith('-')) return arg; + if (optionsWithValue.has(arg)) i += 1; + } + return undefined; +} + +const SYSTEMCTL_OPTIONS_WITH_VALUE = new Set([ + '-p', + '--property', + '-n', + '--lines', + '-o', + '--output', + '-t', + '--type', + '-H', + '--host', + '-M', + '--machine', + '--state', +]); + +const COMPOSE_OPTIONS_WITH_VALUE = new Set([ + '-f', + '--file', + '-p', + '--project-name', + '--project-directory', + '--env-file', + '--profile', +]); + +function isReadOnlyGit(args: string[]): boolean { + const rest = [...args]; + // Global options before the subcommand. + while (rest.length > 0 && rest[0].startsWith('-')) { + const option = rest.shift()!; + if (option === '-c') return false; // config overrides can run hooks/aliases + if (option === '-C') { + rest.shift(); + continue; + } + if (option !== '--no-pager' && option !== '-P') return false; + } + const [sub, ...subArgs] = rest; + if (!sub) return true; + if (GIT_READ_ONLY_SUBCOMMANDS.has(sub)) { + if (sub === 'diff' && hasFlag(subArgs, '--output')) return false; + return true; + } + if (sub === 'branch') { + if ( + hasFlag( + subArgs, + '-d', + '-D', + '-m', + '-M', + '-c', + '-C', + '-f', + '-u', + '--delete', + '--move', + '--copy', + '--force', + '--set-upstream-to', + '--unset-upstream', + '--edit-description', + ) + ) { + return false; + } + // "git branch " creates a branch; only listing forms are read-only. + const listing = hasFlag(subArgs, '--list', '-l', '--contains', '--merged'); + return listing || positional(subArgs).length === 0; + } + if (sub === 'tag') { + return hasFlag(subArgs, '-l', '--list') || subArgs.length === 0; + } + if (sub === 'remote') { + return ( + subArgs.length === 0 || + (subArgs.length === 1 && subArgs[0] === '-v') || + subArgs[0] === 'show' || + subArgs[0] === 'get-url' + ); + } + if (sub === 'stash') { + return subArgs[0] === 'list' || subArgs[0] === 'show'; + } + if (sub === 'worktree') return subArgs[0] === 'list'; + if (sub === 'config') { + return hasFlag(subArgs, '--get', '--get-all', '--list', '-l'); + } + return false; +} + +function isReadOnlySystemctl(args: string[]): boolean { + const sub = firstPositional(args, SYSTEMCTL_OPTIONS_WITH_VALUE); + return sub !== undefined && SYSTEMCTL_READ_ONLY.has(sub); +} + +function isReadOnlyDocker(args: string[]): boolean { + const rest = [...args]; + while (rest.length > 0 && rest[0].startsWith('-')) { + const option = rest.shift()!; + if (option === '--context' || option === '-c' || option === '-H') { + rest.shift(); + } else if (!option.startsWith('--context=')) { + return false; + } + } + const [sub, ...subArgs] = rest; + if (!sub) return false; + if (DOCKER_READ_ONLY.has(sub)) return true; + if (sub === 'stats') return hasFlag(subArgs, '--no-stream'); + if (sub === 'context') return subArgs[0] === 'ls' || subArgs[0] === 'show'; + if (sub === 'compose') { + const composeSub = firstPositional(subArgs, COMPOSE_OPTIONS_WITH_VALUE); + return ( + composeSub === 'ps' || + composeSub === 'logs' || + composeSub === 'config' || + composeSub === 'ls' + ); + } + return false; +} + +function isReadOnlyCurl(args: string[]): boolean { + if ( + hasFlag( + args, + '-d', + '-F', + '-T', + '-o', + '-O', + '-K', + '--data', + '--data-raw', + '--data-binary', + '--data-urlencode', + '--json', + '--form', + '--upload-file', + '--output', + '--remote-name', + '--remote-name-all', + '--config', + '--cookie-jar', + '-c', + ) + ) { + return false; + } + for (let i = 0; i < args.length; i += 1) { + const arg = args[i]; + let method: string | undefined; + if (arg === '-X' || arg === '--request') method = args[i + 1]; + else if (arg.startsWith('--request=')) method = arg.slice(10); + else if (/^-X[A-Za-z]+$/.test(arg)) method = arg.slice(2); + if (method !== undefined && !/^(?:GET|HEAD|OPTIONS)$/i.test(method)) { + return false; + } + } + return true; +} + +function isReadOnlyWget(args: string[]): boolean { + if (hasFlag(args, '--post-data', '--post-file', '--method', '--body-data')) { + return false; + } + if (hasFlag(args, '--spider')) return true; + // Only "print to stdout" forms: -O - / -qO- / --output-document=-. + return args.some( + (arg, i) => + ((arg === '-O' || arg === '--output-document') && args[i + 1] === '-') || + /^-[a-zA-Z]*O-$/.test(arg) || + arg === '--output-document=-', + ); +} + +function isReadOnlySqlite(args: string[]): boolean { + const readonly = + hasFlag(args, '-readonly', '--readonly') || + args.some((arg) => /^file:.*[?&]mode=ro\b/.test(arg)); + if (!readonly) return false; + return !args.some((arg) => SQL_WRITE_PATTERN.test(arg)); +} + +function isReadOnlyFind(args: string[]): boolean { + return !args.some((arg) => + /^-(?:delete|exec|execdir|ok|okdir|fprint|fprint0|fprintf|fls)$/.test(arg), + ); +} + +function isReadOnlySed(args: string[]): boolean { + if (hasFlag(args, '-i', '--in-place')) return false; + // The "w file" / "W file" commands write files. + return !args.some((arg) => /(?:^|[;/}\s])[wW]\s+\S/.test(arg)); +} + +function isReadOnlyGh(args: string[]): boolean { + const [group, action, ...rest] = args; + if (group === 'api') { + const apiArgs = [action, ...rest].filter((a): a is string => !!a); + if ( + hasFlag(apiArgs, '-f', '-F', '--field', '--raw-field', '--input') || + apiArgs.some((arg, i) => { + const method = + arg === '-X' || arg === '--method' + ? apiArgs[i + 1] + : arg.startsWith('--method=') + ? arg.slice(9) + : undefined; + return method !== undefined && !/^GET$/i.test(method); + }) + ) { + return false; + } + return true; + } + const readActions = new Set([ + 'list', + 'view', + 'status', + 'diff', + 'checks', + 'watch', + ]); + return ( + ['pr', 'run', 'issue', 'release', 'repo', 'workflow'].includes(group) && + readActions.has(action) + ); +} + +function isReadOnlyKill(args: string[]): boolean { + // "kill -0 " only checks that the process exists; "kill -l" lists signals. + return args[0] === '-0' || args[0] === '-l'; +} + +/** Strip wrapper commands (sudo, timeout, env, ...) and variable assignments. */ +function unwrapCommand(words: string[]): string[] { + let rest = words; + for (;;) { + while (rest.length > 0 && /^[A-Za-z_][A-Za-z0-9_]*=/.test(rest[0])) { + rest = rest.slice(1); + } + const [head, ...tail] = rest; + if (!head || !COMMAND_WRAPPERS.has(head)) return rest; + let next = tail; + if (head === 'sudo') { + while (next.length > 0 && next[0].startsWith('-')) { + const option = next[0]; + next = next.slice(1); + if (option === '-u' || option === '-g') next = next.slice(1); + } + } else if (head === 'timeout') { + while (next.length > 0 && next[0].startsWith('-')) { + const option = next[0]; + next = next.slice(1); + if (option === '-s' || option === '-k') next = next.slice(1); + } + next = next.slice(1); // duration + } else if (head === 'nice') { + if (next[0] === '-n') next = next.slice(2); + else if (next[0]?.startsWith('-')) next = next.slice(1); + } else if (head === 'env') { + while (next.length > 0 && next[0].startsWith('-')) next = next.slice(1); + } else if (head === 'time') { + while (next.length > 0 && next[0].startsWith('-')) next = next.slice(1); + } + if (next.length === 0) return head === 'env' ? ['env'] : []; + rest = next; + } +} + +function isReadOnlySimpleCommand(words: string[]): boolean { + const unwrapped = unwrapCommand(words); + if (unwrapped.length === 0) return true; // bare assignment + const [rawCommand, ...args] = unwrapped; + const command = rawCommand.split('/').at(-1) ?? rawCommand; + + if (ALWAYS_READ_ONLY.has(command)) return true; + switch (command) { + case 'env': + case 'printenv': + return args.length === 0 || command === 'printenv'; + case 'export': + case 'unset': + case 'local': + case 'set': + return true; // shell-local state only + case 'git': + return isReadOnlyGit(args); + case 'systemctl': + return isReadOnlySystemctl(args); + case 'journalctl': + return !hasFlag( + args, + '--rotate', + '--flush', + '--sync', + '--vacuum-size', + '--vacuum-time', + '--vacuum-files', + ); + case 'docker': + return isReadOnlyDocker(args); + case 'curl': + return isReadOnlyCurl(args); + case 'wget': + return isReadOnlyWget(args); + case 'sqlite3': + return isReadOnlySqlite(args); + case 'find': + return isReadOnlyFind(args); + case 'sed': + return isReadOnlySed(args); + case 'sort': + return !hasFlag(args, '-o', '--output'); + case 'awk': + case 'gawk': + return !args.some((arg) => + /\bsystem\s*\(|\bprint[^;]*>|getline/.test(arg), + ); + case 'gh': + return isReadOnlyGh(args); + case 'kill': + return isReadOnlyKill(args); + case 'crontab': + return args.length === 1 && args[0] === '-l'; + case 'tsc': + return hasFlag(args, '--noEmit'); + case 'ip': + return ( + args.length > 0 && + ['addr', 'a', 'route', 'r', 'link', 'l', 'neigh'].includes(args[0]) && + (args.length === 1 || args[1] === 'show' || args[1] === 'list') + ); + case 'ping': + return hasFlag(args, '-c'); + case 'top': + return hasFlag(args, '-b'); + default: + return false; + } +} + +/** + * Classify one shell command line. Read-only only when every pipeline segment + * is a known read-only command and nothing is redirected into a file. + */ +export function classifyBashCommand(command: string): BashCommandClass { + const trimmed = command.trim(); + if (!trimmed) return 'read_only'; + const tokens = tokenize(trimmed); + if (!tokens) return 'mutating'; + + let words: string[] = []; + const segments: string[][] = []; + for (const token of tokens) { + if (token.kind === 'redirect') { + if (!token.target || !HARMLESS_REDIRECT_TARGETS.has(token.target)) { + return 'mutating'; + } + continue; + } + if (token.kind === 'op') { + if (words.length > 0) segments.push(words); + words = []; + continue; + } + words.push(token.value); + } + if (words.length > 0) segments.push(words); + + for (const segment of segments) { + if (segment[0] === 'xargs') { + // xargs runs the command that follows its own options. + let rest = segment.slice(1); + while (rest.length > 0 && rest[0].startsWith('-')) { + const option = rest[0]; + rest = rest.slice(1); + if (/^-[IdEsLnP]$/.test(option)) rest = rest.slice(1); + } + if (rest.length === 0 || !isReadOnlySimpleCommand(rest)) { + return 'mutating'; + } + continue; + } + if (!isReadOnlySimpleCommand(segment)) return 'mutating'; + } + return 'read_only'; +} diff --git a/src/message-agent-executor-attempt-runner.ts b/src/message-agent-executor-attempt-runner.ts index eec9a7e..3abd416 100644 --- a/src/message-agent-executor-attempt-runner.ts +++ b/src/message-agent-executor-attempt-runner.ts @@ -108,7 +108,9 @@ interface RunMessageAgentAttemptArgs { recordFinalOutputBeforeDelivery( outputText: string, attachments?: OutboundAttachment[], + toolUsage?: AgentOutput['toolUsage'], ): boolean; + resolveFinalDeliveryText?(outputText: string): string; }; log: Logger; } @@ -345,7 +347,31 @@ class MessageAgentAttemptRunner { if (!this.finalOutputWasAccepted(event)) { return; } - await this.args.onOutput?.(event.output); + await this.args.onOutput?.(this.withFinalDeliveryText(event)); + } + + /** Swap in the lifecycle's delivery text (review-skip marker/note). */ + private withFinalDeliveryText(event: EvaluatedAgentOutput): AgentOutput { + const { output, outputText } = event; + if ( + (output.phase ?? 'final') !== 'final' || + output.status !== 'success' || + !outputText + ) { + return output; + } + const text = + this.args.pairedExecutionLifecycle.resolveFinalDeliveryText?.( + outputText, + ) ?? outputText; + if (text === outputText) return output; + return { + ...output, + result: text, + ...(output.output?.visibility === 'public' + ? { output: { ...output.output, text } } + : {}), + }; } private finalOutputWasAccepted(event: EvaluatedAgentOutput): boolean { @@ -362,6 +388,7 @@ class MessageAgentAttemptRunner { return this.args.pairedExecutionLifecycle.recordFinalOutputBeforeDelivery( event.outputText, getAgentOutputAttachments(event.output), + event.output.toolUsage, ); } catch (err) { this.args.log.warn( diff --git a/src/message-agent-executor-paired.ts b/src/message-agent-executor-paired.ts index 47e62f5..f067a32 100644 --- a/src/message-agent-executor-paired.ts +++ b/src/message-agent-executor-paired.ts @@ -25,6 +25,13 @@ import type { PairedTurnIdentity } from './paired-turn-identity.js'; import { resolvePairedTurnRunOwnership } from './paired-turn-run-ownership.js'; import { isHumanMessageCloseReason } from './message-close-reasons.js'; import { persistPairedTurnOutputAttachments } from './paired-turn-output-attachments.js'; +import { + extractReviewSkipMarker, + REVIEW_SKIPPED_COMPLETION_REASON, + REVIEW_SKIPPED_NOTE, + type AgentToolUsage, + type OwnerReviewSkipRequest, +} from './review-skip.js'; import type { OutboundAttachment, PairedRoomRole } from './types.js'; type ExecutorLog = Pick; @@ -58,6 +65,7 @@ function completeStoredExecution( status: 'succeeded' | 'failed', runId: string, summary: string | null, + ownerReviewSkip: OwnerReviewSkipRequest | null, ): void { completePairedExecutionContext({ taskId, @@ -65,6 +73,7 @@ function completeStoredExecution( status, runId, summary, + ...(ownerReviewSkip ? { ownerReviewSkip } : {}), }); } @@ -164,7 +173,10 @@ export interface PairedExecutionLifecycle { recordFinalOutputBeforeDelivery( outputText: string, attachments?: OutboundAttachment[], + toolUsage?: AgentToolUsage, ): boolean; + /** The text to deliver for an accepted final output. */ + resolveFinalDeliveryText(outputText: string): string; completeImmediately(args: { status: 'succeeded' | 'failed' }): void; markStatus(status: 'succeeded' | 'failed'): void; markSawOutput(sawOutput: boolean): void; @@ -204,6 +216,7 @@ class PairedExecutionLifecycleController implements PairedExecutionLifecycle { private pairedSawOutput = false; private pairedTurnOutputPersisted = false; private pairedTurnStateFinalized = false; + private ownerReviewSkip: OwnerReviewSkipRequest | null = null; private leaseHeartbeatTimer: ReturnType | null = null; constructor(private readonly args: CreatePairedExecutionLifecycleArgs) { @@ -241,17 +254,57 @@ class PairedExecutionLifecycleController implements PairedExecutionLifecycle { recordFinalOutputBeforeDelivery( outputText: string, attachments: OutboundAttachment[] = [], + toolUsage?: AgentToolUsage, ): boolean { if (this.wasInterruptedByHumanMessage()) return false; if (!this.currentRunOwnsActiveAttempt('streamed-final-output')) { return false; } - this.lockVisibleVerdict(outputText, attachments); + const finalText = this.captureOwnerReviewSkip(outputText, toolUsage); + this.lockVisibleVerdict(finalText, attachments); this.completeSuccessfulOwnerTurnBeforeDeliveryIfNeeded(); this.persistPairedTurnOutputIfNeeded(); return true; } + resolveFinalDeliveryText(outputText: string): string { + const { completedRole, pairedExecutionContext } = this.args; + if (completedRole !== 'owner' || !pairedExecutionContext) { + return outputText; + } + const { text } = extractReviewSkipMarker(outputText); + if (!this.ownerReviewSkip) return text; + const task = getPairedTaskById(pairedExecutionContext.task.id); + return task?.status === 'completed' && + task.completion_reason === REVIEW_SKIPPED_COMPLETION_REASON + ? `${text}\n\n${REVIEW_SKIPPED_NOTE}` + : text; + } + + /** + * Strip a trailing "리뷰 불필요: …" line from an owner answer and remember the + * request (with the run's tool usage) for the completion guards. + */ + private captureOwnerReviewSkip( + outputText: string, + toolUsage: AgentToolUsage | undefined, + ): string { + const { completedRole, pairedExecutionContext } = this.args; + if (completedRole !== 'owner' || !pairedExecutionContext) { + return outputText; + } + const { text, reason } = extractReviewSkipMarker(outputText); + if (reason && !this.ownerReviewSkip) { + this.ownerReviewSkip = { + reason, + toolUsage: toolUsage ?? null, + workspaceHeadAtStart: + pairedExecutionContext.workspaceHeadAtStart ?? null, + }; + } + return text; + } + completeImmediately({ status }: { status: PairedExecutionStatus }): void { const { completedRole, pairedExecutionContext, runId } = this.args; if (!pairedExecutionContext || this.pairedExecutionCompleted) { @@ -270,6 +323,9 @@ class PairedExecutionLifecycleController implements PairedExecutionLifecycle { status, runId, summary: this.pairedExecutionSummary, + ...(this.ownerReviewSkip + ? { ownerReviewSkip: this.ownerReviewSkip } + : {}), }); this.pairedExecutionCompleted = true; } @@ -467,6 +523,9 @@ class PairedExecutionLifecycleController implements PairedExecutionLifecycle { status: 'succeeded', runId, summary: this.pairedExecutionSummary, + ...(this.ownerReviewSkip + ? { ownerReviewSkip: this.ownerReviewSkip } + : {}), }); this.pairedExecutionCompleted = true; } @@ -595,6 +654,7 @@ class PairedExecutionLifecycleController implements PairedExecutionLifecycle { state.effectiveStatus, runId, this.pairedExecutionSummary, + this.ownerReviewSkip, ); this.pairedExecutionCompleted = true; } diff --git a/src/message-agent-executor.test.ts b/src/message-agent-executor.test.ts index 981a3e7..1732b67 100644 --- a/src/message-agent-executor.test.ts +++ b/src/message-agent-executor.test.ts @@ -1832,11 +1832,7 @@ 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(db.getRouterState).mockReturnValue('paired-task-review'); vi.mocked(serviceRouting.getEffectiveChannelLease).mockReturnValue({ chat_jid: 'group@test', @@ -3548,3 +3544,114 @@ describe('runAgentForGroup task-scoped paired sessions', () => { expect(db.setRouterState).not.toHaveBeenCalled(); }); }); + +describe('runAgentForGroup owner review-skip marker', () => { + const task = { + id: 'task-skip', + 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', + }; + const toolUsage = { tools: ['Read'], bashCommands: [] }; + const answer = 'TASK_DONE\n\n설명입니다.\n\n리뷰 불필요: 조회만 함'; + + beforeEach(() => { + vi.resetAllMocks(); + resetPairedFollowUpScheduleState(); + vi.mocked(buildRoomMemoryBriefing).mockResolvedValue(undefined as never); + vi.mocked( + pairedExecutionContext.preparePairedExecutionContext, + ).mockReturnValue({ + task, + workspace: null, + envOverrides: { EJCLAW_PAIRED_TASK_ID: task.id }, + workspaceHeadAtStart: 'head-1', + }); + vi.mocked(agentRunner.runAgentProcess).mockImplementation( + async (_group, _input, _onProcess, onOutput) => { + await onOutput?.({ + status: 'success', + result: answer, + output: { visibility: 'public', text: answer }, + phase: 'final', + toolUsage, + }); + return { status: 'success', result: null }; + }, + ); + }); + + async function run(): Promise { + const delivered: string[] = []; + await runAgentForGroup(makeDeps(), { + group: { ...makeGroup(), folder: 'test-group' }, + prompt: 'why?', + chatJid: 'group@test', + runId: 'run-skip', + hasHumanMessage: true, + onOutput: async (output) => { + if (output.output?.visibility === 'public') { + delivered.push(output.output.text); + } + }, + }); + return delivered; + } + + it('passes the marker and tool usage to completion and appends the skip note', async () => { + vi.mocked(db.getPairedTaskById).mockReturnValue({ + ...task, + status: 'completed', + completion_reason: 'review_skipped', + }); + + const delivered = await run(); + + expect( + pairedExecutionContext.completePairedExecutionContext, + ).toHaveBeenCalledWith( + expect.objectContaining({ + role: 'owner', + summary: 'TASK_DONE\n\n설명입니다.', + ownerReviewSkip: { + reason: '조회만 함', + toolUsage, + workspaceHeadAtStart: 'head-1', + }, + }), + ); + expect(db.insertPairedTurnOutput).toHaveBeenCalledWith( + task.id, + 1, + 'owner', + 'TASK_DONE\n\n설명입니다.', + ); + expect(delivered).toEqual([ + 'TASK_DONE\n\n설명입니다.\n\n-# 검토 생략(변경 없는 설명형 답변) · "검토해줘"라고 하면 검토합니다', + ]); + }); + + it('strips the marker without the note when the guards sent it to review', async () => { + vi.mocked(db.getPairedTaskById).mockReturnValue({ + ...task, + status: 'review_ready', + }); + + const delivered = await run(); + expect(delivered[0]).toBe('TASK_DONE\n\n설명입니다.'); + expect(delivered.join('\n')).not.toContain('리뷰 불필요'); + expect(delivered.join('\n')).not.toContain('검토 생략'); + }); +}); diff --git a/src/message-runtime-group-processing.ts b/src/message-runtime-group-processing.ts index fd1bc15..27875cf 100644 --- a/src/message-runtime-group-processing.ts +++ b/src/message-runtime-group-processing.ts @@ -37,6 +37,7 @@ import { } from './token-refresh.js'; import { findChannel, formatMessages } from './router.js'; import { stopRoomWorkIfRequested, type RoomStopResult } from './room-stop.js'; +import { reopenReviewSkippedTaskForReview } from './review-request-gate.js'; import { createScopedLogger, logger } from './logger.js'; import type { GroupQueue, GroupRunContext } from './group-queue.js'; import type { @@ -293,6 +294,15 @@ async function processMissedMessages( return true; } + const reviewRequestOutcome = await runReviewRequestGate( + args, + runtime, + missedMessages, + ); + if (reviewRequestOutcome !== null) { + return reviewRequestOutcome; + } + const reloginOutcome = await runReloginRequiredGate( args, runtime, @@ -447,6 +457,50 @@ async function runReloginRequiredGate( return true; } +/** + * "검토해줘" right after an answer whose review was skipped: run the reviewer + * on that answer (the task is reopened) instead of starting a new owner turn. + * Returns null when the message is not such a request. + */ +async function runReviewRequestGate( + args: ProcessGroupMessagesDeps, + runtime: RuntimeContext, + missedMessages: NewMessage[], +): Promise { + const task = reopenReviewSkippedTaskForReview({ + chatJid: runtime.chatJid, + messages: missedMessages, + }); + if (!task) return null; + + const lastMessage = missedMessages[missedMessages.length - 1]; + if (lastMessage?.seq != null) { + advanceLastAgentCursor( + args.getLastAgentTimestamps(), + args.saveState, + runtime.chatJid, + lastMessage.seq, + ); + } + const outcome = await runPendingPairedTurnIfNeeded({ + chatJid: runtime.chatJid, + group: runtime.group, + runId: runtime.runId, + log: runtime.log, + timezone: args.timezone, + task, + rawMissedMessages: [], + saveState: args.saveState, + lastAgentTimestamps: args.getLastAgentTimestamps(), + executeTurn: args.executeTurn, + getFixedRoleChannelName, + roleToChannel: runtime.roleToChannel, + labelPairedSenders: args.labelPairedSenders, + mode: 'idle', + }); + return outcome ?? true; +} + /** * A stop request that reaches a queued run without having been handled by the * message loop (e.g. it was pending across a restart) still stops the room's diff --git a/src/paired-completion-signals.ts b/src/paired-completion-signals.ts index 146e81a..47a981b 100644 --- a/src/paired-completion-signals.ts +++ b/src/paired-completion-signals.ts @@ -5,7 +5,10 @@ export type CompletionSignal = | { kind: 'request_owner_finalize' } | { kind: 'request_owner_changes' } | { kind: 'request_arbiter' } - | { kind: 'complete'; completionReason: 'done' | 'escalated' } + | { + kind: 'complete'; + completionReason: 'done' | 'escalated' | 'review_skipped'; + } | { kind: 'preserve_review_ready' }; export function resolveOwnerCompletionSignal(args: { @@ -14,6 +17,8 @@ export function resolveOwnerCompletionSignal(args: { hasChangesSinceApproval?: boolean | null; roundTripCount?: number; deadlockThreshold?: number; + /** The owner marked the answer "리뷰 불필요" and every guard passed. */ + reviewSkipApproved?: boolean; }): CompletionSignal { const { phase, @@ -21,6 +26,7 @@ export function resolveOwnerCompletionSignal(args: { hasChangesSinceApproval = false, roundTripCount = 0, deadlockThreshold = Number.POSITIVE_INFINITY, + reviewSkipApproved = false, } = args; if (visibleVerdict === 'blocked' || visibleVerdict === 'needs_context') { @@ -28,6 +34,12 @@ export function resolveOwnerCompletionSignal(args: { } if (phase === 'normal') { + if ( + reviewSkipApproved && + (visibleVerdict === 'task_done' || visibleVerdict === 'done') + ) { + return { kind: 'complete', completionReason: 'review_skipped' }; + } return { kind: 'request_reviewer', resetStatusToActive: false, diff --git a/src/paired-execution-context-owner.ts b/src/paired-execution-context-owner.ts index 363ac4a..de4c7d3 100644 --- a/src/paired-execution-context-owner.ts +++ b/src/paired-execution-context-owner.ts @@ -16,8 +16,19 @@ import { transitionPairedTaskStatus, } from './paired-task-status.js'; import { resolveOwnerCompletionSignal } from './paired-completion-signals.js'; -import { hasCodeChangesSinceRef } from './paired-source-ref.js'; +import { + hasCodeChangesSinceRef, + isWorkingTreeClean, + resolveHeadCommit, +} from './paired-source-ref.js'; import { parseVisibleVerdict } from './paired-verdict.js'; +import { getTaskContextMessages } from './message-runtime-task-context.js'; +import { + containsReviewRequest, + evaluateReviewSkipGuards, + REVIEW_SKIPPED_COMPLETION_REASON, + type OwnerReviewSkipRequest, +} from './review-skip.js'; import type { PairedTask } from './types.js'; type OwnerFinalizeOutcome = 'stop' | 're_review'; @@ -421,10 +432,51 @@ function maybeAutoTriggerReviewerAfterOwnerCompletion(args: { } } +/** + * Decide whether an owner's "리뷰 불필요" marker may be honored: the owner turn + * must have changed nothing (workspace, tools, shell commands) and the user + * must not have asked for a review in this task. + */ +function isOwnerReviewSkipApproved(args: { + task: PairedTask; + workspaceDir: string | null; + hasNewChanges: boolean | null; + request: OwnerReviewSkipRequest; +}): boolean { + const { task, workspaceDir, request } = args; + const explicitReviewRequested = getTaskContextMessages( + task.chat_jid, + task, + ).some( + (message) => + !message.is_bot_message && containsReviewRequest(message.content), + ); + const failures = evaluateReviewSkipGuards({ + request, + hasCodeChangesSinceBase: args.hasNewChanges, + workingTreeClean: workspaceDir ? isWorkingTreeClean(workspaceDir) : null, + workspaceHeadNow: workspaceDir ? resolveHeadCommit(workspaceDir) : null, + explicitReviewRequested, + }); + logger.info( + { + taskId: task.id, + reason: request.reason, + approved: failures.length === 0, + failedGuards: failures.slice(0, 10), + }, + failures.length === 0 + ? 'Owner review-skip marker honored' + : 'Owner review-skip marker ignored because a guard failed', + ); + return failures.length === 0; +} + export function handleOwnerCompletion(args: { task: PairedTask; taskId: string; summary?: string | null; + reviewSkip?: OwnerReviewSkipRequest | null; }): void { const { task, taskId, summary } = args; const now = new Date().toISOString(); @@ -459,11 +511,42 @@ export function handleOwnerCompletion(args: { ownerVerdict === 'step_done' && hasNewChanges === false ? (task.empty_step_done_streak ?? 0) + 1 : 0; + const reviewSkipApproved = + !!args.reviewSkip && + (ownerVerdict === 'task_done' || ownerVerdict === 'done') && + isOwnerReviewSkipApproved({ + task, + workspaceDir: workspace?.workspace_dir ?? null, + hasNewChanges, + request: args.reviewSkip, + }); const signal = resolveOwnerCompletionSignal({ phase: 'normal', visibleVerdict: ownerVerdict, + reviewSkipApproved, }); + if (signal.kind === 'complete') { + transitionPairedTaskStatus({ + taskId, + currentStatus: task.status, + nextStatus: 'completed', + expectedUpdatedAt: task.updated_at, + updatedAt: now, + patch: { + completion_reason: REVIEW_SKIPPED_COMPLETION_REASON, + owner_failure_count: 0, + owner_step_done_streak: 0, + empty_step_done_streak: 0, + }, + }); + logger.info( + { taskId, summary: summary?.slice(0, 100) }, + 'Owner answer completed without review (review-skip marker honored)', + ); + return; + } + if (signal.kind === 'request_arbiter') { requestArbiterOrEscalate({ taskId, diff --git a/src/paired-execution-context.ts b/src/paired-execution-context.ts index 1bda987..d111dfc 100644 --- a/src/paired-execution-context.ts +++ b/src/paired-execution-context.ts @@ -47,7 +47,11 @@ import { applyPairedTaskPatch, transitionPairedTaskStatus, } from './paired-task-status.js'; -import { resolveCanonicalSourceRef } from './paired-source-ref.js'; +import { + resolveCanonicalSourceRef, + resolveHeadCommit, +} from './paired-source-ref.js'; +import type { OwnerReviewSkipRequest } from './review-skip.js'; import { ensurePairedWorkspaceProvisioned, isOwnerWorkspaceRepairNeededError, @@ -447,6 +451,8 @@ export interface PreparedPairedExecutionContext { gateTurnKind?: string | null; requiresVisibleVerdict?: boolean; blockMessage?: string; + /** Owner workspace HEAD when the owner run started (review-skip guard). */ + workspaceHeadAtStart?: string | null; } function isOwnerContinuationTurn( @@ -565,9 +571,8 @@ export function preparePairedExecutionContext(args: { }); } } - // 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. + // Stable per-channel worktree (not per-task); the agent session is scoped + // to the paired task (paired-session-binding.ts). try { workspace = provisionOwnerWorkspaceForPairedTask(latestTask.id); } catch (error) { @@ -684,15 +689,26 @@ export function preparePairedExecutionContext(args: { requiresVisibleVerdict: roomRoleContext.role === 'reviewer' || roomRoleContext.role === 'arbiter', blockMessage, + ...resolveOwnerWorkspaceHead(roomRoleContext.role, workspace), }; } +function resolveOwnerWorkspaceHead( + role: PairedRoomRole, + workspace: PairedWorkspace | null, +): Pick { + if (role !== 'owner' || !workspace?.workspace_dir) return {}; + return { workspaceHeadAtStart: resolveHeadCommit(workspace.workspace_dir) }; +} + type CompletePairedExecutionContextArgs = { taskId: string; role: PairedRoomRole; status: 'succeeded' | 'failed'; runId?: string; summary?: string | null; + /** Owner asked to skip review ("리뷰 불필요"); honored only if guards pass. */ + ownerReviewSkip?: OwnerReviewSkipRequest | null; }; export function completePairedExecutionContext( @@ -792,7 +808,12 @@ function completePairedExecutionContextBody( } throw error; } - handleOwnerCompletion({ task, taskId, summary: args.summary }); + handleOwnerCompletion({ + task, + taskId, + summary: args.summary, + reviewSkip: args.ownerReviewSkip ?? null, + }); return; } diff --git a/src/paired-review-skip-flow.test.ts b/src/paired-review-skip-flow.test.ts new file mode 100644 index 0000000..e855111 --- /dev/null +++ b/src/paired-review-skip-flow.test.ts @@ -0,0 +1,356 @@ +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', () => { + const updatePairedTask = vi.fn(); + return { + getLatestOpenPairedTaskForChat: vi.fn(), + getLatestPairedTaskForChat: vi.fn(), + getMessagesSince: vi.fn(() => []), + getRecentChatMessages: vi.fn(() => []), + getPairedTaskById: vi.fn(), + getPairedWorkspace: vi.fn(), + hasActiveCiWatcherForChat: vi.fn(() => false), + releasePairedTaskExecutionLease: vi.fn(), + updatePairedTask, + updatePairedTaskIfUnchanged: vi.fn((id, _expectedUpdatedAt, updates) => { + updatePairedTask(id, updates); + return true; + }), + }; +}); + +vi.mock('./paired-workspace-manager.js', () => ({ + ensurePairedWorkspaceProvisioned: vi.fn(), + isOwnerWorkspaceRepairNeededError: vi.fn(() => false), + markPairedTaskReviewReady: vi.fn(), + prepareReviewerWorkspaceForExecution: vi.fn(), + provisionOwnerWorkspaceForPairedTask: vi.fn(), +})); + +vi.mock('./service-routing.js', () => ({ + hasReviewerLease: 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 { completePairedExecutionContext } from './paired-execution-context.js'; +import * as pairedWorkspaceManager from './paired-workspace-manager.js'; +import { reopenReviewSkippedTaskForReview } from './review-request-gate.js'; +import type { OwnerReviewSkipRequest } from './review-skip.js'; +import type { NewMessage, PairedTask, PairedWorkspace } 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-skip-')); + git(repoDir, 'init'); + git(repoDir, 'config', 'user.name', 'Test'); + git(repoDir, 'config', 'user.email', 'test@example.com'); + fs.writeFileSync(path.join(repoDir, 'README.md'), 'hello\n'); + git(repoDir, 'add', 'README.md'); + git(repoDir, 'commit', '-m', 'init'); + return repoDir; +} + +function buildTask(overrides: Partial = {}): PairedTask { + return { + id: 'task-1', + chat_jid: 'dc:test', + group_folder: 'room', + owner_service_id: 'claude', + reviewer_service_id: 'codex-review', + title: null, + source_ref: 'HEAD', + plan_notes: null, + review_requested_at: null, + round_trip_count: 0, + owner_failure_count: 0, + reviewer_failure_count: 0, + owner_step_done_streak: 0, + finalize_step_done_count: 0, + task_done_then_user_reopen_count: 0, + empty_step_done_streak: 0, + arbiter_intervention_count: 0, + status: 'active', + 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', + ...overrides, + }; +} + +function ownerWorkspace(dir: string): PairedWorkspace { + return { + id: 'task-1:owner', + task_id: 'task-1', + role: 'owner', + workspace_dir: dir, + 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', + }; +} + +function humanMessage(content: string, seq = 10): NewMessage { + return { + id: `m-${seq}`, + chat_jid: 'dc:test', + sender: 'user', + sender_name: 'User', + content, + timestamp: '2026-03-28T00:00:01.000Z', + is_bot_message: false, + is_from_me: false, + seq, + }; +} + +describe('owner review-skip completion', () => { + let repoDir: string; + let head: string; + + beforeEach(() => { + vi.resetAllMocks(); + vi.mocked(db.updatePairedTaskIfUnchanged).mockImplementation( + (id, _expected, updates) => { + vi.mocked(db.updatePairedTask)(id, updates); + return true; + }, + ); + vi.mocked(db.getMessagesSince).mockReturnValue([ + humanMessage('이 채널 왜 답을 안 해?'), + ]); + repoDir = createRepo(); + head = git(repoDir, 'rev-parse', 'HEAD'); + vi.mocked(db.getPairedTaskById).mockReturnValue( + buildTask({ source_ref: git(repoDir, 'rev-parse', 'HEAD^{tree}') }), + ); + vi.mocked(db.getPairedWorkspace).mockImplementation((_id, role) => + role === 'owner' ? ownerWorkspace(repoDir) : undefined, + ); + vi.mocked( + pairedWorkspaceManager.provisionOwnerWorkspaceForPairedTask, + ).mockReturnValue(ownerWorkspace(repoDir)); + vi.mocked(pairedWorkspaceManager.markPairedTaskReviewReady).mockReturnValue( + { + ownerWorkspace: ownerWorkspace(repoDir), + reviewerWorkspace: ownerWorkspace(repoDir), + }, + ); + }); + + function complete( + request: Partial = {}, + summary = 'TASK_DONE\n\n원인은 X입니다.', + ): void { + completePairedExecutionContext({ + taskId: 'task-1', + role: 'owner', + status: 'succeeded', + summary, + ownerReviewSkip: { + reason: '설명만 함', + toolUsage: { + tools: ['Read', 'Bash'], + bashCommands: ['git log --oneline -5', 'journalctl -n 20'], + }, + workspaceHeadAtStart: head, + ...request, + }, + }); + } + + function completedAsReviewSkipped(): boolean { + return vi + .mocked(db.updatePairedTask) + .mock.calls.some( + ([, updates]) => + updates.status === 'completed' && + updates.completion_reason === 'review_skipped', + ); + } + + it('closes the task without review when every guard passes', () => { + complete(); + expect(completedAsReviewSkipped()).toBe(true); + expect( + pairedWorkspaceManager.markPairedTaskReviewReady, + ).not.toHaveBeenCalled(); + }); + + it('reviews when a shell command could have changed something', () => { + complete({ + toolUsage: { + tools: ['Bash'], + bashCommands: ['systemctl --user restart ejclaw'], + }, + }); + expect(completedAsReviewSkipped()).toBe(false); + expect(pairedWorkspaceManager.markPairedTaskReviewReady).toHaveBeenCalled(); + }); + + it('reviews when a file-editing tool was used', () => { + complete({ toolUsage: { tools: ['Edit'], bashCommands: [] } }); + expect(completedAsReviewSkipped()).toBe(false); + expect(pairedWorkspaceManager.markPairedTaskReviewReady).toHaveBeenCalled(); + }); + + it('reviews when the runner did not report tool usage', () => { + complete({ toolUsage: null }); + expect(completedAsReviewSkipped()).toBe(false); + }); + + it('reviews when the workspace has uncommitted changes', () => { + fs.writeFileSync(path.join(repoDir, 'README.md'), 'changed\n'); + complete(); + expect(completedAsReviewSkipped()).toBe(false); + }); + + it('reviews when a commit landed during the owner run', () => { + fs.writeFileSync(path.join(repoDir, 'b.txt'), 'b\n'); + git(repoDir, 'add', 'b.txt'); + git(repoDir, 'commit', '-m', 'b'); + complete(); + expect(completedAsReviewSkipped()).toBe(false); + }); + + it('reviews when HEAD moved even if the tree did not change', () => { + git(repoDir, 'commit', '--allow-empty', '-m', 'empty'); + complete(); + expect(completedAsReviewSkipped()).toBe(false); + }); + + it('reviews when the user asked for a review in this task', () => { + vi.mocked(db.getMessagesSince).mockReturnValue([ + humanMessage('이 채널 왜 답을 안 하는지 보고 검토해줘'), + ]); + complete(); + expect(completedAsReviewSkipped()).toBe(false); + }); + + it('ignores the marker on a STEP_DONE answer', () => { + complete({}, 'STEP_DONE\n\n1단계만 봤습니다.'); + expect(completedAsReviewSkipped()).toBe(false); + expect(pairedWorkspaceManager.markPairedTaskReviewReady).toHaveBeenCalled(); + }); +}); + +describe('review request after a review-skipped answer', () => { + beforeEach(() => { + vi.resetAllMocks(); + vi.mocked(db.updatePairedTaskIfUnchanged).mockImplementation( + (id, _expected, updates) => { + vi.mocked(db.updatePairedTask)(id, updates); + return true; + }, + ); + vi.mocked(db.getLatestOpenPairedTaskForChat).mockReturnValue(undefined); + vi.mocked(db.getLatestPairedTaskForChat).mockReturnValue( + buildTask({ status: 'completed', completion_reason: 'review_skipped' }), + ); + vi.mocked(db.getPairedTaskById).mockReturnValue( + buildTask({ status: 'review_ready' }), + ); + vi.mocked(pairedWorkspaceManager.markPairedTaskReviewReady).mockReturnValue( + { + ownerWorkspace: ownerWorkspace('/tmp/owner'), + reviewerWorkspace: ownerWorkspace('/tmp/owner'), + }, + ); + }); + + it('reopens the review-skipped task for the reviewer on "검토해줘"', () => { + const task = reopenReviewSkippedTaskForReview({ + chatJid: 'dc:test', + messages: [humanMessage('검토해줘')], + }); + + expect(task?.id).toBe('task-1'); + expect(db.updatePairedTask).toHaveBeenCalledWith( + 'task-1', + expect.objectContaining({ status: 'active', completion_reason: null }), + ); + expect( + pairedWorkspaceManager.markPairedTaskReviewReady, + ).toHaveBeenCalledWith('task-1'); + expect(db.updatePairedTask).toHaveBeenCalledWith( + 'task-1', + expect.objectContaining({ round_trip_count: 1 }), + ); + }); + + it('does nothing when the latest task was reviewed normally', () => { + vi.mocked(db.getLatestPairedTaskForChat).mockReturnValue( + buildTask({ status: 'completed', completion_reason: 'done' }), + ); + expect( + reopenReviewSkippedTaskForReview({ + chatJid: 'dc:test', + messages: [humanMessage('검토해줘')], + }), + ).toBeNull(); + expect(db.updatePairedTask).not.toHaveBeenCalled(); + }); + + it('does nothing for a message that carries another instruction', () => { + expect( + reopenReviewSkippedTaskForReview({ + chatJid: 'dc:test', + messages: [humanMessage('이거 고쳐서 다시 검토해줘')], + }), + ).toBeNull(); + }); + + it('does nothing while another task is open', () => { + vi.mocked(db.getLatestOpenPairedTaskForChat).mockReturnValue( + buildTask({ id: 'task-2', status: 'active' }), + ); + expect( + reopenReviewSkippedTaskForReview({ + chatJid: 'dc:test', + messages: [humanMessage('검토해줘')], + }), + ).toBeNull(); + }); + + it('restores the skipped state when the owner workspace is gone', () => { + vi.mocked(pairedWorkspaceManager.markPairedTaskReviewReady).mockReturnValue( + null, + ); + vi.mocked(db.getPairedTaskById).mockReturnValue( + buildTask({ status: 'active' }), + ); + expect( + reopenReviewSkippedTaskForReview({ + chatJid: 'dc:test', + messages: [humanMessage('검토해줘')], + }), + ).toBeNull(); + expect(db.updatePairedTask).toHaveBeenLastCalledWith( + 'task-1', + expect.objectContaining({ + status: 'completed', + completion_reason: 'review_skipped', + }), + ); + }); +}); diff --git a/src/paired-source-ref.ts b/src/paired-source-ref.ts index d522984..77e530d 100644 --- a/src/paired-source-ref.ts +++ b/src/paired-source-ref.ts @@ -18,6 +18,36 @@ function resolveCanonicalTreeHash(workDir: string): string | null { } } +/** Current HEAD commit of a workspace, or null when it cannot be read. */ +export function resolveHeadCommit(workDir: string): string | null { + try { + return ( + execFileSync('git', ['rev-parse', 'HEAD'], { + cwd: workDir, + encoding: 'utf-8', + stdio: ['ignore', 'pipe', 'pipe'], + }).trim() || null + ); + } catch { + return null; + } +} + +/** True when `git status --porcelain` is empty; null when git fails. */ +export function isWorkingTreeClean(workDir: string): boolean | null { + try { + return ( + execFileSync('git', ['status', '--porcelain'], { + cwd: workDir, + encoding: 'utf-8', + stdio: ['ignore', 'pipe', 'pipe'], + }).trim() === '' + ); + } catch { + return null; + } +} + export function hasCodeChangesSinceRef( workDir: string, sourceRef: string | null | undefined, diff --git a/src/review-request-gate.ts b/src/review-request-gate.ts new file mode 100644 index 0000000..55196b8 --- /dev/null +++ b/src/review-request-gate.ts @@ -0,0 +1,104 @@ +import { + getLatestOpenPairedTaskForChat, + getLatestPairedTaskForChat, + getPairedTaskById, +} from './db.js'; +import { logger } from './logger.js'; +import { isExternalHumanMessage } from './message-runtime-rules.js'; +import { applyPairedTaskPatch } from './paired-task-status.js'; +import { markPairedTaskReviewReady } from './paired-workspace-manager.js'; +import { + isReviewRequestMessage, + REVIEW_SKIPPED_COMPLETION_REASON, +} from './review-skip.js'; +import { hasReviewerLease } from './service-routing.js'; +import type { NewMessage, PairedTask } from './types.js'; + +/** + * "검토해줘" after a review-skipped answer: reopen that same task for the + * reviewer instead of starting a new owner task. Reopening (rather than a new + * task) keeps the owner answer as the task's turn output — which is what the + * reviewer reviews — and keeps the owner's task-scoped session for revisions. + */ + +/** The batch is exactly one short human review request. */ +export function findReviewRequest(messages: NewMessage[]): NewMessage | null { + const human = messages.filter(isExternalHumanMessage); + if (human.length !== 1) return null; + return isReviewRequestMessage(human[0].content) ? human[0] : null; +} + +/** + * Reopen the room's latest task for review when the user's new message is a + * bare review request and that task was closed with its review skipped. + * Returns the task (now review_ready) or null when the gate does not apply. + */ +export function reopenReviewSkippedTaskForReview(args: { + chatJid: string; + messages: NewMessage[]; +}): PairedTask | null { + const { chatJid } = args; + if (!hasReviewerLease(chatJid)) return null; + if (!findReviewRequest(args.messages)) return null; + if (getLatestOpenPairedTaskForChat(chatJid)) return null; + const task = getLatestPairedTaskForChat(chatJid); + if ( + !task || + task.status !== 'completed' || + task.completion_reason !== REVIEW_SKIPPED_COMPLETION_REASON + ) { + return null; + } + + // completed is terminal in the normal state machine; this explicit reopen is + // the one sanctioned exit, guarded by the task revision. + const reopenedAt = new Date().toISOString(); + if ( + !applyPairedTaskPatch({ + taskId: task.id, + expectedUpdatedAt: task.updated_at, + updatedAt: reopenedAt, + patch: { status: 'active', completion_reason: null }, + }) + ) { + return null; + } + if (!markPairedTaskReviewReady(task.id)) { + const current = getPairedTaskById(task.id); + if (current) { + applyPairedTaskPatch({ + taskId: task.id, + expectedUpdatedAt: current.updated_at, + updatedAt: new Date().toISOString(), + patch: { + status: 'completed', + completion_reason: REVIEW_SKIPPED_COMPLETION_REASON, + }, + }); + } + logger.warn( + { chatJid, taskId: task.id }, + 'Could not reopen review-skipped task for review (owner workspace missing)', + ); + return null; + } + const reviewReady = getPairedTaskById(task.id); + if (!reviewReady) return null; + applyPairedTaskPatch({ + taskId: task.id, + expectedUpdatedAt: reviewReady.updated_at, + updatedAt: new Date().toISOString(), + patch: { + round_trip_count: 1, + owner_failure_count: 0, + reviewer_failure_count: 0, + arbiter_verdict: null, + arbiter_requested_at: null, + }, + }); + logger.info( + { chatJid, taskId: task.id }, + 'Reopened review-skipped task for review on user request', + ); + return getPairedTaskById(task.id) ?? null; +} diff --git a/src/review-skip.test.ts b/src/review-skip.test.ts new file mode 100644 index 0000000..45bf365 --- /dev/null +++ b/src/review-skip.test.ts @@ -0,0 +1,228 @@ +import { describe, expect, it } from 'vitest'; + +import { resolveOwnerCompletionSignal } from './paired-completion-signals.js'; +import { + containsReviewRequest, + evaluateReviewSkipGuards, + extractReviewSkipMarker, + findToolUsageMutations, + isReviewRequestMessage, + type OwnerReviewSkipRequest, +} from './review-skip.js'; + +describe('extractReviewSkipMarker', () => { + it('strips a trailing marker line and returns the reason', () => { + expect( + extractReviewSkipMarker( + 'TASK_DONE\n\n설명입니다.\n\n리뷰 불필요: 코드 변경 없는 설명\n', + ), + ).toEqual({ + text: 'TASK_DONE\n\n설명입니다.', + reason: '코드 변경 없는 설명', + }); + }); + + it('accepts bold and full-width colon variants', () => { + expect( + extractReviewSkipMarker('답변\n**리뷰 불필요**: 조회만 함').reason, + ).toBe('조회만 함'); + }); + + it('ignores a marker that is not the last line', () => { + const text = '리뷰 불필요: 이건 본문 인용\n실제 마지막 줄'; + expect(extractReviewSkipMarker(text)).toEqual({ text, reason: null }); + }); + + it('does not strip when the marker is the whole answer', () => { + const text = '리뷰 불필요: 이유'; + expect(extractReviewSkipMarker(text)).toEqual({ text, reason: null }); + }); + + it('returns the text untouched without a marker', () => { + expect(extractReviewSkipMarker('TASK_DONE\n본문')).toEqual({ + text: 'TASK_DONE\n본문', + reason: null, + }); + }); +}); + +describe('isReviewRequestMessage', () => { + it.each([ + '검토해줘', + '검토해 줘', + '검토 해줘', + '리뷰해줘', + '리뷰 해줘', + '검토 부탁해', + '검토 부탁드려요', + '검토 좀 해줘', + '이거 검토해줘', + '방금 거 리뷰 좀', + '검토해주세요.', + '검토!', + '<@123456> 검토해줘', + 'review', + 'please review', + 'review it please', + ])('treats %j as a review request', (text) => { + expect(isReviewRequestMessage(text)).toBe(true); + }); + + it.each([ + '검토하지 마', + '검토 안 해도 돼', + '이 코드 고치고 검토해줘', + '검토해줘\n그리고 배포도', + '리뷰 불필요', + '리뷰어 설정 바꿔줘', + '로그인 기능 검토해서 개선안 만들어줘', + 'review the login flow and fix the bug', + '', + ])('does not treat %j as a bare review request', (text) => { + expect(isReviewRequestMessage(text)).toBe(false); + }); +}); + +describe('containsReviewRequest', () => { + it.each([ + '이 코드 고치고 검토해줘', + '수정한 다음 리뷰 받아줘', + '검토 부탁합니다', + 'please review this change', + ])('detects an explicit review request in %j', (text) => { + expect(containsReviewRequest(text)).toBe(true); + }); + + it.each(['리뷰 불필요', '검토하지 마', '이 채널 왜 답 안 해?', 'reviewer'])( + 'does not flag %j', + (text) => { + expect(containsReviewRequest(text)).toBe(false); + }, + ); +}); + +describe('findToolUsageMutations', () => { + it('passes read-only tools and read-only shell commands', () => { + expect( + findToolUsageMutations({ + tools: [ + 'Read', + 'Grep', + 'Bash', + 'mcp__ejclaw__read_db_evidence', + 'mcp__ejclaw__send_message', + ], + bashCommands: ['git status', 'journalctl --user -u ejclaw -n 20'], + }), + ).toEqual([]); + }); + + it.each([ + ['Edit'], + ['Write'], + ['MultiEdit'], + ['NotebookEdit'], + ['Agent'], + ['Task'], + ['TeamCreate'], + ['mcp__ejclaw__schedule_task'], + ['mcp__ejclaw__update_task'], + ['mcp__ejclaw__cancel_task'], + ['mcp__ejclaw__pause_task'], + ['mcp__ejclaw__resume_task'], + ['mcp__ejclaw__watch_ci'], + ['mcp__ejclaw__assign_room'], + ['mcp__other__read_db_evidence'], + ['SomeNewTool'], + ])('flags the %s tool', (tool) => { + expect(findToolUsageMutations({ tools: [tool], bashCommands: [] })).toEqual( + [`tool ${tool}`], + ); + }); + + it('flags mutating shell commands', () => { + expect( + findToolUsageMutations({ + tools: ['Bash', 'Bash'], + bashCommands: ['ls', 'systemctl --user restart ejclaw'], + }), + ).toEqual(['bash: systemctl --user restart ejclaw']); + }); + + it('fails closed when usage is missing or truncated', () => { + expect(findToolUsageMutations(null)).toEqual(['tool usage not reported']); + expect( + findToolUsageMutations({ tools: [], bashCommands: [], truncated: true }), + ).toEqual(['tool usage report truncated']); + }); +}); + +describe('evaluateReviewSkipGuards', () => { + const request: OwnerReviewSkipRequest = { + reason: '설명만 함', + toolUsage: { tools: ['Read', 'Bash'], bashCommands: ['git log -3'] }, + workspaceHeadAtStart: 'abc', + }; + const clean = { + request, + hasCodeChangesSinceBase: false, + workingTreeClean: true, + workspaceHeadNow: 'abc', + explicitReviewRequested: false, + } as const; + + it('passes when nothing changed', () => { + expect(evaluateReviewSkipGuards(clean)).toEqual([]); + }); + + it.each([ + [{ hasCodeChangesSinceBase: true }], + [{ hasCodeChangesSinceBase: null }], + [{ workingTreeClean: false }], + [{ workingTreeClean: null }], + [{ workspaceHeadNow: 'def' }], + [{ workspaceHeadNow: null }], + [{ explicitReviewRequested: true }], + [{ request: { ...request, workspaceHeadAtStart: null } }], + [ + { + request: { + ...request, + toolUsage: { tools: ['Bash'], bashCommands: ['rm -rf x'] }, + }, + }, + ], + ])('fails when %j', (override) => { + expect( + evaluateReviewSkipGuards({ ...clean, ...override }).length, + ).toBeGreaterThan(0); + }); +}); + +describe('resolveOwnerCompletionSignal review skip', () => { + it('completes a TASK_DONE answer when the skip was approved', () => { + expect( + resolveOwnerCompletionSignal({ + phase: 'normal', + visibleVerdict: 'task_done', + reviewSkipApproved: true, + }), + ).toEqual({ kind: 'complete', completionReason: 'review_skipped' }); + }); + + it('still requests review without approval or for non-final verdicts', () => { + expect( + resolveOwnerCompletionSignal({ + phase: 'normal', + visibleVerdict: 'task_done', + }).kind, + ).toBe('request_reviewer'); + expect( + resolveOwnerCompletionSignal({ + phase: 'normal', + visibleVerdict: 'step_done', + reviewSkipApproved: true, + }).kind, + ).toBe('request_reviewer'); + }); +}); diff --git a/src/review-skip.ts b/src/review-skip.ts new file mode 100644 index 0000000..58637ac --- /dev/null +++ b/src/review-skip.ts @@ -0,0 +1,189 @@ +import { classifyBashCommand } from './bash-command-classifier.js'; + +/** + * "리뷰 불필요" — the owner may mark a pure explanation/investigation answer as + * not needing review. The marker is a request, not a decision: the host only + * honors it after re-checking that the owner turn changed nothing. + */ + +export const REVIEW_SKIPPED_COMPLETION_REASON = 'review_skipped'; + +/** Discord small-text note appended to an answer whose review was skipped. */ +export const REVIEW_SKIPPED_NOTE = + '-# 검토 생략(변경 없는 설명형 답변) · "검토해줘"라고 하면 검토합니다'; + +/** Tool calls the runner observed during one agent run. */ +export interface AgentToolUsage { + /** Tool names in call order (may repeat). */ + tools: string[]; + /** Bash commands in call order. */ + bashCommands: string[]; + /** True when the runner dropped entries because of its size cap. */ + truncated?: boolean; +} + +export interface OwnerReviewSkipRequest { + reason: string; + /** null when the runner did not report tool usage (e.g. a Codex owner). */ + toolUsage: AgentToolUsage | null; + /** Owner workspace HEAD commit when the owner run started. */ + workspaceHeadAtStart: string | null; +} + +const MARKER_LINE_PATTERN = + /^\s*(?:\*\*)?리뷰\s*불필요(?:\*\*)?\s*[::]\s*(.*)$/; + +/** + * Split a trailing "리뷰 불필요: " line off an owner answer. Only the + * last non-empty line counts, so an answer that merely mentions the marker in + * its body is left untouched. + */ +export function extractReviewSkipMarker(text: string): { + text: string; + reason: string | null; +} { + const lines = text.split('\n'); + let last = lines.length - 1; + while (last >= 0 && lines[last].trim() === '') last -= 1; + if (last < 0) return { text, reason: null }; + const match = lines[last].match(MARKER_LINE_PATTERN); + if (!match) return { text, reason: null }; + const stripped = lines.slice(0, last).join('\n').trimEnd(); + if (!stripped.trim()) return { text, reason: null }; + return { + text: stripped, + reason: match[1].replace(/\*\*$/, '').trim() || '(이유 없음)', + }; +} + +// Tools that only read. Everything else (Edit, Write, MultiEdit, NotebookEdit, +// Agent/Task subagents whose calls are not visible, team tools, unknown tools) +// counts as possibly mutating. +const READ_ONLY_TOOLS = new Set([ + 'Read', + 'Glob', + 'Grep', + 'LS', + 'WebSearch', + 'WebFetch', + 'TodoWrite', + 'ToolSearch', + 'Skill', + 'TaskOutput', + 'BashOutput', + 'NotebookRead', +]); + +const READ_ONLY_MCP_TOOLS = new Set([ + 'send_message', + 'list_tasks', + 'read_db_evidence', + 'read_deploy_evidence', + 'read_github_evidence', + 'read_host_evidence', + 'read_repo_evidence', + 'run_verification', +]); + +function isReadOnlyTool(name: string): boolean { + if (READ_ONLY_TOOLS.has(name)) return true; + // Only EJClaw's own MCP tools are known; other MCP servers count as mutating. + const [prefix, server, ...rest] = name.split('__'); + return ( + prefix === 'mcp' && + server === 'ejclaw' && + READ_ONLY_MCP_TOOLS.has(rest.join('__')) + ); +} + +/** Why the owner turn may have changed something; empty when it did not. */ +export function findToolUsageMutations( + toolUsage: AgentToolUsage | null, +): string[] { + if (!toolUsage) return ['tool usage not reported']; + const reasons: string[] = []; + if (toolUsage.truncated) reasons.push('tool usage report truncated'); + for (const tool of new Set(toolUsage.tools)) { + if (tool !== 'Bash' && !isReadOnlyTool(tool)) { + reasons.push(`tool ${tool}`); + } + } + for (const command of toolUsage.bashCommands) { + if (classifyBashCommand(command) === 'mutating') { + reasons.push(`bash: ${command.slice(0, 120)}`); + } + } + return reasons; +} + +/** + * Every guard that must hold before a "리뷰 불필요" marker is honored. Returns + * the list of failed guards (empty = honor the marker). + */ +export function evaluateReviewSkipGuards(args: { + request: OwnerReviewSkipRequest; + /** git diff of the task base ref vs HEAD; true/null = changed or unknown. */ + hasCodeChangesSinceBase: boolean | null; + /** git status --porcelain is empty; null = unknown. */ + workingTreeClean: boolean | null; + workspaceHeadNow: string | null; + explicitReviewRequested: boolean; +}): string[] { + const failures: string[] = []; + if (args.explicitReviewRequested) { + failures.push('user explicitly asked for a review'); + } + if (args.hasCodeChangesSinceBase !== false) { + failures.push('workspace content differs from the task base'); + } + if (args.workingTreeClean !== true) { + failures.push('workspace has uncommitted changes'); + } + if ( + !args.request.workspaceHeadAtStart || + !args.workspaceHeadNow || + args.request.workspaceHeadAtStart !== args.workspaceHeadNow + ) { + failures.push('workspace HEAD moved during the owner run'); + } + failures.push(...findToolUsageMutations(args.request.toolUsage)); + return failures; +} + +// ── Review request intent ───────────────────────────────────────── + +const EDGE_MENTIONS_PATTERN = /^(?:<@[!&]?\d+>\s*)+|(?:\s*<@[!&]?\d+>)+$/g; +const TRAILING_NOISE_PATTERN = /[\s.!~…;,?]+$/u; +const MAX_REVIEW_REQUEST_LENGTH = 30; + +const KOREAN_REVIEW_REQUEST_PATTERN = new RegExp( + '^(?:이거|이것|그거|그것|위|위에|위에거|방금|방금거|답변|이답변|그답변)?(?:도|좀)?' + + '(?:검토|리뷰)(?:도|좀)?' + + '(?:해|해줘|해줘요|해주세요|해주라|해줄래|해봐|해봐요|해보자|하자|부탁|부탁해|부탁해요|부탁드려요|부탁드립니다|부탁합니다|받아|받아줘|받아봐|받자|돌려|돌려줘|요청|요청해)?' + + '(?:요)?$', + 'u', +); + +const ENGLISH_REVIEW_REQUEST_PATTERN = + /^(?:(?:please|pls|ok|okay)\s+)?review(?:\s+(?:it|this|that|again))?(?:\s+please)?$/; + +/** The whole (short) message is a request to review the previous answer. */ +export function isReviewRequestMessage(content: string): boolean { + let text = content.trim(); + if (text.includes('\n')) return false; + text = text.replace(EDGE_MENTIONS_PATTERN, '').trim(); + text = text.replace(TRAILING_NOISE_PATTERN, '').toLowerCase(); + if (!text || text.length > MAX_REVIEW_REQUEST_LENGTH) return false; + if (ENGLISH_REVIEW_REQUEST_PATTERN.test(text.replace(/\s+/g, ' '))) { + return true; + } + return KOREAN_REVIEW_REQUEST_PATTERN.test(text.replace(/\s+/g, '')); +} + +const CONTAINS_REVIEW_REQUEST_PATTERN = + /(?:검토|리뷰)\s*(?:도|좀)?\s*(?:해\s*줘|해\s*주세요|해\s*주라|해\s*줄래|해\s*봐|해\s*달라|부탁|받아|돌려|요청|해서\s*(?:알려|보고))|\bplease\s+review\b|\breview\s+(?:it|this|that|please)\b/i; + +/** A message (of any length) that explicitly asks for a review. */ +export function containsReviewRequest(content: string): boolean { + return CONTAINS_REVIEW_REQUEST_PATTERN.test(content); +}