The open-source app everyone uses to manage agents at work
TypeScript acpxagent-orchestrationagent-skillsagentic-aiai-agentsai-engineeringai-governanceai-toolsautonomous-agentsclaudeclaude-codeclaude-skillscodexhermesllmmcpmulti-agentopenclawproject-managementworkflow-automation
import { sql } from "drizzle-orm";
import {
type AnyPgColumn,
pgTable,
uuid,
text,
timestamp,
jsonb,
index,
integer,
bigint,
boolean,
check,
unique,
uniqueIndex,
} from "drizzle-orm/pg-core";
import { companies } from "./companies.js";
import { agents } from "./agents.js";
import { agentWakeupRequests } from "./agent_wakeup_requests.js";
import { issues } from "./issues.js";
export const heartbeatRuns = pgTable(
"heartbeat_runs",
{
id: uuid("id").primaryKey().defaultRandom(),
companyId: uuid("company_id").notNull().references(() => companies.id),
agentId: uuid("agent_id").notNull().references(() => agents.id),
scopeKind: text("scope_kind")
.$type<"company" | "issue">()
.notNull()
.default("company"),
issueId: uuid("issue_id").references((): AnyPgColumn => issues.id, { onDelete: "set null" }),
invocationSource: text("invocation_source").notNull().default("on_demand"),
triggerDetail: text("trigger_detail"),
status: text("status").notNull().default("queued"),
responsibleUserId: text("responsible_user_id"),
// The service validates the company/run boundary; avoid a cyclic schema import.
activeIdentityContextId: uuid("active_identity_context_id"),
startedAt: timestamp("started_at", { withTimezone: true }),
finishedAt: timestamp("finished_at", { withTimezone: true }),
// Set only after provider execution settles; never a timeout on thinking.
executionControlDeadlineAt: timestamp("execution_control_deadline_at", { withTimezone: true }),
// Transactional delivery marker. Null on historical rows; publication never replays provider work.
executionStatusDeliveryId: uuid("execution_status_delivery_id"),
error: text("error"),
wakeupRequestId: uuid("wakeup_request_id").references(() => agentWakeupRequests.id),
exitCode: integer("exit_code"),
signal: text("signal"),
costAccountingPending: boolean("cost_accounting_pending").notNull().default(false),
costAccountedAt: timestamp("cost_accounted_at", { withTimezone: true }),
accountingProjectionVersion: text("accounting_projection_version"),
accountingLastAttemptAt: timestamp("accounting_last_attempt_at", { withTimezone: true }),
accountingLastError: text("accounting_last_error"),
accountingAttemptCount: integer("accounting_attempt_count").notNull().default(0),
usageJson: jsonb("usage_json").$type<Record<string, unknown>>(),
resultJson: jsonb("result_json").$type<Record<string, unknown>>(),
runtimeMode: text("runtime_mode").notNull().default("legacy"),
runtimeModeResolverVersion: text("runtime_mode_resolver_version"),
runtimeModeReason: text("runtime_mode_reason"),
runtimeModeResolvedAt: timestamp("runtime_mode_resolved_at", { withTimezone: true }),
runnerProfileJson: jsonb("runner_profile_json").$type<Record<string, unknown>>(),
runnerInstanceId: uuid("runner_instance_id"),
nativeSessionId: uuid("native_session_id"),
nativeIssueId: uuid("native_issue_id"),
driverKind: text("driver_kind"),
driverVersion: text("driver_version"),
completionContractId: uuid("completion_contract_id"),
completionContractSha256: text("completion_contract_sha256"),
nextEventSeq: bigint("next_event_seq", { mode: "number" }).notNull().default(1),
nativePhase: text("native_phase"),
nativePhaseUpdatedAt: timestamp("native_phase_updated_at", { withTimezone: true }),
sessionIdBefore: text("session_id_before"),
sessionIdAfter: text("session_id_after"),
logStore: text("log_store"),
logRef: text("log_ref"),
logBytes: bigint("log_bytes", { mode: "number" }),
logSha256: text("log_sha256"),
logCompressed: boolean("log_compressed").notNull().default(false),
stdoutExcerpt: text("stdout_excerpt"),
stderrExcerpt: text("stderr_excerpt"),
errorCode: text("error_code"),
externalRunId: text("external_run_id"),
// Legacy controller lease. A PID alone is not an identity across containers.
controllerBootId: uuid("controller_boot_id"),
controllerLeaseExpiresAt: timestamp("controller_lease_expires_at", { withTimezone: true }),
executionStage: text("execution_stage"),
processPid: integer("process_pid"),
processGroupId: integer("process_group_id"),
processStartedAt: timestamp("process_started_at", { withTimezone: true }),
lastOutputAt: timestamp("last_output_at", { withTimezone: true }),
lastOutputSeq: integer("last_output_seq").notNull().default(0),
lastOutputStream: text("last_output_stream"),
lastOutputBytes: bigint("last_output_bytes", { mode: "number" }),
retryOfRunId: uuid("retry_of_run_id").references((): AnyPgColumn => heartbeatRuns.id, {
onDelete: "set null",
}),
processLossRetryCount: integer("process_loss_retry_count").notNull().default(0),
scheduledRetryAt: timestamp("scheduled_retry_at", { withTimezone: true }),
scheduledRetryAttempt: integer("scheduled_retry_attempt").notNull().default(0),
scheduledRetryReason: text("scheduled_retry_reason"),
issueCommentStatus: text("issue_comment_status").notNull().default("not_applicable"),
issueCommentSatisfiedByCommentId: uuid("issue_comment_satisfied_by_comment_id"),
issueCommentRetryQueuedAt: timestamp("issue_comment_retry_queued_at", { withTimezone: true }),
livenessState: text("liveness_state"),
livenessReason: text("liveness_reason"),
continuationAttempt: integer("continuation_attempt").notNull().default(0),
lastUsefulActionAt: timestamp("last_useful_action_at", { withTimezone: true }),
nextAction: text("next_action"),
contextSnapshot: jsonb("context_snapshot").$type<Record<string, unknown>>(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
},
(table) => ({
retainedRecoveryAdoptionIdx: index("heartbeat_runs_retained_recovery_adoption_idx")
.on(table.id).where(sql`${table.resultJson}->'workspaceRestoreRecovery'->>'schema' = 'paperclip.workspace-restore-recovery.v1'
and not (coalesce(${table.resultJson}, '{}'::jsonb) ? 'systemRecoveryAdoption')
and ${table.status} in ('failed', 'interrupted', 'timed_out', 'cancelled', 'succeeded')`),
scopeBindingCheck: check(
"heartbeat_runs_scope_binding_check",
sql`(${table.scopeKind} = 'company' AND ${table.issueId} IS NULL)
OR ${table.scopeKind} = 'issue'`,
),
costAccountingPendingIdx: index("heartbeat_runs_cost_accounting_pending_idx").on(table.updatedAt, table.id).where(sql`${table.costAccountingPending} = true`),
costDataQualityIdx: index("heartbeat_runs_cost_data_quality_idx")
.on(table.companyId, sql`coalesce(${table.finishedAt}, ${table.createdAt}) desc`, table.id)
.where(sql`${table.costAccountingPending} = true and ${table.status} in ('succeeded','failed','timed_out','cancelled','interrupted')`),
executionStatusDeliveryIdx: index("heartbeat_runs_execution_status_delivery_idx")
.on(table.executionStatusDeliveryId).where(sql`${table.executionStatusDeliveryId} is not null`),
executionControlDeadlineIdx: index("heartbeat_runs_execution_control_deadline_idx")
.on(table.executionControlDeadlineAt).where(sql`${table.executionControlDeadlineAt} is not null`),
nativeReplacementPredecessorUq: uniqueIndex("heartbeat_runs_native_replacement_predecessor_uq")
.on(table.companyId, table.retryOfRunId)
.where(sql`${table.scheduledRetryReason} = 'native_safe_replacement'`),
companyNativeIssueRunUq: unique("heartbeat_runs_company_native_issue_id_uq").on(
table.companyId,
table.nativeIssueId,
table.id,
),
companyNativeIssueRunContractUq: unique(
"heartbeat_runs_company_native_issue_contract_id_uq",
).on(
table.companyId,
table.nativeIssueId,
table.id,
table.completionContractId,
),
companyAgentStartedIdx: index("heartbeat_runs_company_agent_started_idx").on(
table.companyId,
table.agentId,
table.startedAt,
),
companyIssueCreatedIdx: index("heartbeat_runs_company_issue_created_idx").on(
table.companyId,
table.issueId,
table.createdAt,
),
companyResponsibleUserIdx: index("heartbeat_runs_company_responsible_user_idx").on(
table.companyId,
table.responsibleUserId,
table.createdAt,
),
companyLivenessIdx: index("heartbeat_runs_company_liveness_idx").on(
table.companyId,
table.livenessState,
table.createdAt,
),
companyStatusLastOutputIdx: index("heartbeat_runs_company_status_last_output_idx").on(
table.companyId,
table.status,
table.lastOutputAt,
),
companyStatusProcessStartedIdx: index("heartbeat_runs_company_status_process_started_idx").on(
table.companyId,
table.status,
table.processStartedAt,
),
companyCreatedAtDescIdx: index("heartbeat_runs_company_created_at_desc_idx").on(
table.companyId,
table.createdAt.desc(),
),
companyCtxIssueCreatedIdx: index("heartbeat_runs_company_ctx_issue_created_idx").on(
table.companyId,
sql`(${table.contextSnapshot} ->> 'issueId')`,
table.createdAt.desc(),
),
companyCtxTaskCreatedIdx: index("heartbeat_runs_company_ctx_task_created_idx").on(
table.companyId,
sql`(${table.contextSnapshot} ->> 'taskId')`,
table.createdAt.desc(),
),
companyCtxTaskKeyCreatedIdx: index("heartbeat_runs_company_ctx_taskkey_created_idx").on(
table.companyId,
sql`(${table.contextSnapshot} ->> 'taskKey')`,
table.createdAt.desc(),
),
companyCtxPaperclipIssueCreatedIdx: index("heartbeat_runs_company_ctx_paperclip_issue_created_idx")
.on(table.companyId, sql`(${table.contextSnapshot} -> 'paperclipIssue' ->> 'id')`, table.createdAt.desc())
.concurrently(),
// Match creation provenance precedence, including empty legacy IDs.
companyOriginIssueIdx: index("heartbeat_runs_company_origin_issue_idx")
.on(table.companyId, sql`coalesce(
${table.nativeIssueId}::text,
nullif(${table.contextSnapshot}->>'issueId', ''),
nullif(${table.contextSnapshot}->>'taskId', ''),
nullif(${table.contextSnapshot}->>'taskKey', '')
)`)
.concurrently(),
}),
);