Files
PaperClipAI/tests/runner-e2e/necessary-question.ts
T
6dda8cc2b7 fix: preserve Stop authority and qualify complete recovery journeys (#17105)
## Thinking Path

> - Paperclip lets people manage agents that do useful work.
> - Users need complete tasks, clear questions, retained context, and
dependable recovery.
> - Separate run tests do not prove that the complete user experience
works.
> - Successful retries can hide earlier failures and missing evidence.
> - This PR extends the existing Product E2E harness with three explicit
journeys.
> - It adds a qualification checkpoint over the full retained result
pool.
> - Independent artifacts, state, rendered conversations, and delivery
receipts establish each outcome.

## Linked Issues or Issue Description

Refs #17088, #17089, and #17046. This PR repairs two Stop lifecycle
defects and combines the qualification changes previously reviewed in
#17095, #17090, and #17099. Daily operations remain with #17051. It adds
no second scheduler or recovery engine.

**What happened?**

A completed run can still leave a user without useful output, an
understandable question, or a working continuation. Existing isolated
tests and best-attempt reports do not establish the combined behavior.

**Expected behavior**

A necessary question includes its explanation and resumes once after an
answer. Stop prevents automatic continuation until the user resumes.
Restart during finalization preserves the accepted provider result and
delivers it once. Qualification requires independent evidence for six
journeys on both agents through Slack and Paperclip.

**Steps to reproduce**

List the necessary-question, followup-stop-resume, and
finalization-recovery suites using the documented selectors. Run one
exact cell with the configured model and target. Supply a private
qualification manifest to the existing report command to grade all
retained attempts. Missing proof and incomplete coverage must fail.

## What Changed

- Wake existing accounting in the same committed native Stop closure. A
receipt that arrives before closure must still settle once; incomplete
receipts remain held.
- Require a later user message before native Stop can promote earlier
saved input. Preserve those earlier messages for the authorized
resumption.
- Add explicit necessary-question cells. Verify the actual prompt and
context, answer, one bound continuation, and the delivered document link
and revision.
- Add explicit follow-up, Stop, and later resumption cells. Verify a
live owned provider turn, cancellation acknowledgement, at least five
seconds without an automatic path, retained direction and workspace
context, and an actual browser download.
- Add explicit Daytona finalization-recovery cells. Stop the owned
controller after public result acceptance and during workspace
finalization. Require the original result, restored file hash, resumed
operation, one provider turn, and one receipt-bound delivery.
- Share the receipt-based delivery observer across both recovery
journeys. Keep model prose separate from the authoritative delivered
comment identity.
- Add a 24-cell qualification checkpoint over every retained attempt.
Require three fresh candidate passes per cell and later staging proof
with exact source, runtime, model, settings, instructions, and
independent evidence.
- Reject absent or unsafe manifest evidence. Preserve failed attempts
and incomplete observations in the normal reports.
- Provide four explicit rotating daily selections. Refuse daily
selection until all required live drivers exist. Keep scheduling and
spending with the existing operations owner.
- Document the exact selectors, evidence contract, limitations, and
remaining staging work.

## Verification

- Local Product E2E support: 3,554 passed with two existing skips;
source prerequisites: 128 passed. E2E typecheck passes. The actual
file-chip and Download-control browser regression passes.
- Two real-database regressions fail before the production repair. The
stopped coordinator leaves accounting asleep after a complete receipt;
the saved queue can restart from pre-Stop input. The repaired settlement
and cancellation cohort passes 66 checks. The complete 256-case
continuation suite passes with stronger two-phase Stop expectations, and
66 native executor accounting/Stop safety cases pass. Server typecheck
passes.
- All required CI, repository build/typecheck/tests, and fresh Greptile
5/5 pass at the final head 232d3c52d0,
with no unresolved findings.
- Both actual-model necessary-question development cells passed on the
earlier recorded c4e409d819 source. This is supporting evidence for that
revision, not current qualification.
- Both fresh Stop development cells at 6036cee2f4 stopped, remained
idle, resumed once, reached Done, and settled original and successor
accounting. Their original machine grades remain failed: the observer
counted the generated file-preparation carrier as another final reply.
The corrected observer independently correlates the applied preparation
receipt with the actual attachment/comment binding. Retained-wire
diagnostic replay finds one final delivery for each model without
changing either grade. Those original failures remain retained:
https://github.com/paperclipai/paperclip/actions/runs/39644220458.
- Both fresh actual-model Stop/resume cells pass all five checks at
232d3c52d0:
https://github.com/paperclipai/paperclip/actions/runs/39647010372.
Independent inspection confirms exactly one cancelled original and one
committed successor on the same task, 5.091/5.513-second quiet intervals
before the user resumes, retained workspace/instructions/tool
identities, and one receipt-bound final response. Each visible JSON chip
opens in a tab and its Download control yields verified bytes. The
rendered reference and changed label independently reconstruct the
registered file hash and the original context hash. Both cleanups pass.
These remain local API-key/per-turn development results, not the
required staging/Slack qualification.
- Other retained Stop failures include missed active boundaries, the
real accounting admission failure, and a preparation observer that
required nativeIssueId before runtime selection. They remain recorded at
https://github.com/paperclipai/paperclip/actions/runs/39636796645 and
https://github.com/paperclipai/paperclip/actions/runs/39642060165. The
preparation observer now validates all present task IDs and still
requires selected native execution at the active checkpoint.
- The remote finalization attempt failed during image export with no
disk space before a provider started. Remote crash acceptance remains
unverified.
- Negative calibration rejects wrong or absent ownership/evidence, stale
settings, unsafe files, repeated admissions, unacknowledged Stop,
premature resumption, incomplete receipts, lost context, genuine
duplicate final replies, and missing delivery. A prepared-looking body
cannot suppress a comment; absent, rejected, foreign, or mismatched file
receipts and attachment bindings also cannot suppress it.
- Core staging/Slack drivers, 72 fresh candidate passes, deployed
staging proof, and recovery of the original user-visible task remain
incomplete. No measured reliability percentage or completed
qualification is claimed.

## Risks

These are explicit development cells. Their API-key and per-turn runs do
not qualify deployed subscription authentication, warm reuse, or Slack.
A fast provider can miss the Stop boundary; that attempt fails. The
remote crash boundary depends on independently observed public state and
an owned controller. The checkpoint is opt-in through a private manifest
and cannot replace the missing live observers. The two production
changes affect native Stop settlement and saved-input promotion. They
use the existing transaction signals and admission path. A complete
receipt can settle without another provider turn. Partial accounting and
all ownership, cleanup, pause, and budget gates remain authoritative.

## Model Used

OpenAI Codex, GPT-6 family, with repository tools and code execution.
The runtime does not expose its exact deployment ID or context-window
size. Those values are not inferred.

## Checklist

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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
Co-authored-by: Paperclip <paperclip@paperclip.ing>
2026-10-21 13:02:27 -05:00

55 lines
4.4 KiB
TypeScript

import { createHash } from "node:crypto";
import { readFileSync } from "node:fs";
import { continuationScenario, continuationTasks, necessaryQuestionContract } from "./continuation-cases.js";
import { questionResumedOnce, sameQuestion, validResumeQuestionForm } from "./question-resume-scoring.js";
import type { ContinuationCheckpoint } from "./continuation-scoring.js";
import type { RunnerTaskFixture } from "./types.js";
type Row = Record<string, any>;
export const necessaryQuestionTask: RunnerTaskFixture = {
...continuationTasks.find(task => task.id === "answer-updates-scope")!,
id: "necessary-free-text", label: "Necessary free-text question and one continuation",
expectedRunCount: 2, minimumExpectedRunCount: 1, attemptTimeoutMs: { local: 10 * 60_000, daytona: 15 * 60_000 }, turnTimeoutMs: 4 * 60_000,
buildTitle: nonce => `Booking confirmation ${nonce}`,
buildPrompt: nonce => continuationScenario("necessary-free-text", nonce).prompt,
buildVisibleMarker: nonce => continuationScenario("necessary-free-text", nonce).marker,
};
export function gradeNecessaryQuestion(checkpoints: ContinuationCheckpoint[], answer: string) {
const initial = checkpoints.find(point => point.phase === "initial"), final = checkpoints.find(point => point.phase === "final");
const cards = (point?: ContinuationCheckpoint) => (point?.interactions ?? []).filter((value: any) => value.kind === "ask_user_questions") as Row[];
const pending = cards(initial), finished = cards(final), question = pending[0], resolved = finished[0];
const field = question?.payload?.questionSet?.questions?.[0], contract = necessaryQuestionContract();
const check = (id: string, passed: boolean, detail: string) => ({ id, passed: Boolean(passed), detail });
const response = resolved?.result?.answers, document = final?.documents[0], navigation = final?.outputDocument;
return [
check("necessary-question.form", checkpoints.length === 2 && !!initial && pending.length === 1 && question?.status === "pending" && initial.documents.length === 0 && initial.attachments.length === 0 &&
validResumeQuestionForm(initial, question, false) && field?.required === true && field.prompt === contract.prompt &&
[question.payload.questionSet.description, field.helpText].includes(contract.context),
"One bound text-only question must show the required prompt and its explanation before delivery."),
check("necessary-question.visible", initial?.questionPresentation?.interactionId === question?.id &&
initial?.questionPresentation?.promptVisible === true && initial?.questionPresentation?.contextVisible === true,
"The browser must observe the actual question and context, not only its title."),
check("necessary-question.answer", finished.length === 1 && !!question && sameQuestion(question, resolved) && resolved?.status === "answered" &&
typeof resolved.resolvedByUserId === "string" && !!resolved.resolvedByUserId && !resolved.resolvedByAgentId &&
Array.isArray(response) && response.length === 1 && response[0]?.questionId === field?.id && response[0]?.otherText === answer &&
!response[0]?.optionIds?.length,
"One real user answer must remain attached to the unchanged question."),
check("necessary-question.one-continuation", questionResumedOnce(initial, final, question) && !!final && final.runs.length <= 2 &&
final.runs.every((run: Row) => run.status === "succeeded" && run.runtimeMode === "native" && run.nativePhase === "committed" && run.resultJson?.finalizationPhase === "committed"),
"The answer must resume its bound provider run or admit exactly one bound semantic successor, without duplicate work."),
check("necessary-question.result", final?.issue.status === "done" && final.documents.length === 1 &&
!!document?.latestRevisionId && document?.body.trim() === `Booking confirmed: ${answer}` &&
navigation?.issueId === final.issue.id && navigation?.key === document.key && navigation?.revisionId === document.latestRevisionId &&
navigation?.visibleBody === document.body.trim(),
"The final reply must open this task's saved confirmation and show its exact answer."),
];
}
export function necessaryQuestionDigest() {
const hash = createHash("sha256");
for (const file of ["necessary-question.ts", "continuation-cases.ts", "continuation-flow.ts", "continuation-scoring.ts", "question-resume-scoring.ts", "stock-harness.ts"])
hash.update(file).update(readFileSync(new URL(file, import.meta.url)));
return hash.digest("hex");
}