Files
EJClaw/src/restart-context.ts
Codex f127ac7a2b 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>
2026-10-01 19:37:29 +09:00

191 lines
5.7 KiB
TypeScript

import fs from 'fs';
import path from 'path';
import { DATA_DIR, SERVICE_ID, TIMEZONE } from './config.js';
import { logger } from './logger.js';
import type { RegisteredGroup } from './types.js';
import { readJsonFile, writeJsonFile } from './utils.js';
export interface RestartInterruptedGroup {
chatJid: string;
groupName: string;
status: 'processing' | 'idle' | 'waiting';
elapsedMs: number | null;
pendingMessages: boolean;
pendingTasks: number;
}
export interface RestartContext {
chatJid: string;
summary: string;
verify: string[];
writtenAt: string;
source?: 'explicit' | 'shutdown-snapshot';
signal?: string;
interruptedGroups?: RestartInterruptedGroup[];
}
export interface RestartRecoveryCandidate {
chatJid: string;
groupFolder: string;
status: RestartInterruptedGroup['status'];
pendingMessages: boolean;
pendingTasks: number;
}
function getRestartContextPath(serviceId: string = SERVICE_ID): string {
return path.join(DATA_DIR, `restart-context.${serviceId}.json`);
}
function formatKoreanTimestamp(timestamp: string | number | Date): string {
return new Date(timestamp).toLocaleString('ko-KR', {
timeZone: TIMEZONE,
hour12: false,
});
}
function readRestartContextFile(filePath: string): RestartContext | null {
const data = readJsonFile<RestartContext>(filePath);
if (data === null && fs.existsSync(filePath)) {
logger.warn(
{ filePath },
'Failed to parse restart context file; ignoring invalid content',
);
}
return data;
}
function isRecoverableInterruptedGroup(
group: RestartInterruptedGroup,
): boolean {
return group.status === 'processing';
}
export function getRecoverableInterruptedGroups(
context: Pick<RestartContext, 'interruptedGroups'> | null,
): RestartInterruptedGroup[] {
return (context?.interruptedGroups ?? []).filter(
isRecoverableInterruptedGroup,
);
}
export function writeShutdownRestartContext(
interruptedGroups: RestartInterruptedGroup[],
signal: string,
serviceIds: string[] = [SERVICE_ID],
): string[] {
const recoverableInterruptedGroups = interruptedGroups.filter(
isRecoverableInterruptedGroup,
);
if (recoverableInterruptedGroups.length === 0) return [];
fs.mkdirSync(DATA_DIR, { recursive: true });
const fallbackChatJid = interruptedGroups[0].chatJid;
const writtenPaths: string[] = [];
for (const serviceId of serviceIds) {
const filePath = getRestartContextPath(serviceId);
const existing = readRestartContextFile(filePath);
const mergedInterrupted = [
...getRecoverableInterruptedGroups(existing),
...recoverableInterruptedGroups,
].filter(
(group, index, all) =>
all.findIndex((candidate) => candidate.chatJid === group.chatJid) ===
index,
);
const payload: RestartContext = {
chatJid: existing?.chatJid || fallbackChatJid,
summary: existing?.summary || '서비스 재시작으로 진행 중인 작업이 중단됨',
verify: existing?.verify ?? [],
writtenAt: new Date().toISOString(),
source: existing?.source || 'shutdown-snapshot',
signal,
interruptedGroups: mergedInterrupted,
};
writeJsonFile(filePath, payload, true);
writtenPaths.push(filePath);
}
return writtenPaths;
}
export function buildInterruptedRestartAnnouncement(
interrupted: RestartInterruptedGroup,
): string {
const lines = ['서비스 재시작으로 이전 작업이 중단됐습니다.'];
lines.push(`- 직전 상태: ${interrupted.status}`);
if (interrupted.elapsedMs !== null) {
lines.push(
`- 직전 실행 시간: ${Math.round(interrupted.elapsedMs / 1000)}초`,
);
}
if (interrupted.pendingMessages) {
lines.push('- 미처리 메시지가 남아 있었음');
}
if (interrupted.pendingTasks > 0) {
lines.push(`- 대기 태스크: ${interrupted.pendingTasks}개`);
}
lines.push('- 필요하면 이어서 요청해 주세요.');
return lines.join('\n');
}
export function consumeRestartContext(): RestartContext | null {
const filePath = getRestartContextPath();
if (!fs.existsSync(filePath)) return null;
const parsed = readJsonFile<RestartContext>(filePath);
if (!parsed) {
logger.warn(
{ filePath },
'Failed to read restart context; removing invalid file',
);
}
try {
fs.unlinkSync(filePath);
} catch {
// Ignore cleanup failure.
}
return parsed;
}
export function buildRestartAnnouncement(context: RestartContext): string {
const lines = ['재시작 완료.', `- 변경: ${context.summary}`];
const recoverableInterruptedGroups = getRecoverableInterruptedGroups(context);
if (recoverableInterruptedGroups.length > 0) {
lines.push(`- 중단 작업 감지: ${recoverableInterruptedGroups.length}개`);
}
if (context.verify.length > 0) {
lines.push(`- 검증: ${context.verify.join(', ')}`);
}
lines.push(`- 기록 시각: ${formatKoreanTimestamp(context.writtenAt)}`);
return lines.join('\n');
}
export function getInterruptedRecoveryCandidates(
context: RestartContext | null,
roomBindings: Record<string, RegisteredGroup>,
): RestartRecoveryCandidate[] {
if (!context?.interruptedGroups?.length) return [];
const seen = new Set<string>();
const candidates: RestartRecoveryCandidate[] = [];
for (const interrupted of getRecoverableInterruptedGroups(context)) {
if (seen.has(interrupted.chatJid)) continue;
const group = roomBindings[interrupted.chatJid];
if (!group) continue;
seen.add(interrupted.chatJid);
candidates.push({
chatJid: interrupted.chatJid,
groupFolder: group.folder,
status: interrupted.status,
pendingMessages: interrupted.pendingMessages,
pendingTasks: interrupted.pendingTasks,
});
}
return candidates;
}