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
@@ -26,7 +26,7 @@ export function buildAgentCrudMethods(
|
||||
createdByAgentId?: string | null;
|
||||
createdByUserId?: string | null;
|
||||
}) => string;
|
||||
cancelRunForDeletion: (runId: string, taskId: string, workspaceId: string | null, summary: string) => void;
|
||||
cancelRunForDeletion: (runId: string, taskId: string | null, workspaceId: string | null, summary: string) => void;
|
||||
addActivity: (input: { companyId: string; actor: string; action: string; entityType: string; entityId: string; detail: string }) => void;
|
||||
},
|
||||
) {
|
||||
@@ -159,7 +159,7 @@ export function buildAgentCrudMethods(
|
||||
},
|
||||
|
||||
deleteAgent(id: string, companyId: string): void {
|
||||
const activeAgentRuns = readAll<{ id: string; taskId: string; workspaceId: string | null }>(
|
||||
const activeAgentRuns = readAll<{ id: string; taskId: string | null; workspaceId: string | null }>(
|
||||
"select id, task_id as taskId, workspace_id as workspaceId from runs where agent_id = ? and company_id = ? and status in ('queued', 'running')",
|
||||
id,
|
||||
companyId,
|
||||
|
||||
@@ -22,7 +22,7 @@ export function buildAgentMethods(
|
||||
createdByAgentId?: string | null;
|
||||
createdByUserId?: string | null;
|
||||
}) => string;
|
||||
cancelRunForDeletion: (runId: string, taskId: string, workspaceId: string | null, summary: string) => void;
|
||||
cancelRunForDeletion: (runId: string, taskId: string | null, workspaceId: string | null, summary: string) => void;
|
||||
addActivity: (input: { companyId: string; actor: string; action: string; entityType: string; entityId: string; detail: string }) => void;
|
||||
},
|
||||
) {
|
||||
|
||||
@@ -49,12 +49,11 @@ export function buildEntityCrudMethods(
|
||||
getTask(id: string): TaskRecord {
|
||||
const row = getDb()
|
||||
.prepare(
|
||||
"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, 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 id = ?",
|
||||
"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, 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 id = ?",
|
||||
)
|
||||
.get(id) as TaskRecord | undefined;
|
||||
if (!row) throw new Error(`Task not found: ${id}`);
|
||||
row.requiresUserReview = Boolean(row.requiresUserReview);
|
||||
row.isHeartbeat = Boolean(row.isHeartbeat);
|
||||
row.startedAt = row.startedAt ?? null;
|
||||
row.completedAt = row.completedAt ?? null;
|
||||
row.cancelledAt = row.cancelledAt ?? null;
|
||||
|
||||
+23
-15
@@ -60,7 +60,7 @@ export function buildRunMethods(
|
||||
createRun(input: {
|
||||
id?: string;
|
||||
companyId: string;
|
||||
taskId: string;
|
||||
taskId: string | null;
|
||||
agentId: string;
|
||||
workspaceId: string | null;
|
||||
connectorId: ConnectorId;
|
||||
@@ -74,7 +74,9 @@ export function buildRunMethods(
|
||||
"insert into runs (id, company_id, task_id, agent_id, workspace_id, connector_id, status, summary, unattributed_cost, log_path, created_at, updated_at) values (?, ?, ?, ?, ?, ?, 'queued', '', 0, ?, ?, ?)",
|
||||
)
|
||||
.run(id, input.companyId, input.taskId, input.agentId, input.workspaceId, input.connectorId, logPath, ts, ts);
|
||||
getDb().prepare("update tasks set active_run_id = ?, updated_at = ? where id = ?").run(id, ts, input.taskId);
|
||||
if (input.taskId !== null) {
|
||||
getDb().prepare("update tasks set active_run_id = ?, updated_at = ? where id = ?").run(id, ts, input.taskId);
|
||||
}
|
||||
});
|
||||
writeFileSync(logPath, "", "utf8");
|
||||
return { id, logPath };
|
||||
@@ -163,7 +165,7 @@ export function buildRunMethods(
|
||||
unattributedCost: boolean;
|
||||
}) {
|
||||
const run = getDb().prepare("select task_id as taskId, agent_id as agentId, company_id as companyId, connector_id as connectorId from runs where id = ?").get(input.runId) as
|
||||
| { taskId: string; agentId: string; companyId: string; connectorId: ConnectorId }
|
||||
| { taskId: string | null; agentId: string; companyId: string; connectorId: ConnectorId }
|
||||
| undefined;
|
||||
if (!run) return { budgetHardStopped: false };
|
||||
const ts = nowIso();
|
||||
@@ -198,14 +200,18 @@ export function buildRunMethods(
|
||||
input.signal, input.model, input.sessionDisplayId, runCostUsd,
|
||||
input.unattributedCost ? 1 : 0, ts, ts, input.runId,
|
||||
);
|
||||
getDb().prepare("update tasks set active_run_id = null, updated_at = ? where id = ?").run(ts, run.taskId);
|
||||
getDb()
|
||||
.prepare("UPDATE tasks SET checkout_run_id = NULL, execution_locked_at = NULL, updated_at = ? WHERE id = ? AND checkout_run_id = ?")
|
||||
.run(ts, run.taskId, input.runId);
|
||||
if (runCostUsd > 0) {
|
||||
if (run.taskId !== null) {
|
||||
getDb().prepare("update tasks set active_run_id = null, updated_at = ? where id = ?").run(ts, run.taskId);
|
||||
getDb()
|
||||
.prepare("update tasks set cost_usd = cost_usd + ?, updated_at = ? where id = ?")
|
||||
.run(runCostUsd, ts, run.taskId);
|
||||
.prepare("UPDATE tasks SET checkout_run_id = NULL, execution_locked_at = NULL, updated_at = ? WHERE id = ? AND checkout_run_id = ?")
|
||||
.run(ts, run.taskId, input.runId);
|
||||
}
|
||||
if (runCostUsd > 0) {
|
||||
if (run.taskId !== null) {
|
||||
getDb()
|
||||
.prepare("update tasks set cost_usd = cost_usd + ?, updated_at = ? where id = ?")
|
||||
.run(runCostUsd, ts, run.taskId);
|
||||
}
|
||||
getDb()
|
||||
.prepare("update agents set spent_monthly_usd = spent_monthly_usd + ?, updated_at = ? where id = ?")
|
||||
.run(runCostUsd, ts, run.agentId);
|
||||
@@ -223,17 +229,19 @@ export function buildRunMethods(
|
||||
return { budgetHardStopped };
|
||||
},
|
||||
|
||||
cancelRunForDeletion(runId: string, taskId: string, workspaceId: string | null, summary: string) {
|
||||
cancelRunForDeletion(runId: string, taskId: string | null, workspaceId: string | null, summary: string) {
|
||||
const ts = nowIso();
|
||||
getDb()
|
||||
.prepare(
|
||||
"update runs set status = 'cancelled', summary = ?, error_message = null, exit_code = null, signal = null, model = null, session_display_id = null, cost_usd = null, unattributed_cost = 1, finished_at = ?, updated_at = ? where id = ?",
|
||||
)
|
||||
.run(summary, ts, ts, runId);
|
||||
getDb().prepare("update tasks set active_run_id = null, updated_at = ? where id = ?").run(ts, taskId);
|
||||
getDb()
|
||||
.prepare("UPDATE tasks SET checkout_run_id = NULL, execution_locked_at = NULL, updated_at = ? WHERE id = ? AND checkout_run_id = ?")
|
||||
.run(ts, taskId, runId);
|
||||
if (taskId !== null) {
|
||||
getDb().prepare("update tasks set active_run_id = null, updated_at = ? where id = ?").run(ts, taskId);
|
||||
getDb()
|
||||
.prepare("UPDATE tasks SET checkout_run_id = NULL, execution_locked_at = NULL, updated_at = ? WHERE id = ? AND checkout_run_id = ?")
|
||||
.run(ts, taskId, runId);
|
||||
}
|
||||
if (workspaceId) {
|
||||
getDb()
|
||||
.prepare(
|
||||
|
||||
+227
-1
@@ -42,7 +42,6 @@ export function ensureOptionalColumns(db: DatabaseSync) {
|
||||
addColumnIfMissing("tasks", "checkout_run_id", "alter table tasks add column checkout_run_id text");
|
||||
addColumnIfMissing("tasks", "execution_locked_at", "alter table tasks add column execution_locked_at text");
|
||||
addColumnIfMissing("tasks", "active_session_id", "alter table tasks add column active_session_id text");
|
||||
addColumnIfMissing("tasks", "is_heartbeat", "alter table tasks add column is_heartbeat integer not null default 0");
|
||||
addColumnIfMissing("cost_entries", "project_id", "alter table cost_entries add column project_id text");
|
||||
db.exec(`
|
||||
create table if not exists task_comments (id text primary key, company_id text not null, task_id text not null, author_agent_id text, author_name text not null, body text not null, created_at text not null);
|
||||
@@ -513,6 +512,233 @@ export function runMigrations(
|
||||
sql: `ALTER TABLE agents ADD COLUMN session_id TEXT;
|
||||
CREATE INDEX IF NOT EXISTS idx_agents_session_id ON agents(session_id)`,
|
||||
},
|
||||
{
|
||||
// Rebuild runs table with task_id NULLABLE. Heartbeat runs (agent
|
||||
// wake-ups with no real task) no longer need to synthesize a fake
|
||||
// task row; they simply insert a run with task_id = NULL. The old
|
||||
// workaround (is_heartbeat flag + acquireHeartbeatTask + cleanup
|
||||
// sweeps) becomes dead code in v36.
|
||||
//
|
||||
// SQLite can't ALTER a column's NOT NULL constraint, so we rebuild:
|
||||
// 1. Snapshot row count
|
||||
// 2. Discover actual column set via PRAGMA (drift safe)
|
||||
// 3. CREATE runs_new with the same columns + task_id nullable
|
||||
// 4. Copy every row
|
||||
// 5. Assert copied count == snapshot count (abort before DROP
|
||||
// if any row went missing)
|
||||
// 6. DROP old, RENAME new
|
||||
// 7. Recreate every index on runs
|
||||
//
|
||||
// FK from run_events(run_id) references runs(id); PRAGMA foreign_keys
|
||||
// OFF during the rebuild (we're inside a transaction already, so we
|
||||
// toggle the defer_foreign_keys flag instead — SQLite forbids
|
||||
// changing foreign_keys mid-transaction).
|
||||
version: 35, name: "make_runs_task_id_nullable",
|
||||
fn: () => {
|
||||
const beforeCount = (db
|
||||
.prepare("SELECT COUNT(*) as cnt FROM runs")
|
||||
.get() as { cnt: number }).cnt;
|
||||
|
||||
const existingCols = (db
|
||||
.prepare("PRAGMA table_info(runs)")
|
||||
.all() as Array<{ name: string; type: string; notnull: number; dflt_value: unknown; pk: number }>);
|
||||
if (existingCols.length === 0) {
|
||||
throw new Error("runs table is missing; refusing to migrate");
|
||||
}
|
||||
const colNames = existingCols.map((c) => c.name);
|
||||
|
||||
// Declare the known v34 column set. If the live DB has drift (extra
|
||||
// columns we did not declare), preserve those verbatim using the
|
||||
// column metadata from PRAGMA.
|
||||
const knownCols = new Set([
|
||||
"id", "company_id", "task_id", "agent_id", "workspace_id",
|
||||
"connector_id", "status", "summary", "error_message", "exit_code",
|
||||
"signal", "model", "session_display_id", "cost_usd",
|
||||
"unattributed_cost", "started_at", "finished_at", "log_path",
|
||||
"created_at", "updated_at", "context_snapshot_json",
|
||||
"actor_type", "actor_id",
|
||||
]);
|
||||
const driftCols = existingCols.filter((c) => !knownCols.has(c.name));
|
||||
|
||||
// Defer FK checks within this transaction.
|
||||
db.exec("PRAGMA defer_foreign_keys = ON");
|
||||
|
||||
// Build CREATE TABLE runs_new. task_id is nullable. Other columns
|
||||
// reuse the declared types / constraints. For drift columns we
|
||||
// emit a best-effort column definition (type, NULL, default).
|
||||
const declaredDdl = [
|
||||
"id TEXT PRIMARY KEY",
|
||||
"company_id TEXT NOT NULL",
|
||||
"task_id TEXT", // NULLABLE (was NOT NULL)
|
||||
"agent_id TEXT NOT NULL",
|
||||
"workspace_id TEXT",
|
||||
"connector_id TEXT NOT NULL",
|
||||
"status TEXT NOT NULL",
|
||||
"summary TEXT NOT NULL",
|
||||
"error_message TEXT",
|
||||
"exit_code INTEGER",
|
||||
"signal TEXT",
|
||||
"model TEXT",
|
||||
"session_display_id TEXT",
|
||||
"cost_usd REAL",
|
||||
"unattributed_cost INTEGER NOT NULL DEFAULT 0",
|
||||
"started_at TEXT",
|
||||
"finished_at TEXT",
|
||||
"log_path TEXT",
|
||||
"created_at TEXT NOT NULL",
|
||||
"updated_at TEXT NOT NULL",
|
||||
"context_snapshot_json TEXT",
|
||||
"actor_type TEXT",
|
||||
"actor_id TEXT",
|
||||
];
|
||||
for (const drift of driftCols) {
|
||||
const type = drift.type || "TEXT";
|
||||
declaredDdl.push(`${drift.name} ${type}`);
|
||||
}
|
||||
|
||||
db.exec(`CREATE TABLE runs_new (${declaredDdl.join(", ")})`);
|
||||
|
||||
// Copy preserving every column present in the old table.
|
||||
const copyCols = colNames.join(", ");
|
||||
db.exec(`INSERT INTO runs_new (${copyCols}) SELECT ${copyCols} FROM runs`);
|
||||
|
||||
const afterCount = (db
|
||||
.prepare("SELECT COUNT(*) as cnt FROM runs_new")
|
||||
.get() as { cnt: number }).cnt;
|
||||
if (afterCount !== beforeCount) {
|
||||
throw new Error(
|
||||
`runs copy row count mismatch: before=${beforeCount} after=${afterCount}; aborting before DROP`,
|
||||
);
|
||||
}
|
||||
|
||||
db.exec("DROP TABLE runs");
|
||||
db.exec("ALTER TABLE runs_new RENAME TO runs");
|
||||
|
||||
// Recreate every index on runs.
|
||||
db.exec("CREATE INDEX IF NOT EXISTS idx_runs_company ON runs(company_id)");
|
||||
db.exec("CREATE INDEX IF NOT EXISTS idx_runs_task ON runs(task_id)");
|
||||
db.exec("CREATE INDEX IF NOT EXISTS idx_runs_agent ON runs(agent_id)");
|
||||
db.exec("CREATE INDEX IF NOT EXISTS idx_runs_company_status ON runs(company_id, status)");
|
||||
db.exec("CREATE INDEX IF NOT EXISTS idx_runs_company_created_at ON runs(company_id, created_at DESC)");
|
||||
db.exec("CREATE INDEX IF NOT EXISTS idx_runs_agent_created_at ON runs(agent_id, created_at DESC)");
|
||||
|
||||
log.info(`[migration v35] runs table rebuilt with nullable task_id (${afterCount} rows preserved)`);
|
||||
},
|
||||
},
|
||||
{
|
||||
// Drop the `tasks.is_heartbeat` column and all synthetic heartbeat
|
||||
// task rows. Prerequisite: v35 must have made runs.task_id nullable
|
||||
// so we can null-out runs that pointed at heartbeat tasks before
|
||||
// deleting those task rows.
|
||||
version: 36, name: "drop_tasks_is_heartbeat_and_synthetic_rows",
|
||||
fn: () => {
|
||||
const hasColumn = columnExists(db, "tasks", "is_heartbeat");
|
||||
if (!hasColumn) {
|
||||
log.info("[migration v36] tasks.is_heartbeat already absent; skipping");
|
||||
return;
|
||||
}
|
||||
|
||||
// 1. NULL-out runs that pointed at heartbeat tasks.
|
||||
const updated = db
|
||||
.prepare(
|
||||
"UPDATE runs SET task_id = NULL WHERE task_id IN (SELECT id FROM tasks WHERE is_heartbeat = 1)",
|
||||
)
|
||||
.run();
|
||||
const runsNulledOut = Number(updated.changes);
|
||||
|
||||
// 2. Delete synthetic heartbeat tasks. Cost entries referring to
|
||||
// these tasks remain with their task_id pointing at now-deleted
|
||||
// ids — acceptable, cost_entries.task_id has no FK constraint.
|
||||
// task_comments and approvals attached to these tasks are
|
||||
// already cascaded by the task row delete or would remain
|
||||
// orphaned; heartbeat tasks carry neither in practice.
|
||||
const beforeHeartbeatCount = (db
|
||||
.prepare("SELECT COUNT(*) as cnt FROM tasks WHERE is_heartbeat = 1")
|
||||
.get() as { cnt: number }).cnt;
|
||||
db.exec("DELETE FROM tasks WHERE is_heartbeat = 1");
|
||||
|
||||
// 3. Rebuild `tasks` without the is_heartbeat column.
|
||||
const beforeTasksCount = (db
|
||||
.prepare("SELECT COUNT(*) as cnt FROM tasks")
|
||||
.get() as { cnt: number }).cnt;
|
||||
|
||||
const existingCols = (db
|
||||
.prepare("PRAGMA table_info(tasks)")
|
||||
.all() as Array<{ name: string; type: string; notnull: number; dflt_value: unknown; pk: number }>);
|
||||
const keepCols = existingCols.filter((c) => c.name !== "is_heartbeat");
|
||||
|
||||
db.exec("PRAGMA defer_foreign_keys = ON");
|
||||
|
||||
// Declared v20 + v13 + v38+v39/v20 column set for `tasks`. Drift
|
||||
// columns (any column we haven't declared here) are preserved
|
||||
// verbatim using PRAGMA metadata — same drift-safe shape as v35.
|
||||
const declaredCols = new Map<string, string>([
|
||||
["id", "TEXT PRIMARY KEY"],
|
||||
["company_id", "TEXT NOT NULL"],
|
||||
["project_id", "TEXT"],
|
||||
["goal_id", "TEXT"],
|
||||
["parent_id", "TEXT"],
|
||||
["title", "TEXT NOT NULL"],
|
||||
["description", "TEXT NOT NULL"],
|
||||
["assignee_agent_id", "TEXT"],
|
||||
["workspace_id", "TEXT"],
|
||||
["status", "TEXT NOT NULL"],
|
||||
["priority", "TEXT NOT NULL"],
|
||||
["active_run_id", "TEXT"],
|
||||
["session_json", "TEXT"],
|
||||
["session_display_id", "TEXT"],
|
||||
["cost_usd", "REAL NOT NULL DEFAULT 0"],
|
||||
["created_at", "TEXT NOT NULL"],
|
||||
["updated_at", "TEXT NOT NULL"],
|
||||
["task_type", "TEXT NOT NULL DEFAULT 'general'"],
|
||||
["requires_user_review", "INTEGER NOT NULL DEFAULT 0"],
|
||||
["retry_count", "INTEGER NOT NULL DEFAULT 0"],
|
||||
["last_failure_at", "TEXT"],
|
||||
["checkout_run_id", "TEXT"],
|
||||
["execution_locked_at", "TEXT"],
|
||||
["active_session_id", "TEXT"],
|
||||
["started_at", "TEXT"],
|
||||
["completed_at", "TEXT"],
|
||||
["cancelled_at", "TEXT"],
|
||||
]);
|
||||
|
||||
const ddl = keepCols.map((c) => {
|
||||
const declared = declaredCols.get(c.name);
|
||||
if (declared) return `${c.name} ${declared}`;
|
||||
return `${c.name} ${c.type || "TEXT"}`;
|
||||
});
|
||||
|
||||
db.exec(`CREATE TABLE tasks_new (${ddl.join(", ")})`);
|
||||
|
||||
const copyCols = keepCols.map((c) => c.name).join(", ");
|
||||
db.exec(`INSERT INTO tasks_new (${copyCols}) SELECT ${copyCols} FROM tasks`);
|
||||
|
||||
const afterTasksCount = (db
|
||||
.prepare("SELECT COUNT(*) as cnt FROM tasks_new")
|
||||
.get() as { cnt: number }).cnt;
|
||||
if (afterTasksCount !== beforeTasksCount) {
|
||||
throw new Error(
|
||||
`tasks copy row count mismatch: before=${beforeTasksCount} after=${afterTasksCount}; aborting before DROP`,
|
||||
);
|
||||
}
|
||||
|
||||
db.exec("DROP TABLE tasks");
|
||||
db.exec("ALTER TABLE tasks_new RENAME TO tasks");
|
||||
|
||||
// Recreate every index on tasks.
|
||||
db.exec("CREATE INDEX IF NOT EXISTS idx_tasks_company ON tasks(company_id)");
|
||||
db.exec("CREATE INDEX IF NOT EXISTS idx_tasks_assignee ON tasks(assignee_agent_id)");
|
||||
db.exec("CREATE INDEX IF NOT EXISTS idx_tasks_project ON tasks(project_id)");
|
||||
db.exec("CREATE INDEX IF NOT EXISTS idx_tasks_company_status ON tasks(company_id, status)");
|
||||
db.exec("CREATE INDEX IF NOT EXISTS idx_tasks_company_created_at ON tasks(company_id, created_at DESC)");
|
||||
db.exec("CREATE INDEX IF NOT EXISTS idx_tasks_company_updated_at ON tasks(company_id, updated_at DESC)");
|
||||
db.exec("CREATE INDEX IF NOT EXISTS idx_tasks_company_assignee_status ON tasks(company_id, assignee_agent_id, status)");
|
||||
|
||||
log.info(
|
||||
`[migration v36] removed tasks.is_heartbeat; deleted ${beforeHeartbeatCount} synthetic heartbeat task row(s); nulled task_id on ${runsNulledOut} run(s); preserved ${afterTasksCount} task row(s)`,
|
||||
);
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
for (const migration of migrations) {
|
||||
|
||||
@@ -75,9 +75,9 @@ export function buildSnapshotMethods(
|
||||
...companyArgs,
|
||||
),
|
||||
tasks: 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, 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${companyWhere ? `${companyWhere} and is_heartbeat = 0` : " where is_heartbeat = 0"} order by created_at desc limit 2000`,
|
||||
`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, 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${companyWhere} order by created_at desc limit 2000`,
|
||||
...companyArgs,
|
||||
).map((record) => ({ ...record, requiresUserReview: toBoolean(record.requiresUserReview), isHeartbeat: toBoolean(record.isHeartbeat), startedAt: record.startedAt ?? null, completedAt: record.completedAt ?? null, cancelledAt: record.cancelledAt ?? null })) as TaskRecord[],
|
||||
).map((record) => ({ ...record, requiresUserReview: toBoolean(record.requiresUserReview), startedAt: record.startedAt ?? null, completedAt: record.completedAt ?? null, cancelledAt: record.cancelledAt ?? null })) as TaskRecord[],
|
||||
approvals: readAll<ApprovalRecord>(
|
||||
`select id, company_id as companyId, related_task_id as relatedTaskId, related_agent_id as relatedAgentId, requested_by_agent_id as requestedByAgentId, type, payload_summary as payloadSummary, impact_summary as impactSummary, payload_json as payloadJson, decision_note as decisionNote, state, created_at as createdAt, updated_at as updatedAt from approvals${companyWhere} order by created_at desc limit 1000`,
|
||||
...companyArgs,
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import type { DatabaseSync } from "node:sqlite";
|
||||
import type { TaskRecord } from "@shared/types";
|
||||
import {
|
||||
@@ -12,7 +11,7 @@ import { chooseBestTaskAssignee } from "./task-assignment";
|
||||
export function buildTaskStatusMethods(
|
||||
getDb: () => DatabaseSync,
|
||||
readAll: ReadAll,
|
||||
transaction: Transaction,
|
||||
_transaction: Transaction,
|
||||
deps: {
|
||||
addComment: (input: { companyId: string; taskId: string; authorAgentId: string | null; authorName: string; body: string }) => void;
|
||||
addActivity: (input: { companyId: string; actor: string; action: string; entityType: string; entityId: string; detail: string }) => void;
|
||||
@@ -102,152 +101,6 @@ export function buildTaskStatusMethods(
|
||||
return { previousStatus };
|
||||
},
|
||||
|
||||
findReusableHeartbeatTask(agentId: string, companyId: string): TaskRecord | null {
|
||||
const row = getDb()
|
||||
.prepare(
|
||||
`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,
|
||||
created_at as createdAt, updated_at as updatedAt
|
||||
FROM tasks
|
||||
WHERE company_id = ? AND assignee_agent_id = ? AND is_heartbeat = 1
|
||||
AND status IN ('done', 'in_review')
|
||||
ORDER BY updated_at DESC, rowid DESC
|
||||
LIMIT 1`,
|
||||
)
|
||||
.get(companyId, agentId) as TaskRecord | undefined;
|
||||
if (row) {
|
||||
row.requiresUserReview = Boolean(row.requiresUserReview);
|
||||
row.isHeartbeat = Boolean(row.isHeartbeat);
|
||||
}
|
||||
return row ?? null;
|
||||
},
|
||||
|
||||
acquireHeartbeatTask(input: {
|
||||
agentId: string;
|
||||
companyId: string;
|
||||
runId: string;
|
||||
workspaceId: string | null;
|
||||
title: string;
|
||||
description: string;
|
||||
priority: string;
|
||||
}): TaskRecord | null {
|
||||
return transaction<TaskRecord | null>(() => {
|
||||
const ts = nowIso();
|
||||
const db = getDb();
|
||||
|
||||
const claimable = db
|
||||
.prepare(
|
||||
`SELECT id, status FROM tasks
|
||||
WHERE company_id = ? AND assignee_agent_id = ? AND is_heartbeat = 1
|
||||
AND status IN ('todo', 'backlog', 'done', 'in_review')
|
||||
AND checkout_run_id IS NULL
|
||||
ORDER BY
|
||||
CASE status WHEN 'todo' THEN 0 WHEN 'backlog' THEN 1 WHEN 'in_review' THEN 2 WHEN 'done' THEN 3 ELSE 4 END ASC,
|
||||
updated_at DESC, rowid DESC
|
||||
LIMIT 1`,
|
||||
)
|
||||
.get(input.companyId, input.agentId) as { id: string; status: string } | undefined;
|
||||
|
||||
let taskId: string | null = null;
|
||||
if (claimable) {
|
||||
const claimResult = db
|
||||
.prepare(
|
||||
`UPDATE tasks
|
||||
SET checkout_run_id = ?, execution_locked_at = ?, status = 'in_progress',
|
||||
started_at = COALESCE(started_at, ?), completed_at = NULL, cancelled_at = NULL,
|
||||
updated_at = ?
|
||||
WHERE id = ? AND checkout_run_id IS NULL
|
||||
AND status IN ('todo', 'backlog', 'done', 'in_review')`,
|
||||
)
|
||||
.run(input.runId, ts, ts, ts, claimable.id);
|
||||
if (claimResult.changes > 0) {
|
||||
taskId = claimable.id;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
} else {
|
||||
const inflight = db
|
||||
.prepare(
|
||||
`SELECT 1 FROM tasks
|
||||
WHERE company_id = ? AND assignee_agent_id = ? AND is_heartbeat = 1
|
||||
AND status NOT IN ('done', 'cancelled')
|
||||
LIMIT 1`,
|
||||
)
|
||||
.get(input.companyId, input.agentId);
|
||||
if (inflight) return null;
|
||||
|
||||
taskId = randomUUID();
|
||||
db.prepare(
|
||||
`INSERT INTO tasks
|
||||
(id, company_id, project_id, goal_id, parent_id, title, description,
|
||||
assignee_agent_id, workspace_id, status, priority,
|
||||
checkout_run_id, execution_locked_at, started_at, is_heartbeat,
|
||||
created_at, updated_at)
|
||||
VALUES (?, ?, NULL, NULL, NULL, ?, ?, ?, ?, 'in_progress', ?, ?, ?, ?, 1, ?, ?)`,
|
||||
).run(
|
||||
taskId,
|
||||
input.companyId,
|
||||
input.title,
|
||||
input.description,
|
||||
input.agentId,
|
||||
input.workspaceId,
|
||||
input.priority,
|
||||
input.runId,
|
||||
ts,
|
||||
ts,
|
||||
ts,
|
||||
ts,
|
||||
);
|
||||
}
|
||||
|
||||
const row = db
|
||||
.prepare(
|
||||
`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, task_type as taskType,
|
||||
started_at as startedAt, completed_at as completedAt, cancelled_at as cancelledAt,
|
||||
created_at as createdAt, updated_at as updatedAt
|
||||
FROM tasks WHERE id = ?`,
|
||||
)
|
||||
.get(taskId) as TaskRecord | undefined;
|
||||
if (!row) return null;
|
||||
row.requiresUserReview = Boolean(row.requiresUserReview);
|
||||
row.isHeartbeat = Boolean(row.isHeartbeat);
|
||||
row.startedAt = row.startedAt ?? null;
|
||||
row.completedAt = row.completedAt ?? null;
|
||||
row.cancelledAt = row.cancelledAt ?? null;
|
||||
return row;
|
||||
});
|
||||
},
|
||||
|
||||
cleanupDuplicateHeartbeatTasks(companyId: string): number {
|
||||
const ts = nowIso();
|
||||
const result = getDb()
|
||||
.prepare(
|
||||
`UPDATE tasks SET status = 'cancelled', updated_at = ?
|
||||
WHERE company_id = ? AND is_heartbeat = 1
|
||||
AND status IN ('done', 'in_review', 'todo', 'blocked', 'backlog')
|
||||
AND id NOT IN (
|
||||
SELECT id FROM (
|
||||
SELECT id, ROW_NUMBER() OVER (PARTITION BY assignee_agent_id ORDER BY updated_at DESC, rowid DESC) as rn
|
||||
FROM tasks
|
||||
WHERE company_id = ? AND is_heartbeat = 1 AND status != 'cancelled'
|
||||
) WHERE rn = 1
|
||||
)`,
|
||||
)
|
||||
.run(ts, companyId, companyId);
|
||||
return Number(result.changes);
|
||||
},
|
||||
|
||||
listReviewTasksForManager(managerId: string, companyId: string): TaskRecord[] {
|
||||
return readAll<TaskRecord>(
|
||||
`select t.id, t.company_id as companyId, t.project_id as projectId, t.goal_id as goalId,
|
||||
@@ -255,11 +108,11 @@ export function buildTaskStatusMethods(
|
||||
t.assignee_agent_id as assigneeAgentId, t.workspace_id as workspaceId,
|
||||
t.status, t.priority, t.active_run_id as activeRunId,
|
||||
t.session_json as sessionJson, t.session_display_id as sessionDisplayId,
|
||||
t.cost_usd as costUsd, t.is_heartbeat as isHeartbeat,
|
||||
t.cost_usd as costUsd,
|
||||
t.created_at as createdAt, t.updated_at as updatedAt
|
||||
from tasks t
|
||||
inner join agents a on t.assignee_agent_id = a.id
|
||||
where t.company_id = ? and t.status = 'in_review' and a.reports_to = ? and t.is_heartbeat = 0
|
||||
where t.company_id = ? and t.status = 'in_review' and a.reports_to = ?
|
||||
order by ${taskPriorityOrderSql("t.priority")} desc, t.created_at asc`,
|
||||
companyId,
|
||||
managerId,
|
||||
|
||||
Reference in new issue
Block a user