fix(github): let a queued push start the next review turn instead of a blocker continuation (#22223)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - A GitHub review bot reviews each PR in a task. Each push sends a new
review request to that task as a chat message.
> - A push that arrives during a review waits as a deferred chat wake.
That wake starts a new turn. The turn binds its tools to the newest
pushed commit.
> - #21959 and #22140 continue a run that reports a blocker in a fresh
session. That continuation keeps the source binding of the blocked run.
It also holds the task, so the waiting push request does not run.
> - On staging, a push during a review made the publication fail with
"requested for an older pull request head". The agent reported a
blocker. Paperclip then continued twice with the old binding. Each
continuation finished the review and could not publish it.
> - A second failure mode: a complete re-review that listed only the
files changed since the prior review got a short rejection. The
rejection named no files, and a small model stopped instead of
correcting the submission.
> - This pull request lets a queued chat request take the next turn
instead of a blocker continuation. It also names the missing files in
the coverage rejection.
> - The benefit is that reviews publish for the newest push without a
person, and agents can correct incomplete coverage on the next call.

## Linked Issues or Issue Description

**What happened?**
On staging, automatic GitHub reviews stopped publishing. The bots posted
"Publication is currently blocked" and "Paperclip must authorize the
review for <newest commit>". The run history showed this sequence: a
review run started for the first commit. Two pushes arrived during the
run. Steering into the active run was rejected for both pushes, so they
waited as deferred chat wakes. The run reported a blocker. Paperclip
then started two `native_environment_blocker` continuations. Each
continuation had no message of its own, so its GitHub tools resolved to
the first commit's request and refused the current head. The waiting
push requests did not run until a later push.

**What did you expect?**
A push request that waits behind a run starts the next turn, bound to
that push. The agent then reviews and publishes for the current head.

**Steps to reproduce**
1. Start an automatic review on a PR.
2. Push a new commit while the review runs, so the review request waits
as a deferred chat wake.
3. Let the run report a blocker (for example after the stale-head
publication refusal).
4. See that a fresh-session retry starts with the old binding and the
push request stays deferred.

Refs #21959, #22140, #22066

## What Changed

- `status-arbiter.ts`: new rule before the blocker continuation lanes.
When a blocked run has a queued chat request for the same task and
agent, the decision is `preserve` with only `release_checkout` (reason
`native_blocker_superseded_by_queued_request`). The normal release drain
then starts the queued request. A pause hold or a board-owned blocker
keeps the existing behavior.
- `native-runtime/queued-chat-request.ts`: new `hasQueuedChatRequest`
query. It uses the same chat-wake test that keeps chat wakes out of
first turns (`chatConversationId` or `externalChatProvider`).
- `native-run-finalizer.ts`: supplies `hasQueuedChatRequest` to the
arbiter, only for a blocked report.
- `chat-github-review-policy.ts` / `chat-github-reviews.ts`:
`githubCompleteCoverageGap` replaces the inline check. The rejection now
names the missing files (up to 20), says that a complete review covers
all changed files, and gives the two corrections (add them to
`reviewedPaths`, or submit `complete: false` with `omittedPaths`).

## Verification

- Red/green: `cd server && npx vitest run
src/services/native-runtime/native-environment-blocker.integration.test.ts`.
The new case failed before the fix with reason
`native_environment_blocker` and one scheduled retry, as on staging.
After the fix it passes: no retry, the task stays `in_progress`, and the
chat wake stays deferred for the release drain.
- Red/green: `npx vitest run
src/services/native-runtime/status-arbiter.test.ts -t "queued chat
request"`.
- Red/green: `npx vitest run
src/services/chat-github-review-policy.test.ts -t
githubCompleteCoverageGap`.
- `native-agent-blocker.integration.test.ts` and the full arbiter and
review-policy suites pass.
- `cd server && npx tsc --noEmit -p .` passes.
- `pnpm verify` on the changed files (results in the CI checks below).

## Risks

- Low to medium. The new rule changes only blocked reports that would
otherwise auto-continue while a chat request waits behind the run.
Without a waiting chat request, the behavior does not change.
- The waiting request now starts the next turn instead of the
continuation. If the blocker is real, that turn can report it again, and
the existing lanes apply.
- The finalizer does one more indexed read, only for blocked reports.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code with tool use: code
search, editing, shell, test runs, and staging run inspection through
the browser.

## 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
- [ ] I will address all Greptile and reviewer comments before
requesting merge

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
DottaandClaude Opus 5.5 authored and GitHub committed 2026-11-18 15:00:57 -06:00
1 parent 911fe5bb9a
commit 7f9c115cc2
8 files changed
+220 -13

No files matched your search

@@ -8,6 +8,7 @@ import {
type GitHubIssueEventContext,
} from "@paperclipai/shared";
import {
githubCompleteCoverageGap,
githubManualMessagePrompt,
githubConfiguredInstructionSources,
GITHUB_CONFIGURED_SKILL_GUIDANCE,
@@ -465,3 +466,39 @@ describe("GitHub finding category contract", () => {
expect(validateGitHubReviewAssessment(assessment(), context.headSha, { ...policy, findingCategories: [] }).findings).toEqual([]);
});
});
describe("githubCompleteCoverageGap", () => {
const files = ["ui/src/lib/a.ts", "ui/src/lib/b.ts", "tests/c.spec.ts", "doc/d.md"];
const coverage = (reviewedPaths: string[], omittedPaths: string[] = []) => ({ reviewedPaths, omittedPaths, limitations: [] });
it("accepts a complete assessment that reviewed every allowed changed file", () => {
expect(githubCompleteCoverageGap(files, coverage([...files].reverse()))).toBeNull();
});
it("names the changed files a complete assessment left out and how to correct the submission", () => {
// A re-review often lists only the files changed since the prior assessment.
const message = githubCompleteCoverageGap(files, coverage(["ui/src/lib/a.ts"]));
expect(message).toContain("A complete assessment must cover every non-excluded changed file");
expect(message).toContain("3 of 4");
for (const path of ["ui/src/lib/b.ts", "tests/c.spec.ts", "doc/d.md"]) expect(message).toContain(path);
expect(message).not.toContain("ui/src/lib/a.ts,");
expect(message).toContain("reviewedPaths");
expect(message).toContain("complete: false");
expect(message).toContain("omittedPaths");
});
it("names changed files that a complete assessment also lists as omitted", () => {
const message = githubCompleteCoverageGap(files, coverage(files, ["doc/d.md"]));
expect(message).toContain("doc/d.md");
expect(message).toContain("omittedPaths");
});
it("bounds a long list of missing files", () => {
const many = Array.from({ length: 60 }, (_, index) => `src/file-${index}.ts`);
const message = githubCompleteCoverageGap(many, coverage([]))!;
expect(message).toContain("60 of 60");
expect(message).toContain("src/file-19.ts");
expect(message).not.toContain("src/file-20.ts");
expect(message).toContain("40 more");
});
});
@@ -231,6 +231,38 @@ export function validateGitHubReviewAssessment(
return assessment;
}
const COVERAGE_GAP_LISTED_PATHS = 20;
function listedPaths(paths: string[]): string {
const shown = paths.slice(0, COVERAGE_GAP_LISTED_PATHS).join(", ");
return paths.length > COVERAGE_GAP_LISTED_PATHS ? `${shown}, and ${paths.length - COVERAGE_GAP_LISTED_PATHS} more` : shown;
}
/**
* Why a complete assessment does not cover the PR's allowed changed files, or
* null when it does. The message names the files, so the agent can correct the
* same submission instead of giving up on publication.
*/
export function githubCompleteCoverageGap(
allowedChangedPaths: string[],
coverage: Pick<GitHubReviewAssessment["coverage"], "reviewedPaths" | "omittedPaths">,
): string | null {
const allowed = new Set(allowedChangedPaths);
const reviewed = new Set(coverage.reviewedPaths);
const missing = allowedChangedPaths.filter(path => !reviewed.has(path));
const omitted = coverage.omittedPaths.filter(path => allowed.has(path));
if (missing.length === 0 && omitted.length === 0) return null;
return [
"A complete assessment must cover every non-excluded changed file in the PR, not only the files changed since a prior review.",
missing.length > 0
? `coverage.reviewedPaths is missing ${missing.length} of ${allowedChangedPaths.length} changed files: ${listedPaths(missing)}.`
: null,
omitted.length > 0 ? `coverage.omittedPaths names changed files: ${listedPaths(omitted)}.` : null,
"Review those files, add them to coverage.reviewedPaths, and call submit_review again. "
+ "If you cannot review them, submit complete: false and list them in coverage.omittedPaths.",
].filter(Boolean).join(" ");
}
export function githubReviewConclusion(
assessment: GitHubReviewAssessment,
threshold: GitHubReviewPolicy["ratingThreshold"],
+8 -11
View File
@@ -49,6 +49,7 @@ import {
import { githubChatPrincipalAccess } from "./chat-github-access.js";
import {
effectiveGitHubReviewPolicy,
githubCompleteCoverageGap,
githubReviewConclusion,
githubReviewPathIsExcluded,
githubReviewLineIsInPatch,
@@ -832,17 +833,13 @@ export function githubChatReviewService(db: Db, fetchImpl = fetch) {
throw conflict(
"Assessment coverage and findings must refer to this PR's allowed changed files",
);
if (
assessment.complete &&
(assessment.coverage.omittedPaths.some((path) => paths.has(path)) ||
permittedFiles.some(
(file) =>
!assessment.coverage.reviewedPaths.includes(file.filename),
))
)
throw conflict(
"A complete assessment must cover every non-excluded changed file",
);
const coverageGap = assessment.complete
? githubCompleteCoverageGap(
permittedFiles.map((file) => file.filename),
assessment.coverage,
)
: null;
if (coverageGap) throw conflict(coverageGap);
// Commit the immutable assessment and its publication together. A restart
// must never leave a stored result with no durable publication intent.
const actionId = await db.transaction(async (tx) => {
@@ -109,10 +109,44 @@ export function deferredWakeJoinsFirstTurn(
reason !== null && COMMENT_WAKE_REASONS.has(reason) &&
!payload.interactionId && !context.interactionId && !context.interactionStatus &&
!payload.queuedCommentInterrupt && context.resumeIntent !== true &&
!nonEmptyString(context.chatConversationId) && !nonEmptyString(payload.externalChatProvider) &&
!deferredWakeIsChatRequest(payload) &&
queuedCommentIdsFromWakePayload(payload).length > 0;
}
/**
* Whether a deferred wake carries a chat request. A chat wake keeps its own
* delivery: the run it starts binds that request's source, so its tools act on
* what the request asked for. `deferredWakeChatRequestSql` is the same test in SQL.
*/
export function deferredWakeIsChatRequest(payloadValue: unknown): boolean {
const payload = record(payloadValue);
return Boolean(nonEmptyString(record(payload[DEFERRED_WAKE_CONTEXT_KEY]).chatConversationId) ||
nonEmptyString(payload.externalChatProvider));
}
function deferredWakeChatRequestSql(payload: typeof agentWakeupRequests.payload) {
return sql`(nullif(btrim(${payload}->${DEFERRED_WAKE_CONTEXT_KEY}->>'chatConversationId'), '') is not null
or nullif(btrim(${payload}->>'externalChatProvider'), '') is not null)`;
}
/**
* Whether a chat request waits as a deferred wake behind the agent's current
* run on this task. Work that would continue the current run in a fresh session
* yields to it, because that continuation would keep the older request's source.
*/
export async function hasQueuedChatRequest(
db: Pick<Db, "select">,
input: { companyId: string; issueId: string; agentId: string },
): Promise<boolean> {
const [wake] = await db.select({ id: agentWakeupRequests.id }).from(agentWakeupRequests).where(and(
eq(agentWakeupRequests.companyId, input.companyId), eq(agentWakeupRequests.agentId, input.agentId),
eq(agentWakeupRequests.status, DEFERRED_WAKE_STATUS), isNull(agentWakeupRequests.runId),
sql`${agentWakeupRequests.payload}->>'issueId' = ${input.issueId}`,
deferredWakeChatRequestSql(agentWakeupRequests.payload),
)).limit(1);
return Boolean(wake);
}
type QueuedMessage = { id: string; body: string; createdAt: Date };
export function renderFirstTurnQueuedInput(messages: readonly QueuedMessage[]): string | null {
@@ -1,7 +1,7 @@
import { randomUUID } from "node:crypto";
import { and, eq } from "drizzle-orm";
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
import { agents, companies, completionContracts, createDb, heartbeatRuns, issues, issueTreeHoldMembers, issueTreeHolds, nativeRunFinalizations, statusDecisionEffects, statusDecisions } from "@paperclipai/db";
import { agentWakeupRequests, agents, companies, completionContracts, createDb, issueComments, heartbeatRuns, issues, issueTreeHoldMembers, issueTreeHolds, nativeRunFinalizations, statusDecisionEffects, statusDecisions } from "@paperclipai/db";
import type { ControlPlanePort, NativeExecutionInputV1, PrpStructuredRunResult, PrpTerminalState } from "@paperclipai/paperclip-runner";
import { startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js";
import { CONTROL_PLANE_CONFORMANCE_RESULT } from "../../vendor/paperclip-runner/testing.js";
@@ -17,6 +17,9 @@ import { finalizeNativeRun } from "./native-run-finalizer.js";
import { NATIVE_ENVIRONMENT_BLOCKER_CODE, NATIVE_ENVIRONMENT_BLOCKER_EXHAUSTED_ACTION, NATIVE_ENVIRONMENT_BLOCKER_EXHAUSTED_CODE,
NATIVE_ENVIRONMENT_BLOCKER_HINT, NATIVE_ENVIRONMENT_BLOCKER_MAX_RETRIES } from "./native-environment-blocker.js";
import { taskInterruptionPresentation } from "../task-interruption-presentation.js";
import { NATIVE_BLOCKER_SUPERSEDED_BY_QUEUED_REQUEST_CODE } from "./status-arbiter.js";
import { createReleaseIssueExecution } from "../../modules/wake-queue/application/use-cases.js";
import { createPostgresWakeQueueAdapter } from "../../modules/wake-queue/adapters/postgres.js";
type Blocker = NonNullable<PrpStructuredRunResult["blocker"]>;
@@ -115,6 +118,58 @@ describe("native run that reports a system environment blocker", () => {
expect(retries).toHaveLength(0);
});
async function queueWake(issueId: string, chat: boolean) {
const [message] = await db.insert(issueComments).values({ companyId, issueId, authorUserId: "env-owner",
body: chat ? "GitHub review request for the newest commit." : "Also check the totals." }).returning();
const conversationId = randomUUID();
const context = { issueId, taskId: issueId, wakeReason: chat ? "External chat message received" : "issue_commented",
wakeSource: "assignment", commentId: message!.id, wakeCommentId: message!.id, wakeCommentIds: [message!.id],
...(chat ? { source: "chat:github", chatConversationId: conversationId } : {}) };
const [wake] = await db.insert(agentWakeupRequests).values({ companyId, agentId, source: "assignment", triggerDetail: "system",
reason: context.wakeReason, status: "deferred_issue_execution", requestedByActorType: "user", requestedByActorId: "env-owner",
payload: { issueId, mutation: chat ? "chat_message_received" : "comment", wakeCommentId: message!.id, _paperclipWakeContext: context },
}).returning();
return { wakeId: wake!.id, messageId: message!.id, conversationId };
}
it("lets a queued chat request start the next turn with its own binding instead of continuing the blocked run", async () => {
// A GitHub push during a review waits as a chat wake. A fresh-session
// continuation would keep the older push's binding and could not publish.
let queued!: Awaited<ReturnType<typeof queueWake>>;
const { runId, decision, retries, issue } = await reportBlocked(environmentBlocker, {}, async issueId => {
queued = await queueWake(issueId, true);
});
expect(decision).toMatchObject({ reasonCode: NATIVE_BLOCKER_SUPERSEDED_BY_QUEUED_REQUEST_CODE });
expect(retries).toHaveLength(0);
expect(issue).toMatchObject({ status: "in_progress", unblockDescriptor: null });
const released = await createReleaseIssueExecution({
issueLock: createPostgresWakeQueueAdapter(db, {
resolveResponsibleUserId: async () => "env-owner",
getRoutineEnv: async () => ({ routineId: null, env: null, responsibleUserId: null }),
resolveSessionBeforeForWakeup: async () => null,
} as never),
recovery: { escalateStrandedAssignedIssue: async () => undefined, escalateStrandedRecoveryIssueInPlace: async () => undefined },
})({ companyId, runId, now: new Date() });
expect(released.outcome.kind).toBe("promoted");
const [wake] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, queued.wakeId));
const [next] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, wake!.runId!));
expect(next!.retryOfRunId).toBeNull();
expect(next!.contextSnapshot).toMatchObject({ issueId: issue.id, wakeCommentId: queued.messageId,
chatConversationId: queued.conversationId });
expect(next!.contextSnapshot).not.toHaveProperty("retryReason");
const [task] = await db.select().from(issues).where(eq(issues.id, issue.id));
expect(task!.executionRunId).toBe(next!.id);
await db.update(heartbeatRuns).set({ status: "cancelled" }).where(eq(heartbeatRuns.id, next!.id));
});
it("still continues the blocked run when only a plain comment waits behind it", async () => {
const { decision, retries } = await reportBlocked(environmentBlocker, {}, issueId => queueWake(issueId, false));
expect(decision).toMatchObject({ reasonCode: NATIVE_ENVIRONMENT_BLOCKER_CODE });
expect(retries).toHaveLength(1);
await db.update(heartbeatRuns).set({ status: "cancelled" }).where(eq(heartbeatRuns.id, retries[0]!.id));
});
it("keeps a blocker that only its owner can resolve", async () => {
const { decision, retries, issue } = await reportBlocked({ ...environmentBlocker, owner: { kind: "user", name: "board" },
reasonCode: "credential_missing", unblockAction: "Add the deploy key." });
@@ -34,6 +34,7 @@ import { isFailedTurnContinuationRun } from "./native-failed-turn-continuation.j
import { readPersistedNativeFailureEvidence } from "./native-provider-failure-evidence.js";
import { NATIVE_TOOL_RECEIPT_LIMIT_CODE, cancelStoppedRunContinuation, nativeRunHasStopRequest, readPersistedNativeToolReceiptLimitStop } from "./native-tool-receipt-limit.js";
import { NATIVE_ENVIRONMENT_BLOCKER_CODE, NATIVE_ENVIRONMENT_BLOCKER_EXHAUSTED_CODE, isNativeEnvironmentBlocker } from "./native-environment-blocker.js";
import { hasQueuedChatRequest } from "./first-turn-queued-input.js";
import { NATIVE_AGENT_BLOCKER_CONTINUATION_CODE, NATIVE_AGENT_BLOCKER_HANDOFF_CODE } from "./native-agent-blocker.js";
import { explainFailedRun, explainNativeTurnFailure, NATIVE_RUN_FAILED_UNEXPLAINED } from "./native-run-failure-explanation.js";
import { dismissAutomaticCompletionReviews } from "./automatic-completion-reviews.js";
@@ -1776,6 +1777,8 @@ export async function finalizeNativeRun(input: {
&& isNativeEnvironmentBlocker(result),
agentBlockerRecoverable: terminalState === "succeeded" && ownsProviderFailureDecision && !reviewContext && !stopRequested
&& result.reportedWorkDisposition === "blocked",
hasQueuedChatRequest: terminalState === "succeeded" && result.reportedWorkDisposition === "blocked"
&& await hasQueuedChatRequest(input.db, { companyId: run.companyId, issueId: authoritativeIssue.id, agentId: run.agentId }),
failureRetryCount: executionFailureRetryCount(run),
// Only the task's current owner may turn its own failed continuation
// into a blocker; the committer rechecks that under the issue lock.
@@ -769,6 +769,31 @@ describe("native status authority", () => {
}
});
it("hands the next turn to a queued chat request instead of continuing a blocker in a fresh session", () => {
// A GitHub push that arrives during a review waits as a chat wake. A
// self-continuation would keep the older request's head and never publish.
const blocked = (ownerKind: "system" | "agent") => assessment({ reportedDisposition: "blocked", objectiveSatisfied: false,
allCriteriaSatisfied: false, blocker: { unblockAction: "Publish the review.", boardOwned: false, ownerKind, scope: "task_wide" } });
const superseded = { statusAction: "preserve", toStatus: "in_progress",
reasonCode: "native_blocker_superseded_by_queued_request", unblockDescriptor: null, effects: [{ kind: "release_checkout" }] };
expect(arbitrate({ assessment: blocked("system"), environmentBlocker: true, hasQueuedChatRequest: true })).toMatchObject(superseded);
expect(arbitrate({ assessment: blocked("agent"), agentBlockerRecoverable: true, hasQueuedChatRequest: true })).toMatchObject(superseded);
// Spent automatic continuations bind the blocker to the board, as without a queued request.
expect(arbitrate({ assessment: blocked("system"), environmentBlocker: true, hasQueuedChatRequest: true, failureRetryCount: 2 }))
.toMatchObject({ reasonCode: "native_environment_blocker_exhausted", toStatus: "blocked", unblockDescriptor: { owner: "board" } });
expect(arbitrate({ assessment: blocked("agent"), agentBlockerRecoverable: true, hasQueuedChatRequest: true, failureRetryCount: 1 }))
.toMatchObject({ reasonCode: "native_agent_blocker_needs_person", toStatus: "blocked" });
expect(arbitrate({ assessment: blocked("system"), environmentBlocker: true, hasQueuedChatRequest: true, hasActivePauseHold: true }))
.toMatchObject({ reasonCode: "task_wide_blocker_bound" });
// A blocker for a person or an external owner is bound now, as without a queued request.
for (const ownerKind of ["user", "external"] as const) {
const owned = assessment({ reportedDisposition: "blocked", objectiveSatisfied: false, allCriteriaSatisfied: false,
blocker: { unblockAction: "Add the deploy key.", boardOwned: false, ownerKind, scope: "task_wide" } });
expect(arbitrate({ assessment: owned, agentBlockerRecoverable: true, hasQueuedChatRequest: true }))
.toMatchObject({ reasonCode: "native_agent_blocker_needs_person", toStatus: "blocked" });
}
});
it("continues a blocker the agent owns once, then hands it to the board, and never binds it back to the agent", () => {
const blocked = (ownerKind: "agent" | "external") => assessment({ reportedDisposition: "blocked", objectiveSatisfied: false,
allCriteriaSatisfied: false, blocker: { unblockAction: "Save the ledger.", boardOwned: false, ownerKind, scope: "task_wide" } });
@@ -12,6 +12,7 @@ export const NATIVE_STATUS_ARBITER_POLICY_VERSION = "phase6-v14";
/** The automatic continuation after a failed turn is used once per chain. */
export const NATIVE_RUN_FAILED_RETRY_CAUSE = "native_run_failed";
export const NATIVE_RESPONSE_WAKE_WAITING_REASON = "response_wake_waiting_for_input";
export const NATIVE_BLOCKER_SUPERSEDED_BY_QUEUED_REQUEST_CODE = "native_blocker_superseded_by_queued_request";
export const NATIVE_RUN_FAILED_CONTINUATION_EXHAUSTED_ACTION =
"The agent's turn failed again after Paperclip continued it automatically. The saved work is kept. Check the failed run, then Retry the task.";
@@ -265,6 +266,8 @@ export function arbitrateNativeStatus(input: {
/** The current owner's blocked report names a system-owned environment or tool outage. */
environmentBlocker?: boolean;
agentBlockerRecoverable?: boolean;
/** A chat request for this task and agent is waiting as a deferred wake behind this run. */
hasQueuedChatRequest?: boolean;
failureRetryCount?: number;
/**
* This run was itself the automatic continuation of an earlier failed turn.
@@ -631,6 +634,27 @@ export function arbitrateNativeStatus(input: {
})),
};
}
// A newer chat request waits behind this run. It starts the next turn with
// its own source binding and the full task history. A fresh-session
// continuation would inherit this run's older request instead, and would
// hold the task so the newer request never runs. Only a blocker that the
// lanes below would continue automatically yields. A blocker for a person or
// an external owner, or one whose automatic continuations are spent, is still
// bound now.
const blocker = input.assessment.blocker;
const retries = input.failureRetryCount ?? 0;
const continuesAutomatically = Boolean(blocker) && !input.isConversation && !input.hasActivePauseHold && (
(input.environmentBlocker === true && retries < NATIVE_ENVIRONMENT_BLOCKER_MAX_RETRIES) ||
(input.agentBlockerRecoverable === true && blocker!.scope === "task_wide" && !blocker!.boardOwned &&
blocker!.ownerKind === "agent" && retries < NATIVE_AGENT_BLOCKER_MAX_CONTINUATIONS));
if (input.assessment.reportedDisposition === "blocked" && input.hasQueuedChatRequest && continuesAutomatically) {
return {
policyVersion: NATIVE_STATUS_ARBITER_POLICY_VERSION,
statusAction: "preserve", toStatus: input.priorIssueStatus,
reasonCode: NATIVE_BLOCKER_SUPERSEDED_BY_QUEUED_REQUEST_CODE, unblockDescriptor: null,
effects: [{ kind: "release_checkout" }],
};
}
if (
input.assessment.reportedDisposition === "blocked" &&
input.assessment.blocker &&