This commit is contained in:
ZacharyZhang-NY committed 2026-04-17 14:03:56 -04:00
1 parent 806200b3d1
commit 5547c29491
216 files changed
+5043 -3352

No files matched your search

+75
View File
@@ -408,5 +408,80 @@ export function buildAgentHierarchyMethods(
)
.run(merged.enabled ? 1 : 0, merged.intervalSec, policyJson, ts, agentId, companyId);
},
/**
* Returns ids of non-terminated agents in a department. Used by
* `resolveMessageWakeTargets` to fan out "department" channel messages.
*/
listDepartmentAgentIds(companyId: string, department: string): string[] {
return readAll<{ id: string }>(
"select id from agents where company_id = ? and department = ? and status != 'terminated'",
companyId,
department,
).map((row) => row.id);
},
/**
* Returns ids of non-terminated agents that have no manager (top of the
* reporting tree). Used by `resolveMessageWakeTargets` for "company"
* channel broadcast.
*/
listTopLevelAgentIds(companyId: string): string[] {
return readAll<{ id: string }>(
"select id from agents where company_id = ? and reports_to is null and status != 'terminated'",
companyId,
).map((row) => row.id);
},
/**
* Returns ids of agents that can receive incident pings: everybody not
* terminated or still pending approval.
*/
listIncidentPingableAgentIds(companyId: string): string[] {
return readAll<{ id: string }>(
"select id from agents where company_id = ? and status not in ('terminated', 'pending_approval')",
companyId,
).map((row) => row.id);
},
/**
* Returns the agent's display name, or null if the agent no longer
* exists. Used for notification subject lines.
*/
findAgentName(agentId: string): string | null {
const row = getDb()
.prepare("select name from agents where id = ? limit 1")
.get(agentId) as { name: string } | undefined;
return row?.name ?? null;
},
/**
* Returns (id, name) pairs for the given ids, scoped to company. Used
* for batched name resolution when fanning out message wake targets.
*/
listAgentNamesByIds(companyId: string, agentIds: readonly string[]): Array<{ id: string; name: string }> {
if (agentIds.length === 0) return [];
const placeholders = agentIds.map(() => "?").join(",");
return readAll<{ id: string; name: string }>(
`select id, name from agents where id in (${placeholders}) and company_id = ?`,
...agentIds,
companyId,
);
},
/**
* Returns ids of active agents with the given ids, filtered to the
* company scope. Used by project-channel wake targeting to drop
* terminated members before pinging.
*/
listActiveAgentIdsFromIds(companyId: string, agentIds: readonly string[]): string[] {
if (agentIds.length === 0) return [];
const placeholders = agentIds.map(() => "?").join(",");
return readAll<{ id: string }>(
`select id from agents where id in (${placeholders}) and company_id = ? and status != 'terminated'`,
...agentIds,
companyId,
).map((row) => row.id);
},
};
}
+41 -1
View File
@@ -1,5 +1,6 @@
import { randomUUID } from "node:crypto";
import type { DatabaseSync, SQLInputValue } from "node:sqlite";
import log from "electron-log/main.js";
import type { ApprovalRecord } from "@shared/types";
import type { ReadAll, Transaction } from "./helpers";
import { normalizeOptionalId, nowIso, parseJson } from "./helpers";
@@ -54,7 +55,11 @@ export function buildApprovalMethods(
try {
const payload = JSON.parse(input.payloadJson) as { agentId?: string };
relatedAgentId = payload.agentId ?? null;
} catch { /* ignore malformed payload */ }
} catch (error) {
log.warn(
`[db/approvals] malformed payloadJson on hire_agent request for company ${input.companyId}: ${error instanceof Error ? error.message : String(error)}`,
);
}
}
if (input.type === "hire_agent") {
if (!relatedAgentId) {
@@ -346,5 +351,40 @@ export function buildApprovalMethods(
}
});
},
/**
* Returns the first pending approval linked to a task (id + type),
* or null when none exists. Used by task-quality-gates to decide
* whether an in-review task still has a blocking approval.
*/
findPendingApprovalForTask(companyId: string, taskId: string): { id: string; type: string } | null {
const row = getDb()
.prepare(
`SELECT id, type FROM approvals
WHERE company_id = ? AND related_task_id = ? AND state = 'pending'
LIMIT 1`,
)
.get(companyId, taskId) as { id: string; type: string } | undefined;
return row ?? null;
},
/**
* Returns true when the given agent has a pending review-type approval
* against one of their tasks. Used by checkpoint-engine to decide
* whether heartbeat should pause in co-founder mode.
*/
hasPendingReviewApprovalForAgent(companyId: string, agentId: string): boolean {
const row = getDb()
.prepare(
`SELECT 1 as hit FROM approvals a
JOIN tasks t ON a.related_task_id = t.id
WHERE a.company_id = ? AND a.state = 'pending'
AND t.assignee_agent_id = ?
AND a.type IN ('plan_review','scope_review','draft_review','strategy_review','deliverable_review','exception_review')
LIMIT 1`,
)
.get(companyId, agentId) as { hit: number } | undefined;
return row !== undefined;
},
};
}
-2
View File
@@ -32,8 +32,6 @@ export function buildBackupMethods(
backupDatabase(deps.getDb(), join(targetDir, "profile.sqlite")),
cp(deps.logsDir, join(targetDir, "logs"), { recursive: true, force: true }),
cp(deps.artifactsDir, join(targetDir, "artifacts"), { recursive: true, force: true }),
copyIfExists(join(deps.profileDir, "vault.key"), join(targetDir, "vault.key")),
copyIfExists(join(deps.profileDir, "agent-api-signing.key"), join(targetDir, "agent-api-signing.key")),
copyIfExists(`${deps.dbPath}-wal`, join(targetDir, "profile.sqlite-wal")),
copyIfExists(`${deps.dbPath}-shm`, join(targetDir, "profile.sqlite-shm")),
];
+2 -1
View File
@@ -49,11 +49,12 @@ 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, 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, 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 = ?",
)
.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;
+3 -2
View File
@@ -279,14 +279,15 @@ export function buildRunMethods(
getInterruptedRunsForRecovery(): Array<{
runId: string; taskId: string; taskTitle: string; agentId: string;
agentName: string; connectorId: string; interruptedAt: string;
agentName: string; companyId: string; connectorId: string; interruptedAt: string;
}> {
return readAll<{
runId: string; taskId: string; taskTitle: string; agentId: string;
agentName: string; connectorId: string; interruptedAt: string;
agentName: string; companyId: string; connectorId: string; interruptedAt: string;
}>(
`select r.id as runId, r.task_id as taskId, t.title as taskTitle,
r.agent_id as agentId, a.name as agentName,
r.company_id as companyId,
r.connector_id as connectorId, r.finished_at as interruptedAt
from runs r
join tasks t on t.id = r.task_id
+15
View File
@@ -40,6 +40,7 @@ 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);
@@ -455,6 +456,20 @@ export function runMigrations(
}
},
},
{
// Explicit flag for synthesized heartbeat tasks. Replaces title-prefix
// sniffing (`title LIKE '[Heartbeat]%'`) across queries, filters, and
// automation gates. Backfills from existing `[Heartbeat]` titles so the
// new column agrees with historical data on first boot.
version: 33, name: "add_tasks_is_heartbeat",
fn: () => {
if (!columnExists(db, "tasks", "is_heartbeat")) {
db.prepare("ALTER TABLE tasks ADD COLUMN is_heartbeat INTEGER NOT NULL DEFAULT 0").run();
}
db.prepare("UPDATE tasks SET is_heartbeat = 1 WHERE is_heartbeat = 0 AND title LIKE '[Heartbeat]%'").run();
db.exec("CREATE INDEX IF NOT EXISTS idx_tasks_is_heartbeat ON tasks(is_heartbeat)");
},
},
{
// pi-mono session transcripts + credential vault. Idempotent; safe to
// re-apply on fresh DBs or DBs that already have the tables.
+10 -2
View File
@@ -1,6 +1,7 @@
import { existsSync, lstatSync, realpathSync, unlinkSync } from "node:fs";
import { extname, resolve, sep } from "node:path";
import type { DatabaseSync } from "node:sqlite";
import log from "electron-log/main.js";
import type { ReadAll } from "./helpers";
import { nowIso } from "./helpers";
@@ -14,7 +15,10 @@ function isWithinOrEqual(targetPath: string, rootPath: string) {
function safeRealpath(targetPath: string) {
try {
return realpathSync(targetPath);
} catch {
} catch (error) {
log.debug(
`[db/settings] realpathSync fallback for ${targetPath}: ${error instanceof Error ? error.message : String(error)}`,
);
return resolve(targetPath);
}
}
@@ -113,7 +117,11 @@ export function buildSettingsMethods(
if (run.logPath) {
try {
unlinkSync(run.logPath);
} catch { /* Log files may already be gone */ }
} catch (error) {
log.warn(
`[db/settings] purgeExpiredRunLogs: unlink failed for run ${run.id} (${run.logPath}): ${error instanceof Error ? error.message : String(error)}`,
);
}
}
getDb()
.prepare("update runs set log_path = null, updated_at = ? where id = ?")
+2 -2
View File
@@ -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, 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`,
`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`,
...companyArgs,
).map((record) => ({ ...record, requiresUserReview: toBoolean(record.requiresUserReview), startedAt: record.startedAt ?? null, completedAt: record.completedAt ?? null, cancelledAt: record.cancelledAt ?? null })) as TaskRecord[],
).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[],
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,
+82 -13
View File
@@ -33,6 +33,7 @@ export type TaskListByStatusesRow = {
sessionDisplayId: string | null;
costUsd: number | null;
requiresUserReview: boolean;
isHeartbeat: boolean;
startedAt: string | null;
completedAt: string | null;
cancelledAt: string | null;
@@ -168,12 +169,24 @@ export function buildTaskCrudMethods(
});
},
listAgentTasks(agentId: string, companyId: string, statuses: string[]): TaskRecord[] {
/**
* 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).
*/
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, 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, is_heartbeat as isHeartbeat, created_at as createdAt, updated_at as updatedAt
from tasks
where company_id = ? and assignee_agent_id = ? and status in (${placeholders})
where company_id = ? and assignee_agent_id = ? and status in (${placeholders})${heartbeatClause}
order by
case status
when 'in_progress' then 0
@@ -187,20 +200,21 @@ 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.
* me/standup builder in routes-agents-standup.ts. Heartbeat tasks are
* excluded so UI aggregations do not surface synthetic wake tasks.
*/
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 = ? order by created_at desc",
"select id, title, status, priority from tasks where company_id = ? and assignee_agent_id = ? and is_heartbeat = 0 order by created_at desc",
companyId,
agentId,
);
@@ -209,7 +223,8 @@ 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.
* me/standup builder to fetch reports' tasks in one query. Heartbeat
* tasks are excluded.
*/
listTasksForAssignees(
companyId: string,
@@ -224,7 +239,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}) 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}) and is_heartbeat = 0 order by created_at desc`,
companyId,
...assigneeIds,
);
@@ -232,7 +247,7 @@ export function buildTaskCrudMethods(
/**
* Returns the slim task projection used by the me/standup aggregation.
* Ordered by created_at desc.
* Ordered by created_at desc. Heartbeat tasks are excluded.
*/
listTasksForStandup(companyId: string): Array<{
id: string;
@@ -243,23 +258,32 @@ 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 = ? order by created_at desc",
"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",
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.
*/
listTasksByStatuses(
companyId: string,
statuses: string[],
options: { includeHeartbeat?: boolean } = {},
): TaskListByStatusesRow[] {
const placeholders = statuses.map(() => "?").join(", ");
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`,
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`,
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,
@@ -269,7 +293,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 title not like '[Heartbeat]%'",
"select count(*) as cnt from tasks where company_id = ? and status not in ('done', 'cancelled') and is_heartbeat = 0",
)
.get(companyId) as { cnt: number };
return row.cnt;
@@ -518,5 +542,50 @@ export function buildTaskCrudMethods(
.run(ts, taskId);
},
/**
* Returns the set of distinct assignee agent ids on tasks in a project,
* excluding unassigned tasks. Used by message-dispatch to fan out wake
* targets for a project channel.
*/
listProjectTaskAssigneeIds(projectId: string, companyId: string): string[] {
const rows = readAll<{ assigneeAgentId: string | null }>(
"select distinct assignee_agent_id as assigneeAgentId from tasks where project_id = ? and company_id = ? and assignee_agent_id is not null",
projectId,
companyId,
);
return rows.map((r) => r.assigneeAgentId).filter((id): id is string => id !== null);
},
/**
* Returns assignee agent ids for a set of task ids scoped to a company.
* Used by task-quality-gates sweep to find reviewers of in-review tasks
* that have exceeded the review timeout.
*/
listReviewTasksForSweep(companyId: string): Array<{
id: string;
assigneeAgentId: string | null;
updatedAt: string;
title: string;
}> {
return readAll(
`SELECT id, assignee_agent_id as assigneeAgentId, updated_at as updatedAt, title
FROM tasks
WHERE company_id = ? AND status = 'in_review'`,
companyId,
);
},
/**
* Returns `task_type` for a single task id, or null when the task is
* missing. Used by checkpoint-engine to branch on task type without
* loading the full row.
*/
getTaskType(taskId: string): string | null {
const row = getDb()
.prepare("SELECT task_type as taskType FROM tasks WHERE id = ? LIMIT 1")
.get(taskId) as { taskType: string | null } | undefined;
return row?.taskType ?? null;
},
};
}
+14 -10
View File
@@ -111,9 +111,10 @@ export function buildTaskStatusMethods(
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 title LIKE '[Heartbeat]%'
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`,
@@ -121,6 +122,7 @@ export function buildTaskStatusMethods(
.get(companyId, agentId) as TaskRecord | undefined;
if (row) {
row.requiresUserReview = Boolean(row.requiresUserReview);
row.isHeartbeat = Boolean(row.isHeartbeat);
}
return row ?? null;
},
@@ -141,7 +143,7 @@ export function buildTaskStatusMethods(
const claimable = db
.prepare(
`SELECT id, status FROM tasks
WHERE company_id = ? AND assignee_agent_id = ? AND title LIKE '[Heartbeat]%'
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
@@ -172,7 +174,7 @@ export function buildTaskStatusMethods(
const inflight = db
.prepare(
`SELECT 1 FROM tasks
WHERE company_id = ? AND assignee_agent_id = ? AND title LIKE '[Heartbeat]%'
WHERE company_id = ? AND assignee_agent_id = ? AND is_heartbeat = 1
AND status NOT IN ('done', 'cancelled')
LIMIT 1`,
)
@@ -184,9 +186,9 @@ export function buildTaskStatusMethods(
`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,
checkout_run_id, execution_locked_at, started_at, is_heartbeat,
created_at, updated_at)
VALUES (?, ?, NULL, NULL, NULL, ?, ?, ?, ?, 'in_progress', ?, ?, ?, ?, ?, ?)`,
VALUES (?, ?, NULL, NULL, NULL, ?, ?, ?, ?, 'in_progress', ?, ?, ?, ?, 1, ?, ?)`,
).run(
taskId,
input.companyId,
@@ -211,7 +213,7 @@ export function buildTaskStatusMethods(
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,
task_type as taskType,
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 = ?`,
@@ -219,6 +221,7 @@ export function buildTaskStatusMethods(
.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;
@@ -231,13 +234,13 @@ export function buildTaskStatusMethods(
const result = getDb()
.prepare(
`UPDATE tasks SET status = 'cancelled', updated_at = ?
WHERE company_id = ? AND title LIKE '[Heartbeat]%'
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 title LIKE '[Heartbeat]%' AND status != 'cancelled'
WHERE company_id = ? AND is_heartbeat = 1 AND status != 'cancelled'
) WHERE rn = 1
)`,
)
@@ -252,10 +255,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.created_at as createdAt, t.updated_at as updatedAt
t.cost_usd as costUsd, t.is_heartbeat as isHeartbeat,
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 = ?
where t.company_id = ? and t.status = 'in_review' and a.reports_to = ? and t.is_heartbeat = 0
order by ${taskPriorityOrderSql("t.priority")} desc, t.created_at asc`,
companyId,
managerId,