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:
@@ -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',
|
||||
});
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -51,7 +51,6 @@ const input: AgentInput = {
|
||||
groupFolder: 'agent-runner-test',
|
||||
chatJid: 'dc:test',
|
||||
runId: 'run-1',
|
||||
isMain: false,
|
||||
};
|
||||
|
||||
describe('runSpawnedAgentProcess', () => {
|
||||
|
||||
@@ -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}`,
|
||||
|
||||
@@ -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,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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],
|
||||
|
||||
@@ -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',
|
||||
);
|
||||
|
||||
@@ -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),
|
||||
}));
|
||||
}
|
||||
@@ -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');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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[] };
|
||||
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -19,7 +19,6 @@ describe('getStoredRoomSettingsRowFromDatabase mode_source resilience', () => {
|
||||
folder: 'cgv-macro',
|
||||
triggerPattern: '',
|
||||
requiresTrigger: false,
|
||||
isMain: false,
|
||||
ownerAgentType: 'claude-code' as const,
|
||||
workDir: null,
|
||||
};
|
||||
|
||||
@@ -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(),
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
|
||||
@@ -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,
|
||||
);
|
||||
|
||||
|
||||
@@ -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: '',
|
||||
|
||||
60
src/index.ts
60
src/index.ts
@@ -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();
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -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':
|
||||
|
||||
@@ -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!,
|
||||
|
||||
@@ -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';
|
||||
}
|
||||
@@ -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',
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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;
|
||||
|
||||
17
src/ipc.ts
17
src/ipc.ts
@@ -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(
|
||||
|
||||
@@ -84,7 +84,6 @@ describe('message agent compact refresh', () => {
|
||||
groupFolder: 'room',
|
||||
chatJid: 'room@test',
|
||||
runId: 'run-1',
|
||||
isMain: false,
|
||||
assistantName: 'Andy',
|
||||
},
|
||||
activeRole: 'owner',
|
||||
|
||||
@@ -39,7 +39,6 @@ describe('runMessageAgentAttempt', () => {
|
||||
groupFolder: 'test',
|
||||
chatJid: 'dc:test',
|
||||
runId: 'run-test',
|
||||
isMain: false,
|
||||
assistantName: 'Andy',
|
||||
},
|
||||
activeRole: 'arbiter',
|
||||
|
||||
@@ -40,7 +40,6 @@ interface AgentInput {
|
||||
groupFolder: string;
|
||||
chatJid: string;
|
||||
runId: string;
|
||||
isMain: boolean;
|
||||
assistantName: string;
|
||||
roomRoleContext?: RoomRoleContext;
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
|
||||
@@ -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'),
|
||||
|
||||
@@ -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 };
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -27,7 +27,6 @@ export interface SchedulerDependencies {
|
||||
export interface TaskExecutionContext {
|
||||
group: RegisteredGroup;
|
||||
groupDir: string;
|
||||
isMain: boolean;
|
||||
queueJid: string;
|
||||
runtimeIpcDir: string;
|
||||
runtimeTaskId?: string;
|
||||
|
||||
@@ -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',
|
||||
);
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
Reference in New Issue
Block a user