fix(native): report why an unclassified Codex turn failed (#16354)

<!-- Write all pull request text in Simplified Technical English
(ASD-STE100): short sentences, one instruction per sentence, simple
approved vocabulary, and the active voice. -->

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Native runs use the Paperclip runner to drive a provider session,
for example the Codex app server
> - When a Codex turn fails, two classifiers look for known failures: a
model rejection and a server capacity failure
> - When no classifier matches, the run fails with the generic message
`Native session failed` and the error code `adapter_failed`
> - The run failure report to Sentry then has no data about the cause,
because the server drops the Codex `codexErrorInfo` value
> - This pull request records a closed-vocabulary diagnostic for that
failed turn and sends it to the Sentry `provider_failure` context
> - The benefit is that operators can see which Codex failure kind
causes these generic failures, and then write a targeted fix

## Linked Issues or Issue Description

**What happened?**
Hosted staging reports many run failures with the title `Error: Native
session failed`. The events have `agent_adapter=paperclip_runner`,
`error_code=adapter_failed`, `driverKind=codex_app_server`, and
`exitCode=1`. The events do not show why the Codex turn failed.

**Expected behavior**
A run failure report for a failed Codex turn shows the failure kind, so
that an operator can find the cause. The report must not contain
provider response text, prompts, or model names.

**Steps to reproduce**
1. Start a native Codex run.
2. Make the Codex app server end the turn with `status: "failed"` and an
error that is not a model rejection or `serverOverloaded`. For example,
use `codexErrorInfo: "contextWindowExceeded"`.
3. Look at the Sentry event for the run failure. Before this change, the
`provider_failure` context is empty.

**Agent adapter(s) involved**
Codex (native runner, `codex_app_server` driver).

## What Changed

- `native-provider-failure.ts`: The provider failure observation now
records a diagnostic for each failed Codex turn. The diagnostic has only
closed values: `provider: "codex"`, `category: "turn_failed"`, a known
`CodexErrorInfo` kind (or `unrecognized` / `absent`), an HTTP status
from 100 to 599 for the HTTP variants, and a runner failure code from an
explicit allowlist of the codes the runner itself writes on a failed
Codex turn (any other string becomes `unrecognized`, because a provider
error object can carry its own `code`). It never copies the provider
message.
- New `unclassifiedTurnFailure()` gives this diagnostic only for a
failed terminal turn that `forTerminal()` does not classify.
`forTerminal()`, error codes, error messages, retries, and finalizer
decisions do not change.
- New `readNativeTurnFailureDiagnostic()` rebuilds a persisted value
from the closed vocabulary and rejects all other values.
- `native-session-executor.ts`: The adapter result keeps the generic
message. It adds `resultJson.nativeTurnFailure` when the turn failure is
unclassified.
- `run-failure-diagnostics.ts`: The run failure report copies the
validated diagnostic into the `provider` context. Sentry sends this as
`provider_failure`.
- Tests: unit tests for the vocabulary, HTTP status bounds, unknown
kinds, runner codes, and privacy; a diagnostics test; and an update to
the end-to-end executor test for the `unknown-error` scenario.

## Verification

- `pnpm exec vitest run
src/services/native-runtime/native-provider-failure
src/services/__tests__/run-failure-diagnostics.test.ts
src/services/__tests__/run-failure-report*.test.ts
src/__tests__/sentry*.test.ts` (in `server/`): 6 files, 432 passed, 5
skipped.
- `pnpm exec vitest run
src/services/native-runtime/native-session-executor.test.ts` (in
`server/`): 698 passed.
- I could not run the full `tsc --noEmit` in my sandbox: the memory
limit stopped the process, and the runner vendor build needs `cargo`. CI
runs the full typecheck.
- To check by hand: make a Codex turn fail with an unclassified error.
Then make sure that the Sentry event `provider_failure` context shows
`category: turn_failed` and the `codexErrorInfo` kind, and no provider
text.

## Risks

- Low risk. The change adds diagnostic data only. Run status, error
code, error message, retry, and finalizer logic do not change.
- Privacy: the diagnostic uses an allowlist of Codex enum names, a
bounded integer, and an allowlist of runner-issued failure codes. Tests
make sure that provider text does not get through.
- If Codex adds a new `CodexErrorInfo` kind, the diagnostic shows
`unrecognized` until the allowlist gets the new kind.
- This change does not fix the root cause. It gives the data that is
necessary to find the cause.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude
Code with tool use (shell, file edit, test runs).

## 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
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

Related: #15347 (capacity classifier), #15304 (model rejection
diagnostics).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: devinfoley <139239+devinfoley@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
authored and GitHub committed 2026-10-14 20:14:10 -07:00
1 parent 3a440d28c4
commit 275189d8d6
8 files changed
+205 -9

No files matched your search

@@ -190,6 +190,19 @@ describe("run failure diagnostics", () => {
}
});
it("exports only the closed vocabulary of an unclassified native turn failure", () => {
const diagnostic = { provider: "codex", category: "turn_failed", codexErrorInfo: "responseStreamDisconnected", httpStatus: 502 };
const result = sanitizeRunFailureDiagnostics(collectRunFailureDiagnostics(run({ resultJson: {
nativeTurnFailure: { ...diagnostic, runnerFailureCode: "private_prompt_slug", message: "private-provider-response" },
} }), {}));
expect(result.provider).toEqual({ ...diagnostic, runnerFailureCode: "unrecognized" });
expect(JSON.stringify(result)).not.toContain("rivate");
for (const value of [null, [], { ...diagnostic, codexErrorInfo: "private-kind" },
Object.defineProperty({}, "provider", { get() { throw new Error("private"); } })]) {
expect(collectRunFailureDiagnostics(run({ resultJson: { nativeTurnFailure: value } }), {}).provider).toEqual({});
}
});
it("exports only the saved remote recovery stage and reason", () => {
const result = sanitizeRunFailureDiagnostics(collectRunFailureDiagnostics(run({
errorCode: "runner_remote_process_identity_unavailable", resultJson: {
@@ -9,8 +9,7 @@ function record(value: unknown): Record<string, unknown> {
? value as Record<string, unknown> : {};
}
/** Re-derive authority from immutable run-bound evidence, including after restart. */
export async function readPersistedNativeProviderFailure(
async function observePersistedNativeTurnFailure(
db: Db,
run: typeof heartbeatRuns.$inferSelect,
turnId: string | null,
@@ -41,7 +40,30 @@ export async function readPersistedNativeProviderFailure(
row.sourcePayloadSha256 !== nativeSha256(parsed.event)) return null;
const observed = createNativeProviderFailureObservation(execution.provider);
observed.observe(parsed.event);
return observed.forTerminal(turnId, terminal);
return observed;
}
/** Re-derive authority from immutable run-bound evidence, including after restart. */
export async function readPersistedNativeProviderFailure(
...args: Parameters<typeof observePersistedNativeTurnFailure>
) {
const [, , turnId, terminal] = args;
return (await observePersistedNativeTurnFailure(...args))?.forTerminal(turnId, terminal) ?? null;
}
/**
* Recovery can finalize before heartbeat saves the adapter result. Rebuild the
* classified failure and the diagnostics-only turn failure from one event.
*/
export async function readPersistedNativeFailureEvidence(
...args: Parameters<typeof observePersistedNativeTurnFailure>
) {
const [, , turnId, terminal] = args;
const observed = await observePersistedNativeTurnFailure(...args);
return {
providerFailure: observed?.forTerminal(turnId, terminal) ?? null,
turnFailure: observed?.unclassifiedTurnFailure(turnId, terminal) ?? null,
};
}
export async function readPersistedNativeModelRejection(
@@ -19,7 +19,7 @@ import { prepareNativeHeartbeatRun } from "./prepare-native-run.js";
import { NATIVE_MODEL_REJECTION_DIAGNOSTIC, NATIVE_MODEL_REJECTION_MESSAGE } from "./native-provider-failure.js";
import { collectRunFailureDiagnostics } from "../run-failure-diagnostics.js";
import { finalizeNativeRun } from "./native-run-finalizer.js";
import { readPersistedNativeModelRejection } from "./native-provider-failure-evidence.js";
import { readPersistedNativeFailureEvidence, readPersistedNativeModelRejection } from "./native-provider-failure-evidence.js";
import { heartbeatService } from "../heartbeat.js";
import { getNativeReviewAssignment, readNativeReviewAssignmentContext } from "./native-review-participant.js";
import { claimQueuedNativeReviewRun } from "./native-review-dispatch.js";
@@ -136,6 +136,9 @@ describe("native completed failure diagnostics", () => {
expect(adapter.errorCode).toBe(classified ? "native_provider_model_rejected" : undefined);
expect(adapter.errorMessage).toBe(classified ? NATIVE_MODEL_REJECTION_MESSAGE : scenario === "succeeded" ? null : `Native session ${terminal.runTerminalState}`);
expect(adapter.resultJson?.nativeProviderFailure).toEqual(classified ? NATIVE_MODEL_REJECTION_DIAGNOSTIC : undefined);
// Only a committed, unclassified failure of the terminal turn explains the generic message.
const turnFailure = scenario === "unknown-error" ? { provider: "codex", category: "turn_failed", codexErrorInfo: "other" } : undefined;
expect(adapter.resultJson?.nativeTurnFailure).toEqual(turnFailure);
expect(adapter.nativeFinalization).toMatchObject({ result, terminal, turnId, workspaceFinalizeStatus: "pending" });
expect(provider.execute).toHaveBeenCalledTimes(1);
expect(execution.provider).toEqual({ kind: "codex", model });
@@ -145,7 +148,7 @@ describe("native completed failure diagnostics", () => {
expect(await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, issueId))).toHaveLength(0);
expect(await db.select().from(heartbeatRunEvents).where(eq(heartbeatRunEvents.runId, runId))).toHaveLength(scenario.startsWith("untrusted-") ? 0 : 1);
const diagnostics = collectRunFailureDiagnostics({ ...run, resultJson: adapter.resultJson ?? null }, {});
expect(diagnostics.provider).toEqual(classified ? NATIVE_MODEL_REJECTION_DIAGNOSTIC : {});
expect(diagnostics.provider).toEqual(classified ? NATIVE_MODEL_REJECTION_DIAGNOSTIC : turnFailure ?? {});
expect(JSON.stringify(diagnostics)).not.toContain(model);
expect(JSON.stringify(diagnostics)).not.toContain("Private");
const [persistedRun] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));
@@ -153,6 +156,7 @@ describe("native completed failure diagnostics", () => {
expect(await readPersistedNativeModelRejection(db, persistedRun, turnId, terminal)).toEqual(classified ? {
errorCode: "native_provider_model_rejected", errorMessage: NATIVE_MODEL_REJECTION_MESSAGE, diagnostic: NATIVE_MODEL_REJECTION_DIAGNOSTIC,
} : null);
expect((await readPersistedNativeFailureEvidence(db, persistedRun, turnId, terminal)).turnFailure).toEqual(turnFailure ?? null);
if (classified) {
if (scenario === "committed") {
// Neither saved display diagnostics nor a different execution binding
@@ -197,6 +201,7 @@ describe("native completed failure diagnostics", () => {
expect(await db.select().from(nativeRunResults).where(eq(nativeRunResults.runId, runId))).toEqual(acceptedBefore);
const [finalRun] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));
expect(finalRun).toMatchObject({ status: "failed", errorCode: "native_provider_model_rejected", error: NATIVE_MODEL_REJECTION_MESSAGE });
expect(finalRun.resultJson?.nativeTurnFailure).toBeUndefined();
const [finalIssue] = await db.select().from(issues).where(eq(issues.id, issueId));
expect(finalIssue.status).toBe(scenario.endsWith("-review") ? "in_review" : ownerChanged ? "in_progress" : "blocked");
const decisions = await db.select().from(statusDecisions).where(eq(statusDecisions.runId, runId));
@@ -264,6 +269,10 @@ describe("native completed failure diagnostics", () => {
await finalizeNativeRun({ db, runId, workspaceFinalizeStatus: "succeeded" });
const [decision] = await db.select().from(statusDecisions).where(eq(statusDecisions.runId, runId));
expect(decision.reasonCode).toBe("run_failed_partial_evidence_preserved");
// Recovery finalized before heartbeat saved the adapter result, so the
// turn failure must come from the persisted runner event.
const [finalRun] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));
expect(finalRun.resultJson?.nativeTurnFailure).toEqual(turnFailure);
const wakes = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, companyId));
expect(wakes.filter(wake => wake.payload?.issueId === issueId)).toHaveLength(1);
}
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import type { PrpEvent, PrpTerminalState } from "../../vendor/paperclip-runner/index.js";
import { createNativeProviderFailureObservation, NATIVE_MODEL_REJECTION_DIAGNOSTIC, NATIVE_MODEL_REJECTION_MESSAGE, NATIVE_PROVIDER_OVERLOADED_MESSAGE } from "./native-provider-failure.js";
import { createNativeProviderFailureObservation, NATIVE_MODEL_REJECTION_DIAGNOSTIC, NATIVE_MODEL_REJECTION_MESSAGE, NATIVE_PROVIDER_OVERLOADED_MESSAGE, readNativeTurnFailureDiagnostic } from "./native-provider-failure.js";
const model = "test-model";
const response = {
@@ -76,6 +76,63 @@ describe("native provider failure observation", () => {
expect(observed.forTerminal("turn", terminal)).toBeNull();
});
it.each([
[{ codexErrorInfo: "contextWindowExceeded", message: "Private provider text" }, { codexErrorInfo: "contextWindowExceeded" }],
[{ codexErrorInfo: { responseStreamDisconnected: { httpStatusCode: 502 } }, message: "Private" }, { codexErrorInfo: "responseStreamDisconnected", httpStatus: 502 }],
[{ codexErrorInfo: { httpConnectionFailed: { httpStatusCode: "502" } } }, { codexErrorInfo: "httpConnectionFailed" }],
[{ codexErrorInfo: { httpConnectionFailed: { httpStatusCode: 9_999 } } }, { codexErrorInfo: "httpConnectionFailed" }],
[{ codexErrorInfo: "privateUnknownKind" }, { codexErrorInfo: "unrecognized" }],
[{ codexErrorInfo: { privateUnknownKind: {} } }, { codexErrorInfo: "unrecognized" }],
[{ codexErrorInfo: { other: {}, badRequest: {} } }, { codexErrorInfo: "unrecognized" }],
[{ code: "provider_event_type_invalid", message: "Unknown canonical provider event type.", recoverable: false }, { codexErrorInfo: "absent", runnerFailureCode: "provider_event_type_invalid" }],
[{ code: "Private Code With Spaces", message: "Private" }, { codexErrorInfo: "absent", runnerFailureCode: "unrecognized" }],
[{ code: "private_prompt_slug", message: "Private" }, { codexErrorInfo: "absent", runnerFailureCode: "unrecognized" }],
[{ code: 42, message: "Private" }, { codexErrorInfo: "absent" }],
[{ message: NATIVE_PROVIDER_OVERLOADED_MESSAGE }, { codexErrorInfo: "absent" }],
])("describes an unclassified failed turn with closed vocabulary only %#", (error, expected) => {
const observed = observation();
observed.observe({ ...event, payload: { status: "failed", error } });
expect(observed.forTerminal("turn", terminal)).toBeNull();
const diagnostic = observed.unclassifiedTurnFailure("turn", terminal);
expect(diagnostic).toEqual({ provider: "codex", category: "turn_failed", ...expected });
expect(JSON.stringify(diagnostic)).not.toMatch(/private/i);
expect(readNativeTurnFailureDiagnostic(diagnostic)).toEqual(diagnostic);
});
it("does not describe a classified, unfailed, or unrelated turn as unclassified", () => {
const rejected = observation();
rejected.observe(event);
expect(rejected.unclassifiedTurnFailure("turn", terminal)).toBeNull();
const overloaded = observation();
overloaded.observe({ ...event, payload: { status: "failed", error: { codexErrorInfo: "serverOverloaded" } } });
expect(overloaded.unclassifiedTurnFailure("turn", terminal)).toBeNull();
const other = observation();
other.observe({ ...event, payload: { status: "failed", error: { codexErrorInfo: "sandboxError" } } });
expect(other.unclassifiedTurnFailure("later-turn", terminal)).toBeNull();
expect(other.unclassifiedTurnFailure(null, terminal)).toBeNull();
expect(other.unclassifiedTurnFailure("turn", { ...terminal, runTerminalState: "succeeded" })).toBeNull();
expect(other.unclassifiedTurnFailure("turn", { ...terminal, turnTerminalState: "cancelled" })).toBeNull();
const claude = createNativeProviderFailureObservation({ kind: "claude", model });
claude.observe({ ...event, payload: { status: "failed", error: { codexErrorInfo: "sandboxError" } } });
expect(claude.unclassifiedTurnFailure("turn", terminal)).toBeNull();
});
it.each([
null, [], "turn_failed",
{ provider: "codex", category: "turn_failed", codexErrorInfo: "private-kind" },
{ provider: "claude", category: "turn_failed", codexErrorInfo: "other" },
{ provider: "codex", category: "server_overloaded", codexErrorInfo: "other" },
])("rejects a persisted turn-failure diagnostic outside the vocabulary %#", (value) => {
expect(readNativeTurnFailureDiagnostic(value)).toBeNull();
});
it("drops unbounded fields from a persisted turn-failure diagnostic", () => {
expect(readNativeTurnFailureDiagnostic({
provider: "codex", category: "turn_failed", codexErrorInfo: "badRequest", httpStatus: 1.5,
runnerFailureCode: "private_prompt_slug", message: "private provider response",
})).toEqual({ provider: "codex", category: "turn_failed", codexErrorInfo: "badRequest", runnerFailureCode: "unrecognized" });
});
it.each([{ kind: "claude", model }, { kind: "codex" }, { kind: "codex", model: "other" }])(
"does not apply a rejection to another selected provider/model (%j)", (provider) => {
const observed = createNativeProviderFailureObservation(provider);
@@ -35,16 +35,98 @@ export function readNativeModelRejectionDiagnostic(value: unknown) {
} catch { return null; }
}
/**
* Codex `CodexErrorInfo` variants. Unit variants arrive as strings; HTTP
* variants arrive as one-key objects that can carry `httpStatusCode`.
*/
const CODEX_ERROR_INFO_KINDS: ReadonlySet<string> = new Set([
"contextWindowExceeded", "usageLimitExceeded", "serverOverloaded", "httpConnectionFailed",
"responseStreamConnectionFailed", "internalServerError", "unauthorized", "badRequest",
"threadRollbackFailed", "sandboxError", "responseStreamDisconnected",
"responseTooManyFailedAttempts", "other",
]);
/**
* `error.code` values the runner itself writes on a failed Codex turn: the
* Codex driver's `failProtocol` callers and runnerd's Codex backend. A provider
* error object can also carry `code`, so any other value is `unrecognized`.
*/
const NATIVE_TURN_FAILURE_RUNNER_CODES: ReadonlySet<string> = new Set([
"thread_binding_mismatch", "turn_binding_mismatch", "turn_start_mismatch", "tool_binding_mismatch",
"runtime_request_binding_mismatch", "runtime_request_duplicate", "runtime_request_recovery_failed",
"notification_transport_failed", "provider_event_type_invalid", "invalid_semantic_result",
"conflicting_semantic_result", "conflicting_turn_terminal", "invalid_spawn_lineage",
"provider_descendant_capacity_exhausted", "provider_terminal_error_missing", "provider_turn_lost_on_restore",
]);
/**
* Closed vocabulary for a failed Codex turn that no classifier above claims.
* It explains generic `Native session failed` reports without provider text.
*/
export interface NativeTurnFailureDiagnostic {
provider: "codex";
category: "turn_failed";
/** A known `CodexErrorInfo` kind, `unrecognized`, or `absent`. */
codexErrorInfo: string;
httpStatus?: number;
/** A known runner-issued failure code, or `unrecognized` for any other code. */
runnerFailureCode?: string;
}
function httpStatusField(value: unknown) {
return typeof value === "number" && Number.isInteger(value) && value >= 100 && value <= 599
? { httpStatus: value } : {};
}
function runnerFailureCodeField(value: unknown) {
if (typeof value !== "string") return {};
return { runnerFailureCode: NATIVE_TURN_FAILURE_RUNNER_CODES.has(value) ? value : "unrecognized" };
}
function codexErrorInfoFields(value: unknown): Pick<NativeTurnFailureDiagnostic, "codexErrorInfo" | "httpStatus"> {
if (value === undefined || value === null) return { codexErrorInfo: "absent" };
if (typeof value === "string") return { codexErrorInfo: CODEX_ERROR_INFO_KINDS.has(value) ? value : "unrecognized" };
const entry = record(value);
const keys = Object.keys(entry);
if (keys.length !== 1 || !CODEX_ERROR_INFO_KINDS.has(keys[0]!)) return { codexErrorInfo: "unrecognized" };
return { codexErrorInfo: keys[0]!, ...httpStatusField(record(entry[keys[0]!]).httpStatusCode) };
}
/** Rebuild a persisted turn-failure diagnostic from its closed vocabulary only. */
export function readNativeTurnFailureDiagnostic(value: unknown): NativeTurnFailureDiagnostic | null {
try {
const entry = record(value);
const kind = entry.codexErrorInfo;
if (entry.provider !== "codex" || entry.category !== "turn_failed" || typeof kind !== "string" ||
(kind !== "absent" && kind !== "unrecognized" && !CODEX_ERROR_INFO_KINDS.has(kind))) return null;
return {
provider: "codex",
category: "turn_failed",
codexErrorInfo: kind,
...httpStatusField(entry.httpStatus),
...runnerFailureCodeField(entry.runnerFailureCode),
};
} catch { return null; }
}
/** Observe only events accepted by the bound control-plane persistence port. */
export function createNativeProviderFailureObservation(provider: { kind: string; model?: string | null }) {
let rejectedTurnId: string | null = null;
let overloadedTurnId: string | null = null;
const failedTurns = new Map<string, NativeTurnFailureDiagnostic>();
return {
observe(event: PrpEvent) {
if (provider.kind !== "codex" ||
event.sourceKind !== "runner" || event.eventType !== "turn.failed" || !event.turnId) return;
const payload = record(event.payload);
const failure = record(payload.error);
if (payload.status === "failed") {
failedTurns.set(event.turnId, {
provider: "codex",
category: "turn_failed",
...codexErrorInfoFields(failure.codexErrorInfo),
...runnerFailureCodeField(failure.code),
});
}
if (payload.status === "failed" && failure.codexErrorInfo === "serverOverloaded") {
overloadedTurnId = event.turnId;
return;
@@ -75,5 +157,12 @@ export function createNativeProviderFailureObservation(provider: { kind: string;
diagnostic: { ...NATIVE_MODEL_REJECTION_DIAGNOSTIC },
};
},
/** Diagnostics only: the failed turn that `forTerminal` did not classify. */
unclassifiedTurnFailure(turnId: string | null | undefined, terminal: PrpTerminalState) {
if (!turnId || terminal.turnTerminalState !== "failed" || terminal.runTerminalState !== "failed" ||
turnId === overloadedTurnId || turnId === rejectedTurnId) return null;
const diagnostic = failedTurns.get(turnId);
return diagnostic ? { ...diagnostic } : null;
},
};
}
@@ -4,7 +4,7 @@ import { activeIssueInteractionCondition } from "../issue-question-context.js";
import { hasPendingNativeChildCompletion } from "./native-child-completion-delivery.js";
import { settleExternalConversation } from "../slack-conversation-lifecycle.js";
import { executionFailureRetryCount } from "../execution-recovery-attempt.js";
import { readPersistedNativeProviderFailure } from "./native-provider-failure-evidence.js";
import { readPersistedNativeFailureEvidence } from "./native-provider-failure-evidence.js";
import { dismissAutomaticCompletionReviews } from "./automatic-completion-reviews.js";
import { getNativeReviewAssignment, readNativeReviewAssignmentContext } from "./native-review-participant.js";
import { conversationNativeDecision, isConversation } from "../agent-conversations.js";
@@ -1344,7 +1344,7 @@ export async function finalizeNativeRun(input: {
(!planWait || nativeSha256(planWait.result) !== nativeSha256(result))) {
throw new Error("native_plan_wait_authority_lost");
}
const providerFailure = await readPersistedNativeProviderFailure(
const { providerFailure, turnFailure } = await readPersistedNativeFailureEvidence(
input.db, run, resultRow.turnId, envelope.terminal as PrpTerminalState,
);
const ownsProviderFailureDecision =
@@ -1504,6 +1504,7 @@ export async function finalizeNativeRun(input: {
const clearExecutionFailure = input.projectRunStatus && finalizationPhase === "committed" && terminalState === "succeeded";
const finalizationMetadata = {
...(providerFailure ? { nativeProviderFailure: providerFailure.diagnostic } : {}),
...(turnFailure ? { nativeTurnFailure: turnFailure } : {}),
finalizationPhase,
...(finalizationPhase === "committed" ? { failureCode: null, originalFailureCode: null, nextAttemptAt: null } : {}),
assessmentId: assessmentRow.id,
@@ -9593,6 +9593,8 @@ async function executePaperclipNativeSessionWithinScope(
if (collectInstructions && !collectedByOwner) await timeController("instruction_collection", () => instructionCopy!.collectStopped());
}
const providerFailure = providerFailureObservation.forTerminal(native.turnId, native.terminal);
// Keep the generic failure behavior, but record why the turn failed.
const unclassifiedTurnFailure = providerFailureObservation.unclassifiedTurnFailure(native.turnId, native.terminal);
const adapterResult: AdapterExecutionResult = {
exitCode: native.terminal.runTerminalState === "succeeded" ? 0 : 1,
signal: null,
@@ -9607,6 +9609,7 @@ async function executePaperclipNativeSessionWithinScope(
nativeTerminal: native.terminal as unknown as Record<string, unknown>,
...(input.execution.schema === "paperclip.native-execution-input.v6" ? { providerAccounting: { usage: null, cost: null, externallyBilled: true }, externalStopConfirmed: false } : {}),
...(providerFailure ? { nativeProviderFailure: providerFailure.diagnostic } : {}),
...(unclassifiedTurnFailure ? { nativeTurnFailure: unclassifiedTurnFailure } : {}),
...(native.goalRolloverRequired ? { goalRolloverRequired: true } : {}),
planSynchronizations,
},
@@ -9,7 +9,7 @@ import { sanitizeWorkspaceRestoreDiagnostic } from "@paperclipai/adapter-utils/w
import { ACP_TOOL_KINDS } from "@paperclipai/adapter-utils/acpx-engine/constants";
import { redactCurrentUserText } from "../log-redaction.js";
import { redactSensitiveText, REDACTED_EVENT_VALUE } from "../redaction.js";
import { readNativeModelRejectionDiagnostic } from "./native-runtime/native-provider-failure.js";
import { readNativeModelRejectionDiagnostic, readNativeTurnFailureDiagnostic } from "./native-runtime/native-provider-failure.js";
import { readRemoteRunnerRecoveryDiagnostic } from "./native-runtime/remote-runner-recovery-diagnostics.js";
import { MANAGED_GIT_WORKTREE_REASON_CODES, PERSISTED_WORKSPACE_SOURCE_REASON_CODES, readManagedGitInspectionDiagnostic } from "./workspace-validation-diagnostics.js";
@@ -340,6 +340,8 @@ export function collectRunFailureDiagnostics(run: Run, options: RunFailureReport
const provider = scalars(read(result, "terminalSessionFailure"), ["category", "title", "details"]);
const nativeProviderFailure = readNativeModelRejectionDiagnostic(read(result, "nativeProviderFailure"));
if (nativeProviderFailure) Object.assign(provider, nativeProviderFailure);
const nativeTurnFailure = readNativeTurnFailureDiagnostic(read(result, "nativeTurnFailure"));
if (nativeTurnFailure) Object.assign(provider, nativeTurnFailure);
const truncatedFields: string[] = [];
const providerTruncation = read(read(result, "terminalSessionFailure"), "truncatedFields");
if (Array.isArray(providerTruncation)) {