From 205482b2c21f0378fdb39b42e5b91a215726b306 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Fri, 4 Dec 2026 20:08:57 -0600 Subject: [PATCH] fix(telemetry): emit missing server telemetry across native, onboarding, and routine paths (#23297) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Paperclip emits first-party product telemetry from server lifecycle transitions so operators and Cloud analytics can measure real agent runs, completions, onboarding, and routines > - A full audit of every `track*` helper in `packages/shared/src/telemetry/events.ts` found several server code paths that perform real product transitions directly in the database without emitting their existing telemetry events: native/reconciliation terminal run failure writers (`agent.task_run`), agent-accepted `native_completion_review` closures (`agent.task_completed`), `active-run-watchdog` overwriting a null `lastHeartbeatAt` (suppressing `agent.first_heartbeat`), `onboarding-seed` creating the first agent and mission goal (`agent.created`, `goal.created`), routine suggestions creating a routine (`routine.created`), and standing check reports recording a routine run (`routine.run`) > - Because those paths bypass the REST routes or `emitTerminalAgentTaskRun` (which skips rows already written to `"failed"`), deployments under-report failed native runs, agent-reviewed completions, onboarding hires, and routine activity > - This pull request wires up the existing telemetry helpers at each missing server-side transition after transaction commit using a shared terminal-failure emitter, passes an explicit root database handle for post-commit operator-containment telemetry, skips non-terminal `retryable_failure` writes while emitting non-blocking telemetry on `retryable_failure -> terminal_failure` / `committed` transitions (including superseded retry retirement), keeps `agent-task-run-telemetry.ts` free of circular imports from `run-failure-report.ts`, updates `packages/shared/src/telemetry/README.md`, and adds embedded-Postgres regression tests covering every restored path > - The benefit is complete, deduplicated, non-blocking server-side telemetry across native runtime, onboarding, and routine flows without changing any telemetry contract schema ## Linked Issues or Issue Description Refs #22963 **What happened?** Several server-side lifecycle paths transitioned database rows directly without emitting their existing first-party telemetry events: 1. `native-session-executor.ts`, `native-restart-recovery.ts`, `native-superseded-retry.ts`, `execution-control-reconciliation.ts`, and `native-failed-run-owner-release.ts` wrote `heartbeat_runs.status = 'failed'` or transitioned `retryable_failure -> terminal_failure` directly (so `heartbeat.ts`'s `emitTerminalAgentTaskRun` later saw `previousStatus === updated.status` and skipped `agent.task_run`). 2. `issue-thread-interactions.ts` allowed an agent reviewer to accept a `native_completion_review` confirmation card and move an `in_review` task to `done` without emitting `agent.task_completed`. 3. `active-run-watchdog/adapters/postgres.ts` set `agents.lastHeartbeatAt = new Date()` unconditionally when folding a silent run instead of using `settledHeartbeat(now)`, suppressing `agent.first_heartbeat` for never-heartbeated agents. 4. `onboarding-seed.ts` created a company's first agent and mission goal without emitting `agent.created` or `goal.created`. 5. `routine-suggestions.ts` created routines from task suggestions without emitting `routine.created`, and `routine-standing-checks.ts` inserted completed `routine_runs` without emitting `routine.run`. **Expected behavior** Each of those committed transitions emits its existing first-party telemetry event once after commit, non-blocking, with accurate company and person scope (`withTelemetryActor` / `withTelemetryCompany`), using an explicit live root DB handle after outer transaction commit, skipping pending native retries (`retryable_failure`), and emitting no duplicates on replay or rollback. **Steps to reproduce** 1. Trigger any of the paths above in embedded Postgres (as exercised in `server/src/__tests__/missing-server-telemetry-emissions.test.ts`). 2. Observe that the database state transitions as expected, while the corresponding telemetry event is missing, dropped on a finished transaction, prematurely emitted on a retryable native failure, or blocking finalization while pending. **Paperclip version or commit** Merged cleanly with `master` at `054b4e1395b7f246e2c18d222b701595daf5522b` (PR head `b4e70c295b78de4bdcec1788e342c421cce1e138`). ## What Changed - `server/src/services/agent-task-run-telemetry.ts` & `server/src/services/run-failure-report.ts`: keep `isRunFailureStatus`, `isPendingNativeRetry`, and `isNewTerminalRunFailure` as pure leaf helpers in `agent-task-run-telemetry.ts` (re-exported by `run-failure-report.ts`) and colocate `emitTerminalRunFailure(db, run, options)` in `run-failure-report.ts` so `agent-task-run-telemetry.ts` never imports `run-failure-report.ts` (avoiding a circular dependency into `status-decision-committer.ts` that broke `vi.mock("../agent-task-run-telemetry.js")` in `native-task-completed-telemetry.test.ts`). Tighten `isNewTerminalRunFailure` so writes into `failed/retryable_failure` return `false` while writes leaving `retryable_failure` into a terminal failure return `true`, guard `emitAgentTaskRun` against `isPendingNativeRetry`, and select `nativePhase` in `emitAgentTaskRunById`. - `server/src/routes/issues.ts`, `server/src/services/execution-recovery-resolution.ts`, and `server/src/services/native-runtime/native-failed-run-owner-release.ts`: require an explicit root `telemetryDb: Db` whenever `controllerContainment` is set (discriminated union type plus runtime guard, removing the `input.telemetryDb ?? input.db` and `release.telemetryDb ?? db` fallbacks) so `afterTransactionCommit` always runs `emitTerminalRunFailure` against the root pool instead of a finished outer transaction, gated on `isNewTerminalRunFailure(run, settledRun)`. - `server/src/services/native-runtime/native-run-finalizer.ts` and `server/src/services/native-runtime/native-run-projection.ts`: emit non-blocking `void emitAgentTaskRun(...)` + `void reportRunFailure(...)` on the `isNewTerminalRunFailure` branch when a native run transitions from `failed/retryable_failure` to `failed/committed`, ensuring telemetry DB lookups never block finalization, projection, review responses, or chat settlement. - `server/src/services/native-runtime/native-superseded-retry.ts`, `server/src/services/native-runtime/native-finalization-reconciler.ts`, and `server/src/services/native-runtime/native-restart-recovery.ts`: return the retired `heartbeatRuns` row from `retireSupersededNativeRetry` so both `claimNativeSessionResumptions` and `claimNativeRestartRecoveries` emit `agent.task_run` and `reportRunFailure` once after commit when retiring a superseded `retryable_failure` run to `terminal_failure`. - `server/src/services/native-runtime/native-session-executor.ts`: select `runtimeMode` and `nativePhase` before the failure write, gate on `isNewTerminalRunFailure(runBeforeWrite, updatedRun)`, and emit via `emitTerminalRunFailure(input.db, terminalRunToReport, { failureReport: { nativeCloseFailure: error } })`. - `server/src/services/native-runtime/native-restart-recovery.ts`: return `updatedRun` from `endNamespaceUnverifiedRun` and call `emitTerminalRunFailure` after commit in both `claimNativeRestartRecoveries` and `boundAwaitingEvidence` (making `boundAwaitingEvidence` consistent with inline unverified-run termination for both telemetry and Sentry failure reporting). - `server/src/services/execution-control-reconciliation.ts`: gate terminal failure detection on `isNewTerminalRunFailure(run, updatedRun)` and emit via `emitTerminalRunFailure(db, terminalRunToReport)`. - `server/src/modules/active-run-watchdog/adapters/postgres.ts`: use `settledHeartbeat(now)` instead of `new Date()` when folding a silent run so a never-heartbeated agent keeps `lastHeartbeatAt = null` until its first real heartbeat. - `server/src/services/issue-thread-interactions.ts`: call `void emitAgentTaskCompleted(committedDb, completedTask)` in the post-commit `publish` hook when an agent reviewer accepts a `native_completion_review` confirmation card and closes the task to `done`. - `server/src/services/onboarding-seed.ts`: emit `trackAgentCreated` (after hire commit) and `trackGoalCreated` (via `afterTransactionCommit`) with `withTelemetryActor` when onboarding seed creates a new first agent or mission goal. - `server/src/services/routine-suggestions.ts`: emit `trackRoutineCreated` with `withTelemetryActor` after both the routine and its trigger are created. - `server/src/services/routine-standing-checks.ts`: emit `trackRoutineRun` (`source: STANDING_CHECK_TRIGGER_KIND` = `"heartbeat"`, `status: "completed"`) with `withTelemetryCompany` after committing a standing-check report. Emitting the raw value follows `packages/shared/src/telemetry/README.md`; the receiving layer and `posthog-direct/enum-fallbacks.generated.ts` normalize unknown `routine.run.source` values to `"other"` until `"heartbeat"` is promoted in the telemetry schema. - `packages/shared/src/telemetry/README.md` & `tests/runner-e2e/source-sdk-public-inputs.json`: document the restored `agent.task_run` and `agent.task_completed` emission paths per `rules/data-paths.mdc`. - `server/src/__tests__/missing-server-telemetry-emissions.test.ts`: add embedded-Postgres TDD regression tests covering every restored path, including `isNewTerminalRunFailure`, the real board containment route (`POST /api/issues/:id/recovery-actions/resolve`) for both `running` and `retryable_failure` runs, `native-session-executor` retryable vs terminal settlement, `native-restart-recovery` inline and `boundAwaitingEvidence` termination, non-blocking `finalizeNativeRun` / `projectCommittedRun` while `emitAgentTaskRun` is pending, superseded-retry retirement telemetry in both `claimNativeRestartRecoveries` and `claimNativeSessionResumptions`, and strict `telemetryDb` enforcement on `validateExecutionReconciliation`. ## Telemetry Contract Exception (`rules/data-paths.mdc`) - **Unchanged generated contract exception:** `packages/shared/src/telemetry/generated/paperclip-telemetry.ts` has no diff in this PR because all six emitted events (`agent.task_run`, `agent.task_completed`, `agent.created`, `goal.created`, `routine.created`, `routine.run`) and all of their dimensions, types, and optionality already exist unchanged in the generated contract. No new event names, dimensions, or enum values were added to the telemetry contract. - **Documentation & privacy review preserved:** `packages/shared/src/telemetry/README.md` is updated in this PR to document the restored emission paths, and privacy review remains requested per `rules/data-paths.mdc` because this PR adds callers to existing helpers in `packages/shared/src/telemetry/events.ts`. ## Verification - **RED (initial review-finding regression proof before fix on `9f10d34af2`):** `pnpm --filter @paperclipai/server exec vitest run src/__tests__/missing-server-telemetry-emissions.test.ts -t "classifies pending native retries|board containment route|retryable native session failures"` — **3/3 failed**. - **RED (targeted P1/CI/review fix pass before `b4e70c295b`):** - `pnpm --filter @paperclipai/server exec vitest run src/services/native-runtime/native-task-completed-telemetry.test.ts` — **3/3 failed** (reproducing CI shard 16 failure caused by the `agent-task-run-telemetry.ts -> run-failure-report.ts` circular import into `status-decision-committer.ts`). - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/missing-server-telemetry-emissions.test.ts -t "without awaiting emitAgentTaskRun|retiring a superseded native retry|requires an explicit root telemetryDb"` — **3/3 failed** (reproducing blocking `await emitAgentTaskRun`, missing `agent.task_run` on superseded retry retirement, and silent `telemetryDb` fallback to `input.db`). - **GREEN (on final head `b4e70c295b78de4bdcec1788e342c421cce1e138`):** - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/missing-server-telemetry-emissions.test.ts` — **1/1 file, 12/12 tests passed**. - `pnpm --filter @paperclipai/server exec vitest run src/services/native-runtime/native-task-completed-telemetry.test.ts src/__tests__/heartbeat-status-preserving-telemetry.test.ts src/__tests__/agent-task-run-telemetry.test.ts` — **3/3 files, 59/59 tests passed** (3 + 1 + 55). - **Test budget:** `node scripts/check-test-budget.mjs --files server/src/__tests__/missing-server-telemetry-emissions.test.ts` — **PASS** (113 nightly suites validated, 1 test file checked). - **Verify scope & local gap:** Local `tsc --noEmit` was skipped to avoid exceeding the container's shared 9.7 GiB cgroup memory limit; GitHub PR CI supplied full typecheck, build, serialized server suites (`ci / verify`), and E2E (`ci / e2e`) verification for head `b4e70c295b78de4bdcec1788e342c421cce1e138`. - **GitHub CI on `b4e70c295b78de4bdcec1788e342c421cce1e138`:** - `ci / verify` — **PASS** (https://github.com/paperclipai/paperclip/actions/runs/47455114528/job/145468380453; includes Typecheck + Release Registry, Build, policy, Runner support/package/native server suites, and all 20 server test shards). - `ci / e2e` — **PASS** (https://github.com/paperclipai/paperclip/actions/runs/47455114528/job/145468199932; all 16 E2E shards). - All 87 status checks completed with zero failures and zero pending checks. - **Automated reviews on `b4e70c295b78de4bdcec1788e342c421cce1e138`:** Greptile **5/5** (`SUCCESS`, unchanged-contract exception recorded), Ponytail **5/5** (`Verdict: ship`), Feynman **4/5** (zero functional defects; structural rationale recorded below and in threads, 17/17 review threads resolved). - **Structural decisions (`rules/pull-request-review.mdc` & `rules/test-budget.mdc`):** - `server/src/services/native-runtime/native-finalization-reconciler.ts` grew from 1,000 lines on `master` to 1,006 lines (+6 net lines) to keep the `retiredSupersededRun` capture, error-clear, and post-commit `void emitTerminalRunFailure` call locally visible inside `claimNativeSessionResumptions` rather than bundling an unrelated reconciler refactor into this telemetry fix. - `server/src/__tests__/missing-server-telemetry-emissions.test.ts` (1,447 lines) keeps all 12 embedded-Postgres telemetry regressions in one shared `beforeAll` suite (grouped by domain `describe` blocks) to avoid multiplying disposable Postgres startup cost across CI shards per `rules/test-budget.mdc`. ## Risks - Low risk. No telemetry schemas, event names, or dimension contracts changed; all new emissions run after transaction commit as best-effort/fire-and-forget and catch errors so telemetry can never block or fail product flows. - `native-restart-recovery.ts`'s `boundAwaitingEvidence` and `retireSupersededNativeRetry` callers now invoke terminal failure telemetry/reporting after commit, matching inline unverified-run termination. - Deployments will see more accurate counts for failed `agent.task_run`, agent-reviewed `agent.task_completed`, `agent.created` / `goal.created` during onboarding, and `routine.created` / `routine.run`, which is the intended fix. - Requesting privacy review per `rules/data-paths.mdc` because this PR adds callers to existing helpers in `packages/shared/src/telemetry/events.ts`. ## Model Used - Google Antigravity (Gemini 4 Neon, High reasoning, tool use and code execution). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups (explicit unchanged-contract exception recorded per `rules/data-paths.mdc`) - [x] I will address all Greptile and reviewer comments before requesting merge --- packages/shared/src/telemetry/README.md | 28 +- ...missing-server-telemetry-emissions.test.ts | 1447 +++++++++++++++++ .../active-run-watchdog/adapters/postgres.ts | 4 +- server/src/routes/issues.ts | 5 +- .../src/services/agent-task-run-telemetry.ts | 42 +- .../execution-control-reconciliation.ts | 8 +- .../services/execution-recovery-resolution.ts | 34 +- .../src/services/issue-thread-interactions.ts | 13 + .../native-failed-run-owner-release.ts | 12 +- .../native-finalization-reconciler.ts | 10 +- .../native-runtime/native-restart-recovery.ts | 39 +- .../native-runtime/native-run-finalizer.ts | 1 + .../native-runtime/native-run-projection.ts | 1 + .../native-runtime/native-session-executor.ts | 11 +- .../native-runtime/native-superseded-retry.ts | 12 +- server/src/services/onboarding-seed.ts | 35 +- .../src/services/routine-standing-checks.ts | 17 + server/src/services/routine-suggestions.ts | 12 + server/src/services/run-failure-report.ts | 52 +- .../runner-e2e/source-sdk-public-inputs.json | 2 +- 20 files changed, 1714 insertions(+), 71 deletions(-) create mode 100644 server/src/__tests__/missing-server-telemetry-emissions.test.ts diff --git a/packages/shared/src/telemetry/README.md b/packages/shared/src/telemetry/README.md index 7f4f1cd060f..bbe0a3e936e 100644 --- a/packages/shared/src/telemetry/README.md +++ b/packages/shared/src/telemetry/README.md @@ -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 diff --git a/server/src/__tests__/missing-server-telemetry-emissions.test.ts b/server/src/__tests__/missing-server-telemetry-emissions.test.ts new file mode 100644 index 00000000000..c5462e2d85a --- /dev/null +++ b/server/src/__tests__/missing-server-telemetry-emissions.test.ts @@ -0,0 +1,1447 @@ +import { randomUUID } from "node:crypto"; +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import express from "express"; +import request from "supertest"; +import { and, eq, sql } from "drizzle-orm"; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; +import { + activityLog, + agentWakeupRequests, + agents, + companies, + companyMemberships, + companyOnboardingSeeds, + completionContracts, + createDb, + environmentLeases, + goals, + heartbeatRunEvents, + heartbeatRuns, + issueComments, + issueRecoveryActions, + issueThreadInteractions, + issues, + nativeRunFinalizations, + nativeRunResults, + principalPermissionGrants, + projects, + routineRuns, + routineTriggers, + routines, + statusDecisionEffects, + statusDecisions, + workAssessments, +} from "@paperclipai/db"; +import type { NativeExecutionInputV1 } from "@paperclipai/paperclip-runner"; +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(), + emitAgentTaskRun: vi.fn(), + actualEmitAgentTaskRun: null as ((...args: unknown[]) => Promise) | null, +})); + +const nativeRunnerMocks = vi.hoisted(() => ({ + executeNativeSession: vi.fn(), +})); + +vi.mock("../telemetry.js", () => ({ + getTelemetryClient: telemetryMocks.getTelemetryClient, + trackCloudPostHogEvent: vi.fn(), + trackCloudTrialExposure: vi.fn(), +})); + +vi.mock("../services/agent-task-run-telemetry.js", async () => { + const actual = await vi.importActual( + "../services/agent-task-run-telemetry.js", + ); + telemetryMocks.actualEmitAgentTaskRun = actual.emitAgentTaskRun as unknown as (...args: unknown[]) => Promise; + telemetryMocks.emitAgentTaskRun.mockImplementation((...args: unknown[]) => + actual.emitAgentTaskRun(...(args as Parameters)), + ); + return { + ...actual, + emitAgentTaskRun: telemetryMocks.emitAgentTaskRun, + }; +}); + +vi.mock("../vendor/paperclip-runner/index.js", async (importOriginal) => ({ + ...(await importOriginal()), + executeNativeSession: nativeRunnerMocks.executeNativeSession, +})); + +import { errorHandler } from "../middleware/error-handler.js"; +import { issueRoutes } from "../routes/issues.js"; +import { createLocalDiskStorageProvider } from "../storage/local-disk-provider.js"; +import { createStorageService } from "../storage/service.js"; +import { reconcileAbandonedExecutionControl } from "../services/execution-control-reconciliation.js"; +import { validateExecutionReconciliation } from "../services/execution-recovery-resolution.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"; +import { isNewTerminalRunFailure } from "../services/run-failure-report.js"; +import { + claimNativeRestartRecoveries, + NATIVE_NAMESPACE_UNVERIFIED_WAIT_MS, + NATIVE_RESTART_EVIDENCE_HARD_CAP_MS, +} from "../services/native-runtime/native-restart-recovery.js"; +import { claimNativeSessionResumptions } from "../services/native-runtime/native-finalization-reconciler.js"; +import { finalizeNativeRun } from "../services/native-runtime/native-run-finalizer.js"; +import { projectCommittedRun } from "../services/native-runtime/native-run-projection.js"; +import { PaperclipControlPlanePort } from "../services/native-runtime/paperclip-control-plane-port.js"; +import { + CONTROL_PLANE_CONFORMANCE_RESULT, + CONTROL_PLANE_CONFORMANCE_TERMINAL, +} from "../vendor/paperclip-runner/testing.js"; +import { nativeControllerAuthorityDigest } from "../services/native-runtime/native-runner-ownership.js"; +import { executePaperclipNativeSession } from "../services/native-runtime/native-session-executor.js"; +import { prepareNativeHeartbeatRun } from "../services/native-runtime/prepare-native-run.js"; +import { buildNativeCompletionContract } from "../services/native-runtime/completion-contracts.js"; + +const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport(); +const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip; + +describeEmbeddedPostgres("missing server telemetry emissions", () => { + let db!: ReturnType; + let tempDb: Awaited> | null = null; + let storageRoot = ""; + let capturedEvents: Array<{ + event: string; + dims: Record; + companyId: string | undefined; + person: ReturnType; + }> = []; + + beforeAll(async () => { + tempDb = await startEmbeddedPostgresTestDatabase("paperclip-missing-telemetry-"); + db = createDb(tempDb.connectionString); + storageRoot = await mkdtemp(join(tmpdir(), "paperclip-missing-telemetry-storage-")); + }, 30_000); + + beforeEach(() => { + capturedEvents = []; + nativeRunnerMocks.executeNativeSession.mockReset(); + telemetryMocks.emitAgentTaskRun.mockReset(); + if (telemetryMocks.actualEmitAgentTaskRun) { + const actualEmit = telemetryMocks.actualEmitAgentTaskRun; + telemetryMocks.emitAgentTaskRun.mockImplementation((...args: unknown[]) => actualEmit(...args)); + } + telemetryMocks.track.mockReset(); + telemetryMocks.track.mockImplementation((event: string, dims: Record) => { + 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(nativeRunFinalizations); + await db.delete(statusDecisionEffects); + await db.delete(statusDecisions); + await db.delete(workAssessments); + await db.delete(nativeRunResults); + await db.delete(completionContracts); + await db.delete(environmentLeases); + await db.delete(heartbeatRunEvents); + await db.delete(agentWakeupRequests); + 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(companyMemberships); + await db.delete(agents); + await db.delete(companies); + }); + + afterAll(async () => { + await db?.$client.end({ timeout: 1 }); + await tempDb?.cleanup(); + if (storageRoot) await rm(storageRoot, { recursive: true, force: true }); + }); + + 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[1]["run"], + sourceIssue: { + id: issueId, + companyId, + identifier: "TLM-1", + status: "done", + title: "Folded first run task", + assigneeAgentId: agentId, + } as unknown as Parameters[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); + }); + + it("classifies pending native retries as non-terminal in isNewTerminalRunFailure", () => { + expect(isNewTerminalRunFailure( + { status: "running", runtimeMode: "native", nativePhase: "observed" }, + { status: "failed", runtimeMode: "native", nativePhase: "retryable_failure" }, + )).toBe(false); + expect(isNewTerminalRunFailure( + { status: "failed", runtimeMode: "native", nativePhase: "retryable_failure" }, + { status: "failed", runtimeMode: "native", nativePhase: "terminal_failure" }, + )).toBe(true); + expect(isNewTerminalRunFailure( + { status: "failed", runtimeMode: "native", nativePhase: "terminal_failure" }, + { status: "failed", runtimeMode: "native", nativePhase: "terminal_failure" }, + )).toBe(false); + expect(isNewTerminalRunFailure( + { status: "running", runtimeMode: "native", nativePhase: "observed" }, + { status: "failed", runtimeMode: "native", nativePhase: "terminal_failure" }, + )).toBe(true); + expect(isNewTerminalRunFailure( + { status: "running", runtimeMode: "native", nativePhase: "observed" }, + { status: "running", runtimeMode: "native", nativePhase: "observed" }, + )).toBe(false); + expect(isNewTerminalRunFailure( + { status: "failed", runtimeMode: "native", nativePhase: "retryable_failure" }, + { status: "succeeded", runtimeMode: "native", nativePhase: "committed" }, + )).toBe(false); + }); + + it("emits agent.task_run after outer commit through the board containment route for both running and retryable_failure runs", async () => { + const containmentEvidence = + "Deployment operator verified the original host controller, provider and tools are stopped; external action outcomes were reviewed."; + + const runBoardContainment = async (initial: { + runStatus: "running" | "failed"; + nativePhase: "observed" | "retryable_failure"; + coordinatorPhase: "observed" | "retryable_failure"; + }) => { + const { companyId, agentId } = await seedBaseCompany(); + const operatorUserId = "user-operator"; + await db.insert(companyMemberships).values({ + companyId, + principalType: "user", + principalId: operatorUserId, + status: "active", + membershipRole: "owner", + }); + const issueId = randomUUID(); + const runId = randomUUID(); + const now = new Date(); + const expiredAt = new Date(now.getTime() - 10_000); + + await db.insert(issues).values({ + id: issueId, + companyId, + title: `Board contained run (${initial.coordinatorPhase})`, + status: "in_progress", + assigneeAgentId: agentId, + createdByUserId: "user-creator", + responsibleUserId: operatorUserId, + }); + await db.insert(heartbeatRuns).values({ + id: runId, + companyId, + agentId, + invocationSource: "assignment", + status: initial.runStatus, + runtimeMode: "native", + runtimeModeResolvedAt: now, + nativeIssueId: issueId, + nativePhase: initial.nativePhase, + responsibleUserId: operatorUserId, + startedAt: new Date(now.getTime() - 60_000), + finishedAt: initial.runStatus === "failed" ? expiredAt : null, + contextSnapshot: { issueId }, + }); + await db.update(issues).set({ executionRunId: runId }).where(eq(issues.id, issueId)); + const [coordinator] = await db.insert(nativeRunFinalizations).values({ + runId, + companyId, + issueId, + phase: initial.coordinatorPhase, + attempt: 1, + leaseOwner: "foreign-controller-owner", + leaseExpiresAt: expiredAt, + controllerGeneration: 1, + controllerBootId: "foreign-boot-id", + controllerHostHash: "foreign-process-space", + controllerPid: 999_999, + controllerProcessStartedAt: new Date(now.getTime() - 60_000), + }).returning(); + const [expiry] = await db + .select({ epoch: sql`extract(epoch from ${nativeRunFinalizations.leaseExpiresAt})::numeric::text` }) + .from(nativeRunFinalizations) + .where(eq(nativeRunFinalizations.runId, runId)); + const digest = nativeControllerAuthorityDigest(coordinator!, expiry?.epoch ?? null); + const [action] = await db.insert(issueRecoveryActions).values({ + companyId, + sourceIssueId: issueId, + kind: "active_run_watchdog", + ownerType: "board", + ownerAgentId: null, + returnOwnerAgentId: agentId, + cause: "native_restart_recovery_blocked", + fingerprint: `native-controller-space:${runId}:${digest}`, + status: "active", + evidence: { + runId, + reason: "controller_process_space_unverified", + controllerAuthority: { + schema: "paperclip.native-controller-authority.v1", + digest, + }, + }, + nextAction: "Confirm the original controller and provider stopped before retrying.", + }).returning(); + + const app = express(); + app.use(express.json()); + app.use((req, _res, next) => { + req.actor = { + type: "board", + userId: operatorUserId, + source: "session", + companyIds: [companyId], + memberships: [{ companyId, membershipRole: "owner", status: "active" }], + }; + next(); + }); + app.use("/api", issueRoutes(db, createStorageService(createLocalDiskStorageProvider(storageRoot)))); + app.use(errorHandler); + + capturedEvents = []; + const response = await request(app) + .post(`/api/issues/${issueId}/recovery-actions/resolve`) + .send({ + actionId: action!.id, + outcome: "restored", + sourceIssueStatus: "in_progress", + executionReconciliation: { + runId, + controllerStopped: true, + providerStopped: true, + controllerAuthorityDigest: digest, + actionOutcome: "mixed", + outcomeEvidence: containmentEvidence, + }, + }); + expect(response.status, JSON.stringify(response.body)).toBe(200); + + const [settledRun] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)); + expect(settledRun).toMatchObject({ status: "failed", nativePhase: "terminal_failure" }); + + 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"); + }); + }; + + await runBoardContainment({ + runStatus: "running", + nativePhase: "observed", + coordinatorPhase: "observed", + }); + await runBoardContainment({ + runStatus: "failed", + nativePhase: "retryable_failure", + coordinatorPhase: "retryable_failure", + }); + }); + + it("skips agent.task_run for retryable native session failures and emits once on terminal failure", async () => { + const { companyId, agentId } = await seedBaseCompany(); + const issueId = randomUUID(); + const runId = randomUUID(); + const now = new Date(); + + await db.insert(issues).values({ + id: issueId, + companyId, + title: "Native session failure settlement", + status: "in_progress", + workMode: "standard", + assigneeAgentId: agentId, + createdByUserId: "user-creator", + responsibleUserId: "user-responsible", + }); + const [issue] = await db.select().from(issues).where(eq(issues.id, issueId)); + const [run] = await db.insert(heartbeatRuns).values({ + id: runId, + companyId, + agentId, + invocationSource: "assignment", + status: "running", + runtimeMode: "native", + nativeIssueId: issueId, + responsibleUserId: "user-responsible", + startedAt: now, + contextSnapshot: { issueId }, + }).returning(); + await db.update(issues).set({ executionRunId: runId }).where(eq(issues.id, issueId)); + const native = await prepareNativeHeartbeatRun({ db, run: run!, issue: issue!, environmentLeaseId: randomUUID() }); + const [contract] = await db.select().from(completionContracts).where(eq(completionContracts.issueId, issueId)); + await db.insert(nativeRunFinalizations).values({ + runId, + companyId, + issueId, + phase: "observed", + }); + const execution: NativeExecutionInputV1 = { + schema: "paperclip.native-execution-input.v1", + binding: { companyId, runId, issueId, agentId, executionWorkspaceId: runId }, + provider: { kind: "codex", model: "test-model" }, + task: { identifier: issueId, title: issue!.title, description: null, prompt: "Do the work.", workMode: "standard" }, + workspace: { cwd: "/tmp", repoUrl: null, repoRef: null, branchName: null }, + session: { + normalizedSessionId: native.normalizedSessionId, + driverKind: "codex_app_server", + protocolVersion: 1, + lifecyclePolicy: { mode: "per_turn", idleTimeoutMs: null }, + }, + completionContract: { + id: contract!.id, + sha256: contract!.canonicalSha256, + schemaVersion: "paperclip.completion-contract.v1", + contract: buildNativeCompletionContract(issue!, { revision: contract!.revision }), + }, + interactionResponses: [], + credentialBindings: [], + }; + await db.update(heartbeatRuns).set({ + runnerProfileJson: { + nativeExecutionInput: execution, + sessionCheckpoint: { + backendKind: "codex_app_server", + sessionId: native.normalizedSessionId, + providerSessionId: "provider-session-1", + activeTurnId: "provider-turn-1", + }, + }, + }).where(eq(heartbeatRuns.id, runId)); + + const stubBackend = { + descriptor: async () => { throw new Error("Unexpected provider call"); }, + openSession: async () => { throw new Error("Unexpected provider call"); }, + }; + + // Attempt 1: transient failure persists status="failed", nativePhase="retryable_failure" -> NOT terminal. + capturedEvents = []; + nativeRunnerMocks.executeNativeSession.mockRejectedValueOnce(new Error("provider_transport_failed")); + await executePaperclipNativeSession({ + db, + execution, + runnerInstanceId: native.runnerInstanceId, + backend: stubBackend, + }).catch(() => undefined); + + const [retryableRun] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)); + expect(retryableRun).toMatchObject({ status: "failed", nativePhase: "retryable_failure" }); + // Flush pending microtasks/promises to ensure no async emitAgentTaskRun fires. + await new Promise((resolve) => setTimeout(resolve, 50)); + expect(capturedEvents.filter((e) => e.event === "agent.task_run")).toHaveLength(0); + + // Final attempt: resumption claims the retry (returning status to "running") and attempt 3 exhausts retries -> emits ONCE. + await db.update(heartbeatRuns).set({ + status: "running", + finishedAt: null, + error: null, + errorCode: null, + nativePhase: "observed", + }).where(eq(heartbeatRuns.id, runId)); + await db.update(nativeRunFinalizations).set({ + attempt: 2, + phase: "observed", + leaseOwner: null, + leaseExpiresAt: null, + nextAttemptAt: new Date(Date.now() - 1_000), + }).where(eq(nativeRunFinalizations.runId, runId)); + nativeRunnerMocks.executeNativeSession.mockRejectedValueOnce(new Error("provider_transport_failed")); + await executePaperclipNativeSession({ + db, + execution, + runnerInstanceId: native.runnerInstanceId, + backend: stubBackend, + }).catch(() => undefined); + + const [terminalRun] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)); + expect(terminalRun).toMatchObject({ status: "failed", nativePhase: "terminal_failure" }); + + 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("emits agent.task_run when native restart recovery ends an unverified run inline or via boundAwaitingEvidence", async () => { + const { companyId, agentId } = await seedBaseCompany(); + const now = new Date(); + + // Case 1: claimNativeRestartRecoveries ends a foreign-space lapsed run inline. + const inlineIssueId = randomUUID(); + const inlineRunId = randomUUID(); + const lapsedAt = new Date(now.getTime() - NATIVE_NAMESPACE_UNVERIFIED_WAIT_MS - 10_000); + await db.insert(issues).values({ + id: inlineIssueId, + companyId, + title: "Inline restart recovery timeout", + status: "in_progress", + assigneeAgentId: agentId, + createdByUserId: "user-creator", + responsibleUserId: "user-responsible", + }); + await db.insert(heartbeatRuns).values({ + id: inlineRunId, + companyId, + agentId, + invocationSource: "assignment", + status: "running", + runtimeMode: "native", + runtimeModeResolvedAt: lapsedAt, + nativeIssueId: inlineIssueId, + nativePhase: "observed", + responsibleUserId: "user-responsible", + startedAt: new Date(lapsedAt.getTime() - 30_000), + contextSnapshot: { issueId: inlineIssueId }, + }); + await db.update(issues).set({ executionRunId: inlineRunId }).where(eq(issues.id, inlineIssueId)); + await db.insert(nativeRunFinalizations).values({ + runId: inlineRunId, + companyId, + issueId: inlineIssueId, + phase: "observed", + attempt: 1, + leaseOwner: "foreign-owner-inline", + leaseExpiresAt: lapsedAt, + controllerGeneration: 1, + controllerBootId: "foreign-boot-inline", + controllerHostHash: "foreign-process-space", + controllerPid: 999_998, + controllerProcessStartedAt: new Date(lapsedAt.getTime() - 30_000), + }); + + capturedEvents = []; + const inlineDispositions = await claimNativeRestartRecoveries({ + db, + restartKind: "hard", + runIds: [inlineRunId], + now, + }); + expect(inlineDispositions).toEqual([ + { kind: "blocked", runId: inlineRunId, reason: "controller_process_space_unverified" }, + ]); + + 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"); + }); + + // Case 2: boundAwaitingEvidence ends a wait that exceeded the restart evidence hard cap. + const boundedIssueId = randomUUID(); + const boundedRunId = randomUUID(); + const justExpiredAt = new Date(now.getTime() - 1_000); + const waitedSince = new Date(now.getTime() - NATIVE_RESTART_EVIDENCE_HARD_CAP_MS - 10_000); + await db.insert(issues).values({ + id: boundedIssueId, + companyId, + title: "Bounded awaiting evidence timeout", + status: "in_progress", + assigneeAgentId: agentId, + createdByUserId: "user-creator", + responsibleUserId: "user-responsible", + }); + await db.insert(heartbeatRuns).values({ + id: boundedRunId, + companyId, + agentId, + invocationSource: "assignment", + status: "running", + runtimeMode: "native", + runtimeModeResolvedAt: waitedSince, + nativeIssueId: boundedIssueId, + nativePhase: "observed", + responsibleUserId: "user-responsible", + startedAt: new Date(waitedSince.getTime() - 30_000), + contextSnapshot: { issueId: boundedIssueId }, + }); + await db.update(issues).set({ executionRunId: boundedRunId }).where(eq(issues.id, boundedIssueId)); + await db.insert(nativeRunFinalizations).values({ + runId: boundedRunId, + companyId, + issueId: boundedIssueId, + phase: "observed", + attempt: 1, + leaseOwner: "other-controller-grace", + leaseExpiresAt: justExpiredAt, + controllerGeneration: 1, + controllerBootId: "other-boot-grace", + controllerHostHash: "foreign-process-space", + controllerPid: 999_997, + controllerProcessStartedAt: new Date(waitedSince.getTime() - 30_000), + failureDetail: { restartEvidenceWaitSince: waitedSince.toISOString() }, + }); + + capturedEvents = []; + const boundedDispositions = await claimNativeRestartRecoveries({ + db, + restartKind: "hard", + runIds: [boundedRunId], + now, + }); + expect(boundedDispositions).toEqual([ + { kind: "blocked", runId: boundedRunId, reason: expect.stringMatching(/^restart_evidence_timeout:/) }, + ]); + + 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("returns finalizeNativeRun and projectCommittedRun without awaiting emitAgentTaskRun when leaving retryable_failure", async () => { + const { companyId, agentId } = await seedBaseCompany(); + const now = new Date(); + + // Case 1: projectCommittedRun transitioning failed/retryable_failure -> failed/committed must not await telemetry. + const projIssueId = randomUUID(); + const projContractId = randomUUID(); + const projRunId = randomUUID(); + const projResultId = randomUUID(); + await db.insert(issues).values({ + id: projIssueId, + companyId, + title: "Non-blocking projection leaving retryable failure", + status: "in_progress", + assigneeAgentId: agentId, + createdByUserId: "user-creator", + responsibleUserId: "user-responsible", + }); + await db.insert(completionContracts).values({ + id: projContractId, + companyId, + issueId: projIssueId, + revision: 1, + schemaVersion: "paperclip.completion-contract.v1", + policyVersion: "telemetry-nonblocking-v1", + risk: "standard", + completionAuthority: "server_arbiter", + incompleteCriteriaPolicy: "preserve_non_terminal", + contractJson: { + revision: "telemetry-nonblocking-v1", + objective: "Project non-blocking", + criteria: [{ id: "objective", requirement: "Return immediately" }], + }, + canonicalSha256: `contract-${projContractId}`, + createdByActorType: "system", + createdByActorId: "test", + }); + const [projRun] = await db.insert(heartbeatRuns).values({ + id: projRunId, + companyId, + agentId, + invocationSource: "assignment", + status: "failed", + runtimeMode: "native", + nativeIssueId: projIssueId, + nativePhase: "retryable_failure", + nativeSessionId: projRunId, + runnerInstanceId: randomUUID(), + completionContractId: projContractId, + completionContractSha256: `contract-${projContractId}`, + startedAt: new Date(now.getTime() - 10_000), + finishedAt: new Date(now.getTime() - 2_000), + errorCode: "provider_transport_failed", + contextSnapshot: { issueId: projIssueId }, + }).returning(); + await db.insert(nativeRunResults).values({ + id: projResultId, + companyId, + issueId: projIssueId, + runId: projRunId, + completionContractId: projContractId, + serverFingerprint: `fp-${projResultId}`, + schemaStatus: "accepted", + resultJson: { + terminal: { ...CONTROL_PLANE_CONFORMANCE_TERMINAL, runTerminalState: "failed", turnTerminalState: "failed" }, + }, + canonicalSha256: `sha-${projResultId}`, + }); + const [projCoordinator] = await db.insert(nativeRunFinalizations).values({ + runId: projRunId, + companyId, + issueId: projIssueId, + phase: "committed", + resultId: projResultId, + }).returning(); + + let releaseProjTelemetry!: () => void; + const pendingProjTelemetry = new Promise((resolve) => { + releaseProjTelemetry = resolve; + }); + telemetryMocks.emitAgentTaskRun.mockImplementationOnce(() => pendingProjTelemetry); + try { + const outcome = await Promise.race([ + projectCommittedRun({ db, run: projRun!, coordinator: projCoordinator! }).then(() => "returned" as const), + new Promise<"timed_out">((resolve) => setTimeout(() => resolve("timed_out"), 250)), + ]); + expect(outcome).toBe("returned"); + expect(telemetryMocks.emitAgentTaskRun).toHaveBeenCalledTimes(1); + } finally { + releaseProjTelemetry(); + await pendingProjTelemetry; + } + + // Case 2: finalizeNativeRun transitioning failed/retryable_failure -> failed/committed must not await telemetry. + const finIssueId = randomUUID(); + const finContractId = randomUUID(); + const finRunId = randomUUID(); + const finSessionId = randomUUID(); + const finRunnerInstanceId = randomUUID(); + const finContractSha = `contract-${finContractId}`; + await db.insert(issues).values({ + id: finIssueId, + companyId, + title: "Non-blocking finalizer leaving retryable failure", + status: "in_progress", + assigneeAgentId: agentId, + createdByUserId: "user-creator", + responsibleUserId: "user-responsible", + }); + await db.insert(completionContracts).values({ + id: finContractId, + companyId, + issueId: finIssueId, + revision: 1, + schemaVersion: "paperclip.completion-contract.v1", + policyVersion: "telemetry-nonblocking-v1", + risk: "standard", + completionAuthority: "server_arbiter", + incompleteCriteriaPolicy: "preserve_non_terminal", + contractJson: { + revision: CONTROL_PLANE_CONFORMANCE_RESULT.completionClaim.contractRevision, + objective: "Finalize non-blocking", + criteria: [{ id: "objective", requirement: "Return immediately" }], + }, + canonicalSha256: finContractSha, + createdByActorType: "system", + createdByActorId: "test", + }); + await db.insert(heartbeatRuns).values({ + id: finRunId, + companyId, + agentId, + invocationSource: "assignment", + status: "running", + runtimeMode: "native", + nativeIssueId: finIssueId, + nativeSessionId: finSessionId, + runnerInstanceId: finRunnerInstanceId, + completionContractId: finContractId, + completionContractSha256: finContractSha, + contextSnapshot: { issueId: finIssueId }, + }); + const port = new PaperclipControlPlanePort(db, { + companyId, + issueId: finIssueId, + runId: finRunId, + agentId, + sessionId: finSessionId, + completionContractId: finContractId, + completionContractSha256: finContractSha, + sourceInstanceId: finRunnerInstanceId, + controlPlaneSourceInstanceId: "telemetry-nonblocking-test", + }); + await port.openRun({ + identity: { runId: finRunId, sessionId: finSessionId, companyId, issueId: finIssueId, agentId }, + backendKind: "mock", + sourceInstanceId: finRunnerInstanceId, + }); + await port.completeRun({ + result: { + ...CONTROL_PLANE_CONFORMANCE_RESULT, + reportedWorkDisposition: "blocked", + completionClaim: { + ...CONTROL_PLANE_CONFORMANCE_RESULT.completionClaim, + objectiveSatisfied: false, + }, + blocker: { + reasonCode: "tool_error", + owner: { kind: "agent", name: "worker" }, + unblockAction: "Retry after fixing tool failure.", + scope: "task_wide", + }, + }, + terminal: { + ...CONTROL_PLANE_CONFORMANCE_TERMINAL, + reportedWorkDisposition: "blocked", + runTerminalState: "failed", + turnTerminalState: "failed", + }, + callerResultId: `${finRunId}:result`, + }); + await db.update(heartbeatRuns).set({ + status: "failed", + nativePhase: "retryable_failure", + finishedAt: new Date(now.getTime() - 1_000), + errorCode: "provider_transport_failed", + }).where(eq(heartbeatRuns.id, finRunId)); + await db.update(nativeRunFinalizations).set({ + phase: "retryable_failure", + leaseOwner: null, + leaseExpiresAt: null, + nextAttemptAt: null, + }).where(eq(nativeRunFinalizations.runId, finRunId)); + + telemetryMocks.emitAgentTaskRun.mockClear(); + let releaseFinTelemetry!: () => void; + const pendingFinTelemetry = new Promise((resolve) => { + releaseFinTelemetry = resolve; + }); + telemetryMocks.emitAgentTaskRun.mockImplementationOnce(() => pendingFinTelemetry); + try { + const outcome = await Promise.race([ + finalizeNativeRun({ + db, + runId: finRunId, + workspaceFinalizeStatus: "succeeded", + projectRunStatus: true, + skipNativeResponsePresentation: true, + skipExternalConversationSettlement: true, + skipNativeRecoveryNotices: true, + skipExternalAgentSettlement: true, + }).then(() => "returned" as const), + new Promise<"timed_out">((resolve) => setTimeout(() => resolve("timed_out"), 250)), + ]); + expect(outcome).toBe("returned"); + expect(telemetryMocks.emitAgentTaskRun).toHaveBeenCalledTimes(1); + } finally { + releaseFinTelemetry(); + await pendingFinTelemetry; + } + }); + + it("emits agent.task_run when retiring a superseded native retry via restart recovery or session resumption", async () => { + const { companyId, agentId } = await seedBaseCompany(); + const now = new Date(); + + async function seedSupersededRetryFixture(label: string) { + const issueId = randomUUID(); + const runId = randomUUID(); + const successorRunId = randomUUID(); + const leaseId = randomUUID(); + const workspaceId = randomUUID(); + const providerLeaseId = `daytona-lease-${label}`; + const remoteCwd = `/workspace/${label}`; + const failedAt = new Date(now.getTime() - 60_000); + + await db.insert(issues).values({ + id: issueId, + companyId, + title: `Superseded retry ${label}`, + status: "in_progress", + assigneeAgentId: agentId, + createdByUserId: "user-creator", + responsibleUserId: "user-responsible", + executionRunId: null, + }); + await db.insert(heartbeatRuns).values({ + id: runId, + companyId, + agentId, + invocationSource: "assignment", + status: "failed", + runtimeMode: "native", + runtimeModeResolvedAt: failedAt, + nativeIssueId: issueId, + nativePhase: "retryable_failure", + responsibleUserId: "user-responsible", + startedAt: new Date(failedAt.getTime() - 15_000), + finishedAt: failedAt, + errorCode: "provider_transport_failed", + contextSnapshot: { issueId }, + runnerProfileJson: { + nativeWorkspaceSync: { + schema: "paperclip.native-workspace-sync/v3", + state: "prepared", + descriptorSha256: "a".repeat(64), + baselineSha256: "b".repeat(64), + finalHostSha256: null, + workspaceId, + leaseId, + providerLeaseId, + remoteCwd, + resourceDisposition: null, + }, + }, + }); + await db.insert(nativeRunFinalizations).values({ + runId, + companyId, + issueId, + phase: "retryable_failure", + attempt: 1, + leaseOwner: null, + leaseExpiresAt: null, + nextAttemptAt: new Date(now.getTime() - 1_000), + }); + await db.insert(environmentLeases).values({ + id: leaseId, + companyId, + issueId, + heartbeatRunId: runId, + provider: "daytona", + providerLeaseId, + leasePolicy: "ephemeral", + status: "active", + metadata: { remoteCwd, driver: "sandbox" }, + }); + await db.insert(heartbeatRuns).values({ + id: successorRunId, + companyId, + agentId, + invocationSource: "assignment", + status: "succeeded", + runtimeMode: "native", + nativeIssueId: issueId, + nativePhase: "committed", + responsibleUserId: "user-responsible", + startedAt: new Date(failedAt.getTime() + 5_000), + finishedAt: new Date(failedAt.getTime() + 10_000), + contextSnapshot: { + issueId, + previousRunId: runId, + taskRetryRequestId: `retry-req-${label}`, + }, + }); + return { issueId, runId }; + } + + // Path 1: native-restart-recovery + const restartFixture = await seedSupersededRetryFixture("restart"); + capturedEvents = []; + const restartDispositions = await claimNativeRestartRecoveries({ + db, + restartKind: "hard", + runIds: [restartFixture.runId], + now, + }); + expect(restartDispositions).toEqual([ + { kind: "blocked", runId: restartFixture.runId, reason: "native_retry_superseded" }, + ]); + 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"); + }); + + // Path 2: native-finalization-reconciler (claimNativeSessionResumptions) + const resumeFixture = await seedSupersededRetryFixture("resumption"); + capturedEvents = []; + const resumeClaims = await claimNativeSessionResumptions({ + db, + runnerInstanceId: "test-runner", + runIds: [resumeFixture.runId], + now, + }); + expect(resumeClaims).toEqual([]); + const [retiredRun] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, resumeFixture.runId)); + expect(retiredRun?.nativePhase).toBe("terminal_failure"); + 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("requires an explicit root telemetryDb when validateExecutionReconciliation settles controller containment", async () => { + const { companyId, agentId } = await seedBaseCompany(); + const issueId = randomUUID(); + const runId = randomUUID(); + const actionId = randomUUID(); + + await expect( + validateExecutionReconciliation({ + db, + telemetryDb: undefined as unknown as ReturnType, + companyId, + issueId, + agentId, + sourceRunId: runId, + controllerContainment: { actionId, actorId: "user-board" }, + decision: { + runId, + providerStopped: true, + controllerStopped: true, + controllerAuthorityDigest: "a".repeat(64), + actionOutcome: "not_performed", + outcomeEvidence: "Verified original controller host stopped before containment.", + }, + }), + ).rejects.toThrow("controller_containment_requires_root_telemetry_db"); + }); +}); diff --git a/server/src/modules/active-run-watchdog/adapters/postgres.ts b/server/src/modules/active-run-watchdog/adapters/postgres.ts index f7e01ce56ca..00fb24eb56f 100644 --- a/server/src/modules/active-run-watchdog/adapters/postgres.ts +++ b/server/src/modules/active-run-watchdog/adapters/postgres.ts @@ -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), diff --git a/server/src/routes/issues.ts b/server/src/routes/issues.ts index 46f7037532c..9594c7ba3fe 100644 --- a/server/src/routes/issues.ts +++ b/server/src/routes/issues.ts @@ -10624,7 +10624,7 @@ export function issueRoutes( if (outcome !== "restored" || sourceIssueStatus !== lockedIssue.status) { throw conflict("Record workspace repair without changing the current task status or requesting a retry."); } - await validateExecutionReconciliation({ db: tx as unknown as Db, + await validateExecutionReconciliation({ db: tx as unknown as Db, telemetryDb: db, companyId: lockedIssue.companyId, issueId: lockedIssue.id, agentId: lockedIssue.assigneeAgentId, sourceRunId: workspaceRepairAction.evidence.runId, decision: executionReconciliation, workspaceRepairOnly: true, @@ -10860,7 +10860,7 @@ export function issueRoutes( if (outcome !== "restored" || sourceIssueStatus !== lockedIssue.status || !actionId || activeRecoveryAction.id !== actionId || workspaceBaseRef || workspaceRetry) throw conflict("Containment only records the original execution. Keep the task unchanged, then use Retry separately."); - await validateExecutionReconciliation({ db: tx as unknown as Db, companyId: lockedIssue.companyId, + await validateExecutionReconciliation({ db: tx as unknown as Db, telemetryDb: db, companyId: lockedIssue.companyId, issueId: lockedIssue.id, agentId: lockedIssue.assigneeAgentId, sourceRunId: activeRecoveryAction.evidence.runId, decision: executionReconciliation, controllerContainment: { actionId, actorId: actor.actorId } }); @@ -10871,6 +10871,7 @@ export function issueRoutes( assertBoard(req); await validateExecutionReconciliation({ db: tx as unknown as Db, + telemetryDb: db, companyId: lockedIssue.companyId, issueId: lockedIssue.id, agentId: lockedIssue.assigneeAgentId, diff --git a/server/src/services/agent-task-run-telemetry.ts b/server/src/services/agent-task-run-telemetry.ts index 11e5d58fce5..7927dc9a69c 100644 --- a/server/src/services/agent-task-run-telemetry.ts +++ b/server/src/services/agent-task-run-telemetry.ts @@ -13,7 +13,37 @@ type HeartbeatRun = typeof heartbeatRuns.$inferSelect; type TelemetryRun = Pick - & Partial>; + & Partial>; + +export type RunFailureStatus = "failed" | "timed_out" | "cancelled"; +export type RunFailureTransitionState = Pick; + +export function isRunFailureStatus(status: string): status is RunFailureStatus { + return status === "failed" || status === "timed_out" || status === "cancelled"; +} + +/** + * A native run that waits for a same-run retry is stored as `failed` with + * `nativePhase: "retryable_failure"`. That is not terminal: the retry or the + * workspace copy-back retry can still finish the run as succeeded. + */ +export function isPendingNativeRetry(run: RunFailureTransitionState): boolean { + return run.status === "failed" && run.runtimeMode === "native" && run.nativePhase === "retryable_failure"; +} + +/** + * Whether a status write is a new terminal failure for telemetry and + * `reportRunFailure`. A write into a pending native retry (`failed` with + * `nativePhase: "retryable_failure"`) is not terminal. A run that leaves a + * pending native retry into a terminal failure status counts, even when + * `status` stays `failed`, because its earlier write was skipped. + */ +export function isNewTerminalRunFailure(before: RunFailureTransitionState, after: RunFailureTransitionState): boolean { + if (!isRunFailureStatus(after.status)) return false; + if (isPendingNativeRetry(after)) return false; + if (after.status !== before.status) return true; + return isPendingNativeRetry(before); +} const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; @@ -209,6 +239,15 @@ function resolveDurationSeconds( * remove the delay. */ export async function emitAgentTaskRun(db: Db, run: TelemetryRun): Promise { + if ( + isPendingNativeRetry({ + status: run.status, + runtimeMode: run.runtimeMode ?? "legacy", + nativePhase: run.nativePhase ?? null, + }) + ) { + return; + } void reportFinalizedRunDiagnostics(db, run); try { const client = getTelemetryClient(); @@ -319,6 +358,7 @@ export async function emitAgentTaskRunById( stderrExcerpt: heartbeatRuns.stderrExcerpt, driverKind: heartbeatRuns.driverKind, runtimeMode: heartbeatRuns.runtimeMode, + nativePhase: heartbeatRuns.nativePhase, resultJson: sql | null>`jsonb_build_object('providerFailure', jsonb_build_object('category', ${heartbeatRuns.resultJson}->'providerFailure'->'category'))`, }) .from(heartbeatRuns) diff --git a/server/src/services/execution-control-reconciliation.ts b/server/src/services/execution-control-reconciliation.ts index 87ca219cfa8..ec95e4b5167 100644 --- a/server/src/services/execution-control-reconciliation.ts +++ b/server/src/services/execution-control-reconciliation.ts @@ -20,7 +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 { reportRunFailure } from "./run-failure-report.js"; +import { emitTerminalRunFailure, isNewTerminalRunFailure } 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"; import { EXECUTION_FINALIZATION_DEADLINE_EXCEEDED, EXECUTION_FINALIZATION_DEADLINE_MESSAGE, @@ -288,7 +288,7 @@ export async function reconcileAbandonedExecutionControl( }) .where(eq(heartbeatRuns.id, run.id)) .returning(); - if (updatedRun && updatedRun.status !== run.status) { + if (updatedRun && isNewTerminalRunFailure(run, updatedRun)) { terminalRunToReport = updatedRun; } await tx @@ -360,7 +360,9 @@ export async function reconcileAbandonedExecutionControl( return true; }); if (repaired) surfaced += 1; - if (terminalRunToReport) void reportRunFailure(db, terminalRunToReport); + if (terminalRunToReport) { + emitTerminalRunFailure(db, terminalRunToReport); + } } catch { logger.warn( { runId: candidate.runId }, diff --git a/server/src/services/execution-recovery-resolution.ts b/server/src/services/execution-recovery-resolution.ts index bf7600e52f4..448c86bbd5b 100644 --- a/server/src/services/execution-recovery-resolution.ts +++ b/server/src/services/execution-recovery-resolution.ts @@ -80,7 +80,7 @@ export function executionRecoverySettlementNote(input: { : "Automatic recovery stopped. Recorded work is preserved; actions with unverified outcomes will not be repeated."; } -type ExecutionReconciliationInput = { +type ExecutionReconciliationBaseInput = { db: Db; companyId: string; issueId: string; @@ -89,19 +89,39 @@ type ExecutionReconciliationInput = { decision: ExecutionReconciliation | undefined; /** Board-only source repair: never authorize a continuation of this run. */ workspaceRepairOnly?: boolean; - controllerContainment?: { actionId: string; actorId: string }; }; +type ExecutionReconciliationInput = + | (ExecutionReconciliationBaseInput & { + controllerContainment: { actionId: string; actorId: string }; + /** Root database handle for post-commit telemetry (required so containment never queries a finished outer transaction). */ + telemetryDb: Db; + }) + | (ExecutionReconciliationBaseInput & { + controllerContainment?: undefined; + /** Optional root database handle for post-commit telemetry when `db` is an outer transaction. */ + telemetryDb?: Db; + }); + export async function validateExecutionReconciliation(input: ExecutionReconciliationInput) { if (input.controllerContainment) { + if (!input.telemetryDb) { + throw new Error("controller_containment_requires_root_telemetry_db"); + } + const { telemetryDb } = input; // 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 }, telemetryDb), + ); } - return validateExecutionReconciliationInScope(input); + return validateExecutionReconciliationInScope(input, input.telemetryDb); } -async function validateExecutionReconciliationInScope(input: ExecutionReconciliationInput) { +async function validateExecutionReconciliationInScope( + input: ExecutionReconciliationInput, + telemetryDb: Db | undefined, +) { const { db, companyId, issueId, agentId, decision } = input; if (!decision || decision.runId !== input.sourceRunId || (!agentId && !input.workspaceRepairOnly)) { throw conflict( @@ -112,10 +132,14 @@ async function validateExecutionReconciliationInScope(input: ExecutionReconcilia if (decision.controllerStopped !== undefined || decision.controllerAuthorityDigest !== undefined) { if (!decision.controllerStopped || !decision.controllerAuthorityDigest || !input.controllerContainment || input.workspaceRepairOnly) throw conflict("Original-host controller containment requires its exact board recovery action."); + if (!telemetryDb) { + throw new Error("controller_containment_requires_root_telemetry_db"); + } operatorContained = await settleOperatorContainedNativeOwner(db, { 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" }); diff --git a/server/src/services/issue-thread-interactions.ts b/server/src/services/issue-thread-interactions.ts index dfa5473eb32..e4c838306e2 100644 --- a/server/src/services/issue-thread-interactions.ts +++ b/server/src/services/issue-thread-interactions.ts @@ -156,6 +156,7 @@ import { publishCommittedBoardEvent, } from "./headless-common.js"; import type { BoardEventView } from "@paperclipai/shared"; +import { emitAgentTaskCompleted } from "./agent-task-run-telemetry.js"; import { emitPlanApprovedAfterCommit, emitChatStartedIfFirstOwnerTurn } from "./product-telemetry.js"; import { authorizationService } from "./authorization.js"; import { isCloudManagedInstance } from "./cloud-instance.js"; @@ -2906,6 +2907,7 @@ export function issueThreadInteractionService( const now = new Date(); const postCommitActivityPublications: ActivityPublication[] = []; const postCommitBoardEvents: BoardEventView[] = []; + let completedTask: Parameters[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); @@ -3105,6 +3107,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({ @@ -3221,6 +3233,7 @@ export function issueThreadInteractionService( for (const publication of postCommitActivityPublications) publishActivity(publication); for (const event of postCommitBoardEvents) publishCommittedBoardEvent(event); await emitInteractionResolvedTelemetry(committedDb, result.interaction); + if (completedTask) void emitAgentTaskCompleted(committedDb, completedTask); }; if (args.mutationOptions?.deferConfirmationCommitEffects) args.mutationOptions.deferConfirmationCommitEffects(publish); else await publish(db); diff --git a/server/src/services/native-runtime/native-failed-run-owner-release.ts b/server/src/services/native-runtime/native-failed-run-owner-release.ts index 5fcbdaff7f6..8d394b9a380 100644 --- a/server/src/services/native-runtime/native-failed-run-owner-release.ts +++ b/server/src/services/native-runtime/native-failed-run-owner-release.ts @@ -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 { emitTerminalRunFailure, isNewTerminalRunFailure } from "../run-failure-report.js"; import { logger } from "../../middleware/logger.js"; import { adapterExecutionControls } from "../adapter-execution-control.js"; import { proveOwnerGone, type LocalOwnerStamp } from "../owner-proof.js"; @@ -47,7 +48,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 ( @@ -368,6 +369,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 (isNewTerminalRunFailure(run, settledRun)) { + const telemetryDb = release.telemetryDb; + afterTransactionCommit(() => { + emitTerminalRunFailure(telemetryDb, settledRun, { failureReport: false }); + }); + } await preserveNativeFailedWorkspace(tx, settledRun); await settleNativeTerminalWake(tx, settledRun); await notifyNativeStatusReassessment(tx, scope); @@ -480,6 +487,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 { const [owner] = await db.select().from(nativeRunFinalizations).where(and( eq(nativeRunFinalizations.companyId, input.companyId), eq(nativeRunFinalizations.issueId, input.issueId), diff --git a/server/src/services/native-runtime/native-finalization-reconciler.ts b/server/src/services/native-runtime/native-finalization-reconciler.ts index 89b268f7f48..520021ff88c 100644 --- a/server/src/services/native-runtime/native-finalization-reconciler.ts +++ b/server/src/services/native-runtime/native-finalization-reconciler.ts @@ -175,9 +175,15 @@ export async function claimNativeSessionResumptions(input: { eq(heartbeatRuns.nativeIssueId, issue.id), )).for("update").limit(1); if (!run || !coordinator || run.runnerProfileJson?.legacyWorkspaceRecoveryMigration != null) return false; - if (await retireSupersededNativeRetry(tx as unknown as Db, { + const retiredSuperseded = await retireSupersededNativeRetry(tx as unknown as Db, { run, coordinator, issueExecutionRunId: issue.executionRunId, now, - })) return false; + }); + if (retiredSuperseded) { + if (isNewTerminalRunFailure(run, retiredSuperseded)) { + terminalRunToEmit = retiredSuperseded; + } + return false; + } if (!(NATIVE_SESSION_RESUMPTION_ISSUE_STATUSES as readonly string[]).includes(issue.status)) return false; const row = { run, coordinator }; if ( diff --git a/server/src/services/native-runtime/native-restart-recovery.ts b/server/src/services/native-runtime/native-restart-recovery.ts index 0d379910cfe..b23be87aed5 100644 --- a/server/src/services/native-runtime/native-restart-recovery.ts +++ b/server/src/services/native-runtime/native-restart-recovery.ts @@ -50,7 +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 { isNewTerminalRunFailure, reportRunFailure } from "../run-failure-report.js"; +import { emitTerminalRunFailure, isNewTerminalRunFailure } 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"; import { retireSupersededNativeRetry } from "./native-superseded-retry.js"; @@ -1060,6 +1060,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: { @@ -1270,9 +1271,17 @@ export async function claimNativeRestartRecoveries(input: { reason: "result_already_persisted", } as const; } - if (!input.liveRunExecutions?.has(row.run.id) && await retireSupersededNativeRetry(tx as unknown as Db, { - run: row.run, coordinator: row.coordinator, issueExecutionRunId: row.issueExecutionRunId, now, - })) return { kind: "blocked", runId: row.run.id, reason: "native_retry_superseded" } as const; + const retiredSuperseded = !input.liveRunExecutions?.has(row.run.id) + ? await retireSupersededNativeRetry(tx as unknown as Db, { + run: row.run, coordinator: row.coordinator, issueExecutionRunId: row.issueExecutionRunId, now, + }) + : null; + if (retiredSuperseded) { + if (isNewTerminalRunFailure(row.run, retiredSuperseded)) { + terminalRunToReport = retiredSuperseded; + } + return { kind: "blocked", runId: row.run.id, reason: "native_retry_superseded" } as const; + } const profile = row.run.runnerProfileJson ?? {}; const storedRemoteWorkspace = remoteWorkspaceRunReferenceSchema.safeParse(profile.remoteWorkspace); const remoteWorkspace = readNativeWorkspaceSyncReference(profile.nativeWorkspaceSync) @@ -1498,12 +1507,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; } } @@ -2237,8 +2249,9 @@ export async function claimNativeRestartRecoveries(input: { reason: routineBusy ? "routine_execution_busy" : NATIVE_RESTART_RECOVERY_FAILED, retryAt: new Date(now.getTime() + 30_000) }; }); - if (terminalRunToReport) - void reportRunFailure(input.db, terminalRunToReport); + if (terminalRunToReport) { + emitTerminalRunFailure(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) @@ -2268,8 +2281,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; @@ -2296,12 +2310,19 @@ 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) { + emitTerminalRunFailure(db, terminalRunToEmit); + } + return result; } catch (error) { logger.warn({ err: error, runId: candidate.runId }, "bounded restart-recovery wait check deferred"); return waiting; diff --git a/server/src/services/native-runtime/native-run-finalizer.ts b/server/src/services/native-runtime/native-run-finalizer.ts index a8d3451c719..6e9d2a04db3 100644 --- a/server/src/services/native-runtime/native-run-finalizer.ts +++ b/server/src/services/native-runtime/native-run-finalizer.ts @@ -2215,6 +2215,7 @@ export async function finalizeNativeRun(input: { void reportRunFailure(input.db, projection.after); } else if (input.projectRunStatus && !alreadyEmittedByCommittedDecision && projection && isNewTerminalRunFailure(projection.before, projection.after)) { + void emitAgentTaskRun(input.db, projection.after); void reportRunFailure(input.db, projection.after); } if (input.projectRunStatus) diff --git a/server/src/services/native-runtime/native-run-projection.ts b/server/src/services/native-runtime/native-run-projection.ts index 1e0bf6875a7..500e9cf2b95 100644 --- a/server/src/services/native-runtime/native-run-projection.ts +++ b/server/src/services/native-runtime/native-run-projection.ts @@ -220,6 +220,7 @@ export async function projectCommittedRun(input: { await emitAgentTaskRun(input.db, projected.after); void reportRunFailure(input.db, projected.after); } else if (projected && isNewTerminalRunFailure(projected.before, projected.after)) { + void emitAgentTaskRun(input.db, projected.after); void reportRunFailure(input.db, projected.after); } } diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index b17c5186865..c483547401b 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -317,7 +317,7 @@ import { NATIVE_PROVIDER_SIDE_EFFECT_PENDING, NATIVE_PROVIDER_STATE_INCOMPATIBLE import { clearRunProviderStateUnsaved, markAcceptedRunProviderStateUnsaved } from "./native-provider-state-unsaved.js"; import { verifyRetainedMaintenanceNoLaunch } from "./native-maintenance-no-launch.js"; import { issueRecoveryActionService } from "../issue-recovery-actions.js"; -import { reportRunFailure } from "../run-failure-report.js"; +import { emitTerminalRunFailure, isNewTerminalRunFailure } from "../run-failure-report.js"; import { REMOTE_RECOVERY_MARKER_READ_SCRIPT, REMOTE_RECOVERY_PROCESS_CHECK_SCRIPT, REMOTE_RUNNER_EXIT_EVIDENCE_SCRIPT, RemoteRunnerRecoveryError, attachRemoteRunnerRecoveryDiagnostic, boundRemoteRunnerExitEvidence, @@ -13948,7 +13948,8 @@ async function executePaperclipNativeSessionAttempt( throw new Error("native_session_lease_lost"); } const [runBeforeWrite] = await tx - .select({ status: heartbeatRuns.status, resultJson: heartbeatRuns.resultJson, + .select({ status: heartbeatRuns.status, runtimeMode: heartbeatRuns.runtimeMode, + nativePhase: heartbeatRuns.nativePhase, resultJson: heartbeatRuns.resultJson, runnerInstanceId: heartbeatRuns.runnerInstanceId, nativeSessionId: heartbeatRuns.nativeSessionId, costAccountedAt: heartbeatRuns.costAccountedAt }) .from(heartbeatRuns) @@ -14016,7 +14017,7 @@ async function executePaperclipNativeSessionAttempt( if ( updatedRun && runBeforeWrite && - updatedRun.status !== runBeforeWrite.status + isNewTerminalRunFailure(runBeforeWrite, updatedRun) ) { terminalRunToReport = updatedRun; } @@ -14198,7 +14199,9 @@ 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) { + emitTerminalRunFailure(input.db, terminalRunToReport, { failureReport: { nativeCloseFailure: error } }); + } await boundedExecutionCleanup(async () => { await stoppedLeaseRenewal; await attemptFailureStep(() => diff --git a/server/src/services/native-runtime/native-superseded-retry.ts b/server/src/services/native-runtime/native-superseded-retry.ts index b79e9faff49..89289be420c 100644 --- a/server/src/services/native-runtime/native-superseded-retry.ts +++ b/server/src/services/native-runtime/native-superseded-retry.ts @@ -10,16 +10,16 @@ export async function retireSupersededNativeRetry(db: Db, input: { coordinator: typeof nativeRunFinalizations.$inferSelect; issueExecutionRunId: string | null; now: Date; -}): Promise { +}): Promise { const { run, coordinator, now } = input; if (run.runtimeMode !== "native" || run.status !== "failed" || !run.startedAt || !run.finishedAt || run.processPid !== null || run.processGroupId !== null || coordinator.phase !== "retryable_failure" || coordinator.resultId || coordinator.leaseOwner || coordinator.companyId !== run.companyId || coordinator.issueId !== run.nativeIssueId || coordinator.runId !== run.id || input.issueExecutionRunId === run.id - || run.runnerProfileJson?.nativeWorkspaceFinalizationOwner || nativeRunHasNoWorkspaceAccess(run)) return false; + || run.runnerProfileJson?.nativeWorkspaceFinalizationOwner || nativeRunHasNoWorkspaceAccess(run)) return null; const reference = readNativeWorkspaceSyncReference(run.runnerProfileJson?.nativeWorkspaceSync); - if (reference?.state !== "prepared") return false; + if (reference?.state !== "prepared") return null; const [successor] = await db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(and( eq(heartbeatRuns.companyId, run.companyId), eq(heartbeatRuns.nativeIssueId, coordinator.issueId), @@ -29,7 +29,7 @@ export async function retireSupersededNativeRetry(db: Db, input: { sql`${heartbeatRuns.contextSnapshot}->>'previousRunId' = ${run.id}`, sql`nullif(${heartbeatRuns.contextSnapshot}->>'taskRetryRequestId', '') is not null`, )).orderBy(desc(heartbeatRuns.startedAt)).limit(1); - if (!successor) return false; + if (!successor) return null; const [source] = await db.select({ id: environmentLeases.id }).from(environmentLeases).where(and( eq(environmentLeases.id, reference.leaseId), eq(environmentLeases.companyId, run.companyId), eq(environmentLeases.heartbeatRunId, run.id), eq(environmentLeases.issueId, coordinator.issueId), @@ -37,7 +37,7 @@ export async function retireSupersededNativeRetry(db: Db, input: { sql`${environmentLeases.metadata}->>'remoteCwd' = ${reference.remoteCwd}`, sql`(${environmentLeases.executionWorkspaceId} is null or ${environmentLeases.executionWorkspaceId}::text = ${reference.workspaceId})`, )).limit(1); - if (!source) return false; + if (!source) return null; await notifyExecutionRunWork(db, { companyId: run.companyId, runId: run.id }); await db.update(nativeRunFinalizations).set({ phase: "terminal_failure", nextAttemptAt: null, @@ -52,5 +52,5 @@ export async function retireSupersededNativeRetry(db: Db, input: { if (!preserved || !hasRequiredWorkspaceRecovery(preserved.resultJson)) { throw new Error("superseded_native_retry_preservation_not_recorded"); } - return true; + return preserved; } diff --git a/server/src/services/onboarding-seed.ts b/server/src/services/onboarding-seed.ts index 86d24d3d878..48f69971bc4 100644 --- a/server/src/services/onboarding-seed.ts +++ b/server/src/services/onboarding-seed.ts @@ -1,8 +1,9 @@ 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 { getDefaultCloudTrialInferenceController } from "./cloud-trial-inference.js"; +import { trackAgentCreated, trackGoalCreated } from "@paperclipai/shared/telemetry"; import { writePaperclipSkillSyncPreference } from "@paperclipai/adapter-utils/server-utils"; import { findActiveServerAdapter } from "../adapters/registry.js"; import { agentService } from "./agents.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"; /** @@ -192,6 +195,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", @@ -210,6 +224,7 @@ export function onboardingSeedService(db: Db) { companyId: string, seed: ApplyOnboardingSeed, preparedAgentId: string | null, + audit?: OnboardingSeedAuditActor, ): Promise { const goalSvc = goalService(dbx); @@ -251,6 +266,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"); + } + }); } } @@ -321,7 +350,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( diff --git a/server/src/services/routine-standing-checks.ts b/server/src/services/routine-standing-checks.ts index bf880b04d15..8852b9dad5f 100644 --- a/server/src/services/routine-standing-checks.ts +++ b/server/src/services/routine-standing-checks.ts @@ -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 }; }, }; diff --git a/server/src/services/routine-suggestions.ts b/server/src/services/routine-suggestions.ts index e11feef2a53..b2ee1475274 100644 --- a/server/src/services/routine-suggestions.ts +++ b/server/src/services/routine-suggestions.ts @@ -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 { diff --git a/server/src/services/run-failure-report.ts b/server/src/services/run-failure-report.ts index 49572e67db5..d8d3b19948d 100644 --- a/server/src/services/run-failure-report.ts +++ b/server/src/services/run-failure-report.ts @@ -27,6 +27,14 @@ import { REVIEWED_CHAT_BINDING_NOT_READY } from "./reviewed-chat-binding-diagnos import { REUSABLE_SANDBOX_RESUME_FAILED_CODE } from "./reusable-sandbox-resume-error.js"; import { WORKSPACE_STORAGE_RETRY_CODES } from "./workspace-provider-failure.js"; import { readProviderFailure } from "@paperclipai/shared"; +import { + emitAgentTaskRun, + isNewTerminalRunFailure, + isPendingNativeRetry, + isRunFailureStatus, +} from "./agent-task-run-telemetry.js"; + +export { isNewTerminalRunFailure, isPendingNativeRetry, isRunFailureStatus }; type HeartbeatRun = typeof heartbeatRuns.$inferSelect; @@ -46,29 +54,31 @@ const pendingRunFailureReports = new Set>(); /** Bounds the shutdown wait, so one stuck report cannot hang the process exit. */ const PENDING_REPORT_DRAIN_TIMEOUT_MS = 5_000; -function isRunFailureStatus(status: string): status is RunFailureStatus { - return status === "failed" || status === "timed_out" || status === "cancelled"; -} - -type RunFailureTransitionState = Pick; - /** - * A native run that waits for a same-run retry is stored as `failed` with - * `nativePhase: "retryable_failure"`. That is not terminal: the retry or the - * workspace copy-back retry can still finish the run as succeeded. + * Emits post-commit terminal failure telemetry (`agent.task_run`) and, unless + * disabled with `failureReport: false`, reports the failure to Sentry. + * Skips pending native retries (`failed` with `nativePhase: "retryable_failure"`). + * When `before` is provided, emits only when `isNewTerminalRunFailure(before, run)` + * is true. Always fire-and-forget; never blocks or throws. */ -function isPendingNativeRetry(run: RunFailureTransitionState): boolean { - return run.status === "failed" && run.runtimeMode === "native" && run.nativePhase === "retryable_failure"; -} - -/** - * Whether a status write is a new terminal failure to pass to `reportRunFailure`. - * A status change counts. A run that leaves a pending native retry but stays - * `failed` also counts, because `reportRunFailure` skipped its earlier write. - */ -export function isNewTerminalRunFailure(before: RunFailureTransitionState, after: RunFailureTransitionState): boolean { - if (after.status !== before.status) return true; - return isPendingNativeRetry(before) && !isPendingNativeRetry(after); +export function emitTerminalRunFailure( + db: Db, + run: HeartbeatRun, + options?: { + before?: Pick | null; + failureReport?: RunFailureReportOptions | false; + }, +): boolean { + if (options?.before !== undefined) { + if (!options.before || !isNewTerminalRunFailure(options.before, run)) return false; + } else if (!isRunFailureStatus(run.status) || isPendingNativeRetry(run)) { + return false; + } + void emitAgentTaskRun(db, run); + if (options?.failureReport !== false) { + void reportRunFailure(db, run, options?.failureReport); + } + return true; } function readTaskId(run: HeartbeatRun): string | null { diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index d53f51a7381..a689033509c 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -401,7 +401,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",