refactor(scheduler): split 15s tick into 4 independent intervals

Split the single 15s setInterval in scheduler.ts (6 serial jobs) into 4
independent schedulers so a slow job no longer stalls the others:

- scheduler-heartbeat.ts (15s): wake eligible agents, CEO bootstrap,
  schedule automation trigger
- scheduler-lock-recovery.ts (60s): stale task-lock recovery and stale
  workspace-lock release
- scheduler-idle-automation.ts (60s): idle-agent automation dispatch
- scheduler-housekeeping.ts (300s): monthly budget reset, expired budget
  incident auto-close, stale review sweep, expired wakeup purge

scheduler.ts is now a thin composer exposing startAllSchedulers /
stopAllSchedulers. Bootstrap and service-graph updated accordingly.
Business logic, error isolation, and atomic actions preserved.
This commit is contained in:
ZacharyZhang-NY committed 2026-04-16 21:47:09 -04:00
1 parent 2676400e0c
commit f8052c3741
8 files changed
+307 -173

No files matched your search

@@ -0,0 +1,50 @@
import type { OrchestrationDependencies } from "./types";
export function createIdleAutomationScheduler(deps: OrchestrationDependencies) {
const { db, logger, dispatchAutomation, hasWorkerReady, isQuitting } = deps;
let timer: ReturnType<typeof setInterval> | null = null;
function start() {
if (timer) clearInterval(timer);
timer = setInterval(() => {
try {
if (isQuitting() || !hasWorkerReady()) return;
const activeCompanies = db.listActiveCompanyIds();
const now = Date.now();
for (const company of activeCompanies) {
try {
const companyAgents = db.listActiveAgentsForCompany(company.id);
for (const agent of companyAgents) {
if (!db.hasAgentAssignedTasks(agent.id, company.id)) {
const lastActive = agent.lastHeartbeatAt ? new Date(agent.lastHeartbeatAt).getTime() : 0;
const idleThreshold = 20 * 60 * 1000;
if (now - lastActive > idleThreshold) {
dispatchAutomation("agent_idle", {
companyId: company.id,
agentId: agent.id,
department: agent.department ?? undefined,
});
}
}
}
} catch (error) {
logger.error(`[idle-automation] Error processing company ${company.id}: ${error instanceof Error ? error.message : String(error)}`);
}
}
} catch (error) {
logger.error(`[idle-automation] Scheduler error: ${error instanceof Error ? error.message : String(error)}`);
}
}, 60_000);
}
function stop() {
if (timer) clearInterval(timer);
timer = null;
}
return { start, stop };
}