refactor: remove dead exports and orphan modules
Delete exported symbols that nothing in src/, setup/, scripts/ or runners/ references (and no test exercises), iterated to a fixed point: service-routing lease/failover helpers, paired-workspace-manager fingerprint/registration helpers, message-runtime-rules trigger helpers, utils.fetchWithTimeout, detectPnpmStorePath, isCodexMainService, isDeltaHandoffEnabledForGroup with the unused DELTA_HANDOFF config, the deprecated db/schema.applySchemaMigrations alias, unused db wrappers (memories, router state, sessions-by-agent-type, room skill override writes, recent chat/turn-output queries) and a few unused type aliases. Orphan files: src/dashboard.ts + src/dashboard-status-content.ts (only referenced each other), src/restart-context-cli.ts (never invoked) and the unused src/config/index.ts barrel. Service-handoff / channel-owner-lease code is left for a later batch. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -186,14 +186,6 @@ export function classifyRotationTrigger(
|
||||
|
||||
// ── Unified error classification ────────────────────────────────
|
||||
|
||||
export type ErrorCategory =
|
||||
| 'rate-limit'
|
||||
| 'auth-expired'
|
||||
| 'org-access-denied'
|
||||
| 'overloaded'
|
||||
| 'network-error'
|
||||
| 'none';
|
||||
|
||||
export type AgentErrorClassification =
|
||||
| {
|
||||
category: 'none';
|
||||
|
||||
@@ -14,11 +14,7 @@ import {
|
||||
} from './claude-credentials-path.js';
|
||||
import { DATA_DIR } from './config.js';
|
||||
import { logger } from './logger.js';
|
||||
import {
|
||||
getAllTokens,
|
||||
getConfiguredClaudeTokens,
|
||||
getCurrentToken,
|
||||
} from './token-rotation.js';
|
||||
import { getAllTokens, getConfiguredClaudeTokens } from './token-rotation.js';
|
||||
import { readJsonFile, writeJsonFile } from './utils.js';
|
||||
|
||||
const USAGE_CACHE_FILE = path.join(DATA_DIR, 'claude-usage-cache.json');
|
||||
@@ -423,27 +419,6 @@ async function fetchUsageForToken(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch Claude usage via the OAuth API.
|
||||
* Uses the current active token from rotation.
|
||||
*/
|
||||
export async function fetchClaudeUsage(): Promise<ClaudeUsageData | null> {
|
||||
// Prefer the access token in credentials.json when present. The static .env
|
||||
// token (CLAUDE_CODE_OAUTH_TOKEN) was issued before the `user:profile` scope
|
||||
// was required for /api/oauth/usage and so always 403s. The credentials file
|
||||
// is the canonical source written by `claude auth login` and kept fresh by
|
||||
// token-refresh.ts — its accessToken carries the full scope set.
|
||||
const credsToken = readCredentialsAccessToken(0);
|
||||
const token =
|
||||
credsToken || getCurrentToken() || getConfiguredClaudeTokens()[0];
|
||||
if (!token) {
|
||||
logger.debug('No Claude OAuth token available for usage check');
|
||||
return null;
|
||||
}
|
||||
// Pass accountIndex=0 so 401/403 → forceRefreshToken retry path engages.
|
||||
return (await fetchUsageForToken(token, 0)).usage;
|
||||
}
|
||||
|
||||
export interface ClaudeAccountProfile {
|
||||
email: string;
|
||||
planType: string; // "max", "pro", "free"
|
||||
@@ -634,6 +609,3 @@ export async function fetchAllClaudeUsage(): Promise<ClaudeAccountUsage[]> {
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
// Legacy alias
|
||||
export const fetchClaudeUsageViaCli = fetchClaudeUsage;
|
||||
|
||||
@@ -1,16 +1,7 @@
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
export type CodexConfigFeature = 'fast_mode' | 'goals';
|
||||
|
||||
export function codexConfigPath(): string {
|
||||
const override = process.env.EJCLAW_CODEX_CONFIG_PATH?.trim();
|
||||
if (override) return override;
|
||||
const home = process.env.EJCLAW_SETTINGS_HOME || os.homedir();
|
||||
return path.join(home, '.codex', 'config.toml');
|
||||
}
|
||||
|
||||
export function readCodexFeatureFromContent(
|
||||
content: string,
|
||||
feature: CodexConfigFeature,
|
||||
@@ -66,18 +57,3 @@ export function writeCodexFeatureInContent(
|
||||
}
|
||||
return `${trimmed}\n\n[features]\n${line}\n`;
|
||||
}
|
||||
|
||||
export function writeCodexFeatureToFile(
|
||||
filePath: string,
|
||||
feature: CodexConfigFeature,
|
||||
value: boolean,
|
||||
): void {
|
||||
const content = fs.existsSync(filePath)
|
||||
? fs.readFileSync(filePath, 'utf-8')
|
||||
: '';
|
||||
const updated = writeCodexFeatureInContent(content, feature, value);
|
||||
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
||||
const tempPath = `${filePath}.tmp`;
|
||||
fs.writeFileSync(tempPath, updated, { mode: 0o600 });
|
||||
fs.renameSync(tempPath, filePath);
|
||||
}
|
||||
|
||||
@@ -308,26 +308,11 @@ function loadCodexState(quiet = false): void {
|
||||
if (restoredDeadAuth) saveCodexState();
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-read the on-disk rotation state (written by any service).
|
||||
* Call before dashboard renders so the renderer picks up rotations
|
||||
* performed by the Codex service process.
|
||||
*/
|
||||
export function reloadCodexStateFromDisk(): void {
|
||||
if (accounts.length <= 1) return;
|
||||
loadCodexState(true);
|
||||
}
|
||||
|
||||
/** Get the auth.json path for the current active account. */
|
||||
export function getActiveCodexAuthPath(): string | null {
|
||||
return getCodexAuthPath();
|
||||
}
|
||||
|
||||
/** Currently active codex account index (after rotation). */
|
||||
export function getCurrentCodexAccountIndex(): number {
|
||||
return accounts.length === 0 ? 0 : currentIndex;
|
||||
}
|
||||
|
||||
/** Find the rotation-array index that owns the given auth.json path. */
|
||||
export function findCodexAccountIndexByAuthPath(
|
||||
authPath: string,
|
||||
|
||||
@@ -28,10 +28,6 @@ export function isClaudeService(serviceId: string = SERVICE_ID): boolean {
|
||||
return normalizeServiceId(serviceId) === CLAUDE_SERVICE_ID;
|
||||
}
|
||||
|
||||
export function isCodexMainService(serviceId: string = SERVICE_ID): boolean {
|
||||
return normalizeServiceId(serviceId) === CODEX_MAIN_SERVICE_ID;
|
||||
}
|
||||
|
||||
export function isReviewService(serviceId: string = SERVICE_ID): boolean {
|
||||
return normalizeServiceId(serviceId) === CODEX_REVIEW_SERVICE_ID;
|
||||
}
|
||||
@@ -152,16 +148,3 @@ const SESSION_COMMAND_ALLOWED_SENDERS = CONFIG.sessionCommands.allowedSenders;
|
||||
export function isSessionCommandSenderAllowed(sender: string): boolean {
|
||||
return SESSION_COMMAND_ALLOWED_SENDERS.has(sender);
|
||||
}
|
||||
|
||||
// Delta handoff: cross-provider session continuity with probe + fallback
|
||||
export const DELTA_HANDOFF_ENABLED = CONFIG.deltaHandoff.enabled;
|
||||
export const DELTA_HANDOFF_CANARY_GROUPS = CONFIG.deltaHandoff.canaryGroups;
|
||||
|
||||
export function isDeltaHandoffEnabledForGroup(groupFolder: string): boolean {
|
||||
if (!DELTA_HANDOFF_ENABLED) return false;
|
||||
// If canary groups are specified, only enable for those groups
|
||||
if (DELTA_HANDOFF_CANARY_GROUPS.size > 0) {
|
||||
return DELTA_HANDOFF_CANARY_GROUPS.has(groupFolder);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -1,2 +0,0 @@
|
||||
export type { AppConfig, RoleModelConfig } from './schema.js';
|
||||
export { loadConfig } from './load-config.js';
|
||||
@@ -280,14 +280,5 @@ export function loadConfig(): AppConfig {
|
||||
.filter(Boolean),
|
||||
),
|
||||
},
|
||||
deltaHandoff: {
|
||||
enabled: readText('DELTA_HANDOFF_ENABLED') === 'true',
|
||||
canaryGroups: new Set(
|
||||
(readText('DELTA_HANDOFF_CANARY_GROUPS') ?? '')
|
||||
.split(',')
|
||||
.map((value) => value.trim())
|
||||
.filter(Boolean),
|
||||
),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -93,8 +93,4 @@ export interface AppConfig {
|
||||
sessionCommands: {
|
||||
allowedSenders: Set<string>;
|
||||
};
|
||||
deltaHandoff: {
|
||||
enabled: boolean;
|
||||
canaryGroups: Set<string>;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { STATUS_SHOW_ROOMS } from './config.js';
|
||||
import type { GroupStatus } from './group-queue.js';
|
||||
|
||||
export function formatElapsed(ms: number): string {
|
||||
@@ -84,7 +83,3 @@ export function composeDashboardContent(
|
||||
);
|
||||
return parts.join('\n\n');
|
||||
}
|
||||
|
||||
export function shouldShowRoomStatus(): boolean {
|
||||
return STATUS_SHOW_ROOMS;
|
||||
}
|
||||
|
||||
@@ -1,64 +0,0 @@
|
||||
import { STATUS_SHOW_ROOM_DETAILS, STATUS_SHOW_ROOMS } from './config.js';
|
||||
import {
|
||||
composeDashboardContent,
|
||||
type DashboardRoomLine,
|
||||
getStatusLabel,
|
||||
renderCategorizedRoomSections,
|
||||
} from './dashboard-render.js';
|
||||
import type { GroupQueue } from './group-queue.js';
|
||||
import type { AgentType, Channel, RegisteredGroup } from './types.js';
|
||||
|
||||
export interface DashboardOptions {
|
||||
assistantName: string;
|
||||
channels: Channel[];
|
||||
getSessions: () => Record<string, string>;
|
||||
queue: GroupQueue;
|
||||
roomBindings: () => Record<string, RegisteredGroup>;
|
||||
statusChannelId: string;
|
||||
statusUpdateInterval: number;
|
||||
usageUpdateInterval: number;
|
||||
serviceAgentType?: AgentType;
|
||||
}
|
||||
|
||||
function getSessionLabel(sessionId: string | undefined): string {
|
||||
if (!sessionId) return '세션 없음';
|
||||
const shortId = sessionId.length > 8 ? sessionId.slice(-8) : sessionId;
|
||||
return `세션 ${shortId}`;
|
||||
}
|
||||
|
||||
export function buildStatusContent(opts: DashboardOptions): string {
|
||||
if (!STATUS_SHOW_ROOMS) return '';
|
||||
|
||||
const sessions = opts.getSessions();
|
||||
const groups = opts.roomBindings();
|
||||
const statuses = opts.queue.getStatuses(Object.keys(groups));
|
||||
|
||||
let totalActive = 0;
|
||||
let totalWaiting = 0;
|
||||
const roomLines: DashboardRoomLine[] = statuses
|
||||
.map((status) => {
|
||||
const group = groups[status.jid];
|
||||
if (!group) return null;
|
||||
if (status.status === 'processing') totalActive += 1;
|
||||
if (status.status === 'waiting') totalWaiting += 1;
|
||||
return {
|
||||
category: '기타',
|
||||
categoryPosition: 999,
|
||||
position: 999,
|
||||
line: ` **${group.name}** — ${getStatusLabel(status)} · ${getSessionLabel(sessions[group.folder])}`,
|
||||
};
|
||||
})
|
||||
.filter((line): line is DashboardRoomLine => Boolean(line));
|
||||
|
||||
const header = `**에이전트 상태** (${opts.assistantName}) — 활성 ${totalActive} | 큐대기 ${totalWaiting} | 전체 ${roomLines.length}`;
|
||||
if (!STATUS_SHOW_ROOM_DETAILS) {
|
||||
return composeDashboardContent([header]);
|
||||
}
|
||||
|
||||
return composeDashboardContent([
|
||||
`${header}\n\n${renderCategorizedRoomSections({
|
||||
lines: roomLines,
|
||||
showCategoryHeaders: false,
|
||||
})}`,
|
||||
]);
|
||||
}
|
||||
@@ -1,117 +0,0 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import type { DashboardOptions } from './dashboard-status-content.js';
|
||||
import { formatRoomName } from './unified-dashboard.js';
|
||||
|
||||
function makeOptions(sessionId?: string): DashboardOptions {
|
||||
const sessions: Record<string, string> = sessionId
|
||||
? { 'group-folder': sessionId }
|
||||
: {};
|
||||
|
||||
return {
|
||||
assistantName: 'Test',
|
||||
channels: [],
|
||||
getSessions: () => sessions,
|
||||
queue: {
|
||||
getStatuses: () => [
|
||||
{
|
||||
jid: 'dc:123',
|
||||
status: 'inactive',
|
||||
elapsedMs: null,
|
||||
pendingMessages: false,
|
||||
pendingTasks: 0,
|
||||
},
|
||||
],
|
||||
} as unknown as DashboardOptions['queue'],
|
||||
roomBindings: () => ({
|
||||
'dc:123': {
|
||||
name: 'clone-test',
|
||||
folder: 'group-folder',
|
||||
trigger: '@bot',
|
||||
added_at: '2026-03-16T00:00:00.000Z',
|
||||
},
|
||||
}),
|
||||
statusChannelId: 'status',
|
||||
statusUpdateInterval: 60000,
|
||||
usageUpdateInterval: 60000,
|
||||
};
|
||||
}
|
||||
|
||||
describe('buildStatusContent', () => {
|
||||
async function loadBuildStatusContent(
|
||||
options: {
|
||||
statusShowRooms?: string;
|
||||
statusShowRoomDetails?: string;
|
||||
} = {},
|
||||
): Promise<(opts: DashboardOptions) => string> {
|
||||
vi.resetModules();
|
||||
process.env.STATUS_SHOW_ROOMS = options.statusShowRooms ?? 'true';
|
||||
process.env.STATUS_SHOW_ROOM_DETAILS =
|
||||
options.statusShowRoomDetails ?? 'true';
|
||||
const mod = await import('./dashboard-status-content.js');
|
||||
return mod.buildStatusContent;
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
delete process.env.STATUS_SHOW_ROOMS;
|
||||
delete process.env.STATUS_SHOW_ROOM_DETAILS;
|
||||
});
|
||||
|
||||
it('shows cleared sessions as empty', async () => {
|
||||
const buildStatusContent = await loadBuildStatusContent();
|
||||
const content = buildStatusContent(makeOptions());
|
||||
expect(content).toContain('세션 없음');
|
||||
});
|
||||
|
||||
it('shows a shortened session id when a session exists', async () => {
|
||||
const buildStatusContent = await loadBuildStatusContent();
|
||||
const content = buildStatusContent(makeOptions('session-1234567890'));
|
||||
expect(content).toContain('세션 34567890');
|
||||
});
|
||||
|
||||
it('returns an empty string when room status display is disabled', async () => {
|
||||
const buildStatusContent = await loadBuildStatusContent({
|
||||
statusShowRooms: 'false',
|
||||
});
|
||||
expect(buildStatusContent(makeOptions())).toBe('');
|
||||
});
|
||||
|
||||
it('renders only the status header when room details are disabled', async () => {
|
||||
const buildStatusContent = await loadBuildStatusContent({
|
||||
statusShowRooms: 'true',
|
||||
statusShowRoomDetails: 'false',
|
||||
});
|
||||
|
||||
expect(buildStatusContent(makeOptions())).toContain('**에이전트 상태**');
|
||||
expect(buildStatusContent(makeOptions())).not.toContain('**clone-test**');
|
||||
});
|
||||
});
|
||||
|
||||
describe('formatRoomName', () => {
|
||||
it('uses the stored chat name without adding an extra Discord hash', () => {
|
||||
expect(
|
||||
formatRoomName(
|
||||
'dc:123',
|
||||
undefined,
|
||||
'registered-room-name',
|
||||
'My Server #bot-chat',
|
||||
),
|
||||
).toBe('My Server #bot-chat');
|
||||
});
|
||||
|
||||
it('adds a Discord hash for raw channel metadata names', () => {
|
||||
expect(
|
||||
formatRoomName(
|
||||
'dc:123',
|
||||
{
|
||||
name: 'bot-chat',
|
||||
position: 1,
|
||||
category: 'Bots',
|
||||
categoryPosition: 1,
|
||||
},
|
||||
'registered-room-name',
|
||||
'My Server #bot-chat',
|
||||
),
|
||||
).toBe('#bot-chat');
|
||||
});
|
||||
});
|
||||
@@ -1,31 +0,0 @@
|
||||
import {
|
||||
buildStatusContent,
|
||||
type DashboardOptions,
|
||||
} from './dashboard-status-content.js';
|
||||
import {
|
||||
purgeDashboardChannel,
|
||||
startUnifiedDashboard,
|
||||
} from './unified-dashboard.js';
|
||||
|
||||
export { buildStatusContent, purgeDashboardChannel };
|
||||
export type { DashboardOptions };
|
||||
|
||||
export async function startStatusDashboard(
|
||||
opts: DashboardOptions,
|
||||
): Promise<void> {
|
||||
await startUnifiedDashboard({
|
||||
assistantName: opts.assistantName,
|
||||
serviceId: opts.serviceAgentType === 'codex' ? 'codex-main' : 'claude',
|
||||
serviceAgentType: opts.serviceAgentType || 'claude-code',
|
||||
statusChannelId: opts.statusChannelId,
|
||||
statusUpdateInterval: opts.statusUpdateInterval,
|
||||
usageUpdateInterval: opts.usageUpdateInterval,
|
||||
channels: opts.channels,
|
||||
queue: opts.queue,
|
||||
roomBindings: opts.roomBindings,
|
||||
});
|
||||
}
|
||||
|
||||
export async function startUsageDashboard(): Promise<void> {
|
||||
// Usage dashboard is integrated into startStatusDashboard via unified dashboard.
|
||||
}
|
||||
14
src/db.ts
14
src/db.ts
@@ -6,10 +6,7 @@ export {
|
||||
} from './db/runtime-database.js';
|
||||
export {
|
||||
_setMemoryTimestampsForTests,
|
||||
archiveMemory,
|
||||
createProducedWorkItem,
|
||||
enforceMemoryBounds,
|
||||
expireStaleMemories,
|
||||
getAllChats,
|
||||
getLastHumanMessageContent,
|
||||
getLastHumanMessageSender,
|
||||
@@ -23,8 +20,6 @@ export {
|
||||
getOpenWorkItemForChat,
|
||||
getRecentDeliveredWorkItemsForChat,
|
||||
getRecentChatMessages,
|
||||
getRecentChatMessagesBatch,
|
||||
hasMessage,
|
||||
hasRecentRestartAnnouncement,
|
||||
markWorkItemDelivered,
|
||||
markWorkItemDeliveryRetry,
|
||||
@@ -32,7 +27,6 @@ export {
|
||||
rememberMemory,
|
||||
storeChatMetadata,
|
||||
storeMessage,
|
||||
touchMemories,
|
||||
} from './db/runtime-memory-messages.js';
|
||||
export {
|
||||
_deleteStoredRoomSettingsForTests,
|
||||
@@ -43,7 +37,6 @@ export {
|
||||
createTask,
|
||||
deleteAllSessionsForGroup,
|
||||
deleteSession,
|
||||
deleteStoredRoomSkillOverride,
|
||||
deleteTask,
|
||||
findDuplicateCiWatcher,
|
||||
getAllRoomBindings,
|
||||
@@ -58,22 +51,16 @@ export {
|
||||
getRegisteredAgentTypesForJid,
|
||||
getRegisteredGroup,
|
||||
getRouterState,
|
||||
getRouterStateForService,
|
||||
getSession,
|
||||
getSessionForAgentType,
|
||||
getStoredRoomRoleAgentPlan,
|
||||
getStoredRoomSettings,
|
||||
getStoredRoomSkillOverrides,
|
||||
getTaskById,
|
||||
getTasksForGroup,
|
||||
hasActiveCiWatcherForChat,
|
||||
logTaskRun,
|
||||
setExplicitRoomMode,
|
||||
setRouterState,
|
||||
setRouterStateForService,
|
||||
setSession,
|
||||
setSessionForAgentType,
|
||||
upsertStoredRoomSkillOverride,
|
||||
updateRegisteredGroupName,
|
||||
updateTask,
|
||||
updateTaskAfterRun,
|
||||
@@ -107,7 +94,6 @@ export {
|
||||
getPairedTurnAttempts,
|
||||
getPairedTurnById,
|
||||
getPairedTurnOutputs,
|
||||
getRecentPairedTurnOutputsForChat,
|
||||
getPairedTurnsForTask,
|
||||
getLatestPairedTurnForTask,
|
||||
updatePairedTurnProgressText,
|
||||
|
||||
@@ -165,16 +165,6 @@ export function touchMemoriesInDatabase(
|
||||
tx();
|
||||
}
|
||||
|
||||
export function archiveMemoryInDatabase(database: Database, id: number): void {
|
||||
database
|
||||
.prepare(
|
||||
`UPDATE memories
|
||||
SET archived_at = COALESCE(archived_at, ?)
|
||||
WHERE id = ?`,
|
||||
)
|
||||
.run(new Date().toISOString(), id);
|
||||
}
|
||||
|
||||
function buildCompactMemoryExpiryCutoff(nowIso: string): string {
|
||||
return new Date(
|
||||
new Date(nowIso).getTime() - COMPACT_MEMORY_TTL_DAYS * 24 * 60 * 60 * 1000,
|
||||
|
||||
@@ -95,17 +95,6 @@ export function getAllChatsFromDatabase(database: Database): ChatInfo[] {
|
||||
.all() as ChatInfo[];
|
||||
}
|
||||
|
||||
export function hasMessageInDatabase(
|
||||
database: Database,
|
||||
chatJid: string,
|
||||
id: string,
|
||||
): boolean {
|
||||
const row = database
|
||||
.prepare('SELECT 1 FROM messages WHERE chat_jid = ? AND id = ? LIMIT 1')
|
||||
.get(chatJid, id);
|
||||
return !!row;
|
||||
}
|
||||
|
||||
export function storeMessageInDatabase(
|
||||
database: Database,
|
||||
msg: NewMessage,
|
||||
@@ -352,44 +341,6 @@ export function getRecentChatMessagesFromDatabase(
|
||||
return rows.map(normalizeMessageRow);
|
||||
}
|
||||
|
||||
export function getRecentChatMessagesBatchFromDatabase(
|
||||
database: Database,
|
||||
chatJids: string[],
|
||||
limit: number = 8,
|
||||
): Map<string, NewMessage[]> {
|
||||
const out = new Map<string, NewMessage[]>();
|
||||
if (chatJids.length === 0) return out;
|
||||
const placeholders = chatJids.map(() => '?').join(',');
|
||||
const sql = `
|
||||
WITH ranked AS (
|
||||
SELECT id, chat_jid, sender, sender_name, content, timestamp,
|
||||
is_from_me, is_bot_message, message_source_kind,
|
||||
ROW_NUMBER() OVER (PARTITION BY chat_jid ORDER BY timestamp DESC) AS rn
|
||||
FROM messages
|
||||
WHERE chat_jid IN (${placeholders})
|
||||
AND content != '' AND content IS NOT NULL
|
||||
)
|
||||
SELECT id, chat_jid, sender, sender_name, content, timestamp,
|
||||
is_from_me, is_bot_message, message_source_kind
|
||||
FROM ranked
|
||||
WHERE rn <= ?
|
||||
ORDER BY chat_jid, timestamp ASC
|
||||
`;
|
||||
const rows = database.prepare(sql).all(...chatJids, limit) as Array<
|
||||
NewMessage & {
|
||||
is_from_me?: boolean | number;
|
||||
is_bot_message?: boolean | number;
|
||||
}
|
||||
>;
|
||||
for (const row of rows) {
|
||||
const normalized = normalizeMessageRow(row);
|
||||
const existing = out.get(normalized.chat_jid);
|
||||
if (existing) existing.push(normalized);
|
||||
else out.set(normalized.chat_jid, [normalized]);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function getLastHumanMessageTimestampFromDatabase(
|
||||
database: Database,
|
||||
chatJid: string,
|
||||
|
||||
@@ -94,32 +94,6 @@ export function getPairedTurnOutputsFromDatabase(
|
||||
.map((row) => hydratePairedTurnOutputRow(row as StoredPairedTurnOutputRow));
|
||||
}
|
||||
|
||||
const recentOutputsForChatStmtCache = new WeakMap<
|
||||
Database,
|
||||
ReturnType<Database['prepare']>
|
||||
>();
|
||||
|
||||
export function getRecentPairedTurnOutputsForChatFromDatabase(
|
||||
database: Database,
|
||||
chatJid: string,
|
||||
limit: number = 8,
|
||||
): PairedTurnOutput[] {
|
||||
let stmt = recentOutputsForChatStmtCache.get(database);
|
||||
if (!stmt) {
|
||||
stmt = database.prepare(`
|
||||
SELECT o.*
|
||||
FROM paired_turn_outputs o
|
||||
INNER JOIN paired_tasks t ON o.task_id = t.id
|
||||
WHERE t.chat_jid = ?
|
||||
ORDER BY o.created_at DESC
|
||||
LIMIT ?
|
||||
`);
|
||||
recentOutputsForChatStmtCache.set(database, stmt);
|
||||
}
|
||||
const rows = stmt.all(chatJid, limit) as StoredPairedTurnOutputRow[];
|
||||
return rows.reverse().map(hydratePairedTurnOutputRow);
|
||||
}
|
||||
|
||||
export function getLatestTurnNumberFromDatabase(
|
||||
database: Database,
|
||||
taskId: string,
|
||||
|
||||
@@ -38,14 +38,6 @@ export interface StoredRoomSkillOverride {
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface StoredRoomSkillOverrideInput {
|
||||
chatJid: string;
|
||||
agentType: AgentType;
|
||||
skillScope: string;
|
||||
skillName: string;
|
||||
enabled: boolean;
|
||||
}
|
||||
|
||||
export interface AssignRoomInput {
|
||||
name: string;
|
||||
roomMode?: RoomMode;
|
||||
@@ -384,56 +376,6 @@ export function getStoredRoomSkillOverridesFromDatabase(
|
||||
.filter((row): row is StoredRoomSkillOverride => Boolean(row));
|
||||
}
|
||||
|
||||
export function upsertStoredRoomSkillOverrideInDatabase(
|
||||
database: Database,
|
||||
input: StoredRoomSkillOverrideInput,
|
||||
): void {
|
||||
const agentType = normalizeStoredAgentType(input.agentType);
|
||||
if (!agentType) {
|
||||
throw new Error(`Unsupported agent type: ${input.agentType}`);
|
||||
}
|
||||
const now = new Date().toISOString();
|
||||
database
|
||||
.prepare(
|
||||
`INSERT INTO room_skill_overrides (
|
||||
chat_jid, agent_type, skill_scope, skill_name, enabled,
|
||||
created_at, updated_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(chat_jid, agent_type, skill_scope, skill_name)
|
||||
DO UPDATE SET
|
||||
enabled = excluded.enabled,
|
||||
updated_at = excluded.updated_at`,
|
||||
)
|
||||
.run(
|
||||
input.chatJid,
|
||||
agentType,
|
||||
input.skillScope,
|
||||
input.skillName,
|
||||
input.enabled ? 1 : 0,
|
||||
now,
|
||||
now,
|
||||
);
|
||||
}
|
||||
|
||||
export function deleteStoredRoomSkillOverrideFromDatabase(
|
||||
database: Database,
|
||||
input: Omit<StoredRoomSkillOverrideInput, 'enabled'>,
|
||||
): void {
|
||||
const agentType = normalizeStoredAgentType(input.agentType);
|
||||
if (!agentType) {
|
||||
throw new Error(`Unsupported agent type: ${input.agentType}`);
|
||||
}
|
||||
database
|
||||
.prepare(
|
||||
`DELETE FROM room_skill_overrides
|
||||
WHERE chat_jid = ?
|
||||
AND agent_type = ?
|
||||
AND skill_scope = ?
|
||||
AND skill_name = ?`,
|
||||
)
|
||||
.run(input.chatJid, agentType, input.skillScope, input.skillName);
|
||||
}
|
||||
|
||||
function getStoredRoomModeRowFromDatabase(
|
||||
database: Database,
|
||||
chatJid: string,
|
||||
|
||||
@@ -26,23 +26,6 @@ export function getRouterStateFromDatabase(
|
||||
return prefixedRow.value;
|
||||
}
|
||||
|
||||
export function getRouterStateForServiceFromDatabase(
|
||||
database: Database,
|
||||
key: string,
|
||||
serviceId: string,
|
||||
): string | undefined {
|
||||
const prefixedKey = `${normalizeServiceId(serviceId)}:${key}`;
|
||||
const row = database
|
||||
.prepare('SELECT value FROM router_state WHERE key = ?')
|
||||
.get(prefixedKey) as { value: string } | undefined;
|
||||
if (row) return row.value;
|
||||
|
||||
const canonical = database
|
||||
.prepare('SELECT value FROM router_state WHERE key = ?')
|
||||
.get(key) as { value: string } | undefined;
|
||||
return canonical?.value;
|
||||
}
|
||||
|
||||
export function setRouterStateInDatabase(
|
||||
database: Database,
|
||||
key: string,
|
||||
@@ -53,18 +36,6 @@ export function setRouterStateInDatabase(
|
||||
.run(key, value);
|
||||
}
|
||||
|
||||
export function setRouterStateForServiceInDatabase(
|
||||
database: Database,
|
||||
key: string,
|
||||
value: string,
|
||||
serviceId: string,
|
||||
): void {
|
||||
const prefixedKey = `${normalizeServiceId(serviceId)}:${key}`;
|
||||
database
|
||||
.prepare('INSERT OR REPLACE INTO router_state (key, value) VALUES (?, ?)')
|
||||
.run(prefixedKey, value);
|
||||
}
|
||||
|
||||
export function getUnsupportedRouterStateKeysFromDatabase(
|
||||
database: Database,
|
||||
): string[] {
|
||||
|
||||
@@ -7,12 +7,8 @@ import {
|
||||
type MemoryScopeKind,
|
||||
type MemorySourceKind,
|
||||
type RecallMemoryQuery,
|
||||
archiveMemoryInDatabase,
|
||||
enforceMemoryBoundsInDatabase,
|
||||
expireStaleMemoriesInDatabase,
|
||||
recallMemoriesFromDatabase,
|
||||
rememberMemoryInDatabase,
|
||||
touchMemoriesInDatabase,
|
||||
} from './memories.js';
|
||||
import {
|
||||
type ChatInfo,
|
||||
@@ -26,8 +22,6 @@ import {
|
||||
getNewMessagesBySeqFromDatabase,
|
||||
getNewMessagesFromDatabase,
|
||||
getRecentChatMessagesFromDatabase,
|
||||
getRecentChatMessagesBatchFromDatabase,
|
||||
hasMessageInDatabase,
|
||||
hasRecentRestartAnnouncementInDatabase,
|
||||
storeChatMetadataInDatabase,
|
||||
storeMessageInDatabase,
|
||||
@@ -80,29 +74,6 @@ export function _setMemoryTimestampsForTests(
|
||||
);
|
||||
}
|
||||
|
||||
export function touchMemories(ids: number[]): void {
|
||||
touchMemoriesInDatabase(requireDatabase(), ids);
|
||||
}
|
||||
|
||||
export function archiveMemory(id: number): void {
|
||||
archiveMemoryInDatabase(requireDatabase(), id);
|
||||
}
|
||||
|
||||
export function expireStaleMemories(args?: {
|
||||
scopeKind?: MemoryScopeKind;
|
||||
scopeKey?: string;
|
||||
now?: string;
|
||||
}): number {
|
||||
return expireStaleMemoriesInDatabase(requireDatabase(), args);
|
||||
}
|
||||
|
||||
export function enforceMemoryBounds(
|
||||
scopeKind: MemoryScopeKind,
|
||||
scopeKey: string,
|
||||
): void {
|
||||
enforceMemoryBoundsInDatabase(requireDatabase(), scopeKind, scopeKey);
|
||||
}
|
||||
|
||||
export function rememberMemory(input: {
|
||||
scopeKind: MemoryScopeKind;
|
||||
scopeKey: string;
|
||||
@@ -144,10 +115,6 @@ export function storeMessage(msg: NewMessage): void {
|
||||
storeMessageInDatabase(requireDatabase(), msg);
|
||||
}
|
||||
|
||||
export function hasMessage(chatJid: string, id: string): boolean {
|
||||
return hasMessageInDatabase(requireDatabase(), chatJid, id);
|
||||
}
|
||||
|
||||
export function getNewMessages(
|
||||
jids: string[],
|
||||
lastTimestamp: string,
|
||||
@@ -226,17 +193,6 @@ export function getRecentChatMessages(
|
||||
return getRecentChatMessagesFromDatabase(requireDatabase(), chatJid, limit);
|
||||
}
|
||||
|
||||
export function getRecentChatMessagesBatch(
|
||||
chatJids: string[],
|
||||
limit: number = 8,
|
||||
): Map<string, NewMessage[]> {
|
||||
return getRecentChatMessagesBatchFromDatabase(
|
||||
requireDatabase(),
|
||||
chatJids,
|
||||
limit,
|
||||
);
|
||||
}
|
||||
|
||||
export function getLastHumanMessageTimestamp(chatJid: string): string | null {
|
||||
return getLastHumanMessageTimestampFromDatabase(requireDatabase(), chatJid);
|
||||
}
|
||||
|
||||
@@ -53,7 +53,6 @@ import {
|
||||
import {
|
||||
getLatestTurnNumberFromDatabase,
|
||||
getPairedTurnOutputsFromDatabase,
|
||||
getRecentPairedTurnOutputsForChatFromDatabase,
|
||||
insertPairedTurnOutputInDatabase,
|
||||
} from './paired-turn-outputs.js';
|
||||
import {
|
||||
@@ -387,17 +386,6 @@ export function getPairedTurnOutputs(taskId: string): PairedTurnOutput[] {
|
||||
return getPairedTurnOutputsFromDatabase(requireDatabase(), taskId);
|
||||
}
|
||||
|
||||
export function getRecentPairedTurnOutputsForChat(
|
||||
chatJid: string,
|
||||
limit: number = 8,
|
||||
): PairedTurnOutput[] {
|
||||
return getRecentPairedTurnOutputsForChatFromDatabase(
|
||||
requireDatabase(),
|
||||
chatJid,
|
||||
limit,
|
||||
);
|
||||
}
|
||||
|
||||
export function getLatestTurnNumber(taskId: string): number {
|
||||
return getLatestTurnNumberFromDatabase(requireDatabase(), taskId);
|
||||
}
|
||||
|
||||
@@ -28,7 +28,6 @@ import {
|
||||
assignRoomInDatabase,
|
||||
clearExplicitRoomModeInDatabase,
|
||||
deleteStoredRoomSettingsForTestsInDatabase,
|
||||
deleteStoredRoomSkillOverrideFromDatabase,
|
||||
getAllRoomBindingsFromDatabase,
|
||||
getEffectiveRoomModeFromDatabase,
|
||||
getEffectiveRuntimeRoomModeFromDatabase,
|
||||
@@ -42,9 +41,7 @@ import {
|
||||
setRegisteredGroupForTestsInDatabase,
|
||||
setStoredRoomOwnerAgentTypeForTestsInDatabase,
|
||||
type StoredRoomSkillOverride,
|
||||
type StoredRoomSkillOverrideInput,
|
||||
updateRegisteredGroupNameInDatabase,
|
||||
upsertStoredRoomSkillOverrideInDatabase,
|
||||
} from './rooms.js';
|
||||
import { type StoredRoomSettings } from './room-registration.js';
|
||||
import {
|
||||
@@ -56,9 +53,7 @@ import {
|
||||
} from './sessions.js';
|
||||
import {
|
||||
getLastRespondingAgentTypeFromDatabase,
|
||||
getRouterStateForServiceFromDatabase,
|
||||
getRouterStateFromDatabase,
|
||||
setRouterStateForServiceInDatabase,
|
||||
setRouterStateInDatabase,
|
||||
} from './router-state.js';
|
||||
import {
|
||||
@@ -75,7 +70,6 @@ import {
|
||||
getDueTasksFromDatabase,
|
||||
getRecentConsecutiveErrorsFromDatabase,
|
||||
getTaskByIdFromDatabase,
|
||||
getTasksForGroupFromDatabase,
|
||||
hasActiveCiWatcherForChatInDatabase,
|
||||
logTaskRunInDatabase,
|
||||
updateTaskAfterRunInDatabase,
|
||||
@@ -121,17 +115,6 @@ export function findDuplicateCiWatcher(
|
||||
);
|
||||
}
|
||||
|
||||
export function getTasksForGroup(
|
||||
groupFolder: string,
|
||||
agentType?: AgentType,
|
||||
): ScheduledTask[] {
|
||||
return getTasksForGroupFromDatabase(
|
||||
requireDatabase(),
|
||||
groupFolder,
|
||||
agentType,
|
||||
);
|
||||
}
|
||||
|
||||
export function getAllTasks(agentType?: AgentType): ScheduledTask[] {
|
||||
return getAllTasksFromDatabase(requireDatabase(), agentType);
|
||||
}
|
||||
@@ -235,29 +218,10 @@ export function getRouterState(key: string): string | undefined {
|
||||
return getRouterStateFromDatabase(requireDatabase(), key, SERVICE_ID);
|
||||
}
|
||||
|
||||
export function getRouterStateForService(
|
||||
key: string,
|
||||
serviceId: string,
|
||||
): string | undefined {
|
||||
return getRouterStateForServiceFromDatabase(
|
||||
requireDatabase(),
|
||||
key,
|
||||
serviceId,
|
||||
);
|
||||
}
|
||||
|
||||
export function setRouterState(key: string, value: string): void {
|
||||
setRouterStateInDatabase(requireDatabase(), key, value);
|
||||
}
|
||||
|
||||
export function setRouterStateForService(
|
||||
key: string,
|
||||
value: string,
|
||||
serviceId: string,
|
||||
): void {
|
||||
setRouterStateForServiceInDatabase(requireDatabase(), key, value, serviceId);
|
||||
}
|
||||
|
||||
export function getSession(
|
||||
groupFolder: string,
|
||||
agentType: AgentType = 'claude-code',
|
||||
@@ -293,21 +257,6 @@ export function getAllSessions(): Record<string, string> {
|
||||
);
|
||||
}
|
||||
|
||||
export function getSessionForAgentType(
|
||||
groupFolder: string,
|
||||
agentType: string,
|
||||
): string | undefined {
|
||||
return getSessionFromDatabase(requireDatabase(), groupFolder, agentType);
|
||||
}
|
||||
|
||||
export function setSessionForAgentType(
|
||||
groupFolder: string,
|
||||
agentType: string,
|
||||
sessionId: string,
|
||||
): void {
|
||||
setSessionInDatabase(requireDatabase(), groupFolder, agentType, sessionId);
|
||||
}
|
||||
|
||||
export function getLastRespondingAgentType(
|
||||
chatJid: string,
|
||||
): AgentType | undefined {
|
||||
@@ -376,18 +325,6 @@ export function getStoredRoomSkillOverrides(
|
||||
return getStoredRoomSkillOverridesFromDatabase(db, chatJid);
|
||||
}
|
||||
|
||||
export function upsertStoredRoomSkillOverride(
|
||||
input: StoredRoomSkillOverrideInput,
|
||||
): void {
|
||||
upsertStoredRoomSkillOverrideInDatabase(requireDatabase(), input);
|
||||
}
|
||||
|
||||
export function deleteStoredRoomSkillOverride(
|
||||
input: Omit<StoredRoomSkillOverrideInput, 'enabled'>,
|
||||
): void {
|
||||
deleteStoredRoomSkillOverrideFromDatabase(requireDatabase(), input);
|
||||
}
|
||||
|
||||
export function getExplicitRoomMode(chatJid: string): RoomMode | undefined {
|
||||
return getExplicitRoomModeFromDatabase(requireDatabase(), chatJid);
|
||||
}
|
||||
|
||||
@@ -23,6 +23,3 @@ export function applyLegacySchemaMigrations(
|
||||
`ALTER TABLE work_items ADD COLUMN service_id TEXT`,
|
||||
);
|
||||
}
|
||||
|
||||
/** @deprecated New schema changes should be added under src/db/migrations/*. */
|
||||
export const applySchemaMigrations = applyLegacySchemaMigrations;
|
||||
|
||||
@@ -107,26 +107,6 @@ export function findDuplicateCiWatcherInDatabase(
|
||||
.get(chatJid, ciProvider, ciMetadata) as ScheduledTask | undefined;
|
||||
}
|
||||
|
||||
export function getTasksForGroupFromDatabase(
|
||||
database: Database,
|
||||
groupFolder: string,
|
||||
agentType?: AgentType,
|
||||
): ScheduledTask[] {
|
||||
if (agentType) {
|
||||
return database
|
||||
.prepare(
|
||||
'SELECT * FROM scheduled_tasks WHERE group_folder = ? AND agent_type = ? ORDER BY created_at DESC',
|
||||
)
|
||||
.all(groupFolder, agentType) as ScheduledTask[];
|
||||
}
|
||||
|
||||
return database
|
||||
.prepare(
|
||||
'SELECT * FROM scheduled_tasks WHERE group_folder = ? ORDER BY created_at DESC',
|
||||
)
|
||||
.all(groupFolder) as ScheduledTask[];
|
||||
}
|
||||
|
||||
export function getAllTasksFromDatabase(
|
||||
database: Database,
|
||||
agentType?: AgentType,
|
||||
|
||||
@@ -273,34 +273,6 @@ export function getOpenWorkItemFromDatabase(
|
||||
return row ? hydrateWorkItemRow(row) : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Recent delivered owner-side work items for a chat, newest last.
|
||||
* Used by single-mode prompt building to surface the bot's own prior
|
||||
* answers (which only live in work_items.result_payload) so a new turn
|
||||
* can reference what it previously said.
|
||||
*/
|
||||
export function getRecentDeliveredOwnerWorkItemsForChatFromDatabase(
|
||||
database: Database,
|
||||
chatJid: string,
|
||||
limit: number,
|
||||
): WorkItem[] {
|
||||
if (limit <= 0) {
|
||||
return [];
|
||||
}
|
||||
const rows = database
|
||||
.prepare(
|
||||
`SELECT *
|
||||
FROM work_items
|
||||
WHERE chat_jid = ?
|
||||
AND status = 'delivered'
|
||||
AND (delivery_role = 'owner' OR delivery_role IS NULL)
|
||||
ORDER BY id DESC
|
||||
LIMIT ?`,
|
||||
)
|
||||
.all(chatJid, limit) as StoredWorkItemRow[];
|
||||
return rows.map(hydrateWorkItemRow).reverse();
|
||||
}
|
||||
|
||||
export function getOpenWorkItemForChatFromDatabase(
|
||||
database: Database,
|
||||
chatJid: string,
|
||||
|
||||
@@ -170,13 +170,6 @@ export function _setRegisteredGroups(
|
||||
runtimeState.setRoomBindings(groups);
|
||||
}
|
||||
|
||||
/** @internal - exported for testing */
|
||||
export function _setRoomBindings(
|
||||
groups: Record<string, RegisteredGroup>,
|
||||
): void {
|
||||
runtimeState.setRoomBindings(groups);
|
||||
}
|
||||
|
||||
async function tryDeliverRestartAnnouncement(
|
||||
chatJid: string,
|
||||
rawText: string,
|
||||
|
||||
@@ -12,8 +12,6 @@ export {
|
||||
resolveClaudeRetryTrigger,
|
||||
resolveCodexRetryTrigger,
|
||||
type AttemptRetryAction,
|
||||
type AttemptRetryState as ExecutorAttemptState,
|
||||
type AttemptStreamedTrigger as ExecutorStreamedTrigger,
|
||||
} from './agent-attempt-retry.js';
|
||||
|
||||
export type PairedFollowUpQueueAction = 'pending' | 'none';
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { getLastHumanMessageTimestamp } from './db.js';
|
||||
import { filterProcessableMessages } from './bot-message-filter.js';
|
||||
import { normalizeStoredSeqCursor } from './message-cursor.js';
|
||||
import { isTriggerAllowed, loadSenderAllowlist } from './sender-allowlist.js';
|
||||
import { isTaskStatusControlMessage } from './task-watch-status.js';
|
||||
import { ARBITER_AGENT_TYPE, REVIEWER_AGENT_TYPE } from './config.js';
|
||||
import type { VisibleVerdict } from './paired-verdict.js';
|
||||
@@ -21,7 +20,6 @@ import {
|
||||
type NewMessage,
|
||||
type PairedRoomRole,
|
||||
type PairedTaskStatus,
|
||||
type RegisteredGroup,
|
||||
} from './types.js';
|
||||
|
||||
const BOT_COLLABORATION_WINDOW_MS = 12 * 60 * 60 * 1000;
|
||||
@@ -346,22 +344,6 @@ export function resolveConfiguredRoleAgentPlan(
|
||||
});
|
||||
}
|
||||
|
||||
/** Resolve the effective agent type for a role, considering per-role overrides. */
|
||||
export function resolveEffectiveAgentType(
|
||||
role: 'owner' | 'reviewer' | 'arbiter',
|
||||
groupAgentType: AgentType | undefined,
|
||||
reviewerAgentType: AgentType = REVIEWER_AGENT_TYPE,
|
||||
arbiterAgentType: AgentType | null | undefined = ARBITER_AGENT_TYPE,
|
||||
): AgentType {
|
||||
const plan = resolveConfiguredRoleAgentPlan(
|
||||
role !== 'owner',
|
||||
groupAgentType,
|
||||
reviewerAgentType,
|
||||
arbiterAgentType,
|
||||
);
|
||||
return resolveAgentTypeForRole(plan, role);
|
||||
}
|
||||
|
||||
/** Session folder key for a role. Owner uses groupFolder, others use groupFolder:role. */
|
||||
export function resolveSessionFolder(
|
||||
groupFolder: string,
|
||||
@@ -487,44 +469,6 @@ export function shouldSkipBotOnlyCollaboration(
|
||||
);
|
||||
}
|
||||
|
||||
export function hasAllowedTrigger(opts: {
|
||||
chatJid: string;
|
||||
messages: NewMessage[];
|
||||
group: RegisteredGroup;
|
||||
triggerPattern: RegExp;
|
||||
hasImplicitContinuationWindow: (
|
||||
chatJid: string,
|
||||
messages: NewMessage[],
|
||||
) => boolean;
|
||||
}): boolean {
|
||||
const {
|
||||
chatJid,
|
||||
messages,
|
||||
group,
|
||||
triggerPattern,
|
||||
hasImplicitContinuationWindow,
|
||||
} = opts;
|
||||
|
||||
if (group.isMain === true || group.requiresTrigger === false) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Paired rooms: bot-to-bot ping-pong doesn't need trigger patterns.
|
||||
// Peer bot messages (from reviewer/owner) are always allowed.
|
||||
if (hasReviewerLease(chatJid)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const allowlistCfg = loadSenderAllowlist();
|
||||
const hasTrigger = messages.some(
|
||||
(message) =>
|
||||
triggerPattern.test(message.content.trim()) &&
|
||||
(message.is_from_me ||
|
||||
isTriggerAllowed(chatJid, message.sender, allowlistCfg)),
|
||||
);
|
||||
return hasTrigger || hasImplicitContinuationWindow(chatJid, messages);
|
||||
}
|
||||
|
||||
export function getProcessableMessages(
|
||||
chatJid: string,
|
||||
messages: Parameters<typeof filterProcessableMessages>[0],
|
||||
|
||||
@@ -109,5 +109,3 @@ export function requestArbiterOrEscalate(args: {
|
||||
}
|
||||
return transitioned;
|
||||
}
|
||||
|
||||
export type RequestArbiterOrEscalateFn = typeof requestArbiterOrEscalate;
|
||||
|
||||
@@ -449,14 +449,6 @@ export interface PreparedPairedExecutionContext {
|
||||
blockMessage?: string;
|
||||
}
|
||||
|
||||
export interface PairedExecutionRecoveryPlan {
|
||||
task: PairedTask;
|
||||
role: RoomRoleContext['role'];
|
||||
checkpointFingerprint: string | null;
|
||||
recoveryKey: string;
|
||||
prompt: string;
|
||||
}
|
||||
|
||||
function isOwnerContinuationTurn(
|
||||
turnIdentity: PairedTurnIdentity | undefined,
|
||||
): boolean {
|
||||
|
||||
@@ -143,6 +143,3 @@ export function applyPairedTaskPatch(args: {
|
||||
}
|
||||
return updated;
|
||||
}
|
||||
|
||||
export type TransitionPairedTaskStatusFn = typeof transitionPairedTaskStatus;
|
||||
export type ApplyPairedTaskPatchFn = typeof applyPairedTaskPatch;
|
||||
|
||||
@@ -483,19 +483,6 @@ function listAllowedUntrackedFiles(sourceDir: string): string[] {
|
||||
]).filter(shouldIncludeUntrackedReviewerPath);
|
||||
}
|
||||
|
||||
function listReviewableTrackedDiffFiles(
|
||||
sourceDir: string,
|
||||
sourceRef: string,
|
||||
): string[] {
|
||||
return listGitPaths(sourceDir, [
|
||||
'diff',
|
||||
'--name-only',
|
||||
'-z',
|
||||
sourceRef,
|
||||
'--',
|
||||
]).filter((relativePath) => !isReviewerSnapshotDeniedPath(relativePath));
|
||||
}
|
||||
|
||||
function copySnapshotPaths(
|
||||
sourceDir: string,
|
||||
targetDir: string,
|
||||
@@ -696,76 +683,6 @@ function makeWorkspaceRecord(args: {
|
||||
};
|
||||
}
|
||||
|
||||
export function resolvePairedTaskSourceFingerprint(
|
||||
taskId: string,
|
||||
): string | null {
|
||||
const { task } = getTaskAndProject(taskId);
|
||||
const ownerWorkspace = getPairedWorkspace(taskId, 'owner');
|
||||
if (!ownerWorkspace) {
|
||||
return task.source_ref || null;
|
||||
}
|
||||
|
||||
ensureGitRepository(ownerWorkspace.workspace_dir);
|
||||
return buildReviewerSnapshotFingerprint({
|
||||
sourceDir: ownerWorkspace.workspace_dir,
|
||||
allowedTrackedFiles: listAllowedTrackedFiles(ownerWorkspace.workspace_dir),
|
||||
deletedTrackedFiles: listDeletedTrackedFiles(ownerWorkspace.workspace_dir),
|
||||
allowedUntrackedFiles: listAllowedUntrackedFiles(
|
||||
ownerWorkspace.workspace_dir,
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
export function hasReviewableOwnerWorkspaceChanges(taskId: string): boolean {
|
||||
const { task } = getTaskAndProject(taskId);
|
||||
const ownerWorkspace = getPairedWorkspace(taskId, 'owner');
|
||||
if (!ownerWorkspace) {
|
||||
return false;
|
||||
}
|
||||
|
||||
ensureGitRepository(ownerWorkspace.workspace_dir);
|
||||
const reviewableTrackedDiffs = listReviewableTrackedDiffFiles(
|
||||
ownerWorkspace.workspace_dir,
|
||||
task.source_ref || 'HEAD',
|
||||
);
|
||||
if (reviewableTrackedDiffs.length > 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return listAllowedUntrackedFiles(ownerWorkspace.workspace_dir).length > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the canonical project directory as the owner workspace.
|
||||
* No worktree is created — the owner works directly on the live project.
|
||||
* This preserves the Claude SDK session across tasks (same project path).
|
||||
*/
|
||||
export function registerOwnerCanonicalWorkspace(
|
||||
taskId: string,
|
||||
canonicalWorkDir: string,
|
||||
): PairedWorkspace {
|
||||
ensureGitRepository(canonicalWorkDir);
|
||||
const installResult = ensureWorkspaceDependenciesInstalled(canonicalWorkDir);
|
||||
if (installResult.installed) {
|
||||
logger.info(
|
||||
{
|
||||
taskId,
|
||||
workspaceDir: canonicalWorkDir,
|
||||
packageManager: installResult.packageManager,
|
||||
command: installResult.commandText ?? null,
|
||||
},
|
||||
'Installed owner workspace dependencies',
|
||||
);
|
||||
}
|
||||
const workspace = makeWorkspaceRecord({
|
||||
taskId,
|
||||
role: 'owner',
|
||||
workspaceDir: canonicalWorkDir,
|
||||
});
|
||||
upsertPairedWorkspace(workspace);
|
||||
return workspace;
|
||||
}
|
||||
|
||||
export function provisionOwnerWorkspaceForPairedTask(
|
||||
taskId: string,
|
||||
): PairedWorkspace {
|
||||
|
||||
@@ -1,70 +0,0 @@
|
||||
import { SERVICE_ID } from './config.js';
|
||||
import { writeRestartContext } from './restart-context.js';
|
||||
|
||||
function printUsageAndExit(): never {
|
||||
console.error(
|
||||
[
|
||||
'Usage:',
|
||||
' bun src/restart-context-cli.ts write --chat-jid <jid> --summary <text> [--verify <text> ...] [--service-id <id> ...]',
|
||||
].join('\n'),
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const [, , command, ...args] = process.argv;
|
||||
if (command !== 'write') {
|
||||
printUsageAndExit();
|
||||
}
|
||||
|
||||
let chatJid = '';
|
||||
let summary = '';
|
||||
const verify: string[] = [];
|
||||
const serviceIds: string[] = [];
|
||||
|
||||
for (let i = 0; i < args.length; i += 1) {
|
||||
const arg = args[i];
|
||||
const value = args[i + 1];
|
||||
if (!value) {
|
||||
printUsageAndExit();
|
||||
}
|
||||
|
||||
if (arg === '--chat-jid' || arg === '--jid') {
|
||||
chatJid = value;
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (arg === '--summary') {
|
||||
summary = value;
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (arg === '--verify') {
|
||||
verify.push(value);
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (arg === '--service-id') {
|
||||
serviceIds.push(value);
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
printUsageAndExit();
|
||||
}
|
||||
|
||||
if (!chatJid || !summary) {
|
||||
printUsageAndExit();
|
||||
}
|
||||
|
||||
const written = writeRestartContext(
|
||||
{
|
||||
chatJid,
|
||||
summary,
|
||||
verify,
|
||||
},
|
||||
serviceIds.length > 0 ? serviceIds : [SERVICE_ID],
|
||||
);
|
||||
|
||||
for (const filePath of written) {
|
||||
console.log(filePath);
|
||||
}
|
||||
@@ -133,26 +133,6 @@ function getRecentCommit(processStartedAtMs: number): string | null {
|
||||
return null;
|
||||
}
|
||||
|
||||
export function writeRestartContext(
|
||||
context: Omit<RestartContext, 'writtenAt'>,
|
||||
serviceIds: string[] = [SERVICE_ID],
|
||||
): string[] {
|
||||
fs.mkdirSync(DATA_DIR, { recursive: true });
|
||||
const payload: RestartContext = {
|
||||
...context,
|
||||
verify: context.verify,
|
||||
writtenAt: new Date().toISOString(),
|
||||
};
|
||||
|
||||
const writtenPaths: string[] = [];
|
||||
for (const serviceId of serviceIds) {
|
||||
const filePath = getRestartContextPath(serviceId);
|
||||
writeJsonFile(filePath, payload, true);
|
||||
writtenPaths.push(filePath);
|
||||
}
|
||||
return writtenPaths;
|
||||
}
|
||||
|
||||
export function writeShutdownRestartContext(
|
||||
roomBindings: Record<string, RegisteredGroup>,
|
||||
interruptedGroups: RestartInterruptedGroup[],
|
||||
|
||||
@@ -9,7 +9,6 @@ import {
|
||||
normalizeServiceId,
|
||||
} from './config.js';
|
||||
import {
|
||||
clearChannelOwnerLease,
|
||||
getAllChannelOwnerLeases,
|
||||
getEffectiveRuntimeRoomMode,
|
||||
getStoredRoomRoleAgentPlan,
|
||||
@@ -253,26 +252,6 @@ export function resolveLeaseServiceId(
|
||||
}
|
||||
}
|
||||
|
||||
export function isOwnerServiceForChat(
|
||||
chatJid: string,
|
||||
serviceId: string = SERVICE_ID,
|
||||
): boolean {
|
||||
const lease = getEffectiveChannelLease(chatJid);
|
||||
return (
|
||||
normalizeServiceId(serviceId) === resolveLeaseServiceId(lease, 'owner')
|
||||
);
|
||||
}
|
||||
|
||||
export function isReviewerServiceForChat(
|
||||
chatJid: string,
|
||||
serviceId: string = SERVICE_ID,
|
||||
): boolean {
|
||||
const lease = getEffectiveChannelLease(chatJid);
|
||||
return (
|
||||
normalizeServiceId(serviceId) === resolveLeaseServiceId(lease, 'reviewer')
|
||||
);
|
||||
}
|
||||
|
||||
export function hasReviewerLease(chatJid: string): boolean {
|
||||
return (
|
||||
resolveLeaseServiceId(getEffectiveChannelLease(chatJid), 'reviewer') !==
|
||||
@@ -280,16 +259,6 @@ export function hasReviewerLease(chatJid: string): boolean {
|
||||
);
|
||||
}
|
||||
|
||||
export function isArbiterServiceForChat(
|
||||
chatJid: string,
|
||||
serviceId: string = SERVICE_ID,
|
||||
): boolean {
|
||||
const lease = getEffectiveChannelLease(chatJid);
|
||||
return (
|
||||
normalizeServiceId(serviceId) === resolveLeaseServiceId(lease, 'arbiter')
|
||||
);
|
||||
}
|
||||
|
||||
export function shouldServiceProcessChat(
|
||||
_chatJid: string,
|
||||
_serviceId: string = SERVICE_ID,
|
||||
@@ -314,10 +283,6 @@ export function activateCodexFailover(_chatJid: string, reason: string): void {
|
||||
);
|
||||
}
|
||||
|
||||
export function isGlobalFailoverActive(): boolean {
|
||||
return globalFailoverActive;
|
||||
}
|
||||
|
||||
export function getGlobalFailoverInfo(): {
|
||||
active: boolean;
|
||||
reason: string | null;
|
||||
@@ -337,27 +302,3 @@ export function clearGlobalFailover(): void {
|
||||
globalFailoverActivatedAt = null;
|
||||
logger.info('Global failover cleared — resuming normal owner routing');
|
||||
}
|
||||
|
||||
export function restoreDefaultChannelLease(chatJid: string): void {
|
||||
clearChannelOwnerLease(chatJid);
|
||||
leaseCache.delete(chatJid);
|
||||
lastLeaseRefreshAt = Date.now();
|
||||
}
|
||||
|
||||
export interface ActiveFailoverLease {
|
||||
chatJid: string;
|
||||
activatedAt: string | null;
|
||||
}
|
||||
|
||||
export function getActiveCodexFailoverLeases(): ActiveFailoverLease[] {
|
||||
// Global failover: report as a single pseudo-lease
|
||||
if (globalFailoverActive) {
|
||||
return [{ chatJid: '*', activatedAt: globalFailoverActivatedAt }];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
/** @deprecated Use getActiveCodexFailoverLeases() instead */
|
||||
export function getActiveCodexFailoverChatJids(): string[] {
|
||||
return getActiveCodexFailoverLeases().map((l) => l.chatJid);
|
||||
}
|
||||
|
||||
@@ -41,8 +41,6 @@ export type AgentOutputPhase =
|
||||
/** Phase as visible in the UI (mapped from AgentOutputPhase). */
|
||||
export type VisiblePhase = 'silent' | 'progress' | 'final';
|
||||
|
||||
export type AgentVisibility = 'public' | 'silent';
|
||||
|
||||
export interface OutboundAttachment {
|
||||
path: string;
|
||||
name?: string;
|
||||
@@ -166,8 +164,6 @@ export interface PairedWorkspace {
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export type AgentResponsePolicy = 'normal' | 'silent-unless-addressed';
|
||||
|
||||
export type StructuredAgentOutput =
|
||||
| {
|
||||
visibility: 'public';
|
||||
|
||||
@@ -219,10 +219,3 @@ export function startUsagePrimer(): void {
|
||||
};
|
||||
scheduleNext();
|
||||
}
|
||||
|
||||
export function stopUsagePrimer(): void {
|
||||
if (primerTimer) {
|
||||
clearTimeout(primerTimer);
|
||||
primerTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
15
src/utils.ts
15
src/utils.ts
@@ -38,21 +38,6 @@ export function writeJsonFile(
|
||||
|
||||
// ── Fetch with timeout ──────────────────────────────────────────
|
||||
|
||||
/** Wrapper around fetch() that aborts after timeoutMs. */
|
||||
export async function fetchWithTimeout(
|
||||
url: string,
|
||||
init: RequestInit,
|
||||
timeoutMs: number,
|
||||
): Promise<Response> {
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
||||
try {
|
||||
return await fetch(url, { ...init, signal: controller.signal });
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Time formatting ─────────────────────────────────────────────
|
||||
|
||||
/** Format milliseconds as Korean elapsed time (e.g. "1시간 2분 30초"). */
|
||||
|
||||
@@ -553,42 +553,3 @@ export function ensureWorkspaceDependenciesInstalled(
|
||||
commandText: command.commandText,
|
||||
};
|
||||
}
|
||||
|
||||
export function detectPnpmStorePath(workspaceDir: string): string | null {
|
||||
if (detectWorkspacePackageManager(workspaceDir) !== 'pnpm') {
|
||||
return null;
|
||||
}
|
||||
if (process.env.PNPM_STORE_DIR && fs.existsSync(process.env.PNPM_STORE_DIR)) {
|
||||
return process.env.PNPM_STORE_DIR;
|
||||
}
|
||||
|
||||
const candidates: Array<[string, string[]]> = [
|
||||
['pnpm', ['store', 'path']],
|
||||
['corepack', ['pnpm', 'store', 'path']],
|
||||
];
|
||||
for (const [file, args] of candidates) {
|
||||
try {
|
||||
const storePath = execFileSync(file, args, {
|
||||
cwd: workspaceDir,
|
||||
env: buildWorkspaceCommandEnvironment(workspaceDir, 'pnpm'),
|
||||
encoding: 'utf-8',
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
timeout: 5000,
|
||||
}).trim();
|
||||
if (storePath && fs.existsSync(storePath)) {
|
||||
return storePath;
|
||||
}
|
||||
} catch {
|
||||
// Try the next candidate.
|
||||
}
|
||||
}
|
||||
|
||||
const defaultStore = path.join(
|
||||
process.env.HOME || '',
|
||||
'.local',
|
||||
'share',
|
||||
'pnpm',
|
||||
'store',
|
||||
);
|
||||
return fs.existsSync(defaultStore) ? defaultStore : null;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user