fix(telemetry): emit missing server telemetry across native, onboarding, and routine paths

This commit is contained in:
Dotta committed 2026-11-30 10:25:02 -06:00
1 parent e7ed0c2f93
commit ae3b990977
13 files changed
+669 -27

No files matched your search

+17 -11
View File
@@ -118,6 +118,10 @@ for their exact dimensions and optionality.
`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.
Every path that writes a run into a terminal state — including legacy heartbeat
finalization, native session failure settlement, native restart recovery,
execution-control reconciliation, and operator-contained native owner release —
must emit `agent.task_run` once after commit without blocking run settlement.
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
@@ -149,17 +153,19 @@ harness is missing from the contract. Add it to the telemetry-backend schema
first, then copy the regenerated contract here.
`agent.task_completed` records one task completion when an agent moves a task
from a non-`done` status into `done`. Both the REST issue update route and the
native status decision committer (`commitNativeStatusDecision` via
`emitAgentTaskCompleted`) emit this event once per committed transition into
`done`. Native completion starts the emit after the transaction commits without
awaiting it, so telemetry lookups never block or fail run finalization. A
rolled-back transaction, a replayed native decision (`replayed: true`), or a
commit on a task that is already `done` (for example, already closed by the
issue route) emits nothing. Native completion sends the same dimensions as the
issue route, including `telemetryAdapterType()` for Paperclip runner harnesses
and `withTelemetryActor()` / `resolveTelemetryPerson()` for Cloud company and
person attribution.
from a non-`done` status into `done`. The REST issue update route, the native
status decision committer (`commitNativeStatusDecision` via
`emitAgentTaskCompleted`), and agent-accepted `native_completion_review`
interaction approvals (`issue-thread-interactions.ts`) emit this event once per
committed transition into `done`. Native and interaction completion paths start
the emit after the transaction commits without awaiting it, so telemetry lookups
never block or fail run finalization. A rolled-back transaction, a replayed
native decision (`replayed: true`), or a commit on a task that is already `done`
(for example, already closed by the issue route) emits nothing. Native and
interaction completion paths send the same dimensions as the issue route,
including `telemetryAdapterType()` for Paperclip runner harnesses and
`withTelemetryActor()` / `resolveTelemetryPerson()` for Cloud company and person
attribution.
## Product Lifecycle Events
@@ -0,0 +1,530 @@
import { randomUUID } from "node:crypto";
import { eq } from "drizzle-orm";
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import {
activityLog,
agents,
companies,
companyOnboardingSeeds,
completionContracts,
createDb,
goals,
heartbeatRunEvents,
heartbeatRuns,
issueComments,
issueRecoveryActions,
issueThreadInteractions,
issues,
nativeRunFinalizations,
nativeRunResults,
principalPermissionGrants,
projects,
routineRuns,
routineTriggers,
routines,
statusDecisions,
workAssessments,
} from "@paperclipai/db";
import {
getEmbeddedPostgresTestSupport,
startEmbeddedPostgresTestDatabase,
} from "./helpers/embedded-postgres.js";
import { scopedTelemetryCompanyId, scopedTelemetryPerson } from "../telemetry-company-scope.js";
const telemetryMocks = vi.hoisted(() => ({
track: vi.fn(),
getTelemetryClient: vi.fn(),
}));
vi.mock("../telemetry.js", () => ({
getTelemetryClient: telemetryMocks.getTelemetryClient,
trackCloudPostHogEvent: vi.fn(),
trackCloudTrialExposure: vi.fn(),
}));
import { reconcileAbandonedExecutionControl } from "../services/execution-control-reconciliation.js";
import { createPostgresWatchdogAdapter } from "../modules/active-run-watchdog/adapters/postgres.js";
import { issueThreadInteractionService } from "../services/issue-thread-interactions.js";
import { onboardingSeedService } from "../services/onboarding-seed.js";
import { routineSuggestionService } from "../services/routine-suggestions.js";
import { standingCheckService, STANDING_CHECK_TRIGGER_KIND } from "../services/routine-standing-checks.js";
import { instanceSettingsService } from "../services/instance-settings.js";
const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
describeEmbeddedPostgres("missing server telemetry emissions", () => {
let db!: ReturnType<typeof createDb>;
let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
let capturedEvents: Array<{
event: string;
dims: Record<string, unknown>;
companyId: string | undefined;
person: ReturnType<typeof scopedTelemetryPerson>;
}> = [];
beforeAll(async () => {
tempDb = await startEmbeddedPostgresTestDatabase("paperclip-missing-telemetry-");
db = createDb(tempDb.connectionString);
}, 30_000);
beforeEach(() => {
capturedEvents = [];
telemetryMocks.track.mockReset();
telemetryMocks.track.mockImplementation((event: string, dims: Record<string, unknown>) => {
capturedEvents.push({
event,
dims,
companyId: scopedTelemetryCompanyId(),
person: scopedTelemetryPerson(),
});
});
telemetryMocks.getTelemetryClient.mockReturnValue({
track: telemetryMocks.track,
hashPrivateRef: (value: string) => `hashed:${value}`,
});
});
afterEach(async () => {
await db.delete(activityLog);
await db.delete(routineRuns);
await db.delete(routineTriggers);
await db.delete(routines);
await db.delete(issueThreadInteractions);
await db.delete(issueComments);
await db.delete(issueRecoveryActions);
await db.delete(statusDecisions);
await db.delete(workAssessments);
await db.delete(nativeRunResults);
await db.delete(completionContracts);
await db.delete(nativeRunFinalizations);
await db.delete(heartbeatRunEvents);
await db.delete(heartbeatRuns);
await db.delete(companyOnboardingSeeds);
await db.delete(issues);
await db.delete(projects);
await db.delete(goals);
await db.delete(principalPermissionGrants);
await db.delete(agents);
await db.delete(companies);
});
afterAll(async () => {
await db?.$client.end({ timeout: 1 });
await tempDb?.cleanup();
});
async function seedBaseCompany() {
const companyId = randomUUID();
const agentId = randomUUID();
const reviewerAgentId = randomUUID();
await db.insert(companies).values({
id: companyId,
name: "Telemetry Audit Co",
issuePrefix: `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`,
requireBoardApprovalForNewAgents: false,
defaultResponsibleUserId: "user-default",
});
await db.insert(agents).values([
{
id: agentId,
companyId,
name: "Worker Agent",
role: "engineer",
status: "running",
adapterType: "paperclip_runner",
adapterConfig: { provider: "acpx", acpxAgent: "claude", model: "claude-sonnet-4-6" },
runtimeConfig: {},
permissions: {},
lastHeartbeatAt: null,
},
{
id: reviewerAgentId,
companyId,
name: "Reviewer Agent",
role: "qa",
status: "idle",
adapterType: "paperclip_runner",
adapterConfig: { provider: "acpx", acpxAgent: "codex", model: "gpt-5-codex" },
runtimeConfig: {},
permissions: {},
lastHeartbeatAt: null,
},
]);
return { companyId, agentId, reviewerAgentId };
}
it("emits agent.task_run when execution-control reconciliation marks an abandoned run failed", async () => {
const { companyId, agentId } = await seedBaseCompany();
const issueId = randomUUID();
const runId = randomUUID();
const now = new Date();
const past = new Date(now.getTime() - 120_000);
await db.insert(issues).values({
id: issueId,
companyId,
title: "Abandoned execution control task",
status: "in_progress",
assigneeAgentId: agentId,
createdByUserId: "user-creator",
responsibleUserId: "user-responsible",
});
await db.insert(heartbeatRuns).values({
id: runId,
companyId,
agentId,
invocationSource: "assignment",
status: "running",
startedAt: past,
executionControlDeadlineAt: past,
contextSnapshot: { issueId },
});
await reconcileAbandonedExecutionControl(db, now);
await vi.waitFor(() => {
const taskRunEvents = capturedEvents.filter((e) => e.event === "agent.task_run");
expect(taskRunEvents).toHaveLength(1);
expect(taskRunEvents[0]?.dims).toMatchObject({
agent_id: agentId,
state: "failed",
adapter_type: "claude_local",
agent_role: "engineer",
});
expect(taskRunEvents[0]?.companyId).toBe(companyId);
expect(taskRunEvents[0]?.person?.userId).toBe("user-creator");
});
});
it("preserves null lastHeartbeatAt when active-run-watchdog folds a never-heartbeated agent's run", async () => {
const { companyId, agentId } = await seedBaseCompany();
const issueId = randomUUID();
const runId = randomUUID();
const now = new Date();
const startedAt = new Date(now.getTime() - 60_000);
await db.insert(issues).values({
id: issueId,
companyId,
title: "Folded first run task",
status: "done",
assigneeAgentId: agentId,
});
await db.insert(heartbeatRuns).values({
id: runId,
companyId,
agentId,
invocationSource: "assignment",
status: "running",
startedAt,
contextSnapshot: { issueId },
});
const writer = createPostgresWatchdogAdapter(db);
const outcome = await writer.foldSourceResolvedRun(companyId, {
run: {
id: runId,
companyId,
agentId,
status: "running",
startedAt,
contextSnapshot: { issueId },
resultJson: null,
} as unknown as Parameters<typeof writer.foldSourceResolvedRun>[1]["run"],
sourceIssue: {
id: issueId,
companyId,
identifier: "TLM-1",
status: "done",
title: "Folded first run task",
assigneeAgentId: agentId,
} as unknown as Parameters<typeof writer.foldSourceResolvedRun>[1]["sourceIssue"],
evidence: {
kind: "activity",
id: randomUUID(),
action: "issue.updated",
createdAt: now,
},
silenceStartedAt: startedAt,
silenceAgeMs: 60_000,
existingEvaluation: null,
cleanup: { attempted: false, outcome: "no_process_metadata", adapterType: "paperclip_runner" },
now,
});
expect(outcome.kind).toBe("folded");
const [agent] = await db.select({ lastHeartbeatAt: agents.lastHeartbeatAt })
.from(agents)
.where(eq(agents.id, agentId));
expect(agent?.lastHeartbeatAt).toBeNull();
});
it("emits agent.task_completed when an agent reviewer accepts a native_completion_review card closing the task", async () => {
const { companyId, agentId, reviewerAgentId } = await seedBaseCompany();
const issueId = randomUUID();
const interactionId = randomUUID();
const sourceRunId = randomUUID();
const reviewerRunId = randomUUID();
const contractId = randomUUID();
const resultId = randomUUID();
const assessmentId = randomUUID();
const decisionId = randomUUID();
await db.insert(issues).values({
id: issueId,
companyId,
title: "Reviewed task",
status: "in_review",
statusVersion: 1,
lastStatusDecisionId: decisionId,
assigneeAgentId: agentId,
createdByUserId: "user-creator",
responsibleUserId: "user-responsible",
});
await db.insert(completionContracts).values({
id: contractId,
companyId,
issueId,
revision: 1,
schemaVersion: "paperclip.completion-contract.v1",
policyVersion: "task-completed-telemetry-v1",
risk: "standard",
completionAuthority: "server_arbiter",
incompleteCriteriaPolicy: "preserve_non_terminal",
contractJson: { revision: "task-completed-telemetry-v1", objective: "Finish", criteria: [] },
canonicalSha256: `contract-${contractId}`,
createdByActorType: "system",
createdByActorId: "test",
});
await db.insert(heartbeatRuns).values([
{
id: sourceRunId,
companyId,
agentId,
invocationSource: "assignment",
status: "succeeded",
runtimeMode: "native",
nativeIssueId: issueId,
nativeSessionId: sourceRunId,
runnerInstanceId: randomUUID(),
completionContractId: contractId,
completionContractSha256: `contract-${contractId}`,
startedAt: new Date(),
finishedAt: new Date(),
contextSnapshot: { issueId },
},
{
id: reviewerRunId,
companyId,
agentId: reviewerAgentId,
invocationSource: "assignment",
status: "running",
nativeIssueId: issueId,
startedAt: new Date(),
contextSnapshot: {
issueId,
nativeReviewInteractionId: interactionId,
nativeReviewDecisionId: decisionId,
},
},
]);
await db.update(issues).set({ executionRunId: reviewerRunId }).where(eq(issues.id, issueId));
await db.insert(nativeRunResults).values({
id: resultId,
companyId,
issueId,
runId: sourceRunId,
completionContractId: contractId,
serverFingerprint: `fp-${resultId}`,
schemaStatus: "accepted",
resultJson: {},
canonicalSha256: `sha-${resultId}`,
});
await db.insert(workAssessments).values({
id: assessmentId,
companyId,
issueId,
runId: sourceRunId,
contractId,
resultId,
triggerKind: "native_result",
triggerActorCompanyId: companyId,
priorIssueStatus: "in_progress",
priorStatusVersion: 0,
policyVersion: "task-completed-telemetry-v1",
assessmentJson: {},
inputDigest: `digest-${assessmentId}`,
});
await db.insert(statusDecisions).values({
id: decisionId,
companyId,
issueId,
runId: sourceRunId,
assessmentId,
decisionVersion: 1,
policyVersion: "native-status-arbiter-v1",
fromStatus: "in_progress",
toStatus: "in_review",
reasonCode: "review_required",
applicationState: "applied",
decisionJson: { projectedStatusVersion: 1 },
decisionDigest: `digest-${decisionId}`,
});
await db.insert(issueThreadInteractions).values({
id: interactionId,
companyId,
issueId,
kind: "request_confirmation",
status: "pending",
requestedResolverPolicy: "anyone",
effectiveResolverPolicy: "anyone",
createdByAgentId: agentId,
sourceRunId,
addresseeAgentId: reviewerAgentId,
payload: {
version: 1,
title: "Review completed work",
prompt: "Please approve",
target: { type: "custom", key: "native_completion_review", revisionId: decisionId },
recipients: [{ type: "agent", agentId: reviewerAgentId }],
} as unknown as typeof issueThreadInteractions.$inferInsert["payload"],
});
const interactionsSvc = issueThreadInteractionService(db);
await interactionsSvc.acceptInteraction(
{ id: issueId, companyId, projectId: null, goalId: null },
interactionId,
{},
{ agentId: reviewerAgentId, userId: null, runId: reviewerRunId },
);
await vi.waitFor(() => {
const completedEvents = capturedEvents.filter((e) => e.event === "agent.task_completed");
expect(completedEvents).toHaveLength(1);
expect(completedEvents[0]?.dims).toMatchObject({
agent_id: reviewerAgentId,
agent_role: "qa",
adapter_type: "codex_local",
model: "gpt-5-codex",
task_id: `hashed:${issueId}`,
});
expect(completedEvents[0]?.companyId).toBe(companyId);
expect(completedEvents[0]?.person?.userId).toBe("user-creator");
});
});
it("emits agent.created and goal.created once when onboarding-seed creates the first agent and mission goal", async () => {
const companyId = randomUUID();
await db.insert(companies).values({
id: companyId,
name: "Onboarding Co",
issuePrefix: `O${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`,
requireBoardApprovalForNewAgents: false,
defaultResponsibleUserId: "user-founder",
});
const selection = await import("../services/agent-runner-selection.js");
const spy = vi.spyOn(selection, "resolveNewAgentRunnerForCompany").mockImplementation(async (_db, _companyId, input) =>
selection.resolveNewAgentRunner({ ...input, target: { driver: "local", platform: "linux", architecture: "x64" } }),
);
try {
const seed = {
revision: "b".repeat(32),
mission: "Build reliable telemetry",
agent: { name: "Ada", role: "Chief of Staff" },
};
const svc = onboardingSeedService(db);
const first = await svc.apply(companyId, seed, { actorType: "user", actorId: "user-founder" });
expect(first.changed).toBe(true);
expect(first.agentId).toBeTruthy();
expect(first.goalId).toBeTruthy();
const agentCreated = capturedEvents.filter((e) => e.event === "agent.created");
const goalCreated = capturedEvents.filter((e) => e.event === "goal.created");
expect(agentCreated).toHaveLength(1);
expect(agentCreated[0]?.dims).toMatchObject({
agent_id: first.agentId,
agent_role: "ceo",
});
expect(agentCreated[0]?.companyId).toBe(companyId);
expect(agentCreated[0]?.person?.userId).toBe("user-founder");
expect(goalCreated).toHaveLength(1);
expect(goalCreated[0]?.dims).toMatchObject({ goal_level: "company" });
expect(goalCreated[0]?.companyId).toBe(companyId);
// Re-applying the same revision must not double-emit.
capturedEvents = [];
const second = await svc.apply(companyId, seed, { actorType: "user", actorId: "user-founder" });
expect(second.changed).toBe(false);
expect(capturedEvents.filter((e) => e.event === "agent.created")).toHaveLength(0);
expect(capturedEvents.filter((e) => e.event === "goal.created")).toHaveLength(0);
} finally {
spy.mockRestore();
}
});
it("emits routine.created for routine suggestions and routine.run for standing check reports", async () => {
const { companyId, agentId } = await seedBaseCompany();
const projectId = randomUUID();
const issueId = randomUUID();
await db.insert(projects).values({
id: projectId,
companyId,
name: "Ops",
status: "in_progress",
});
await db.insert(issues).values({
id: issueId,
companyId,
projectId,
title: "Check inbox daily",
status: "done",
assigneeAgentId: agentId,
createdByUserId: "user-founder",
});
await instanceSettingsService(db).updateExperimental({ enableResponsibilities: true });
const suggestionSvc = routineSuggestionService(db);
const created = await suggestionSvc.createFromTask(
{ id: issueId, companyId },
{
title: "Daily inbox check",
assigneeAgentId: agentId,
cadence: { frequency: "daily", time: "09:00" },
timezone: "UTC",
},
{ userId: "user-founder", runId: null },
);
const routineCreatedEvents = capturedEvents.filter((e) => e.event === "routine.created");
expect(routineCreatedEvents).toHaveLength(1);
expect(routineCreatedEvents[0]?.companyId).toBe(companyId);
expect(routineCreatedEvents[0]?.person?.userId).toBe("user-founder");
// Seed a heartbeat standing-check trigger on the routine and report it.
await db.insert(routineTriggers).values({
companyId,
routineId: created.routine.id,
kind: STANDING_CHECK_TRIGGER_KIND,
label: "Every heartbeat",
enabled: true,
});
capturedEvents = [];
const standingSvc = standingCheckService(db);
await standingSvc.report(
{ id: created.routine.id, companyId },
{ outcome: "nothing_needed" },
{ agentId, runId: null },
);
const routineRunEvents = capturedEvents.filter((e) => e.event === "routine.run");
expect(routineRunEvents).toHaveLength(1);
expect(routineRunEvents[0]?.dims).toEqual({
source: STANDING_CHECK_TRIGGER_KIND,
status: "completed",
});
expect(routineRunEvents[0]?.companyId).toBe(companyId);
});
});
@@ -23,6 +23,7 @@ import { visibleIssueCondition } from "../../../services/issue-visibility.js";
import { logActivity } from "../../../services/activity-log.js";
import { appendHeartbeatRunEvent } from "../../../services/heartbeat-run-events.js";
import { emitAgentTaskRun } from "../../../services/agent-task-run-telemetry.js";
import { settledHeartbeat } from "../../../services/heartbeat/agent-status.js";
import {
executeIssuePostCommitActions,
issueService,
@@ -521,9 +522,10 @@ export function createPostgresWatchdogAdapter(db: Db): WatchdogRunReader & Watch
const runningCount = Number(runningCountRow?.count ?? 0);
const nextAgentStatus = runningCount > 0 ? "running" : "idle";
await notifyDeliveryWork(tx, DELIVERY_QUEUES.agentTimers);
const now = new Date();
await tx
.update(agents)
.set({ status: nextAgentStatus, lastHeartbeatAt: new Date(), updatedAt: new Date() })
.set({ status: nextAgentStatus, lastHeartbeatAt: settledHeartbeat(now), updatedAt: now })
.where(and(
eq(agents.id, input.run.agentId),
eq(agents.companyId, companyId),
@@ -20,6 +20,7 @@ import {
import { parseIssueExecutionState } from "./issue-execution-policy.js";
import { issueRecoveryActionService } from "./issue-recovery-actions.js";
import { hasLiveLegacyController } from "./legacy-controller-lease.js";
import { emitAgentTaskRun } from "./agent-task-run-telemetry.js";
import { reportRunFailure } from "./run-failure-report.js";
import { getNativeReviewAssignment, readNativeReviewAssignmentContext } from "./native-runtime/native-review-participant.js";
import { preserveNativeFailedWorkspace } from "./native-runtime/native-failed-workspace-recovery.js";
@@ -360,7 +361,10 @@ export async function reconcileAbandonedExecutionControl(
return true;
});
if (repaired) surfaced += 1;
if (terminalRunToReport) void reportRunFailure(db, terminalRunToReport);
if (terminalRunToReport) {
void emitAgentTaskRun(db, terminalRunToReport);
void reportRunFailure(db, terminalRunToReport);
}
} catch {
logger.warn(
{ runId: candidate.runId },
@@ -96,12 +96,12 @@ export async function validateExecutionReconciliation(input: ExecutionReconcilia
if (input.controllerContainment) {
// Validation and contained-owner settlement must roll back together even
// when a caller is not already inside the board route's transaction.
return input.db.transaction(tx => validateExecutionReconciliationInScope({ ...input, db: tx as unknown as Db }));
return input.db.transaction(tx => validateExecutionReconciliationInScope({ ...input, db: tx as unknown as Db }, input.db));
}
return validateExecutionReconciliationInScope(input);
return validateExecutionReconciliationInScope(input, input.db);
}
async function validateExecutionReconciliationInScope(input: ExecutionReconciliationInput) {
async function validateExecutionReconciliationInScope(input: ExecutionReconciliationInput, telemetryDb: Db) {
const { db, companyId, issueId, agentId, decision } = input;
if (!decision || decision.runId !== input.sourceRunId || (!agentId && !input.workspaceRepairOnly)) {
throw conflict(
@@ -116,6 +116,7 @@ async function validateExecutionReconciliationInScope(input: ExecutionReconcilia
companyId, issueId, runId: decision.runId, actionId: input.controllerContainment.actionId,
actorId: input.controllerContainment.actorId, authorityDigest: decision.controllerAuthorityDigest,
actionOutcome: decision.actionOutcome, outcomeEvidence: decision.outcomeEvidence,
telemetryDb,
});
if (!operatorContained) throw conflict("The recorded controller authority changed, is still leased, or its cleanup is unsettled. Refresh before recording containment.",
{ code: "native_controller_containment_stale" });
@@ -148,6 +148,7 @@ import { logger } from "../middleware/logger.js";
import { conflict, forbidden, notFound, unprocessable } from "../errors.js";
import { getTelemetryClient } from "../telemetry.js";
import { withTelemetryCompany } from "../telemetry-company-scope.js";
import { emitAgentTaskCompleted } from "./agent-task-run-telemetry.js";
import { emitPlanApprovedAfterCommit } from "./product-telemetry.js";
import { authorizationService } from "./authorization.js";
import { isCloudManagedInstance } from "./cloud-instance.js";
@@ -2710,6 +2711,7 @@ export function issueThreadInteractionService(
const now = new Date();
const postCommitActivityPublications: ActivityPublication[] = [];
let completedTask: Parameters<typeof emitAgentTaskCompleted>[1] | null = null;
const result = await db.transaction(async (tx) => {
await assertInteractionRunWriteAllowed(tx as unknown as Db, args.issue, args.actor, [JSON.stringify(args.input)]);
await notifyChatConfirmationResolution(tx, args.current);
@@ -2895,6 +2897,16 @@ export function issueThreadInteractionService(
assigneeUserId: completedIssue.assigneeUserId ?? null,
status: completedIssue.status,
};
if (issueContext.status !== "done" && completedIssue.status === "done" && args.actor.agentId) {
completedTask = {
companyId: args.issue.companyId,
agentId: args.actor.agentId,
issueId: args.issue.id,
taskCreatedByUserId: completedIssue.createdByUserId,
taskAssignedByUserId: completedIssue.responsibleUserId,
runOwnerUserId: null,
};
}
}
} else if (
shouldReturnAcceptedConfirmationToCreatorAgent({
@@ -2994,6 +3006,7 @@ export function issueThreadInteractionService(
const publish = async (committedDb: Db) => {
for (const publication of postCommitActivityPublications) publishActivity(publication);
await emitInteractionResolvedTelemetry(committedDb, result.interaction);
if (completedTask) void emitAgentTaskCompleted(committedDb, completedTask);
};
if (args.mutationOptions?.deferConfirmationCommitEffects) args.mutationOptions.deferConfirmationCommitEffects(publish);
else await publish(db);
@@ -5,7 +5,8 @@ import { preserveNativeFailedWorkspace } from "./native-failed-workspace-recover
import { settleNativeTerminalWake } from "./native-run-projection.js";
import { notifyNativeStatusReassessment } from "../native-status-reassessment-notifications.js";
import { and, asc, eq, gt, inArray, isNotNull, isNull, lte, ne, or, sql } from "drizzle-orm";
import { activityLog, environmentLeases, heartbeatRuns, issueRecoveryActions, issues, nativeRunFinalizations, nativeRunResults, workspaceOperations, type Db } from "@paperclipai/db";
import { activityLog, afterTransactionCommit, environmentLeases, heartbeatRuns, issueRecoveryActions, issues, nativeRunFinalizations, nativeRunResults, workspaceOperations, type Db } from "@paperclipai/db";
import { emitAgentTaskRun } from "../agent-task-run-telemetry.js";
import { logger } from "../../middleware/logger.js";
import { adapterExecutionControls } from "../adapter-execution-control.js";
import { proveOwnerGone, type LocalOwnerStamp } from "../owner-proof.js";
@@ -46,7 +47,7 @@ type Release =
| { kind: "expired_owner"; runId: string; leaseOwner: string; attempt: number; controllerGeneration: number }
| { kind: "operator_containment"; runId: string; leaseOwner: string; attempt: number;
companyId: string; issueId: string; actionId: string; authorityDigest: string; actorId: string; controllerGeneration: number;
actionOutcome: ExecutionReconciliation["actionOutcome"]; outcomeEvidence: string };
actionOutcome: ExecutionReconciliation["actionOutcome"]; outcomeEvidence: string; telemetryDb?: Db };
/** Environment leases that `agentExecutionsHaveStopped` would still treat as live. */
const unsettledRunEnvironmentLease = sql`exists (
@@ -327,6 +328,12 @@ async function settleFailedRunOwner(db: Db, release: Release, now: Date): Promis
processPid: null, processGroupId: null, processStartedAt: null, executionControlDeadlineAt: null } : {}),
}).where(eq(heartbeatRuns.id, run.id)).returning();
if (release.kind === "operator_containment" && settledRun) {
if (run.status !== settledRun.status) {
const telemetryDb = release.telemetryDb ?? db;
afterTransactionCommit(() => {
void emitAgentTaskRun(telemetryDb, settledRun);
});
}
await preserveNativeFailedWorkspace(tx, settledRun);
await settleNativeTerminalWake(tx, settledRun);
await notifyNativeStatusReassessment(tx, scope);
@@ -426,6 +433,7 @@ export async function settleOperatorContainedNativeOwner(db: Db, input: {
companyId: string; issueId: string; runId: string; actionId: string;
authorityDigest: string; actorId: string;
actionOutcome: ExecutionReconciliation["actionOutcome"]; outcomeEvidence: string;
telemetryDb?: Db;
}): Promise<boolean> {
const [owner] = await db.select().from(nativeRunFinalizations).where(and(
eq(nativeRunFinalizations.companyId, input.companyId), eq(nativeRunFinalizations.issueId, input.issueId),
@@ -50,6 +50,7 @@ import { redactSensitiveText } from "../../redaction.js";
import { isUniqueViolation } from "../../db-errors.js";
import { logger } from "../../middleware/logger.js";
import { issueRecoveryActionService } from "../issue-recovery-actions.js";
import { emitAgentTaskRun } from "../agent-task-run-telemetry.js";
import { isNewTerminalRunFailure, reportRunFailure } from "../run-failure-report.js";
import { nativeControllerAuthorityDigest, isNativeRunnerOwnershipHeld, readNativeRemoteExecutionOwnership } from "./native-runner-ownership.js";
import { nativeRestartContinuationInFlight, nativeRestartInterruptedTurnId, type PersistedNativeSession } from "../../vendor/paperclip-runner/index.js";
@@ -1060,6 +1061,7 @@ async function endNamespaceUnverifiedRun(tx: Db, row: {
maxAttempts: 3, wakePolicy: null, supersedeOnIdentityChange: true });
}
if (updatedRun) await preserveNativeFailedWorkspace(tx, updatedRun);
return updatedRun ?? null;
}
export function settledNativeControllerNamespaceAttention(owner: {
@@ -1498,12 +1500,15 @@ export async function claimNativeRestartRecoveries(input: {
: starts.length ? Math.min(...starts) : null;
unverifiedWaitEndsAt = (waitingSince ?? now.getTime()) + NATIVE_NAMESPACE_UNVERIFIED_WAIT_MS;
if (waitingSince !== null && now.getTime() - waitingSince >= NATIVE_NAMESPACE_UNVERIFIED_WAIT_MS) {
await endNamespaceUnverifiedRun(tx as unknown as Db, row, now, takeover.reason, historyEntry({
const endedRun = await endNamespaceUnverifiedRun(tx as unknown as Db, row, now, takeover.reason, historyEntry({
now, restartKind: input.restartKind, controller, generation: row.coordinator.controllerGeneration,
disposition: "blocked", reason: takeover.reason, requestId: input.recoveryRequestId ?? null,
providerAttempt: row.coordinator.attempt, processPid: row.run.processPid, processStartedAt: row.run.processStartedAt,
hasCheckpoint: false, hasProviderEvidence: false, stderrTail: row.run.stderrExcerpt,
}), input.recoveryRequestId ?? null);
if (endedRun && isNewTerminalRunFailure(row.run, endedRun)) {
terminalRunToReport = endedRun;
}
return { kind: "blocked", runId: row.run.id, reason: takeover.reason } as const;
}
}
@@ -2226,8 +2231,10 @@ export async function claimNativeRestartRecoveries(input: {
reason: routineBusy ? "routine_execution_busy" : NATIVE_RESTART_RECOVERY_FAILED,
retryAt: new Date(now.getTime() + 30_000) };
});
if (terminalRunToReport)
if (terminalRunToReport) {
void emitAgentTaskRun(input.db, terminalRunToReport);
void reportRunFailure(input.db, terminalRunToReport);
}
if (claimScope && "leaseOwner" in disposition) input.onClaim?.(disposition, claimScope);
dispositions.push(disposition.kind === "awaiting_evidence"
? await boundAwaitingEvidence(input.db, candidate, disposition, now, input.restartKind)
@@ -2257,8 +2264,9 @@ async function boundAwaitingEvidence(db: Db, candidate: { runId: string; company
const recheck = disposition.retryAt ?? new Date(now.getTime() + NATIVE_NAMESPACE_UNVERIFIED_WAIT_MS);
const waiting = { ...disposition, retryAt: recheck };
if (SELF_RESOLVING_WAITS.includes(disposition.reason)) return disposition;
let terminalRunToEmit: typeof heartbeatRuns.$inferSelect | null = null;
try {
return await db.transaction(async tx => {
const result = await db.transaction(async tx => {
const [issue] = await tx.select({ id: issues.id }).from(issues).where(and(eq(issues.id, candidate.issueId),
eq(issues.companyId, candidate.companyId))).for("update", { skipLocked: true });
if (!issue) return waiting;
@@ -2285,12 +2293,20 @@ async function boundAwaitingEvidence(db: Db, candidate: { runId: string; company
if (lapsedFor < NATIVE_NAMESPACE_UNVERIFIED_WAIT_MS && now.getTime() - since < NATIVE_RESTART_EVIDENCE_HARD_CAP_MS) return waiting;
const reason = `restart_evidence_timeout:${disposition.reason}`.slice(0, 120);
const controller = await currentNativeControllerIdentity();
await endNamespaceUnverifiedRun(tx as unknown as Db, row, now, reason, historyEntry({ now, restartKind, controller,
const endedRun = await endNamespaceUnverifiedRun(tx as unknown as Db, row, now, reason, historyEntry({ now, restartKind, controller,
generation: row.coordinator.controllerGeneration, disposition: "blocked", reason, requestId: null,
providerAttempt: row.coordinator.attempt, processPid: row.run.processPid, processStartedAt: row.run.processStartedAt,
hasCheckpoint: false, hasProviderEvidence: false, stderrTail: row.run.stderrExcerpt }), null);
if (endedRun && isNewTerminalRunFailure(row.run, endedRun)) {
terminalRunToEmit = endedRun;
}
return { kind: "blocked" as const, runId: row.run.id, reason };
});
if (terminalRunToEmit) {
void emitAgentTaskRun(db, terminalRunToEmit);
void reportRunFailure(db, terminalRunToEmit);
}
return result;
} catch (error) {
logger.warn({ err: error, runId: candidate.runId }, "bounded restart-recovery wait check deferred");
return waiting;
@@ -45,6 +45,7 @@ import { crashPoint } from "@paperclipai/shared/crash-points";
export { nativeUsageCostUsd, nativeUsageBiller, normalizeNativeUsage } from "./native-usage-accounting.js";
import { measureRunnerOperation, recordRunnerTimingReceipt } from "./runner-operation-timing.js";
import { formatNativeRunLogEvent } from "./native-run-log-export.js";
import { emitAgentTaskRun } from "../agent-task-run-telemetry.js";
import { notifyExternalAgentSettlement } from "../../modules/external-agents/index.js";
import { notifyNativeResultCommit } from "../native-result-commit-notifications.js";
import { releaseRetainedNativeSessionCleanup } from "../retained-native-session-cleanup-notifications.js";
@@ -14074,7 +14075,10 @@ async function executePaperclipNativeSessionAttempt(
});
// Pass the raw error only for closed settlement labels: its text bypasses
// the identity redactor applied to the persisted message above.
if (terminalRunToReport) void reportRunFailure(input.db, terminalRunToReport, { nativeCloseFailure: error });
if (terminalRunToReport) {
void emitAgentTaskRun(input.db, terminalRunToReport);
void reportRunFailure(input.db, terminalRunToReport, { nativeCloseFailure: error });
}
await boundedExecutionCleanup(async () => {
await stoppedLeaseRenewal;
await attemptFailureStep(() =>
+32 -3
View File
@@ -1,7 +1,8 @@
import { and, eq, ne, sql } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import { agents, companyOnboardingSeeds, goals, toolConnections } from "@paperclipai/db";
import { afterTransactionCommit, agents, companyOnboardingSeeds, goals, toolConnections } from "@paperclipai/db";
import { resolveCloudTrialModel, type ApplyOnboardingSeed } from "@paperclipai/shared";
import { trackAgentCreated, trackGoalCreated } from "@paperclipai/shared/telemetry";
import { instanceSettingsService } from "./instance-settings.js";
import { writePaperclipSkillSyncPreference } from "@paperclipai/adapter-utils/server-utils";
import { findActiveServerAdapter } from "../adapters/registry.js";
@@ -11,7 +12,9 @@ import { withDedicatedDbConnection } from "@paperclipai/db";
import { PAPERCLIP_CORE_SKILL_KEYS } from "./company-skills.js";
import { goalService } from "./goals.js";
import { readBuiltInAgentMarker } from "../lib/built-in-agent-metadata.js";
import { trackCloudPostHogEvent, trackCloudTrialExposure } from "../telemetry.js";
import { getTelemetryClient, trackCloudPostHogEvent, trackCloudTrialExposure } from "../telemetry.js";
import { resolveTelemetryPerson, withTelemetryActor } from "../telemetry-company-scope.js";
import { logger } from "../middleware/logger.js";
import { logActivity, publishActivity, type ActivityPublication } from "./activity-log.js";
/**
@@ -191,6 +194,17 @@ export function onboardingSeedService(db: Db) {
lastHeartbeatAt: null,
}, { createdByUserId: actorUserId });
agentId = created.id;
try {
const telemetryClient = getTelemetryClient();
if (telemetryClient) {
const person = resolveTelemetryPerson({ runOwnerUserId: actorUserId });
withTelemetryActor({ companyId, person }, () =>
trackAgentCreated(telemetryClient, { agentRole: created.role, agentId: created.id }),
);
}
} catch (err) {
logger.warn({ err, companyId, agentId: created.id }, "failed to emit agent.created telemetry");
}
if (useCloudTrial) {
trackCloudPostHogEvent(
"cloud_trial.started",
@@ -209,6 +223,7 @@ export function onboardingSeedService(db: Db) {
companyId: string,
seed: ApplyOnboardingSeed,
preparedAgentId: string | null,
audit?: OnboardingSeedAuditActor,
): Promise<OnboardingSeedApplication> {
const goalSvc = goalService(dbx);
@@ -250,6 +265,20 @@ export function onboardingSeedService(db: Db) {
status: "active",
});
goalId = created.id;
const goalActorUserId = audit?.actorType === "user" ? audit.actorId : null;
const goalPerson = resolveTelemetryPerson({ runOwnerUserId: goalActorUserId });
afterTransactionCommit(() => {
try {
const telemetryClient = getTelemetryClient();
if (telemetryClient) {
withTelemetryActor({ companyId, person: goalPerson }, () =>
trackGoalCreated(telemetryClient, { goalLevel: created.level }),
);
}
} catch (err) {
logger.warn({ err, companyId, goalId: created.id }, "failed to emit goal.created telemetry");
}
});
}
}
@@ -320,7 +349,7 @@ export function onboardingSeedService(db: Db) {
const preparedAgentId = await prepareAgent(database, companyId, seed, audit);
const result = await database.transaction(async (tx) => {
const dbx = tx as unknown as Db;
const applied = await applyWithin(dbx, companyId, seed, preparedAgentId);
const applied = await applyWithin(dbx, companyId, seed, preparedAgentId, audit);
if (applied.changed && audit) {
await logActivity(
@@ -8,8 +8,12 @@ import {
type StandingCheckOutcome,
type StandingCheckReported,
} from "@paperclipai/shared";
import { trackRoutineRun } from "@paperclipai/shared/telemetry";
import { asBoolean, asNumber, parseObject } from "../adapters/utils.js";
import { conflict, forbidden, notFound, unprocessable } from "../errors.js";
import { logger } from "../middleware/logger.js";
import { getTelemetryClient } from "../telemetry.js";
import { withTelemetryCompany } from "../telemetry-company-scope.js";
import { supportsUnscopedTimerHeartbeat } from "./heartbeat-policy.js";
/**
@@ -206,6 +210,19 @@ export function standingCheckService(db: Db) {
.where(eq(routines.id, routine.id));
return created!;
});
try {
const telemetryClient = getTelemetryClient();
if (telemetryClient) {
withTelemetryCompany(routine.companyId, () =>
trackRoutineRun(telemetryClient, {
source: STANDING_CHECK_TRIGGER_KIND,
status: "completed",
}),
);
}
} catch (err) {
logger.warn({ err, routineId: routine.id, runId: run.id }, "failed to emit routine.run telemetry");
}
return { routineId: routine.id, runId: run.id, checkedAt: checkedAt.toISOString(), outcome, note, issueId };
},
};
@@ -25,8 +25,11 @@ import {
type SuggestRoutineInteraction,
type SuggestRoutinePayload,
} from "@paperclipai/shared";
import { trackRoutineCreated } from "@paperclipai/shared/telemetry";
import { conflict, forbidden, notFound, unprocessable } from "../errors.js";
import { logger } from "../middleware/logger.js";
import { getTelemetryClient } from "../telemetry.js";
import { resolveTelemetryPerson, withTelemetryActor } from "../telemetry-company-scope.js";
import { instanceSettingsService } from "./instance-settings.js";
import { isAcceptClaimLost, issueThreadInteractionService, type AcceptClaim } from "./issue-thread-interactions.js";
import { responsibilityService } from "./responsibilities.js";
@@ -343,6 +346,15 @@ export function routineSuggestionService(
throw error;
}
const trigger = created.trigger;
try {
const telemetryClient = getTelemetryClient();
if (telemetryClient) {
const person = resolveTelemetryPerson({ runOwnerUserId: actor.userId });
withTelemetryActor({ companyId: issue.companyId, person }, () => trackRoutineCreated(telemetryClient));
}
} catch (err) {
logger.warn({ err, routineId: routine.id }, "failed to emit routine.created telemetry");
}
const filed: FiledUnder = [];
try {
@@ -381,7 +381,7 @@
"packages/shared/src/standing-checks.ts": "7ab71e4b6984e41e1c1dfd1bddf0116041d5abf1",
"packages/shared/src/subscriptions.ts": "ef70e63395ca967bbc30776b71560e96eb354a75",
"packages/shared/src/summary-slot.test.ts": "5f8e222dea425f0d5bff0adb5c683087bd7cf7fb",
"packages/shared/src/telemetry/README.md": "7f4f1cd060fadc1660f057590ea66a64670c89bf",
"packages/shared/src/telemetry/README.md": "bbe0a3e936e059723014672fcfc505a1a78f0d8f",
"packages/shared/src/telemetry/client-types.test.ts": "3b630edda4972b929ba4decd7457f226eb9cfc5b",
"packages/shared/src/telemetry/client.test.ts": "5a95f2305a393c5b2e7750b10e0ed65da0f30cf8",
"packages/shared/src/telemetry/client.ts": "d6534ce8aaa6f69fb2dd03e12487db024e250a96",