Files
PaperClipAI/tests/runner-e2e/question-resume-scoring.ts
T
DottaandClaude Opus 5.5 a0d5f275af test(e2e): grade the question journey's saved reference by its complete token (#22949)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The daily QA staging smoke runs the `question-answer-resume` product
journey against a real agent
> - The board answers the agent's reference question with the text `Use
<marker>.`
> - The grader required the literal text `Use <marker>.` in the saved
note
> - Agents read `Use X.` as an instruction. Some save `Use X.`, others
save only `X`. Both notes are correct
> - This pull request grades the saved note by the complete marker
token, not by the answer's instruction wording
> - The benefit is that the smoke case no longer fails at random on a
correct note

## Linked Issues or Issue Description

**Describe the bug**
The QA staging smoke case `question-answer-resume` failed with
`journey_operation_failed`. The failed checks were
`question-resume.complete-evidence` and `question-document-reloaded`.

**Steps to reproduce**
1. Run the QA staging smoke journeys (full run on 2026-11-25).
2. The agent asks for a reference. The board answers `Use
AMBERjourney179560441987913f9fa70.`
3. The agent saves `Welcome to the club meetup this afternoon — we're
glad you're here; reference: AMBERjourney179560441987913f9fa70.`
4. The grader fails the note because it does not contain the word `Use`.

**Expected behavior**
A note that contains the complete submitted reference and the selected
time passes. A second campaign on the same day passed only because that
agent kept `Use` in the note.

**Additional context**
The private record also showed 4 `Invalid JSON body` responses. They
come from one failed `POST /api/issues/{id}/interactions` call that the
agent made itself, before it retried with a valid body and got 201. That
call is not the cause of the failure. The journey and the server route
are correct.

## What Changed

- Add `includesSubmittedReference` in
`tests/runner-e2e/question-resume-scoring.ts`. It matches the complete
marker token with no extra letters or digits on either side.
- Use it in `question-resume.complete-evidence` and in
`question-document-reloaded`.
- `waitForClarificationDocument` waits for the complete marker
(`submittedReferencePattern`), not for `Use <marker>.`. Before, a
correct note without `Use` timed out in the browser readback.
- Change the old unit test that rejected a note with only the marker. It
now accepts that note. New cases reject a shortened marker, an extended
marker, and a prefixed marker.

## Verification

- Red: the new cases failed on the old grader (3 failed, 144 passed).
The new readback case timed out on the old wait (1 failed, 3 passed).
- Green: `pnpm exec vitest run --config
tests/runner-e2e/vitest.config.ts` on the question-resume,
clarification, and question-documentation tests: 6 files, 170 tests
pass.
- `pnpm test:e2e:runner:typecheck` passes.
- After merge: a single-case `qa-staging-smoke.yml` run for
`question-answer-resume` on the new harness pin.

## Risks

Low risk. Test code only. The grader still requires the full marker. The
marker is a unique nonce, so a truncated or changed reference still
fails.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use and
code execution.

## Checklist

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

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 11:09:02 -06:00

165 lines
11 KiB
TypeScript

import { isDeepStrictEqual } from "node:util";
import type { ContinuationCheckpoint } from "./continuation-scoring.js";
import { isSingleClaudeQuestion } from "./runtime-question-readiness.js";
import { includesSubmittedReference } from "./submitted-reference.js";
type Row = Record<string, any>;
export type QuestionPath = "provider" | "semantic" | "api";
const nonempty = (v: unknown): v is string => typeof v === "string" && v.trim().length > 0;
const questions = (c?: ContinuationCheckpoint): Row[] =>
(c?.interactions ?? []).filter((i: any) => i.kind === "ask_user_questions") as Row[];
export const resumeQuestionFields = (i?: Row): Row[] =>
Array.isArray(i?.payload?.questionSet?.questions) ? i.payload.questionSet.questions : [];
function nativeApiQuestionReceipt(run: Row | undefined, question: Row) {
const hash = (value: unknown) => typeof value === "string" && /^[a-f0-9]{64}$/.test(value);
return Object.entries(run?.resultJson?.apiToolReceipts ?? {}).find(([key, value]) => {
const receipt = value as Row, original = receipt?.result?.data;
return hash(key) && hash(receipt?.digest) && receipt?.state === "completed"
&& receipt.operationId === "POST /api/issues/{id}/interactions" && receipt.result?.operationId === receipt.operationId
&& receipt.result.ok === true && receipt.result.status === 201 && original?.status === "pending"
&& original.kind === "ask_user_questions" && original.createdByUserId === null && question.createdByUserId === null
&& sameQuestion(original, question);
});
}
function sameNativeApiQuestionReceipt(before: ContinuationCheckpoint | undefined, after: ContinuationCheckpoint | undefined, question?: Row) {
if (!question) return false;
const receipt = nativeApiQuestionReceipt(before?.runs.find(run => run.id === question.sourceRunId), question);
return !!receipt && isDeepStrictEqual(receipt,
nativeApiQuestionReceipt(after?.runs.find(run => run.id === question.sourceRunId), question));
}
/** Classify by server-owned identities and an applied native mutation receipt. A
* missing receipt is unknown, never inferred from form shape or run count. */
export function questionPath(checkpoint: ContinuationCheckpoint | undefined, i?: Row): QuestionPath | null {
if (!checkpoint || !i || !nonempty(i.id) || !nonempty(i.sourceRunId) || !nonempty(i.idempotencyKey)) return null;
const matches = checkpoint.runs.filter(r => r.id === i.sourceRunId) as Row[];
const run = matches.length === 1 ? matches[0] : undefined;
if (!run || run.runtimeMode !== "native" || !nonempty(run.companyId) ||
run.companyId !== (checkpoint.issue as Row).companyId ||
i.companyId !== run.companyId || i.issueId !== checkpoint.issue.id || run.issueId !== i.issueId ||
!nonempty(checkpoint.issue.assigneeAgentId) || i.createdByAgentId !== checkpoint.issue.assigneeAgentId ||
run.agentId !== checkpoint.issue.assigneeAgentId) return null;
const request = i.payload?.runtimeRequestId;
if (request !== undefined) {
return nonempty(request) && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,159}$/.test(request) &&
i.idempotencyKey === `paperclip-runner-question:${run.id}:${request}` &&
i.continuationPolicy === "none" && run.status === "running" ? "provider" : null;
}
const receipt = run.resultJson?.semanticToolReceipts?.[i.idempotencyKey];
const created = receipt?.result?.interaction;
if (run.status !== "succeeded" || i.continuationPolicy !== "wake_assignee") return null;
if (
receipt?.operationId === "request_human_input" && receipt.result?.disposition === "applied" &&
created?.id === i.id && created?.sourceRunId === run.id && created?.issueId === i.issueId &&
created?.companyId === i.companyId && created?.kind === "ask_user_questions" &&
isDeepStrictEqual(created?.payload?.questionSet, i.payload?.questionSet)) return "semantic";
return nativeApiQuestionReceipt(run, i) ? "api" : null;
}
export function validResumeQuestionForm(checkpoint: ContinuationCheckpoint, i: Row, choice: boolean): boolean {
const path = questionPath(checkpoint, i);
const fields = resumeQuestionFields(i);
if (!path || fields.some(f => !nonempty(f.id)) || new Set(fields.map(f => f.id)).size !== fields.length) return false;
if (!choice) return fields.length === 1 && fields[0].answerMode === "text" &&
!fields[0].options?.length && !fields[0].customAnswer;
return fields[0]?.answerMode === "single_select" &&
(fields.length === 1 || (path === "provider" && isSingleClaudeQuestion(fields)));
}
export function validResumeReferenceForm(checkpoint: ContinuationCheckpoint, i: Row): boolean {
if (validResumeQuestionForm(checkpoint, i, false)) return true;
const fields = resumeQuestionFields(i), field = fields[0], options: Row[] = Array.isArray(field?.options) ? field.options : [];
return questionPath(checkpoint, i) === "provider" && fields.length === 1 && nonempty(field.id)
&& field.answerMode === "single_select" && field.customAnswer?.enabled === true
&& options.length > 0 && options.every(option => nonempty(option.id) && nonempty(option.label))
&& new Set(options.map(option => option.id)).size === options.length;
}
export function sameQuestion(a: Row, b?: Row) {
return !!b && ["id", "kind", "sourceRunId", "issueId", "companyId", "createdByAgentId", "idempotencyKey", "continuationPolicy"]
.every(k => a[k] === b[k]) && isDeepStrictEqual(a.payload, b.payload);
}
function answeredByUser(i?: Row) {
return i?.status === "answered" && nonempty(i.resolvedByUserId) && !i.resolvedByAgentId;
}
export function questionResumedOnce(before: ContinuationCheckpoint | undefined, after: ContinuationCheckpoint | undefined, i?: Row) {
if (!before || !after || !i) return false;
const path = questionPath(before, i);
const prior = new Set(before.runs.map(r => r.id));
const next = after.runs.filter(r => !prior.has(r.id)) as Row[];
if (prior.size !== before.runs.length || new Set(after.runs.map(r => r.id)).size !== after.runs.length ||
before.runs.some(r => !after.runs.some(n => n.id === r.id))) return false;
if (path === "provider") return next.length === 0 &&
after.runs.some(r => r.id === i.sourceRunId && ["running", "succeeded"].includes(r.status));
if ((path !== "semantic" && path !== "api") || next.length !== 1) return false;
if (path === "api" && !sameNativeApiQuestionReceipt(before, after, i)) return false;
const context = next[0].contextSnapshot;
return context?.issueId === i.issueId && context?.sourceRunId === i.sourceRunId &&
context?.interactionId === i.id && context?.interactionKind === "ask_user_questions" &&
context?.interactionStatus === "answered";
}
/** Behavioral qualification supports each verified native path. It does not
* replace the separate documentation-placement/semantic-tool qualification. */
export function gradeQuestionResume(checkpoints: ContinuationCheckpoint[], marker: string) {
const initial = checkpoints.find(c => c.phase === "initial");
const middle = checkpoints.find(c => c.phase === "answered");
const final = checkpoints.find(c => c.phase === "final");
const first = questions(initial)[0];
const second = questions(middle).find(i => i.status === "pending");
const choice = resumeQuestionFields(first)[0];
const text = resumeQuestionFields(second)[0];
const options: Row[] = choice?.options ?? [];
const afternoon = options.find(o => /^afternoon\b/i.test(String(o.label).trim()));
const checks = [{
id: "question-resume.forms",
passed: !!initial && !!middle && questions(initial).length === 1 && first?.status === "pending" &&
validResumeQuestionForm(initial, first, true) && options.length >= 2 &&
options.every(o => nonempty(o.id)) && new Set(options.map(o => o.id)).size === options.length &&
options.some(o => /^morning\b/i.test(String(o.label).trim())) && !!afternoon &&
questions(middle).length === 2 && questions(middle).filter(i => i.status === "pending").length === 1 &&
nonempty(second?.id) && second?.id !== first?.id && validResumeReferenceForm(middle, second),
detail: "One choice plus only a verified provider Other companion, then a distinct typed reference with an explicit provider written-answer control or a text field.",
}];
for (const [before, after, i, field, answer] of [
[initial, middle, first, choice, "choice"], [middle, final, second, text, "text"],
] as const) {
const committed = questions(after).filter(q => q.id === i?.id);
const retained = questions(final).filter(q => q.id === i?.id);
const response: Row[] = committed[0]?.result?.answers ?? [];
const primary = response.filter(a => a.questionId === field?.id);
const optionalIds = resumeQuestionFields(i).slice(1).map(f => f.id);
const validAnswer = primary.length === 1 && (answer === "choice"
? primary[0].optionIds?.length === 1 && primary[0].optionIds[0] === afternoon?.id && !primary[0].otherText
: !primary[0].optionIds?.length && primary[0].otherText === `Use ${marker}.`);
checks.push({
id: `question-resume.${answer}.answer`,
passed: !!i && committed.length === 1 && retained.length === 1 &&
sameQuestion(i, committed[0]) && sameQuestion(i, retained[0]) && answeredByUser(committed[0]) &&
answeredByUser(retained[0]) && isDeepStrictEqual(committed[0].result, retained[0].result) &&
validAnswer && response.every(a => a.questionId === field?.id ||
(optionalIds.includes(a.questionId) && !a.optionIds?.length && !a.otherText)),
detail: "The real board answer must remain bound to the unchanged question, with no fabricated or substituted response.",
}, {
id: `question-resume.${answer}.path`,
passed: questionResumedOnce(before, after, i) &&
(questionPath(before, i) !== "api" || sameNativeApiQuestionReceipt(before, final, i)),
detail: `Observed path: ${questionPath(before, i) ?? "unknown"}; provider answers resume the same run; durable native questions require one exactly bound response wake.`,
});
}
checks.push({
id: "question-resume.complete-evidence",
passed: checkpoints.length === 3 && !!initial && !!middle && !!final && initial.runs.length === 1 &&
questions(final).length === 2 && final.runs.length >= 1 && final.runs.length <= 3 &&
final.runs.every((r: Row) => r.companyId === (final.issue as Row).companyId &&
r.issueId === final.issue.id && r.agentId === final.issue.assigneeAgentId &&
typeof r.runnerProfileJson?.nativeExecutionInput?.task?.prompt === "string") &&
final.documents.length === 1 && !!final.documents[0].latestRevisionId &&
includesSubmittedReference(final.documents[0].body, marker) && /\bafternoon\b/i.test(final.documents[0].body),
detail: "Retain all three checkpoints, every native input and exactly one saved document containing the choice and the complete submitted reference.",
});
return checks.map(c => ({ ...c, passed: Boolean(c.passed) }));
}