refactor: remove the main room concept

No room has room_settings.is_main = 1, so every main-only path was dead,
and admin work is done from the host shell. Each room's agent may now
only act on its own room:

- IPC: messages/inbound injection only to the source room; schedule,
  update, pause, resume and cancel only for the source room's tasks;
  drop the assign_room and refresh_groups IPC tasks and the deps they
  needed (assignRoom/syncGroups/getAvailableGroups/writeGroupsSnapshot)
- DB/host evidence is always scoped to the source group folder
- runner MCP server: drop the assign_room tool, the target_group_jid
  parameters and the isMain flag; list_tasks shows only the room's tasks
- drop EJCLAW_IS_MAIN, RunnerInput.isMain and AgentInput.isMain; the
  global CLAUDE.md memory is now included for every room
- drop the available_groups.json snapshot (available-groups.ts), the
  inferred restart announcement that only went to the main room, and
  the unused Channel.syncGroups hook
- setup register: drop --is-main; deregister-room: drop the main-room
  refusal and --force, and fix its unknown[] binding type error
- remove the groups/main/ template

The room_settings.is_main column and migrations are untouched; new rows
get the column default (0) and nothing reads it anymore.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Codex
2026-10-01 19:37:29 +09:00
parent ce4547daa6
commit f127ac7a2b
62 changed files with 136 additions and 1412 deletions

View File

@@ -76,11 +76,11 @@ journalctl --user -u ejclaw -f | grep -iE 'transcri|audio|whisper|groq'
### 등록은 되어 있는데 응답이 이상함
```bash
bun -e "import {Database} from 'bun:sqlite'; const db=new Database('store/messages.db',{readonly:true}); console.table(db.query('select chat_jid, folder, room_mode, requires_trigger, is_main, owner_agent_type, work_dir from room_settings').all())"
bun -e "import {Database} from 'bun:sqlite'; const db=new Database('store/messages.db',{readonly:true}); console.table(db.query('select chat_jid, folder, room_mode, requires_trigger, owner_agent_type, work_dir from room_settings').all())"
```
- `chat_jid`는 `dc:<channel_id>` 형식이어야 합니다. tribunal 방인데 `work_dir`가 비어 있으면 첫 턴에 자동 복구됩니다.
- `folder`는 `discord_main` 또는 `discord_<name>` 형태를 유지합니다.
- `folder`는 `discord_<name>` 형태를 유지합니다.
- 작업 중단("그만", "stop")이 안 먹으면 로그의 `Stopped room work on user request`와 `src/stop-intent.ts` 판정 규칙을 같이 봅니다.
## 원칙

View File

@@ -107,11 +107,10 @@ bun run setup -- --step runners
bun run setup -- --step register -- \
--jid dc:123456789012345678 \
--name "My Server #general" \
--folder discord_main \
--is-main
--folder discord_general
```
보조 채널 예시:
다른 채널 예시 (모든 방은 동등하며 자기 방만 다룹니다):
```bash
bun run setup -- --step register -- \

3
.gitignore vendored
View File

@@ -20,11 +20,8 @@ logs/
# Groups - only track base structure and specific CLAUDE.md files
groups-*/
groups/*
!groups/main/
!groups/global/
groups/main/*
groups/global/*
!groups/main/CLAUDE.md
!groups/global/CLAUDE.md
# Secrets

View File

@@ -22,10 +22,12 @@
- macOS launchd·nohup(WSL) 설치 경로와 `launchd/`, 쓰이지 않던 `repo-tokens/` GitHub Action. 서비스 설치는 Linux systemd만 지원
- 루트에서 import하지 않던 `yaml`, `zod`, `@modelcontextprotocol/sdk` 의존성 (agent-runner는 자체 의존성 유지)
- `/compact`·`/clear`·`/stop` 세션 명령(main 방·관리자 전용이라 실제로 쓰이지 않음)과 `SESSION_COMMAND_ALLOWED_SENDERS` 설정, agent-runner의 `/compact` 처리. `.env`에 남아 있는 `SESSION_COMMAND_*` 값은 더 이상 시작을 막지 않고 무시됨
- main(관리) 방 개념과 그것이 열어 주던 방 간 기능. 모든 방의 `is_main`이 0이라 실제로 쓰이지 않았음. 이제 각 방의 에이전트는 자기 방만 다룸: 다른 방 예약 작업 생성/수정/일시정지/취소(`target_group_jid`), 다른 방으로 메시지 전송·inbound 주입, 전체 방 범위의 DB 증거 조회, IPC `assign_room`/`refresh_groups`와 에이전트용 `assign_room` 도구, `available_groups.json` 스냅샷, main 방 전용 global memory 제외, `EJCLAW_IS_MAIN` 환경 변수, main 방으로 보내던 추론 재시작 알림, `setup --step register`의 `--is-main`, `scripts/deregister-room.ts`의 main 방 보호(`--force`), `groups/main/` 템플릿 제거. `room_settings.is_main` 컬럼은 스키마에 남아 있으나 더 이상 읽거나 쓰지 않음
- 기본 비활성이던 주기적 Codex warm-up 루프와 `CODEX_WARMUP_ENABLED`/`CODEX_WARMUP_INTERVAL_MS`. 고정 슬롯 usage primer는 그대로 동작
### Fixed
- `scripts/deregister-room.ts`의 타입 오류(`bun run typecheck:all`에서만 보이던 `unknown[]` 바인딩) 수정
- 메시지 처리 커서가 뒤로 감기지 않도록 함. 더 새로운 메시지를 이미 처리한 뒤 끝난 이전 실행이 커서를 되돌려 같은 메시지가 다시 실행되던 경로를 막음
- Codex 계정이 1개일 때 두 방이 동시에 Codex를 쓰면 두 번째 실행이 "Codex rotation pool unavailable"로 즉시 실패하고 리뷰가 조용히 생략되던 문제 수정. 잠금이 다른 실행에 잡혀 있으면 최대 15분 기다림 (30ba510)
- 이미 턴 소유권을 잃은 실행의 5초 진행 표시 타이머가 멈추지 않아, 실제로 작업 중인 방의 진행 메시지가 멈춘 것처럼 보이던 문제 수정 (69ae334)

View File

@@ -17,7 +17,8 @@ EJClaw는 Discord 위에서 동작하는 Tribunal 멀티에이전트 개발 보
- 단일 `ejclaw` 서비스가 owner / reviewer / arbiter 세 역할과 세 Discord 봇을 함께 관리합니다.
- 사용자 진입점은 owner 하나이며, reviewer와 arbiter는 내부 역할로 동작합니다.
- room-level 설정은 `room_settings`를 기준으로 하며, `assign_room`이 공개 assignment 인터페이스입니다.
- room-level 설정은 `room_settings`를 기준으로 하며, 방 등록은 `bun run setup -- --step register`(내부적으로 `assignRoom`)로 합니다.
- 모든 방은 동등합니다. 별도의 main(관리) 방은 없고, 각 방의 에이전트는 자기 방의 메시지·예약 작업·DB 증거만 다룰 수 있습니다. 여러 방에 걸친 관리 작업은 호스트 셸에서 합니다.
- reviewer는 owner의 현재 worktree를 direct mount로 읽고, role-scoped read-only 보호를 적용받습니다.
- paired runtime은 SQLite(WAL), stable owner worktree, turn/lease 추적, host verification으로 구성됩니다.
@@ -30,7 +31,7 @@ EJClaw는 Discord 위에서 동작하는 Tribunal 멀티에이전트 개발 보
- 승인 후 변경 감지와 재리뷰
- Claude 장애 시 Codex로 넘기는 global failover
- Claude OAuth 멀티 토큰 로테이션
- `assign_room` 기반 명시적 room assignment
- `room_settings` 기반 명시적 room assignment
- 자연어 중단: 작업 중인 방에 "그만", "멈춰", "중단해", "취소", "stop" 같은 짧은 메시지만 보내면 실행 중인 에이전트를 끝내고 열린 paired task를 닫음
- Bun + SQLite 기반 빠른 런타임
@@ -45,7 +46,7 @@ GitHub `main` 베이스 위에 운영 중 검증된 변경을 현재 코드 구
- 대시보드: 등록된 방 별칭을 Discord 채널명과 분리해 보존.
- 상태 대시보드 갱신 정책: 기본 갱신을 벽시계 분 경계(:00초)에 정렬하고, 새 채팅 메시지·에이전트 활성 변화 시 즉시(1.5s 디바운스) 갱신. 상태 메시지 편집이 실패하면 15초 간격 2회 재시도 후에만 새 메시지로 재게시하며(봇 재시작 직후에는 즉시 재표시), 편집 실패로 인한 반복 재생성(알림 스팸)을 제거.
- Claude 세션 토큰 write-back: 각 Claude 턴 종료 시 세션이 rotate한 OAuth 토큰을 표준 자격증명(data/claude)으로 수렴시켜, 본체 리프레시 루프와 세션 CLI가 같은 토큰 패밀리를 각자 갱신하다 발생하던 `invalid_grant`(리프레시 토큰 패밀리 폐기 → 재로그인 강제)를 방지. 세션 자격증명 스캔 경로도 실제 구조(`services/<id>/.claude`, `tasks/<id>` 하위)에 맞게 정정해 fan-out/stale 정리가 실제 세션 파일을 덮도록 함. Codex는 기존 write-back(`syncCodexSessionAuthBack`)을 사용.
- 채널 등록 해제 도구(`scripts/deregister-room.ts`): 채널 등록 해제 시 paired 데이터·세션(reviewer·arbiter 포함)·워크스페이스·디스크 폴더(git worktree 포함)를 전부 정리하고 채팅 채널과 메시지만 보존. `--dry-run` 미리보기, main 방 보호, 다른 방과 공유하는 폴더 보호, 실행 전 DB 자동 백업 포함.
- 채널 등록 해제 도구(`scripts/deregister-room.ts`): 채널 등록 해제 시 paired 데이터·세션(reviewer·arbiter 포함)·워크스페이스·디스크 폴더(git worktree 포함)를 전부 정리하고 채팅 채널과 메시지만 보존. `--dry-run` 미리보기, 다른 방과 공유하는 폴더 보호, 실행 전 DB 자동 백업 포함.
## Tribunal 시스템

View File

@@ -53,6 +53,11 @@ Discord ──► SQLite (WAL) ──► GroupQueue ──┬──► Owner (ho
paired_turn_outputs Discord display
```
## 방 격리와 작업 중단
- 모든 방은 동등합니다. main(관리) 방 개념은 없으며, 각 방의 에이전트가 IPC로 할 수 있는 일(메시지 전송·inbound 주입, 예약 작업 생성/수정/일시정지/취소, DB·호스트 증거 조회)은 자기 방(같은 group folder)으로만 제한됩니다. 방 등록/변경은 호스트 셸(`setup --step register`, `scripts/deregister-room.ts`)에서 합니다.
- 사람이 "그만"·"멈춰"·"stop" 같은 중단 의도만 담긴 짧은 메시지를 보내면 메시지 루프(`src/message-runtime-dispatch.ts` → `src/room-stop.ts`)가 가로채, 커서를 그 메시지까지 넘기고 열린 paired task를 `user_stopped`로 닫은 뒤 `GroupQueue.closeStdin`(사유 `user-stop`) + `killProcess`로 실행 중인 에이전트를 끝냅니다. 판정 규칙은 `src/stop-intent.ts`에 있습니다.
## Tribunal 역할 분리
| 역할 | 기본 선택 | 설명 |
@@ -101,6 +106,7 @@ Discord ──► SQLite (WAL) ──► GroupQueue ──┬──► Owner (ho
| --- | --- |
| `src/index.ts` | 전체 오케스트레이션 진입점 |
| `src/message-runtime.ts` | 메시지 루프, paired flow 연결 |
| `src/room-stop.ts`, `src/stop-intent.ts` | 자연어 작업 중단 |
| `src/message-turn-controller.ts` | progress / final delivery 제어 |
| `src/paired-execution-context.ts` | owner / reviewer / arbiter 실행 준비 |
| `src/paired-workspace-manager.ts` | owner / reviewer workspace 관리 |

View File

@@ -53,7 +53,7 @@ ARBITER_FALLBACK_ENABLED=true
설명:
- reviewer / arbiter provider는 전역 `REVIEWER_AGENT_TYPE` / `ARBITER_AGENT_TYPE`이 기본값이고, 방마다 `assign_room`의 `reviewer_agent_type` / `arbiter_agent_type`으로 덮어쓸 수 있습니다
- reviewer / arbiter provider는 전역 `REVIEWER_AGENT_TYPE` / `ARBITER_AGENT_TYPE`이 기본값이고, 방마다 `src/db.ts`의 `assignRoom(jid, { name, reviewerAgentType, arbiterAgentType })`를 관리 셸에서 호출해 덮어쓸 수 있습니다 (에이전트용 `assign_room` 도구는 제거됨)
- 역할별 `*_MODEL`은 해당 역할의 provider에 맞춰 주입됩니다. `codex` 역할에는 Codex 모델을, `claude-code` 역할에는 Claude 모델을 넣어야 합니다.
- 예를 들어 `ARBITER_AGENT_TYPE=claude-code`로 바꾸면 그때 `ARBITER_MODEL=claude-opus-5-5`를 사용할 수 있습니다.
- 모델 ID는 추측하지 말고 `GET https://api.anthropic.com/v1/models`로 확인하세요(`claude-opus-5-0` 같은 표기는 존재하지 않음). 새 모델은 더 높은 Claude Code CLI 버전을 요구할 수 있으므로(예: Opus 5.5는 CLI 2.1.280 이상), `.env`를 바꾸기 전에 runner SDK로 실제 호출해 보고 적용하세요. Opus/Sonnet 5.x는 `CLAUDE_THINKING=adaptive`만 지원합니다.

View File

@@ -93,7 +93,7 @@ bun scripts/deregister-room.ts --dry-run <channelId...> # preview what will be
bun scripts/deregister-room.ts <channelId...> # execute the purge
```
Accepts bare Discord channel IDs (auto-prefixed to `dc:`) or full JIDs; multiple ids allowed. Safety built in: refuses a `is_main` room without `--force`; a group folder still used by another room is NOT deleted on disk (only that chat's DB rows); `--dry-run` writes nothing.
Accepts bare Discord channel IDs (auto-prefixed to `dc:`) or full JIDs; multiple ids allowed. Safety built in: a group folder still used by another room is NOT deleted on disk (only that chat's DB rows); `--dry-run` writes nothing.
Applying to the live process is now automatic: after the purge the script calls `signalEjclawReload()`, which sends `SIGHUP` to the running service's main PID → `runtimeState.reloadRoomBindings()`, so the room drops from live bindings with NO full restart. Do NOT run a plain `systemctl restart` from inside a turn (it kills the agent mid-command and can't be confirmed). Verify by the `Room bindings reloaded` log or `getRegisteredGroup(jid)` → undefined. Always take a quick DB backup first for irreversible purges: `cp store/messages.db /home/claude/ejclaw-db-backup-$(date +%Y%m%d-%H%M%S).db`.
@@ -101,7 +101,7 @@ Applying to the live process is now automatic: after the purge the script calls
The agent runs INSIDE `ejclaw.service`, so a plain `systemctl --user restart ejclaw.service` from within a turn kills the agent mid-command: the restart is unreliable and you CANNOT confirm it in the same turn. Never claim a restart/reload happened without evidence — the repeated "재시작 됐다고 했는데 안 됨" complaints came from claiming success without verifying.
When you register (or deregister) a channel via a DB write (bun script / `setup --step register`) from a non-main room, the running process does NOT see it until its in-memory room bindings are reloaded. Preferred way — hot-reload, NO full restart, agent survives so you can verify in the same turn:
When you register (or deregister) a channel via a DB write (bun script / `setup --step register`) from a room, the running process does NOT see it until its in-memory room bindings are reloaded. Preferred way — hot-reload, NO full restart, agent survives so you can verify in the same turn:
```bash
kill -HUP "$(systemctl --user show -p MainPID --value ejclaw.service)"

View File

@@ -1,5 +0,0 @@
# Main Group Memory
This file is for mutable memory and admin context specific to the main group.
Keep platform-wide operating rules in `prompts/claude-platform.md`.

View File

@@ -203,7 +203,6 @@ class ClaudeQueryRunner {
ejclaw: buildEjclawMcpServerConfig(this.args.mcpServerPath, {
chatJid: this.args.runnerInput.chatJid,
groupFolder: this.args.runnerInput.groupFolder,
isMain: this.args.runnerInput.isMain,
agentType: process.env[EJCLAW_ENV.agentType] || 'claude-code',
roomRole: this.args.runnerInput.roomRoleContext?.role || '',
ipcDir: process.env[EJCLAW_ENV.ipcDir],

View File

@@ -45,7 +45,6 @@ const REPO_ROOT = process.env[EJCLAW_ENV.workDir] || process.cwd();
// Context from environment variables (set by the agent runner)
const chatJid = process.env[EJCLAW_ENV.chatJid]!;
const groupFolder = process.env[EJCLAW_ENV.groupFolder]!;
const isMain = process.env[EJCLAW_ENV.isMain] === '1';
const agentType = process.env[EJCLAW_ENV.agentType] || 'claude-code';
const roomRole = process.env[EJCLAW_ENV.roomRole];
const runtimeTaskId = process.env[EJCLAW_ENV.runtimeTaskId];
@@ -152,12 +151,6 @@ SCHEDULE VALUE FORMAT (all times are LOCAL timezone):
.describe(
'group=runs with chat history and memory, isolated=fresh session (include context in prompt). Default: group.',
),
target_group_jid: z
.string()
.optional()
.describe(
'(Main group only) JID of the group to schedule the task for. Defaults to the current group.',
),
},
async (args) => {
// Validate schedule_value before writing IPC
@@ -217,9 +210,8 @@ SCHEDULE VALUE FORMAT (all times are LOCAL timezone):
}
}
// Non-main groups can only schedule for themselves
const targetJid =
isMain && args.target_group_jid ? args.target_group_jid : chatJid;
// A room can only schedule tasks for itself.
const targetJid = chatJid;
const taskId = `task-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
@@ -310,12 +302,6 @@ server.tool(
.describe(
'group=runs with chat history and memory, isolated=fresh session (include all context in check_instructions). Default: isolated.',
),
target_group_jid: z
.string()
.optional()
.describe(
'(Main group only) JID of the group to schedule the watcher for. Defaults to the current group.',
),
},
async (args) => {
if (roomRole && roomRole !== 'owner') {
@@ -398,8 +384,7 @@ server.tool(
};
}
const targetJid =
isMain && args.target_group_jid ? args.target_group_jid : chatJid;
const targetJid = chatJid;
const taskId = `task-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
const prompt = buildCiWatchPrompt({
target,
@@ -511,7 +496,7 @@ registerRepoEvidenceTool(server, REPO_ROOT);
server.tool(
'list_tasks',
"List all scheduled tasks. From main: shows all tasks. From other groups: shows only that group's tasks.",
'List the scheduled tasks of this room.',
{},
async () => {
const tasksFile = path.join(IPC_DIR, 'current_tasks.json');
@@ -527,11 +512,9 @@ server.tool(
const allTasks = JSON.parse(fs.readFileSync(tasksFile, 'utf-8'));
const tasks = isMain
? allTasks
: allTasks.filter(
(t: { groupFolder: string }) => t.groupFolder === groupFolder,
);
const tasks = allTasks.filter(
(t: { groupFolder: string }) => t.groupFolder === groupFolder,
);
if (tasks.length === 0) {
return {
@@ -582,7 +565,6 @@ server.tool(
type: 'pause_task',
taskId: args.task_id,
groupFolder,
isMain,
timestamp: new Date().toISOString(),
};
@@ -608,7 +590,6 @@ server.tool(
type: 'resume_task',
taskId: args.task_id,
groupFolder,
isMain,
timestamp: new Date().toISOString(),
};
@@ -652,7 +633,6 @@ server.tool(
type: 'cancel_task',
taskId: resolvedId,
groupFolder,
isMain,
timestamp: new Date().toISOString(),
};
@@ -728,7 +708,6 @@ if (allowGenericScheduling) {
type: 'update_task',
taskId: args.task_id,
groupFolder,
isMain: String(isMain),
timestamp: new Date().toISOString(),
};
if (args.prompt !== undefined) data.prompt = args.prompt;
@@ -751,113 +730,6 @@ if (allowGenericScheduling) {
);
}
server.tool(
'assign_room',
`Assign or update a room using room-level settings. Main group only.
If folder is omitted, the host generates one automatically.`,
{
jid: z
.string()
.describe(
'The chat JID (e.g., "120363336345536173@g.us", "tg:-1001234567890", "dc:1234567890123456")',
),
name: z.string().describe('Display name for the room'),
room_mode: z
.enum(['single', 'tribunal'])
.default('tribunal')
.describe(
'single=owner only, tribunal=owner/reviewer roles enabled (default)',
),
owner_agent_type: z
.enum(['claude-code', 'codex'])
.optional()
.describe('Preferred owner agent type for the room'),
reviewer_agent_type: z
.enum(['claude-code', 'codex'])
.optional()
.describe('Optional reviewer agent type override for tribunal rooms'),
arbiter_agent_type: z
.enum(['claude-code', 'codex'])
.optional()
.describe('Optional arbiter agent type override for tribunal rooms'),
folder: z
.string()
.optional()
.describe(
'Optional folder override. If omitted, the host generates one automatically.',
),
trigger: z
.string()
.optional()
.describe('Optional canonical trigger label to store for the room'),
requires_trigger: z
.boolean()
.optional()
.describe('Whether direct trigger mention is required'),
is_main: z
.boolean()
.optional()
.describe('Whether this room is the privileged main control room'),
work_dir: z
.string()
.optional()
.describe('Optional working directory override'),
},
async (args: {
jid: string;
name: string;
room_mode?: 'single' | 'tribunal';
owner_agent_type?: 'claude-code' | 'codex';
reviewer_agent_type?: 'claude-code' | 'codex';
arbiter_agent_type?: 'claude-code' | 'codex';
folder?: string;
trigger?: string;
requires_trigger?: boolean;
is_main?: boolean;
work_dir?: string;
}) => {
if (!isMain) {
return {
content: [
{
type: 'text' as const,
text: 'Only the main group can assign rooms.',
},
],
isError: true,
};
}
const data = {
type: 'assign_room',
jid: args.jid,
name: args.name,
room_mode: args.room_mode || 'tribunal',
owner_agent_type: args.owner_agent_type,
reviewer_agent_type: args.reviewer_agent_type,
arbiter_agent_type: args.arbiter_agent_type,
folder: args.folder,
trigger: args.trigger,
requiresTrigger: args.requires_trigger,
isMain: args.is_main,
workDir: args.work_dir,
timestamp: new Date().toISOString(),
};
writeIpcFile(TASKS_DIR, data);
return {
content: [
{
type: 'text' as const,
text: `Room "${args.name}" assignment requested.`,
},
],
};
},
);
// Start the stdio transport
const transport = new StdioServerTransport();
await server.connect(transport);

View File

@@ -4,7 +4,6 @@ import { EJCLAW_ENV } from 'ejclaw-runners-shared';
export interface EjclawMcpServerConfigInput {
chatJid: string;
groupFolder: string;
isMain: boolean;
agentType: string;
roomRole: string;
ipcDir?: string;
@@ -22,7 +21,6 @@ export function buildEjclawMcpServerConfig(
env: {
[EJCLAW_ENV.chatJid]: input.chatJid,
[EJCLAW_ENV.groupFolder]: input.groupFolder,
[EJCLAW_ENV.isMain]: input.isMain ? '1' : '0',
[EJCLAW_ENV.agentType]: input.agentType,
[EJCLAW_ENV.roomRole]: input.roomRole,
...(input.ipcDir && {

View File

@@ -5,7 +5,6 @@ export interface RunnerInput {
sessionId?: string;
groupFolder: string;
chatJid: string;
isMain: boolean;
isScheduledTask?: boolean;
assistantName?: string;
secrets?: Record<string, string>;

View File

@@ -9,7 +9,6 @@ describe('ejclaw MCP config', () => {
buildEjclawMcpServerConfig('/runner/dist/ipc-mcp-stdio.js', {
chatJid: 'dc:room',
groupFolder: 'ejclaw',
isMain: true,
agentType: 'claude-code',
roomRole: 'reviewer',
ipcDir: '/tmp/ipc/task',
@@ -22,7 +21,6 @@ describe('ejclaw MCP config', () => {
env: {
[EJCLAW_ENV.chatJid]: 'dc:room',
[EJCLAW_ENV.groupFolder]: 'ejclaw',
[EJCLAW_ENV.isMain]: '1',
[EJCLAW_ENV.agentType]: 'claude-code',
[EJCLAW_ENV.roomRole]: 'reviewer',
[EJCLAW_ENV.ipcDir]: '/tmp/ipc/task',

View File

@@ -46,7 +46,6 @@ interface RunnerInput {
sessionId?: string;
groupFolder: string;
chatJid: string;
isMain: boolean;
isScheduledTask?: boolean;
assistantName?: string;
agentType?: string;

View File

@@ -6,7 +6,6 @@ export const EJCLAW_ENV = {
groupFolder: 'EJCLAW_GROUP_FOLDER',
hostIpcDir: 'EJCLAW_HOST_IPC_DIR',
ipcDir: 'EJCLAW_IPC_DIR',
isMain: 'EJCLAW_IS_MAIN',
roomRole: 'EJCLAW_ROOM_ROLE',
runId: 'EJCLAW_RUN_ID',
runtimeTaskId: 'EJCLAW_RUNTIME_TASK_ID',

View File

@@ -4,7 +4,7 @@
* channel record (chats) and its message history (messages).
*
* Usage:
* bun scripts/deregister-room.ts [--dry-run] [--force] [--no-backup] <channelId|jid> [more...]
* bun scripts/deregister-room.ts [--dry-run] [--no-backup] <channelId|jid> [more...]
*
* What it removes for each target chat:
* - room registration + role/skill overrides + channel owner lease
@@ -20,7 +20,6 @@
* startup), e.g. `systemctl --user restart ejclaw.service`.
*
* Safety:
* - refuses to deregister a main room unless --force
* - a group folder shared by another remaining room is NOT deleted on disk
* (only that chat's DB rows are removed)
* - --dry-run reports what would change without writing anything
@@ -38,13 +37,12 @@ import { signalEjclawReload } from '../src/runtime-reload-signal.js';
const args = process.argv.slice(2);
const dryRun = args.includes('--dry-run');
const force = args.includes('--force');
const noBackup = args.includes('--no-backup');
const ids = args.filter((a) => !a.startsWith('--'));
if (ids.length === 0) {
console.error(
'Usage: bun scripts/deregister-room.ts [--dry-run] [--force] [--no-backup] <channelId|jid> [more...]',
'Usage: bun scripts/deregister-room.ts [--dry-run] [--no-backup] <channelId|jid> [more...]',
);
process.exit(2);
}
@@ -62,7 +60,6 @@ const db = new Database(path.join(STORE_DIR, 'messages.db'));
interface Target {
jid: string;
folders: string[];
isMain: boolean;
name: string | null;
registered: boolean;
}
@@ -92,30 +89,17 @@ function backtraceFolders(jid: string): string[] {
const targets: Target[] = jids.map((jid) => {
const r = db
.query('SELECT folder, is_main, name FROM room_settings WHERE chat_jid=?')
.get(jid) as
| { folder: string | null; is_main: number | null; name: string | null }
| undefined;
.query('SELECT folder, name FROM room_settings WHERE chat_jid=?')
.get(jid) as { folder: string | null; name: string | null } | undefined;
const folders = r?.folder ? [r.folder] : backtraceFolders(jid);
return {
jid,
folders,
isMain: r?.is_main === 1,
name: r?.name ?? null,
registered: Boolean(r),
};
});
const mainTargets = targets.filter((t) => t.isMain);
if (mainTargets.length && !force) {
console.error(
'Refusing to deregister main room(s):',
mainTargets.map((t) => t.jid).join(', '),
'\nPass --force only if you really intend to unregister the main control room.',
);
process.exit(3);
}
const targetJidSet = new Set(jids);
function folderShared(folder: string): boolean {
const rows = db
@@ -136,7 +120,7 @@ for (const t of targets) {
console.log('=== targets ===');
for (const t of targets) {
console.log(
` ${t.jid} | name=${t.name ?? '(unregistered)'} | folder=${t.folders.length ? t.folders.join(',') : '-'} | registered=${t.registered}${t.isMain ? ' | MAIN' : ''}`,
` ${t.jid} | name=${t.name ?? '(unregistered)'} | folder=${t.folders.length ? t.folders.join(',') : '-'} | registered=${t.registered}`,
);
}
if (sharedFolders.size) {
@@ -165,7 +149,7 @@ const scheduledTaskIds = (
const qS = scheduledTaskIds.map(() => '?').join(',');
const safeFolderList = [...safeFolders];
const count = (t: string, where: string, a: unknown[]): number =>
const count = (t: string, where: string, a: string[]): number =>
(
db.query(`SELECT COUNT(*) n FROM ${t} WHERE ${where}`).get(...a) as {
n: number;

View File

@@ -219,7 +219,6 @@ function storedRoomSettingsMatchesLegacySnapshot(
stored.name === snapshot.name &&
stored.folder === snapshot.folder &&
(stored.requiresTrigger ?? true) === snapshot.requiresTrigger &&
(stored.isMain ?? false) === snapshot.isMain &&
(stored.workDir ?? null) === (snapshot.workDir ?? null)
);
}
@@ -381,7 +380,6 @@ function collectLegacyRoomRegistrationSnapshot(
? preferredOwnerRow.trigger_pattern
: ownerRow.trigger_pattern,
requiresTrigger: (first.requires_trigger ?? 1) === 1,
isMain: (first.is_main ?? 0) === 1,
ownerAgentType,
workDir: first.work_dir ?? null,
};

View File

@@ -84,7 +84,6 @@ describe('register step', () => {
expect(assignRoomMock).toHaveBeenCalledWith('dc:test-room', {
name: 'Test Room',
folder: 'test-room',
isMain: false,
});
expect(mkdirSpy).toHaveBeenCalledWith('/tmp/ejclaw-groups/test-room/logs', {
recursive: true,
@@ -149,13 +148,11 @@ describe('register step', () => {
'Main Room',
'--folder',
'main-room',
'--is-main',
]);
expect(assignRoomMock).toHaveBeenCalledWith('dc:main-room', {
name: 'Main Room',
folder: 'main-room',
isMain: true,
});
expect(mkdirSpy).toHaveBeenCalledTimes(1);
expect(readSpy).not.toHaveBeenCalled();

View File

@@ -19,7 +19,6 @@ interface RegisterArgs {
name: string;
folder: string;
channel: string;
isMain: boolean;
assistantNameProvided: boolean;
}
@@ -29,7 +28,6 @@ function parseArgs(args: string[]): RegisterArgs {
name: '',
folder: '',
channel: 'discord',
isMain: false,
assistantNameProvided: false,
};
@@ -47,9 +45,6 @@ function parseArgs(args: string[]): RegisterArgs {
case '--channel':
result.channel = (args[++i] || '').toLowerCase();
break;
case '--is-main':
result.isMain = true;
break;
case '--assistant-name':
result.assistantNameProvided = true;
i += 1;
@@ -107,7 +102,6 @@ export async function run(args: string[]): Promise<void> {
assignRoom(parsed.jid, {
name: parsed.name,
folder: parsed.folder,
isMain: parsed.isMain,
});
logger.info('Assigned room through canonical room service');
@@ -121,7 +115,6 @@ export async function run(args: string[]): Promise<void> {
assignRoom(parsed.jid, {
name: parsed.name,
folder: parsed.folder,
isMain: parsed.isMain,
workDir: canonicalWorkDir,
});
logger.info(

View File

@@ -214,7 +214,7 @@ describe('prepareGroupEnvironment codex auth handling', () => {
CODEX_MODEL: 'gpt-5.4',
});
prepareGroupEnvironment(group, false, 'dc:test');
prepareGroupEnvironment(group, 'dc:test');
const authPath = path.join(
tempRoot,
@@ -250,7 +250,7 @@ describe('prepareGroupEnvironment codex auth handling', () => {
mockGetActiveCodexAuthPath.mockReturnValue(rotatedAuthPath);
mockReadEnvFile.mockReturnValue({});
prepareGroupEnvironment(group, false, 'dc:test');
prepareGroupEnvironment(group, 'dc:test');
const authPath = path.join(
tempRoot,
@@ -280,7 +280,7 @@ describe('prepareGroupEnvironment codex auth handling', () => {
mockGetActiveCodexAuthPath.mockReturnValue(rotatedAuthPath);
mockReadEnvFile.mockReturnValue({});
expect(() => prepareGroupEnvironment(group, false, 'dc:test')).toThrow(
expect(() => prepareGroupEnvironment(group, 'dc:test')).toThrow(
/Codex rotation pool unavailable/,
);
@@ -379,7 +379,6 @@ describe('prepareGroupEnvironment prompt stacks', () => {
);
prepareGroupEnvironment(
{ ...group, workDir: path.join(tempRoot, 'workdir') },
false,
'dc:test',
{
memoryBriefing: 'memory briefing',
@@ -421,14 +420,9 @@ describe('prepareGroupEnvironment prompt stacks', () => {
'owner common paired prompt\n',
);
prepareGroupEnvironment(
{ ...group, agentType: 'claude-code' },
false,
'dc:test',
{
memoryBriefing: 'memory briefing',
},
);
prepareGroupEnvironment({ ...group, agentType: 'claude-code' }, 'dc:test', {
memoryBriefing: 'memory briefing',
});
const claudePath = path.join(
tempRoot,
@@ -458,7 +452,6 @@ describe('prepareGroupEnvironment prompt stacks', () => {
const prepared = prepareGroupEnvironment(
{ ...group, agentType: 'claude-code' },
false,
'dc:test',
);
@@ -482,7 +475,7 @@ describe('prepareGroupEnvironment prompt stacks', () => {
const promptsDir = path.join(tempRoot, 'prompts');
fs.mkdirSync(promptsDir, { recursive: true });
prepareGroupEnvironment(group, false, 'dc:test');
prepareGroupEnvironment(group, 'dc:test');
const agentsPath = path.join(
tempRoot,
@@ -516,7 +509,7 @@ describe('prepareGroupEnvironment prompt stacks', () => {
'owner common paired prompt\n',
);
prepareGroupEnvironment(group, false, 'dc:test', { roomRole });
prepareGroupEnvironment(group, 'dc:test', { roomRole });
const agents = fs.readFileSync(
path.join(
@@ -598,7 +591,7 @@ describe('prepareGroupEnvironment Codex MCP room role env', () => {
mockReadEnvFile.mockReturnValue({});
writeMcpServer();
prepareGroupEnvironment(group, false, 'dc:test', {
prepareGroupEnvironment(group, 'dc:test', {
roomRole: 'owner',
});
@@ -609,7 +602,7 @@ describe('prepareGroupEnvironment Codex MCP room role env', () => {
mockReadEnvFile.mockReturnValue({});
writeMcpServer();
prepareGroupEnvironment(group, true, 'dc:test');
prepareGroupEnvironment(group, 'dc:test');
expect(readCodexConfigToml()).not.toContain(EJCLAW_ENV.roomRole);
});
@@ -661,7 +654,6 @@ describe('prepareGroupEnvironment room skill overrides', () => {
prepareGroupEnvironment(
{ ...group, agentType: 'claude-code', workDir },
false,
'dc:test',
{
skillOverrides: [
@@ -706,7 +698,7 @@ describe('prepareGroupEnvironment room skill overrides', () => {
writeSkill(runnerSkills, 'runner-keep');
writeSkill(runnerSkills, 'runner-off');
const prepared = prepareGroupEnvironment(group, false, 'dc:test', {
const prepared = prepareGroupEnvironment(group, 'dc:test', {
skillOverrides: [
{
chatJid: 'dc:test',
@@ -800,7 +792,7 @@ describe('prepareGroupEnvironment Codex goals handling', () => {
it('keeps Codex goals disabled by default and enables them only via opt-in config', () => {
mockReadEnvFile.mockReturnValue({});
const defaultPrepared = prepareGroupEnvironment(group, false, 'dc:test');
const defaultPrepared = prepareGroupEnvironment(group, 'dc:test');
expect(defaultPrepared.env.CODEX_GOALS).toBeUndefined();
const enabledPrepared = prepareGroupEnvironment(
@@ -810,7 +802,6 @@ describe('prepareGroupEnvironment Codex goals handling', () => {
codexGoals: true,
},
},
false,
'dc:test',
);
expect(enabledPrepared.env.CODEX_GOALS).toBe('true');
@@ -821,7 +812,7 @@ describe('prepareGroupEnvironment Codex goals handling', () => {
CODEX_GOALS: 'true',
});
const prepared = prepareGroupEnvironment(group, false, 'dc:test');
const prepared = prepareGroupEnvironment(group, 'dc:test');
expect(prepared.env.CODEX_GOALS).toBe('true');
});
@@ -837,7 +828,7 @@ describe('prepareGroupEnvironment Codex goals handling', () => {
);
try {
const prepared = prepareGroupEnvironment(group, false, 'dc:test');
const prepared = prepareGroupEnvironment(group, 'dc:test');
expect(prepared.env.CODEX_GOALS).toBe('true');
} finally {
homedirSpy.mockRestore();
@@ -895,7 +886,6 @@ describe('prepareReadonlySessionEnvironment codex compatibility', () => {
const prepared = prepareReadonlySessionEnvironment({
sessionDir,
chatJid: 'dc:test',
isMain: false,
groupFolder: 'codex-test-group',
agentType: 'claude-code',
memoryBriefing: 'memory briefing',
@@ -949,7 +939,6 @@ args = ["other.js"]
prepareReadonlySessionEnvironment({
sessionDir,
chatJid: 'dc:test',
isMain: false,
groupFolder: 'codex-test-group',
agentType: 'codex',
memoryBriefing: 'memory briefing',
@@ -1013,7 +1002,6 @@ describe('writeReadonlyRoleClaudeMd', () => {
writeReadonlyRoleClaudeMd({
sessionDir,
chatJid: 'dc:test',
isMain: false,
role,
memoryBriefing: 'memory briefing',
});

View File

@@ -235,7 +235,6 @@ function upsertEjclawMcpServerSection(args: {
hostIpcDir: string;
chatJid: string;
groupFolder: string;
isMain: boolean;
agentType: AgentType;
roomRole?: PairedRoomRole;
workDir?: string;
@@ -286,7 +285,6 @@ ${tomlEnvLine(EJCLAW_ENV.ipcDir, args.ipcDir)}
${tomlEnvLine(EJCLAW_ENV.hostIpcDir, args.hostIpcDir)}
${tomlEnvLine(EJCLAW_ENV.chatJid, args.chatJid)}
${tomlEnvLine(EJCLAW_ENV.groupFolder, args.groupFolder)}
${tomlEnvLine(EJCLAW_ENV.isMain, args.isMain ? '1' : '0')}
${tomlEnvLine(EJCLAW_ENV.agentType, args.agentType)}
${args.roomRole ? `${tomlEnvLine(EJCLAW_ENV.roomRole, args.roomRole)}\n` : ''}
${args.workDir ? `${tomlEnvLine(EJCLAW_ENV.workDir, args.workDir)}\n` : ''}
@@ -297,7 +295,6 @@ ${args.workDir ? `${tomlEnvLine(EJCLAW_ENV.workDir, args.workDir)}\n` : ''}
function buildBaseRunnerEnv(args: {
group: RegisteredGroup;
chatJid: string;
isMain: boolean;
groupDir: string;
groupIpcDir: string;
hostIpcDir: string;
@@ -336,7 +333,6 @@ function buildBaseRunnerEnv(args: {
...(args.group.workDir ? { [EJCLAW_ENV.workDir]: args.group.workDir } : {}),
[EJCLAW_ENV.chatJid]: args.chatJid,
[EJCLAW_ENV.groupFolder]: args.group.folder,
[EJCLAW_ENV.isMain]: args.isMain ? '1' : '0',
[EJCLAW_ENV.agentType]: args.agentType,
CLAUDE_CONFIG_DIR: args.groupSessionsDir,
...(args.runtimeTaskId
@@ -426,7 +422,6 @@ function readPairedRolePrompt(
function buildReadonlyRoleClaudeMd(args: {
projectRoot: string;
chatJid: string;
isMain: boolean;
role: 'reviewer' | 'arbiter';
memoryBriefing?: string;
}): {
@@ -443,10 +438,9 @@ function buildReadonlyRoleClaudeMd(args: {
? readPairedRolePrompt(args.projectRoot, args.role)
: undefined;
const globalClaudeMdPath = path.join(GROUPS_DIR, 'global', 'CLAUDE.md');
const globalClaudeMemory =
!args.isMain && fs.existsSync(globalClaudeMdPath)
? fs.readFileSync(globalClaudeMdPath, 'utf-8').trim()
: undefined;
const globalClaudeMemory = fs.existsSync(globalClaudeMdPath)
? fs.readFileSync(globalClaudeMdPath, 'utf-8').trim()
: undefined;
const content = [
claudePlatformPrompt,
claudePairedRoomPrompt,
@@ -475,14 +469,12 @@ function buildReadonlyRoleClaudeMd(args: {
export function writeReadonlyRoleClaudeMd(args: {
sessionDir: string;
chatJid: string;
isMain: boolean;
role: 'reviewer' | 'arbiter';
memoryBriefing?: string;
}): void {
const { content } = buildReadonlyRoleClaudeMd({
projectRoot: process.cwd(),
chatJid: args.chatJid,
isMain: args.isMain,
role: args.role,
memoryBriefing: args.memoryBriefing,
});
@@ -503,7 +495,6 @@ function prepareCodexSessionEnvironment(args: {
groupDir: string;
sessionRootDir: string;
chatJid: string;
isMain: boolean;
roomRole?: PairedRoomRole;
isPairedRoom: boolean;
useFailoverPromptPack: boolean;
@@ -642,7 +633,6 @@ function prepareCodexSessionEnvironment(args: {
hostIpcDir: args.env[EJCLAW_ENV.hostIpcDir],
chatJid: args.chatJid,
groupFolder: args.group.folder,
isMain: args.isMain,
agentType: 'codex',
roomRole: args.roomRole,
workDir:
@@ -672,7 +662,6 @@ export interface PreparedReadonlySessionEnvironment {
export function prepareGroupEnvironment(
group: RegisteredGroup,
isMain: boolean,
chatJid: string,
options?: {
memoryBriefing?: string;
@@ -753,10 +742,9 @@ export function prepareGroupEnvironment(
const ownerCommonPairedRoomPrompt = isPairedRoom
? readOptionalPromptFile(projectRoot, 'owner-common-paired-room.md')
: undefined;
const globalClaudeMemory =
!isMain && fs.existsSync(globalClaudeMdPath)
? fs.readFileSync(globalClaudeMdPath, 'utf-8').trim()
: undefined;
const globalClaudeMemory = fs.existsSync(globalClaudeMdPath)
? fs.readFileSync(globalClaudeMdPath, 'utf-8').trim()
: undefined;
// Owner CLAUDE.md: platform rules + owner paired room rules.
// Reviewer paired room rules are NOT included — those belong to the
// Read-only reviewer/arbiter session only (via prepareReadonlySessionEnvironment).
@@ -799,7 +787,6 @@ export function prepareGroupEnvironment(
const env = buildBaseRunnerEnv({
group,
chatJid,
isMain,
groupDir,
groupIpcDir,
hostIpcDir,
@@ -820,7 +807,6 @@ export function prepareGroupEnvironment(
groupDir,
sessionRootDir,
chatJid,
isMain,
roomRole: options?.roomRole,
isPairedRoom,
useFailoverPromptPack: useCodexReviewFailoverPromptPack,
@@ -846,7 +832,6 @@ export function prepareGroupEnvironment(
export function prepareReadonlySessionEnvironment(args: {
sessionDir: string;
chatJid: string;
isMain: boolean;
groupFolder: string;
agentType: AgentType;
memoryBriefing?: string;
@@ -859,7 +844,6 @@ export function prepareReadonlySessionEnvironment(args: {
const {
sessionDir,
chatJid,
isMain,
groupFolder,
agentType,
memoryBriefing,
@@ -921,7 +905,6 @@ export function prepareReadonlySessionEnvironment(args: {
} = buildReadonlyRoleClaudeMd({
projectRoot,
chatJid,
isMain,
role,
memoryBriefing,
});
@@ -952,7 +935,6 @@ export function prepareReadonlySessionEnvironment(args: {
hostIpcDir,
chatJid,
groupFolder,
isMain,
agentType,
roomRole: role,
workDir,

View File

@@ -51,7 +51,6 @@ const input: AgentInput = {
groupFolder: 'agent-runner-test',
chatJid: 'dc:test',
runId: 'run-1',
isMain: false,
};
describe('runSpawnedAgentProcess', () => {

View File

@@ -390,7 +390,6 @@ export function runSpawnedAgentProcess(
`ChatJid: ${input.chatJid}`,
`GroupFolder: ${input.groupFolder}`,
`RunId: ${input.runId || 'n/a'}`,
`IsMain: ${input.isMain}`,
`AgentType: ${group.agentType || 'claude-code'}`,
`Duration: ${duration}ms`,
`Exit Code: ${code}`,

View File

@@ -9,7 +9,6 @@ import { writeJsonFile } from './utils.js';
export function writeTasksSnapshot(
groupFolder: string,
isMain: boolean,
tasks: Array<{
id: string;
groupFolder: string;
@@ -25,33 +24,7 @@ export function writeTasksSnapshot(
? resolveTaskRuntimeIpcPath(groupFolder, runtimeTaskId)
: resolveGroupIpcPath(groupFolder);
fs.mkdirSync(groupIpcDir, { recursive: true });
const filteredTasks = isMain
? tasks
: tasks.filter((t) => t.groupFolder === groupFolder);
const filteredTasks = tasks.filter((t) => t.groupFolder === groupFolder);
const tasksFile = path.join(groupIpcDir, 'current_tasks.json');
writeJsonFile(tasksFile, filteredTasks, true);
}
export interface AvailableGroup {
jid: string;
name: string;
lastActivity: string;
isRegistered: boolean;
}
export function writeGroupsSnapshot(
groupFolder: string,
isMain: boolean,
groups: AvailableGroup[],
_registeredJids?: Set<string>,
): void {
const groupIpcDir = resolveGroupIpcPath(groupFolder);
fs.mkdirSync(groupIpcDir, { recursive: true });
const visibleGroups = isMain ? groups : [];
const groupsFile = path.join(groupIpcDir, 'available_groups.json');
writeJsonFile(
groupsFile,
{ groups: visibleGroups, lastSync: new Date().toISOString() },
true,
);
}

View File

@@ -126,7 +126,6 @@ const testInput = {
prompt: 'Hello',
groupFolder: 'test-group',
chatJid: 'test@g.us',
isMain: false,
};
function emitOutputMarker(
@@ -861,7 +860,6 @@ describe('agent-runner room skill overrides', () => {
expect(getStoredRoomSkillOverrides).toHaveBeenCalledWith(testInput.chatJid);
expect(prepareGroupEnvironmentSpy).toHaveBeenCalledWith(
testGroup,
testInput.isMain,
testInput.chatJid,
expect.objectContaining({
skillOverrides: [skillOverride],

View File

@@ -25,11 +25,7 @@ import {
import { syncClaudeSessionAuthBack } from './token-refresh.js';
import { runSpawnedAgentProcess } from './agent-runner-process.js';
import { getStoredRoomSkillOverrides } from './db.js';
export {
type AvailableGroup,
writeGroupsSnapshot,
writeTasksSnapshot,
} from './agent-runner-snapshot.js';
export { writeTasksSnapshot } from './agent-runner-snapshot.js';
import { logger } from './logger.js';
import { RegisteredGroup, RoomRoleContext } from './types.js';
import type { StoredRoomSkillOverride } from './db/rooms.js';
@@ -41,7 +37,6 @@ export interface AgentInput {
groupFolder: string;
chatJid: string;
runId?: string;
isMain: boolean;
isScheduledTask?: boolean;
runtimeTaskId?: string;
useTaskScopedSession?: boolean;
@@ -175,7 +170,7 @@ export async function runAgentProcess(
// rate-limited this returns at once and the prepare step below fails fast.
await waitForCodexAuthLease();
}
const prepared = prepareGroupEnvironment(group, input.isMain, input.chatJid, {
const prepared = prepareGroupEnvironment(group, input.chatJid, {
memoryBriefing: input.memoryBriefing,
runtimeTaskId: input.runtimeTaskId,
useTaskScopedSession: input.useTaskScopedSession,
@@ -204,7 +199,6 @@ export async function runAgentProcess(
readonlySession = prepareReadonlySessionEnvironment({
sessionDir: envOverrides.CLAUDE_CONFIG_DIR,
chatJid: input.chatJid,
isMain: input.isMain,
groupFolder: group.folder,
agentType: group.agentType || 'claude-code',
memoryBriefing: input.memoryBriefing,
@@ -239,7 +233,6 @@ export async function runAgentProcess(
writeReadonlyRoleClaudeMd({
sessionDir: envOverrides.CLAUDE_CONFIG_DIR,
chatJid: input.chatJid,
isMain: input.isMain,
role: input.roomRoleContext.role,
memoryBriefing: input.memoryBriefing,
});
@@ -287,7 +280,6 @@ export async function runAgentProcess(
runId: input.runId,
processName,
agentType: group.agentType || 'claude-code',
isMain: input.isMain,
},
'Spawning agent process',
);

View File

@@ -1,19 +0,0 @@
import type { AvailableGroup } from './agent-runner.js';
import { getAllChats } from './db.js';
import type { RegisteredGroup } from './types.js';
export function listAvailableGroups(
roomBindings: Record<string, RegisteredGroup>,
): AvailableGroup[] {
const chats = getAllChats();
const registeredJids = new Set(Object.keys(roomBindings));
return chats
.filter((chat) => chat.jid !== '__group_sync__' && chat.is_group)
.map((chat) => ({
jid: chat.jid,
name: chat.name,
lastActivity: chat.last_message_time,
isRegistered: registeredJids.has(chat.jid),
}));
}

View File

@@ -135,7 +135,7 @@ describe('DB evidence presets', () => {
runDbEvidenceRequest(
requireDatabase(),
{ action: 'db_paired_task_status', taskId: 'task-1' },
{ sourceGroup: 'room-folder', isMain: false },
{ sourceGroup: 'room-folder' },
),
) as { task: { id: string; group_folder: string } };
expect(status.task.id).toBe('task-1');
@@ -144,7 +144,7 @@ describe('DB evidence presets', () => {
const flowText = runDbEvidenceRequest(
requireDatabase(),
{ action: 'db_paired_task_flow', taskId: 'task-1' },
{ sourceGroup: 'room-folder', isMain: false },
{ sourceGroup: 'room-folder' },
);
expect(flowText).toContain('"output_chars"');
expect(flowText).toContain('"last_error_chars"');
@@ -153,25 +153,16 @@ describe('DB evidence presets', () => {
expect(flowText).not.toContain('sk-12345678901234567890');
});
it('scopes non-main DB evidence to the source group', () => {
it('scopes DB evidence to the source group', () => {
seedPairedTask();
const blocked = JSON.parse(
runDbEvidenceRequest(
requireDatabase(),
{ action: 'db_paired_task_status', taskId: 'task-1' },
{ sourceGroup: 'other-folder', isMain: false },
{ sourceGroup: 'other-folder' },
),
) as { task: unknown };
expect(blocked.task).toBeNull();
const main = JSON.parse(
runDbEvidenceRequest(
requireDatabase(),
{ action: 'db_paired_task_status', taskId: 'task-1' },
{ sourceGroup: 'other-folder', isMain: true },
),
) as { task: { id: string } };
expect(main.task.id).toBe('task-1');
});
});

View File

@@ -21,7 +21,6 @@ export interface DbEvidenceRequest {
export interface DbEvidenceScope {
sourceGroup: string;
isMain: boolean;
}
const DEFAULT_RECENT_MINUTES = 60;
@@ -62,9 +61,7 @@ function groupScopeClause(scope: DbEvidenceScope): {
clause: string;
params: SqlBinding[];
} {
return scope.isMain
? { clause: '', params: [] }
: { clause: ' AND group_folder = ?', params: [scope.sourceGroup] };
return { clause: ' AND group_folder = ?', params: [scope.sourceGroup] };
}
function getScopedTask(
@@ -288,12 +285,12 @@ function runRecentPairedFailures(
attempts.state = 'failed'
OR attempts.last_error IS NOT NULL
)
${scope.isMain ? '' : 'AND tasks.group_folder = ?'}
AND tasks.group_folder = ?
ORDER BY attempts.updated_at DESC
LIMIT ?
`,
)
.all(cutoff, ...(scope.isMain ? [] : [scope.sourceGroup]), limit);
.all(cutoff, scope.sourceGroup, limit);
const deliveryRetries = database
.prepare(
@@ -309,12 +306,12 @@ function runRecentPairedFailures(
FROM work_items
WHERE updated_at >= ?
AND status = 'delivery_retry'
${scope.isMain ? '' : 'AND group_folder = ?'}
AND group_folder = ?
ORDER BY updated_at DESC
LIMIT ?
`,
)
.all(cutoff, ...(scope.isMain ? [] : [scope.sourceGroup]), limit);
.all(cutoff, scope.sourceGroup, limit);
return stringifyEvidence({
action: request.action,
@@ -436,10 +433,8 @@ function runScheduledTaskRuns(
clauses.push('logs.task_id = ?');
params.push(taskId);
}
if (!scope.isMain) {
clauses.push('tasks.group_folder = ?');
params.push(scope.sourceGroup);
}
clauses.push('tasks.group_folder = ?');
params.push(scope.sourceGroup);
params.push(limit);
const rows = database

View File

@@ -72,7 +72,7 @@ describe('scheduled task DB evidence presets', () => {
const tasksText = runDbEvidenceRequest(
requireDatabase(),
{ action: 'db_recent_scheduled_tasks', minutes: 1440 },
{ sourceGroup: 'room-folder', isMain: false },
{ sourceGroup: 'room-folder' },
);
expect(tasksText).toContain('"ci_repo": "phj1081/EJClaw"');
@@ -94,7 +94,7 @@ describe('scheduled task DB evidence presets', () => {
taskId: 'watch-1',
minutes: 1440,
},
{ sourceGroup: 'room-folder', isMain: false },
{ sourceGroup: 'room-folder' },
);
expect(runsText).toContain('"duration_ms": 42');
@@ -104,14 +104,14 @@ describe('scheduled task DB evidence presets', () => {
expect(runsText).not.toContain('raw scheduler error');
});
it('scopes scheduled task evidence for non-main rooms', () => {
it('scopes scheduled task evidence to the source room', () => {
seedScheduledTaskEvidence();
const scopedOut = JSON.parse(
runDbEvidenceRequest(
requireDatabase(),
{ action: 'db_recent_scheduled_tasks', minutes: 1440 },
{ sourceGroup: 'other-folder', isMain: false },
{ sourceGroup: 'other-folder' },
),
) as { tasks: unknown[] };

View File

@@ -332,7 +332,6 @@ function collectLegacyRoomRegistrationSnapshotForTests(
? existingStored.trigger!
: (preferredOwnerRow?.trigger_pattern ?? ownerRow.trigger_pattern),
requiresTrigger: (first.requires_trigger ?? 1) === 1,
isMain: (first.is_main ?? 0) === 1,
ownerAgentType,
workDir: first.work_dir ?? null,
};
@@ -471,7 +470,6 @@ function getPendingLegacyRegisteredGroupJidsForTests(
stored.name !== plan.snapshot.name ||
stored.folder !== plan.snapshot.folder ||
(stored.requiresTrigger ?? true) !== plan.snapshot.requiresTrigger ||
(stored.isMain ?? false) !== plan.snapshot.isMain ||
(stored.workDir ?? null) !== (plan.snapshot.workDir ?? null)
) {
return true;
@@ -2357,9 +2355,9 @@ describe('message query LIMIT', () => {
});
});
// --- RegisteredGroup isMain round-trip ---
// --- RegisteredGroup projection ---
describe('registered group isMain', () => {
describe('registered group projection', () => {
it('projects trigger metadata from canonical room settings into registered groups', () => {
_setRegisteredGroupForTests('dc:triggered', {
name: 'Triggered Room',
@@ -2379,36 +2377,6 @@ describe('registered group isMain', () => {
});
});
it('persists isMain=true through set/get round-trip', () => {
_setRegisteredGroupForTests('dc:main', {
name: 'Main Chat',
folder: 'discord_main',
trigger: '@Andy',
added_at: '2024-01-01T00:00:00.000Z',
isMain: true,
});
const groups = getAllRoomBindings();
const group = groups['dc:main'];
expect(group).toBeDefined();
expect(group.isMain).toBe(true);
expect(group.folder).toBe('discord_main');
});
it('omits isMain for non-main groups', () => {
_setRegisteredGroupForTests('group@g.us', {
name: 'Family Chat',
folder: 'discord_family-chat',
trigger: '@Andy',
added_at: '2024-01-01T00:00:00.000Z',
});
const groups = getAllRoomBindings();
const group = groups['group@g.us'];
expect(group).toBeDefined();
expect(group.isMain).toBeUndefined();
});
it('filters duplicate jid registrations by agent type', () => {
_setRegisteredGroupForTests('dc:shared', {
name: 'Shared Room',

View File

@@ -19,7 +19,6 @@ describe('getStoredRoomSettingsRowFromDatabase mode_source resilience', () => {
folder: 'cgv-macro',
triggerPattern: '',
requiresTrigger: false,
isMain: false,
ownerAgentType: 'claude-code' as const,
workDir: null,
};

View File

@@ -23,7 +23,6 @@ export interface StoredRoomSettings {
folder?: string;
trigger?: string;
requiresTrigger?: boolean;
isMain?: boolean;
ownerAgentType?: AgentType;
workDir?: string;
}
@@ -33,7 +32,6 @@ export interface RoomRegistrationSnapshot {
folder: string;
triggerPattern: string;
requiresTrigger: boolean;
isMain: boolean;
ownerAgentType: AgentType;
workDir: string | null;
}
@@ -161,7 +159,7 @@ export function getStoredRoomSettingsRowFromDatabase(
const row = database
.prepare(
`SELECT room_mode, mode_source, name, folder, trigger_pattern,
requires_trigger, is_main, owner_agent_type, work_dir
requires_trigger, owner_agent_type, work_dir
FROM room_settings
WHERE chat_jid = ?`,
)
@@ -173,7 +171,6 @@ export function getStoredRoomSettingsRowFromDatabase(
folder: string | null;
trigger_pattern: string | null;
requires_trigger: number | null;
is_main: number | null;
owner_agent_type: string | null;
work_dir: string | null;
}
@@ -209,7 +206,6 @@ export function getStoredRoomSettingsRowFromDatabase(
trigger: row.trigger_pattern ?? undefined,
requiresTrigger:
row.requires_trigger === null ? undefined : row.requires_trigger === 1,
isMain: row.is_main === null ? undefined : row.is_main === 1,
ownerAgentType: normalizeStoredAgentType(row.owner_agent_type),
workDir: row.work_dir ?? undefined,
};
@@ -300,7 +296,6 @@ export function buildRegisteredGroupFromStoredSettings(
added_at: capabilityMetadata?.createdAt || new Date(0).toISOString(),
agentConfig: capabilityMetadata?.agentConfig,
requiresTrigger: stored.requiresTrigger ?? false,
isMain: stored.isMain ? true : undefined,
agentType: resolvedAgentType,
workDir: stored.workDir,
};
@@ -452,12 +447,11 @@ export function insertStoredRoomSettings(
folder,
trigger_pattern,
requires_trigger,
is_main,
owner_agent_type,
work_dir,
created_at,
updated_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
)
.run(
chatJid,
@@ -467,7 +461,6 @@ export function insertStoredRoomSettings(
snapshot.folder,
snapshot.triggerPattern,
snapshot.requiresTrigger ? 1 : 0,
snapshot.isMain ? 1 : 0,
snapshot.ownerAgentType,
snapshot.workDir,
now,
@@ -489,12 +482,11 @@ export function insertStoredRoomSettingsFromMigration(
folder,
trigger_pattern,
requires_trigger,
is_main,
owner_agent_type,
work_dir,
created_at,
updated_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(chat_jid) DO NOTHING`,
)
.run(
@@ -505,7 +497,6 @@ export function insertStoredRoomSettingsFromMigration(
plan.snapshot.folder,
plan.snapshot.triggerPattern,
plan.snapshot.requiresTrigger ? 1 : 0,
plan.snapshot.isMain ? 1 : 0,
plan.snapshot.ownerAgentType,
plan.snapshot.workDir,
plan.createdAt,
@@ -666,7 +657,6 @@ export function updateStoredRoomMetadata(
folder = ?,
trigger_pattern = ?,
requires_trigger = ?,
is_main = ?,
owner_agent_type = ?,
work_dir = ?,
updated_at = ?
@@ -677,7 +667,6 @@ export function updateStoredRoomMetadata(
snapshot.folder,
snapshot.triggerPattern,
snapshot.requiresTrigger ? 1 : 0,
snapshot.isMain ? 1 : 0,
snapshot.ownerAgentType,
snapshot.workDir,
new Date().toISOString(),

View File

@@ -47,7 +47,6 @@ export interface AssignRoomInput {
folder?: string;
trigger?: string;
requiresTrigger?: boolean;
isMain?: boolean;
workDir?: string;
addedAt?: string;
ownerAgentConfig?: RegisteredGroup['agentConfig'];
@@ -140,7 +139,6 @@ function seedRoomBindingForTestsInDatabase(
: (group.trigger ?? ''),
requiresTrigger:
group.requiresTrigger ?? existingStored?.requiresTrigger ?? false,
isMain: group.isMain ?? existingStored?.isMain ?? false,
ownerAgentType,
workDir: group.workDir ?? existingStored?.workDir ?? null,
};
@@ -201,7 +199,6 @@ export function assignRoomInDatabase(
triggerPattern: input.trigger ?? existing?.trigger ?? '',
requiresTrigger:
input.requiresTrigger ?? existing?.requiresTrigger ?? false,
isMain: input.isMain ?? existing?.isMain ?? false,
ownerAgentType,
workDir: input.workDir ?? existing?.workDir ?? null,
};
@@ -218,7 +215,6 @@ export function assignRoomInDatabase(
folder = ?,
trigger_pattern = ?,
requires_trigger = ?,
is_main = ?,
owner_agent_type = ?,
work_dir = ?,
updated_at = ?
@@ -230,7 +226,6 @@ export function assignRoomInDatabase(
snapshot.folder,
snapshot.triggerPattern,
snapshot.requiresTrigger ? 1 : 0,
snapshot.isMain ? 1 : 0,
snapshot.ownerAgentType,
snapshot.workDir,
now,
@@ -412,7 +407,6 @@ function buildRoomRegistrationSnapshotFromStoredRoom(
),
triggerPattern: stored.trigger ?? '',
requiresTrigger: stored.requiresTrigger ?? false,
isMain: stored.isMain ?? false,
ownerAgentType,
workDir: stored.workDir ?? null,
};

View File

@@ -41,10 +41,6 @@ describe('host evidence IPC', () => {
deps = {
sendMessage: async () => {},
roomBindings: () => ({ 'other@g.us': OTHER_GROUP }),
assignRoom: () => {},
syncGroups: async () => {},
getAvailableGroups: () => [],
writeGroupsSnapshot: () => {},
};
fs.rmSync(resolveGroupIpcPath('other-group'), {
@@ -79,7 +75,6 @@ describe('host evidence IPC', () => {
action: 'ejclaw_service_status',
},
'other-group',
false,
deps,
);
@@ -108,7 +103,6 @@ describe('host evidence IPC', () => {
ref: undefined,
artifactKind: undefined,
sourceGroup: 'other-group',
isMain: false,
});
expect(response.requestId).toBe('req-1');
expect(response.ok).toBe(true);
@@ -123,7 +117,6 @@ describe('host evidence IPC', () => {
action: 'cat /etc/shadow',
},
'other-group',
false,
deps,
);

View File

@@ -55,7 +55,6 @@ export interface HostEvidenceRequest {
ref?: string;
artifactKind?: string;
sourceGroup?: string;
isMain?: boolean;
}
export interface HostEvidenceResult {
@@ -319,10 +318,7 @@ export async function runHostEvidenceRequest(
minutes: request.minutes,
limit: request.limit,
},
{
sourceGroup: request.sourceGroup ?? '',
isMain: request.isMain === true,
},
{ sourceGroup: request.sourceGroup ?? '' },
),
),
stderr: '',

View File

@@ -17,7 +17,6 @@ import {
getChannelFactory,
getRegisteredChannelNames,
} from './channels/registry.js';
import { writeGroupsSnapshot } from './agent-runner.js';
import {
hasRecentRestartAnnouncement,
initDatabase,
@@ -39,7 +38,6 @@ import {
consumeRestartContext,
getRecoverableInterruptedGroups,
getInterruptedRecoveryCandidates,
inferRecentRestartContext,
type RestartContext,
writeShutdownRestartContext,
} from './restart-context.js';
@@ -55,7 +53,7 @@ import {
startUnifiedDashboard,
} from './unified-dashboard.js';
import { startUsagePrimer } from './usage-primer.js';
import { Channel, NewMessage, RegisteredGroup } from './types.js';
import { Channel, NewMessage } from './types.js';
import { logger } from './logger.js';
import { initCodexTokenRotation } from './codex-token-rotation.js';
import {
@@ -153,21 +151,6 @@ async function deliverFormattedCanonicalMessage(
);
}
/**
* Get available groups list for the agent.
* Returns groups ordered by most recent activity.
*/
export function getAvailableGroups(): import('./agent-runner.js').AvailableGroup[] {
return runtimeState.getAvailableGroups();
}
/** @internal - exported for testing */
export function _setRegisteredGroups(
groups: Record<string, RegisteredGroup>,
): void {
runtimeState.setRoomBindings(groups);
}
async function tryDeliverRestartAnnouncement(
chatJid: string,
rawText: string,
@@ -225,31 +208,6 @@ async function announceRestartRecovery(
return explicitContext;
}
const inferred = inferRecentRestartContext(
runtimeState.getRoomBindings(),
processStartedAtMs,
);
if (!inferred) return null;
if (hasRecentRestartAnnouncement(inferred.chatJid, dedupeSince)) {
logger.info(
{ chatJid: inferred.chatJid },
'Skipped duplicate inferred restart recovery announcement',
);
return null;
}
if (
await tryDeliverRestartAnnouncement(
inferred.chatJid,
inferred.lines.join('\n'),
)
) {
logger.info(
{ chatJid: inferred.chatJid },
'Sent inferred restart recovery announcement',
);
}
return null;
}
@@ -335,11 +293,7 @@ async function main(): Promise<void> {
pendingMessages: status.pendingMessages,
pendingTasks: status.pendingTasks,
}));
const writtenPaths = writeShutdownRestartContext(
roomBindings,
interruptedGroups,
signal,
);
const writtenPaths = writeShutdownRestartContext(interruptedGroups, signal);
if (writtenPaths.length > 0) {
logger.info(
{
@@ -508,16 +462,6 @@ async function main(): Promise<void> {
},
nudgeScheduler: nudgeSchedulerLoop,
roomBindings: runtimeState.getRoomBindings,
assignRoom: runtimeState.assignRoomForIpc,
syncGroups: async (force: boolean) => {
await Promise.all(
channels
.filter((ch) => ch.syncGroups)
.map((ch) => ch.syncGroups!(force)),
);
},
getAvailableGroups,
writeGroupsSnapshot,
});
queue.setProcessMessagesFn(runtime.processGroupMessages);
queue.enterRecoveryMode();

View File

@@ -3,13 +3,9 @@ import { describe, it, expect, beforeEach, vi } from 'vitest';
import {
_setRegisteredGroupForTests,
_initTestDatabase,
assignRoom,
createTask,
getAllTasks,
recallMemories,
getRegisteredAgentTypesForJid,
getRegisteredGroup,
getStoredRoomSettings,
getTaskById,
} from './db.js';
import { forwardAuthorizedIpcMessage, processTaskIpc, IpcDeps } from './ipc.js';
@@ -22,7 +18,6 @@ const MAIN_GROUP: RegisteredGroup = {
folder: 'whatsapp_main',
trigger: 'always',
added_at: '2024-01-01T00:00:00.000Z',
isMain: true,
};
const OTHER_GROUP: RegisteredGroup = {
@@ -60,42 +55,13 @@ beforeEach(() => {
sendMessage: async () => {},
nudgeScheduler: vi.fn(),
roomBindings: () => groups,
assignRoom: (jid, room) => {
const assigned = assignRoom(jid, room);
if (!assigned) return;
const { jid: _ignoredJid, ...group } = assigned;
groups[jid] = group;
},
syncGroups: async () => {},
getAvailableGroups: () => [],
writeGroupsSnapshot: () => {},
};
});
// --- schedule_task authorization ---
describe('schedule_task authorization', () => {
it('main group can schedule for another group', async () => {
await processTaskIpc(
{
type: 'schedule_task',
prompt: 'do something',
schedule_type: 'once',
schedule_value: '2025-06-01T00:00:00',
targetJid: 'other@g.us',
},
'whatsapp_main',
true,
deps,
);
// Verify task was created in DB for the other group
const allTasks = getAllTasks();
expect(allTasks.length).toBe(1);
expect(allTasks[0].group_folder).toBe('other-group');
});
it('non-main group can schedule for itself', async () => {
it('a room can schedule for itself', async () => {
await processTaskIpc(
{
type: 'schedule_task',
@@ -105,7 +71,6 @@ describe('schedule_task authorization', () => {
targetJid: 'other@g.us',
},
'other-group',
false,
deps,
);
@@ -129,8 +94,7 @@ describe('schedule_task authorization', () => {
schedule_value: '2025-06-01T00:00:00',
targetJid: 'other@g.us',
},
'whatsapp_main',
true,
'other-group',
deps,
);
@@ -156,8 +120,7 @@ describe('schedule_task authorization', () => {
agent_type: 'codex',
room_role: 'owner',
},
'whatsapp_main',
true,
'other-group',
deps,
);
@@ -167,7 +130,7 @@ describe('schedule_task authorization', () => {
expect(allTasks[0].room_role).toBe('owner');
});
it('non-main group cannot schedule for another group', async () => {
it('a room cannot schedule for another group', async () => {
await processTaskIpc(
{
type: 'schedule_task',
@@ -177,7 +140,6 @@ describe('schedule_task authorization', () => {
targetJid: 'main@g.us',
},
'other-group',
false,
deps,
);
@@ -194,8 +156,7 @@ describe('schedule_task authorization', () => {
schedule_value: '2025-06-01T00:00:00',
targetJid: 'unknown@g.us',
},
'whatsapp_main',
true,
'other-group',
deps,
);
@@ -213,7 +174,6 @@ describe('schedule_task authorization', () => {
targetJid: 'other-group',
},
'other-group',
false,
deps,
);
@@ -237,7 +197,6 @@ describe('persist_memory authorization', () => {
source_ref: 'compact:test',
},
'other-group',
false,
deps,
);
@@ -261,7 +220,6 @@ describe('persist_memory authorization', () => {
source_kind: 'compact',
},
'other-group',
false,
deps,
);
@@ -304,31 +262,19 @@ describe('pause_task authorization', () => {
});
});
it('main group can pause any task', async () => {
await processTaskIpc(
{ type: 'pause_task', taskId: 'task-other' },
'whatsapp_main',
true,
deps,
);
expect(getTaskById('task-other')!.status).toBe('paused');
});
it('non-main group can pause its own task', async () => {
it('a room can pause its own task', async () => {
await processTaskIpc(
{ type: 'pause_task', taskId: 'task-other' },
'other-group',
false,
deps,
);
expect(getTaskById('task-other')!.status).toBe('paused');
});
it('non-main group cannot pause another groups task', async () => {
it('a room cannot pause another groups task', async () => {
await processTaskIpc(
{ type: 'pause_task', taskId: 'task-main' },
'other-group',
false,
deps,
);
expect(getTaskById('task-main')!.status).toBe('active');
@@ -353,31 +299,19 @@ describe('resume_task authorization', () => {
});
});
it('main group can resume any task', async () => {
await processTaskIpc(
{ type: 'resume_task', taskId: 'task-paused' },
'whatsapp_main',
true,
deps,
);
expect(getTaskById('task-paused')!.status).toBe('active');
});
it('non-main group can resume its own task', async () => {
it('a room can resume its own task', async () => {
await processTaskIpc(
{ type: 'resume_task', taskId: 'task-paused' },
'other-group',
false,
deps,
);
expect(getTaskById('task-paused')!.status).toBe('active');
});
it('non-main group cannot resume another groups task', async () => {
it('a room cannot resume another groups task', async () => {
await processTaskIpc(
{ type: 'resume_task', taskId: 'task-paused' },
'third-group',
false,
deps,
);
expect(getTaskById('task-paused')!.status).toBe('paused');
@@ -409,7 +343,6 @@ describe('update_task behavior', () => {
schedule_value: '2025-07-01T00:00:00',
},
'other-group',
false,
deps,
);
@@ -423,30 +356,7 @@ describe('update_task behavior', () => {
// --- cancel_task authorization ---
describe('cancel_task authorization', () => {
it('main group can cancel any task', async () => {
createTask({
id: 'task-to-cancel',
group_folder: 'other-group',
chat_jid: 'other@g.us',
prompt: 'cancel me',
schedule_type: 'once',
schedule_value: '2025-06-01T00:00:00',
context_mode: 'isolated',
next_run: null,
status: 'active',
created_at: '2024-01-01T00:00:00.000Z',
});
await processTaskIpc(
{ type: 'cancel_task', taskId: 'task-to-cancel' },
'whatsapp_main',
true,
deps,
);
expect(getTaskById('task-to-cancel')).toBeUndefined();
});
it('non-main group can cancel its own task', async () => {
it('a room can cancel its own task', async () => {
createTask({
id: 'task-own',
group_folder: 'other-group',
@@ -463,13 +373,12 @@ describe('cancel_task authorization', () => {
await processTaskIpc(
{ type: 'cancel_task', taskId: 'task-own' },
'other-group',
false,
deps,
);
expect(getTaskById('task-own')).toBeUndefined();
});
it('non-main group cannot cancel another groups task', async () => {
it('a room cannot cancel another groups task', async () => {
createTask({
id: 'task-foreign',
group_folder: 'whatsapp_main',
@@ -486,116 +395,42 @@ describe('cancel_task authorization', () => {
await processTaskIpc(
{ type: 'cancel_task', taskId: 'task-foreign' },
'other-group',
false,
deps,
);
expect(getTaskById('task-foreign')).toBeDefined();
});
});
// --- assign_room authorization ---
describe('assign_room authorization', () => {
it('non-main group cannot assign a room', async () => {
await processTaskIpc(
{
type: 'assign_room',
jid: 'new@g.us',
name: 'New Group',
folder: 'new-group',
},
'other-group',
false,
deps,
);
// roomBindings should not have changed
expect(groups['new@g.us']).toBeUndefined();
});
it('main group cannot assign with unsafe folder path', async () => {
await processTaskIpc(
{
type: 'assign_room',
jid: 'new@g.us',
name: 'New Group',
folder: '../../outside',
},
'whatsapp_main',
true,
deps,
);
expect(groups['new@g.us']).toBeUndefined();
});
});
// --- refresh_groups authorization ---
describe('refresh_groups authorization', () => {
it('non-main group cannot trigger refresh', async () => {
// This should be silently blocked (no crash, no effect)
await processTaskIpc(
{ type: 'refresh_groups' },
'other-group',
false,
deps,
);
// If we got here without error, the auth gate worked
});
});
// --- IPC message authorization ---
// Tests the authorization pattern from startIpcWatcher (ipc.ts).
// The logic: isMain || (targetGroup && targetGroup.folder === sourceGroup)
// The logic: targetGroup && targetGroup.folder === sourceGroup
describe('IPC message authorization', () => {
// Replicate the exact check from the IPC watcher
function isMessageAuthorized(
sourceGroup: string,
isMain: boolean,
targetChatJid: string,
roomBindings: Record<string, RegisteredGroup>,
): boolean {
const targetGroup = roomBindings[targetChatJid];
return isMain || (!!targetGroup && targetGroup.folder === sourceGroup);
return !!targetGroup && targetGroup.folder === sourceGroup;
}
it('main group can send to any group', () => {
expect(
isMessageAuthorized('whatsapp_main', true, 'other@g.us', groups),
).toBe(true);
expect(
isMessageAuthorized('whatsapp_main', true, 'third@g.us', groups),
).toBe(true);
it('a room can send to its own chat', () => {
expect(isMessageAuthorized('other-group', 'other@g.us', groups)).toBe(true);
});
it('non-main group can send to its own chat', () => {
expect(
isMessageAuthorized('other-group', false, 'other@g.us', groups),
).toBe(true);
});
it('non-main group cannot send to another groups chat', () => {
expect(isMessageAuthorized('other-group', false, 'main@g.us', groups)).toBe(
it('a room cannot send to another groups chat', () => {
expect(isMessageAuthorized('other-group', 'main@g.us', groups)).toBe(false);
expect(isMessageAuthorized('other-group', 'third@g.us', groups)).toBe(
false,
);
expect(
isMessageAuthorized('other-group', false, 'third@g.us', groups),
).toBe(false);
});
it('non-main group cannot send to unregistered JID', () => {
expect(
isMessageAuthorized('other-group', false, 'unknown@g.us', groups),
).toBe(false);
});
it('main group can send to unregistered JID', () => {
// Main is always authorized regardless of target
expect(
isMessageAuthorized('whatsapp_main', true, 'unknown@g.us', groups),
).toBe(true);
it('a room cannot send to unregistered JID', () => {
expect(isMessageAuthorized('other-group', 'unknown@g.us', groups)).toBe(
false,
);
});
it('forwards senderRole through authorized IPC messages', async () => {
@@ -610,7 +445,6 @@ describe('IPC message authorization', () => {
runId: 'run-reviewer-ipc',
},
'other-group',
false,
groups,
sendMessage,
);
@@ -648,7 +482,6 @@ describe('IPC message authorization', () => {
attachments,
},
'other-group',
false,
groups,
sendMessage,
);
@@ -686,7 +519,6 @@ describe('IPC message authorization', () => {
}),
},
'other-group',
false,
groups,
sendMessage,
);
@@ -723,7 +555,6 @@ describe('IPC message authorization', () => {
sourceKind: 'trusted_external_bot',
},
'other-group',
false,
groups,
sendMessage,
injectInboundMessage,
@@ -763,7 +594,6 @@ describe('IPC message authorization', () => {
sourceKind: 'trusted_external_bot',
},
'other-group',
false,
groups,
sendMessage,
injectInboundMessage,
@@ -786,7 +616,6 @@ describe('IPC message authorization', () => {
runId: 'run-reviewer-ipc',
},
'other-group',
false,
groups,
sendMessage,
);
@@ -809,8 +638,7 @@ describe('schedule_task schedule types', () => {
schedule_value: '0 9 * * *', // every day at 9am
targetJid: 'other@g.us',
},
'whatsapp_main',
true,
'other-group',
deps,
);
@@ -833,8 +661,7 @@ describe('schedule_task schedule types', () => {
schedule_value: 'not a cron',
targetJid: 'other@g.us',
},
'whatsapp_main',
true,
'other-group',
deps,
);
@@ -852,8 +679,7 @@ describe('schedule_task schedule types', () => {
schedule_value: '3600000', // 1 hour
targetJid: 'other@g.us',
},
'whatsapp_main',
true,
'other-group',
deps,
);
@@ -885,8 +711,7 @@ Check the run.
schedule_value: '60000',
targetJid: 'other@g.us',
},
'whatsapp_main',
true,
'other-group',
deps,
);
@@ -922,8 +747,7 @@ Managed by host-driven watcher.
}),
targetJid: 'other@g.us',
},
'whatsapp_main',
true,
'other-group',
deps,
);
@@ -943,8 +767,7 @@ Managed by host-driven watcher.
schedule_value: '60000',
targetJid: 'other@g.us',
},
'whatsapp_main',
true,
'other-group',
deps,
);
@@ -962,8 +785,7 @@ Managed by host-driven watcher.
schedule_value: 'abc',
targetJid: 'other@g.us',
},
'whatsapp_main',
true,
'other-group',
deps,
);
@@ -979,8 +801,7 @@ Managed by host-driven watcher.
schedule_value: '0',
targetJid: 'other@g.us',
},
'whatsapp_main',
true,
'other-group',
deps,
);
@@ -996,8 +817,7 @@ Managed by host-driven watcher.
schedule_value: 'not-a-date',
targetJid: 'other@g.us',
},
'whatsapp_main',
true,
'other-group',
deps,
);
@@ -1018,8 +838,7 @@ describe('schedule_task context_mode', () => {
context_mode: 'group',
targetJid: 'other@g.us',
},
'whatsapp_main',
true,
'other-group',
deps,
);
@@ -1037,8 +856,7 @@ describe('schedule_task context_mode', () => {
context_mode: 'isolated',
targetJid: 'other@g.us',
},
'whatsapp_main',
true,
'other-group',
deps,
);
@@ -1056,8 +874,7 @@ describe('schedule_task context_mode', () => {
context_mode: 'bogus' as any,
targetJid: 'other@g.us',
},
'whatsapp_main',
true,
'other-group',
deps,
);
@@ -1074,8 +891,7 @@ describe('schedule_task context_mode', () => {
schedule_value: '2025-06-01T00:00:00',
targetJid: 'other@g.us',
},
'whatsapp_main',
true,
'other-group',
deps,
);
@@ -1083,178 +899,3 @@ describe('schedule_task context_mode', () => {
expect(tasks[0].context_mode).toBe('isolated');
});
});
// --- assign_room success path ---
describe('assign_room success', () => {
it('main group can assign a new room', async () => {
await processTaskIpc(
{
type: 'assign_room',
jid: 'new@g.us',
name: 'New Group',
folder: 'new-group',
},
'whatsapp_main',
true,
deps,
);
const group = getRegisteredGroup('new@g.us');
expect(group).toBeDefined();
expect(group!.name).toBe('New Group');
expect(group!.folder).toBe('new-group');
});
it('assign_room persists trigger metadata through IPC', async () => {
await processTaskIpc(
{
type: 'assign_room',
jid: 'triggered@g.us',
name: 'Triggered Group',
folder: 'triggered-group',
trigger: '@Repro',
requiresTrigger: true,
},
'whatsapp_main',
true,
deps,
);
expect(getStoredRoomSettings('triggered@g.us')).toMatchObject({
trigger: '@Repro',
requiresTrigger: true,
});
expect(getRegisteredGroup('triggered@g.us')).toMatchObject({
trigger: '@Repro',
requiresTrigger: true,
});
});
it('assign_room auto-fills missing folder and defaults to tribunal without exposing trigger metadata', async () => {
await processTaskIpc(
{
type: 'assign_room',
jid: 'partial@g.us',
name: 'Partial',
},
'whatsapp_main',
true,
deps,
);
const group = getRegisteredGroup('partial@g.us');
expect(group).toBeDefined();
expect(group!.folder).toMatch(/^grp_whatsapp_/);
expect(getStoredRoomSettings('partial@g.us')?.roomMode).toBe('tribunal');
});
it('assign_room preserves an existing tribunal room mode when room_mode is omitted', async () => {
assignRoom('legacy-tribunal@g.us', {
name: 'Legacy Tribunal',
roomMode: 'tribunal',
ownerAgentType: 'codex',
folder: 'legacy-tribunal',
});
await processTaskIpc(
{
type: 'assign_room',
jid: 'legacy-tribunal@g.us',
name: 'Legacy Tribunal Renamed',
folder: 'legacy-tribunal',
},
'whatsapp_main',
true,
deps,
);
expect(getStoredRoomSettings('legacy-tribunal@g.us')).toMatchObject({
chatJid: 'legacy-tribunal@g.us',
roomMode: 'tribunal',
modeSource: 'explicit',
name: 'Legacy Tribunal Renamed',
});
expect(
getRegisteredAgentTypesForJid('legacy-tribunal@g.us').sort(),
).toEqual(['claude-code', 'codex']);
});
it('main group can assign a tribunal room and materialize capability rows', async () => {
await processTaskIpc(
{
type: 'assign_room',
jid: 'tribunal@g.us',
name: 'Tribunal Room',
room_mode: 'tribunal',
owner_agent_type: 'codex',
},
'whatsapp_main',
true,
deps,
);
const stored = getStoredRoomSettings('tribunal@g.us');
expect(stored).toMatchObject({
chatJid: 'tribunal@g.us',
roomMode: 'tribunal',
modeSource: 'explicit',
name: 'Tribunal Room',
ownerAgentType: 'codex',
});
expect(stored?.folder).toMatch(/^grp_whatsapp_/);
expect(getRegisteredAgentTypesForJid('tribunal@g.us').sort()).toEqual([
'claude-code',
'codex',
]);
});
it('main group can assign per-room reviewer and arbiter agent types', async () => {
await processTaskIpc(
{
type: 'assign_room',
jid: 'tribunal-role-overrides@g.us',
name: 'Tribunal Role Overrides',
room_mode: 'tribunal',
owner_agent_type: 'claude-code',
reviewer_agent_type: 'codex',
arbiter_agent_type: 'claude-code',
},
'whatsapp_main',
true,
deps,
);
expect(getStoredRoomSettings('tribunal-role-overrides@g.us')).toMatchObject(
{
chatJid: 'tribunal-role-overrides@g.us',
roomMode: 'tribunal',
modeSource: 'explicit',
name: 'Tribunal Role Overrides',
ownerAgentType: 'claude-code',
},
);
expect(
getRegisteredAgentTypesForJid('tribunal-role-overrides@g.us').sort(),
).toEqual(['claude-code', 'codex']);
expect(
getRegisteredGroup('tribunal-role-overrides@g.us', 'codex'),
).toMatchObject({
agentType: 'codex',
});
});
it('assign_room rejects request with missing fields', async () => {
await processTaskIpc(
{
type: 'assign_room',
jid: 'broken@g.us',
},
'whatsapp_main',
true,
deps,
);
expect(getRegisteredGroup('broken@g.us')).toBeUndefined();
});
});

View File

@@ -8,7 +8,6 @@ import type { RegisteredGroup } from './types.js';
export async function forwardAuthorizedIpcMessage(
msg: IpcMessagePayload,
sourceGroup: string,
isMain: boolean,
roomBindings: Record<string, RegisteredGroup>,
sendMessage: (
jid: string,
@@ -38,16 +37,13 @@ export async function forwardAuthorizedIpcMessage(
return { outcome: 'ignored', senderRole: msg.senderRole ?? null };
}
// A room may only send to or inject into itself.
const targetGroup = roomBindings[msg.chatJid];
const isMainOverride = isMain === true;
if (
!(isMainOverride || (targetGroup && targetGroup.folder === sourceGroup))
) {
if (!targetGroup || targetGroup.folder !== sourceGroup) {
return {
outcome: 'blocked',
chatJid: msg.chatJid,
targetGroup: targetGroup?.folder ?? null,
isMainOverride,
targetGroup: targetGroup.folder,
senderRole: msg.senderRole ?? null,
};
}
@@ -57,8 +53,7 @@ export async function forwardAuthorizedIpcMessage(
return {
outcome: 'ignored',
chatJid: msg.chatJid,
targetGroup: targetGroup?.folder ?? null,
isMainOverride,
targetGroup: targetGroup.folder,
senderRole: msg.senderRole ?? null,
};
}
@@ -75,8 +70,7 @@ export async function forwardAuthorizedIpcMessage(
return {
outcome: 'sent',
chatJid: msg.chatJid,
targetGroup: targetGroup?.folder ?? null,
isMainOverride,
targetGroup: targetGroup.folder,
senderRole: msg.senderRole ?? null,
};
}
@@ -86,8 +80,7 @@ export async function forwardAuthorizedIpcMessage(
return {
outcome: 'sent',
chatJid: msg.chatJid,
targetGroup: targetGroup?.folder ?? null,
isMainOverride,
targetGroup: targetGroup.folder,
senderRole: msg.senderRole ?? null,
};
}
@@ -103,8 +96,7 @@ export async function forwardAuthorizedIpcMessage(
return {
outcome: 'sent',
chatJid: msg.chatJid,
targetGroup: targetGroup?.folder ?? null,
isMainOverride,
targetGroup: targetGroup.folder,
senderRole: msg.senderRole ?? null,
};
}

View File

@@ -2,10 +2,6 @@ import { deleteTask, updateTask } from './db.js';
import { logger } from './logger.js';
import { handleHostEvidenceRequest } from './ipc-task-processor/host-evidence.js';
import { handlePersistMemory } from './ipc-task-processor/memory.js';
import {
handleAssignRoom,
handleRefreshGroups,
} from './ipc-task-processor/rooms.js';
import { handleScheduleTask } from './ipc-task-processor/schedule.js';
import {
handleTaskStateMutation,
@@ -16,16 +12,15 @@ import type { IpcDeps, TaskIpcPayload } from './ipc-types.js';
export async function processTaskIpc(
data: TaskIpcPayload,
sourceGroup: string,
isMain: boolean,
deps: IpcDeps,
): Promise<void> {
switch (data.type) {
case 'schedule_task':
handleScheduleTask(data, sourceGroup, isMain, deps);
handleScheduleTask(data, sourceGroup, deps);
break;
case 'pause_task':
handleTaskStateMutation(data, sourceGroup, isMain, {
handleTaskStateMutation(data, sourceGroup, {
action: () => updateTask(data.taskId!, { status: 'paused' }),
successMessage: 'Task paused via IPC',
unauthorizedMessage: 'Unauthorized task pause attempt',
@@ -33,7 +28,7 @@ export async function processTaskIpc(
break;
case 'resume_task':
handleTaskStateMutation(data, sourceGroup, isMain, {
handleTaskStateMutation(data, sourceGroup, {
action: () => updateTask(data.taskId!, { status: 'active' }),
successMessage: 'Task resumed via IPC',
unauthorizedMessage: 'Unauthorized task resume attempt',
@@ -41,7 +36,7 @@ export async function processTaskIpc(
break;
case 'cancel_task':
handleTaskStateMutation(data, sourceGroup, isMain, {
handleTaskStateMutation(data, sourceGroup, {
action: () => deleteTask(data.taskId!),
successMessage: 'Task cancelled via IPC',
unauthorizedMessage: 'Unauthorized task cancel attempt',
@@ -49,19 +44,11 @@ export async function processTaskIpc(
break;
case 'host_evidence_request':
await handleHostEvidenceRequest(data, sourceGroup, isMain, deps);
await handleHostEvidenceRequest(data, sourceGroup, deps);
break;
case 'update_task':
handleUpdateTask(data, sourceGroup, isMain);
break;
case 'refresh_groups':
await handleRefreshGroups(sourceGroup, isMain, deps);
break;
case 'assign_room':
handleAssignRoom(data, sourceGroup, isMain, deps);
handleUpdateTask(data, sourceGroup);
break;
case 'persist_memory':

View File

@@ -9,7 +9,6 @@ import type { IpcDeps, TaskIpcPayload } from '../ipc-types.js';
export async function handleHostEvidenceRequest(
data: TaskIpcPayload,
sourceGroup: string,
isMain: boolean,
deps: IpcDeps,
): Promise<void> {
if (!data.requestId) {
@@ -21,7 +20,7 @@ export async function handleHostEvidenceRequest(
}
if (data.action === 'ejclaw_room_runtime') {
handleRoomRuntimeReportRequest(data, sourceGroup, isMain, deps);
handleRoomRuntimeReportRequest(data, sourceGroup, deps);
return;
}
@@ -60,7 +59,6 @@ export async function handleHostEvidenceRequest(
artifactKind:
typeof data.artifact_kind === 'string' ? data.artifact_kind : undefined,
sourceGroup,
isMain,
});
writeHostEvidenceResponse(sourceGroup, {
@@ -83,7 +81,6 @@ export async function handleHostEvidenceRequest(
function handleRoomRuntimeReportRequest(
data: TaskIpcPayload,
sourceGroup: string,
isMain: boolean,
deps: IpcDeps,
): void {
if (!data.chatJid) {
@@ -125,7 +122,6 @@ function handleRoomRuntimeReportRequest(
const report = deps.getRoomRuntimeReport({
chatJid: data.chatJid,
sourceGroup,
isMain,
});
writeHostEvidenceResponse(sourceGroup, {
requestId: data.requestId!,

View File

@@ -1,135 +0,0 @@
import { isValidGroupFolder } from '../group-folder.js';
import { logger } from '../logger.js';
import type { IpcDeps, TaskIpcPayload } from '../ipc-types.js';
import type { AgentType, RoomMode } from '../types.js';
export async function handleRefreshGroups(
sourceGroup: string,
isMain: boolean,
deps: IpcDeps,
): Promise<void> {
if (!isMain) {
logger.warn({ sourceGroup }, 'Unauthorized refresh_groups attempt blocked');
return;
}
logger.info({ sourceGroup }, 'Group metadata refresh requested via IPC');
await deps.syncGroups(true);
const availableGroups = deps.getAvailableGroups();
deps.writeGroupsSnapshot(sourceGroup, true, availableGroups);
}
export function handleAssignRoom(
data: TaskIpcPayload,
sourceGroup: string,
isMain: boolean,
deps: IpcDeps,
): void {
const validation = validateAssignRoomRequest(data, sourceGroup, isMain);
if (!validation.ok) return;
deps.assignRoom(data.jid!, {
name: data.name!,
roomMode: data.room_mode,
ownerAgentType: data.owner_agent_type,
reviewerAgentType: data.reviewer_agent_type,
arbiterAgentType: data.arbiter_agent_type,
folder: data.folder,
trigger: data.trigger,
requiresTrigger: data.requiresTrigger,
isMain: data.isMain,
workDir: data.workDir,
});
}
function validateAssignRoomRequest(
data: TaskIpcPayload,
sourceGroup: string,
isMain: boolean,
): { ok: true } | { ok: false } {
if (!isMain) {
logger.warn(
{ sourceGroup, type: data.type },
`Unauthorized ${data.type} attempt blocked`,
);
return { ok: false };
}
if (!data.jid || !data.name) {
logger.warn(
{ data },
`Invalid ${data.type} request - missing required fields`,
);
return { ok: false };
}
if (data.folder && !isValidGroupFolder(data.folder)) {
logger.warn(
{ sourceGroup, folder: data.folder },
`Invalid ${data.type} request - unsafe folder name`,
);
return { ok: false };
}
if (data.trigger !== undefined && typeof data.trigger !== 'string') {
logger.warn(
{ sourceGroup, trigger: data.trigger },
'Invalid assign_room request - trigger must be a string',
);
return { ok: false };
}
if (
data.requiresTrigger !== undefined &&
typeof data.requiresTrigger !== 'boolean'
) {
logger.warn(
{ sourceGroup, requiresTrigger: data.requiresTrigger },
'Invalid assign_room request - requiresTrigger must be a boolean',
);
return { ok: false };
}
if (data.room_mode !== undefined && !isRoomMode(data.room_mode)) {
logger.warn(
{ sourceGroup, roomMode: data.room_mode },
'Invalid assign_room request - unknown room_mode',
);
return { ok: false };
}
if (
data.owner_agent_type !== undefined &&
!isAssignableAgentType(data.owner_agent_type)
) {
logger.warn(
{ sourceGroup, ownerAgentType: data.owner_agent_type },
'Invalid assign_room request - unknown owner_agent_type',
);
return { ok: false };
}
if (
data.reviewer_agent_type !== undefined &&
!isAssignableAgentType(data.reviewer_agent_type)
) {
logger.warn(
{ sourceGroup, reviewerAgentType: data.reviewer_agent_type },
'Invalid assign_room request - unknown reviewer_agent_type',
);
return { ok: false };
}
if (
data.arbiter_agent_type !== undefined &&
data.arbiter_agent_type !== null &&
!isAssignableAgentType(data.arbiter_agent_type)
) {
logger.warn(
{ sourceGroup, arbiterAgentType: data.arbiter_agent_type },
'Invalid assign_room request - unknown arbiter_agent_type',
);
return { ok: false };
}
return { ok: true };
}
function isRoomMode(value: string): value is RoomMode {
return value === 'single' || value === 'tribunal';
}
function isAssignableAgentType(value: string): value is AgentType {
return value === 'claude-code' || value === 'codex';
}

View File

@@ -24,7 +24,6 @@ interface ResolvedScheduleTarget {
export function handleScheduleTask(
data: TaskIpcPayload,
sourceGroup: string,
isMain: boolean,
deps: IpcDeps,
): void {
if (!hasRequiredScheduleFields(data)) return;
@@ -33,7 +32,7 @@ export function handleScheduleTask(
const target = resolveScheduleTarget(data.targetJid, roomBindings);
if (!target) return;
if (!isMain && target.folder !== sourceGroup) {
if (target.folder !== sourceGroup) {
logger.warn(
{ sourceGroup, targetFolder: target.folder },
'Unauthorized schedule_task attempt blocked',

View File

@@ -12,7 +12,6 @@ type NextRunResolution = { abort: true } | { abort: false; nextRun?: string };
export function handleTaskStateMutation(
data: TaskIpcPayload,
sourceGroup: string,
isMain: boolean,
config: {
action: () => void;
successMessage: string;
@@ -22,7 +21,7 @@ export function handleTaskStateMutation(
if (!data.taskId) return;
const task = getTaskById(data.taskId);
if (task && (isMain || task.group_folder === sourceGroup)) {
if (task && task.group_folder === sourceGroup) {
config.action();
logger.info({ taskId: data.taskId, sourceGroup }, config.successMessage);
} else {
@@ -36,7 +35,6 @@ export function handleTaskStateMutation(
export function handleUpdateTask(
data: TaskIpcPayload,
sourceGroup: string,
isMain: boolean,
): void {
if (!data.taskId) return;
@@ -48,7 +46,7 @@ export function handleUpdateTask(
);
return;
}
if (!isMain && task.group_folder !== sourceGroup) {
if (task.group_folder !== sourceGroup) {
logger.warn(
{ taskId: data.taskId, sourceGroup },
'Unauthorized task update attempt',

View File

@@ -1,5 +1,3 @@
import type { AvailableGroup } from './agent-runner.js';
import type { AssignRoomInput } from './db.js';
import type {
AgentType,
MessageSourceKind,
@@ -7,7 +5,6 @@ import type {
PairedRoomRole,
PairedTask,
RegisteredGroup,
RoomMode,
} from './types.js';
export interface InjectInboundMessagePayload {
@@ -73,21 +70,12 @@ export interface IpcDeps {
) => Promise<void>;
nudgeScheduler?: () => void;
roomBindings: () => Record<string, RegisteredGroup>;
assignRoom: (jid: string, room: AssignRoomInput) => void;
syncGroups: (force: boolean) => Promise<void>;
getAvailableGroups: () => AvailableGroup[];
writeGroupsSnapshot: (
groupFolder: string,
isMain: boolean,
availableGroups: AvailableGroup[],
) => void;
injectInboundMessage?: (
payload: InjectInboundMessagePayload,
) => Promise<void>;
getRoomRuntimeReport?: (args: {
chatJid: string;
sourceGroup: string;
isMain: boolean;
}) => RoomRuntimeReport;
}
@@ -110,7 +98,6 @@ export interface IpcMessageForwardResult {
outcome: 'ignored' | 'sent' | 'blocked';
chatJid?: string;
targetGroup?: string | null;
isMainOverride?: boolean;
senderRole?: string | null;
}
@@ -128,17 +115,6 @@ export interface TaskIpcPayload {
groupFolder?: string;
chatJid?: string;
targetJid?: string;
jid?: string;
name?: string;
folder?: string;
trigger?: string;
requiresTrigger?: boolean;
room_mode?: RoomMode;
owner_agent_type?: AgentType;
reviewer_agent_type?: AgentType;
arbiter_agent_type?: AgentType | null;
isMain?: boolean;
workDir?: string;
scopeKind?: string;
scopeKey?: string;
content?: string;

View File

@@ -58,14 +58,7 @@ export function startIpcWatcher(deps: IpcDeps): void {
const roomBindings = deps.roomBindings();
// Build folder→isMain lookup from registered groups
const folderIsMain = new Map<string, boolean>();
for (const group of Object.values(roomBindings)) {
if (group.isMain) folderIsMain.set(group.folder, true);
}
for (const sourceGroup of groupFolders) {
const isMain = folderIsMain.get(sourceGroup) === true;
const messagesDir = path.join(ipcBaseDir, sourceGroup, 'messages');
const tasksDir = path.join(ipcBaseDir, sourceGroup, 'tasks');
const errorDir = path.join(ipcBaseDir, 'errors');
@@ -111,7 +104,6 @@ export function startIpcWatcher(deps: IpcDeps): void {
const forwardResult = await forwardAuthorizedIpcMessage(
msg,
sourceGroup,
isMain,
roomBindings,
deps.sendMessage,
deps.injectInboundMessage,
@@ -123,7 +115,6 @@ export function startIpcWatcher(deps: IpcDeps): void {
chatJid: forwardResult.chatJid,
sourceGroup,
targetGroup: forwardResult.targetGroup ?? null,
isMainOverride: forwardResult.isMainOverride,
senderRole: forwardResult.senderRole ?? null,
},
'IPC message sent',
@@ -135,7 +126,6 @@ export function startIpcWatcher(deps: IpcDeps): void {
chatJid: forwardResult.chatJid,
sourceGroup,
targetGroup: forwardResult.targetGroup ?? null,
isMainOverride: forwardResult.isMainOverride,
senderRole: forwardResult.senderRole ?? null,
},
'Unauthorized IPC message attempt blocked',
@@ -177,12 +167,7 @@ export function startIpcWatcher(deps: IpcDeps): void {
if (!data || typeof data !== 'object')
throw new Error('Invalid JSON');
// Pass source group identity to processTaskIpc for authorization
await processTaskIpc(
data as TaskIpcPayload,
sourceGroup,
isMain,
deps,
);
await processTaskIpc(data as TaskIpcPayload, sourceGroup, deps);
fs.unlinkSync(claimedPath);
} catch (err) {
logger.error(

View File

@@ -84,7 +84,6 @@ describe('message agent compact refresh', () => {
groupFolder: 'room',
chatJid: 'room@test',
runId: 'run-1',
isMain: false,
assistantName: 'Andy',
},
activeRole: 'owner',

View File

@@ -39,7 +39,6 @@ describe('runMessageAgentAttempt', () => {
groupFolder: 'test',
chatJid: 'dc:test',
runId: 'run-test',
isMain: false,
assistantName: 'Andy',
},
activeRole: 'arbiter',

View File

@@ -40,7 +40,6 @@ interface AgentInput {
groupFolder: string;
chatJid: string;
runId: string;
isMain: boolean;
assistantName: string;
roomRoleContext?: RoomRoleContext;
}

View File

@@ -3,7 +3,6 @@ import path from 'path';
import { isUnsafeHostPairedModeEnabled } from 'ejclaw-runners-shared';
import { listAvailableGroups } from './available-groups.js';
import {
ARBITER_AGENT_TYPE,
REVIEWER_AGENT_TYPE,
@@ -33,7 +32,7 @@ import type {
RegisteredGroup,
RoomRoleContext,
} from './types.js';
import { writeGroupsSnapshot, writeTasksSnapshot } from './agent-runner.js';
import { writeTasksSnapshot } from './agent-runner.js';
interface ExecutionTargetDeps {
assistantName: string;
@@ -273,7 +272,6 @@ class MessageAgentExecutionTargetPreparer {
const tasks = getAllTasks(ownerAgentType);
writeTasksSnapshot(
this.args.group.folder,
this.args.group.isMain === true,
tasks.map((task) => ({
id: task.id,
groupFolder: task.group_folder,
@@ -284,11 +282,6 @@ class MessageAgentExecutionTargetPreparer {
next_run: task.next_run,
})),
);
writeGroupsSnapshot(
this.args.group.folder,
this.args.group.isMain === true,
listAvailableGroups(this.deps.getRoomBindings()),
);
}
private canRetryClaudeCredentials(isClaudeCodeAgent: boolean): boolean {

View File

@@ -4,14 +4,9 @@ import * as config from './config.js';
const NO_VISIBLE_VERDICT_SUMMARY = `검토 중입니다.\nExecution completed without a visible terminal verdict.`;
vi.mock('./agent-runner.js', () => ({
runAgentProcess: vi.fn(),
writeGroupsSnapshot: vi.fn(),
writeTasksSnapshot: vi.fn(),
}));
vi.mock('./available-groups.js', () => ({
listAvailableGroups: vi.fn(() => []),
}));
vi.mock('./config.js', () => ({
ARBITER_SERVICE_ID: null,
CLAUDE_SERVICE_ID: 'claude',

View File

@@ -79,7 +79,6 @@ export async function runAgentForGroup(
},
): Promise<'success' | 'error'> {
const { group, prompt, chatJid, runId, startSeq, endSeq, onOutput } = args;
const isMain = group.isMain === true;
const preparedExecution = await prepareMessageAgentExecutionTarget(deps, {
group,
prompt,
@@ -176,7 +175,6 @@ export async function runAgentForGroup(
groupFolder: group.folder,
chatJid,
runId,
isMain,
assistantName: deps.assistantName,
roomRoleContext,
};

View File

@@ -23,7 +23,6 @@ const makeCodexLease = (chatJid: string): EffectiveChannelLease => ({
vi.mock('./agent-runner.js', () => ({
runAgentProcess: vi.fn(),
writeGroupsSnapshot: vi.fn(),
writeTasksSnapshot: vi.fn(),
}));
@@ -3779,7 +3778,7 @@ describe('createMessageRuntime', () => {
expect(agentRunner.runAgentProcess).toHaveBeenCalledTimes(1);
});
it('processes first and follow-up messages without trigger mentions in non-main groups', async () => {
it('processes first and follow-up messages without trigger mentions', async () => {
const chatJid = 'group@test';
const group: RegisteredGroup = {
...makeGroup('codex'),

View File

@@ -1,4 +1,3 @@
import { execSync } from 'child_process';
import fs from 'fs';
import path from 'path';
@@ -26,11 +25,6 @@ export interface RestartContext {
interruptedGroups?: RestartInterruptedGroup[];
}
export interface InferredRestartContext {
chatJid: string;
lines: string[];
}
export interface RestartRecoveryCandidate {
chatJid: string;
groupFolder: string;
@@ -39,8 +33,6 @@ export interface RestartRecoveryCandidate {
pendingTasks: number;
}
const INFER_WINDOW_MS = 3 * 60 * 1000;
function getRestartContextPath(serviceId: string = SERVICE_ID): string {
return path.join(DATA_DIR, `restart-context.${serviceId}.json`);
}
@@ -52,15 +44,6 @@ function formatKoreanTimestamp(timestamp: string | number | Date): string {
});
}
function getMainGroupJid(
roomBindings: Record<string, RegisteredGroup>,
): string | null {
const mainEntry = Object.entries(roomBindings).find(
([, group]) => group.isMain === true,
);
return mainEntry?.[0] ?? null;
}
function readRestartContextFile(filePath: string): RestartContext | null {
const data = readJsonFile<RestartContext>(filePath);
if (data === null && fs.existsSync(filePath)) {
@@ -86,55 +69,7 @@ export function getRecoverableInterruptedGroups(
);
}
function getLatestDistBuildTime(): number | null {
const distDir = path.join(process.cwd(), 'dist');
if (!fs.existsSync(distDir)) return null;
let latestMtime = 0;
for (const entry of fs.readdirSync(distDir)) {
if (!entry.endsWith('.js')) continue;
const stat = fs.statSync(path.join(distDir, entry));
latestMtime = Math.max(latestMtime, stat.mtimeMs);
}
return latestMtime > 0 ? latestMtime : null;
}
function getRecentCommit(processStartedAtMs: number): string | null {
try {
const sinceSeconds = Math.max(
60,
Math.ceil(INFER_WINDOW_MS / 1000) + 30,
).toString();
const output = execSync(
`git log --since='${sinceSeconds} seconds ago' -1 --format=%h%x20%s`,
{
cwd: process.cwd(),
stdio: ['ignore', 'pipe', 'ignore'],
encoding: 'utf8',
},
).trim();
if (!output) return null;
const commitTime = execSync('git log -1 --format=%ct', {
cwd: process.cwd(),
stdio: ['ignore', 'pipe', 'ignore'],
encoding: 'utf8',
}).trim();
const commitTimeMs = Number(commitTime) * 1000;
if (
Number.isFinite(commitTimeMs) &&
commitTimeMs >= processStartedAtMs - INFER_WINDOW_MS
) {
return output;
}
} catch {
// Ignore git inference failures on deployed environments without .git.
}
return null;
}
export function writeShutdownRestartContext(
roomBindings: Record<string, RegisteredGroup>,
interruptedGroups: RestartInterruptedGroup[],
signal: string,
serviceIds: string[] = [SERVICE_ID],
@@ -145,8 +80,7 @@ export function writeShutdownRestartContext(
if (recoverableInterruptedGroups.length === 0) return [];
fs.mkdirSync(DATA_DIR, { recursive: true });
const mainChatJid =
getMainGroupJid(roomBindings) ?? interruptedGroups[0].chatJid;
const fallbackChatJid = interruptedGroups[0].chatJid;
const writtenPaths: string[] = [];
for (const serviceId of serviceIds) {
@@ -162,7 +96,7 @@ export function writeShutdownRestartContext(
);
const payload: RestartContext = {
chatJid: existing?.chatJid || mainChatJid,
chatJid: existing?.chatJid || fallbackChatJid,
summary: existing?.summary || '서비스 재시작으로 진행 중인 작업이 중단됨',
verify: existing?.verify ?? [],
writtenAt: new Date().toISOString(),
@@ -254,30 +188,3 @@ export function getInterruptedRecoveryCandidates(
return candidates;
}
export function inferRecentRestartContext(
roomBindings: Record<string, RegisteredGroup>,
processStartedAtMs: number,
): InferredRestartContext | null {
const chatJid = getMainGroupJid(roomBindings);
if (!chatJid) return null;
const latestBuildTime = getLatestDistBuildTime();
const recentCommit = getRecentCommit(processStartedAtMs);
const buildLooksRecent =
latestBuildTime !== null &&
latestBuildTime >= processStartedAtMs - INFER_WINDOW_MS;
if (!buildLooksRecent && !recentCommit) return null;
const lines = ['재시작 감지.', '- 명시적 재시작 힌트는 없어 추론 기반임.'];
if (recentCommit) {
lines.push(`- 최근 커밋: ${recentCommit}`);
}
if (latestBuildTime !== null) {
lines.push(`- 최근 빌드: ${formatKoreanTimestamp(latestBuildTime)}`);
}
lines.push(`- 시작 시각: ${formatKoreanTimestamp(processStartedAtMs)}`);
return { chatJid, lines };
}

View File

@@ -1,170 +0,0 @@
import { describe, it, expect, beforeEach } from 'vitest';
import { _initTestDatabase, storeChatMetadata } from './db.js';
import { getAvailableGroups, _setRegisteredGroups } from './index.js';
beforeEach(() => {
_initTestDatabase();
_setRegisteredGroups({});
});
// --- JID ownership patterns ---
describe('JID ownership patterns', () => {
// These test the patterns that will become ownsJid() on the Channel interface
it('WhatsApp group JID: ends with @g.us', () => {
const jid = '12345678@g.us';
expect(jid.endsWith('@g.us')).toBe(true);
});
it('WhatsApp DM JID: ends with @s.whatsapp.net', () => {
const jid = '12345678@s.whatsapp.net';
expect(jid.endsWith('@s.whatsapp.net')).toBe(true);
});
});
// --- getAvailableGroups ---
describe('getAvailableGroups', () => {
it('returns only groups, excludes DMs', () => {
storeChatMetadata(
'group1@g.us',
'2024-01-01T00:00:01.000Z',
'Group 1',
'whatsapp',
true,
);
storeChatMetadata(
'user@s.whatsapp.net',
'2024-01-01T00:00:02.000Z',
'User DM',
'whatsapp',
false,
);
storeChatMetadata(
'group2@g.us',
'2024-01-01T00:00:03.000Z',
'Group 2',
'whatsapp',
true,
);
const groups = getAvailableGroups();
expect(groups).toHaveLength(2);
expect(groups.map((g) => g.jid)).toContain('group1@g.us');
expect(groups.map((g) => g.jid)).toContain('group2@g.us');
expect(groups.map((g) => g.jid)).not.toContain('user@s.whatsapp.net');
});
it('excludes __group_sync__ sentinel', () => {
storeChatMetadata('__group_sync__', '2024-01-01T00:00:00.000Z');
storeChatMetadata(
'group@g.us',
'2024-01-01T00:00:01.000Z',
'Group',
'whatsapp',
true,
);
const groups = getAvailableGroups();
expect(groups).toHaveLength(1);
expect(groups[0].jid).toBe('group@g.us');
});
it('marks registered groups correctly', () => {
storeChatMetadata(
'reg@g.us',
'2024-01-01T00:00:01.000Z',
'Registered',
'whatsapp',
true,
);
storeChatMetadata(
'unreg@g.us',
'2024-01-01T00:00:02.000Z',
'Unregistered',
'whatsapp',
true,
);
_setRegisteredGroups({
'reg@g.us': {
name: 'Registered',
folder: 'registered',
trigger: '@Andy',
added_at: '2024-01-01T00:00:00.000Z',
},
});
const groups = getAvailableGroups();
const reg = groups.find((g) => g.jid === 'reg@g.us');
const unreg = groups.find((g) => g.jid === 'unreg@g.us');
expect(reg?.isRegistered).toBe(true);
expect(unreg?.isRegistered).toBe(false);
});
it('returns groups ordered by most recent activity', () => {
storeChatMetadata(
'old@g.us',
'2024-01-01T00:00:01.000Z',
'Old',
'whatsapp',
true,
);
storeChatMetadata(
'new@g.us',
'2024-01-01T00:00:05.000Z',
'New',
'whatsapp',
true,
);
storeChatMetadata(
'mid@g.us',
'2024-01-01T00:00:03.000Z',
'Mid',
'whatsapp',
true,
);
const groups = getAvailableGroups();
expect(groups[0].jid).toBe('new@g.us');
expect(groups[1].jid).toBe('mid@g.us');
expect(groups[2].jid).toBe('old@g.us');
});
it('excludes non-group chats regardless of JID format', () => {
// Unknown JID format stored without is_group should not appear
storeChatMetadata(
'unknown-format-123',
'2024-01-01T00:00:01.000Z',
'Unknown',
);
// Explicitly non-group with unusual JID
storeChatMetadata(
'custom:abc',
'2024-01-01T00:00:02.000Z',
'Custom DM',
'custom',
false,
);
// A real group for contrast
storeChatMetadata(
'group@g.us',
'2024-01-01T00:00:03.000Z',
'Group',
'whatsapp',
true,
);
const groups = getAvailableGroups();
expect(groups).toHaveLength(1);
expect(groups[0].jid).toBe('group@g.us');
});
it('returns empty array when no chats exist', () => {
const groups = getAvailableGroups();
expect(groups).toHaveLength(0);
});
});

View File

@@ -1,10 +1,4 @@
import fs from 'fs';
import path from 'path';
import { listAvailableGroups } from './available-groups.js';
import {
type AssignRoomInput,
assignRoom,
deleteAllSessionsForGroup,
deleteSession,
getAllRoomBindings,
@@ -13,7 +7,6 @@ import {
setRouterState,
setSession,
} from './db.js';
import { resolveGroupFolderPath } from './group-folder.js';
import { logger } from './logger.js';
import { normalizeStoredSeqCursor } from './message-cursor.js';
import type { AgentType, RegisteredGroup } from './types.js';
@@ -29,15 +22,12 @@ export interface RuntimeState {
reloadRoomBindings: () => void;
saveState: () => void;
clearSession: (groupFolder: string, opts?: { allRoles?: boolean }) => void;
assignRoomForIpc: (jid: string, input: AssignRoomInput) => void;
getAvailableGroups: () => import('./agent-runner.js').AvailableGroup[];
getLastTimestamp: () => string;
setLastTimestamp: (timestamp: string) => void;
getLastAgentTimestamps: () => Record<string, string>;
getSessions: () => Record<string, string>;
persistSession: (groupFolder: string, sessionId: string) => void;
getRoomBindings: () => Record<string, RegisteredGroup>;
setRoomBindings: (groups: Record<string, RegisteredGroup>) => void;
}
export function createRuntimeState(): RuntimeState {
@@ -111,36 +101,11 @@ export function createRuntimeState(): RuntimeState {
);
};
const assignRoomForIpc = (jid: string, input: AssignRoomInput): void => {
const assignedGroup = assignRoom(jid, input);
if (!assignedGroup) {
logger.warn({ jid }, 'Failed to assign room from IPC');
return;
}
let groupDir: string;
try {
groupDir = resolveGroupFolderPath(assignedGroup.folder);
} catch (err) {
logger.warn(
{ jid, folder: assignedGroup.folder, err },
'Rejecting room assignment with invalid folder',
);
return;
}
const { jid: _ignoredJid, ...storedGroup } = assignedGroup;
roomBindings[jid] = storedGroup;
fs.mkdirSync(path.join(groupDir, 'logs'), { recursive: true });
};
return {
loadState,
reloadRoomBindings,
saveState,
clearSession,
assignRoomForIpc,
getAvailableGroups: () => listAvailableGroups(roomBindings),
getLastTimestamp: () => lastTimestamp,
setLastTimestamp: (timestamp) => {
lastTimestamp = timestamp;
@@ -149,8 +114,5 @@ export function createRuntimeState(): RuntimeState {
getSessions: () => sessions,
persistSession,
getRoomBindings: () => roomBindings,
setRoomBindings: (groups) => {
roomBindings = groups;
},
};
}

View File

@@ -80,7 +80,6 @@ export function resolveTaskExecutionContext(
throw new Error(`Group not found: ${task.group_folder}`);
}
const isMain = group.isMain === true;
const taskAgentType =
task.agent_type || deps.serviceAgentType || 'claude-code';
const sessions = deps.getSessions();
@@ -93,7 +92,6 @@ export function resolveTaskExecutionContext(
return {
group,
groupDir,
isMain,
queueJid: getTaskQueueJid(task),
runtimeIpcDir,
runtimeTaskId,
@@ -107,13 +105,11 @@ export function resolveTaskExecutionContext(
export function writeTaskSnapshotForGroup(
taskAgentType: AgentType,
groupFolder: string,
isMain: boolean,
runtimeTaskId?: string,
): void {
const tasks = getAllTasks(taskAgentType);
writeTasksSnapshot(
groupFolder,
isMain,
tasks.map((task) => ({
id: task.id,
groupFolder: task.group_folder,

View File

@@ -27,7 +27,6 @@ export interface SchedulerDependencies {
export interface TaskExecutionContext {
group: RegisteredGroup;
groupDir: string;
isMain: boolean;
queueJid: string;
runtimeIpcDir: string;
runtimeTaskId?: string;

View File

@@ -1251,7 +1251,6 @@ Check the run.
);
expect(writeTasksSnapshotMock).toHaveBeenCalledWith(
'shared-group',
false,
expect.any(Array),
'task-watch-runtime',
);
@@ -1670,7 +1669,6 @@ Check the run.
);
expect(writeTasksSnapshotMock).toHaveBeenCalledWith(
'shared-group',
false,
expect.any(Array),
'task-isolated-runtime',
);

View File

@@ -128,7 +128,6 @@ function writeCurrentTaskSnapshot(
writeTaskSnapshotForGroup(
taskAgentType,
task.group_folder,
context.isMain,
context.runtimeTaskId,
);
}
@@ -285,7 +284,6 @@ async function runTask(
sessionId: context.sessionId,
groupFolder: task.group_folder,
chatJid: task.chat_jid,
isMain: context.isMain,
isScheduledTask: true,
runtimeTaskId: context.runtimeTaskId,
useTaskScopedSession: context.useTaskScopedSession,

View File

@@ -203,7 +203,6 @@ export interface RegisteredGroup {
added_at: string;
agentConfig?: AgentConfig;
requiresTrigger?: boolean; // Whether non-paired messages must match the room trigger
isMain?: boolean; // True for the main control group (no trigger, elevated privileges)
agentType?: AgentType;
workDir?: string; // Working directory for the agent (defaults to group folder)
}
@@ -301,8 +300,6 @@ export interface Channel {
options: DeleteRecentMessagesByContentOptions,
): Promise<number>;
sendAndTrack?(jid: string, text: string): Promise<string | null>;
// Optional: sync group/chat names from the platform.
syncGroups?(force: boolean): Promise<void>;
// Optional: get channel metadata (position, category) for ordering.
getChannelMeta?(jids: string[]): Promise<Map<string, ChannelMeta>>;
// Optional: delete all messages in a channel (used for dashboard cleanup).
@@ -315,8 +312,7 @@ export interface Channel {
export type OnInboundMessage = (chatJid: string, message: NewMessage) => void;
// Callback for chat metadata discovery.
// name is optional — channels that deliver names inline (Telegram) pass it here;
// channels that sync names separately (via syncGroups) omit it.
// name is optional — channels that do not know the name at delivery time omit it.
export type OnChatMetadata = (
chatJid: string,
timestamp: string,