Files
PaperClipAI/server/src/services/native-runtime/native-question-bridge.ts
T
DottaandPaperclip 43acbcc398 fix(runner): preserve sessions and complete question and approval continuations (#13655)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The native runner connects task state to provider sessions.
> - Follow-up turns must retain provider memory and carry new user
direction.
> - Lost session IDs caused repeated context and extra input tokens.
> - Native question answers and approval races could leave valid work
blocked.
> - This pull request repairs those paths and adds regression coverage.
> - Agents can continue accepted work without repeating the conversation
or losing the user's answer.

## Linked Issues or Issue Description

Refs #13574. That merged PR shortened continuation prompts and moved
question instructions into tool documentation. This change preserves
sessions and fixes failures exposed by broader testing. Related runtime
work: #13408 and #13410.

**What happened?**

Native follow-up turns could lose the provider session ID. Completion
guidance could replace the original task with its latest comment. Claude
native questions could remain pending after the user answered. Approval
during a running tool call could suspend the run before the tool
response arrived. Onboarding and chat handoff instructions also caused
repeated planning or missing plan documents.

**Expected behavior**

Reuse a valid provider session. Send only new events when that session
already has the history. Preserve the task requirements and apply later
user direction. Store the question answer and deliver it to the waiting
run. Finish governed tool responses before suspending. Execute the
accepted plan without asking for the same approval again.

**Steps to reproduce**

Run the continuation, local-session-integrity, first-task, and
agent-chat suites with native Codex and Claude. Include
provider-question-bridge, accept-while-running, and plan-handoff.

**Paperclip version or commit**

This branch is based on master d54b75011. The active full catalog run
tests 4e75881db. Later review fixes have separate regression coverage.

**Deployment mode**

Isolated local instances and Daytona sandboxes in the existing Runner
full-stack E2E harness.

## What Changed

- Retain provider session identity across turns and late usage
snapshots. Send new continuation events on session reuse, with full
context available for a fresh session.
- Preserve task requirements and later direction in completion guidance.
Return the current contract revision after a stale completion
submission.
- Bridge native Claude questions to saved Paperclip cards. Submit
answers through the saved card and resume the same run.
- Delay governed suspension until tool results settle. Add a
deterministic test barrier for approval during an active run.
- Clarify free-text question examples, explicit onboarding plans, and
execution of accepted chat plans.
- Fix continuation readiness, verified output evidence, and declared
screenshot collection.
- Qualify the legacy Claude test CLI at 2.1.277. The old 2.1.19 CLI did
not discover mounted skills. Update the existing workflow pin and
isolated launcher together.
- Refresh the Daytona image lockfile integrity pin after reviewing
master patch updates.
- Carry continuation mode as runtime metadata instead of inferring it
from user-visible text. Install the test Claude CLI without lifecycle
scripts.

## Verification

- Targeted paid verification: 20/20 cases passed across
local-environment campaigns before the rebase.
[Report](https://pages.paperclip.ing/runner-e2e-seven-fixes-35397904249/).
- Harness checks: 379 unit tests passed; harness typecheck passed.
- Latest-head PR checks: 55 passed, two intentionally skipped. Greptile
is 5/5; the security scan passes.
- Review regressions: 350 executor tests and 204 session/driver tests
passed. A script-free Claude install was verified with the actual CLI.
- Full catalog, including the explicit-only everyday suite: [run
35417932353](https://github.com/paperclipai/paperclip/actions/runs/35417932353).
Completed: **164/205 passed; 41 failed**. [Full dashboard and failure
investigation](https://pages.paperclip.ing/runner-e2e-full-catalog-35417932353/).
Includes 204 case artifacts and one pre-case GitHub authorization
timeout; missing evidence is not scored as a pass. The full run tested
`4e75881db`; Final-head metadata/CLI smoke cases both passed. In the
separate [six infrastructure
retries](https://github.com/paperclipai/paperclip/actions/runs/35419769343),
the GitHub timeout case passed and all five Docker preflight failures
repeated. [Follow-up
dashboard](https://pages.paperclip.ing/runner-e2e-full-catalog-35417932353/follow-up/).
- Full local typecheck and build passed on the rebased branch. The full
local unit run completed with 657 passing files, two test timeouts and
one suite setup timeout. All three affected files passed when rerun in
isolation (84 tests). The first full local run was not clean.
- Focused regression coverage includes the live question bridge,
same-run response delivery, UI routing, stale revisions, approval
overlap, and session reuse.

## Full-catalog follow-ups

- Test infrastructure: 14 Claude everyday cells probe an absent host
CLI; six cells failed pre-task GitHub/Docker qualification (GitHub
passes on retry; all five Docker cases repeat; the workflow preflight
allowlist omits their case IDs); five ACPX Codex cells cannot create
sandbox namespaces.
- Runtime: four OpenCode completion-criteria mismatches masked by
shutdown errors, one service-approval suspension failure; three Daytona
recovery failures encounter existing skill files; one duplicate
completion wake.
- Confirmed test defects: question pagination and a noncanonical plan
document key.
- Product/behavior: mismatched visible/required question sets, an
attachment instead of the requested task document, one lone-option
onboarding question, early completion instead of review, and a Codex
Mini completion-schema failure.
- The report job itself fails on trusted master’s stale patch/lock
configuration. The linked report is rebuilt with the shared renderer
from original cell results and public fixture screenshots; it excludes
private snapshots, logs and traces.

These are investigated follow-ups, not silently regraded passes.
First-task passed 51/52. The PR checks are green independently of the
broader catalog’s behavioral/infrastructure failures.

## Risks

- Session reuse depends on a valid provider identity and context
coverage. Fresh-session fallback and reset tests cover this boundary.
- Native question delivery spans saved interaction state and a live
provider run. Tests cover duplicate events, closed runs, and same-run
answers.
- Provider behavior varies. The full paid catalog may expose failures
beyond these targeted fixes; those results will be reported without
relaxing valid approval or output checks.
- The legacy Claude version update is limited to test infrastructure. No
database migration is included.

## Model Used

OpenAI Codex, GPT-6 family, with repository inspection, code execution,
and browser/E2E tools. The exact runtime model identifier and
context-window size are not exposed in this session.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass (targeted checks and all
three timeout-file reruns pass; full-run timeout caveat above)
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-09-19 07:42:57 -05:00

445 lines
17 KiB
TypeScript

import { and, eq, inArray, sql } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import { heartbeatRuns, issueThreadInteractions } from "@paperclipai/db";
import type {
AskUserQuestionsAnswer,
AskUserQuestionsInteraction,
AskUserQuestionsQuestionOption,
PaperclipQuestionSetPayload,
RespondIssueThreadInteraction,
} from "@paperclipai/shared";
import type { PrpEvent } from "../../vendor/paperclip-runner/index.js";
import {
parsePaperclipQuestionResponse,
parsePaperclipQuestionSet,
type PaperclipQuestionResponse,
type PaperclipQuestionSet,
} from "../../vendor/paperclip-runner/index.js";
import { logger } from "../../middleware/logger.js";
import { unprocessable } from "../../errors.js";
import { logActivity } from "../activity-log.js";
import { issueThreadInteractionService } from "../issue-thread-interactions.js";
import { questionResponseDeliveryService } from "../question-response-delivery.js";
import type { NativeRunStoreBinding } from "./native-run-coordinator-store.js";
const QUESTION_KEY_PREFIX = "paperclip-runner-question:";
const REQUEST_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,159}$/;
const TEXT_ANSWER_OPTION_ID = "paperclip_text_answer";
const CUSTOM_ANSWER_OPTION_ID = "paperclip_custom_answer";
export const NATIVE_QUESTION_CANCELLATION_CONTEXT_KEY = "nativeQuestionCancellation";
type QueueCommand = (
type: string,
payload?: Record<string, unknown>,
commandId?: string,
) => { readonly commandId: string; readonly controllerSeq: number } | Promise<{ readonly commandId: string; readonly controllerSeq: number }>;
interface NativeQuestionCommandTarget {
binding: Pick<NativeRunStoreBinding, "companyId" | "issueId" | "runId" | "agentId">;
queueCommand: QueueCommand;
}
const activeTargets = new Map<string, NativeQuestionCommandTarget>();
interface NativeQuestionIdentity {
idempotencyKey?: string | null;
sourceRunId?: string | null;
payload: unknown;
}
export interface NativeQuestionAuthorizationIdentity extends NativeQuestionIdentity {
companyId: string;
issueId: string;
}
export type NativeQuestionCancellationCause =
| { kind: "issue_terminal"; issueStatus: string }
| { kind: "interaction_withdrawn"; interactionId: string }
| { kind: "interaction_cancelled"; interactionId: string };
type DbTransaction = Parameters<Parameters<Db["transaction"]>[0]>[0];
type NativeQuestionMutationDb = Pick<Db | DbTransaction, "select" | "update">;
function record(value: unknown): Record<string, unknown> | null {
return value && typeof value === "object" && !Array.isArray(value)
? value as Record<string, unknown>
: null;
}
function requestIdForInteraction(
interaction: NativeQuestionIdentity,
): string | null {
const payload = record(interaction.payload);
if (!interaction.sourceRunId || !payload?.questionSet) return null;
const key = interaction.idempotencyKey;
const expectedPrefix = `${QUESTION_KEY_PREFIX}${interaction.sourceRunId}:`;
if (!key?.startsWith(expectedPrefix)) return null;
const requestId = key.slice(expectedPrefix.length);
if (!REQUEST_ID_PATTERN.test(requestId)) return null;
return typeof payload.runtimeRequestId === "string" && payload.runtimeRequestId !== requestId
? null
: requestId;
}
function uniqueSyntheticOptionId(existing: readonly string[], preferred: string): string {
const ids = new Set(existing);
if (!ids.has(preferred)) return preferred;
for (let suffix = 2; suffix < 10_000; suffix += 1) {
const candidate = `${preferred}_${suffix}`;
if (!ids.has(candidate)) return candidate;
}
throw new Error("native_question_synthetic_option_exhausted");
}
function toInteractionPayload(questionSet: PaperclipQuestionSet, runtimeRequestId: string) {
return {
version: 1 as const,
...(questionSet.title ? { title: questionSet.title.slice(0, 240) } : {}),
...(questionSet.submitLabel ? { submitLabel: questionSet.submitLabel.slice(0, 120) } : {}),
questions: questionSet.questions.map((question) => {
const canonicalOptions = question.options ?? [];
const options: AskUserQuestionsQuestionOption[] = canonicalOptions.map((option) => ({
id: option.id,
label: option.label,
...(option.description ? { description: option.description } : {}),
}));
if (question.answerMode === "text") {
options.push({
id: uniqueSyntheticOptionId([], TEXT_ANSWER_OPTION_ID),
label: question.header ?? "Type an answer",
...(question.textValidation?.inputType
? { description: `Expected ${question.textValidation.inputType} input` }
: {}),
freeText: true,
});
} else if (question.customAnswer?.enabled) {
options.push({
id: uniqueSyntheticOptionId(canonicalOptions.map((option) => option.id), CUSTOM_ANSWER_OPTION_ID),
label: question.customAnswer.label ?? "Other",
...(question.customAnswer.placeholder ? { description: question.customAnswer.placeholder } : {}),
freeText: true,
});
}
return {
id: question.id,
prompt: question.prompt,
...((question.helpText || question.header)
? { helpText: question.helpText ?? question.header }
: {}),
selectionMode: question.answerMode === "multi_select" ? "multi" as const : "single" as const,
required: question.required,
allowOther: question.answerMode === "text" || question.customAnswer?.enabled === true,
options,
};
}),
questionSet: questionSet as PaperclipQuestionSetPayload,
runtimeRequestId,
// A generic task comment cannot satisfy this provider request. Keep the
// card actionable until a validated answer or an explicit terminal action.
supersedeOnUserComment: false,
};
}
function canonicalResponse(
questionSet: PaperclipQuestionSetPayload,
answers: readonly AskUserQuestionsAnswer[],
): PaperclipQuestionResponse {
const answerByQuestionId = new Map(answers.map((answer) => [answer.questionId, answer]));
const response: PaperclipQuestionResponse = {
schema: "paperclip.question_response.v1",
answers: {},
};
for (const question of questionSet.questions) {
const answer = answerByQuestionId.get(question.id);
if (!answer) continue;
if (question.answerMode === "text") {
response.answers[question.id] = {
...(answer.otherText !== undefined && answer.otherText !== null
? { text: answer.otherText }
: {}),
};
} else {
const customOptionId = question.customAnswer?.enabled
? uniqueSyntheticOptionId(
(question.options ?? []).map((option) => option.id),
CUSTOM_ANSWER_OPTION_ID,
)
: null;
response.answers[question.id] = {
selectedOptionIds: answer.optionIds.filter((optionId) => optionId !== customOptionId),
...(answer.otherText !== undefined && answer.otherText !== null
? { customText: answer.otherText }
: {}),
};
}
}
return parsePaperclipQuestionResponse(questionSet, response);
}
async function authorizedNativeRun(
db: Pick<Db | DbTransaction, "select">,
interaction: NativeQuestionAuthorizationIdentity,
) {
const requestId = requestIdForInteraction(interaction);
if (!requestId || !interaction.sourceRunId) return null;
const run = await db.select({
id: heartbeatRuns.id,
companyId: heartbeatRuns.companyId,
issueId: heartbeatRuns.nativeIssueId,
agentId: heartbeatRuns.agentId,
runtimeMode: heartbeatRuns.runtimeMode,
status: heartbeatRuns.status,
}).from(heartbeatRuns).where(and(
eq(heartbeatRuns.id, interaction.sourceRunId),
eq(heartbeatRuns.companyId, interaction.companyId),
eq(heartbeatRuns.nativeIssueId, interaction.issueId),
eq(heartbeatRuns.runtimeMode, "native"),
)).limit(1).then((rows) => rows[0] ?? null);
return run ? { ...run, requestId } : null;
}
/** Materialize a canonical runtime input request as the existing task-thread card. */
export async function projectNativeRuntimeRequest(input: {
db: Db;
binding: Pick<NativeRunStoreBinding, "companyId" | "issueId" | "runId" | "agentId" | "normalizedSessionId" | "runnerSourceInstanceId">;
event: PrpEvent;
}): Promise<AskUserQuestionsInteraction | null> {
if (input.event.eventType !== "runtime_request.created") return null;
if (
input.event.runId !== input.binding.runId
|| input.event.normalizedSessionId !== input.binding.normalizedSessionId
|| input.event.sourceInstanceId !== input.binding.runnerSourceInstanceId
) {
throw new Error("native_runtime_request_binding_mismatch");
}
const request = record(record(input.event.payload)?.request);
if (
!request
|| request.schema !== "paperclip.runtime_request.v2"
|| request.requestKind !== "runtime"
|| request.type !== "input"
|| request.status !== "pending"
|| typeof request.requestId !== "string"
|| !REQUEST_ID_PATTERN.test(request.requestId)
) {
throw new Error("native_runtime_request_invalid");
}
const questionSet = parsePaperclipQuestionSet(request.input);
if (questionSet.questions.some((question) => question.textValidation?.pattern !== undefined)) {
// JavaScript regular expressions have no execution budget. Provider-authored
// patterns therefore stay fail-closed until the runner contract supplies a
// bounded regex dialect rather than exposing the server to catastrophic backtracking.
throw new Error("native_runtime_question_pattern_unsupported");
}
const idempotencyKey = `${QUESTION_KEY_PREFIX}${input.binding.runId}:${request.requestId}`;
const existing = await input.db.select({ id: issueThreadInteractions.id })
.from(issueThreadInteractions)
.where(and(
eq(issueThreadInteractions.companyId, input.binding.companyId),
eq(issueThreadInteractions.issueId, input.binding.issueId),
eq(issueThreadInteractions.idempotencyKey, idempotencyKey),
))
.limit(1)
.then((rows) => rows[0] ?? null);
const interaction = await issueThreadInteractionService(input.db).create(
{ id: input.binding.issueId, companyId: input.binding.companyId },
{
kind: "ask_user_questions",
idempotencyKey,
sourceRunId: input.binding.runId,
resolverPolicy: "human_only",
continuationPolicy: "none",
...(questionSet.title ? { title: questionSet.title.slice(0, 240) } : {}),
...(typeof request.prompt === "string" ? { summary: request.prompt.slice(0, 1000) } : {}),
payload: toInteractionPayload(questionSet, request.requestId),
},
{ agentId: input.binding.agentId, runId: input.binding.runId },
{ supersedePendingSiblingInteractions: false },
) as AskUserQuestionsInteraction;
if (!existing) {
await logActivity(input.db, {
companyId: input.binding.companyId,
actorType: "agent",
actorId: input.binding.agentId,
agentId: input.binding.agentId,
runId: input.binding.runId,
action: "issue.thread_interaction_created",
entityType: "issue",
entityId: input.binding.issueId,
details: {
interactionId: interaction.id,
interactionKind: interaction.kind,
interactionStatus: interaction.status,
runtimeMode: "native",
},
});
}
if (interaction.status === "answered") {
await deliverNativeQuestionResponseDurably(input.db, interaction);
}
return interaction;
}
/** Validate untrusted board input before the existing interaction service persists it. */
export function validateNativeQuestionResponseInput(
interaction: AskUserQuestionsInteraction,
input: RespondIssueThreadInteraction,
): void {
if (!requestIdForInteraction(interaction) || !interaction.payload.questionSet) return;
try {
canonicalResponse(interaction.payload.questionSet, input.answers);
} catch (error) {
throw unprocessable(
error instanceof Error ? error.message : "Invalid native question response",
{ code: "invalid_question_response" },
);
}
}
/** Queue an answered interaction into the active durable PRP command stream. */
export async function deliverNativeQuestionResponse(
db: Db,
interaction: AskUserQuestionsInteraction,
): Promise<"not_native" | "pending" | "queued"> {
if (interaction.status !== "answered" || !interaction.result || !interaction.payload.questionSet) {
return "not_native";
}
const run = await authorizedNativeRun(db, interaction);
if (!run) return "not_native";
const response = canonicalResponse(interaction.payload.questionSet, interaction.result.answers);
const target = activeTargets.get(run.id);
if (
!target
|| target.binding.companyId !== run.companyId
|| target.binding.issueId !== run.issueId
|| target.binding.agentId !== run.agentId
) {
return "pending";
}
try {
await target.queueCommand(
"request.resolve",
{ requestId: run.requestId, response: response as unknown as Record<string, unknown> },
`question_${interaction.id}`,
);
return "queued";
} catch (error) {
logger.warn(
{ err: error, runId: run.id, interactionId: interaction.id },
"native question response remains durable for session recovery",
);
return "pending";
}
}
async function deliverNativeQuestionResponseDurably(
db: Db,
interaction: AskUserQuestionsInteraction,
): Promise<void> {
await questionResponseDeliveryService(db, {
heartbeat: {
wakeup: async () => {
throw new Error("native_question_wake_unreachable");
},
} as never,
resolveNativeQuestion: (candidate) => deliverNativeQuestionResponse(db, candidate),
}).deliver(interaction.id);
}
export async function flushNativeQuestionResponses(
db: Db,
runId: string,
): Promise<void> {
const target = activeTargets.get(runId);
if (!target) return;
const interactions = await issueThreadInteractionService(db).listForIssue(target.binding.issueId);
for (const interaction of interactions) {
if (
interaction.kind === "ask_user_questions"
&& interaction.sourceRunId === runId
&& interaction.status === "answered"
) {
await deliverNativeQuestionResponseDurably(db, interaction);
}
}
}
export function registerNativeQuestionCommandTarget(target: NativeQuestionCommandTarget): () => void {
const existing = activeTargets.get(target.binding.runId);
if (existing) throw new Error("native_question_command_target_conflict");
activeTargets.set(target.binding.runId, target);
return () => {
if (activeTargets.get(target.binding.runId) === target) {
activeTargets.delete(target.binding.runId);
}
};
}
export async function nativeQuestionRunToCancel(
db: Db,
interaction: NativeQuestionAuthorizationIdentity,
): Promise<string | null> {
const run = await authorizedNativeRun(db, interaction);
return run && ["queued", "running"].includes(run.status) ? run.id : null;
}
/**
* Persist cancellation intent in the same transaction that closes the issue.
* The post-commit fast path and the heartbeat recovery sweep both consume this
* marker, so process exit or a transient process-termination failure cannot
* strand a native run after its question has expired.
*/
export async function requestNativeQuestionRunCancellation(
db: NativeQuestionMutationDb,
interaction: NativeQuestionAuthorizationIdentity,
cause: NativeQuestionCancellationCause,
): Promise<string | null> {
const run = await authorizedNativeRun(db, interaction);
if (!run || !["queued", "running"].includes(run.status)) return null;
const marker = JSON.stringify({
version: 1,
issueId: interaction.issueId,
...cause,
requestedAt: new Date().toISOString(),
});
return db.update(heartbeatRuns).set({
contextSnapshot: sql`jsonb_set(
case
when jsonb_typeof(${heartbeatRuns.contextSnapshot}) = 'object'
then ${heartbeatRuns.contextSnapshot}
else '{}'::jsonb
end,
array[${NATIVE_QUESTION_CANCELLATION_CONTEXT_KEY}],
${marker}::jsonb,
true
)`,
updatedAt: new Date(),
}).where(and(
eq(heartbeatRuns.id, run.id),
eq(heartbeatRuns.companyId, interaction.companyId),
eq(heartbeatRuns.nativeIssueId, interaction.issueId),
eq(heartbeatRuns.runtimeMode, "native"),
inArray(heartbeatRuns.status, ["queued", "running"]),
)).returning({ id: heartbeatRuns.id }).then((rows) => rows[0]?.id ?? null);
}
/** Capture the minimum bound identity needed to cancel after the issue transaction commits. */
export function nativeQuestionCancellationIdentity(
interaction: NativeQuestionAuthorizationIdentity,
): NativeQuestionAuthorizationIdentity | null {
if (!requestIdForInteraction(interaction)) return null;
return {
companyId: interaction.companyId,
issueId: interaction.issueId,
sourceRunId: interaction.sourceRunId,
payload: interaction.payload,
idempotencyKey: interaction.idempotencyKey,
};
}
export const nativeQuestionBridgeInternals = {
resetForTests: () => activeTargets.clear(),
};