Commit Graph

126 Commits

Author SHA1 Message Date
Eyejoker
4a5edaceb6 refactor: remove SERVICE_AGENT_TYPE legacy constant
SERVICE_AGENT_TYPE was always 'claude-code' in the unified service,
making it a misleading constant. Each group already has its own
agentType field.

- Removed SERVICE_AGENT_TYPE from config.ts
- Session functions now accept agentType parameter (default: 'claude-code')
- Task scheduler uses task-level agent_type for token rotation decisions
- All fallback defaults changed to 'claude-code' literal
- Logging uses 'unified' instead of the misleading type
2026-03-30 23:10:48 +09:00
Eyejoker
5562e30ce1 refactor: use resolveActiveRole() as SSOT for all status→role mapping
Eliminated duplicate task status checks in message-agent-executor.ts
and message-runtime.ts. All status→role decisions now flow through
the single resolveActiveRole() function.
2026-03-30 23:03:00 +09:00
Eyejoker
d3df67e08c chore: remove dead code (pairedCursorKey, unused ARBITER_AGENT_TYPE import) 2026-03-30 22:59:18 +09:00
Eyejoker
14d70f345a refactor: extract resolveActiveRole() as single source of status→role mapping
resolveCursorKey and resolveChannel both duplicated the same
taskStatus→role switch. Now resolveActiveRole() is the single
mapping, and both functions derive from it.
2026-03-30 22:58:00 +09:00
Eyejoker
a91776b067 refactor: centralize channel selection with resolveChannel()
Replace all manual channel selection (useReviewerChannel,
useArbiterChannel, isReviewerWorkItem, isArbiterWorkItem, 3-way
ternary chains) with a single resolveChannel(taskStatus) function
that maps task status to the correct Discord bot channel.
2026-03-30 22:56:40 +09:00
Eyejoker
7ad40276d9 refactor: centralize cursor key resolution with resolveCursorKey()
Replace all manual cursor key construction (hardcoded chatJid:reviewer,
chatJid:arbiter, pairedCursorKey, 3-way ternary) with a single
resolveCursorKey(chatJid, taskStatus) function.

- Removed pairedCursorKey import (no longer needed)
- Removed loopIsReviewerTurn, loopIsArbiterTurn intermediate variables
- All cursor key logic now flows through one function that maps
  task status to the correct role-specific key
2026-03-30 22:54:35 +09:00
Eyejoker
46926f32f3 fix: use role-specific cursor keys in review_ready and arbiter_requested paths
The review_ready and arbiter_requested paths in processGroupMessages
were advancing the default (owner) cursor instead of the role-specific
cursor. This caused the reviewer to miss the owner's messages because
the owner cursor had already moved past them.

Now review_ready advances chatJid:reviewer cursor only, and
arbiter_requested advances chatJid:arbiter cursor only.
2026-03-30 22:50:26 +09:00
Eyejoker
4ccd45e549 fix: arbiter always uses discord-review bot regardless of model 2026-03-30 22:34:49 +09:00
Eyejoker
f3b25b1b40 fix: apply role labels to arbiter conversation context 2026-03-30 22:33:42 +09:00
Eyejoker
a043f2b79a feat: implement MAGI 3-agent arbiter system for deadlock resolution
Introduces a third agent role (arbiter) that is summoned on-demand
when owner and reviewer reach a deadlock (same verdict 3+ rounds).

Architecture:
- 3 Discord bots: owner (codex), reviewer (claude), arbiter (claude/codex)
- Arbiter is NOT always-on — only invoked when deadlock detected
- Arbiter renders binding verdict: PROCEED/REVISE/RESET/ESCALATE
- Non-escalate verdicts reset round_trip_count and resume ping-pong
- Backward compatible: ARBITER_AGENT_TYPE unset = existing 2-agent mode

Changes across 13 source files + 7 test files:
- types.ts: PairedRoomRole += 'arbiter', new statuses, ArbiterVerdict type
- config.ts: ARBITER_AGENT_TYPE, ARBITER_SERVICE_ID, ARBITER_DEADLOCK_THRESHOLD
- db.ts: schema migration (arbiter columns in channel_owner + paired_tasks)
- service-routing.ts: arbiter_service_id in lease
- room-role-context.ts: arbiter role detection
- paired-execution-context.ts: deadlock->arbiter, verdict handling
- message-runtime.ts: arbiter turn routing, cursor, sender labeling
- message-agent-executor.ts: arbiter mode, failover
- agent-runner.ts + environment.ts: arbiter container mode
- platform-prompts.ts: arbiter prompt loading

New files:
- prompts/arbiter-paired-room.md: arbiter system prompt
- src/arbiter-context.ts: builds conversation context for arbiter judgment
2026-03-30 22:20:42 +09:00
Eyejoker
58ed721d6e feat: auto-recreate reviewer containers on token rotation
When OAuth tokens rotate or refresh, all reviewer containers are
automatically removed. The next reviewer turn recreates them with
the latest token, preventing 401 auth failures.

Uses callback pattern to avoid circular dependencies:
- token-rotation.ts: onTokenRotated(cb)
- token-refresh.ts: onTokenRefreshed(cb)
- index.ts: registers recreateAllReviewerContainers as callback
2026-03-30 21:51:45 +09:00
Eyejoker
c954a383d3 fix: route reviewer failover handoffs via reviewer channel
Reviewer failover handoffs were routed through the owner channel,
causing codex-review to run in owner mode instead of reviewer mode.
Now detects reviewer handoffs by reason prefix and routes them
through the correct reviewer channel.
2026-03-30 20:32:20 +09:00
Eyejoker
39e94c47b3 fix: collect handoffs for all service IDs in unified service
The unified service runs all three bots (claude, codex-main,
codex-review) in one process but only queried handoffs for SERVICE_ID
(claude). Reviewer failover handoffs targeting codex-review were
never picked up. Now queries all three service IDs.
2026-03-30 20:26:43 +09:00
Eyejoker
b209061006 fix: use separate cursors for owner and reviewer in paired rooms
Root cause: owner and reviewer shared the same message cursor. When
the owner's turn completed, the cursor advanced past the owner's
message. The reviewer's turn then only saw messages after that cursor,
missing the owner's response entirely.

Now paired rooms use role-aware cursor keys (chatJid for owner,
chatJid:reviewer for reviewer). Each role advances only its own
cursor, so the reviewer always sees the owner's latest messages
and vice versa.
2026-03-30 20:23:16 +09:00
Eyejoker
78fa078921 fix: only reset merge_ready to active when human message is present
The finalize turn (auto-triggered after reviewer approval) was being
treated as a new working turn because merge_ready was unconditionally
reset to active. Now merge_ready is only reset when a human message
is in the batch, preserving the finalize flow for bot-only turns.
2026-03-30 19:48:25 +09:00
Eyejoker
f30b25d2b4 fix: use English role labels (owner/reviewer) for paired room sender names 2026-03-30 19:31:31 +09:00
Eyejoker
c17edd8773 feat: label bot messages with role names in paired rooms
In paired rooms, bot messages now show sender as "오너" or "리뷰어"
instead of the Discord nickname. Uses channel.isOwnMessage() to
identify which bot sent each message, then maps via the channel
lease to determine the role. This ensures agents correctly identify
who is the owner and who is the reviewer regardless of bot nicknames.
2026-03-30 19:30:59 +09:00
Eyejoker
17e92d4c3d fix: isolate stale finals from next runs 2026-03-30 05:23:29 +09:00
Eyejoker
5e4f1fa8da Merge pull request #1 from phj1081/codex/remove-explicit-paired-review-command-path
refactor: remove dead paired review and output suppression paths
2026-03-30 03:35:34 +09:00
Eyejoker
e863db61a8 refactor: remove dead output suppression path 2026-03-30 03:22:08 +09:00
Eyejoker
0c6167f5dc fix: remove hardcoded finalize instructions from turn prompt 2026-03-30 02:35:44 +09:00
Eyejoker
691be0dc86 refactor: streamline paired room prompts and fix role separation
Prompts:
- Remove model-specific names (클코, Codex) — use owner/reviewer only
- Compress duplicated sections (communication, stagnation, consensus)
  while preserving 4 ontological questions and verdict protocol intact
- Remove verdict examples (redundant with status descriptions)
- claude-platform.md: strip SDK defaults, keep only send_message rules

Code:
- Remove reviewer paired room prompt from owner CLAUDE.md
  (was causing role confusion — owner got "You are the reviewer")
- Remove "Provide feedback or approve" from review turn prompt
  (conflicted with CLAUDE.md verdict protocol)

187 lines → 100 lines across 4 prompt files.
2026-03-30 02:31:04 +09:00
Eyejoker
5865dea558 fix: route reviewer output to reviewer channel in queued message path
When reviewer was triggered via the normal message dispatch path (not
the review_ready check path), output was sent through the owner channel.
Now checks paired task status to determine the correct output channel.
2026-03-30 00:54:51 +09:00
Eyejoker
4f87c840ba refactor: remove /review command and clean up unused imports 2026-03-29 21:17:14 +09:00
Eyejoker
9127841359 fix: /clear resets paired task to prevent reviewer auto-triggering after session clear 2026-03-29 21:07:34 +09:00
Eyejoker
d8cb4b691e feat: verdict-based ping-pong control with merge_ready finalization
- DONE → merge_ready → owner final turn (commit/push) → completed
- DONE_WITH_CONCERNS → active → owner addresses → ping-pong continues
- BLOCKED/NEEDS_CONTEXT → completed (escalate to user, stop ping-pong)
- Regular feedback → active → ping-pong continues
- Owner detects merge_ready status and finalizes autonomously
2026-03-29 20:59:08 +09:00
Eyejoker
16d20fe627 feat: paired review system overhaul — unified service, configurable agents, silent output removal
- Remove UNIFIED_MODE legacy: single service manages all 3 Discord bots
- Add OWNER_AGENT_TYPE / REVIEWER_AGENT_TYPE env vars for configurable agent selection
- Fix Discord channel routing: reviewer output goes through correct bot (discord/discord-review)
- Fix channel name assignment: explicit names prevent agentTypeFilter collision
- Remove silent output suppression system: harness-level protections replace prompt workarounds
- Add reviewer approval detection: DONE marker on first line stops ping-pong
- Include user's original message in reviewer prompt for context
- Fix round_trip_count auto-reset on new user message
- Fix session ID conflict: reviewer doesn't reuse owner's session
- Fix pending progress text flush in runner on close sentinel
- Promote buffered intermediate text to final result when result event has no text
- Remove legacy files: .env.codex.example, .env.codex-review.example, migrate-unify.cjs
- Update CLAUDE.md: server-side build deployment, unified architecture docs
2026-03-29 20:50:32 +09:00
Eyejoker
a8bf6b806d fix: run reviewer turn on review_ready status even without new messages 2026-03-29 19:19:47 +09:00
Eyejoker
9e0de1297c fix: /clear now resets both owner and reviewer sessions in paired rooms 2026-03-29 19:00:42 +09:00
Eyejoker
2ec90fe086 feat: add /stop command to kill running agent process
- /stop, /cancel, /kill aliases all supported
- SIGTERM first (allows graceful AbortController cleanup), SIGKILL after 5s
- Wired through session-commands → GroupQueue.killProcess()
2026-03-29 18:44:37 +09:00
Eyejoker
d01f98bd61 feat: unify 3 bot services into single process
- Add UNIFIED_MODE flag (default on, disable with UNIFIED_MODE=0)
- Register all 3 Discord bots in one process (claude, codex, review)
- Load all registered groups regardless of agent_type (codex/owner priority)
- Start credential proxy and container cleanup at unified startup
- shouldServiceProcessChat returns true in unified mode
- Add findChannelByName for role-based response routing
- Backward compatible: UNIFIED_MODE=0 restores per-service behavior
2026-03-29 18:37:17 +09:00
Eyejoker
fc9f2867b9 refactor: simplify paired review system and add reviewer container isolation
Phase 1 — Strip over-engineering (-3,665 lines):
- DB tables: 7 → 3 (remove executions, approvals, artifacts, events)
- Task statuses: 11 → 5 (active, review_ready, in_review, merge_ready, completed)
- Remove plan governance, event sourcing, gate/verdict, freshness guards
- paired-execution-context: 980 → 299 lines
- Session commands: remove /risk, /plan, /approve-plan, /request-plan-changes

Phase 2 — Container isolation for reviewers:
- Add container-runtime.ts (Docker abstraction)
- Add credential-proxy.ts (API key injection without container exposure)
- Add container-runner.ts (reviewer-specific read-only mount + tmpfs)
- Add container/Dockerfile + agent-runner (Chromium, Claude Code, Codex)
- agent-runner.ts: auto-route reviewer execution to container mode
2026-03-29 18:24:56 +09:00
Eyejoker
0e12a560a4 feat: finalize paired tasks on deploy completion 2026-03-29 06:42:03 +09:00
Eyejoker
29310ce67f feat: recover paired executions after restart 2026-03-29 05:06:25 +09:00
Eyejoker
d460933229 feat: add paired intent checkpoints 2026-03-29 03:34:55 +09:00
Eyejoker
b536c90716 feat: add high-risk paired plan gate 2026-03-29 02:13:57 +09:00
Eyejoker
b0c833fd70 fix: keep review requests pending without owner workspace 2026-03-29 00:21:29 +09:00
Eyejoker
e7f49d77da feat: add paired review workspace flow 2026-03-28 21:14:25 +09:00
Eyejoker
b97d1a6260 refactor: unify typing policy across services 2026-03-28 06:52:57 +09:00
Eyejoker
e1fdc47552 style: sync pre-commit formatting fallout 2026-03-28 05:41:16 +09:00
Eyejoker
ba9f6871b6 feat: add codex review failover and suppress output hardening 2026-03-28 05:40:38 +09:00
Eyejoker
18788f7f91 chore: add state transition logging 2026-03-25 12:16:09 +09:00
Eyejoker
03b9480614 fix: prevent typing indicator leak on agent run exceptions and follow-up race
Two leak paths caused Discord typing indicators to persist indefinitely:

1. If runAgent() threw before turnController.finish(), setTyping(false)
   was never called. Wrap the agent run in try/finally to guarantee cleanup.

2. Follow-up message piping called setTyping(true) fire-and-forget. If
   the Promise resolved after finish()'s setTyping(false), the typing
   interval was recreated with nobody to clear it. Await the call to
   serialize the on/off sequence.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-25 11:18:54 +09:00
Eyejoker
5ea3439c5f refactor: extract shared utilities, protocol constants, and retry loop
Phase 3: provider-retry.ts — shared Claude rotation loop (SSOT)
  - retryClaudeWithRotation extracted from message-agent-executor + task-scheduler
  - ~200 lines of duplicated retry logic removed

Phase 4: types.ts — AgentOutputPhase + VisiblePhase unified
Phase 5: types.ts — AgentConfig extended with claudeThinking/claudeThinkingBudget

Utilities (utils.ts):
  - getErrorMessage: 14 occurrences of instanceof Error pattern → 1 function
  - readJsonFile/writeJsonFile: 19 occurrences of JSON+fs pattern → 2 functions
  - fetchWithTimeout: 3 occurrences of AbortController pattern → 1 function
  - formatElapsedKorean: deduplicated from task-watch-status + message-turn-controller

Protocol (agent-protocol.ts):
  - OUTPUT_START/END_MARKER centralized (runners keep local copies with SSOT reference)
  - IMAGE_TAG_RE, IPC constants documented

Runner: show "대화 요약 중..." progress message during auto-compact

Net: -137 lines, 354/354 tests passing
2026-03-25 04:59:49 +09:00
Eyejoker
f5eae07657 fix: use resolved ipc dirs for recovery flow 2026-03-23 07:18:47 +09:00
Eyejoker
9def49f7fb fix: isolate watcher task runtimes 2026-03-23 07:16:07 +09:00
Eyejoker
898c77fcfc refactor: consolidate runtime helpers 2026-03-23 06:39:26 +09:00
Eyejoker
c733217074 style: format runtime helpers 2026-03-23 06:17:41 +09:00
Eyejoker
d4b19ab950 refactor: split message runtime state 2026-03-23 06:17:17 +09:00
Eyejoker
2c37103243 refactor: restore pre-v1 runtime follow-up flow 2026-03-23 05:54:48 +09:00