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

## 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
This commit is contained in:
Dotta authored and GitHub committed 2026-12-04 20:08:57 -06:00
1 parent 1a20fb1953
commit 205482b2c2
20 files changed
+1714 -71

No files matched your search

+17 -11
View File
@@ -118,6 +118,10 @@ for their exact dimensions and optionality.
`agent.task_run` records one terminal state for one agent run: `succeeded`,
`interrupted`, `failed`, `cancelled`, or `timed_out`. Emit it once per run, at
the run's terminal transition. Do not emit it for a run that is still active.
Every path that writes a run into a terminal state — including legacy heartbeat
finalization, native session failure settlement, native restart recovery,
execution-control reconciliation, and operator-contained native owner release —
must emit `agent.task_run` once after commit without blocking run settlement.
The event's `task_id` dimension is optional and privacy-protected. Never emit
the raw task id. Pass the raw id to `trackAgentTaskRun()` in `events.ts`. The
@@ -149,17 +153,19 @@ harness is missing from the contract. Add it to the telemetry-backend schema
first, then copy the regenerated contract here.
`agent.task_completed` records one task completion when an agent moves a task
from a non-`done` status into `done`. Both the REST issue update route and the
native status decision committer (`commitNativeStatusDecision` via
`emitAgentTaskCompleted`) emit this event once per committed transition into
`done`. Native completion starts the emit after the transaction commits without
awaiting it, so telemetry lookups never block or fail run finalization. A
rolled-back transaction, a replayed native decision (`replayed: true`), or a
commit on a task that is already `done` (for example, already closed by the
issue route) emits nothing. Native completion sends the same dimensions as the
issue route, including `telemetryAdapterType()` for Paperclip runner harnesses
and `withTelemetryActor()` / `resolveTelemetryPerson()` for Cloud company and
person attribution.
from a non-`done` status into `done`. The REST issue update route, the native
status decision committer (`commitNativeStatusDecision` via
`emitAgentTaskCompleted`), and agent-accepted `native_completion_review`
interaction approvals (`issue-thread-interactions.ts`) emit this event once per
committed transition into `done`. Native and interaction completion paths start
the emit after the transaction commits without awaiting it, so telemetry lookups
never block or fail run finalization. A rolled-back transaction, a replayed
native decision (`replayed: true`), or a commit on a task that is already `done`
(for example, already closed by the issue route) emits nothing. Native and
interaction completion paths send the same dimensions as the issue route,
including `telemetryAdapterType()` for Paperclip runner harnesses and
`withTelemetryActor()` / `resolveTelemetryPerson()` for Cloud company and person
attribution.
## Product Lifecycle Events
File diff suppressed because it is too large. Load diff
@@ -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),
+3 -2
View File
@@ -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,
@@ -13,7 +13,37 @@ type HeartbeatRun = typeof heartbeatRuns.$inferSelect;
type TelemetryRun = Pick<HeartbeatRun,
"id" | "companyId" | "agentId" | "status" | "startedAt" | "finishedAt" | "usageJson" | "contextSnapshot"
| "errorCode" | "resultJson">
& Partial<Pick<HeartbeatRun, "responsibleUserId" | "error" | "stderrExcerpt" | "driverKind" | "runtimeMode">>;
& Partial<Pick<HeartbeatRun, "responsibleUserId" | "error" | "stderrExcerpt" | "driverKind" | "runtimeMode" | "nativePhase">>;
export type RunFailureStatus = "failed" | "timed_out" | "cancelled";
export type RunFailureTransitionState = Pick<HeartbeatRun, "status" | "runtimeMode" | "nativePhase">;
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<void> {
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<Record<string, unknown> | null>`jsonb_build_object('providerFailure', jsonb_build_object('category', ${heartbeatRuns.resultJson}->'providerFailure'->'category'))`,
})
.from(heartbeatRuns)
@@ -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 },
@@ -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" });
@@ -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<typeof emitAgentTaskCompleted>[1] | null = null;
const result = await db.transaction(async (tx) => {
await assertInteractionRunWriteAllowed(tx as unknown as Db, args.issue, args.actor, [JSON.stringify(args.input)]);
await notifyChatConfirmationResolution(tx, args.current);
@@ -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);
@@ -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<boolean> {
const [owner] = await db.select().from(nativeRunFinalizations).where(and(
eq(nativeRunFinalizations.companyId, input.companyId), eq(nativeRunFinalizations.issueId, input.issueId),
@@ -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 (
@@ -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;
@@ -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)
@@ -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);
}
}
@@ -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(() =>
@@ -10,16 +10,16 @@ export async function retireSupersededNativeRetry(db: Db, input: {
coordinator: typeof nativeRunFinalizations.$inferSelect;
issueExecutionRunId: string | null;
now: Date;
}): Promise<boolean> {
}): Promise<typeof heartbeatRuns.$inferSelect | null> {
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;
}
+32 -3
View File
@@ -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<OnboardingSeedApplication> {
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(
@@ -8,8 +8,12 @@ import {
type StandingCheckOutcome,
type StandingCheckReported,
} from "@paperclipai/shared";
import { trackRoutineRun } from "@paperclipai/shared/telemetry";
import { asBoolean, asNumber, parseObject } from "../adapters/utils.js";
import { conflict, forbidden, notFound, unprocessable } from "../errors.js";
import { logger } from "../middleware/logger.js";
import { getTelemetryClient } from "../telemetry.js";
import { withTelemetryCompany } from "../telemetry-company-scope.js";
import { supportsUnscopedTimerHeartbeat } from "./heartbeat-policy.js";
/**
@@ -206,6 +210,19 @@ export function standingCheckService(db: Db) {
.where(eq(routines.id, routine.id));
return created!;
});
try {
const telemetryClient = getTelemetryClient();
if (telemetryClient) {
withTelemetryCompany(routine.companyId, () =>
trackRoutineRun(telemetryClient, {
source: STANDING_CHECK_TRIGGER_KIND,
status: "completed",
}),
);
}
} catch (err) {
logger.warn({ err, routineId: routine.id, runId: run.id }, "failed to emit routine.run telemetry");
}
return { routineId: routine.id, runId: run.id, checkedAt: checkedAt.toISOString(), outcome, note, issueId };
},
};
@@ -25,8 +25,11 @@ import {
type SuggestRoutineInteraction,
type SuggestRoutinePayload,
} from "@paperclipai/shared";
import { trackRoutineCreated } from "@paperclipai/shared/telemetry";
import { conflict, forbidden, notFound, unprocessable } from "../errors.js";
import { logger } from "../middleware/logger.js";
import { getTelemetryClient } from "../telemetry.js";
import { resolveTelemetryPerson, withTelemetryActor } from "../telemetry-company-scope.js";
import { instanceSettingsService } from "./instance-settings.js";
import { isAcceptClaimLost, issueThreadInteractionService, type AcceptClaim } from "./issue-thread-interactions.js";
import { responsibilityService } from "./responsibilities.js";
@@ -343,6 +346,15 @@ export function routineSuggestionService(
throw error;
}
const trigger = created.trigger;
try {
const telemetryClient = getTelemetryClient();
if (telemetryClient) {
const person = resolveTelemetryPerson({ runOwnerUserId: actor.userId });
withTelemetryActor({ companyId: issue.companyId, person }, () => trackRoutineCreated(telemetryClient));
}
} catch (err) {
logger.warn({ err, routineId: routine.id }, "failed to emit routine.created telemetry");
}
const filed: FiledUnder = [];
try {
+31 -21
View File
@@ -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<Promise<void>>();
/** 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<HeartbeatRun, "status" | "runtimeMode" | "nativePhase">;
/**
* 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<HeartbeatRun, "status" | "runtimeMode" | "nativePhase"> | 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 {
@@ -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",