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:
1 parent
92795f7bfb
commit
7e1d4199ee
44 files changed
+385
-674
No files matched your search
@@ -33,7 +33,6 @@ export type TaskListByStatusesRow = {
|
||||
sessionDisplayId: string | null;
|
||||
costUsd: number | null;
|
||||
requiresUserReview: boolean;
|
||||
isHeartbeat: boolean;
|
||||
startedAt: string | null;
|
||||
completedAt: string | null;
|
||||
cancelledAt: string | null;
|
||||
@@ -170,23 +169,18 @@ export function buildTaskCrudMethods(
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns actionable real work for an agent. Heartbeat tasks are
|
||||
* excluded by default since they are synthesized wake-up placeholders;
|
||||
* pass `{ includeHeartbeat: true }` to include them (heartbeat-loop
|
||||
* callers that already filter by `is_heartbeat` do not need this).
|
||||
* Returns actionable real work for an agent.
|
||||
*/
|
||||
listAgentTasks(
|
||||
agentId: string,
|
||||
companyId: string,
|
||||
statuses: string[],
|
||||
options: { includeHeartbeat?: boolean } = {},
|
||||
): TaskRecord[] {
|
||||
const placeholders = statuses.map(() => "?").join(",");
|
||||
const heartbeatClause = options.includeHeartbeat ? "" : " and is_heartbeat = 0";
|
||||
return readAll<TaskRecord>(
|
||||
`select id, company_id as companyId, project_id as projectId, goal_id as goalId, parent_id as parentId, title, description, assignee_agent_id as assigneeAgentId, workspace_id as workspaceId, status, priority, active_run_id as activeRunId, session_json as sessionJson, session_display_id as sessionDisplayId, cost_usd as costUsd, task_type as taskType, is_heartbeat as isHeartbeat, created_at as createdAt, updated_at as updatedAt
|
||||
`select id, company_id as companyId, project_id as projectId, goal_id as goalId, parent_id as parentId, title, description, assignee_agent_id as assigneeAgentId, workspace_id as workspaceId, status, priority, active_run_id as activeRunId, session_json as sessionJson, session_display_id as sessionDisplayId, cost_usd as costUsd, task_type as taskType, created_at as createdAt, updated_at as updatedAt
|
||||
from tasks
|
||||
where company_id = ? and assignee_agent_id = ? and status in (${placeholders})${heartbeatClause}
|
||||
where company_id = ? and assignee_agent_id = ? and status in (${placeholders})
|
||||
order by
|
||||
case status
|
||||
when 'in_progress' then 0
|
||||
@@ -200,21 +194,19 @@ export function buildTaskCrudMethods(
|
||||
companyId,
|
||||
agentId,
|
||||
...statuses,
|
||||
).map((t) => ({ ...t, isHeartbeat: Boolean(t.isHeartbeat) }));
|
||||
);
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns the slim task projection (id, title, status, priority) for a
|
||||
* single assignee, ordered by created_at desc. Used by the alternate
|
||||
* me/standup builder in routes-agents-standup.ts. Heartbeat tasks are
|
||||
* excluded so UI aggregations do not surface synthetic wake tasks.
|
||||
* single assignee, ordered by created_at desc.
|
||||
*/
|
||||
listAssigneeTasksForStandup(
|
||||
companyId: string,
|
||||
agentId: string,
|
||||
): Array<{ id: string; title: string; status: string; priority: string }> {
|
||||
return readAll(
|
||||
"select id, title, status, priority from tasks where company_id = ? and assignee_agent_id = ? and is_heartbeat = 0 order by created_at desc",
|
||||
"select id, title, status, priority from tasks where company_id = ? and assignee_agent_id = ? order by created_at desc",
|
||||
companyId,
|
||||
agentId,
|
||||
);
|
||||
@@ -222,9 +214,7 @@ export function buildTaskCrudMethods(
|
||||
|
||||
/**
|
||||
* Returns the slim task projection for a set of assignees. Safe on
|
||||
* an empty assignee list (returns []). Used by the alternate
|
||||
* me/standup builder to fetch reports' tasks in one query. Heartbeat
|
||||
* tasks are excluded.
|
||||
* an empty assignee list (returns []).
|
||||
*/
|
||||
listTasksForAssignees(
|
||||
companyId: string,
|
||||
@@ -239,7 +229,7 @@ export function buildTaskCrudMethods(
|
||||
if (assigneeIds.length === 0) return [];
|
||||
const placeholders = assigneeIds.map(() => "?").join(",");
|
||||
return readAll(
|
||||
`select id, title, status, priority, assignee_agent_id as assigneeAgentId from tasks where company_id = ? and assignee_agent_id in (${placeholders}) and is_heartbeat = 0 order by created_at desc`,
|
||||
`select id, title, status, priority, assignee_agent_id as assigneeAgentId from tasks where company_id = ? and assignee_agent_id in (${placeholders}) order by created_at desc`,
|
||||
companyId,
|
||||
...assigneeIds,
|
||||
);
|
||||
@@ -247,7 +237,7 @@ export function buildTaskCrudMethods(
|
||||
|
||||
/**
|
||||
* Returns the slim task projection used by the me/standup aggregation.
|
||||
* Ordered by created_at desc. Heartbeat tasks are excluded.
|
||||
* Ordered by created_at desc.
|
||||
*/
|
||||
listTasksForStandup(companyId: string): Array<{
|
||||
id: string;
|
||||
@@ -258,32 +248,26 @@ export function buildTaskCrudMethods(
|
||||
priority: string;
|
||||
}> {
|
||||
return readAll(
|
||||
"select id, company_id as companyId, title, assignee_agent_id as assigneeAgentId, status, priority from tasks where company_id = ? and is_heartbeat = 0 order by created_at desc",
|
||||
"select id, company_id as companyId, title, assignee_agent_id as assigneeAgentId, status, priority from tasks where company_id = ? order by created_at desc",
|
||||
companyId,
|
||||
);
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns tasks filtered by status. Heartbeat tasks are excluded by
|
||||
* default — they are synthesized wake placeholders and should not
|
||||
* appear in the user-facing issue list. Pass `{ includeHeartbeat: true }`
|
||||
* to include them.
|
||||
* Returns tasks filtered by status.
|
||||
*/
|
||||
listTasksByStatuses(
|
||||
companyId: string,
|
||||
statuses: string[],
|
||||
options: { includeHeartbeat?: boolean } = {},
|
||||
): TaskListByStatusesRow[] {
|
||||
const placeholders = statuses.map(() => "?").join(", ");
|
||||
const heartbeatClause = options.includeHeartbeat ? "" : " and is_heartbeat = 0";
|
||||
return readAll<TaskListByStatusesRow & { requiresUserReview: number | boolean; isHeartbeat: number | boolean }>(
|
||||
`select id, company_id as companyId, project_id as projectId, goal_id as goalId, parent_id as parentId, title, description, assignee_agent_id as assigneeAgentId, workspace_id as workspaceId, status, priority, active_run_id as activeRunId, session_json as sessionJson, session_display_id as sessionDisplayId, cost_usd as costUsd, requires_user_review as requiresUserReview, is_heartbeat as isHeartbeat, started_at as startedAt, completed_at as completedAt, cancelled_at as cancelledAt, created_at as createdAt, updated_at as updatedAt from tasks where company_id = ? and status in (${placeholders})${heartbeatClause} order by created_at desc`,
|
||||
return readAll<TaskListByStatusesRow & { requiresUserReview: number | boolean }>(
|
||||
`select id, company_id as companyId, project_id as projectId, goal_id as goalId, parent_id as parentId, title, description, assignee_agent_id as assigneeAgentId, workspace_id as workspaceId, status, priority, active_run_id as activeRunId, session_json as sessionJson, session_display_id as sessionDisplayId, cost_usd as costUsd, requires_user_review as requiresUserReview, started_at as startedAt, completed_at as completedAt, cancelled_at as cancelledAt, created_at as createdAt, updated_at as updatedAt from tasks where company_id = ? and status in (${placeholders}) order by created_at desc`,
|
||||
companyId,
|
||||
...statuses,
|
||||
).map((t) => ({
|
||||
...t,
|
||||
requiresUserReview: Boolean(t.requiresUserReview),
|
||||
isHeartbeat: Boolean(t.isHeartbeat),
|
||||
startedAt: t.startedAt ?? null,
|
||||
completedAt: t.completedAt ?? null,
|
||||
cancelledAt: t.cancelledAt ?? null,
|
||||
@@ -293,7 +277,7 @@ export function buildTaskCrudMethods(
|
||||
countActiveTasksForCompany(companyId: string): number {
|
||||
const row = getDb()
|
||||
.prepare(
|
||||
"select count(*) as cnt from tasks where company_id = ? and status not in ('done', 'cancelled') and is_heartbeat = 0",
|
||||
"select count(*) as cnt from tasks where company_id = ? and status not in ('done', 'cancelled')",
|
||||
)
|
||||
.get(companyId) as { cnt: number };
|
||||
return row.cnt;
|
||||
|
||||
Reference in new issue
Block a user