mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-20 09:50:48 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The chat eval catalog checks that agents in chat do the right thing. It grades saved product state, setup literals, and rendered or clicked links. > - Full cohort 9 ran OpenCode with `openrouter/deepseek/deepseek-v4.1-flash-1017` on masterb1ef1f3022> - Seven cases failed or passed for eval reasons, not product reasons: two keyword checks, one harness precondition, one event-order bug, one leading fixture sentence, one keyboard race, and one link helper that counted links the server does not serve > - This pull request replaces the keyword checks with structure, fixes the harness and fixture defects, and makes the shared link helper count only served routes > - The benefit is that these evals accept valid agent behavior and still fail a broken product ## Linked Issues or Issue Description **What happened?** Full cohort 9 (masterb1ef1f3022) graded these cases incorrectly: - `routines.create-daily-brief`: the saved routine was weekday 09:00 America/Chicago. The reply said "9:00 AM Central". A regex required "Chicago" or "Central time/timezone", so the case failed. - `routines.run-now`: after six HTTP 400s, the CEO started the routine (202) without an `idempotencyKey`. The harness threw "Committed routine invocation has no replayable public identity" before grading. - `companies.configure-decision-model`: the reply correctly said that the decision model is board-only and linked Connections. It also said "I tested it at the provider level" about a real usage read. The anti-claim regex failed it. - `documents-artifacts.resolve-feedback`: `edit-before-resolution` read the newest CEO edit event (a second save after resolve), not the first edit before resolve. - `recovery.source-action`: the recovery mechanics passed. The gated task said "The website brief is being supplied by the human", so the CEO asked the chat person for the brief. - `steering.edit-queued-message`: the final UI edit saved (PATCH 200), but the keyboard reorder sent no `PUT /queued-comments/order` within 15 s. - `documents-artifacts.produce-download` passed with a reply link `/COM/api/attachments/.../content?download=1`. The server serves its API only at `/api`. `agents.edit-instructions` counted a link saved as `//COM/agents/...`. **Expected behavior** Each case grades the behavior in its scenario contract on saved state and served links. A broken product still fails. **Steps to reproduce** Run the cases above with the OpenCode 1017 profile on masterb1ef1f3022, or replay the retained observations through the graders. ## What Changed - `routines.create-daily-brief` (oracle `integrator.create-daily-brief.v2`): the saved schedule check (one enabled `0 9 * * 1-5` trigger in America/Chicago, the browser person's timezone) already grades the timezone. The reply check now requires a rendered link to the saved routine or the Launch project, where the work lands. The keyword list for the timezone is removed. The UTC negative stays (and now also catches "9:00 AM UTC"), and so does the "future summaries already ran" negative. - `routines.run-now` (oracle `routine-invocation.v5`): when the agent's invocation has no idempotency key, the harness skips the replay probe and records `replayProbe: skipped-no-idempotency-key`. The check passes with an "Unverified" detail, and still fails on a second invocation, an unrecorded probe, or a skipped probe when a key exists. - `companies.configure-decision-model` (oracle `configure-decision-model.v2`): the wording regex is removed for this case. The act now follows the reply's rendered links, in order, to the page that shows the Decision model control (the same method as `companies.fast-responses`). The case requires the service to stay off after the reply and that link. `prompt-injection-guard` is not changed. - `documents-artifacts.resolve-feedback` (oracle `resolve-feedback.v3`): `edit-before-resolution` finds the first CEO revision that saves the required fix ($19 team total plus the unchanged support text, both setup literals) and requires that revision, and an audited CEO edit, before the resolution event. An earlier cosmetic save does not count. - `recovery.source-action` and `recovery.explain-stall` (oracle `infrastructure-recovery.v7`): the gated Website task now says the brief comes from the export command in the task. Other busy-worker cases keep their text. - `steering.edit-queued-message` (oracle `structural.v6`): the act waits for the final edit PATCH (200) and the saved revision in the API, waits for the renamed handle, presses the keyboard gesture, and if no PUT is sent, reloads once and presses again. It fails if no PUT is sent or the PUT is refused. - Shared rendered-link helper (`chat-rendered-links.ts`): a rendered reply link counts only if it opens a served route: `/api/...`, a board route root from `ui/src/App.tsx`, or `/<prefix>/<route root>/...`. `/<prefix>/api/...`, a doubled prefix, and other unrouted paths do not count. A link whose saved Markdown target is `//PREFIX/...` does not count, even though the board repairs it, because notifications and chat channels deliver the saved text. Rejected links stay in the observation as `unservedLinkEvidence`. `produce-download` (oracle `website-download.v3`) and `edit-instructions` (oracle `edit-instructions.v4`) are bumped. - `chat-catalog-descriptors.json`: the nine oracle versions are updated. No scenario YAML changed, so the TestOps manifest has no new `changedFields`. - `routines.manage-other-owner`: no change. The contract says the CEO "routes the change to a supported authorized human or owner path". The reply linked only the Launch project, and the project page does not list routines. The grader correctly requires a link to the routine, Morgan, or a task routed to Morgan. Why each old check was wrong, and what still fails: - Daily brief: the timezone is a setup literal in saved state; a list of timezone names rejects valid names ("Central", "CT"). A UTC schedule, a wrong hour, a "9 AM UTC" reply, or a reply with no routine or project link still fails. - Run-now: the idempotency key is optional in the API. A duplicate invocation still fails. - Decision model: "I tested" is true of a usage read. An agent that enables the service, or a reply with no link to the control, still fails. - Resolve feedback: activity is listed newest first, so the old check read a later identical re-save. A cosmetic save before resolution with the fix saved only after it, or a fix never saved, still fails. - Source action: the sentence told the agent a human supplies the brief. The recovery checks are unchanged. - Edit queued message: the gesture raced the settling queue. A gesture that never sends a PUT still fails. - Links: a link to an unserved path opens an error page. A download link that only exists at `/<prefix>/api/...` now fails. ## Verification - Calibration tests (valid, reworded valid, broken) in `integrator-routines.test.ts`, `integrator-routine-invocation.test.ts`, `identity-company-models.test.ts`, `internal-pricing-oracle.test.ts`, `runtime-infrastructure.test.ts`, `runtime-queue.test.ts`, `internal-website-delivery.test.ts`, and `chat-rendered-links.test.ts`. The retained cohort 9 replies are the valid cases. - `npx vitest run --config tests/runner-e2e/vitest.config.ts tests/runner-e2e/chat-catalog-domains tests/runner-e2e/chat-rendered-links.test.ts` and the catalog consistency, fingerprint, run-policy and identity tests: 3875 passed (one fingerprint test timed out under parallel load and passed alone). - `pnpm test:e2e:runner:typecheck`: passed. - `node --test tests/runner-e2e/chat-full-catalog-testops-manifest.test.mjs`: 10 passed. - `node tests/runner-e2e/source-sdk-public-inputs.mjs649536ab2c--check`: unchanged. - Paid run (8 cells, OpenCode 1017): paid run [43345834002](https://github.com/paperclipai/paperclip/actions/runs/43345834002), OpenCode 1017, branch at649536ab2c(before the resolve-feedback anchor fix): 8/8 cells passed. - `routines.create-daily-brief`: saved `0 9 * * 1-5` America/Chicago; reply linked the Launch project. - `routines.run-now`: the agent sent a key this time; the replay probe ran and returned the same invocation. The keyless path is covered only by calibration. - `companies.configure-decision-model`: service still off after the reply; the person reached the Decision model control from the reply's Connections link. - `documents-artifacts.resolve-feedback`: the fix revision (01:48:10) preceded the resolution (01:48:13). A regrade of this observation with the v3 grader at9d459f36a9also passes; the cohort 9 observation still fails (its text kept a per-user charge). - `recovery.source-action`: recovery checks and the task link passed. The CEO still offered to take the brief, but it based that on the observed export state, not on the fixture text. - `steering.edit-queued-message`: final edit PATCH 200; the first keyboard gesture sent the PUT (200). - `documents-artifacts.produce-download` and `agents.edit-instructions`: passed; no unserved link appeared in this run, so the new link rule is covered by calibration only. ## Risks - The link helper is shared. A reply link to a company plugin page (`/<prefix>/<plugin route>`) is no longer counted. No current grader expects one. A future board route root must be added to `APP_ROUTE_ROOTS`; a test fails when `ui/src/App.tsx` changes its route roots. - A reply that only links a page through `//PREFIX/...` now fails cases that need that link. This is intended. - `configure-decision-model` no longer checks reply wording. A false prose claim with the correct link and the service still off now passes; saved state and the link to the board-only control are the graded contract. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, via Claude Code with tool use (shell, file edits). Extended reasoning was available. ## 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>
202 lines
18 KiB
TypeScript
202 lines
18 KiB
TypeScript
import { chatCatalogNativePhaseDeadline, chatCatalogNativePhaseIsTimely } from "../chat-catalog-contract.js";
|
|
import { expect, type Locator, type Page, type Response } from "@playwright/test";
|
|
import { createHash } from "node:crypto";
|
|
import { writeFile } from "node:fs/promises";
|
|
import { inflateRawSync } from "node:zlib";
|
|
import { pollUntil } from "../api.js";
|
|
import { collectRunEvents } from "../run-observations.js";
|
|
import type { ChatCatalogContext } from "../chat-catalog-contract.js";
|
|
import { checks, type Entity } from "./internal-support.js";
|
|
import { busyRuntimeWorker, releaseRuntimeWorker } from "./runtime-busy-worker.js";
|
|
import { runtimeDefinition, runtimeObservation, observeRuntime, type RuntimeAgent } from "./runtime-support.js";
|
|
import type { IssueAttachment, IssueQueuedCommentQueue } from "../../../packages/shared/src/types/issue.js";
|
|
import type { IssueWorkProduct } from "../../../packages/shared/src/types/work-product.js";
|
|
/** Move a queued message up one place with the drag handle's keyboard gesture, as a keyboard user does.
|
|
* Saving an edit disables every handle until that queue change settles, and a gesture pressed on a disabled
|
|
* handle does nothing, so wait for this handle to be enabled first. The gesture must send the queue order
|
|
* request; its status is returned so the caller can tell an accepted move from a refused one. When a gesture
|
|
* sends nothing, `beforeRetry` (for example a reload that refetches the queue) runs and the gesture is pressed
|
|
* again, up to `attempts` gestures in all; every gesture is reported. */
|
|
export async function keyboardMoveQueuedMessageUp(page: Pick<Page, "waitForResponse">, handle: Pick<Locator, "isEnabled" | "focus" | "press">,
|
|
timeoutMs = 15_000, intervalMs = 100, options: { attempts?: number; beforeRetry?: () => Promise<void> } = {}): Promise<{ status: number; waitedForEnabledMs: number; gestures: number }> {
|
|
const attempts = Math.max(1, options.attempts ?? 1);
|
|
for (let gesture = 1; ; gesture++) {
|
|
const started = Date.now();
|
|
while (!await handle.isEnabled()) {
|
|
if (Date.now() - started >= timeoutMs) throw new Error("The queued message's reorder handle stayed disabled");
|
|
await new Promise(resolve => setTimeout(resolve, intervalMs));
|
|
}
|
|
const waitedForEnabledMs = Date.now() - started;
|
|
const sent = page.waitForResponse((response: Response) => response.request().method() === "PUT"
|
|
&& new URL(response.url()).pathname.endsWith("/queued-comments/order"), { timeout: timeoutMs });
|
|
sent.catch(() => undefined);
|
|
await handle.focus(); await handle.press("Space"); await handle.press("ArrowUp"); await handle.press("Space");
|
|
const response = await sent.catch(() => null);
|
|
if (response) return { status: response.status(), waitedForEnabledMs, gestures: gesture };
|
|
if (gesture >= attempts) throw new Error(`The keyboard reorder gesture sent no queue order request after ${gesture} gesture(s)`);
|
|
await options.beforeRetry?.();
|
|
}
|
|
}
|
|
const MAX_DELIVERABLE_BYTES = 262_144;
|
|
/** Text of each stored or deflated entry in a zip deliverable, read from its central directory; [] when it is not a readable zip. */
|
|
export function zipEntryTexts(bytes: Buffer): string[] {
|
|
try {
|
|
const eocd = bytes.lastIndexOf(Buffer.from([0x50, 0x4b, 0x05, 0x06])); if (eocd < 0 || eocd + 22 > bytes.length) return [];
|
|
const texts: string[] = []; let at = bytes.readUInt32LE(eocd + 16);
|
|
for (let index = 0, count = bytes.readUInt16LE(eocd + 10); index < count && at + 46 <= bytes.length && bytes.readUInt32LE(at) === 0x02014b50; index++) {
|
|
const method = bytes.readUInt16LE(at + 10), size = bytes.readUInt32LE(at + 20), local = bytes.readUInt32LE(at + 42);
|
|
const start = local + 30 + bytes.readUInt16LE(local + 26) + bytes.readUInt16LE(local + 28), data = bytes.subarray(start, start + size);
|
|
if (method === 0) texts.push(data.toString("utf8"));
|
|
else if (method === 8) texts.push(inflateRawSync(data, { maxOutputLength: 4 * MAX_DELIVERABLE_BYTES }).toString("utf8"));
|
|
at += 46 + bytes.readUInt16LE(at + 28) + bytes.readUInt16LE(at + 30) + bytes.readUInt16LE(at + 32);
|
|
}
|
|
return texts;
|
|
} catch { return []; }
|
|
}
|
|
/** Find a message object with the exact comment id and body, descending into JSON nested as string values. */
|
|
function jsonCarriesComment(value: unknown, comment: { id: string; body: string }, depth = 0): boolean {
|
|
if (depth > 6) return false;
|
|
if (typeof value === "string") {
|
|
const text = value.trim(); if (!/^[[{]/.test(text)) return false;
|
|
try { return jsonCarriesComment(JSON.parse(text), comment, depth + 1); } catch { return false; }
|
|
}
|
|
if (Array.isArray(value)) return value.some(item => jsonCarriesComment(item, comment, depth + 1));
|
|
if (!value || typeof value !== "object") return false;
|
|
const row = value as Record<string, unknown>;
|
|
return (row.id === comment.id && row.body === comment.body) || Object.values(row).some(item => jsonCarriesComment(item, comment, depth + 1));
|
|
}
|
|
/** Native continuations embed new comments as JSON (an envelope may nest it again as a string), so a body with quotes or newlines appears escaped. */
|
|
export const TASK_HISTORY_READ_EVENT = "task_history.read";
|
|
export function historyReadRevisions(events: ReadonlyArray<{ eventType?: unknown; payload?: unknown }>) {
|
|
const reads: Record<string, string> = {};
|
|
for (const row of events) {
|
|
if (row.eventType !== TASK_HISTORY_READ_EVENT) continue;
|
|
const comments = (row.payload as { comments?: unknown } | null | undefined)?.comments;
|
|
if (!comments || typeof comments !== "object" || Array.isArray(comments)) continue;
|
|
for (const [id, at] of Object.entries(comments as Record<string, unknown>))
|
|
if (typeof at === "string" && Number.isFinite(Date.parse(at)) && !(Date.parse(reads[id] ?? "") >= Date.parse(at))) reads[id] = at;
|
|
}
|
|
return reads;
|
|
}
|
|
export function readCurrentRevision(reads: Record<string, string> | undefined, comment: { id: string; updatedAt?: unknown } | undefined) {
|
|
if (!comment) return false;
|
|
const read = Date.parse(String(reads?.[comment.id] ?? "")), current = Date.parse(String(comment.updatedAt ?? ""));
|
|
return Number.isFinite(read) && Number.isFinite(current) && read >= current;
|
|
}
|
|
export async function runHistoryReads(ctx: ChatCatalogContext, runId: string) {
|
|
const events = await collectRunEvents<{ seq?: number; eventType?: unknown; payload?: unknown }>((afterSeq, limit) => ctx.input.api.get(`/api/heartbeat-runs/${runId}/events?afterSeq=${afterSeq}&limit=${limit}`));
|
|
return historyReadRevisions(events);
|
|
}
|
|
export function settledQueue<T>(accept: (value: T) => boolean, quietMs: number) {
|
|
let since: number | undefined;
|
|
return (value: T) => { if (!accept(value)) { since = undefined; return false; } since ??= Date.now(); return Date.now() - since >= quietMs; };
|
|
}
|
|
export function promptCarriesComment(prompt: string | undefined, comment: { id: string; body: string }) {
|
|
return typeof prompt === "string" && prompt.includes(comment.id)
|
|
&& (prompt.includes(comment.body) || prompt.includes(JSON.stringify(comment.body).slice(1, -1)) || jsonCarriesComment(prompt, comment));
|
|
}
|
|
/** A task is named by its setup-assigned identifier (which chat links) or by a link to its page. */
|
|
export function replyNamesTask(reply: string, task: Entity) {
|
|
const keys = [task.identifier, task.id].filter((key): key is string => !!key);
|
|
return keys.some(key => new RegExp(`(?<![A-Za-z0-9-])${key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?![0-9])`).test(reply));
|
|
}
|
|
/** The saved requirement is the one queued comment the controller's canonical turn wrote; its wording is the model's. */
|
|
function savedRequirement(queue: IssueQueuedCommentQueue | undefined, leadId: string) {
|
|
return queue?.entries.length === 1 && queue.entries[0]!.comment.authorAgentId === leadId ? queue.entries[0] : undefined;
|
|
}
|
|
export function gradeQueuedFollowup(value: unknown) {
|
|
const c = checks(); const o = runtimeObservation(value);
|
|
c.add("real-queue-and-delivery-evidence", !!o, "The actual task queue, saved requirement, real initial worker and later consuming native input are required."); if (!o) return c.result();
|
|
const task = o.state.task as Entity; const queued = o.state.queuedAtReply as IssueQueuedCommentQueue | undefined;
|
|
const requirement = savedRequirement(queued, o.leadId);
|
|
c.add("correct-task-ordered-waiting-requirement-once", !!queued && queued.issueId === task.id && ["queued", "deferred"].includes(queued.state ?? "")
|
|
&& queued.entries.length === 1 && requirement?.position === 0 && o.state.workerStatusAtReply === "running"
|
|
&& requirement.comment.createdByRunId === o.state.canonicalRunId,
|
|
"Exactly one contact-section instruction is durably queued in order on the genuine running Website task and attributed to the source controller turn.");
|
|
// Whether the reply describes the requirement as pending is free-form; it is read from the evidence, not matched by wording.
|
|
c.add("canonical-reply-identifies-affected-task", replyNamesTask(String(o.state.queryReply), task),
|
|
"The canonical reply, written while the requirement still waits behind Morgan's active turn, names the Website task it was saved on.");
|
|
c.add("normal-continuation-consumes-exact-input-once", !!requirement && o.state.consumedCommentId === requirement.comment.id
|
|
&& o.state.deliveryNativeInputBound === true && o.state.consumingRunCount === 1 && o.state.queueEmptyAfterDelivery === true
|
|
&& o.runs.length === 3 && o.runs.every(run => run.status === "succeeded")
|
|
&& o.runs.filter(run => run.agentId === (o.state.worker as Entity).id).length === 2,
|
|
"The same saved requirement is consumed by one ordinary successor native turn after the real prior owner settles.");
|
|
c.add("earlier-work-and-contact-result-retained", o.state.initialBriefRevisionRetained === true && (o.state.contactResultRevision === true || o.state.contactResultDeliverable === true)
|
|
&& o.tasks.length === 1 && o.tasks[0]?.id === task.id && o.tasks[0]?.assigneeAgentId === (o.state.worker as Entity).id && o.tasks[0]?.status === "done",
|
|
"The original worker's saved brief revision remains inspectable and the successor saves an actual contact-section result on the same task, as a document revision or a registered deliverable.");
|
|
return c.result();
|
|
}
|
|
export const runtimeQueueCases = [runtimeDefinition("steering.queue-follow-up", busyRuntimeWorker, gradeQueuedFollowup, {
|
|
oracleVersion: "paperclip.chat-catalog.runtime-queue.v3",
|
|
sourceFiles: ["chat-catalog-domains/runtime-queue.ts", "chat-catalog-domains/runtime-busy-worker.ts", "chat-catalog-domains/runtime-support.ts", "chat-scenarios/steering.yaml"],
|
|
expectedRunCount: 3, attemptTimeoutMs: 720_000,
|
|
setupPolicy: { readiness: "preserve-scenario", invariantCheckIds: ["lead-ready", "real-busy-worker", "worker-task-scope"] },
|
|
async verifySetup(ctx, state) {
|
|
const c = checks(); const lead = await ctx.input.api.get<RuntimeAgent>(`/api/agents/${ctx.input.fixtures.agent.id}`);
|
|
const worker = await ctx.input.api.get<RuntimeAgent>(`/api/agents/${(state.worker as Entity).id}`); const run = (await ctx.allRuns()).find(row => row.id === state.workerRunId);
|
|
c.add("lead-ready", lead.lifecycleState === "ready" && ["active", "idle"].includes(lead.status ?? ""), "The actual controller is admitted normally.");
|
|
c.add("real-busy-worker", worker.lifecycleState === "ready" && ["active", "running"].includes(worker.status ?? "") && run?.status === "running" && state.workerWasReallyWaiting === true,
|
|
"Morgan is genuinely busy in a native tool wait, without a fabricated busy state.");
|
|
c.add("worker-task-scope", run?.agentId === worker.id && run.companyId === ctx.input.fixtures.company.id
|
|
&& [run.contextSnapshot?.issueId, (run as typeof run & { nativeIssueId?: string })?.nativeIssueId].includes((state.task as Entity).id), "The actual active owner belongs to the exact task and company.");
|
|
return c.result();
|
|
},
|
|
async act(ctx, state) {
|
|
const phase = await pollUntil({ label: "Canonical follow-up saved while Morgan remains active", deadlineAt: chatCatalogNativePhaseDeadline(ctx, Date.now() + 150_000),
|
|
load: async () => { await ctx.refreshIssue(); return { source: ctx.issue(), runs: await ctx.allRuns(), queue: await ctx.input.api.get<IssueQueuedCommentQueue>(`/api/issues/${(state.task as Entity).id}/queued-comments`) }; },
|
|
accept: value => chatCatalogNativePhaseIsTimely(ctx) && (value.source?.conversationState === "waiting" && value.runs.length === 2
|
|
&& value.runs.find(run => run.id === state.workerRunId)?.status === "running"
|
|
&& value.runs.some(run => run.agentId === ctx.input.fixtures.agent.id && run.status === "succeeded")
|
|
&& !!savedRequirement(value.queue, ctx.input.fixtures.agent.id)) });
|
|
const canonical = phase.runs.find(run => run.agentId === ctx.input.fixtures.agent.id)!;
|
|
state.canonicalRunId = canonical.id; state.workerStatusAtReply = phase.runs.find(run => run.id === state.workerRunId)!.status;
|
|
state.queuedAtReply = phase.queue; state.queryReply = (await observeRuntime(ctx, state)).reply;
|
|
const source = ctx.input.page.url(), task = state.task as Entity;
|
|
await ctx.input.page.goto(`/${ctx.input.fixtures.company.issuePrefix}/issues/${task.identifier ?? task.id}`, { waitUntil: "domcontentloaded" });
|
|
const requirement = savedRequirement(phase.queue, ctx.input.fixtures.agent.id)!;
|
|
await expect(ctx.input.page.getByTestId(`task-chat-queued-message-${requirement.comment.id}`)).toBeVisible();
|
|
await ctx.input.capture("actual-contact-followup-queue", "Contact requirement remains visibly queued behind real active work", "runtime-contact-queue.png");
|
|
await ctx.input.page.goto(source, { waitUntil: "domcontentloaded" });
|
|
const marker = `Original website brief ${ctx.input.nonce}`; state.briefMarker = marker;
|
|
await writeFile((state.gate as { gate: string }).gate, `The human brief is now ready: save an initial task document with the exact reference ${marker}, then finish this current turn normally. Keep all prior user requirements queued by Paperclip intact for normal delivery; do not create tasks or external effects.`, "utf8");
|
|
const delivered = await pollUntil({ label: "Normal successor receives actual queued contact requirement", deadlineAt: Date.now() + 240_000,
|
|
load: async () => ({ task: await ctx.input.api.get<Entity>(`/api/issues/${task.id}`), runs: await ctx.allRuns(), queue: await ctx.input.api.get<IssueQueuedCommentQueue>(`/api/issues/${task.id}/queued-comments`) }),
|
|
accept: value => value.task.status === "done" && value.runs.length === 3 && value.runs.every(run => run.status === "succeeded") && value.queue.entries.length === 0,
|
|
reject: value => value.runs.length > 3 || value.runs.some(run => ["failed", "cancelled", "timed_out"].includes(run.status)) ? "The single declared queued continuation failed or duplicated work" : undefined });
|
|
const successors = delivered.runs.filter(run => run.agentId === (state.worker as Entity).id && run.id !== state.workerRunId);
|
|
const inputs = await Promise.all(successors.map(run => ctx.input.api.get<{ runnerProfileJson?: { nativeExecutionInput?: { task?: { prompt?: string } } } }>(`/api/heartbeat-runs/${run.id}`)));
|
|
state.consumedCommentId = requirement.comment.id; state.consumingRunCount = successors.length;
|
|
state.deliveryNativeInputBound = inputs.length === 1 && promptCarriesComment(inputs[0]?.runnerProfileJson?.nativeExecutionInput?.task?.prompt, requirement.comment);
|
|
state.queueEmptyAfterDelivery = delivered.queue.entries.length === 0;
|
|
},
|
|
async observe(ctx, state) {
|
|
const o = await observeRuntime(ctx, state);
|
|
state.initialBriefRevisionRetained = o.revisions.some(revision => revision.createdByRunId === state.workerRunId && (revision.body ?? "").includes(String(state.briefMarker)));
|
|
const successorIds = o.runs.filter(run => run.agentId === (state.worker as Entity).id && run.id !== state.workerRunId).map(run => run.id);
|
|
state.contactResultRevision = o.revisions.some(revision => successorIds.includes(revision.createdByRunId ?? "") && /contact/i.test(revision.body ?? "")
|
|
&& revision.createdByAgentId === (state.worker as Entity).id && o.documents.some(doc => doc.id === revision.documentId && doc.latestRevisionId === revision.id));
|
|
// A website build may be delivered as a registered file (often a zip) rather than a document; its file name is the model's, so read every successor deliverable's verified bytes.
|
|
const taskId = (state.task as Entity).id;
|
|
const [products, attachments] = await Promise.all([ctx.input.api.get<IssueWorkProduct[]>(`/api/issues/${taskId}/work-products`), ctx.input.api.get<IssueAttachment[]>(`/api/issues/${taskId}/attachments`)]);
|
|
const delivered = attachments.filter(attachment => attachment.issueId === taskId && successorIds.includes(attachment.originatingRunId ?? "") && attachment.byteSize <= MAX_DELIVERABLE_BYTES
|
|
&& products.some(product => product.type === "artifact" && product.createdByRunId === attachment.originatingRunId && product.metadata?.attachmentId === attachment.id));
|
|
const texts: string[] = [];
|
|
for (const attachment of delivered) {
|
|
const bytes = await ctx.input.api.getAttachmentContent(attachment.id);
|
|
if (bytes.length !== attachment.byteSize || createHash("sha256").update(bytes).digest("hex") !== attachment.sha256) continue;
|
|
const entries = zipEntryTexts(bytes); texts.push(...(entries.length > 0 ? entries : [bytes.toString("utf8")]));
|
|
}
|
|
state.contactResultDeliverable = texts.some(text => /contact/i.test(text));
|
|
return o;
|
|
},
|
|
async verifyResult(ctx, state) {
|
|
const source = ctx.input.page.url(), task = state.task as Entity;
|
|
await ctx.input.page.goto(`/${ctx.input.fixtures.company.issuePrefix}/issues/${task.identifier ?? task.id}`, { waitUntil: "domcontentloaded" });
|
|
await ctx.input.page.reload({ waitUntil: "domcontentloaded" });
|
|
await expect(ctx.input.page.getByRole("heading", { name: task.title!, exact: true }).first()).toBeVisible();
|
|
await expect(ctx.input.page.getByTestId("task-chat-queued-messages")).toHaveCount(0);
|
|
await ctx.input.page.goto(source, { waitUntil: "domcontentloaded" });
|
|
},
|
|
cleanup: async (_ctx, state) => releaseRuntimeWorker(state),
|
|
})];
|