Merge origin/master into feat/antigravity-swarm-command

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* origin/master:
  refactor(plugin-sdk): remove archivedState from the resume result (#22443)
  refactor(runner): let the provider decide whether a released Runner relaunches (#22442)
  fix(connections): drop MCP wording and the MCP guide link from Google Workspace setup (#22793)
  fix(ui): defer the Connectors announcement until a return visit (#22790)
  fix(connections): show only the privacy policy link in the Google Workspace picker (#22795)
  Add count, newest-first and lean run reads to customer-success inspection (#22781)
  fix(connections): keep a finished setup checklist on screen when the app refreshes queries (#22715)
  perf(ci): Phase 2 PR CI under 4 minutes (dynamic workers, fast E2E boot, typecheck overlap, test-budget gate) (#22729)
  fix(plan-mode): open the plan review card when a Plan-mode run settles without one (#22732)
This commit is contained in:
DottaandClaude Opus 5.5 committed 2026-11-24 13:21:12 -06:00
commit 3cbfa500f4
142 files changed
+5552 -11636

No files matched your search

@@ -1,7 +1,7 @@
import fs from "node:fs/promises";
import { constants } from "node:fs";
import { and, eq, getTableColumns, type SQL } from "drizzle-orm";
import type { AnyPgTable, AnyPgColumn } from "drizzle-orm/pg-core";
import { and, asc, count, desc, eq, getTableColumns, type SQL } from "drizzle-orm";
import { getTableConfig, type AnyPgTable, type AnyPgColumn } from "drizzle-orm/pg-core";
import * as schema from "@paperclipai/db";
import type { Db } from "@paperclipai/db";
import {
@@ -31,6 +31,42 @@ export interface CustomerSuccessInspectionOptions {
pluginWorkerManager?: PluginWorkerManager;
}
/**
* The `summary` view of a run: status, timestamps, ids and error codes, never
* the large JSON columns (result, usage, context snapshot, runner profile...),
* which make a full run row 170-540 KB. An allowlist, so a new column stays out
* until someone adds it here.
*/
export const RUN_SUMMARY_COLUMNS = [
"id",
"companyId",
"agentId",
"issueId",
"scopeKind",
"invocationSource",
"triggerDetail",
"status",
"errorCode",
"exitCode",
"runtimeMode",
"driverKind",
"retryOfRunId",
"processLossRetryCount",
"scheduledRetryAttempt",
"continuationAttempt",
"livenessState",
"startedAt",
"finishedAt",
"createdAt",
"updatedAt",
] as const;
function durationMs(row: Record<string, unknown>): number | null {
const started = row.startedAt instanceof Date ? row.startedAt.getTime() : null;
const finished = row.finishedAt instanceof Date ? row.finishedAt.getTime() : null;
return started !== null && finished !== null ? Math.max(0, finished - started) : null;
}
// This is a reviewed catalog of readers, not a proxy for existing GET routes.
// Select credentials out of queries; never load encrypted identity records.
interface Reader {
@@ -109,6 +145,13 @@ export const inspectionReaders: Record<InspectionResource, Reader> = {
threads: { table: schema.chatConversations, parent: "endpointId" },
};
/** The table's primary key columns: a stable tie-breaker for ordered pages. */
export function primaryKeyColumns(table: AnyPgTable): AnyPgColumn[] {
const config = getTableConfig(table);
const single = config.columns.filter((column) => column.primary);
return single.length ? single : (config.primaryKeys[0]?.columns ?? []);
}
async function ownRow(tx: Db, table: AnyPgTable, companyId: string, id: string) {
const columns = getTableColumns(table) as Record<string, AnyPgColumn>;
const [row] = await tx
@@ -157,7 +200,7 @@ export async function readCustomerSuccessResource(
.where(eq(schema.companies.id, q.companyId));
if (!company) throw notFound("Inspection company not found");
}
if (q.operation === "list" || q.operation === "get") {
if (q.operation === "list" || q.operation === "get" || q.operation === "count") {
const reader = inspectionReaders[q.resource!];
const all = getTableColumns(reader.table) as Record<string, AnyPgColumn>;
const columns = Object.fromEntries(
@@ -180,6 +223,7 @@ export async function readCustomerSuccessResource(
const { inArray } = await import("drizzle-orm");
if (!memberships.length) {
if (q.operation === "get") throw notFound("Inspection resource not found");
if (q.operation === "count") return { total: 0, byStatus: all.status ? {} : null };
return { items: [], nextOffset: null };
}
predicates.push(
@@ -200,13 +244,51 @@ export async function readCustomerSuccessResource(
throw unprocessable("This reader does not accept parentId");
predicates.push(eq(all[reader.parent], q.parentId));
}
if (q.operation === "count") {
// Totals only: no row content leaves the database.
if (!all.status) {
const [{ total }] = await tx
.select({ total: count() })
.from(reader.table)
.where(and(...predicates));
return { total: Number(total), byStatus: null };
}
const groups = await tx
.select({ status: all.status, total: count() })
.from(reader.table)
.where(and(...predicates))
.groupBy(all.status);
const byStatus: Record<string, number> = {};
let total = 0;
for (const group of groups) {
byStatus[String(group.status)] = Number(group.total);
total += Number(group.total);
}
return { total, byStatus };
}
const limit = q.operation === "get" ? 1 : Math.max(1, q.limit ?? 25);
const order = all[reader.id ?? "id"] ?? all.createdAt ?? all.companyId;
const idColumn = all[reader.id ?? "id"];
let orderBy: SQL[] | AnyPgColumn[];
if (q.order) {
if (!all.createdAt) throw unprocessable("This resource has no creation time to order by");
const direction = q.order === "newest" ? desc : asc;
// Rows written together share createdAt; the full primary key keeps
// offset pages from repeating or skipping them.
orderBy = [all.createdAt, ...primaryKeyColumns(reader.table)].map((column) => direction(column));
} else {
orderBy = [idColumn ?? all.createdAt ?? all.companyId];
}
const selected =
q.view === "summary"
? Object.fromEntries(
RUN_SUMMARY_COLUMNS.filter((key) => columns[key]).map((key) => [key, columns[key]]),
)
: columns;
let rows = await tx
.select(columns)
.select(selected)
.from(reader.table)
.where(and(...predicates))
.orderBy(order)
.orderBy(...orderBy)
.limit(limit + (q.operation === "get" ? 0 : 1))
.offset(q.offset ?? 0);
if (q.resource === "agents")
@@ -245,6 +327,7 @@ export async function readCustomerSuccessResource(
q.companyId!,
rows as Array<{ id: string }>,
);
if (q.view === "summary") rows = rows.map((r) => ({ ...r, durationMs: durationMs(r) }));
// Match the existing structured event/config redaction, without scanning
// prose, documents, instructions, skill contents, or workspace files.
if (
@@ -1,6 +1,6 @@
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { buildPaperclipTaskMarkdown } from "./task-markdown.js";
import { NATIVE_PLAN_REVIEW_DIRECTIVE, buildPaperclipTaskMarkdown } from "./task-markdown.js";
const issue = {
id: "task-1",
@@ -66,6 +66,15 @@ describe("heartbeat task markdown rendering", () => {
expect(markdown).toContain("Do not invent material user intent or success criteria");
});
it("tells a native Plan-mode run that Paperclip opens the one plan review card", () => {
const planning = { issue: { ...issue, workMode: "planning" } };
expect(buildPaperclipTaskMarkdown({ ...planning, nativeRunner: true })).toContain(NATIVE_PLAN_REVIEW_DIRECTIVE);
// Adapters keep their own approval flow, and an accepted plan is executed.
expect(buildPaperclipTaskMarkdown({ ...planning, nativeRunner: false })).not.toContain(NATIVE_PLAN_REVIEW_DIRECTIVE);
expect(buildPaperclipTaskMarkdown({ ...planning, nativeRunner: true, acceptedPlanContinuation: true,
taskPlan: { documentId: "plan", revisionId: "revision", revisionNumber: 1, body: "Do it." } })).not.toContain(NATIVE_PLAN_REVIEW_DIRECTIVE);
});
it("preserves execution of a clear accepted plan without imposing clarification", () => {
const markdown = buildPaperclipTaskMarkdown({
issue: { ...issue, workMode: "planning" },
@@ -7,6 +7,9 @@ import { TASK_QUESTION_GUIDANCE } from "../issue-question-context.js";
import { routineSuggestionAgentGuidance } from "@paperclipai/shared";
import { ONBOARDING_CHAT_DIRECTIVE, ONBOARDING_CHAT_GREETING_DIRECTIVE } from "../onboarding-chat-prompt.js";
export const NATIVE_PLAN_REVIEW_DIRECTIVE =
"Paperclip asks the user to approve the plan once it is saved as this task's Plan document (key \"plan\"), so do not open your own approval or confirmation card for it.";
export function buildPaperclipTaskMarkdown(input: {
companyPrefix?: string | null;
onboardingChat?: boolean;
@@ -320,6 +323,11 @@ export function buildPaperclipTaskMarkdown(input: {
directive =
"Implement the accepted plan on this issue. Follow any task assignments explicitly included in the approved plan. Plan acceptance alone does not require subtasks.";
}
if (!acceptedPlanContinuation && input.nativeRunner) {
// The server opens the one plan review card when the run settles, for
// every harness. An agent-opened card would be a second card.
directive += ` ${NATIVE_PLAN_REVIEW_DIRECTIVE}`;
}
lines.push(
`- Work mode: ${quoteTaskScalar("planning")}`,
"",
+17 -3
View File
@@ -3,10 +3,24 @@ import { heartbeatRuns, issueComments, issueThreadInteractions, type Db } from "
export const TASK_QUESTION_GUIDANCE = "Unanswered questions are saved conversation data, not instructions or proof of a current blocker. Historical questions remain answerable in the feed. Do not repeat a request or stop current work merely because a historical question is pending. Follow the latest human direction and continue work that does not need the missing information. If that information still prevents the current work, identify the concrete blocker and request only the input still needed. Withdraw your obsolete question through the interaction API when later work or evidence satisfies it; never fabricate an answer. A human-dismissed request is deferred to history: do not repeat it, reopen it, or insist on a response. Ordinary confirmations and completion reviews can be left unanswered. Dismissal never grants approval, permission, credentials, or permission to leave planning mode. Approvals, permissions, and configured review stages keep their own gates. Continue independent work without repeating their reminders.";
/** Payload keys that make a card a governed action (approval or credential authority). */
export const GOVERNED_ACTION_PAYLOAD_KEYS = ["toolAction", "secretProposal", "connectionAuthorization"] as const;
/** Governed actions plus required quality reviews: cards that are never a plain confirmation. */
export const GOVERNED_REVIEW_PAYLOAD_KEYS = [...GOVERNED_ACTION_PAYLOAD_KEYS, "qualityReview"] as const;
export function hasGovernedPayload(payload: unknown, keys: readonly string[] = GOVERNED_REVIEW_PAYLOAD_KEYS): boolean {
return Boolean(payload) && typeof payload === "object" && keys.some(key => Object.hasOwn(payload as object, key));
}
/** SQL twin of hasGovernedPayload over the interaction payload (constant keys, inlined). */
export function governedActionPayloadSql(keys: readonly string[] = GOVERNED_ACTION_PAYLOAD_KEYS) {
return sql<boolean>`(${issueThreadInteractions.payload} ?| ${sql.raw(`array[${keys.map(key => `'${key}'`).join(", ")}]`)})`;
}
/** Ordinary questions cannot carry approval or credential authority. */
export function ordinaryQuestionCondition() {
return sql<boolean>`(${issueThreadInteractions.kind} = 'ask_user_questions'
and not (${issueThreadInteractions.payload} ?| array['toolAction', 'secretProposal', 'connectionAuthorization']))`;
and not (${governedActionPayloadSql()}))`;
}
/**
@@ -17,7 +31,7 @@ export function ordinaryQuestionCondition() {
export function deferrableInteractionCondition() {
return sql<boolean>`(${issueThreadInteractions.kind} in ('ask_user_questions', 'request_confirmation', 'request_checkbox_confirmation', 'request_item_verdicts', 'suggest_tasks')
and ${issueThreadInteractions.effectiveResolverPolicySource} = 'requested'
and not (${issueThreadInteractions.payload} ?| array['toolAction', 'secretProposal', 'connectionAuthorization'])
and not (${governedActionPayloadSql()})
and coalesce(${issueThreadInteractions.payload}->'target'->>'type', '') <> 'issue_document')`;
}
@@ -89,7 +103,7 @@ export function activeIssueInteractionCondition(input: {
${ordinaryQuestionCondition()}
or (${issueThreadInteractions.kind} in ('request_confirmation', 'request_checkbox_confirmation')
and ${issueThreadInteractions.effectiveResolverPolicy} = 'anyone'
and not (${issueThreadInteractions.payload} ?| array['toolAction', 'secretProposal', 'connectionAuthorization']))
and not (${governedActionPayloadSql()}))
)
)` : undefined,
)!;
@@ -14,7 +14,7 @@ import { notifyToolReviewChange } from "./tool-review-work-notifications.js";
import { projectGitHubInteractionErrors } from "./tool-access/github-action-error-projection.js";
import { normalizeEscapedLineBreaks } from "@paperclipai/shared/validators/text";
import { notifyDeliveryWork, DELIVERY_QUEUES } from "./delivery-work-notifications.js";
import { historicalQuestionCondition } from "./issue-question-context.js";
import { hasGovernedPayload, historicalQuestionCondition } from "./issue-question-context.js";
import {
currentContinuationOrigins,
deliveredContinuationCommentIds,
@@ -228,6 +228,8 @@ type CreateInteractionOptions = {
supersedePendingSiblingInteractions?: boolean;
replayAcceptedInteractionIds?: readonly string[];
requireAcceptedReplay?: boolean;
/** Runs once, in the insert transaction, only when this call created the card (never on an idempotent replay). */
afterInsertInTransaction?: (tx: Db, row: IssueThreadInteractionRow) => Promise<void>;
};
type InteractionWakeup = (
@@ -693,7 +695,7 @@ async function isEquivalentAcceptedReplay(
if (
!replayAcceptedInteractionIds.includes(row.id)
|| !isRequestConfirmationLikeKind(row.kind)
|| ["toolAction", "secretProposal", "connectionAuthorization", "qualityReview"].some(key => Object.hasOwn(row.payload, key))
|| hasGovernedPayload(row.payload)
|| row.status !== "accepted"
|| row.result?.outcome !== "accepted"
|| !row.resolvedAt
@@ -5324,6 +5326,7 @@ export function issueThreadInteractionService(
})
.returning();
await options.afterInsertInTransaction?.(tx as unknown as Db, row);
if (row.addresseeAgentId || row.addresseeUserId) {
const [privacyIssue] = await tx.select().from(issues).where(and(eq(issues.id, issue.id), eq(issues.companyId, issue.companyId)));
await ensureAssignmentIssueAccessGrant(tx, { ...privacyIssue!,
@@ -0,0 +1,252 @@
import { and, eq, inArray } from "drizzle-orm";
import { documentRevisions, documents, issueThreadInteractions, issues, type Db } from "@paperclipai/db";
import { logActivity, publishActivity } from "../activity-log.js";
import { documentService } from "../documents.js";
import { HttpError } from "../../errors.js";
import { logger } from "../../middleware/logger.js";
import { issueThreadInteractionService } from "../issue-thread-interactions.js";
import { activeIssueInteractionCondition, hasGovernedPayload } from "../issue-question-context.js";
import { isConversation } from "../../lib/conversation-wake-policy.js";
/**
* The Plan-mode review card for the current plan revision.
*
* Codex and Claude report their plan as a provider event, and the session
* opens the Approve / Request changes card for it. Harnesses without such an
* event (Antigravity and other ACPX agents) write the Plan document with a
* tool and must open the card themselves. A run that forgets, or a recovered
* run that resumes after the original process died, would otherwise leave a
* Plan-mode task waiting on a review nobody can give. When a Plan-mode run
* settles, the server opens the card for the current revision unless one
* already covers it.
*/
export type NativePlanReviewCardOutcome =
/** The server opened the card for this revision. */
| { kind: "created"; interactionId: string; revisionId: string }
/** A pending card (or question) already gives the user the next action. */
| { kind: "pending"; interactionId: string }
/** The current revision was already answered; the agent owes a new revision. */
| { kind: "reviewed"; revisionId: string }
/** Plan mode produced no plan to review. */
| { kind: "no_plan" }
/** Not a Plan-mode task this agent owns, or the revision is not the agent's. */
| { kind: "not_applicable" };
type Binding = { companyId: string; issueId: string; runId: string; agentId: string };
const record = (value: unknown): Record<string, unknown> =>
value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
export function planReviewCardIdempotencyKey(revisionId: string): string {
return `plan-review:v1:${revisionId}`;
}
/**
* The one Plan-review card shape, for the card Paperclip opens from a
* provider's plan event (Codex, Claude) and the one it opens on settle.
*/
export function planReviewConfirmationInput(input: {
issueId: string;
documentId: string;
revisionId: string;
revisionNumber: number;
sourceRunId: string;
idempotencyKey: string;
source: "provider_plan" | "plan_document";
}) {
return {
kind: "request_confirmation" as const,
idempotencyKey: input.idempotencyKey,
sourceRunId: input.sourceRunId,
title: `Review plan revision ${input.revisionNumber}`,
summary: input.source === "provider_plan"
? "Review the synchronized Paperclip plan."
: "Review the plan before the agent starts the work.",
continuationPolicy: "wake_assignee" as const,
payload: {
version: 1 as const,
prompt: `Approve plan revision ${input.revisionNumber}?`,
...(input.source === "provider_plan"
? { detailsMarkdown: "The completed provider plan has been synchronized to the canonical Plan document." }
: {}),
acceptLabel: "Approve plan",
rejectLabel: "Request changes",
rejectRequiresReason: true,
supersedeOnUserComment: false,
target: {
type: "issue_document" as const,
issueId: input.issueId,
documentId: input.documentId,
key: "plan",
revisionId: input.revisionId,
revisionNumber: input.revisionNumber,
label: `Plan v${input.revisionNumber}`,
},
},
};
}
async function coveringCard(db: Db, binding: Binding, revision: { id: string }, conversationMode: boolean) {
// A historical or deferred card cannot give the user the next action; the
// same rule decides the run's governance gate.
const active = new Set((await db.select({ id: issueThreadInteractions.id }).from(issueThreadInteractions).where(and(
eq(issueThreadInteractions.companyId, binding.companyId),
eq(issueThreadInteractions.issueId, binding.issueId),
eq(issueThreadInteractions.status, "pending"),
activeIssueInteractionCondition({ runId: binding.runId, conversationMode }),
))).map(row => row.id));
const cards = await db.select({
id: issueThreadInteractions.id,
kind: issueThreadInteractions.kind,
status: issueThreadInteractions.status,
payload: issueThreadInteractions.payload,
createdAt: issueThreadInteractions.createdAt,
resolvedByUserId: issueThreadInteractions.resolvedByUserId,
resolvedByAgentId: issueThreadInteractions.resolvedByAgentId,
result: issueThreadInteractions.result,
}).from(issueThreadInteractions).where(and(
eq(issueThreadInteractions.companyId, binding.companyId),
eq(issueThreadInteractions.issueId, binding.issueId),
inArray(issueThreadInteractions.kind, ["request_confirmation", "ask_user_questions"]),
));
const targetRevision = (payload: unknown) => {
const target = record(record(payload).target);
return target.type === "issue_document" && typeof target.revisionId === "string" ? target.revisionId : null;
};
// Only an explicit plan review covers a revision: a card bound to this
// revision (the server's, Codex/Claude's, or an agent's card opened with the
// plan target). An unbound confirmation is an ordinary request: it never
// covers a plan, never starts execution and is never withdrawn here. A
// pending question also gives the user the next action. A card bound to an
// older revision does not cover this one.
const covers = (card: (typeof cards)[number]) => {
if (card.kind === "ask_user_questions") return card.status === "pending";
if (hasGovernedPayload(card.payload)) return false;
return targetRevision(card.payload) === revision.id;
};
// A pending card bound to this revision always gates it, also when the
// conversation prior-turn rule would leave it out of the active set.
const pending = cards.find(card => card.status === "pending" && covers(card) &&
(active.has(card.id) || targetRevision(card.payload) === revision.id));
if (pending) return { kind: "pending" as const, interactionId: pending.id };
// How each terminal state of a card bound to this revision counts:
// - accepted or rejected: the user decided this revision;
// - cancelled by the user (withdrawn from the thread): the user declined to
// review this revision. Do not reopen it; the agent is asked to revise.
// - cancelled by an agent or the system, expired (superseded, stale, task
// closed) or failed: no one reviewed it. The revision gets a fresh card.
// A card withdrawn as a stale target was for an older revision, even though
// the withdrawal records the current revision on it.
const bound = cards.filter(card => card.kind === "request_confirmation" && covers(card) &&
record(card.result).outcome !== "stale_target");
const decided = bound.find(card => ["accepted", "rejected"].includes(card.status) ||
(card.status === "cancelled" && card.resolvedByUserId && !card.resolvedByAgentId));
if (decided) return { kind: "reviewed" as const, revisionId: revision.id };
const unreviewed = bound.filter(card => card.status !== "pending")
.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime())[0];
return unreviewed ? { kind: "reopen" as const, afterInteractionId: unreviewed.id } : null;
}
export async function ensureNativePlanReviewCard(db: Db, binding: Binding): Promise<NativePlanReviewCardOutcome> {
const publications: Parameters<typeof publishActivity>[0][] = [];
// One decision per task at a time: reading the current revision and its
// cards, withdrawing older cards, choosing the key and inserting all happen
// under the task row lock, so two settles can never both open a card for
// one plan. Card creation takes the same lock first, so the order matches.
const outcome = await db.transaction(async (transaction) => {
const tx = transaction as unknown as Db;
const [issue] = await tx.select({
workMode: issues.workMode, status: issues.status, assigneeAgentId: issues.assigneeAgentId,
assigneeUserId: issues.assigneeUserId, hiddenAt: issues.hiddenAt,
conversationAgentId: issues.conversationAgentId, conversationUserId: issues.conversationUserId,
}).from(issues).where(and(eq(issues.id, binding.issueId), eq(issues.companyId, binding.companyId))).limit(1).for("update");
if (!issue || issue.workMode !== "planning" || issue.hiddenAt || issue.assigneeUserId ||
issue.assigneeAgentId !== binding.agentId || ["done", "cancelled"].includes(issue.status)) {
return { kind: "not_applicable" } as const;
}
const plan = await documentService(tx).getIssueDocumentByKey(binding.issueId, "plan");
if (!plan?.latestRevisionId) return { kind: "no_plan" } as const;
const [revision] = await tx.select({
id: documentRevisions.id, revisionNumber: documentRevisions.revisionNumber,
createdByAgentId: documentRevisions.createdByAgentId,
}).from(documentRevisions).where(and(
eq(documentRevisions.id, plan.latestRevisionId), eq(documentRevisions.companyId, binding.companyId),
)).limit(1);
if (!revision) return { kind: "no_plan" } as const;
// A delayed settle that read an older revision must not act on it.
const [current] = await tx.select({ latestRevisionId: documents.latestRevisionId, latestRevisionNumber: documents.latestRevisionNumber })
.from(documents).where(and(eq(documents.id, plan.id), eq(documents.companyId, binding.companyId))).for("update");
if (current?.latestRevisionId !== revision.id) return { kind: "not_applicable" } as const;
const conversationMode = isConversation(issue);
const existing = await coveringCard(tx, binding, revision, conversationMode);
if (existing && existing.kind !== "reopen") return existing;
// Only the assigned agent's own proposal is put up for review. A revision
// a person wrote is theirs already.
if (revision.createdByAgentId !== binding.agentId) return { kind: "not_applicable" } as const;
// A card for this revision that no one reviewed keeps its key; the fresh
// card's key names the one it follows.
const idempotencyKey = existing?.kind === "reopen"
? `${planReviewCardIdempotencyKey(revision.id)}:after:${existing.afterInteractionId}`
: planReviewCardIdempotencyKey(revision.id);
// Withdraw cards bound to an older revision. Answering one is already
// refused as a stale target, so this only tidies the thread: a row it
// cannot read must not stop the current card from opening.
await tx.transaction(async (savepoint) => {
await issueThreadInteractionService(savepoint as unknown as Db).expireStaleRequestConfirmationsForIssueDocument(
{ id: binding.issueId, companyId: binding.companyId },
{ id: plan.id, key: "plan", latestRevisionId: current.latestRevisionId, latestRevisionNumber: current.latestRevisionNumber },
{ agentId: binding.agentId, runId: binding.runId });
}).catch((error: unknown) => logger.warn({ issueId: binding.issueId, error }, "Could not withdraw stale plan review cards"));
let inserted = false;
try {
const interaction = await issueThreadInteractionService(tx).create(
{ id: binding.issueId, companyId: binding.companyId },
planReviewConfirmationInput({
issueId: binding.issueId, documentId: plan.id, revisionId: revision.id, revisionNumber: revision.revisionNumber,
sourceRunId: binding.runId, source: "plan_document", idempotencyKey,
}) as never,
{ agentId: binding.agentId, runId: binding.runId },
{
// Leave the agent's other pending cards answerable. Only cards bound
// to an older plan revision were withdrawn above; an unbound card is
// never withdrawn by guess.
supersedePendingSiblingInteractions: false,
// Only the call that inserted the card records it.
afterInsertInTransaction: async (insertTx, row) => {
inserted = true;
await logActivity(insertTx, {
companyId: binding.companyId,
actorType: "system",
actorId: "native-plan-review",
agentId: binding.agentId,
runId: binding.runId,
issueId: binding.issueId,
action: "issue.thread_interaction_created",
entityType: "issue",
entityId: binding.issueId,
details: {
interactionId: row.id,
interactionKind: "request_confirmation",
source: "plan_mode_settle",
planRevisionId: revision.id,
planRevisionNumber: revision.revisionNumber,
},
}, publications);
},
},
);
return inserted
? { kind: "created", interactionId: interaction.id, revisionId: revision.id } as const
: { kind: "pending", interactionId: interaction.id } as const;
} catch (error) {
// The task closed or the agent may no longer write here. A refused card
// must not fail the run's settlement; database errors still surface so
// finalization (or the recovery pass) retries.
if (!(error instanceof HttpError) || error.status >= 500) throw error;
const covered = await coveringCard(tx, binding, revision, conversationMode);
return covered && covered.kind !== "reopen" ? covered : { kind: "not_applicable" } as const;
}
});
for (const publication of publications) publishActivity(publication);
return outcome;
}
@@ -114,6 +114,7 @@ import {
} from "../heartbeat-run-summary.js";
import { resolveChatRunPresentationAuthorizationReason } from "../chat-run-publications.js";
import { settledResponsePublicationSql } from "./native-response-publication-receipt.js";
import { ensureNativePlanReviewCard } from "./native-plan-review-card.js";
import { hasChatRunOwnedProviderInteraction } from "../chat-interaction-arbitration.js";
import {
authorizeCommittedChatResponse,
@@ -1677,6 +1678,23 @@ export async function finalizeNativeRun(input: {
? await findSupersededExternalReviewRequests(input.db, {
companyId: run.companyId, issueId: authoritativeIssue.id, runId: run.id, agentId: run.agentId,
}) : [];
// A Plan-mode run that settles with a plan revision nobody was asked to
// review gets its review card here, whichever harness ran it and whether
// or not the agent remembered to open it. The card is the review gate below.
const planReview = terminalState === "succeeded" && input.workspaceFinalizeStatus === "succeeded" &&
authoritativeIssue.workMode === "planning" && result.reportedWorkDisposition !== "done" &&
!isNativePlanWaitResult(result) &&
!readNativeReviewAssignmentContext(run.contextSnapshot)
? await ensureNativePlanReviewCard(input.db, {
companyId: run.companyId, issueId: authoritativeIssue.id, runId: run.id, agentId: run.agentId,
}).catch((error: unknown) => {
// The run already succeeded; a card that could not be opened must
// not fail its settlement. The task settles in its response wait and
// the stranded-task pass opens the card (idempotently) later.
logger.warn({ runId: run.id, issueId: authoritativeIssue.id, error }, "Plan review card could not be opened at settle; recovery will retry");
return null;
})
: null;
const governanceGate = await pendingNativeGovernance({
db: input.db,
companyId: run.companyId,
@@ -1778,6 +1796,7 @@ export async function finalizeNativeRun(input: {
monitorWaitSuperseded: supersededMonitorWait !== null,
monitorWaitAuthorized: authoritativeIssue.workMode === "standard" && authoritativeIssue.executionRunId === run.id && monitorWaitAt !== null,
planWaitAuthorized: planWait !== null,
planNotProduced: planReview?.kind === "no_plan" || planReview?.kind === "reviewed",
hasPendingChildCompletion,
providerModelRejected: providerFailure?.errorCode === "native_provider_model_rejected" && ownsProviderFailureDecision,
providerOverloaded: providerFailure?.errorCode === "native_provider_overloaded" && ownsProviderFailureDecision,
@@ -15147,10 +15147,12 @@ describe("native warm session supervision", () => {
async ({ name, firstEnvironment = {}, secondEnvironment = {}, refreshTools, unsupportedRefresh = false,
managedGitHub = false, reuse, adoptionReuse = reuse }) => {
const decisions: Record<string, boolean> = {};
for (const path of ["warm", "adoption", ...(refreshTools ? ["portable", "portable-bootstrap", "legacy-plugin"] as const : [])] as const) {
for (const path of ["warm", "adoption", ...(refreshTools ? ["portable", "portable-bootstrap", "legacy-plugin"] as const : []),
...(refreshTools && !unsupportedRefresh ? ["released-unavailable"] as const : [])] as const) {
const portable = path === "portable" || path === "portable-bootstrap";
const bootstrap = path === "portable-bootstrap";
const pluginRecovery = portable || path === "legacy-plugin";
const releasedUnavailable = path === "released-unavailable";
const pluginRecovery = portable || path === "legacy-plugin" || releasedUnavailable;
githubAccess.create.mockReset().mockImplementation(async () => ({ env: {}, ready: true, duplexRequested: false,
activate: githubAccess.activate.mockReset().mockImplementation(() => vi.fn()), stop: githubAccess.stop.mockReset().mockResolvedValue(undefined) }));
const stateBase = await mkdtemp(join(tmpdir(), "paperclip-runnerd-reuse-key-"));
@@ -15228,7 +15230,7 @@ describe("native warm session supervision", () => {
const projection = vi.spyOn(controllerRecovery, "resolveNativeControllerRecovery").mockResolvedValue({ kind: "no_prior_execution" });
const restore = path === "legacy-plugin" ? vi.spyOn(runnerCheckpoint, "restoreNativeRunnerCheckpoint")
.mockImplementation(async (_db, binding) => binding.runId === first.binding.runId && recoveredSession.close.mock.calls.length ? {} as never : null) : undefined;
const issueProjection = path === "legacy-plugin" ? vi.spyOn(issueServiceModule, "issueService")
const issueProjection = path === "legacy-plugin" || releasedUnavailable ? vi.spyOn(issueServiceModule, "issueService")
.mockReturnValue({ update: vi.fn(async () => null) } as never) : undefined;
try {
await executePaperclipNativeSession({ db: leaseDb(first), execution: first, runnerInstanceId: "runner-reuse-key",
@@ -15261,14 +15263,26 @@ describe("native warm session supervision", () => {
});
}
if (pluginRecovery) state.createBackend.mockReturnValueOnce({
kind: "test", recoverSession: async () => ({ recovered: true, session: recoveredSession }),
kind: "test", recoverSession: async () => {
if (releasedUnavailable) throw new Error("native_runner_reuse_unavailable");
return { recovered: true, session: recoveredSession };
},
} as never);
const createOwner = pluginTaskRuntime.createPluginRunnerTaskOwner;
const owners = releasedUnavailable ? vi.spyOn(pluginTaskRuntime, "createPluginRunnerTaskOwner")
.mockImplementation(ownerInput => Object.assign(createOwner(ownerInput), { retiredBeforeClaim: () => true })) : undefined;
const resumeFrom = releasedUnavailable ? vi.spyOn(environmentTaskRuntime, "resolvePluginTaskResume").mockResolvedValue("target-task") : undefined;
const pluginTaskDescription = { kind: "description", taskId: "target-task", warmTaskVersion: 1,
launchPreparationVersion: 1, projectAuthCheckVersion: 1, releaseResumeVersion: 1,
...(releasedUnavailable ? { executionContextVersion: 1 as const } : {}),
runner: { version: "fixture", digest: `sha256:${"a".repeat(64)}` } } as const;
const portableTarget = { ...target, runner: undefined, leaseId: "target-lease",
sandboxLeaseAcquisition: { outcome: path === "legacy-plugin" ? "resumed" : "created", providerLeaseId: "target-task" },
runnerTask: vi.fn(async (operation: { kind: string }) => {
sandboxLeaseAcquisition: { outcome: path === "legacy-plugin" || releasedUnavailable ? "resumed" : "created", providerLeaseId: "target-task" },
runnerTask: vi.fn(async (operation: { kind: string }, options?: { executionContext?: unknown }) => {
if (releasedUnavailable && operation.kind === "describe") {
if (options?.executionContext) throw new Error("fixture replacement bound to the old task context");
return { ...pluginTaskDescription, taskId: "fresh-task" };
}
if (path === "legacy-plugin") {
expect(recoveredSession.close).toHaveBeenCalledOnce();
expect(operation.kind).toBe("describe");
@@ -15313,6 +15327,16 @@ describe("native warm session supervision", () => {
expect(portableTarget.runnerTask).toHaveBeenCalledOnce();
continue;
}
if (releasedUnavailable) {
try {
await continuation;
delete decisions[path];
expect(portableTarget.runnerTask.mock.calls.map(([operation]) => operation.kind)).toContain("describe");
expect(state.execute).toHaveBeenCalledTimes(2);
expect(recoveredSession.close).not.toHaveBeenCalled();
} finally { owners?.mockRestore(); resumeFrom?.mockRestore(); }
continue;
}
if (path === "adoption") await expect(continuation).rejects.toThrow("fixture adoption decision recorded");
else await continuation;
expect(decisions[path]).toBe(portable ? true : path === "adoption" ? adoptionReuse : reuse);
@@ -19613,12 +19637,12 @@ describe("runnerd provider runtime wiring", () => {
});
it.each((["codex", "claude"] as const).flatMap(provider => [
...[[false, false, false, false], [true, false, false, false], [false, true, false, false], [false, false, true, false], ...(provider === "codex" ? [[false, false, false, true]] : [])]
.map(([unknown, shutdown, journalFailure, deadline]) => [provider, unknown, shutdown, journalFailure, deadline, "idle timeout"] as const),
...[[false, false, false], [true, false, false], [false, true, false], ...(provider === "codex" ? [[false, false, true]] : [])]
.map(([unknown, shutdown, deadline]) => [provider, unknown, shutdown, deadline, "idle timeout"] as const),
...(["controller restart", "detach failure", "environment deletion", "replacement hand-off"] as const)
.map(retirement => [provider, false, false, false, false, retirement] as const),
.map(retirement => [provider, false, false, false, retirement] as const),
]))(
"releases settled %s only under its current owner and retires its cache (unknown=%s, shutdown=%s, journalFailure=%s, deadline=%s, retirement=%s)", async (provider, unknown, shutdown, journalFailure, deadline, retirement) => {
"releases settled %s only under its current owner and retires its cache (unknown=%s, shutdown=%s, deadline=%s, retirement=%s)", async (provider, unknown, shutdown, deadline, retirement) => {
await closeIdleWarmNativeSessionsForRestart();
expect(readNativeSessionIdleWork()).toBe("none");
const previousHome = process.env.PAPERCLIP_HOME;
@@ -19654,7 +19678,7 @@ describe("runnerd provider runtime wiring", () => {
});
let allowPhysicalStop!: () => void;
const physicalStop = new Promise<void>(resolve => { allowPhysicalStop = resolve; });
const close = vi.fn(async () => { if (shutdown || deadline || journalFailure) await physicalStop; }), detachControllerForRestart = vi.fn(async () => {});
const close = vi.fn(async () => { if (shutdown || deadline) await physicalStop; }), detachControllerForRestart = vi.fn(async () => {});
const session = { release, close, detachControllerForRestart };
const validated = validatePrpStructuredRunResult({ schema: "paperclip.run_result.v1", reportedWorkDisposition: "done",
summary: "Completed", completionClaim: { contractRevision: current.completionContract.contract.revision,
@@ -19683,7 +19707,7 @@ describe("runnerd provider runtime wiring", () => {
runnerInstanceId: source.runnerInstanceId, useRunnerd: true, runnerIngressAuthorized: true,
runnerExecutionTarget: { ...target, runnerTask: nextTask } })).rejects.toThrow("native_session_supervisor_busy");
expect(nextTask).not.toHaveBeenCalled();
if (provider === "codex" && !unknown && !shutdown && !journalFailure && !deadline) {
if (provider === "codex" && !unknown && !shutdown && !deadline) {
await expect(executePaperclipNativeSession({ db: leaseDb(next), execution: next,
runnerInstanceId: source.runnerInstanceId, useRunnerd: true, runnerIngressAuthorized: true,
runnerExecutionTarget: { ...target, environmentId: "competing-environment", runnerTask: nextTask,
@@ -19714,33 +19738,6 @@ describe("runnerd provider runtime wiring", () => {
expect(JSON.parse(await readFile(join(directory, (await readdir(directory))[0]!), "utf8")).releasedRunner).toBeUndefined();
return;
}
if (journalFailure) {
const directory = join(resolvePaperclipInstanceRoot(), "runtime/paperclip-runner/sessions");
const path = join(directory, (await readdir(directory))[0]!);
await rename(path, `${path}.saved`);
await mkdir(path);
let finished = false;
void execute.finally(() => { finished = true; }).catch(() => undefined);
allowRelease();
await new Promise(resolve => setImmediate(resolve));
expect(finished).toBe(false);
await expect(executePaperclipNativeSession({ db: leaseDb(next), execution: next,
runnerInstanceId: source.runnerInstanceId, useRunnerd: true, runnerIngressAuthorized: true,
managedAiCredentialHome: home, managedAiCredentialIdentity: "selected-revision", managedAiAccountIdentity: "selected-account",
runnerExecutionTarget: { ...target, remoteCwd: "different-workspace", runnerTask: nextTask } })).rejects.toThrow("native_session_supervisor_busy");
expect(nextTask).not.toHaveBeenCalled();
await vi.waitFor(() => expect(close).toHaveBeenCalledOnce());
expect(readNativeSessionIdleWork()).toBe("present");
expect(finished).toBe(false);
await rm(path, { recursive: true });
await rename(`${path}.saved`, path);
expect(JSON.parse(await readFile(path, "utf8")).releasedRunner).toBeUndefined();
allowPhysicalStop();
await expect(execute).resolves.toMatchObject({ sessionId: source.normalizedSessionId });
expect(readNativeSessionIdleWork()).toBe("none");
expect(detachControllerForRestart).not.toHaveBeenCalled();
return;
}
allowRelease();
await expect(execute).resolves.toMatchObject({ sessionId: source.normalizedSessionId });
expect(readNativeSessionIdleWork()).toBe("none");
@@ -19748,21 +19745,20 @@ describe("runnerd provider runtime wiring", () => {
const files = await readdir(directory);
const path = join(directory, files[0]!);
const envelope = JSON.parse(await readFile(path, "utf8"));
expect(envelope.releasedRunner).toMatchObject({ source, taskId: "retained-task", scopeDigest: expect.any(String) });
expect(envelope.releasedRunner).toBeUndefined();
expect(JSON.stringify(envelope)).not.toContain("synthetic-fixture");
if (!unknown) {
const calls = owners.mock.calls.length;
for (const changed of [{ remoteCwd: "different-workspace" }, { runnerTaskProjectIds: ["different-project"] }]) {
await expect(executePaperclipNativeSession({ db: leaseDb(next), execution: next,
runnerInstanceId: source.runnerInstanceId, useRunnerd: true, runnerIngressAuthorized: true,
managedAiCredentialHome: home, managedAiCredentialIdentity: "selected-revision", managedAiAccountIdentity: "selected-account",
runnerExecutionTarget: { ...target, ...changed, runnerTask: nextTask },
runnerEnvironment: provider === "claude" ? { ANTHROPIC_API_KEY: "synthetic-fixture" } : {} })).rejects.toThrow("released_owner_scope_mismatch");
}
await expect(executePaperclipNativeSession({ db: leaseDb(next), execution: next,
runnerInstanceId: source.runnerInstanceId, useRunnerd: true, runnerIngressAuthorized: true,
managedAiCredentialHome: home, managedAiCredentialIdentity: "selected-revision", managedAiAccountIdentity: "selected-account",
runnerExecutionTarget: { ...target, runnerTask: nextTask,
sandboxLeaseAcquisition: { ...target.sandboxLeaseAcquisition, providerLeaseId: "different-task" } },
runnerEnvironment: provider === "claude" ? { ANTHROPIC_API_KEY: "synthetic-fixture" } : {} })).rejects.toThrow("released_owner_scope_mismatch");
expect(owners).toHaveBeenCalledTimes(calls);
expect(nextTask).not.toHaveBeenCalled();
expect(state.execute).toHaveBeenCalledTimes(1);
expect(JSON.parse(await readFile(path, "utf8")).releasedRunner).toEqual(envelope.releasedRunner);
expect(JSON.parse(await readFile(path, "utf8")).releasedRunner).toBeUndefined();
}
if (retirement === "environment deletion") {
expect(await closeWarmNativeSessionsForEnvironment({ environmentId: target.environmentId, reason: "environment deleted" }))
@@ -19777,7 +19773,7 @@ describe("runnerd provider runtime wiring", () => {
expect(await closeIdleWarmNativeSessionsForRestart()).toMatchObject({ closed: 0, busy: 0, failed: 1 });
expect(close).not.toHaveBeenCalled();
expect(readNativeSessionIdleWork()).toBe("present");
expect(JSON.parse(await readFile(path, "utf8")).releasedRunner).toEqual(envelope.releasedRunner);
expect(JSON.parse(await readFile(path, "utf8")).releasedRunner).toBeUndefined();
}
detachControllerForRestart.mockResolvedValue(undefined);
}
@@ -19788,7 +19784,7 @@ describe("runnerd provider runtime wiring", () => {
expect(readNativeSessionIdleWork()).toBe("none");
expect(close).not.toHaveBeenCalled();
expect(task.mock.calls.map(([operation]) => (operation as { kind: string }).kind)).toEqual(["describe"]);
expect(JSON.parse(await readFile(path, "utf8")).releasedRunner).toEqual(envelope.releasedRunner);
expect(JSON.parse(await readFile(path, "utf8")).releasedRunner).toBeUndefined();
if (provider === "codex" && !unknown) {
const inspected = vi.spyOn(remoteWarmRecoveryRuntime, "inspectRemoteWarmSessionRecovery").mockImplementation(async request => {
request.loadCheckpoint(current);
@@ -19805,18 +19801,15 @@ describe("runnerd provider runtime wiring", () => {
{ runnerExecutionTarget: { ...target, runnerTaskProjectIds: ["different-project"] } },
{ runnerExecutionTarget: { ...target, remoteCwd: "different-workspace" } },
{ runnerExecutionTarget: { ...target, sandboxLeaseAcquisition: { ...target.sandboxLeaseAcquisition, providerLeaseId: "different-task" } } },
]) await expect(executePaperclipNativeSession({ ...base, ...changed })).rejects.toThrow("released_owner_scope_mismatch");
]) await expect(executePaperclipNativeSession({ ...base, ...changed })).rejects.toThrow("fixture completed-source proof checked");
await writeFile(path, JSON.stringify({ ...envelope,
releasedRunner: { source, taskId: "retained-task", scopeDigest: `sha256:${"0".repeat(64)}` } }));
await expect(executePaperclipNativeSession(base)).rejects.toThrow("fixture completed-source proof checked");
expect(inspected.mock.calls.at(-1)![0].loadCheckpoint(current)).toMatchObject({ identity: envelope.snapshot.identity });
expect(owners).toHaveBeenCalledTimes(calls);
expect(state.execute).toHaveBeenCalledTimes(1);
} finally { inspected.mockRestore(); }
}
await owners.mock.calls.at(-1)![0].onResumed!(source);
expect(JSON.parse(await readFile(path, "utf8")).releasedRunner).toBeUndefined();
const replacement = { ...envelope, snapshot: { ...envelope.snapshot, identity: { ...envelope.snapshot.identity, runId: "new-owner" } },
releasedRunner: { ...envelope.releasedRunner, source: { ...source, runId: "new-owner" } } };
await writeFile(path, JSON.stringify(replacement));
await expect(owners.mock.calls.at(-1)![0].onResumed!(source)).rejects.toThrow("released_source_mismatch");
expect(JSON.parse(await readFile(path, "utf8")).releasedRunner).toEqual(replacement.releasedRunner);
} finally {
detachControllerForRestart.mockResolvedValue(undefined);
registerRunStartHandover(null);
@@ -19827,7 +19820,7 @@ describe("runnerd provider runtime wiring", () => {
it.each((["codex", "claude"] as const).flatMap(provider => (["current", "stale", ...(provider === "codex" ? ["foreign runner", "foreign lease"] : [])] as const)
.map(receipt => [provider, receipt] as const)))(
"records the confirmed %s source after external checkpoint registration and attachment (receipt=%s)", async (provider, receipt) => {
"accepts only the attached %s source's release receipt after external checkpoint registration (receipt=%s)", async (provider, receipt) => {
const invalidReceipt = receipt !== "current";
await closeIdleWarmNativeSessionsForRestart();
const previousHome = process.env.PAPERCLIP_HOME;
@@ -19899,7 +19892,6 @@ describe("runnerd provider runtime wiring", () => {
.toBe("paperclip.runner.external-control-plane-state.v1");
} else {
expect(options.existingSession).toBe(session);
await owners.mock.calls[0]![0].onResumed!(source);
authority.rotateRunIdentity(successor);
await register!(authority, successor);
await writeFile(join(root, "runner/runner-state.json"), JSON.stringify(durableRunnerState(successor, "ready")));
@@ -19931,7 +19923,7 @@ describe("runnerd provider runtime wiring", () => {
expect(release).toHaveBeenCalledOnce();
const directory = join(resolvePaperclipInstanceRoot(), "runtime/paperclip-runner/sessions");
const path = join(directory, (await readdir(directory))[0]!);
expect(JSON.parse(await readFile(path, "utf8")).releasedRunner.source).toEqual(source);
expect(JSON.parse(await readFile(path, "utf8")).releasedRunner).toBeUndefined();
following = run(next);
void following.catch(() => undefined);
if (invalidReceipt) {
@@ -19944,7 +19936,7 @@ describe("runnerd provider runtime wiring", () => {
} else {
await expect(following).resolves.toMatchObject({ sessionId: source.normalizedSessionId });
expect(release).toHaveBeenCalledTimes(2);
expect(JSON.parse(await readFile(path, "utf8")).releasedRunner.source).toEqual(successor);
expect(JSON.parse(await readFile(path, "utf8")).releasedRunner).toBeUndefined();
expect(close).not.toHaveBeenCalled();
}
} finally {
@@ -337,6 +337,7 @@ import {
type NativeStatusDecision,
} from "./status-arbiter.js";
import { conflict, HttpError } from "../../errors.js";
import { planReviewConfirmationInput } from "./native-plan-review-card.js";
import { redactSensitiveText } from "../../redaction.js";
import { classifyRemoteConnectionError } from "../remote-connection-failure.js";
import { resolvePaperclipRunnerBinary, resolvePaperclipRunnerBinaryAsync, resolveRemotePaperclipRunnerBinary, verifiedBundledRemoteRunnerBinary } from "./native-codex-runner.js";
@@ -2324,33 +2325,15 @@ export async function synchronizeCompletedProviderPlan(input: {
id: input.execution.binding.issueId,
companyId: input.execution.binding.companyId,
},
{
kind: "request_confirmation",
idempotencyKey: `runner-plan-approval:v1:${input.execution.binding.runId}:${planId}:${providerRevision}:${digest}`,
planReviewConfirmationInput({
issueId: input.execution.binding.issueId,
documentId: current.id,
revisionId: revision.id,
revisionNumber: revision.revisionNumber,
sourceRunId: input.execution.binding.runId,
title: `Review plan revision ${revision.revisionNumber}`,
summary: "Review the synchronized Paperclip plan.",
continuationPolicy: "wake_assignee",
payload: {
version: 1,
prompt: `Approve plan revision ${revision.revisionNumber}?`,
detailsMarkdown:
"The completed provider plan has been synchronized to the canonical Plan document.",
acceptLabel: "Approve plan",
rejectLabel: "Request changes",
rejectRequiresReason: true,
supersedeOnUserComment: false,
target: {
type: "issue_document",
issueId: input.execution.binding.issueId,
documentId: current.id,
key: "plan",
revisionId: revision.id,
revisionNumber: revision.revisionNumber,
label: `Plan v${revision.revisionNumber}`,
},
},
} as never,
source: "provider_plan",
idempotencyKey: `runner-plan-approval:v1:${input.execution.binding.runId}:${planId}:${providerRevision}:${digest}`,
}) as never,
{
agentId: input.execution.binding.agentId,
runId: input.execution.binding.runId,
@@ -8796,49 +8779,23 @@ function legacyNativeSessionCheckpointPath(
);
}
type ReleasedWarmRunner = { source: DurableRecoveryIdentity; taskId: string; scopeDigest: string };
const RELEASED_SOURCE_KEYS = ["runnerInstanceId", "environmentLeaseId", "runId", "normalizedSessionId", "turnId", "itemId"] as const;
function releasedWarmScope(input: Parameters<typeof executePaperclipNativeSession>[0]): string {
const target = input.runnerExecutionTarget;
return nativeSha256({ companyId: input.execution.binding.companyId, agentId: input.execution.binding.agentId,
environmentId: target?.kind === "remote" ? target.environmentId ?? null : null, workspace: nativeSessionWorkspaceScope(input.execution),
cwd: input.execution.workspace.cwd, remoteCwd: target?.kind === "remote" ? target.remoteCwd : null,
projectIds: target?.kind === "remote" && target.transport === "sandbox" ? target.runnerTaskProjectIds ?? [] : [],
accountIdentity: input.managedAiAccountIdentity ?? null, credentialIdentity: input.managedAiCredentialIdentity ?? null });
function releasedDurableIdentity(identity: Record<string, unknown> | null): DurableRecoveryIdentity | undefined {
if (!identity || RELEASED_SOURCE_KEYS.some(key => typeof identity[key] !== "string" || !identity[key])) return undefined;
const field = (key: typeof RELEASED_SOURCE_KEYS[number]) => identity[key] as string;
return { runnerInstanceId: field("runnerInstanceId"), environmentLeaseId: field("environmentLeaseId"), runId: field("runId"),
normalizedSessionId: field("normalizedSessionId"), turnId: field("turnId"), itemId: field("itemId") };
}
function requireReleasedWarmScope(input: Parameters<typeof executePaperclipNativeSession>[0],
proof: ReleasedWarmRunner | undefined, identity: unknown): DurableRecoveryIdentity {
function releasedWarmSource(input: Parameters<typeof executePaperclipNativeSession>[0], taskId: string | null): DurableRecoveryIdentity {
const target = input.runnerExecutionTarget;
if (!proof || target?.kind !== "remote" || target.transport !== "sandbox" || !target.runnerTask
|| proof.taskId !== target.sandboxLeaseAcquisition?.providerLeaseId
|| proof.scopeDigest !== releasedWarmScope(input) || canonicalJson(proof.source) !== canonicalJson(identity)) {
const source = releasedDurableIdentity(readRunnerdDurableIdentity(scopedRunnerdStateRoot(input.execution)));
if (!source || target?.kind !== "remote" || target.transport !== "sandbox" || !target.runnerTask
|| taskId !== target.sandboxLeaseAcquisition?.providerLeaseId) {
throw new Error("native_session_released_owner_scope_mismatch");
}
return proof.source;
}
function readWarmNativeEnvelope(execution: NativeExecutionInput): Record<string, unknown> | null {
const path = nativeSessionCheckpointPath(execution);
if (!existsSync(path)) return null;
const envelope = record(JSON.parse(readBoundedNativeFile(path, NATIVE_WARM_CHECKPOINT_MAX_BYTES,
"native_session_supervisor_checkpoint_too_large").toString("utf8")));
if (envelope.schema !== "paperclip.native-session-supervisor.v1") throw new Error("native_session_supervisor_checkpoint_mismatch");
return envelope;
}
function releasedWarmRunner(envelope: Record<string, unknown> | null): ReleasedWarmRunner | undefined {
if (!envelope || envelope.releasedRunner === undefined) return undefined;
const proof = record(envelope.releasedRunner), source = record(proof.source);
const snapshot = record(envelope.snapshot), identity = record(snapshot.identity);
for (const key of ["runnerInstanceId", "environmentLeaseId", "runId", "normalizedSessionId", "turnId", "itemId"]) {
if (typeof source[key] !== "string" || !source[key]) throw new Error("native_session_released_source_mismatch");
}
if (typeof proof.taskId !== "string" || !proof.taskId || typeof proof.scopeDigest !== "string"
|| identity.runId !== source.runId || identity.sessionId !== source.normalizedSessionId) {
throw new Error("native_session_released_source_mismatch");
}
return proof as ReleasedWarmRunner;
return source;
}
function writeWarmNativeEnvelope(execution: NativeExecutionInput, envelope: Record<string, unknown>): void {
@@ -8849,38 +8806,15 @@ function writeWarmNativeEnvelope(execution: NativeExecutionInput, envelope: Reco
chmodSync(path, 0o600);
}
function updateReleasedWarmRunner(execution: NativeExecutionInput, source: DurableRecoveryIdentity,
taskId: string, proof: ReleasedWarmRunner | null): void {
const envelope = readWarmNativeEnvelope(execution);
const previous = releasedWarmRunner(envelope);
if (!envelope) {
if (proof) throw new Error("native_session_supervisor_checkpoint_missing");
return;
}
if (!proof && !previous) return;
const identity = record(record(envelope.snapshot).identity);
if (identity.companyId !== execution.binding.companyId || identity.agentId !== execution.binding.agentId
|| identity.runId !== source.runId || identity.sessionId !== source.normalizedSessionId
|| (previous && (previous.taskId !== taskId || canonicalJson(previous.source) !== canonicalJson(source)))) {
throw new Error("native_session_released_source_mismatch");
}
if (proof) envelope.releasedRunner = proof;
else delete envelope.releasedRunner;
writeWarmNativeEnvelope(execution, envelope);
}
function persistWarmNativeCheckpoint(
execution: NativeExecutionInput,
configDigest: string,
snapshot: PersistedNativeSession,
processConfigDigest?: string,
): void {
const previous = releasedWarmRunner(readWarmNativeEnvelope(execution));
writeWarmNativeEnvelope(execution, {
schema: "paperclip.native-session-supervisor.v1", configDigest, processConfigDigest,
updatedAt: new Date().toISOString(), snapshot,
...(previous && previous.source.runId === snapshot.identity.runId
&& previous.source.normalizedSessionId === snapshot.identity.sessionId ? { releasedRunner: previous } : {}),
});
}
@@ -11252,10 +11186,11 @@ async function executePaperclipNativeSessionAttempt(
}
const cachedReleasedOwner = warmNativeSessions.get(nativeSessionScopeKey(input.execution));
if (cachedReleasedOwner?.released) {
const proof = portableSource ? undefined : releasedWarmRunner(readWarmNativeEnvelope(input.execution));
const identity = readRunnerdDurableIdentity(scopedRunnerdStateRoot(input.execution));
const durable = portableSource ? undefined : releasedDurableIdentity(identity);
const target = input.runnerExecutionTarget;
const source = portableSource ?? (proof && { taskId: proof.taskId, identity: proof.source });
const source = portableSource ?? (durable && cachedReleasedOwner.pluginTaskId
? { taskId: cachedReleasedOwner.pluginTaskId, identity: durable } : undefined);
if (source && target?.kind === "remote" && target.transport === "sandbox" && target.runnerTask && target.leaseId
&& (portableSource || target.sandboxLeaseAcquisition?.outcome === "created")
&& source.taskId !== target.sandboxLeaseAcquisition?.providerLeaseId) {
@@ -11265,8 +11200,7 @@ async function executePaperclipNativeSessionAttempt(
|| cachedReleasedOwner.preparingRunId && cachedReleasedOwner.preparingRunId !== input.execution.binding.runId
|| cachedReleasedOwner.instructionPreparationRunId && !ownInstructionPreparation
|| cachedReleasedOwner.closeOnReleaseReason) throw new Error("native_session_supervisor_busy");
if (source.taskId !== cachedReleasedOwner.pluginTaskId || cachedReleasedOwner.runId !== identity?.runId ||
(proof && (proof.scopeDigest !== releasedWarmScope(input) || canonicalJson(proof.source) !== canonicalJson(identity)))) {
if (source.taskId !== cachedReleasedOwner.pluginTaskId || cachedReleasedOwner.runId !== identity?.runId) {
throw new Error("native_session_released_owner_scope_mismatch");
}
const wasBusy = cachedReleasedOwner.busy;
@@ -11284,7 +11218,7 @@ async function executePaperclipNativeSessionAttempt(
}
forgetWarmNativeSession(nativeSessionScopeKey(input.execution), cachedReleasedOwner);
} finally { cachedReleasedOwner.busy = wasBusy; }
} else requireReleasedWarmScope(input, proof, identity);
} else releasedWarmSource(input, cachedReleasedOwner.pluginTaskId ?? null);
}
if (input.useRunnerd && canRecoverWarmOwner && !input.backend &&
input.runnerExecutionTarget?.kind === "remote" &&
@@ -11320,7 +11254,6 @@ async function executePaperclipNativeSessionAttempt(
}
if (durableIdentityMatchesSession(identity, input.execution) && identity.runId !== input.execution.binding.runId &&
runnerdAuthorityLifecycleWithVerifiedBackup({ root, identity, execution: input.execution, allowVerifiedBackup: true }) !== "suspended") {
let releasedSource = portableSource?.identity;
remoteWarmRecovery = await inspectRemoteWarmSessionRecovery({
db: input.db, execution: input.execution, target: input.runnerExecutionTarget, identity,
portableSourceTaskId: portableSource?.taskId,
@@ -11328,19 +11261,15 @@ async function executePaperclipNativeSessionAttempt(
resolve(root, "control-plane", "control-plane-state.json"), NATIVE_CONTROL_PLANE_STATE_MAX_BYTES,
"runner_durable_identity_too_large").toString("utf8"))),
matchesExecution: previous => matchesRemoteWarmExecution(previous, input.execution, input.toolRefreshOnResume),
loadCheckpoint: previous => {
if (!portableSource) {
const proof = releasedWarmRunner(readWarmNativeEnvelope(previous));
if (proof) releasedSource = requireReleasedWarmScope(input, proof, identity);
}
return loadWarmNativeCheckpoint(previous, nativeSessionConfigDigest(previous, "remote"), "remote");
},
loadCheckpoint: previous => loadWarmNativeCheckpoint(previous, nativeSessionConfigDigest(previous, "remote"), "remote"),
canReuseProcess: previous => !portableSource && !needsCoreGitHubAccess(input) &&
nativeSessionConfigDigest(previous, "remote") === nativeSessionConfigDigest(input.execution, "remote") && canReuseNativeProcess(input,
record(JSON.parse(readBoundedNativeFile(nativeSessionCheckpointPath(previous),
NATIVE_WARM_CHECKPOINT_MAX_BYTES, "native_session_supervisor_checkpoint_too_large").toString("utf8"))).processConfigDigest),
}) ?? undefined;
if (remoteWarmRecovery) {
const releasedSource = portableSource?.identity
?? (pluginTaskDescription?.releaseResumeVersion === 1 ? releasedDurableIdentity(identity) : undefined);
remoteWarmRecovery.releasedSource = releasedSource;
if (releasedSource) {
const header = await loadNativeRunnerCheckpointHeader(input.db, remoteWarmRecovery.previousExecution.binding).catch((error: unknown) => {
@@ -12318,6 +12247,7 @@ async function executePaperclipNativeSessionAttempt(
let reusingReleasedRunner = false;
let relaunchReleased: { owner?: ReturnType<typeof createPluginRunnerTaskOwner>; source: DurableRecoveryIdentity;
runner: { version: string; digest: string }; published?: true } | undefined;
let releasedRecoveryOwner: ReturnType<typeof createPluginRunnerTaskOwner> | undefined;
let managedCredentialSession: NativeSession | undefined;
let githubAccess: NativeGitHubAccess | undefined;
let releaseGitHubRun: (() => void) | undefined;
@@ -12340,8 +12270,7 @@ async function executePaperclipNativeSessionAttempt(
const registered = warmNativeSessions.get(warmSessionId);
const entry = registered && forgetUnretiredOwnerOnOtherSandbox(warmSessionId, registered, input.runnerExecutionTarget)
? undefined : registered;
const releasedSource = entry?.released ? requireReleasedWarmScope(input, releasedWarmRunner(readWarmNativeEnvelope(input.execution)),
readRunnerdDurableIdentity(scopedRunnerdStateRoot(input.execution))) : undefined;
const releasedSource = entry?.released ? releasedWarmSource(input, entry.pluginTaskId ?? null) : undefined;
if (entry || remoteWarmRecovery?.releasedSource) {
if (input.execution.provider.kind === "codex" ||
(input.execution.provider.kind === "acpx" && input.execution.provider.agent === "claude")) {
@@ -12644,7 +12573,10 @@ async function executePaperclipNativeSessionAttempt(
pluginTaskDescription,
retainedPluginTaskOwner: existingWarmSession ? pluginTaskSessionOwners.get(existingWarmSession) : relaunchReleased?.owner,
relaunchReleased: relaunchReleased ? { source: relaunchReleased.source, runner: relaunchReleased.runner } : undefined,
onPluginTaskOwner: owner => { if (relaunchReleased && !relaunchReleased.owner) relaunchReleased.owner = owner; },
onPluginTaskOwner: owner => {
if (relaunchReleased && !relaunchReleased.owner) relaunchReleased.owner = owner;
else if (remoteWarmRecovery?.releasedSource && !releasedRecoveryOwner) releasedRecoveryOwner = owner;
},
beginRetainedRunAttachment: existingWarmSession && reusingReleasedRunner ? beginRetainedRunAttachment(existingWarmSession) : undefined,
durableEnvironmentLeaseId: durableRunnerBinding?.environmentLeaseId,
remoteWarmRecovery: remoteWarmRecovery ? (recovery => ({
@@ -12678,13 +12610,22 @@ async function executePaperclipNativeSessionAttempt(
input.useRunnerd && input.backend === undefined
? await timeController("backend_setup", () => executionContext ? executionContext.wait(createExecutionBackend) : createExecutionBackend())
: null;
let releasedRecoveryUnavailable: Error | undefined;
let recovered: Awaited<ReturnType<NonNullable<NonNullable<typeof runnerdBackend>["recoverSession"]>>> | undefined;
if (remoteWarmRecovery) {
const recovery = remoteWarmRecovery;
if (executionContext) await executionContext.wait(() => recovery.revalidate(leaseOwner));
else await recovery.revalidate(leaseOwner);
const recovered = await runnerdBackend?.recoverSession?.(remoteWarmRecovery.checkpoint, {
signal: executionContext?.signal ?? new AbortController().signal,
});
try {
recovered = await runnerdBackend?.recoverSession?.(remoteWarmRecovery.checkpoint, {
signal: executionContext?.signal ?? new AbortController().signal,
});
} catch (error) {
if (!recovery.releasedSource || !(error instanceof Error) || error.message !== "native_runner_reuse_unavailable") throw error;
releasedRecoveryUnavailable = error;
}
}
if (remoteWarmRecovery && !releasedRecoveryUnavailable) {
if (!recovered?.recovered || !recovered.session) throw new Error("runner_state_identity_mismatch: remote_warm_session_unproven");
const movedSession = remoteWarmRecovery.portableSourceTaskId !== undefined;
// A portable resume already starts a new Runner. Its run attachment
@@ -12733,12 +12674,14 @@ async function executePaperclipNativeSessionAttempt(
)).then(rows => rows[0])
: null;
let remoteCleanupLease = await readRemoteCleanupLease();
const continueAfterUnavailableReuse = async (error: unknown) => {
const continueAfterUnavailableReuse = async (error: unknown, recovering = false) => {
const target = input.runnerExecutionTarget;
const retainedOwner = existingWarmSession ? pluginTaskSessionOwners.get(existingWarmSession) : relaunchReleased?.owner;
const releasedRecovery = recovering && remoteWarmRecovery?.releasedSource ? remoteWarmRecovery : undefined;
const retainedOwner = existingWarmSession ? pluginTaskSessionOwners.get(existingWarmSession)
: relaunchReleased?.owner ?? (releasedRecovery ? releasedRecoveryOwner : undefined);
if (!(error instanceof Error) || error.message !== "native_runner_reuse_unavailable" || !retainedOwner
|| retainedOwner.retiredBeforeClaim() !== true
|| remoteWarmRecovery || warmConfigDigest === null || target?.kind !== "remote" || target.transport !== "sandbox"
|| (remoteWarmRecovery && !releasedRecovery) || warmConfigDigest === null || target?.kind !== "remote" || target.transport !== "sandbox"
|| !target.runnerTask || runnerdBackend === null) return false;
const retainedTaskId = target.sandboxLeaseAcquisition?.providerLeaseId;
if (existingWarmSession) await existingWarmSession.close({ reason: "retained Runner was unavailable for reuse" });
@@ -12750,6 +12693,16 @@ async function executePaperclipNativeSessionAttempt(
}
}
relaunchReleased = undefined;
if (releasedRecovery) {
if (remoteWarmRecoveryPending) {
if (executionContext) await executionContext.wait(() => releasedRecovery.revalidate(leaseOwner));
else await releasedRecovery.revalidate(leaseOwner);
}
remoteWarmRecovery = undefined;
remoteWarmRecoveryPending = false;
releasedRecoveryOwner = undefined;
await finishStartupContextForFallback();
}
const inspect = () => target.runnerTask!({ kind: "describe" }, executionContext ? { executionContext } : undefined);
const description = environmentTaskResultSchema.parse(await (executionContext ? executionContext.wait(inspect) : inspect()));
if (description.kind !== "description" || description.taskId === retainedTaskId) return false;
@@ -12761,6 +12714,7 @@ async function executePaperclipNativeSessionAttempt(
remoteCleanupLease = await readRemoteCleanupLease();
return true;
};
if (releasedRecoveryUnavailable && !await continueAfterUnavailableReuse(releasedRecoveryUnavailable, true)) throw releasedRecoveryUnavailable;
const portTarget = input.runnerExecutionTarget;
if (input.useRunnerd && !input.backend && !existingWarmSession && portTarget?.kind === "remote" && portTarget.transport === "sandbox"
&& portTarget.runner && !portTarget.runnerTask && portTarget.sandboxLeaseAcquisition?.outcome === "resumed"
@@ -14183,11 +14137,8 @@ async function executePaperclipNativeSessionAttempt(
|| entry.pluginTaskId !== target.sandboxLeaseAcquisition?.providerLeaseId) {
throw new Error("native_session_released_source_mismatch");
}
const source = operation.identity;
updateReleasedWarmRunner(input.execution, source, entry.pluginTaskId,
{ source, taskId: entry.pluginTaskId, scopeDigest: releasedWarmScope(input) });
} catch {
entry.closeOnReleaseReason = "released Runner source proof could not be verified or saved";
entry.closeOnReleaseReason = "released Runner source could not be verified";
await closeWarmNativeSession(entry, entry.closeOnReleaseReason);
forgetWarmNativeSession(scope, entry);
return;
@@ -17060,8 +17011,6 @@ async function createRunnerdBackendWithinSessionClaim(
releasedSource: input.remoteWarmRecovery?.releasedSource,
releasedSourceRunner: input.remoteWarmRecovery?.releasedSourceRunner,
sessionHandoff: !!input.remoteWarmRecovery?.portableSourceTaskId,
onResumed: async source => updateReleasedWarmRunner(input.execution, source, input.remoteWarmRecovery?.portableSourceTaskId ?? description.taskId, null),
onRetired: async source => updateReleasedWarmRunner(input.execution, source, description.taskId, null),
adoptIdentity: adoptionIdentity ?? (adopting && prior ? {
runnerInstanceId: prior.runnerInstanceId, environmentLeaseId: prior.environmentLeaseId,
runId: prior.runId, normalizedSessionId: prior.normalizedSessionId,
@@ -0,0 +1,51 @@
import { describe, expect, it } from "vitest";
import type { NativeEvidenceAssessment } from "./evidence-classifier.js";
import { arbitrateNativeStatus } from "./status-arbiter.js";
import { PLAN_NOT_PRODUCED_REASON } from "./plan-mode-status.js";
const yieldedWait: NativeEvidenceAssessment = {
objectiveClaimSatisfied: false, objectiveSatisfied: false, allCriteriaSatisfied: false, verificationPassed: false,
hasFailedVerification: false, hasBlockingRemainingWork: false, reportedDisposition: "yielded",
summary: "Waiting for plan review", contractRevisionMatches: true, criterionAssessments: [],
verificationAssessments: [], verificationCaveats: [], acceptedEvidenceRefs: [], missingRequirements: [],
rejectedEvidence: [], unverifiableEvidence: [], blocker: null,
continuation: { kind: "response_wake", summary: "Waiting for plan review", idempotencyKey: "plan-review-wake-v1" },
attentionRequests: [], ignoredAttentionRequests: [],
} as NativeEvidenceAssessment;
const arbitrate = (overrides: Partial<Parameters<typeof arbitrateNativeStatus>[0]>) => arbitrateNativeStatus({
assessment: yieldedWait, terminalState: "succeeded", workspaceFinalizeStatus: "succeeded",
agentId: "agent", priorIssueStatus: "in_progress", ...overrides,
});
// Every way a Plan-mode response wait can settle leaves the user one current
// action (the review card is the gate) or schedules the agent to produce one.
describe("Plan-mode response wait settlement", () => {
it.each([
{ name: "assigned run, plan card open", input: { governanceGate: { kind: "interaction" as const, id: "card" } },
reasonCode: "governed_response_waiting", next: "card" },
{ name: "comment-started run, plan card open", input: { governanceGate: { kind: "interaction" as const, id: "card" }, boardResponseWaitAuthorized: true, boardResponseWaitOrigin: true },
reasonCode: "governed_response_waiting", next: "card" },
{ name: "assigned run, no plan", input: { planNotProduced: true },
reasonCode: PLAN_NOT_PRODUCED_REASON, next: "continuation" },
{ name: "comment-started run, no plan", input: { planNotProduced: true, boardResponseWaitAuthorized: true, boardResponseWaitOrigin: true },
reasonCode: PLAN_NOT_PRODUCED_REASON, next: "continuation" },
{ name: "comment-started run whose comment was superseded, no plan", input: { planNotProduced: true, boardResponseWaitOrigin: true },
reasonCode: PLAN_NOT_PRODUCED_REASON, next: "continuation" },
{ name: "second miss after the continuation", input: { planNotProduced: true, allowIncompleteContinuation: false },
reasonCode: PLAN_NOT_PRODUCED_REASON, next: "recovery" },
])("$name", ({ input, reasonCode, next }) => {
const decision = arbitrate(input);
expect(decision.reasonCode).toBe(reasonCode);
const kinds = decision.effects.map(effect => effect.kind);
if (next === "card") expect(kinds).toContain("create_interaction");
if (next === "continuation") expect(kinds).toContain("enqueue_continuation");
if (next === "recovery") expect(kinds).toContain("record_finalization_error");
});
it("leaves Standard-mode and conversation waits unchanged", () => {
expect(arbitrate({}).reasonCode).toBe("response_wake_waiting_for_input");
expect(arbitrate({ boardResponseWaitAuthorized: true }).reasonCode).toBe("board_response_waiting");
expect(arbitrate({ planNotProduced: true, isConversation: true }).reasonCode).not.toBe(PLAN_NOT_PRODUCED_REASON);
});
});
@@ -0,0 +1,36 @@
import type { NativeAuthoritativeIssueStatus, NativeStatusDecision } from "./status-arbiter.js";
export const PLAN_NOT_PRODUCED_REASON = "plan_mode_plan_not_produced";
/**
* Plan mode waits only on a plan review. A Plan-mode run that yields a
* response wait with no plan to review (none saved, or the current revision
* already answered) must not rest as a silent wait. The agent is asked once to
* save its plan (its review card then opens); after that, the task keeps its
* status and shows a recovery step.
*/
export function planNotProducedDecision(input: {
priorIssueStatus: NativeAuthoritativeIssueStatus;
agentId: string;
allowIncompleteContinuation?: boolean;
}): Omit<NativeStatusDecision, "policyVersion"> {
if (input.allowIncompleteContinuation === false) {
return {
statusAction: "preserve", toStatus: input.priorIssueStatus,
reasonCode: PLAN_NOT_PRODUCED_REASON, unblockDescriptor: null,
effects: [{ kind: "record_finalization_error", cause: PLAN_NOT_PRODUCED_REASON,
nextAction: "The agent finished in Plan mode without a new plan to review. Ask it to write the plan, or switch the task out of Plan mode.",
agentId: input.agentId }],
};
}
return {
statusAction: "in_progress", toStatus: "in_progress",
reasonCode: PLAN_NOT_PRODUCED_REASON, unblockDescriptor: null,
effects: [{
kind: "enqueue_continuation", continuationKind: "same_agent",
summary: "This task is in Plan mode and there is no new plan to review. Save your plan (or the revised plan) to this task's Plan document; Paperclip then asks the user to approve it. If you need an answer first, ask a question instead of waiting.",
// The bounded incomplete-report key: a second miss gets the recovery step.
idempotencyKey: "native-completion-incomplete", agentId: input.agentId,
}],
};
}
@@ -311,7 +311,7 @@ describeEmbeddedPostgres("plugin Runner eviction through the Core execution entr
const a = await execute(execution, leaseA); expect(a).toMatchObject({ exitCode: 0, timedOut: false });
await waitForCondition("automatic release A", () => releases.length === 1);
expect((await db.select().from(nativeRunResults).where(eq(nativeRunResults.runId, runId)))[0]).toMatchObject({ schemaStatus: "accepted", resultJson: { result: { reportedWorkDisposition: "done" } } });
expect(await proof()).toMatchObject({ source: releases[0], taskId: taskA });
expect(await proof()).toBeUndefined();
const providerSessionId = (await supervisor()).snapshot.providerSessionId;
expect(providerSessionId).toEqual(expect.any(String));
if (detached) await new Promise(done => setTimeout(done, detachedIdleTimeoutMs + 200));
@@ -401,7 +401,7 @@ describeEmbeddedPostgres("plugin Runner eviction through the Core execution entr
const runB = await admitNext();
if (denied || mode === "bare unavailable") return;
await waitForCondition("automatic release B", () => releases.length === 2);
expect(await proof()).toMatchObject({ source: releases[1], taskId: taskB });
expect(await proof()).toBeUndefined();
expect((await supervisor()).snapshot.providerSessionId).toBe(providerSessionId);
const methods = (await readFile(calls, "utf8")).trim().split(/\r?\n/);
expect(submissions).toBe(2);
@@ -248,7 +248,7 @@ describeEmbeddedPostgres("plugin Runner release/resume through the Core executio
await waitForCondition("parked Runner stopped", () => handle!.isExitConfirmed?.() === true);
const identity = { ...operation.identity, ...operation.runner };
const archived = join(runnerRoot, `archived-${operation.identity.runId}.json`);
const archivedState = await state();
const parkedState = await state();
await rename(join(runnerRoot, "runner-state.json"), archived);
const launch = submittedLaunch!.launch!;
listenPath = `/api/runner/v1/connect/${identity.runId}`;
@@ -260,8 +260,8 @@ describeEmbeddedPostgres("plugin Runner release/resume through the Core executio
...(harness === "claude" ? { acpxLaunchProfile: { authorityDigest: `sha256:${sha("fixture authority")}`, command: sidecar,
commandSha256: `sha256:${sha(await readFile(sidecar, "utf8"))}`, sidecarScript,
sidecarScriptSha256: `sha256:${sha(await readFile(sidecarScript, "utf8"))}` } } : {}) });
relaunches.push({ source: operation.identity, runId: identity.runId, archivedRunId: archivedState.runId });
return { kind: "resume", taskId, outcome: "resumed", runner: artifact, archivedState };
relaunches.push({ source: operation.identity, runId: identity.runId, archivedRunId: parkedState.runId });
return { kind: "resume", taskId, outcome: "resumed", runner: artifact };
}
if (operation.kind === "resume") {
expect(relaunch).toBe(false);
@@ -310,7 +310,7 @@ describeEmbeddedPostgres("plugin Runner release/resume through the Core executio
const a = await execute(execution, leaseA); expect(a).toMatchObject({ exitCode: 0, timedOut: false });
await waitForCondition("automatic release A", () => releases.length === 1);
expect((await db.select().from(nativeRunResults).where(eq(nativeRunResults.runId, runId)))[0]).toMatchObject({ schemaStatus: "accepted", resultJson: { result: { reportedWorkDisposition: "done" } } });
expect(await proof()).toMatchObject({ source: releases[0], taskId });
expect(await proof()).toBeUndefined();
const providerSessionId = (await supervisor()).snapshot.providerSessionId;
expect(providerSessionId).toEqual(expect.any(String));
const pid = handle!.child.pid;
@@ -324,7 +324,7 @@ describeEmbeddedPostgres("plugin Runner release/resume through the Core executio
expect(await closeIdleWarmNativeSessionsForRestart()).toEqual({ closed: 0, busy: 0, failed: 0, failures: [] });
} else await new Promise(done => setTimeout(done, adoptedIdleTimeoutMs + 200));
expect(stops).toBe(0); expect(handle!.isExitConfirmed?.()).toBe(false);
expect(await proof()).toMatchObject({ source: releases[0], taskId });
expect(await proof()).toBeUndefined();
}
expect(readNativeSessionIdleWork()).toBe("none");
await reconcileNativeFinalizations(db, [runId]);
@@ -358,7 +358,7 @@ describeEmbeddedPostgres("plugin Runner release/resume through the Core executio
expect(handle!.isExitConfirmed!()).toBe(true);
expect((await readFile(calls, "utf8")).split(/\r?\n/).filter(method => method === "turn/start")).toHaveLength(1);
expect((await db.select().from(nativeRunResults).where(eq(nativeRunResults.runId, runB)))).toHaveLength(0);
expect(releases).toHaveLength(1); expect((await proof())?.source.runId).not.toBe(runB);
expect(releases).toHaveLength(1); expect(await proof()).toBeUndefined();
return runB;
}
expect(await pendingFollowup).toMatchObject({ exitCode: 0, timedOut: false });
@@ -369,7 +369,7 @@ describeEmbeddedPostgres("plugin Runner release/resume through the Core executio
const runB = await admitNext();
if (cancellation) return;
await waitForCondition("automatic release B", () => releases.length === 2);
expect(await proof()).toMatchObject({ source: releases[1], taskId });
expect(await proof()).toBeUndefined();
expect((await supervisor()).snapshot.providerSessionId).toBe(providerSessionId);
expect(adoption).toHaveBeenCalledTimes(adopted ? 1 : 0);
if (adopted) expect(adoption.mock.calls[0]![0]).toMatchObject({ identity: releases[0], execution: { binding: { runId: runB } } });
@@ -377,7 +377,7 @@ describeEmbeddedPostgres("plugin Runner release/resume through the Core executio
if (adopted) {
runC = await admitNext();
await waitForCondition("automatic release C", () => releases.length === 3);
expect(releases[2]!.runId).toBe(runC); expect(await proof()).toMatchObject({ source: releases[2], taskId });
expect(releases[2]!.runId).toBe(runC); expect(await proof()).toBeUndefined();
expect((await supervisor()).snapshot.providerSessionId).toBe(providerSessionId);
expect(adoption).toHaveBeenCalledTimes(1);
}
@@ -615,17 +615,11 @@ describe("plugin Runner release/resume facade", () => {
it.each([
["the parked build", undefined],
["a relaunched build", { version: "0.4.1", digest: `sha256:${"b".repeat(64)}` }],
])("clears the released Runner proof after a resume on %s, once Core saved a relaunched build", async (_label, runner) => {
])("passes the provider's resume outcome through on %s", async (_label, runner) => {
const task = vi.fn(async (): Promise<unknown> => ({ kind: "resume", taskId: "task", outcome: "resumed", ...(runner ? { runner } : {}) }));
const onResumed = vi.fn(async () => {});
const owner = createPluginRunnerTaskOwner({ ...input("codex"), task, onResumed, resumeRelaunchedRunnerVersion: 1 });
const owner = createPluginRunnerTaskOwner({ ...input("codex"), task, resumeRelaunchedRunnerVersion: 1 });
const outcome = await owner.driver.releaseResume!.resume(requirements.identity, "transient-ticket");
if (runner) {
expect(outcome).toEqual({ outcome: "resumed", runner, settled: expect.any(Function) });
expect(onResumed).not.toHaveBeenCalled();
if (typeof outcome === "object") await outcome.settled?.();
} else expect(outcome).toBe("resumed");
expect(onResumed).toHaveBeenCalledExactlyOnceWith(requirements.identity);
expect(outcome).toEqual(runner ? { outcome: "resumed", runner } : "resumed");
});
it("resumes with the credential resolved for the rebound claimant run", async () => {
@@ -805,8 +799,6 @@ describe("plugin Runner relaunch as the claimant run", () => {
const next = { ...source, runId: "next-run", turnId: "turn-next-run", itemId: "item-next-run" };
const parked = { version: "0.4.0", digest: `sha256:${"c".repeat(64)}` };
const build = { version: "0.4.1", digest: `sha256:${"b".repeat(64)}` };
const settledCut = { schema: "paperclip.runner.durable.state.v1", ...source, lifecycle: "ready", nextSourceSeq: 4, ackedSourceSeq: 3,
outbox: [], pendingTerminalDelivery: null, processedCommands: {} };
const base = { taskId: "task", projectIds: ["00000000-0000-4000-8000-000000000001"], projectAuthCheckVersion: 1 as const, harness: "codex", warmTaskVersion: 1 as const, releaseResumeVersion: 1 as const,
accountIdentity: "selected-account", credentialIdentity: "selected-credential" };
const relaunchSpec = (): RunnerProcessLaunchSpec => {
@@ -814,14 +806,14 @@ describe("plugin Runner relaunch as the claimant run", () => {
return { ...spec, nativeRunner: { ...spec.nativeRunner!, identity: next, lifecyclePolicy: { mode: "warm", idleTimeoutMs: 60_000 } } };
};
async function relaunchOwner(resume: (operation: any) => unknown,
options: { resumeIdentityVersion?: 1; onResumed?: () => Promise<void>; fresh?: true } = { resumeIdentityVersion: 1 }) {
options: { resumeIdentityVersion?: 1; fresh?: true } = { resumeIdentityVersion: 1 }) {
const { task } = provider();
const perform = task.getMockImplementation()!;
task.mockImplementation(async operation => operation.kind === "resume" ? resume(operation) : perform(operation));
const close = vi.fn(async () => {});
ingress.connect.mockReset().mockReturnValue({ ready: Promise.resolve(), quiesce: vi.fn(), close });
const relaunchInput = { ...base, task, authorityRunId: next.runId, resumeRelaunchedRunnerVersion: 1 as const,
resumeIdentityVersion: options.resumeIdentityVersion, relaunch: { source, runner: parked }, onResumed: options.onResumed };
resumeIdentityVersion: options.resumeIdentityVersion, relaunch: { source, runner: parked } };
const owner = createPluginRunnerTaskOwner(options.fresh ? relaunchInput : { ...base, task, adoptIdentity: source, authorityRunId: source.runId });
if (!options.fresh) owner.rebind(relaunchInput);
await prepare(owner, { ...requirements, identity: next });
@@ -831,10 +823,8 @@ describe("plugin Runner relaunch as the claimant run", () => {
}
it("starts the stopped Runner again as the claimant run and accepts the reported build", async () => {
const onResumed = vi.fn(async () => {});
const { owner, task, authority, registration } = await relaunchOwner(
() => ({ kind: "resume", taskId: "task", outcome: "resumed", runner: build, archivedState: settledCut }),
{ resumeIdentityVersion: 1, onResumed });
() => ({ kind: "resume", taskId: "task", outcome: "resumed", runner: build }));
expect(owner.driver.relaunchReleasedRunner).toEqual(source);
expect(owner.driver.adoptExistingRunner).toBeUndefined();
expect(owner.relaunchMayHaveStarted()).toBe(false);
@@ -848,7 +838,6 @@ describe("plugin Runner relaunch as the claimant run", () => {
}]);
expect(task.mock.calls.some(([operation]) => operation.kind === "submit")).toBe(false);
expect(authority.acceptRelaunchedRunner).toHaveBeenCalledExactlyOnceWith("synthetic-ticket", build, parked);
expect(onResumed).toHaveBeenCalledExactlyOnceWith(source);
expect(ingress.connect).toHaveBeenCalledOnce();
expect(owner.relaunchMayHaveStarted()).toBe(true);
owner.rebind({ ...base, task, authorityRunId: "later-run", resumeRelaunchedRunnerVersion: 1, resumeIdentityVersion: 1,
@@ -859,7 +848,7 @@ describe("plugin Runner relaunch as the claimant run", () => {
it("relaunches through a new owner, as after a Core restart, without submitting or adopting", async () => {
const { owner, task, authority, registration } = await relaunchOwner(
() => ({ kind: "resume", taskId: "task", outcome: "resumed", runner: build, archivedState: settledCut }),
() => ({ kind: "resume", taskId: "task", outcome: "resumed", runner: build }),
{ resumeIdentityVersion: 1, fresh: true });
expect(task.mock.calls.find(([operation]) => operation.kind === "prepare")?.[0]).toMatchObject({ priorIdentity: source });
expect(owner.driver.relaunchReleasedRunner).toEqual(source);
@@ -885,7 +874,7 @@ describe("plugin Runner relaunch as the claimant run", () => {
let attempts = 0;
const { task, registration, owner } = await relaunchOwner(() => {
if (attempts++ === 0) throw new Error("fixture resume reply lost");
return { kind: "resume", taskId: "task", outcome: "resumed", runner: build, archivedState: settledCut };
return { kind: "resume", taskId: "task", outcome: "resumed", runner: build };
});
owner.launcher(relaunchSpec());
registration.activate();
@@ -897,21 +886,6 @@ describe("plugin Runner relaunch as the claimant run", () => {
} finally { await registration.release("detach"); }
});
it.each([
["an unsettled cut", { ...settledCut, outbox: [{ sourceSeq: 4 }] }],
["another source's cut", { ...settledCut, runId: "other-run" }],
])("refuses %s before the Runner can connect", async (_label, archivedState) => {
const { authority, registration, owner } = await relaunchOwner(
() => ({ kind: "resume", taskId: "task", outcome: "resumed", runner: build, archivedState }));
owner.launcher(relaunchSpec());
registration.activate();
try {
await expect(registration.ready()).rejects.toThrow("native_runner_released_state_unsettled");
expect(authority.acceptRelaunchedRunner).not.toHaveBeenCalled();
expect(owner.relaunchMayHaveStarted()).toBe(true);
expect(ingress.connect).not.toHaveBeenCalled();
} finally { await registration.release("detach"); }
});
it("reports an unavailable relaunch for ordinary recovery", async () => {
const { registration, owner } = await relaunchOwner(() => ({ kind: "resume", taskId: "task", outcome: "unavailable" }));
@@ -5,7 +5,7 @@ import { environmentTaskOperationSchema, environmentTaskResultSchema, parseEnvir
import type { RunnerIngressEndpoint } from "@paperclipai/adapter-utils/runner-connectivity";
import { RUNNER_PRP_PROTOCOL_MIN, RUNNER_PRP_PROTOCOL_MAX, runnerLaunchPreparationDigest, runnerLaunchRunDigest, type RunnerProcessHandle, type RunnerProcessLaunchSpec,
type DurablePrpControlPlane, type RunnerExecutionDriver, type RunnerReleaseResumeOutcome, type RunnerLaunchPreparer, type DurableRecoveryIdentity, type PrpEvent,
isSettledReleasedRunnerCut } from "../../vendor/paperclip-runner/index.js";
} from "../../vendor/paperclip-runner/index.js";
import { connectRunnerPrpIngress } from "../../realtime/runner-prp-outbound.js";
import type { NativeExecutionContext } from "./native-execution-context.js";
@@ -60,8 +60,6 @@ export function createPluginRunnerTaskOwner(input: {
launchDigestVersion?: 1;
releasedSource?: DurableRecoveryIdentity;
sessionHandoff?: boolean;
onResumed?: (identity: DurableRecoveryIdentity) => Promise<void>;
onRetired?: (identity: DurableRecoveryIdentity) => Promise<void>;
githubBroker?: { url: string; token: string };
githubCredentialBrokerVersion?: 1;
configuredEnvironmentVersion?: 1;
@@ -262,11 +260,8 @@ export function createPluginRunnerTaskOwner(input: {
retiredBeforeClaim = state?.kind === "status" && state.executionStopped === true && state.sessionStateAvailable === true;
throw new Error("native_runner_reuse_unavailable");
}
if (!result.archivedState || !result.runner || !isSettledReleasedRunnerCut(result.archivedState, source)) {
throw new Error("native_runner_released_state_unsettled");
}
if (!result.runner) throw new Error("native_runner_released_state_unsettled");
authority.acceptRelaunchedRunner(native.ticket, result.runner, relaunch.runner);
await input.onResumed?.(source);
markReady();
return;
}
@@ -429,8 +424,6 @@ export function createPluginRunnerTaskOwner(input: {
if (submitted) {
await call({ kind: "complete" });
completed = true;
const identity = preparedIdentity ?? launchIdentity ?? input.priorIdentity;
if (identity) await input.onRetired?.(identity);
}
},
// The Runner is about to exit (its close suspend completed), as on release.
@@ -469,10 +462,7 @@ export function createPluginRunnerTaskOwner(input: {
if (activeOutbound === outbound) activeOutbound = null;
},
resume: async (identity: DurableRecoveryIdentity, ticket: string) => {
const outcome = await resume(identity, ticket);
if (typeof outcome === "object") return { ...outcome, settled: async () => { await input.onResumed?.(identity); } };
if (outcome === "resumed") await input.onResumed?.(identity);
return outcome;
return await resume(identity, ticket);
},
};
},
@@ -555,8 +545,6 @@ export function createPluginRunnerTaskOwner(input: {
}
await call({ kind: "complete" });
completed = true;
const identity = preparedIdentity ?? launchIdentity ?? input.priorIdentity;
if (identity) await input.onRetired?.(identity);
}
return stoppedState?.executionStopped === true && completed && !detached;
};
@@ -5,6 +5,7 @@ import { NATIVE_MODEL_REJECTION_MESSAGE, NATIVE_PROVIDER_CAPACITY_MAX_RETRIES, N
import { NATIVE_TOOL_RECEIPT_LIMIT_CODE, NATIVE_TOOL_RECEIPT_LIMIT_MAX_CONTINUATIONS } from "./native-tool-receipt-limit.js";
import { NATIVE_ENVIRONMENT_BLOCKER_CODE, NATIVE_ENVIRONMENT_BLOCKER_EXHAUSTED_ACTION, NATIVE_ENVIRONMENT_BLOCKER_EXHAUSTED_CODE,
NATIVE_ENVIRONMENT_BLOCKER_MAX_RETRIES } from "./native-environment-blocker.js";
import { planNotProducedDecision } from "./plan-mode-status.js";
import { NATIVE_AGENT_BLOCKER_CONTINUATION_CODE, NATIVE_AGENT_BLOCKER_HANDOFF_CODE,
NATIVE_AGENT_BLOCKER_MAX_CONTINUATIONS } from "./native-agent-blocker.js";
@@ -236,6 +237,8 @@ export function arbitrateNativeStatus(input: {
publishedExternalReview?: boolean;
/** Server-verified accepted plan request and normal provider terminal. */
planWaitAuthorized?: boolean;
/** A Plan-mode run settled with no unanswered plan revision to review. */
planNotProduced?: boolean;
monitorWaitAuthorized?: boolean;
caseHandoffAuthorized?: boolean;
/** The saved timer already admitted another run and this run no longer owns checkout. */
@@ -854,6 +857,12 @@ export function arbitrateNativeStatus(input: {
effects: [],
};
}
// Before the passive board/response waits: a Plan-mode run, assigned or
// comment-started, with no plan to review must not rest as a silent wait.
if (input.planNotProduced === true && !input.isConversation && input.assessment.reportedDisposition === "yielded" &&
input.assessment.continuation?.kind === "response_wake") {
return { policyVersion: NATIVE_STATUS_ARBITER_POLICY_VERSION, ...planNotProducedDecision(input) };
}
if (
input.assessment.reportedDisposition === "yielded" &&
input.assessment.continuation?.kind === "response_wake" &&
+23
View File
@@ -28,6 +28,7 @@ import { isAiAuthenticationBlocked } from "../ai-auth-failure.js";
import { RESTRICTED_WORKSPACE_SOURCE_REASON } from "../workspace-source-restriction.js";
import { PROJECT_STORAGE_ENVIRONMENT_INCOMPATIBLE } from "../project-storage-environment-reason.js";
import { hasCommittedNativePlanWait } from "../native-runtime/native-plan-wait.js";
import { ensureNativePlanReviewCard } from "../native-runtime/native-plan-review-card.js";
import { hasCommittedNativeConversationTurnWait, hasCommittedNativeResponseWakeWait } from "../native-runtime/native-response-wake-wait.js";
import { listExternalReviewWaits } from "../native-runtime/external-review-wait.js";
import { isNativeWorkspaceExportRepairCause } from "@paperclipai/shared";
@@ -5099,6 +5100,28 @@ export function recoveryService(
continue;
}
// A Plan-mode task whose run settled before the server opened plan
// review cards on settle (or whose card opening was interrupted) gets
// its card here; the card is then its next action.
if (
issue.workMode === "planning" &&
issue.status === "in_progress" &&
latestRun?.status === "succeeded" &&
latestRun.agentId === agentId &&
// An accepted native plan waits for the user's next message; its
// answered plan question is the review. Never ask for it again.
parseObject(latestRun.resultJson).finalizationReasonCode !== "native_plan_accepted_waiting_for_continuation" &&
!(await hasCommittedNativePlanWait(db, {
companyId: issue.companyId, issueId: issue.id, runId: latestRun.id, agentId,
})) &&
(await ensureNativePlanReviewCard(db, {
companyId: issue.companyId, issueId: issue.id, runId: latestRun.id, agentId,
})).kind === "created"
) {
result.skipped += 1;
result.issueIds.push(issue.id);
continue;
}
if (
await hasActiveExecutionPath(
issue.companyId,
+2 -1
View File
@@ -641,7 +641,7 @@ type RemoteHttpExecutionAudit = {
protocol: "MCP JSON-RPC 2.0" | "Railway GraphQL" | "Railway GraphQL + SSH" | "Google Workspace REST";
httpMethod: "POST";
endpoint: string;
mcpMethod: "tools/call";
mcpMethod?: "tools/call";
requestId: string;
upstreamToolName: string;
dispatched: true;
@@ -8419,6 +8419,7 @@ export function createToolGatewayService(
};
if (workspaceTarget?.transport === "paperclip_rest") {
execution.request.protocol = "Google Workspace REST";
delete execution.request.mcpMethod;
execution.request.endpoint = googleWorkspaceRestAuditEndpoint(workspaceTarget.service);
await assertWorkspaceGrantCurrent();
const signal = taskSignals.run ? AbortSignal.any([controller.signal, taskSignals.run]) : controller.signal;