mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-26 01:39:51 +01:00
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:
1 parent
702368ffaf
commit
168253f74d
7 files changed
+454
-4
No files matched your search
@@ -148,6 +148,19 @@ Every runner harness is in the generated `adapter_type` enum. A test in
|
||||
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.
|
||||
|
||||
## Product Lifecycle Events
|
||||
|
||||
`model.connected`, `task.created`, `task.completed`, `task.blocked`,
|
||||
|
||||
@@ -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", () => {
|
||||
|
||||
@@ -2,7 +2,7 @@ import { and, eq, sql } from "drizzle-orm";
|
||||
import { agents, heartbeatRuns, issues, type Db } from "@paperclipai/db";
|
||||
import { agentHarnessName, requiresExecutionReconciliation } from "@paperclipai/shared";
|
||||
import { PERMANENT_FAILURE_CODES, RESTART_CLASS_FAILURE_CODES, SETUP_FAILURE_CODES } from "./continuation-cause.js";
|
||||
import { trackAgentTaskRun } from "@paperclipai/shared/telemetry";
|
||||
import { trackAgentTaskCompleted, trackAgentTaskRun } from "@paperclipai/shared/telemetry";
|
||||
import { parseObject } from "../adapters/utils.js";
|
||||
import { logger } from "../middleware/logger.js";
|
||||
import { getTelemetryClient } from "../telemetry.js";
|
||||
@@ -320,3 +320,51 @@ export async function emitAgentTaskRunById(
|
||||
logger.warn({ err, runId: input.runId }, "failed to load run for agent.task_run telemetry");
|
||||
}
|
||||
}
|
||||
|
||||
export async function emitAgentTaskCompleted(
|
||||
db: Db,
|
||||
input: {
|
||||
companyId: string;
|
||||
agentId: string;
|
||||
issueId: string;
|
||||
taskCreatedByUserId?: string | null;
|
||||
taskAssignedByUserId?: string | null;
|
||||
runOwnerUserId?: string | null;
|
||||
},
|
||||
): Promise<void> {
|
||||
try {
|
||||
const client = getTelemetryClient();
|
||||
if (!client) return;
|
||||
|
||||
const agent = await db
|
||||
.select({
|
||||
id: agents.id,
|
||||
role: agents.role,
|
||||
adapterType: agents.adapterType,
|
||||
adapterConfig: agents.adapterConfig,
|
||||
})
|
||||
.from(agents)
|
||||
.where(and(eq(agents.id, input.agentId), eq(agents.companyId, input.companyId)))
|
||||
.then((rows) => rows[0] ?? null);
|
||||
if (!agent) return;
|
||||
|
||||
const model = readNonEmptyString(parseObject(agent.adapterConfig).model) ?? undefined;
|
||||
const person = resolveTelemetryPerson({
|
||||
taskCreatedByUserId: input.taskCreatedByUserId,
|
||||
taskAssignedByUserId: input.taskAssignedByUserId,
|
||||
runOwnerUserId: input.runOwnerUserId,
|
||||
});
|
||||
withTelemetryActor({ companyId: input.companyId, person }, () => trackAgentTaskCompleted(client, {
|
||||
agentRole: agent.role,
|
||||
agentId: agent.id,
|
||||
adapterType: telemetryAdapterType(agent),
|
||||
...(model ? { model } : {}),
|
||||
taskId: input.issueId,
|
||||
}));
|
||||
} catch (err) {
|
||||
logger.warn(
|
||||
{ err, issueId: input.issueId },
|
||||
"failed to emit agent.task_completed telemetry",
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -57,6 +57,12 @@ function agentTaskRunCalls(fromIndex: number) {
|
||||
.filter((call) => call[0] === "agent.task_run");
|
||||
}
|
||||
|
||||
function agentTaskCompletedCalls(fromIndex: number) {
|
||||
return mockTelemetryClient.track.mock.calls
|
||||
.slice(fromIndex)
|
||||
.filter((call) => call[0] === "agent.task_completed");
|
||||
}
|
||||
|
||||
function captureRunFailureCallsFrom(fromIndex: number) {
|
||||
return mockCaptureRunFailure.mock.calls.slice(fromIndex);
|
||||
}
|
||||
@@ -262,6 +268,46 @@ describeEmbeddedPostgres("native run finalizer / status decision committer — a
|
||||
expect(captureRunFailureCallsFrom(captureCallsBefore)).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("emits exactly one agent.task_completed event when finalizeNativeRun closes a task, and none on replay", async () => {
|
||||
const fixture = await seedNativeRun();
|
||||
await db.update(completionContracts).set({
|
||||
risk: "low",
|
||||
completionAuthority: "agent_claim_policy",
|
||||
contractJson: {
|
||||
revision: CONTROL_PLANE_CONFORMANCE_RESULT.completionClaim.contractRevision,
|
||||
objective: "Emit task completion telemetry",
|
||||
criteria: [{ id: "objective", requirement: "Complete the task" }],
|
||||
},
|
||||
}).where(eq(completionContracts.id, fixture.contractId));
|
||||
await driveToCompleteResult(fixture);
|
||||
|
||||
const callsBefore = mockTelemetryClient.track.mock.calls.length;
|
||||
await finalizeNativeRun({
|
||||
db,
|
||||
runId: fixture.runId,
|
||||
workspaceFinalizeStatus: "succeeded",
|
||||
projectRunStatus: true,
|
||||
});
|
||||
|
||||
const [closedIssue] = await db.select().from(issues).where(eq(issues.id, fixture.issueId));
|
||||
expect(closedIssue?.status).toBe("done");
|
||||
await vi.waitFor(() => expect(agentTaskCompletedCalls(callsBefore)).toHaveLength(1));
|
||||
expect(agentTaskCompletedCalls(callsBefore)[0]?.[1]).toMatchObject({
|
||||
agent_id: agentId,
|
||||
adapter_type: "codex_local",
|
||||
task_id: `hashed:${fixture.issueId}`,
|
||||
});
|
||||
|
||||
await finalizeNativeRun({
|
||||
db,
|
||||
runId: fixture.runId,
|
||||
workspaceFinalizeStatus: "succeeded",
|
||||
projectRunStatus: true,
|
||||
});
|
||||
await reconcileNativeFinalizations(db, [fixture.runId]);
|
||||
expect(agentTaskCompletedCalls(callsBefore)).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("emits zero events when a repeat finalize call preserves the succeeded terminal state", async () => {
|
||||
const fixture = await seedNativeRun();
|
||||
await driveToCompleteResult(fixture);
|
||||
|
||||
@@ -0,0 +1,266 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
agents,
|
||||
companies,
|
||||
completionContracts,
|
||||
createDb,
|
||||
heartbeatRuns,
|
||||
issues,
|
||||
nativeRunFinalizations,
|
||||
nativeRunResults,
|
||||
workAssessments,
|
||||
} from "@paperclipai/db";
|
||||
import {
|
||||
getEmbeddedPostgresTestSupport,
|
||||
startEmbeddedPostgresTestDatabase,
|
||||
} from "../../__tests__/helpers/embedded-postgres.js";
|
||||
import { scopedTelemetryCompanyId, scopedTelemetryPerson } from "../../telemetry-company-scope.js";
|
||||
import type { NativeStatusDecision } from "./status-arbiter.js";
|
||||
import { NATIVE_STATUS_ARBITER_POLICY_VERSION } from "./status-arbiter.js";
|
||||
|
||||
const mockTelemetryClient = vi.hoisted(() => ({
|
||||
track: vi.fn(),
|
||||
hashPrivateRef: vi.fn((value: string) => `hashed:${value}`),
|
||||
}));
|
||||
const mockTrackAgentTaskCompleted = vi.hoisted(() => vi.fn());
|
||||
|
||||
vi.mock("../../telemetry.js", () => ({
|
||||
getTelemetryClient: () => mockTelemetryClient,
|
||||
}));
|
||||
|
||||
vi.mock("@paperclipai/shared/telemetry", async () => {
|
||||
const actual = await vi.importActual<typeof import("@paperclipai/shared/telemetry")>(
|
||||
"@paperclipai/shared/telemetry",
|
||||
);
|
||||
return { ...actual, trackAgentTaskCompleted: mockTrackAgentTaskCompleted };
|
||||
});
|
||||
|
||||
const mockEmitAgentTaskCompleted = vi.hoisted(() => vi.fn());
|
||||
|
||||
vi.mock("../agent-task-run-telemetry.js", async () => {
|
||||
const actual = await vi.importActual<typeof import("../agent-task-run-telemetry.js")>(
|
||||
"../agent-task-run-telemetry.js",
|
||||
);
|
||||
mockEmitAgentTaskCompleted.mockImplementation(actual.emitAgentTaskCompleted);
|
||||
return { ...actual, emitAgentTaskCompleted: mockEmitAgentTaskCompleted };
|
||||
});
|
||||
|
||||
import { emitAgentTaskCompleted } from "../agent-task-run-telemetry.js";
|
||||
import { commitNativeStatusDecision } from "./status-decision-committer.js";
|
||||
|
||||
const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
|
||||
const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
|
||||
|
||||
if (!embeddedPostgresSupport.supported) {
|
||||
console.warn(
|
||||
`Skipping embedded Postgres native task completion telemetry tests on this host: ${
|
||||
embeddedPostgresSupport.reason ?? "unsupported environment"
|
||||
}`,
|
||||
);
|
||||
}
|
||||
|
||||
const doneDecision: NativeStatusDecision = {
|
||||
policyVersion: NATIVE_STATUS_ARBITER_POLICY_VERSION,
|
||||
statusAction: "done",
|
||||
toStatus: "done",
|
||||
reasonCode: "completion_contract_satisfied",
|
||||
unblockDescriptor: null,
|
||||
effects: [{ kind: "release_checkout" }],
|
||||
};
|
||||
|
||||
describeEmbeddedPostgres("native task completion telemetry", () => {
|
||||
let db!: ReturnType<typeof createDb>;
|
||||
let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
|
||||
const companyId = randomUUID();
|
||||
const agentId = randomUUID();
|
||||
|
||||
beforeAll(async () => {
|
||||
tempDb = await startEmbeddedPostgresTestDatabase("paperclip-native-task-completed-telemetry-");
|
||||
db = createDb(tempDb.connectionString);
|
||||
await db.insert(companies).values({ id: companyId, name: "Telemetry fixture", issuePrefix: "TLM" });
|
||||
await db.insert(agents).values({
|
||||
id: agentId,
|
||||
companyId,
|
||||
name: "Native worker",
|
||||
role: "engineer",
|
||||
adapterType: "paperclip_runner",
|
||||
adapterConfig: { provider: "acpx", acpxAgent: "claude", model: "fixture-model" },
|
||||
status: "running",
|
||||
});
|
||||
}, 30_000);
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
async function waitForTaskCompletedSend(times: number) {
|
||||
await vi.waitFor(() => expect(mockTrackAgentTaskCompleted).toHaveBeenCalledTimes(times));
|
||||
}
|
||||
|
||||
afterAll(async () => {
|
||||
await db?.$client.end({ timeout: 1 });
|
||||
await tempDb?.cleanup();
|
||||
});
|
||||
|
||||
async function seedArbitratedRun(status: "in_progress" | "done" = "in_progress") {
|
||||
const issueId = randomUUID();
|
||||
const contractId = randomUUID();
|
||||
const runId = randomUUID();
|
||||
const resultId = randomUUID();
|
||||
const assessmentId = randomUUID();
|
||||
const contractSha256 = `contract-${contractId}`;
|
||||
await db.insert(issues).values({
|
||||
id: issueId,
|
||||
companyId,
|
||||
title: "Native completion telemetry fixture",
|
||||
status,
|
||||
assigneeAgentId: agentId,
|
||||
createdByUserId: "user-creator",
|
||||
responsibleUserId: "user-assigner",
|
||||
workMode: "standard",
|
||||
});
|
||||
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: [{ id: "objective", requirement: "Complete the task" }],
|
||||
},
|
||||
canonicalSha256: contractSha256,
|
||||
createdByActorType: "system",
|
||||
createdByActorId: "test",
|
||||
});
|
||||
await db.insert(heartbeatRuns).values({
|
||||
id: runId,
|
||||
companyId,
|
||||
agentId,
|
||||
status: "running",
|
||||
runtimeMode: "native",
|
||||
nativeIssueId: issueId,
|
||||
nativeSessionId: runId,
|
||||
runnerInstanceId: randomUUID(),
|
||||
completionContractId: contractId,
|
||||
completionContractSha256: contractSha256,
|
||||
responsibleUserId: "user-owner",
|
||||
contextSnapshot: { issueId },
|
||||
});
|
||||
await db.insert(nativeRunResults).values({
|
||||
id: resultId,
|
||||
companyId,
|
||||
issueId,
|
||||
runId,
|
||||
completionContractId: contractId,
|
||||
serverFingerprint: `fp-${resultId}`,
|
||||
schemaStatus: "accepted",
|
||||
resultJson: {},
|
||||
canonicalSha256: `sha-${resultId}`,
|
||||
});
|
||||
await db.insert(workAssessments).values({
|
||||
id: assessmentId,
|
||||
companyId,
|
||||
issueId,
|
||||
runId,
|
||||
contractId,
|
||||
resultId,
|
||||
triggerKind: "native_result",
|
||||
triggerActorCompanyId: companyId,
|
||||
priorIssueStatus: status,
|
||||
priorStatusVersion: 0,
|
||||
policyVersion: "task-completed-telemetry-v1",
|
||||
assessmentJson: {},
|
||||
inputDigest: `digest-${assessmentId}`,
|
||||
});
|
||||
await db.insert(nativeRunFinalizations).values({
|
||||
runId,
|
||||
companyId,
|
||||
issueId,
|
||||
phase: "arbitrating",
|
||||
resultId,
|
||||
});
|
||||
return { issueId, runId, assessmentId, status };
|
||||
}
|
||||
|
||||
function commitDone(fixture: Awaited<ReturnType<typeof seedArbitratedRun>>) {
|
||||
return commitNativeStatusDecision({
|
||||
db,
|
||||
companyId,
|
||||
issueId: fixture.issueId,
|
||||
runId: fixture.runId,
|
||||
assessmentId: fixture.assessmentId,
|
||||
priorStatus: fixture.status,
|
||||
priorStatusVersion: 0,
|
||||
priorDecisionId: null,
|
||||
decision: doneDecision,
|
||||
});
|
||||
}
|
||||
|
||||
it("sends agent.task_completed once with company, person, and harness adapter_type when the runner closes a task", async () => {
|
||||
const fixture = await seedArbitratedRun();
|
||||
const observedScopes: Array<{ companyId: string | undefined; person: unknown }> = [];
|
||||
mockTrackAgentTaskCompleted.mockImplementation(() => {
|
||||
observedScopes.push({
|
||||
companyId: scopedTelemetryCompanyId(),
|
||||
person: scopedTelemetryPerson(),
|
||||
});
|
||||
});
|
||||
|
||||
const committed = await commitDone(fixture);
|
||||
expect(committed.issue.status).toBe("done");
|
||||
await waitForTaskCompletedSend(1);
|
||||
expect(mockTrackAgentTaskCompleted).toHaveBeenCalledWith(mockTelemetryClient, {
|
||||
agentRole: "engineer",
|
||||
agentId,
|
||||
adapterType: "claude_local",
|
||||
model: "fixture-model",
|
||||
taskId: fixture.issueId,
|
||||
});
|
||||
expect(observedScopes).toEqual([
|
||||
{
|
||||
companyId,
|
||||
person: { userId: "user-creator", attributedVia: "task_creator" },
|
||||
},
|
||||
]);
|
||||
|
||||
const replayed = await commitDone(fixture);
|
||||
expect(replayed.replayed).toBe(true);
|
||||
expect(mockEmitAgentTaskCompleted).toHaveBeenCalledTimes(1);
|
||||
expect(mockTrackAgentTaskCompleted).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("returns the committed decision while the task-completed send is still pending", async () => {
|
||||
const fixture = await seedArbitratedRun();
|
||||
vi.mocked(emitAgentTaskCompleted).mockImplementationOnce(() => new Promise<void>(() => undefined));
|
||||
|
||||
const committed = await commitDone(fixture);
|
||||
expect(committed.issue.status).toBe("done");
|
||||
expect(mockEmitAgentTaskCompleted).toHaveBeenCalledWith(expect.anything(), {
|
||||
companyId,
|
||||
agentId,
|
||||
issueId: fixture.issueId,
|
||||
taskCreatedByUserId: "user-creator",
|
||||
taskAssignedByUserId: "user-assigner",
|
||||
runOwnerUserId: "user-owner",
|
||||
});
|
||||
});
|
||||
|
||||
it("does not send agent.task_completed again for a task the issue route already closed", async () => {
|
||||
const fixture = await seedArbitratedRun("done");
|
||||
|
||||
const committed = await commitDone(fixture);
|
||||
expect(committed.replayed).toBe(false);
|
||||
expect(committed.issue.status).toBe("done");
|
||||
expect((await db.select().from(issues).where(eq(issues.id, fixture.issueId)))[0]?.status).toBe("done");
|
||||
expect(mockEmitAgentTaskCompleted).not.toHaveBeenCalled();
|
||||
expect(mockTrackAgentTaskCompleted).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -90,7 +90,7 @@ import {
|
||||
publishActivity,
|
||||
type ActivityPublication,
|
||||
} from "../activity-log.js";
|
||||
import { emitAgentTaskRun } from "../agent-task-run-telemetry.js";
|
||||
import { emitAgentTaskCompleted, emitAgentTaskRun } from "../agent-task-run-telemetry.js";
|
||||
import { materializeNativeAgentBlockerContinuation, materializeNativeEnvironmentBlockerRetry, materializeNativeProviderCapacityRetry,
|
||||
materializeNativeToolReceiptLimitContinuation } from "./native-provider-capacity-retry.js";
|
||||
import { NATIVE_ENVIRONMENT_BLOCKER_CODE, NATIVE_ENVIRONMENT_BLOCKER_EXHAUSTED_CODE } from "./native-environment-blocker.js";
|
||||
@@ -1743,6 +1743,7 @@ export async function commitNativeStatusDecision(input: {
|
||||
}
|
||||
const publications: ActivityPublication[] = [];
|
||||
const terminalRunsToEmit: (typeof heartbeatRuns.$inferSelect)[] = [];
|
||||
let completedTask: Parameters<typeof emitAgentTaskCompleted>[1] | null = null;
|
||||
const committed = await input.db.transaction(async (tx) => {
|
||||
const retiredReview = input.requireReassessmentSource?.retiredAutomaticReview;
|
||||
if (retiredReview && !await lockCurrentNativeCompletionContract(tx as unknown as Db, {
|
||||
@@ -1781,6 +1782,7 @@ export async function commitNativeStatusDecision(input: {
|
||||
.limit(1)
|
||||
.then((rows) => rows[0] ?? null);
|
||||
if (!issue) throw new NativeStatusRaceError();
|
||||
completedTask = null;
|
||||
const [originRun] = await tx.select({
|
||||
agentId: heartbeatRuns.agentId,
|
||||
responsibleUserId: heartbeatRuns.responsibleUserId,
|
||||
@@ -2501,6 +2503,16 @@ export async function commitNativeStatusDecision(input: {
|
||||
if (updated.originKind === "routine_execution") {
|
||||
await syncRoutineRunStatusForIssue(tx as unknown as Db, input.issueId);
|
||||
}
|
||||
if (issue.status !== "done" && updated.status === "done" && originRun?.agentId) {
|
||||
completedTask = {
|
||||
companyId: input.companyId,
|
||||
agentId: originRun.agentId,
|
||||
issueId: input.issueId,
|
||||
taskCreatedByUserId: updated.createdByUserId,
|
||||
taskAssignedByUserId: updated.responsibleUserId,
|
||||
runOwnerUserId: originRun.responsibleUserId,
|
||||
};
|
||||
}
|
||||
// Native task completion bypasses the REST issue route. Commit the Studio
|
||||
// output with the authoritative task status so restart cannot lose it.
|
||||
// The durable test row, not a mutable task mode, identifies the obligation.
|
||||
@@ -2780,5 +2792,7 @@ export async function commitNativeStatusDecision(input: {
|
||||
for (const publication of publications) publishActivity(publication);
|
||||
for (const terminalRun of terminalRunsToEmit)
|
||||
await emitAgentTaskRun(input.db, terminalRun);
|
||||
if (completedTask && !committed.replayed)
|
||||
void emitAgentTaskCompleted(input.db, completedTask);
|
||||
return committed;
|
||||
}
|
||||
@@ -380,7 +380,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": "0774d0bfb61e66b65219d7950b634b06e40e5390",
|
||||
"packages/shared/src/telemetry/README.md": "7f4f1cd060fadc1660f057590ea66a64670c89bf",
|
||||
"packages/shared/src/telemetry/client-types.test.ts": "3b630edda4972b929ba4decd7457f226eb9cfc5b",
|
||||
"packages/shared/src/telemetry/client.test.ts": "5a95f2305a393c5b2e7750b10e0ed65da0f30cf8",
|
||||
"packages/shared/src/telemetry/client.ts": "d6534ce8aaa6f69fb2dd03e12487db024e250a96",
|
||||
|
||||
Reference in new issue
Block a user