Skip to content

The open-source app everyone uses to manage agents at work

feat(telemetry): add the agent.task_run event and emit it at every terminal run transition (#12809)

Nicky Leach184b014c259a
diff --git a/packages/shared/src/telemetry/README.md b/packages/shared/src/telemetry/README.md
index 61dfe9f68f..e8312026ae 100644
--- a/packages/shared/src/telemetry/README.md
+++ b/packages/shared/src/telemetry/README.md
@@ -74,6 +74,20 @@ Use `trackInteractionCreated()` and `trackInteractionResolved()` from
`events.ts` to emit these events. The generated contract remains the authority
for their exact dimensions and optionality.
+## Agent Task Run Events
+
+`agent.task_run` records one terminal state for one agent run: `succeeded`,
+`interrupted`, `failed`, `cancelled`, or `timed_out`. Emit it once per run, at
+the run's terminal transition. Do not emit it for a run that is still active.
+
+The event's `task_id` dimension is optional and privacy-protected. Never emit
+the raw task id. Pass the raw id to `trackAgentTaskRun()` in `events.ts`. The
+helper calls `hashPrivateRef()` on `client.ts`, which derives the emitted
+value with a salted hash of the per-installation secret.
+
+Use `trackAgentTaskRun()` to emit this event. The generated contract remains
+the authority for its exact dimensions and optionality.
+
### Other Data Paths
This document covers Paperclip Telemetry only. The generated Telemetry
diff --git a/packages/shared/src/telemetry/events.ts b/packages/shared/src/telemetry/events.ts
index e29b7a478a..5b38b75d78 100644
--- a/packages/shared/src/telemetry/events.ts
+++ b/packages/shared/src/telemetry/events.ts
@@ -112,6 +112,7 @@ export function trackAgentTaskCompleted(
agentId: string;
adapterType: RawDimension<EventDimensionsMap["agent.task_completed"]["adapter_type"]>;
model?: string;
+ taskId?: string;
},
): void {
client.track("agent.task_completed", {
@@ -119,6 +120,36 @@ export function trackAgentTaskCompleted(
agent_id: dims.agentId,
adapter_type: asEventDimension(dims.adapterType),
...(dims.model ? { model: dims.model } : {}),
+ ...(dims.taskId ? { task_id: client.hashPrivateRef(dims.taskId) } : {}),
+ });
+}
+
+export function trackAgentTaskRun(
+ client: TelemetryClient,
+ dims: {
+ agentId: string;
+ state: RawDimension<EventDimensionsMap["agent.task_run"]["state"]>;
+ adapterType?: RawDimension<EventDimensionsMap["agent.task_run"]["adapter_type"]>;
+ agentRole?: RawDimension<EventDimensionsMap["agent.task_run"]["agent_role"]>;
+ model?: string;
+ durationSeconds?: number;
+ inputTokens?: number;
+ outputTokens?: number;
+ cachedTokens?: number;
+ taskId?: string;
+ },
+): void {
+ client.track("agent.task_run", {
+ agent_id: dims.agentId,
+ state: asEventDimension(dims.state),
+ ...(dims.adapterType ? { adapter_type: asEventDimension(dims.adapterType) } : {}),
+ ...(dims.agentRole ? { agent_role: asEventDimension(dims.agentRole) } : {}),
+ ...(dims.model ? { model: dims.model } : {}),
+ ...(dims.durationSeconds === undefined ? {} : { duration_seconds: dims.durationSeconds }),
+ ...(dims.inputTokens === undefined ? {} : { input_tokens: dims.inputTokens }),
+ ...(dims.outputTokens === undefined ? {} : { output_tokens: dims.outputTokens }),
+ ...(dims.cachedTokens === undefined ? {} : { cached_tokens: dims.cachedTokens }),
+ ...(dims.taskId ? { task_id: client.hashPrivateRef(dims.taskId) } : {}),
});
}
diff --git a/packages/shared/src/telemetry/generated/paperclip-telemetry.ts b/packages/shared/src/telemetry/generated/paperclip-telemetry.ts
index d75d145474..b0efe356e7 100644
--- a/packages/shared/src/telemetry/generated/paperclip-telemetry.ts
+++ b/packages/shared/src/telemetry/generated/paperclip-telemetry.ts
@@ -15,6 +15,20 @@ adapter_type: ("process" | "http" | "acpx_local" | "claude_local" | "codex_local
agent_id: string
agent_role: ("ceo" | "cto" | "cmo" | "cfo" | "security" | "engineer" | "designer" | "pm" | "qa" | "devops" | "researcher" | "general" | "other")
model?: string
+task_id?: string
+}
+
+export interface PaperclipAgentTaskRunDimensions {
+adapter_type?: ("process" | "http" | "acpx_local" | "claude_local" | "codex_local" | "cursor_cloud" | "gemini_local" | "hermes_gateway" | "hermes_local" | "opencode_local" | "pi_local" | "cursor" | "openclaw_gateway" | "grok_local" | "kimi_local" | "other")
+agent_id: string
+agent_role?: ("ceo" | "cto" | "cmo" | "cfo" | "security" | "engineer" | "designer" | "pm" | "qa" | "devops" | "researcher" | "general" | "other")
+model?: string
+state: ("succeeded" | "interrupted" | "failed" | "cancelled" | "timed_out")
+duration_seconds?: number
+input_tokens?: number
+output_tokens?: number
+cached_tokens?: number
+task_id?: string
}
export interface PaperclipCompanyImportedDimensions {
@@ -89,6 +103,7 @@ export type PaperclipEventName =
| "agent.created"
| "agent.first_heartbeat"
| "agent.task_completed"
+ | "agent.task_run"
| "company.imported"
| "error.handler_crash"
| "goal.created"
@@ -105,6 +120,7 @@ export interface EventDimensionsMap {
"agent.created": PaperclipAgentCreatedDimensions;
"agent.first_heartbeat": PaperclipAgentFirstHeartbeatDimensions;
"agent.task_completed": PaperclipAgentTaskCompletedDimensions;
+ "agent.task_run": PaperclipAgentTaskRunDimensions;
"company.imported": PaperclipCompanyImportedDimensions;
"error.handler_crash": PaperclipErrorHandlerCrashDimensions;
"goal.created": PaperclipGoalCreatedDimensions;
@@ -122,6 +138,7 @@ export const PAPERCLIP_EVENTS = {
"agent.created": "agent.created",
"agent.first_heartbeat": "agent.first_heartbeat",
"agent.task_completed": "agent.task_completed",
+ "agent.task_run": "agent.task_run",
"company.imported": "company.imported",
"error.handler_crash": "error.handler_crash",
"goal.created": "goal.created",
@@ -174,7 +191,42 @@ export const PAPERCLIP_ENUM_DESCRIPTIONS = {
"adapter_type": {
"process": "Agent runtime uses a local process adapter.",
"http": "Agent runtime uses a generic HTTP adapter.",
- "acpx_local": "Agent runtime used the retired local ACPX adapter.",
+ "acpx_local": "Agent runtime uses the local ACPX adapter.",
+ "claude_local": "Agent runtime uses the local Claude adapter.",
+ "codex_local": "Agent runtime uses the local Codex adapter.",
+ "cursor_cloud": "Agent runtime uses the Cursor cloud adapter.",
+ "gemini_local": "Agent runtime uses the local Gemini adapter.",
+ "hermes_gateway": "Agent runtime uses the Hermes gateway adapter.",
+ "hermes_local": "Agent runtime uses the local Hermes adapter.",
+ "opencode_local": "Agent runtime uses the local OpenCode adapter.",
+ "pi_local": "Agent runtime uses the local Pi adapter.",
+ "cursor": "Agent runtime uses the Cursor adapter.",
+ "openclaw_gateway": "Agent runtime uses the OpenClaw gateway adapter.",
+ "grok_local": "Agent runtime uses the local Grok adapter.",
+ "kimi_local": "Agent runtime uses the local Kimi adapter.",
+ "other": "Fallback when the adapter type is unknown or not represented by the tracked enum."
+ },
+ "agent_role": {
+ "ceo": "Agent configured for company leadership and board coordination work.",
+ "cto": "Agent configured for technical leadership, architecture, and engineering coordination.",
+ "cmo": "Agent configured for marketing leadership work.",
+ "cfo": "Agent configured for finance leadership work.",
+ "security": "Agent configured for security review, risk, or policy work.",
+ "engineer": "Agent configured for general software engineering work.",
+ "designer": "Agent configured for product, visual, or experience design work.",
+ "pm": "Agent configured for product management or planning work.",
+ "qa": "Agent configured for quality assurance, testing, or validation work.",
+ "devops": "Agent configured for infrastructure, deployment, or operations work.",
+ "researcher": "Agent configured for research and information-gathering work.",
+ "general": "Agent configured as a general-purpose worker without a more specific role.",
+ "other": "Fallback when the agent role is unknown or not represented by the tracked enum."
+ }
+ },
+ "agent.task_run": {
+ "adapter_type": {
+ "process": "Agent runtime uses a local process adapter.",
+ "http": "Agent runtime uses a generic HTTP adapter.",
+ "acpx_local": "Agent runtime uses the local ACPX adapter.",
"claude_local": "Agent runtime uses the local Claude adapter.",
"codex_local": "Agent runtime uses the local Codex adapter.",
"cursor_cloud": "Agent runtime uses the Cursor cloud adapter.",
@@ -203,6 +255,13 @@ export const PAPERCLIP_ENUM_DESCRIPTIONS = {
"researcher": "Agent configured for research and information-gathering work.",
"general": "Agent configured as a general-purpose worker without a more specific role.",
"other": "Fallback when the agent role is unknown or not represented by the tracked enum."
+ },
+ "state": {
+ "succeeded": "The agent run finished its task and reached a successful terminal state.",
+ "interrupted": "A user or the board interrupted the agent run before it finished.",
+ "failed": "The agent run reached a terminal state because of an unrecoverable error.",
+ "cancelled": "The agent run was cancelled before it reached a successful terminal state.",
+ "timed_out": "The agent run reached its time limit before it finished."
}
},
"company.imported": {
@@ -228,7 +287,7 @@ export const PAPERCLIP_ENUM_DESCRIPTIONS = {
"adapter_type": {
"process": "Agent runtime uses a local process adapter.",
"http": "Agent runtime uses a generic HTTP adapter.",
- "acpx_local": "Agent runtime used the retired local ACPX adapter.",
+ "acpx_local": "Agent runtime uses the local ACPX adapter.",
"claude_local": "Agent runtime uses the local Claude adapter.",
"codex_local": "Agent runtime uses the local Codex adapter.",
"cursor_cloud": "Agent runtime uses the Cursor cloud adapter.",
@@ -368,6 +427,12 @@ export interface PaperclipTelemetryBatch {
app: "paperclip"
schemaVersion: typeof SCHEMA_VERSION
installId: string
+/**
+ * Optional client application build version. Paperclip clients report PEP 440
+ * local versions such as <nearest-tag>+<commits-since-tag>.git.<abbrev-sha>;
+ * nearest tags are usually CalVer, but legacy SemVer tags such as 0.3.1 can
+ * appear. Ingest documents this shape but does not strictly enforce PEP 440.
+ */
version?: string
events: AnyPaperclipTelemetryEvent[]
}
@@ -383,6 +448,12 @@ export function makeEvent<K extends PaperclipEventName>(
export function makeBatch(
installId: string,
events: readonly AnyPaperclipTelemetryEvent[],
+ /**
+ * Optional client application build version. Paperclip clients report PEP 440
+ * local versions such as <nearest-tag>+<commits-since-tag>.git.<abbrev-sha>;
+ * nearest tags are usually CalVer, but legacy SemVer tags such as 0.3.1 can
+ * appear. Ingest documents this shape but does not strictly enforce PEP 440.
+ */
version?: string
): PaperclipTelemetryBatch {
return {
diff --git a/packages/shared/src/telemetry/index.ts b/packages/shared/src/telemetry/index.ts
index b0ef0da089..7628cac592 100644
--- a/packages/shared/src/telemetry/index.ts
+++ b/packages/shared/src/telemetry/index.ts
@@ -14,6 +14,7 @@ export {
trackSkillImported,
trackAgentFirstHeartbeat,
trackAgentTaskCompleted,
+ trackAgentTaskRun,
trackErrorHandlerCrash,
trackInteractionCreated,
trackInteractionResolved,
diff --git a/server/src/__tests__/agent-task-run-telemetry.test.ts b/server/src/__tests__/agent-task-run-telemetry.test.ts
new file mode 100644
index 0000000000..ef036b73e4
--- /dev/null
+++ b/server/src/__tests__/agent-task-run-telemetry.test.ts
@@ -0,0 +1,291 @@
+import { randomUUID } from "node:crypto";
+import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
+import { agents, companies, createDb, heartbeatRuns } from "@paperclipai/db";
+import {
+ getEmbeddedPostgresTestSupport,
+ startEmbeddedPostgresTestDatabase,
+} from "./helpers/embedded-postgres.js";
+
+const mockTelemetryClient = vi.hoisted(() => ({ track: vi.fn() }));
+const mockTrackAgentTaskRun = vi.hoisted(() => vi.fn());
+
+vi.mock("../telemetry.js", () => ({
+ getTelemetryClient: () => mockTelemetryClient,
+}));
+
+vi.mock("@paperclipai/shared/telemetry", async () => {
+ const actual = await vi.importActual<typeof import("@paperclipai/shared/telemetry")>(
+ "@paperclipai/shared/telemetry",
+ );
+ return {
+ ...actual,
+ trackAgentTaskRun: mockTrackAgentTaskRun,
+ };
+});
+
+import { emitAgentTaskRun } from "../services/agent-task-run-telemetry.ts";
+
+const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
+const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
+
+describeEmbeddedPostgres("emitAgentTaskRun", () => {
+ let db!: ReturnType<typeof createDb>;
+ let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
+ let companyId!: string;
+ let agentId!: string;
+
+ beforeAll(async () => {
+ tempDb = await startEmbeddedPostgresTestDatabase("paperclip-agent-task-run-telemetry-");
+ db = createDb(tempDb.connectionString);
+ }, 20_000);
+
+ afterEach(async () => {
+ vi.clearAllMocks();
+ await db.delete(heartbeatRuns);
+ await db.delete(agents);
+ await db.delete(companies);
+ });
+
+ afterAll(async () => {
+ await tempDb?.cleanup();
+ });
+
+ async function seedCompanyAndAgent(
+ agentOverrides: Partial<typeof agents.$inferInsert> = {},
+ ) {
+ companyId = randomUUID();
+ agentId = randomUUID();
+ await db.insert(companies).values({
+ id: companyId,
+ name: "Paperclip",
+ issuePrefix: `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`,
+ requireBoardApprovalForNewAgents: false,
+ defaultResponsibleUserId: "responsible-user",
+ });
+ await db.insert(agents).values({
+ id: agentId,
+ companyId,
+ name: "CodexCoder",
+ role: "engineer",
+ status: "active",
+ adapterType: "codex_local",
+ adapterConfig: {},
+ runtimeConfig: {},
+ permissions: {},
+ ...agentOverrides,
+ });
+ return { companyId, agentId };
+ }
+
+ it("emits one agent.task_run event for each of the five terminal states", async () => {
+ await seedCompanyAndAgent();
+ const states = ["succeeded", "interrupted", "failed", "cancelled", "timed_out"] as const;
+ for (const state of states) {
+ mockTrackAgentTaskRun.mockClear();
+ const runId = randomUUID();
+ const run = {
+ id: runId,
+ companyId,
+ agentId,
+ status: state,
+ startedAt: null,
+ finishedAt: null,
+ usageJson: null,
+ contextSnapshot: null,
+ } as unknown as typeof heartbeatRuns.$inferSelect;
+
+ await emitAgentTaskRun(db, run);
+
+ expect(mockTrackAgentTaskRun).toHaveBeenCalledTimes(1);
+ expect(mockTrackAgentTaskRun).toHaveBeenCalledWith(
+ mockTelemetryClient,
+ expect.objectContaining({ agentId, state }),
+ );
+ }
+ });
+
+ it("omits durationSeconds when the run has no startedAt", async () => {
+ await seedCompanyAndAgent();
+ const run = {
+ id: randomUUID(),
+ companyId,
+ agentId,
+ status: "succeeded",
+ startedAt: null,
+ finishedAt: null,
+ usageJson: null,
+ contextSnapshot: null,
+ } as unknown as typeof heartbeatRuns.$inferSelect;
+
+ await emitAgentTaskRun(db, run);
+
+ const dims = mockTrackAgentTaskRun.mock.calls[0][1];
+ expect(dims).not.toHaveProperty("durationSeconds");
+ });
+
+ it("sends whole seconds from startedAt to finishedAt", async () => {
+ await seedCompanyAndAgent();
+ const startedAt = new Date("2026-01-01T00:00:00.000Z");
+ const finishedAt = new Date("2026-01-01T00:00:07.400Z");
+ const run = {
+ id: randomUUID(),
+ companyId,
+ agentId,
+ status: "succeeded",
+ startedAt,
+ finishedAt,
+ usageJson: null,
+ contextSnapshot: null,
+ } as unknown as typeof heartbeatRuns.$inferSelect;
+
+ await emitAgentTaskRun(db, run);
+
+ const dims = mockTrackAgentTaskRun.mock.calls[0][1];
+ expect(dims.durationSeconds).toBe(7);
+ expect(Number.isInteger(dims.durationSeconds)).toBe(true);
+ });
+
+ it("never returns a negative durationSeconds when finishedAt precedes startedAt", async () => {
+ await seedCompanyAndAgent();
+ const startedAt = new Date("2026-01-01T00:00:10.000Z");
+ const finishedAt = new Date("2026-01-01T00:00:05.000Z");
+ const run = {
+ id: randomUUID(),
+ companyId,
+ agentId,
+ status: "cancelled",
+ startedAt,
+ finishedAt,
+ usageJson: null,
+ contextSnapshot: null,
+ } as unknown as typeof heartbeatRuns.$inferSelect;
+
+ await emitAgentTaskRun(db, run);
+
+ const dims = mockTrackAgentTaskRun.mock.calls[0][1];
+ expect(dims.durationSeconds).toBe(0);
+ });
+
+ it("omits model, the three token dimensions, and taskId when each source is absent", async () => {
+ await seedCompanyAndAgent({ adapterConfig: {} });
+ const run = {
+ id: randomUUID(),
+ companyId,
+ agentId,
+ status: "failed",
+ startedAt: null,
+ finishedAt: null,
+ usageJson: null,
+ contextSnapshot: null,
+ } as unknown as typeof heartbeatRuns.$inferSelect;
+
+ await emitAgentTaskRun(db, run);
+
+ const dims = mockTrackAgentTaskRun.mock.calls[0][1];
+ expect(dims).not.toHaveProperty("model");
+ expect(dims).not.toHaveProperty("inputTokens");
+ expect(dims).not.toHaveProperty("outputTokens");
+ expect(dims).not.toHaveProperty("cachedTokens");
+ expect(dims).not.toHaveProperty("taskId");
+ });
+
+ it("sends cachedTokens: 0 when usage exists and carries no cached value", async () => {
+ await seedCompanyAndAgent();
+ const run = {
+ id: randomUUID(),
+ companyId,
+ agentId,
+ status: "succeeded",
+ startedAt: null,
+ finishedAt: null,
+ usageJson: { inputTokens: 12, outputTokens: 34 },
+ contextSnapshot: null,
+ } as unknown as typeof heartbeatRuns.$inferSelect;
+
+ await emitAgentTaskRun(db, run);
+
+ const dims = mockTrackAgentTaskRun.mock.calls[0][1];
+ expect(dims.inputTokens).toBe(12);
+ expect(dims.outputTokens).toBe(34);
+ expect(dims.cachedTokens).toBe(0);
+ });
+
+ it("emits with no taskId when contextSnapshot carries no issueId", async () => {
+ await seedCompanyAndAgent();
+ const run = {
+ id: randomUUID(),
+ companyId,
+ agentId,
+ status: "succeeded",
+ startedAt: null,
+ finishedAt: null,
+ usageJson: null,
+ contextSnapshot: { wakeReason: "issue_commented" },
+ } as unknown as typeof heartbeatRuns.$inferSelect;
+
+ await emitAgentTaskRun(db, run);
+
+ const dims = mockTrackAgentTaskRun.mock.calls[0][1];
+ expect(dims).not.toHaveProperty("taskId");
+ });
+
+ it("passes the raw task identifier to trackAgentTaskRun without hashing it", async () => {
+ await seedCompanyAndAgent();
+ const rawIssueId = randomUUID();
+ const run = {
+ id: randomUUID(),
+ companyId,
+ agentId,
+ status: "succeeded",
+ startedAt: null,
+ finishedAt: null,
+ usageJson: null,
+ contextSnapshot: { issueId: rawIssueId },
+ } as unknown as typeof heartbeatRuns.$inferSelect;
+
+ await emitAgentTaskRun(db, run);
+
+ const dims = mockTrackAgentTaskRun.mock.calls[0][1];
+ expect(dims.taskId).toBe(rawIssueId);
+ expect(dims.taskId).not.toMatch(/^[0-9a-f]{32}$/);
+ });
+
+ it("does not throw out of the status write when the emit fails", async () => {
+ await seedCompanyAndAgent();
+ mockTrackAgentTaskRun.mockImplementationOnce(() => {
+ throw new Error("telemetry backend unreachable");
+ });
+ const run = {
+ id: randomUUID(),
+ companyId,
+ agentId,
+ status: "succeeded",
+ startedAt: null,
+ finishedAt: null,
+ usageJson: null,
+ contextSnapshot: null,
+ } as unknown as typeof heartbeatRuns.$inferSelect;
+
+ await expect(emitAgentTaskRun(db, run)).resolves.toBeUndefined();
+ });
+
+ it("omits adapterType and agentRole when the agent row is absent", async () => {
+ await seedCompanyAndAgent();
+ const run = {
+ id: randomUUID(),
+ companyId,
+ agentId: randomUUID(),
+ status: "succeeded",
+ startedAt: null,
+ finishedAt: null,
+ usageJson: null,
+ contextSnapshot: null,
+ } as unknown as typeof heartbeatRuns.$inferSelect;
+
+ await emitAgentTaskRun(db, run);
+
+ const dims = mockTrackAgentTaskRun.mock.calls[0][1];
+ expect(dims).not.toHaveProperty("adapterType");
+ expect(dims).not.toHaveProperty("agentRole");
+ });
+});
diff --git a/server/src/__tests__/heartbeat-lock-release-on-reassignment.test.ts b/server/src/__tests__/heartbeat-lock-release-on-reassignment.test.ts
index 2345748bec..80dbae6822 100644
--- a/server/src/__tests__/heartbeat-lock-release-on-reassignment.test.ts
+++ b/server/src/__tests__/heartbeat-lock-release-on-reassignment.test.ts
@@ -1,6 +1,6 @@
import { randomUUID } from "node:crypto";
import { and, eq } from "drizzle-orm";
-import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
+import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import {
agents,
agentRuntimeState,
@@ -15,6 +15,25 @@ import {
getEmbeddedPostgresTestSupport,
startEmbeddedPostgresTestDatabase,
} from "./helpers/embedded-postgres.js";
+import { drainHeartbeatRunsToQuiescence } from "./helpers/drain-heartbeat-runs.js";
+
+const mockTelemetryClient = vi.hoisted(() => ({ track: vi.fn() }));
+const mockTrackAgentTaskRun = vi.hoisted(() => vi.fn());
+
+vi.mock("../telemetry.js", () => ({
+ getTelemetryClient: () => mockTelemetryClient,
+}));
+
+vi.mock("@paperclipai/shared/telemetry", async () => {
+ const actual = await vi.importActual<typeof import("@paperclipai/shared/telemetry")>(
+ "@paperclipai/shared/telemetry",
+ );
+ return {
+ ...actual,
+ trackAgentTaskRun: mockTrackAgentTaskRun,
+ };
+});
+
import { heartbeatService } from "../services/heartbeat.ts";
const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
@@ -28,14 +47,17 @@ if (!embeddedPostgresSupport.supported) {
describeEmbeddedPostgres("heartbeat lock release on cross-agent reassignment", () => {
let db!: ReturnType<typeof createDb>;
+ let heartbeat!: ReturnType<typeof heartbeatService>;
let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
beforeAll(async () => {
tempDb = await startEmbeddedPostgresTestDatabase("heartbeat-lock-release-on-reassignment-");
db = createDb(tempDb.connectionString);
+ heartbeat = heartbeatService(db);
}, 60_000);
afterEach(async () => {
+ await drainHeartbeatRunsToQuiescence(db, heartbeat);
await db.delete(heartbeatRunEvents);
await db.delete(heartbeatRuns);
await db.delete(agentWakeupRequests);
@@ -43,6 +65,7 @@ describeEmbeddedPostgres("heartbeat lock release on cross-agent reassignment", (
await db.delete(agentRuntimeState);
await db.delete(agents);
await db.delete(companies);
+ vi.clearAllMocks();
});
afterAll(async () => {
@@ -63,6 +86,7 @@ describeEmbeddedPostgres("heartbeat lock release on cross-agent reassignment", (
name: "Paperclip",
issuePrefix,
requireBoardApprovalForNewAgents: false,
+ defaultResponsibleUserId: "responsible-user",
});
await db.insert(agents).values([
@@ -270,4 +294,69 @@ describeEmbeddedPostgres("heartbeat lock release on cross-agent reassignment", (
expect(issue?.executionRunId).toBe(holderRunId);
});
+
+ it("cancels a queued holder's run on reassignment and emits agent.task_run for it", async () => {
+ const { companyId, coderAgentId, reviewerAgentId, issueId, holderRunId } =
+ await seedCrossAgentScenario({ holderStatus: "queued" });
+
+ // Keep the reviewer's queue from auto-claiming/executing the new run
+ // during this unit test, matching the pattern used for the sibling
+ // reassignment scenario in heartbeat-retry-scheduling.test.ts: cap
+ // concurrency at 1, then occupy that one slot with a busy run.
+ await db
+ .update(agents)
+ .set({
+ runtimeConfig: { heartbeat: { wakeOnDemand: true, maxConcurrentRuns: 1 } },
+ })
+ .where(eq(agents.id, reviewerAgentId));
+ await db.insert(heartbeatRuns).values({
+ id: randomUUID(),
+ companyId,
+ agentId: reviewerAgentId,
+ invocationSource: "automation",
+ triggerDetail: "system",
+ status: "running",
+ contextSnapshot: { wakeReason: "test_busy_slot" },
+ startedAt: new Date(),
+ });
+
+ const heartbeat = heartbeatService(db);
+ const newAssigneeRun = await heartbeat.wakeup(reviewerAgentId, {
+ source: "automation",
+ triggerDetail: "system",
+ reason: "issue_assigned",
+ payload: { issueId },
+ contextSnapshot: { issueId, taskId: issueId, wakeReason: "issue_assigned" },
+ requestedByActorType: "user",
+ requestedByActorId: "local-board",
+ });
+
+ expect(newAssigneeRun).not.toBeNull();
+ expect(newAssigneeRun?.agentId).toBe(reviewerAgentId);
+ expect(newAssigneeRun?.status).toBe("queued");
+
+ const holder = await db
+ .select({ status: heartbeatRuns.status, errorCode: heartbeatRuns.errorCode })
+ .from(heartbeatRuns)
+ .where(eq(heartbeatRuns.id, holderRunId))
+ .then((rows) => rows[0] ?? null);
+
+ expect(holder).toEqual({
+ status: "cancelled",
+ errorCode: "lock_released_on_reassignment",
+ });
+
+ // The cancel runs inside enqueueWakeup's transaction, and the run's own
+ // required lifecycle work never awaits the telemetry emission, so wait
+ // for it here instead of asserting it fired synchronously.
+ await vi.waitFor(() => {
+ expect(mockTrackAgentTaskRun).toHaveBeenCalledWith(
+ mockTelemetryClient,
+ expect.objectContaining({
+ agentId: coderAgentId,
+ state: "cancelled",
+ }),
+ );
+ });
+ });
});
diff --git a/server/src/__tests__/heartbeat-retry-scheduling.test.ts b/server/src/__tests__/heartbeat-retry-scheduling.test.ts
index bc04d27db2..28683fa801 100644
--- a/server/src/__tests__/heartbeat-retry-scheduling.test.ts
+++ b/server/src/__tests__/heartbeat-retry-scheduling.test.ts
@@ -1,6 +1,6 @@
import { randomUUID } from "node:crypto";
import { and, eq, inArray, sql } from "drizzle-orm";
-import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
+import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import {
agents,
agentRuntimeState,
@@ -24,6 +24,24 @@ import {
} from "./helpers/embedded-postgres.js";
import { drainHeartbeatRunsToQuiescence } from "./helpers/drain-heartbeat-runs.js";
import { registerServerAdapter, unregisterServerAdapter } from "../adapters/index.ts";
+
+const mockTelemetryClient = vi.hoisted(() => ({ track: vi.fn() }));
+const mockTrackAgentTaskRun = vi.hoisted(() => vi.fn());
+
+vi.mock("../telemetry.js", () => ({
+ getTelemetryClient: () => mockTelemetryClient,
+}));
+
+vi.mock("@paperclipai/shared/telemetry", async () => {
+ const actual = await vi.importActual<typeof import("@paperclipai/shared/telemetry")>(
+ "@paperclipai/shared/telemetry",
+ );
+ return {
+ ...actual,
+ trackAgentTaskRun: mockTrackAgentTaskRun,
+ };
+});
+
import {
BOUNDED_TRANSIENT_HEARTBEAT_RETRY_DELAYS_MS,
INTERACTION_CONTINUATION_INFRA_RETRY_REASON,
@@ -100,6 +118,7 @@ describeEmbeddedPostgres("heartbeat bounded retry scheduling", () => {
// a late write races the deletes and can deadlock or break a foreign key.
await drainHeartbeatRunsToQuiescence(db, heartbeat);
await cleanupRetryFixture();
+ vi.clearAllMocks();
});
afterAll(async () => {
@@ -1670,6 +1689,20 @@ describeEmbeddedPostgres("heartbeat bounded retry scheduling", () => {
.where(eq(agentWakeupRequests.status, "deferred_issue_execution"))
.then((rows) => rows[0]?.count ?? 0);
expect(deferredWakeups).toBe(0);
+
+ // The stale-retry cancel runs inside enqueueWakeup's transaction, and
+ // the run's own required lifecycle work never awaits the telemetry
+ // emission, so wait for it here instead of asserting it fired
+ // synchronously.
+ await vi.waitFor(() => {
+ expect(mockTrackAgentTaskRun).toHaveBeenCalledWith(
+ mockTelemetryClient,
+ expect.objectContaining({
+ agentId: oldAgentId,
+ state: "cancelled",
+ }),
+ );
+ });
});
it("does not promote a scheduled retry after issue ownership changes", async () => {
diff --git a/server/src/__tests__/heartbeat-status-preserving-telemetry.test.ts b/server/src/__tests__/heartbeat-status-preserving-telemetry.test.ts
new file mode 100644
index 0000000000..9872be6d8d
--- /dev/null
+++ b/server/src/__tests__/heartbeat-status-preserving-telemetry.test.ts
@@ -0,0 +1,133 @@
+import { randomUUID } from "node:crypto";
+import { eq } from "drizzle-orm";
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
+import {
+ agents,
+ companies,
+ createDb,
+ heartbeatRuns,
+ issues,
+ nativeRunFinalizations,
+} from "@paperclipai/db";
+import {
+ getEmbeddedPostgresTestSupport,
+ startEmbeddedPostgresTestDatabase,
+} from "./helpers/embedded-postgres.js";
+
+const mockTelemetryClient = vi.hoisted(() => ({
+ track: vi.fn(),
+ hashPrivateRef: vi.fn((value: string) => `hashed:${value}`),
+}));
+vi.mock("../telemetry.js", () => ({
+ getTelemetryClient: () => mockTelemetryClient,
+}));
+
+import { heartbeatService } from "../services/heartbeat.ts";
+
+function agentTaskRunCalls(fromIndex: number) {
+ return mockTelemetryClient.track.mock.calls
+ .slice(fromIndex)
+ .filter((call) => call[0] === "agent.task_run");
+}
+
+const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
+const describeEmbeddedPostgres = embeddedPostgresSupport.supported
+ ? describe
+ : describe.skip;
+
+if (!embeddedPostgresSupport.supported) {
+ console.warn(
+ `Skipping embedded Postgres status-preserving telemetry tests on this host: ${
+ embeddedPostgresSupport.reason ?? "unsupported environment"
+ }`,
+ );
+}
+
+describeEmbeddedPostgres(
+ "heartbeat status-preserving run writes do not re-emit agent.task_run",
+ () => {
+ let db!: ReturnType<typeof createDb>;
+ let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null =
+ null;
+
+ beforeAll(async () => {
+ tempDb = await startEmbeddedPostgresTestDatabase(
+ "heartbeat-status-preserving-telemetry-",
+ );
+ db = createDb(tempDb.connectionString);
+ }, 60_000);
+
+ afterAll(async () => {
+ await tempDb?.cleanup();
+ });
+
+ it("does not re-emit agent.task_run when a native ownership-unverified write keeps a failed run's status unchanged", async () => {
+ const companyId = randomUUID();
+ const agentId = randomUUID();
+ const runId = randomUUID();
+ const issueId = randomUUID();
+ const issuePrefix = `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`;
+
+ await db.insert(companies).values({
+ id: companyId,
+ name: "Status Preserving Telemetry",
+ issuePrefix,
+ });
+ await db.insert(agents).values({
+ id: agentId,
+ companyId,
+ name: "Native worker",
+ adapterType: "paperclip_runner",
+ status: "running",
+ });
+ await db.insert(issues).values({
+ id: issueId,
+ companyId,
+ title: "Native ownership fixture",
+ status: "in_progress",
+ assigneeAgentId: agentId,
+ issueNumber: 1,
+ identifier: `${issuePrefix}-1`,
+ });
+ // The run is already terminal ("failed") before reapOrphanedRuns runs.
+ // Its process id is this test process's own pid, so isProcessAlive()
+ // reports it as still alive, which is the condition that routes
+ // reapOrphanedRuns into markNativeOwnershipUnverified.
+ await db.insert(heartbeatRuns).values({
+ id: runId,
+ companyId,
+ agentId,
+ status: "failed",
+ runtimeMode: "native",
+ nativeIssueId: issueId,
+ processPid: process.pid,
+ contextSnapshot: { issueId },
+ });
+ await db.insert(nativeRunFinalizations).values({
+ runId,
+ companyId,
+ issueId,
+ phase: "retryable_failure",
+ attempt: 0,
+ });
+
+ const heartbeat = heartbeatService(db);
+ const callsBefore = mockTelemetryClient.track.mock.calls.length;
+ await heartbeat.reapOrphanedRuns();
+
+ const run = await db
+ .select({ status: heartbeatRuns.status, errorCode: heartbeatRuns.errorCode })
+ .from(heartbeatRuns)
+ .where(eq(heartbeatRuns.id, runId))
+ .then((rows) => rows[0]);
+ // The write only re-sets the status the run already had ("failed") while
+ // patching in the ownership-unverified error fields — a status-preserving
+ // update, not a new terminal transition.
+ expect(run).toEqual({
+ status: "failed",
+ errorCode: "native_execution_ownership_unverified",
+ });
+ expect(agentTaskRunCalls(callsBefore)).toHaveLength(0);
+ });
+ },
+);
diff --git a/server/src/__tests__/issue-telemetry-routes.test.ts b/server/src/__tests__/issue-telemetry-routes.test.ts
index 5b97cc2483..db46636f66 100644
--- a/server/src/__tests__/issue-telemetry-routes.test.ts
+++ b/server/src/__tests__/issue-telemetry-routes.test.ts
@@ -215,6 +215,7 @@ describe("issue telemetry routes", () => {
agentId: "agent-1",
adapterType: "codex_local",
model: "claude-sonnet-4-6",
+ taskId: "11111111-1111-4111-8111-111111111111",
});
});
}, 10_000);
diff --git a/server/src/__tests__/recovery-stale-issue-lock-sweep.test.ts b/server/src/__tests__/recovery-stale-issue-lock-sweep.test.ts
index 9c79ea9fa8..67fffd3815 100644
--- a/server/src/__tests__/recovery-stale-issue-lock-sweep.test.ts
+++ b/server/src/__tests__/recovery-stale-issue-lock-sweep.test.ts
@@ -44,6 +44,7 @@ describeEmbeddedPostgres("recovery sweepStaleIssueLocks", () => {
}, 20_000);
afterEach(async () => {
+ mockTelemetryClient.track.mockClear();
await db.delete(nativeRunFinalizations);
await db.delete(issueComments);
await db.delete(issueRelations);
@@ -278,6 +279,18 @@ describeEmbeddedPostgres("recovery sweepStaleIssueLocks", () => {
.where(eq(heartbeatRunEvents.runId, runningRunId))
.then((rows) => rows[0]);
expect(event?.message).toContain("process and sandbox gone");
+
+ // The recovery sweep's own terminal write must emit exactly one
+ // agent.task_run event for the run it just terminalized. The write
+ // never awaits the emission, so wait for it here instead of asserting
+ // it fired synchronously.
+ await vi.waitFor(() => {
+ expect(mockTelemetryClient.track).toHaveBeenCalledTimes(1);
+ });
+ expect(mockTelemetryClient.track).toHaveBeenCalledWith(
+ "agent.task_run",
+ expect.objectContaining({ agent_id: agentId, state: "interrupted" }),
+ );
});
it("preserves a process-less native run while same-run resumption owns its retry", async () => {
@@ -379,6 +392,16 @@ describeEmbeddedPostgres("recovery sweepStaleIssueLocks", () => {
.where(eq(heartbeatRunEvents.runId, runningRunId))
.then((rows) => rows[0]);
expect(event?.message).toContain("issue reached a terminal status");
+
+ // The terminal write never awaits the telemetry emission, so wait for
+ // it here instead of asserting it fired synchronously.
+ await vi.waitFor(() => {
+ expect(mockTelemetryClient.track).toHaveBeenCalledTimes(1);
+ });
+ expect(mockTelemetryClient.track).toHaveBeenCalledWith(
+ "agent.task_run",
+ expect.objectContaining({ agent_id: agentId, state: "succeeded" }),
+ );
});
it("terminalizes a running run to cancelled when its issue is cancelled (reuse-lease path)", async () => {
@@ -411,6 +434,16 @@ describeEmbeddedPostgres("recovery sweepStaleIssueLocks", () => {
.where(eq(heartbeatRuns.id, runningRunId))
.then((rows) => rows[0]?.status);
expect(runStatus).toBe("cancelled");
+
+ // The terminal write never awaits the telemetry emission, so wait for
+ // it here instead of asserting it fired synchronously.
+ await vi.waitFor(() => {
+ expect(mockTelemetryClient.track).toHaveBeenCalledTimes(1);
+ });
+ expect(mockTelemetryClient.track).toHaveBeenCalledWith(
+ "agent.task_run",
+ expect.objectContaining({ agent_id: agentId, state: "cancelled" }),
+ );
});
it("does not terminalize a running run whose process is alive and whose issue is not terminal", async () => {
@@ -445,6 +478,9 @@ describeEmbeddedPostgres("recovery sweepStaleIssueLocks", () => {
.where(eq(heartbeatRuns.id, runningRunId))
.then((rows) => rows[0]?.status);
expect(runStatus).toBe("running");
+
+ // No terminal write happened, so no telemetry event fires.
+ expect(mockTelemetryClient.track).not.toHaveBeenCalled();
});
it("does not terminalize a live run that a terminal issue and an active issue both reference", async () => {
diff --git a/server/src/__tests__/shared-telemetry-events.test.ts b/server/src/__tests__/shared-telemetry-events.test.ts
index 739df8004a..ba09ce85df 100644
--- a/server/src/__tests__/shared-telemetry-events.test.ts
+++ b/server/src/__tests__/shared-telemetry-events.test.ts
@@ -1,8 +1,10 @@
+import { createHash } from "node:crypto";
import { describe, expect, it, vi } from "vitest";
import {
trackAgentCreated,
trackAgentFirstHeartbeat,
trackAgentTaskCompleted,
+ trackAgentTaskRun,
trackInteractionCreated,
trackInteractionResolved,
trackInstallCompleted,
@@ -12,7 +14,7 @@ import type { EventDimensionsMap, TelemetryClient } from "@paperclipai/shared/te
function createClient(): TelemetryClient {
return {
track: vi.fn(),
- hashPrivateRef: vi.fn((value: string) => `hashed:${value}`),
+ hashPrivateRef: vi.fn((value: string) => createHash("sha256").update(value).digest("hex").slice(0, 16)),
} as unknown as TelemetryClient;
}
@@ -79,6 +81,89 @@ describe("shared telemetry agent events", () => {
});
});
+ it("hashes the task id for agent.task_completed and never sends the raw value", () => {
+ const client = createClient();
+ const rawTaskId = "11111111-1111-4111-8111-111111111111";
+
+ trackAgentTaskCompleted(client, {
+ agentRole: "qa",
+ agentId: "33333333-3333-4333-8333-333333333333",
+ adapterType: "codex_local",
+ taskId: rawTaskId,
+ });
+
+ expect(client.hashPrivateRef).toHaveBeenCalledWith(rawTaskId);
+ const sentDimensions = vi.mocked(client.track).mock.calls[0]?.[1] as Record<string, unknown>;
+ expect(sentDimensions.task_id).toMatch(/^[0-9a-f]{16}$/);
+ expect(sentDimensions.task_id).not.toBe(rawTaskId);
+ expect(JSON.stringify(sentDimensions)).not.toContain(rawTaskId);
+ });
+
+ it("omits task_id for agent.task_completed when the caller gives no task id", () => {
+ const client = createClient();
+
+ trackAgentTaskCompleted(client, {
+ agentRole: "qa",
+ agentId: "33333333-3333-4333-8333-333333333333",
+ adapterType: "codex_local",
+ });
+
+ expect(client.hashPrivateRef).not.toHaveBeenCalled();
+ expect(client.track).toHaveBeenCalledWith("agent.task_completed", {
+ agent_role: "qa",
+ agent_id: "33333333-3333-4333-8333-333333333333",
+ adapter_type: "codex_local",
+ });
+ });
+
+ it("sends all ten dimensions for agent.task_run when present", () => {
+ const client = createClient();
+ const rawTaskId = "22222222-2222-4222-8222-222222222222";
+
+ trackAgentTaskRun(client, {
+ agentId: "44444444-4444-4444-8444-444444444444",
+ state: "succeeded",
+ adapterType: "claude_local",
+ agentRole: "engineer",
+ model: "claude-sonnet-5",
+ durationSeconds: 12.5,
+ inputTokens: 100,
+ outputTokens: 200,
+ cachedTokens: 50,
+ taskId: rawTaskId,
+ });
+
+ expect(client.hashPrivateRef).toHaveBeenCalledWith(rawTaskId);
+ const sentDimensions = vi.mocked(client.track).mock.calls[0]?.[1] as Record<string, unknown>;
+ expect(sentDimensions).toMatchObject({
+ agent_id: "44444444-4444-4444-8444-444444444444",
+ state: "succeeded",
+ adapter_type: "claude_local",
+ agent_role: "engineer",
+ model: "claude-sonnet-5",
+ duration_seconds: 12.5,
+ input_tokens: 100,
+ output_tokens: 200,
+ cached_tokens: 50,
+ });
+ expect(sentDimensions.task_id).toMatch(/^[0-9a-f]{16}$/);
+ });
+
+ it("omits every absent optional dimension for agent.task_run", () => {
+ const client = createClient();
+
+ trackAgentTaskRun(client, {
+ agentId: "55555555-5555-4555-8555-555555555555",
+ state: "failed",
+ });
+
+ expect(client.hashPrivateRef).not.toHaveBeenCalled();
+ expect(client.track).toHaveBeenCalledWith("agent.task_run", {
+ agent_id: "55555555-5555-4555-8555-555555555555",
+ state: "failed",
+ });
+ });
+
it("keeps non-agent event dimensions unchanged", () => {
const client = createClient();
diff --git a/server/src/routes/issues.ts b/server/src/routes/issues.ts
index 5d3a61eb93..e038d812af 100644
--- a/server/src/routes/issues.ts
+++ b/server/src/routes/issues.ts
@@ -145,6 +145,7 @@ import {
workProductService,
} from "../services/index.js";
import { questionResponseDeliveryService } from "../services/question-response-delivery.js";
+import { emitAgentTaskRun } from "../services/agent-task-run-telemetry.js";
import { artifactReviewDocumentService } from "../services/artifact-review-documents.js";
import { assertCanResolveProposal } from "../services/secret-proposal-authorization.js";
import { buildDocumentReviewContext, buildPlanReviewContext } from "../services/plan-review-context.js";
@@ -5725,7 +5726,8 @@ export function issueRoutes(
queueId: string;
revision?: string;
}) {
- return db.transaction(async (tx) => {
+ let cancelledRunToEmit: typeof heartbeatRuns.$inferSelect | null = null;
+ const result = await db.transaction(async (tx) => {
const locked = await lockQueuedCommentState({
tx,
issue: input.issue,
@@ -5801,13 +5803,14 @@ export function issueRoutes(
eq(heartbeatRuns.id, locked.queueRun.id),
eq(heartbeatRuns.status, "queued"),
))
- .returning({ id: heartbeatRuns.id })
+ .returning()
.then((rows) => rows[0] ?? null);
if (!cancelledRun) {
throw conflict("The queued message is already being dispatched", {
code: "queued_comment_already_dispatching",
});
}
+ cancelledRunToEmit = cancelledRun;
}
} else {
const updatedWake = await tx
@@ -5862,6 +5865,12 @@ export function issueRoutes(
}),
};
});
+ // Telemetry is best-effort background work; it must not delay the
+ // response with a slow lookup, so fire it and do not await it.
+ if (cancelledRunToEmit) {
+ void emitAgentTaskRun(db, cancelledRunToEmit);
+ }
+ return result;
}
function operatorInterruptCancelOptions(input: { issueId: string; actor: ReturnType<typeof getActorInfo> }) {
@@ -10933,6 +10942,7 @@ export function issueRoutes(
agentId: actorAgent.id,
adapterType: actorAgent.adapterType,
model,
+ taskId: issue.id,
});
}
}
diff --git a/server/src/services/agent-task-run-telemetry.ts b/server/src/services/agent-task-run-telemetry.ts
new file mode 100644
index 0000000000..6a1941d68f
--- /dev/null
+++ b/server/src/services/agent-task-run-telemetry.ts
@@ -0,0 +1,124 @@
+import { eq } from "drizzle-orm";
+import { agents, heartbeatRuns, type Db } from "@paperclipai/db";
+import { trackAgentTaskRun } from "@paperclipai/shared/telemetry";
+import { parseObject } from "../adapters/utils.js";
+import { logger } from "../middleware/logger.js";
+import { getTelemetryClient } from "../telemetry.js";
+
+type HeartbeatRun = typeof heartbeatRuns.$inferSelect;
+
+function readNonEmptyString(value: unknown): string | null {
+ return typeof value === "string" && value.trim().length > 0
+ ? value.trim()
+ : null;
+}
+
+function readUsageToken(
+ source: Record<string, unknown>,
+ ...keys: string[]
+): number {
+ for (const key of keys) {
+ const value = source[key];
+ if (typeof value === "number" && Number.isFinite(value)) {
+ return Math.max(0, Math.floor(value));
+ }
+ }
+ return 0;
+}
+
+function resolveDurationSeconds(
+ run: HeartbeatRun,
+ now: Date,
+): number | undefined {
+ if (!run.startedAt) return undefined;
+ const startedAtMs = new Date(run.startedAt).getTime();
+ const endMs = run.finishedAt ? new Date(run.finishedAt).getTime() : now.getTime();
+ return Math.max(0, Math.round((endMs - startedAtMs) / 1000));
+}
+
+/**
+ * Emits one `agent.task_run` telemetry event for a run that a caller already
+ * wrote to a terminal status. The native runtime and the legacy run engine
+ * both call this function beside each terminal status write. Call this
+ * function after the run commits.
+ *
+ * This function never throws. A telemetry failure must never fail a run.
+ * Telemetry enrichment does an awaited database lookup, so treat this call
+ * as best-effort background work: do not let a caller's own required
+ * lifecycle work (publishing a live event, cancelling a wake, clearing an
+ * issue lock, returning a response) wait behind it. Fire this call with
+ * `void emitAgentTaskRun(...)` and never await it, even alongside other
+ * required work with `Promise.all` — an awaited `Promise.all` still blocks
+ * the caller's return on the slower of the two promises, so it does not
+ * remove the delay.
+ */
+export async function emitAgentTaskRun(db: Db, run: HeartbeatRun): Promise<void> {
+ try {
+ const client = getTelemetryClient();
+ if (!client) return;
+
+ const agent = await db
+ .select({
+ role: agents.role,
+ adapterType: agents.adapterType,
+ adapterConfig: agents.adapterConfig,
+ })
+ .from(agents)
+ .where(eq(agents.id, run.agentId))
+ .then((rows) => rows[0] ?? null);
+
+ const usage = parseObject(run.usageJson);
+ const model =
+ readNonEmptyString(usage.model) ??
+ readNonEmptyString(parseObject(agent?.adapterConfig).model) ??
+ undefined;
+
+ const taskId =
+ readNonEmptyString(parseObject(run.contextSnapshot).issueId) ??
+ undefined;
+
+ trackAgentTaskRun(client, {
+ agentId: run.agentId,
+ state: run.status,
+ ...(agent
+ ? { adapterType: agent.adapterType, agentRole: agent.role }
+ : {}),
+ ...(model ? { model } : {}),
+ ...(() => {
+ const durationSeconds = resolveDurationSeconds(run, new Date());
+ return durationSeconds === undefined ? {} : { durationSeconds };
+ })(),
+ ...(run.usageJson != null
+ ? {
+ inputTokens: readUsageToken(
+ usage,
+ "inputTokens",
+ "input_tokens",
+ "rawInputTokens",
+ "raw_input_tokens",
+ ),
+ outputTokens: readUsageToken(
+ usage,
+ "outputTokens",
+ "output_tokens",
+ "rawOutputTokens",
+ "raw_output_tokens",
+ ),
+ cachedTokens: readUsageToken(
+ usage,
+ "cachedInputTokens",
+ "cached_input_tokens",
+ "cacheReadInputTokens",
+ "cache_read_input_tokens",
+ ),
+ }
+ : {}),
+ ...(taskId ? { taskId } : {}),
+ });
+ } catch (err) {
+ logger.warn(
+ { err, runId: run.id },
+ "failed to emit agent.task_run telemetry",
+ );
+ }
+}
diff --git a/server/src/services/heartbeat.ts b/server/src/services/heartbeat.ts
index af753d2cf5..7d47e4159e 100644
--- a/server/src/services/heartbeat.ts
+++ b/server/src/services/heartbeat.ts
@@ -180,6 +180,7 @@ import {
import { costService } from "./costs.js";
import { trackAgentFirstHeartbeat } from "@paperclipai/shared/telemetry";
import { getTelemetryClient } from "../telemetry.js";
+import { emitAgentTaskRun } from "./agent-task-run-telemetry.js";
import { companySkillService } from "./company-skills.js";
import { budgetService, type BudgetEnforcementScope } from "./budgets.js";
import { secretService, type MissingRuntimeBinding } from "./secrets.js";
@@ -10688,11 +10689,34 @@ export function heartbeatService(
return ensured;
}
+ // Emits agent.task_run for a run write that just reached a terminal
+ // status, unless the write only re-set a status the run already had (a
+ // status-preserving patch, such as a livenessReason update on a run that
+ // finished earlier). Only a genuine transition into a terminal status
+ // emits. The emission runs in the background: it never blocks the
+ // caller's remaining lifecycle work, because emitAgentTaskRun never
+ // throws (it logs and swallows its own failures).
+ function emitTerminalAgentTaskRun(
+ updated: typeof heartbeatRuns.$inferSelect,
+ previousStatus: string | null,
+ ) {
+ if (!isHeartbeatRunTerminalStatus(updated.status)) return;
+ if (previousStatus === updated.status) return;
+ clearHeartbeatRunRuntimeStatus(updated.id);
+ void emitAgentTaskRun(db, updated);
+ }
+
async function setRunStatus(
runId: string,
status: string,
patch?: Partial<typeof heartbeatRuns.$inferInsert>,
) {
+ const previousStatus = await db
+ .select({ status: heartbeatRuns.status })
+ .from(heartbeatRuns)
+ .where(eq(heartbeatRuns.id, runId))
+ .then((rows) => rows[0]?.status ?? null);
+
const updated = await db
.update(heartbeatRuns)
.set({ status, ...patch, updatedAt: new Date() })
@@ -10701,15 +10725,13 @@ export function heartbeatService(
.then((rows) => rows[0] ?? null);
if (updated) {
- if (isHeartbeatRunTerminalStatus(updated.status)) {
- clearHeartbeatRunRuntimeStatus(updated.id);
- }
publishLiveEvent({
companyId: updated.companyId,
type: "heartbeat.run.status",
payload: buildHeartbeatRunStatusLiveEventPayload(updated),
});
publishRunLifecyclePluginEvent(updated);
+ emitTerminalAgentTaskRun(updated, previousStatus);
}
return updated;
@@ -10734,6 +10756,15 @@ export function heartbeatService(
fromStatuses: string[],
patch?: Partial<typeof heartbeatRuns.$inferInsert>,
) {
+ // fromStatuses can name a terminal status as its own source (for example,
+ // an idempotent "still failed" patch), so the write below is not always a
+ // genuine transition. Read the pre-write status to tell the two apart.
+ const previousStatus = await db
+ .select({ status: heartbeatRuns.status })
+ .from(heartbeatRuns)
+ .where(eq(heartbeatRuns.id, runId))
+ .then((rows) => rows[0]?.status ?? null);
+
const updated = await db
.update(heartbeatRuns)
.set({ status, ...patch, updatedAt: new Date() })
@@ -10747,15 +10778,13 @@ export function heartbeatService(
.then((rows) => rows[0] ?? null);
if (updated) {
- if (isHeartbeatRunTerminalStatus(updated.status)) {
- clearHeartbeatRunRuntimeStatus(updated.id);
- }
publishLiveEvent({
companyId: updated.companyId,
type: "heartbeat.run.status",
payload: buildHeartbeatRunStatusLiveEventPayload(updated),
});
publishRunLifecyclePluginEvent(updated);
+ emitTerminalAgentTaskRun(updated, previousStatus);
return { run: updated, updated: true as const };
}
@@ -13260,6 +13289,11 @@ export function heartbeatService(
if (!cancelled) return null;
+ // Telemetry is best-effort background work. Fire it in the background
+ // instead of awaiting it, so a slow telemetry lookup never delays the
+ // wake cancel, the issue lock clear, or this function's return.
+ void emitAgentTaskRun(db, cancelled);
+
if (cancelled.wakeupRequestId) {
await db
.update(agentWakeupRequests)
@@ -15361,6 +15395,9 @@ export function heartbeatService(
},
});
publishRunLifecyclePluginEvent(queuedCommentClaim.run);
+ // Fire-and-forget: nothing else in this path depends on the emission,
+ // so it must not delay the return.
+ void emitAgentTaskRun(db, queuedCommentClaim.run);
return null;
}
const claimed = queuedCommentClaim
@@ -23450,6 +23487,8 @@ export function heartbeatService(
// same issue workspace while the assignee already has a live run.
const agentNameKey = normalizeAgentNameKey(agent.name);
+ const cancelledRunsToEmit: (typeof heartbeatRuns.$inferSelect)[] = [];
+
const outcome = await db.transaction(async (tx) => {
await tx.execute(
sql`select id from issues where id = ${issueId} and company_id = ${agent.companyId} for update`,
@@ -23653,6 +23692,8 @@ export function heartbeatService(
.set({ nextEventSeq: eventSeq + 1, updatedAt: now })
.where(eq(heartbeatRuns.id, cancelled.id));
+ cancelledRunsToEmit.push(cancelled);
+
return true;
};
@@ -23717,8 +23758,9 @@ export function heartbeatService(
eq(heartbeatRuns.status, activeExecutionRun.status),
),
)
- .returning({ id: heartbeatRuns.id });
+ .returning();
if (cancelled.length > 0) {
+ cancelledRunsToEmit.push(cancelled[0]);
if (activeExecutionRun.wakeupRequestId) {
await tx
.update(agentWakeupRequests)
@@ -24348,8 +24390,17 @@ export function heartbeatService(
return { kind: "queued" as const, run: newRun };
});
- if (outcome.kind === "deferred" || outcome.kind === "skipped")
+ // Telemetry for the cancelled runs is best-effort background work.
+ // Fire it here and never await it: none of the lifecycle work below,
+ // nor this function's return, depends on it, so a slow telemetry
+ // lookup must not delay them.
+ for (const cancelledRun of cancelledRunsToEmit) {
+ void emitAgentTaskRun(db, cancelledRun);
+ }
+
+ if (outcome.kind === "deferred" || outcome.kind === "skipped") {
return null;
+ }
if (outcome.kind === "coalesced") {
await startNextQueuedRunForAgent(agent.id);
return outcome.run;
diff --git a/server/src/services/native-runtime/native-finalization-reconciler.ts b/server/src/services/native-runtime/native-finalization-reconciler.ts
index f5b50a8fdf..4e7073c42c 100644
--- a/server/src/services/native-runtime/native-finalization-reconciler.ts
+++ b/server/src/services/native-runtime/native-finalization-reconciler.ts
@@ -22,6 +22,7 @@ import {
} from "./status-decision-committer.js";
import { issueRecoveryActionService } from "../issue-recovery-actions.js";
import { issueService } from "../issues.js";
+import { emitAgentTaskRun } from "../agent-task-run-telemetry.js";
import { resumeNativeWorkspaceFinalization } from "./native-workspace-finalizer.js";
import { classifyNativeEvidence } from "./evidence-classifier.js";
import { recordNativeWorkAssessment } from "./work-assessments.js";
@@ -206,6 +207,7 @@ export async function claimNativeSessionResumptions(input: {
const claims: NativeSessionResumeClaim[] = [];
for (const candidate of candidates) {
const leaseOwner = `${input.runnerInstanceId}:resume:${randomUUID()}`;
+ let terminalRunToEmit: typeof heartbeatRuns.$inferSelect | null = null;
const claimed = await input.db.transaction(async (tx) => {
const row = await tx.select({
run: heartbeatRuns,
@@ -294,7 +296,7 @@ export async function claimNativeSessionResumptions(input: {
nextAttemptAt: null,
updatedAt: now,
}).where(eq(nativeRunFinalizations.runId, row.run.id));
- await tx.update(heartbeatRuns).set({
+ const [updatedRun] = await tx.update(heartbeatRuns).set({
status: "failed",
finishedAt: now,
nativePhase: "terminal_failure",
@@ -304,7 +306,8 @@ export async function claimNativeSessionResumptions(input: {
? failureDetail.message
: "Persisted native session state is ambiguous and cannot be resumed safely",
updatedAt: now,
- }).where(eq(heartbeatRuns.id, row.run.id));
+ }).where(eq(heartbeatRuns.id, row.run.id)).returning();
+ terminalRunToEmit = updatedRun ?? null;
await issueService(tx as unknown as Db).update(
row.coordinator.issueId,
{ status: "in_review" },
@@ -359,6 +362,11 @@ export async function claimNativeSessionResumptions(input: {
}).where(eq(heartbeatRuns.id, row.run.id));
return true;
});
+ // Telemetry is best-effort background work; it must not delay claiming
+ // the remaining candidates in this loop, so fire it and do not await it.
+ if (terminalRunToEmit) {
+ void emitAgentTaskRun(input.db, terminalRunToEmit);
+ }
if (claimed) claims.push({ runId: candidate.runId, leaseOwner });
}
return claims;
diff --git a/server/src/services/native-runtime/native-run-finalizer-telemetry.test.ts b/server/src/services/native-runtime/native-run-finalizer-telemetry.test.ts
new file mode 100644
index 0000000000..ab0446d59a
--- /dev/null
+++ b/server/src/services/native-runtime/native-run-finalizer-telemetry.test.ts
@@ -0,0 +1,372 @@
+import { randomUUID } from "node:crypto";
+import { eq } from "drizzle-orm";
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
+import {
+ agents,
+ companies,
+ completionContracts,
+ createDb,
+ heartbeatRuns,
+ issues,
+ nativeRunFinalizations,
+ nativeRunResults,
+ workAssessments,
+} from "@paperclipai/db";
+import {
+ getEmbeddedPostgresTestSupport,
+ startEmbeddedPostgresTestDatabase,
+} from "../../__tests__/helpers/embedded-postgres.js";
+import {
+ CONTROL_PLANE_CONFORMANCE_RESULT,
+ CONTROL_PLANE_CONFORMANCE_TERMINAL,
+} from "../../vendor/paperclip-runner/testing.js";
+
+const mockTelemetryClient = vi.hoisted(() => ({
+ track: vi.fn(),
+ hashPrivateRef: vi.fn((value: string) => `hashed:${value}`),
+}));
+vi.mock("../../telemetry.ts", () => ({ getTelemetryClient: () => mockTelemetryClient }));
+
+function agentTaskRunCalls(fromIndex: number) {
+ return mockTelemetryClient.track.mock.calls
+ .slice(fromIndex)
+ .filter((call) => call[0] === "agent.task_run");
+}
+
+import { PaperclipControlPlanePort } from "./paperclip-control-plane-port.js";
+import { finalizeNativeRun, recordNativeFinalizationFailure } from "./native-run-finalizer.js";
+import { commitNativeStatusDecision } from "./status-decision-committer.js";
+import { NATIVE_STATUS_ARBITER_POLICY_VERSION, type NativeStatusDecision } from "./status-arbiter.js";
+
+const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
+const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
+
+if (!embeddedPostgresSupport.supported) {
+ console.warn(
+ `Skipping embedded Postgres native-finalizer telemetry tests on this host: ${
+ embeddedPostgresSupport.reason ?? "unsupported environment"
+ }`,
+ );
+}
+
+describeEmbeddedPostgres("native run finalizer / status decision committer — agent.task_run emission", () => {
+ let db!: ReturnType<typeof createDb>;
+ let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
+ let companyId: string;
+ let agentId: string;
+
+ beforeAll(async () => {
+ tempDb = await startEmbeddedPostgresTestDatabase("paperclip-native-finalizer-telemetry-");
+ db = createDb(tempDb.connectionString);
+ companyId = randomUUID();
+ agentId = randomUUID();
+ await db.insert(companies).values({ id: companyId, name: "Telemetry", issuePrefix: "TLM" });
+ await db.insert(agents).values({
+ id: agentId,
+ companyId,
+ name: "Native worker",
+ adapterType: "codex_local",
+ status: "running",
+ });
+ }, 30_000);
+
+ afterAll(async () => {
+ await tempDb?.cleanup();
+ });
+
+ async function seedNativeRun() {
+ const issueId = randomUUID();
+ const contractId = randomUUID();
+ const runId = randomUUID();
+ const sessionId = randomUUID();
+ const runnerInstanceId = randomUUID();
+ const contractSha256 = `contract-${contractId}`;
+ await db.insert(issues).values({
+ id: issueId,
+ companyId,
+ title: "Native telemetry fixture",
+ status: "in_progress",
+ assigneeAgentId: agentId,
+ workMode: "standard",
+ });
+ await db.insert(completionContracts).values({
+ id: contractId,
+ companyId,
+ issueId,
+ revision: 1,
+ schemaVersion: "paperclip.completion-contract.v1",
+ policyVersion: "telemetry-v1",
+ risk: "standard",
+ completionAuthority: "server_arbiter",
+ incompleteCriteriaPolicy: "preserve_non_terminal",
+ contractJson: {
+ revision: "telemetry-v1",
+ objective: "Emit telemetry",
+ criteria: [{ id: "objective", requirement: "Complete the task" }],
+ },
+ canonicalSha256: contractSha256,
+ createdByActorType: "system",
+ createdByActorId: "test",
+ });
+ await db.insert(heartbeatRuns).values({
+ id: runId,
+ companyId,
+ agentId,
+ status: "running",
+ runtimeMode: "native",
+ nativeIssueId: issueId,
+ nativeSessionId: sessionId,
+ runnerInstanceId,
+ completionContractId: contractId,
+ completionContractSha256: contractSha256,
+ contextSnapshot: { issueId },
+ });
+ return { issueId, contractId, contractSha256, runId, sessionId, runnerInstanceId };
+ }
+
+ function newPort(fixture: Awaited<ReturnType<typeof seedNativeRun>>) {
+ return new PaperclipControlPlanePort(db, {
+ companyId,
+ issueId: fixture.issueId,
+ runId: fixture.runId,
+ agentId,
+ sessionId: fixture.sessionId,
+ completionContractId: fixture.contractId,
+ completionContractSha256: fixture.contractSha256,
+ sourceInstanceId: fixture.runnerInstanceId,
+ controlPlaneSourceInstanceId: "telemetry-test",
+ });
+ }
+
+ async function driveToCompleteResult(
+ fixture: Awaited<ReturnType<typeof seedNativeRun>>,
+ terminal: typeof CONTROL_PLANE_CONFORMANCE_TERMINAL = CONTROL_PLANE_CONFORMANCE_TERMINAL,
+ ) {
+ const port = newPort(fixture);
+ await port.openRun({
+ identity: {
+ runId: fixture.runId,
+ sessionId: fixture.sessionId,
+ companyId,
+ issueId: fixture.issueId,
+ agentId,
+ },
+ backendKind: "mock",
+ sourceInstanceId: fixture.runnerInstanceId,
+ });
+ await port.completeRun({
+ result: CONTROL_PLANE_CONFORMANCE_RESULT,
+ terminal,
+ callerResultId: `${fixture.runId}:result`,
+ });
+ }
+
+ it("emits exactly one agent.task_run event when the native finalizer commits a terminal status", async () => {
+ const fixture = await seedNativeRun();
+ await driveToCompleteResult(fixture);
+
+ const callsBefore = mockTelemetryClient.track.mock.calls.length;
+ await finalizeNativeRun({
+ db,
+ runId: fixture.runId,
+ workspaceFinalizeStatus: "succeeded",
+ projectRunStatus: true,
+ });
+ const newCalls = agentTaskRunCalls(callsBefore);
+
+ expect(newCalls).toHaveLength(1);
+ expect(newCalls[0]?.[1]).toMatchObject({ agent_id: agentId, state: "succeeded" });
+
+ const run = await db
+ .select({ status: heartbeatRuns.status })
+ .from(heartbeatRuns)
+ .where(eq(heartbeatRuns.id, fixture.runId))
+ .then((rows) => rows[0]);
+ expect(run?.status).toBe("succeeded");
+ });
+
+ it("emits zero events when a repeat finalize call's conditional native write matches no row", async () => {
+ const fixture = await seedNativeRun();
+ await driveToCompleteResult(fixture);
+ await finalizeNativeRun({
+ db,
+ runId: fixture.runId,
+ workspaceFinalizeStatus: "succeeded",
+ projectRunStatus: true,
+ });
+
+ const callsBefore = mockTelemetryClient.track.mock.calls.length;
+ // The coordinator is already "committed", so this second call takes the
+ // projectCommittedRun short-circuit. The run's status is already terminal
+ // ("succeeded"), which sits outside projectCommittedRun's WHERE
+ // (queued/running/failed), so the write matches no row.
+ await finalizeNativeRun({
+ db,
+ runId: fixture.runId,
+ workspaceFinalizeStatus: "succeeded",
+ projectRunStatus: true,
+ });
+ expect(agentTaskRunCalls(callsBefore)).toHaveLength(0);
+ });
+
+ it("emits zero events when a reconciliation replay commits the same failed terminal result again", async () => {
+ const fixture = await seedNativeRun();
+ await driveToCompleteResult(fixture, {
+ ...CONTROL_PLANE_CONFORMANCE_TERMINAL,
+ turnTerminalState: "failed",
+ runTerminalState: "failed",
+ });
+ // workspaceFinalizeStatus reports whether the workspace finalization
+ // step itself succeeded, independent of the run's own terminal state
+ // (runTerminalState below), which is what actually failed here.
+ await finalizeNativeRun({
+ db,
+ runId: fixture.runId,
+ workspaceFinalizeStatus: "succeeded",
+ projectRunStatus: true,
+ });
+ const run = await db
+ .select({ status: heartbeatRuns.status })
+ .from(heartbeatRuns)
+ .where(eq(heartbeatRuns.id, fixture.runId))
+ .then((rows) => rows[0]);
+ expect(run?.status).toBe("failed");
+
+ const callsBefore = mockTelemetryClient.track.mock.calls.length;
+ // The coordinator is already "committed" with a "failed" terminal
+ // result, and the run row is already "failed" — unlike the "succeeded"
+ // case above, "failed" sits INSIDE projectCommittedRun's WHERE clause
+ // (queued/running/failed), so a reconciliation replay's write still
+ // matches the row. The write changes nothing (failed -> failed), so it
+ // must not emit a second event for the same committed result.
+ await finalizeNativeRun({
+ db,
+ runId: fixture.runId,
+ workspaceFinalizeStatus: "succeeded",
+ projectRunStatus: true,
+ });
+ expect(agentTaskRunCalls(callsBefore)).toHaveLength(0);
+ });
+
+ it("emits zero events when a retryable-failure write's conditional status spread is omitted", async () => {
+ const fixture = await seedNativeRun();
+ // recordNativeFinalizationFailure only needs the run and coordinator rows
+ // to exist — no persisted native result is required.
+ await db.insert(nativeRunFinalizations).values({
+ runId: fixture.runId,
+ companyId,
+ issueId: fixture.issueId,
+ phase: "observed",
+ attempt: 0,
+ });
+
+ const callsBefore = mockTelemetryClient.track.mock.calls.length;
+ // projectRunStatus is omitted (falsy): the conditional spread in
+ // recordRetryableFailure never includes `status`, so the write never sets
+ // a terminal status, regardless of the attempt count.
+ await recordNativeFinalizationFailure({
+ db,
+ runId: fixture.runId,
+ error: new Error("native_test_failure"),
+ });
+ expect(agentTaskRunCalls(callsBefore)).toHaveLength(0);
+
+ const run = await db
+ .select({ status: heartbeatRuns.status })
+ .from(heartbeatRuns)
+ .where(eq(heartbeatRuns.id, fixture.runId))
+ .then((rows) => rows[0]);
+ expect(run?.status).toBe("running");
+ });
+
+ it("emits exactly one event for a cancel_continuations write (trap 2: :685/:518 overlap)", async () => {
+ const fixture = await seedNativeRun();
+ // Build the minimal real rows commitNativeStatusDecision's foreign keys
+ // require, without going through the evidence-classifier pipeline.
+ const resultId = randomUUID();
+ await db.insert(nativeRunResults).values({
+ id: resultId,
+ companyId,
+ issueId: fixture.issueId,
+ runId: fixture.runId,
+ completionContractId: fixture.contractId,
+ serverFingerprint: `fp-${resultId}`,
+ schemaStatus: "accepted",
+ resultJson: {},
+ canonicalSha256: `sha-${resultId}`,
+ });
+ const assessmentId = randomUUID();
+ await db.insert(workAssessments).values({
+ id: assessmentId,
+ companyId,
+ issueId: fixture.issueId,
+ runId: fixture.runId,
+ contractId: fixture.contractId,
+ resultId,
+ triggerKind: "native_result",
+ triggerActorCompanyId: companyId,
+ priorIssueStatus: "in_progress",
+ priorStatusVersion: 0,
+ policyVersion: "telemetry-v1",
+ assessmentJson: {},
+ inputDigest: `digest-${assessmentId}`,
+ });
+ await db.insert(nativeRunFinalizations).values({
+ runId: fixture.runId,
+ companyId,
+ issueId: fixture.issueId,
+ phase: "arbitrating",
+ attempt: 0,
+ resultId,
+ });
+
+ // Shaped exactly like resolveNativeCancellationStatus("issue", ...) in
+ // native-session-executor.ts — the only place cancel_continuations is
+ // produced today.
+ const decision: NativeStatusDecision = {
+ policyVersion: NATIVE_STATUS_ARBITER_POLICY_VERSION,
+ statusAction: "cancelled",
+ toStatus: "cancelled",
+ reasonCode: "cancellation_issue_authorized",
+ unblockDescriptor: null,
+ effects: [{ kind: "release_checkout" }, { kind: "cancel_continuations" }],
+ };
+
+ const callsBefore = mockTelemetryClient.track.mock.calls.length;
+ await commitNativeStatusDecision({
+ db,
+ companyId,
+ issueId: fixture.issueId,
+ runId: fixture.runId,
+ assessmentId,
+ priorStatus: "in_progress",
+ priorStatusVersion: 0,
+ priorDecisionId: null,
+ decision,
+ });
+ const afterCommit = agentTaskRunCalls(callsBefore);
+ // status-decision-committer.ts:685 (the cancel_continuations effect)
+ // wrote this run's terminal status and emitted for it.
+ expect(afterCommit).toHaveLength(1);
+ expect(afterCommit[0]?.[1]).toMatchObject({ agent_id: agentId, state: "cancelled" });
+
+ const run = await db
+ .select({ status: heartbeatRuns.status })
+ .from(heartbeatRuns)
+ .where(eq(heartbeatRuns.id, fixture.runId))
+ .then((rows) => rows[0]);
+ expect(run?.status).toBe("cancelled");
+
+ // native-run-finalizer.ts:518's own guard: it skips its emit whenever the
+ // decision it just committed already included cancel_continuations,
+ // because :685 above already wrote and emitted for this run. Reproduce
+ // the exact guard predicate on the same decision object to prove it
+ // resolves to "skip", so the run's total event count for this commit
+ // stays at exactly one even after the finalizer's own write runs.
+ const alreadyEmittedByCommittedDecision = decision.effects.some(
+ (effect) => effect.kind === "cancel_continuations",
+ );
+ expect(alreadyEmittedByCommittedDecision).toBe(true);
+ expect(agentTaskRunCalls(callsBefore)).toHaveLength(1);
+ });
+});
diff --git a/server/src/services/native-runtime/native-run-finalizer.ts b/server/src/services/native-runtime/native-run-finalizer.ts
index bc2b30c894..979013c4d5 100644
--- a/server/src/services/native-runtime/native-run-finalizer.ts
+++ b/server/src/services/native-runtime/native-run-finalizer.ts
@@ -30,6 +30,7 @@ import {
import { issueRecoveryActionService } from "../issue-recovery-actions.js";
import { issueService } from "../issues.js";
import { nativeSha256 } from "./canonical.js";
+import { emitAgentTaskRun } from "../agent-task-run-telemetry.js";
function record(value: unknown): Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value)
@@ -191,6 +192,7 @@ async function recordRetryableFailure(input: {
: acceptedRunTerminalState === "cancelled"
? "cancelled" as const
: "failed" as const;
+ let terminalRunToEmit: typeof heartbeatRuns.$inferSelect | null = null;
const outcome = await input.db.transaction(async (tx) => {
const issue = await tx.select({
lastStatusDecisionId: issues.lastStatusDecisionId,
@@ -253,8 +255,9 @@ async function recordRetryableFailure(input: {
nextAttemptAt: supersededByNewerRun || exhausted ? null : nextAttemptAt,
updatedAt: now,
}).where(eq(nativeRunFinalizations.runId, input.run.id));
- await tx.update(heartbeatRuns).set({
- ...(exhausted && !supersededByNewerRun && input.projectRunStatus ? {
+ const projectsTerminalStatus = exhausted && !supersededByNewerRun && input.projectRunStatus;
+ const [updatedRun] = await tx.update(heartbeatRuns).set({
+ ...(projectsTerminalStatus ? {
status: exhaustedRunStatus,
finishedAt: input.run.finishedAt ?? now,
} : {}),
@@ -268,7 +271,8 @@ async function recordRetryableFailure(input: {
nextAttemptAt: supersededByNewerRun || exhausted ? null : nextAttemptAt.toISOString(),
},
updatedAt: now,
- }).where(eq(heartbeatRuns.id, input.run.id));
+ }).where(eq(heartbeatRuns.id, input.run.id)).returning();
+ if (projectsTerminalStatus) terminalRunToEmit = updatedRun ?? null;
if (supersededByNewerRun) {
await issueRecoveryActionService(tx as unknown as Db).resolveActiveForIssue({
companyId: input.run.companyId,
@@ -311,6 +315,7 @@ async function recordRetryableFailure(input: {
}
return { phase, failureCode, nextAttemptAt: supersededByNewerRun || exhausted ? null : nextAttemptAt };
});
+ if (terminalRunToEmit) await emitAgentTaskRun(input.db, terminalRunToEmit);
return {
...input.coordinator,
...outcome,
@@ -361,7 +366,7 @@ async function projectCommittedRun(input: {
throw new Error("native_finalization_invalid");
}
const now = new Date();
- await input.db.update(heartbeatRuns).set({
+ const [updatedRun] = await input.db.update(heartbeatRuns).set({
status: projectNativeTerminalRunStatus(terminalState as "succeeded" | "failed" | "cancelled"),
finishedAt: input.run.finishedAt ?? now,
nativePhase: "committed",
@@ -371,7 +376,17 @@ async function projectCommittedRun(input: {
eq(heartbeatRuns.id, input.run.id),
eq(heartbeatRuns.runtimeMode, "native"),
inArray(heartbeatRuns.status, ["queued", "running", "failed"]),
- ));
+ )).returning();
+ // The WHERE clause above allows "failed" as a source status, so a run that
+ // failed before its coordinator committed can still pick up the committed
+ // terminal state. A later reconciliation replay can enter this same path
+ // and match that clause again even when the committed state is still
+ // "failed" — the write changes nothing. Emit only when the status
+ // genuinely changed, so a reconciliation replay never emits twice for one
+ // committed terminal result.
+ if (updatedRun && updatedRun.status !== input.run.status) {
+ await emitAgentTaskRun(input.db, updatedRun);
+ }
}
export async function finalizeNativeRun(input: {
@@ -515,7 +530,14 @@ export async function finalizeNativeRun(input: {
const now = new Date();
const finalizationFailed = decision.effects.some((effect) => effect.kind === "record_finalization_error");
const finalizationPhase = finalizationFailed ? "retryable_failure" : "committed";
- await input.db.update(heartbeatRuns).set({
+ // commitNativeStatusDecision() already committed its own transaction above.
+ // Its "cancel_continuations" effect (status-decision-committer.ts) writes a
+ // terminal status to this same run and emits for it. Skip the emit here in
+ // that case so one run reaching a terminal state emits exactly one event.
+ const alreadyEmittedByCommittedDecision = decision.effects.some(
+ (effect) => effect.kind === "cancel_continuations",
+ );
+ const [updatedRun] = await input.db.update(heartbeatRuns).set({
...(input.projectRunStatus ? {
status: terminalState === "succeeded" ? "succeeded" : terminalState === "cancelled" ? "cancelled" : "failed",
finishedAt: now,
@@ -539,7 +561,10 @@ export async function finalizeNativeRun(input: {
workspaceFinalizeStatus: input.workspaceFinalizeStatus,
},
updatedAt: now,
- }).where(eq(heartbeatRuns.id, run.id));
+ }).where(eq(heartbeatRuns.id, run.id)).returning();
+ if (input.projectRunStatus && !alreadyEmittedByCommittedDecision && updatedRun) {
+ await emitAgentTaskRun(input.db, updatedRun);
+ }
return { ...coordinator, phase: finalizationPhase, assessmentId: assessmentRow.id, decisionId: committed.decision.id };
} catch (error) {
if (error instanceof NativeStatusRaceError && attempt < 2) {
diff --git a/server/src/services/native-runtime/status-decision-committer.ts b/server/src/services/native-runtime/status-decision-committer.ts
index 0e1baa3353..8460917811 100644
--- a/server/src/services/native-runtime/status-decision-committer.ts
+++ b/server/src/services/native-runtime/status-decision-committer.ts
@@ -29,6 +29,7 @@ import { issueThreadInteractionService } from "../issue-thread-interactions.js";
import { issueRecoveryActionService } from "../issue-recovery-actions.js";
import { buildIssueBlockersResolvedWakeIdempotencyKey } from "../issue-dependency-wakeups.js";
import { persistActivity, publishActivity, type ActivityPublication } from "../activity-log.js";
+import { emitAgentTaskRun } from "../agent-task-run-telemetry.js";
export class NativeStatusRaceError extends Error {
readonly code = "native_status_race" as const;
@@ -327,6 +328,8 @@ async function materializeDecisionEffect(input: {
effect: NativeStatusEffect;
failpoint?: NativeStatusCommitFailpoint;
preMaterializedEffects?: ReadonlyMap<string, NativeMaterializedStatusEffect>;
+ /** Terminal heartbeat_runs rows this effect wrote. The caller emits agent.task_run for each, after its transaction commits. */
+ terminalRunsToEmit?: (typeof heartbeatRuns.$inferSelect)[];
}): Promise<NativeMaterializedStatusEffect> {
const { effect } = input;
if (effect.kind === "create_interaction") {
@@ -689,8 +692,9 @@ async function materializeDecisionEffect(input: {
}).where(and(
eq(heartbeatRuns.id, input.runId),
eq(heartbeatRuns.companyId, input.companyId),
- )).returning({ id: heartbeatRuns.id });
+ )).returning();
if (!run) throw new Error("native_continuation_cancellation_run_missing");
+ input.terminalRunsToEmit?.push(run);
return {
effectKind: effect.kind,
targetType: "heartbeat_run",
@@ -1033,6 +1037,7 @@ export async function commitNativeStatusDecision(input: {
}
const reasonCode = input.decision.reasonCode;
const publications: ActivityPublication[] = [];
+ const terminalRunsToEmit: (typeof heartbeatRuns.$inferSelect)[] = [];
const committed = await input.db.transaction(async (tx) => {
const coordinator = await tx.select().from(nativeRunFinalizations).where(and(
eq(nativeRunFinalizations.runId, input.runId),
@@ -1136,6 +1141,7 @@ export async function commitNativeStatusDecision(input: {
effect,
failpoint: input.failpoint,
preMaterializedEffects,
+ terminalRunsToEmit,
}));
}
@@ -1333,5 +1339,6 @@ export async function commitNativeStatusDecision(input: {
});
for (const publication of publications) publishActivity(publication);
+ for (const terminalRun of terminalRunsToEmit) await emitAgentTaskRun(input.db, terminalRun);
return committed;
}
diff --git a/server/src/services/recovery/service.ts b/server/src/services/recovery/service.ts
index 8d7655d6d6..ec562ea4ff 100644
--- a/server/src/services/recovery/service.ts
+++ b/server/src/services/recovery/service.ts
@@ -33,6 +33,7 @@ import { redactSensitiveText } from "../../redaction.js";
import { isUniqueViolation } from "../../db-errors.js";
import { logActivity } from "../activity-log.js";
import { appendHeartbeatRunEvent } from "../heartbeat-run-events.js";
+import { emitAgentTaskRun } from "../agent-task-run-telemetry.js";
import { budgetService } from "../budgets.js";
import { issueRecoveryActionService } from "../issue-recovery-actions.js";
import { issueTreeControlService } from "../issue-tree-control.js";
@@ -1568,6 +1569,9 @@ export function recoveryService(db: Db, deps: { enqueueWakeup: RecoveryWakeup })
return updatedRun;
});
if (!finalizedRun) return { kind: "skipped" as const };
+ // Telemetry is best-effort background work; it must not delay the
+ // watchdog fold below, so fire it and do not await it.
+ void emitAgentTaskRun(db, finalizedRun);
if (input.existingEvaluation && !isTerminalIssueStatus(input.existingEvaluation.status)) {
await issuesSvc.update(input.existingEvaluation.id, { status: "done" });
@@ -4629,6 +4633,9 @@ export function recoveryService(db: Db, deps: { enqueueWakeup: RecoveryWakeup })
return { terminalized: false, status: current?.status ?? run.status };
}
+ // Telemetry is best-effort background work; it must not delay clearing
+ // the stale lock below, so fire it and do not await it.
+ void emitAgentTaskRun(db, updated);
runningProcesses.delete(run.id);
// The run update above already committed the terminal status. The audit
// event is best-effort: if the insert fails, the caller must still treat