refactor(schema): make runs.task_id nullable, delete heartbeat workaround

The NOT NULL constraint forced heartbeat runs to synthesize a fake task
row (`[Heartbeat] X — Check for work`) so the FK could resolve. Three
layers of code — acquireHeartbeatTask, findReusableHeartbeatTask,
cleanupDuplicateHeartbeatTasks, plus the is_heartbeat flag column + UI
filter — existed to paper over one bad constraint. Remove the
constraint and the whole workaround vanishes.

SQLite table rebuild with data preservation. Live production DB, no
backup — migration is atomic, idempotent, and verified before DROP.

## Migration v35 (rebuild runs with nullable task_id)

Uses `fn:` form so it can:
- Snapshot `COUNT(*) FROM runs` before copy
- Walk `PRAGMA table_info(runs)` to detect drift columns (v34 declared
  a column set; any additive ALTER since v14 shows up here)
- Assert `COUNT(*) FROM runs_new == beforeCount` before `DROP TABLE runs`
- `PRAGMA defer_foreign_keys = ON` so run_events(run_id) FK defers to
  commit time, by which runs has the same id set under the new name
- Recreate all 6 indexes on the new table

If the assertion fails, the migration throws inside the existing
`transaction()` wrapper. SQLite rolls back the whole migration, old
`runs` table is untouched, `schema_migrations` never records v35. Next
app start retries cleanly.

## Migration v36 (drop tasks.is_heartbeat + synthetic rows)

Runs now carry `task_id = NULL` for heartbeat dispatches. The
`is_heartbeat` flag is dead data going forward.

1. `UPDATE runs SET task_id = NULL WHERE task_id IN (SELECT id FROM tasks WHERE is_heartbeat = 1)`
2. `DELETE FROM tasks WHERE is_heartbeat = 1` (synthetic rows, not real work)
3. Rebuild `tasks` without the `is_heartbeat` column (same defer-FK +
   row-count-assert pattern as v35)

## Code cleanup

- `RunRecord.taskId: string | null`; `createRun` / `cancelRunForDeletion`
  / `finishRun` guard every `UPDATE tasks` path with a null-check.
- `TaskRecord.isHeartbeat` removed; every SELECT / filter / UI reference
  dropped.
- Delete `acquireHeartbeatTask` / `findReusableHeartbeatTask` /
  `cleanupDuplicateHeartbeatTasks` — dead after the constraint lifts.
- Delete `src/main/orchestration/heartbeat-task.ts` (pure workaround
  constant file).
- `heartbeat.ts` creates runs with `taskId: null` when the agent has no
  assigned work. Turn context already supports nullable task
  (heartbeatFallbackSection); prompt surface unchanged.
- `validateTaskCreation` drops the `isHeartbeat` parameter — user-
  authored + automation-authored tasks are never heartbeat.
- Renderer: `run.taskId ? taskMap.get(...) : undefined` in Dashboard /
  RunCenter / RunDetail / RunQueue.
- Delete `tests/unit/heartbeat-coalescing.test.ts` (12 tests that
  exercised the deleted DB methods).
- Drop 1 isHeartbeat-bypass test from `task-quality-gates.test.ts`.

## Grep verification

- `isHeartbeatTaskTitle src/` → 0
- `acquireHeartbeatTask src/` → migration comment only
- `is_heartbeat src/` → schema.ts migration history only
- `isHeartbeat src/` → 0

Tests: 578/578 (was 591 — delta is 13 tests that tested deleted code).
This commit is contained in:
ZacharyZhang-NY committed 2026-04-17 16:16:08 -04:00
1 parent 92795f7bfb
commit 7e1d4199ee
44 files changed
+385 -674

No files matched your search

@@ -55,13 +55,15 @@ export function finalizeRun(
});
let task: TaskRecord | null = null;
try {
task = db.getTask(run.taskId);
} catch (error) {
logger.warn(
`[finalizeRun] getTask(${run.taskId}) failed; task may have been deleted: ${error instanceof Error ? error.message : String(error)}`,
);
task = null;
if (run.taskId) {
try {
task = db.getTask(run.taskId);
} catch (error) {
logger.warn(
`[finalizeRun] getTask(${run.taskId}) failed; task may have been deleted: ${error instanceof Error ? error.message : String(error)}`,
);
task = null;
}
}
if (task) {
@@ -192,13 +194,13 @@ export function runPostCompletionAutomation(
budgetService.checkAndCreateIncidents(run.companyId, run.agentId, task?.projectId ?? null);
}
if ((event.status === "failed" || event.status === "timed_out") && !isQuitting() && !destroyed) {
if ((event.status === "failed" || event.status === "timed_out") && !isQuitting() && !destroyed && run.taskId) {
handleFailureEscalation(
{
db,
wakeAgentIfPossible,
notify: (title, body) =>
notify({ title, body, urgency: "critical", navigation: { section: "tasks", entityId: run.taskId } }),
notify({ title, body, urgency: "critical", navigation: { section: "tasks", entityId: run.taskId ?? "" } }),
logger,
},
{ taskId: run.taskId, agentId: run.agentId, companyId: run.companyId },
@@ -256,7 +258,7 @@ export function runPostCompletionAutomation(
}
// Reset retry count on successful completion
if (event.status === "succeeded") {
if (event.status === "succeeded" && run.taskId) {
handleSuccessReset(db, run.taskId, logger);
}
+3 -1
View File
@@ -36,7 +36,9 @@ export async function handleRunLog(
if (now - lastRenewal >= LEASE_RENEWAL_INTERVAL_MS) {
try {
const run = db.getRun(event.runId);
db.renewTaskLease(run.taskId, run.id);
if (run.taskId) {
db.renewTaskLease(run.taskId, run.id);
}
leaseRenewalMap.set(event.runId, now);
} catch {
// Run not found — skip lease renewal
@@ -30,7 +30,9 @@ export function handleRunStatus(
// run-started housekeeping run here.
try {
const run = db.getRun(event.runId);
db.renewTaskLease(run.taskId, run.id);
if (run.taskId) {
db.renewTaskLease(run.taskId, run.id);
}
onRunStarted?.(run.id, run.taskId, run.agentId, run.companyId);
} catch {
// Run not found — skip status handling
+5 -3
View File
@@ -24,7 +24,7 @@ export function handleWorkerExit(
const affectedCompanyIds = new Map<string, string>();
const requeueCandidates: Array<{
id: string;
taskId: string;
taskId: string | null;
agentId: string;
companyId: string;
workspaceId: string | null;
@@ -48,7 +48,9 @@ export function handleWorkerExit(
db.releaseWorkspaceLock(run.workspaceId, run.id);
}
// EXEC-02: Release execution lock on crash recovery
db.releaseTaskLock(run.taskId, run.id);
if (run.taskId) {
db.releaseTaskLock(run.taskId, run.id);
}
affectedAgentIds.add(run.agentId);
affectedCompanyIds.set(run.agentId, run.companyId);
@@ -97,7 +99,7 @@ export function handleWorkerExit(
if (candidate.workspaceId) {
db.releaseWorkspaceLock(candidate.workspaceId, candidate.id);
}
const task = db.getTask(candidate.taskId);
const task = candidate.taskId ? db.getTask(candidate.taskId) : null;
const agent = db.getAgent(candidate.agentId);
const connector = db.getConnector(agent.connectorId);
const { workspace, lockMode } = resolveWorkspaceWithLockMode(db, task, agent, candidate.companyId);
+3 -3
View File
@@ -71,7 +71,7 @@ export interface WorkerServiceDependencies {
runId: string;
companyId: string;
agent: ReturnType<AppDatabase["getAgent"]>;
task: ReturnType<AppDatabase["getTask"]>;
task: ReturnType<AppDatabase["getTask"]> | null;
connector: ReturnType<AppDatabase["getConnector"]>;
workspace: ReturnType<AppDatabase["getWorkspace"]>;
workspaceMode: "exclusive" | "shared" | "none";
@@ -81,8 +81,8 @@ export interface WorkerServiceDependencies {
trigger: string;
}) => void;
processRunCompletion: (run: RunRecord, event: z.infer<typeof workerMessageSchema> & { type: "run-finished" }) => void;
onRunStarted?: (runId: string, taskId: string, agentId: string, companyId: string) => void;
onRunCompleted?: (runId: string, taskId: string, agentId: string, companyId: string, status: string, summary: string | null, errorMessage: string | null) => void;
onRunStarted?: (runId: string, taskId: string | null, agentId: string, companyId: string) => void;
onRunCompleted?: (runId: string, taskId: string | null, agentId: string, companyId: string, status: string, summary: string | null, errorMessage: string | null) => void;
notify: (options: NotificationOptions) => void;
budgetService?: ReturnType<typeof createBudgetEnforcementService>;
sessionService?: ReturnType<typeof createSessionManagementService>;