fix(telemetry): send agent.task_completed when a native run closes a task (#22963)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Paperclip sends product telemetry, and the `agent.task_completed`
event counts each task that an agent finishes
> - Only the REST issue update route (`server/src/routes/issues.ts`)
sent `agent.task_completed` when an agent moved a task to `done`
> - Native runs close tasks through `commitNativeStatusDecision` in
`server/src/services/native-runtime/status-decision-committer.ts`, which
bypasses the REST route and therefore sent `agent.task_run` without ever
sending `agent.task_completed`
> - Deployments where agents close tasks through native runs
consequently under-report completed tasks
> - This pull request supersedes #21206 (rebased onto current `master`),
sending `agent.task_completed` once after a committed native transition
into `done` without blocking finalization, with full company/person
telemetry scope and underlying Paperclip runner harness `adapter_type`
resolution
> - The benefit is accurate, deduplicated `agent.task_completed`
telemetry across both API and native completion paths

## Linked Issues or Issue Description

Refs #21206

**What happened?**
A native run closes a task through `commitNativeStatusDecision` in
`server/src/services/native-runtime/status-decision-committer.ts`. The
task moves to `done` and the run sends `agent.task_run`, but no
`agent.task_completed` event is sent because the only sender is
`server/src/routes/issues.ts` and native completion does not go through
that route.

**Expected behavior**
Paperclip sends one `agent.task_completed` event each time an agent
moves a task into `done`, on both the REST issue route and native status
commits. The event carries the same dimensions, runner harness
`adapter_type`, company scope, and person attribution as the issue
route. Replayed commits and tasks that were already `done` send nothing.

**Steps to reproduce**
1. Seed a native run ready to commit a `done` status decision on an
`in_progress` task.
2. Call `commitNativeStatusDecision` (or `finalizeNativeRun`) with a
`done` decision.
3. Observe that the task moves to `done`, while
`trackAgentTaskCompleted` is called 0 times.

**Paperclip version or commit**
`master` at `2d065677959b585065ff3fec8718156a4cf6f41d`.

## What Changed

- `server/src/services/agent-task-run-telemetry.ts`: add
`emitAgentTaskCompleted`. It loads the agent within the task's
`companyId`, resolves the underlying runner harness with
`telemetryAdapterType(agent)`, resolves person attribution with
`resolveTelemetryPerson`, wraps `trackAgentTaskCompleted` in
`withTelemetryActor({ companyId, person }, ...)`, and never throws.
- `server/src/services/native-runtime/status-decision-committer.ts`:
select `originRun.responsibleUserId` alongside `originRun.agentId`,
capture the completion payload only when the committed transaction
transitions `issue.status` from non-`done` to `done` with an origin
agent, and invoke `void emitAgentTaskCompleted(input.db, completedTask)`
after commit when `!committed.replayed` so slow lookups cannot block run
finalization.
-
`server/src/services/native-runtime/native-task-completed-telemetry.test.ts`:
add embedded-Postgres regression tests covering single emission (with
company scope, person attribution, and underlying runner harness
`adapter_type`), no duplicate on replay, non-blocking commit while
telemetry is pending, and no emission when the task was already `done`.
- `server/src/__tests__/agent-task-run-telemetry.test.ts`: add unit/DB
coverage for `emitAgentTaskCompleted` (company/person scope, runner
harness `adapterType`, cross-company agent isolation, and error
swallowing).
-
`server/src/services/native-runtime/native-run-finalizer-telemetry.test.ts`:
add an end-to-end `finalizeNativeRun` integration test verifying a real
native run completion emits `agent.task_completed` once through the real
`trackAgentTaskCompleted` path and emits no duplicates on replay or
reconciliation.

Note: this PR supersedes #21206 (whose fork branch had merge conflicts
with pruned test suites and predated `withTelemetryActor` /
`telemetryAdapterType` on `master`, and whose fork repository did not
allow maintainer pushes from this account).

## Verification

- **RED (before fix on `2d065677959b585065ff3fec8718156a4cf6f41d`):**
`pnpm --dir server exec vitest run
src/services/native-runtime/native-task-completed-telemetry.test.ts`
Result: 1 failed | 1 passed — `sends agent.task_completed once with
company, person, and harness adapter_type when the runner closes a task`
failed with `AssertionError: expected "vi.fn()" to be called 1 times,
but got 0 times`.
- **GREEN (after fix):**
`pnpm --dir server exec vitest run
src/services/native-runtime/native-task-completed-telemetry.test.ts
src/__tests__/agent-task-run-telemetry.test.ts
src/services/native-runtime/native-run-finalizer-telemetry.test.ts
src/__tests__/heartbeat-status-preserving-telemetry.test.ts
src/__tests__/issue-telemetry-routes.test.ts`
Result: **5/5 files, 106/106 tests passed**
(`native-task-completed-telemetry.test.ts` 3/3,
`agent-task-run-telemetry.test.ts` 55/55,
`native-run-finalizer-telemetry.test.ts` 42/42 including end-to-end
`finalizeNativeRun`, `issue-telemetry-routes.test.ts` 5/5,
`heartbeat-status-preserving-telemetry.test.ts` 1/1).
- **Typecheck:** `pnpm --filter @paperclipai/server typecheck` —
**PASS** (0 errors across all layers).
- **Test budget:** `node scripts/check-test-budget.mjs --files
server/src/services/native-runtime/native-task-completed-telemetry.test.ts
server/src/__tests__/agent-task-run-telemetry.test.ts
server/src/services/native-runtime/native-run-finalizer-telemetry.test.ts`
— **PASS** (110 nightly suites validated, 3 test files checked).
- **Broader suite:** `pnpm verify --base
2d06567795 --explain` conservatively
selected 1948/2302 files; PR CI supplies the full sharded server,
runner, typecheck, and build verification.
- **Runtime dependency assumption
(`rules/runtime-dependency-boundaries.mdc`):**
`commitNativeStatusDecision` fires `void emitAgentTaskCompleted(...)`
after transaction commit without awaiting it;
`native-task-completed-telemetry.test.ts` verifies with a
never-resolving promise that run finalization returns immediately even
if the telemetry lookup hangs.

## Risks

- Low risk. Emission runs after transaction commit as fire-and-forget
and catches all errors, so a rolled-back commit sends nothing and a
telemetry fault cannot fail or delay a status commit.
- Deployments where native runs close tasks will see
`agent.task_completed` counts rise to reflect actual completions, which
is the intended fix.

## Model Used

- Google Antigravity (`antigravity`, tool use and code execution),
building on and rebasing #21206 onto `master`.

## 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
- [x] I will address all Greptile and reviewer comments before
requesting merge
This commit is contained in:
Dotta authored and GitHub committed 2026-11-25 16:02:12 -06:00
1 parent 702368ffaf
commit 168253f74d
7 files changed
+454 -4

No files matched your search

@@ -13,6 +13,7 @@ import { PAPERCLIP_RUNNER_ACPX_PROFILES, PAPERCLIP_RUNNER_PERMISSION_CAPABILITIE
import { PERMANENT_FAILURE_CODES, PERSON_OWNED_FAILURE_CODES, RESTART_CLASS_FAILURE_CODES, SETUP_FAILURE_CODES } from "../services/continuation-cause.ts";
const mockTelemetryClient = vi.hoisted(() => ({ track: vi.fn() }));
const mockTrackAgentTaskCompleted = vi.hoisted(() => vi.fn());
const mockTrackAgentTaskRun = vi.hoisted(() => vi.fn());
vi.mock("../telemetry.js", () => ({
@@ -25,11 +26,18 @@ vi.mock("@paperclipai/shared/telemetry", async () => {
);
return {
...actual,
trackAgentTaskCompleted: mockTrackAgentTaskCompleted,
trackAgentTaskRun: mockTrackAgentTaskRun,
};
});
import { agentRunFailureCause, emitAgentTaskRun, emitAgentTaskRunById, telemetryAdapterType } from "../services/agent-task-run-telemetry.ts";
import {
agentRunFailureCause,
emitAgentTaskCompleted,
emitAgentTaskRun,
emitAgentTaskRunById,
telemetryAdapterType,
} from "../services/agent-task-run-telemetry.ts";
const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
@@ -430,6 +438,61 @@ describeEmbeddedPostgres("emitAgentTaskRun", () => {
expect(sent[2]).not.toHaveProperty("failureCause");
expect(JSON.stringify(sent)).not.toContain("secret detail");
});
it("emits agent.task_completed in company and person scope with underlying runner harness adapterType", async () => {
await seedCompanyAndAgent({
adapterType: "paperclip_runner",
adapterConfig: { provider: "acpx", acpxAgent: "claude", model: "claude-opus-4-6" },
});
const issueId = randomUUID();
const observed: Array<{ companyId: string | undefined; person: unknown }> = [];
mockTrackAgentTaskCompleted.mockImplementationOnce(() => {
observed.push({ companyId: scopedTelemetryCompanyId(), person: scopedTelemetryPerson() });
});
await emitAgentTaskCompleted(db, {
companyId,
agentId,
issueId,
taskCreatedByUserId: "user-creator",
taskAssignedByUserId: "user-assigner",
runOwnerUserId: "user-owner",
});
expect(mockTrackAgentTaskCompleted).toHaveBeenCalledExactlyOnceWith(mockTelemetryClient, {
agentRole: "engineer",
agentId,
adapterType: "claude_local",
model: "claude-opus-4-6",
taskId: issueId,
});
expect(observed).toEqual([
{ companyId, person: { userId: "user-creator", attributedVia: "task_creator" } },
]);
expect(scopedTelemetryCompanyId()).toBeUndefined();
expect(scopedTelemetryPerson()).toBeUndefined();
});
it("does not emit agent.task_completed for an agent in another company and never throws on emit failure", async () => {
await seedCompanyAndAgent({ adapterConfig: {} });
const issueId = randomUUID();
await emitAgentTaskCompleted(db, { companyId: randomUUID(), agentId, issueId });
expect(mockTrackAgentTaskCompleted).not.toHaveBeenCalled();
mockTrackAgentTaskCompleted.mockImplementationOnce(() => {
throw new Error("telemetry backend unreachable");
});
await expect(
emitAgentTaskCompleted(db, { companyId, agentId, issueId, runOwnerUserId: "user-owner" }),
).resolves.toBeUndefined();
expect(mockTrackAgentTaskCompleted).toHaveBeenCalledExactlyOnceWith(mockTelemetryClient, {
agentRole: "engineer",
agentId,
adapterType: "codex_local",
taskId: issueId,
});
});
});
describe("agentRunFailureCause", () => {