Files
PaperClipAI/tests/runner-e2e/chat-catalog-domains/runtime-discard.ts
T
DottaandClaude Opus 5.5 d16becac04 test(evals): fix cohort-10 secrets entry, steering graders, private-task settle and queue brief (#21296)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The chat eval catalog checks real chat journeys against saved
product state, not reply wording
> - Full cohort 10 failed six cases where the product worked but the
eval was out of date or raced
> - #21225 redesigned Settings → Secrets, and #21243 changed when a
queued comment counts as delivered
> - The private secret steps, two steering graders, one final run check
and one fixture did not follow
> - This pull request updates those eval layers and keeps each one able
to fail a broken product
> - The benefit is that these six cases measure the product again
instead of the stale harness

## Linked Issues or Issue Description

Refs #21225
Refs #21243

**What happened?**
In full cohort 10 (OpenCode, local), six cases failed for eval reasons:

- `secrets.configure-company-secret` and `secrets.personal-secret`: the
private browser step waited for the old "Create secret" dialog and its
Provider field, and for the old personal form text. #21225 renamed the
dialog to "New secret", removed Provider, moved Key under "More
options", and moved the definition name into the "Set your value for …"
heading.
- `steering.steer-active` and `steering.discard-queued-message`:
Morgan's running turn read the queued comments through task history and
cited them in its accepted result. Under #21243 that is delivery, so no
continuation ran. The graders still required one more run and timed out.
- `tasks.private-task`: the final run check read the ledger while the
CEO's `chat_task_completed` follow-up was still running.
- `steering.queue-follow-up`: the brief was only a reference string, so
the continuation asked a question instead of building.

**Expected behavior**
Each case grades the product's current contract on saved state, and
still fails a broken product.

**Steps to reproduce**
Run the six cases at `origin/master` with the OpenCode local profile.
See the cohort-10 evidence for each case.

## What Changed

- `external-private-browser-worker.ts`: the company step opens "New
secret", finds the dialog by its "Who provides the value" radiogroup,
selects Organization, opens "More options" for a requested key, and
picks Paperclip-encrypted storage only when the "Stored in" picker is
shown. The saved secret must now have provider `local_encrypted`. The
personal step binds the form by the heading "Set your value for Personal
publishing credential". Credential handling is unchanged.
`manual-private-*.ts` is unchanged.
- `external-company-secret-create-dialog.test.ts`: the canary page uses
the new dialog. It adds a several-vaults variant (valid), a
wrong-storage result and the retired "Create secret" form (both
rejected). Source anchors follow `Secrets.tsx`.
- `external-personal-secret-entry-dialog.test.ts`: checks that the
worker heading matches what `SetMyUserSecretDialog.tsx` renders, and
rejects another definition and the "Replace your value" form.
- New `runtime-cited-delivery.ts`: `owedAfterTurn` (queued comments the
turn did not read at the current revision and cite) and
`continuationCarriesOwed` (one continuation carries each owed comment
once, with its text and the earlier-read warning, and none that the turn
handled).
- `runtime-active-steering.ts` (oracle `steer-active.v9`): records the
queued comments (person and any CEO relay) and the worker's receipts.
Delivery passes if every queued comment was handled in turn with no
continuation, or one continuation carries exactly the owed ones. Run
count is 2 plus one when anything is owed. The website the worker
registered last must still render blue.
- `runtime-discard.ts` (oracle `runtime-discard.v7`, `minimumRunCount:
4`): the same rule for the font note and the later contact request. The
run that handled the contact request must save its labelled section. The
discarded request must never be cited. The gate no longer says "Leave
saved follow-ups for their ordinary continuation", because that
contradicts the #21243 contract.
- `internal-private-delegation.ts` (oracle `private-task.v3`):
`verifyResult` waits for the delegated work and its completion follow-up
to settle, in the pattern of `identity-plan-review.ts`. A failed or
cancelled run still stops the wait. A worker still running at the
deadline stays bounded active work.
- `runtime-queue.ts` (oracle `runtime-queue.v4`): the gate gives a
complete website brief (product, page, hero copy, features, pricing,
company details). It does not contain the word "contact", so the brief
does not complete the queued requirement.
- Oracle bumps for the secrets cases:
`company-secret-controller-baseline.v22`, `personal-secret.v21`.
`chat-catalog-descriptors.json` follows all bumps and source files. No
scenario YAML changed, so the TestOps manifest is unchanged.

## Why each new check still catches a broken product

- Secrets: the old check matched removed UI text, so it failed a working
product. The new check uses roles and labels, and still fails a missing
form, a failed POST, wrong saved metadata and storage outside Paperclip.
- Steering: the old check required a continuation, which #21243 removes
when the turn cites the comment. The new check still fails an uncited
read with no continuation (the lost-comment bug), a citation without a
current-revision read, a cited comment that was not applied (no blue
page or no saved label), a replay of a handled comment, and any extra
run.
- Private task: the old check read the ledger at a random point after
acceptance. The case still fails if the follow-up fails or is cancelled.
- Queue brief: the grader is unchanged. The brief test fails if the
brief leaks the contact requirement.

## Verification

- `npx vitest run --config tests/runner-e2e/vitest.config.ts
tests/runner-e2e/chat-catalog tests/runner-e2e/chat-catalog-domains`:
285 files, 3948 tests pass.
- Calibration uses the retained cohort-10 receipts. The steer-active
worker read and cited both queued comments. The discard worker read and
cited the font note and the later contact request. Both now pass.
Reworded-valid variants (target handled in turn, relay or font note owed
to one continuation) pass. The broken variants listed above fail.
- `PAPERCLIP_CHAT_EVAL_SECRET_ROUTE_CANARY=1` secrets canaries: 3 of 3
pass. RED: the old worker against the new dialog page fails
(`locator.fill` timeout).
- `pnpm test:e2e:runner:typecheck`: pass. `node --test
tests/runner-e2e/chat-full-catalog-testops-manifest.test.mjs`: 10 of 10.
`node tests/runner-e2e/source-sdk-public-inputs.mjs
e0b618b02a --check`: `changed: false`.
- Paid run: Runner Full-Stack E2E 43368487002 on throwaway branch
`chat-eval/full10-paid` (the six cases). The result follows in a
comment.

## Risks

- Steering: a run that applies a comment but does not cite it still
needs one continuation. This matches the product contract.
- The steer-active gate still asks the worker to keep queued
requirements for normal delivery. Both paths are accepted, so the gate
cannot cause a false pass.
- The private-task settle adds up to 120 seconds inside the original
observation budget.
- Low risk overall: eval-only changes. No product code changed.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, through 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-13 03:38:12 -06:00

160 lines
18 KiB
TypeScript

import { chatCatalogNativePhaseDeadline, chatCatalogNativePhaseIsTimely, chatCatalogNativePhaseRemainingBudget } from "../chat-catalog-contract.js";
import { expect } from "@playwright/test";
import { writeFile } from "node:fs/promises";
import type { IssueComment, IssueQueuedCommentQueue } from "../../../packages/shared/src/types/issue.js";
import { sendChatMessage } from "../chat-flow.js";
import { pollUntil } from "../api.js";
import { submitTaskReply } from "../user-actions.js";
import { checks, hasLink, type Entity } from "./internal-support.js";
import { probeAgentPermission, cleanupIdentityProbes } from "./identity-support.js";
import { releaseRuntimeWorker } from "./runtime-busy-worker.js";
import { humanQueuedRuntime, probeConsumedHumanQueue } from "./runtime-queue-controls.js";
import { handledInTurn, runCommentReceipts, runtimeQueueCases, settledQueue } from "./runtime-queue.js";
import { continuationCarriesOwed, owedAfterTurn, type CommentReceipts, type QueuedFollowUp } from "./runtime-cited-delivery.js";
import { runtimeDefinition, runtimeObservation, observeRuntime } from "./runtime-support.js";
const contactText = "Also add a contact section to the website.";
/** Native prompts embed task comments as JSON, so a multi-line body appears with escaped newlines. */
export function promptCarries(prompt: string | undefined, body: string) {
return !!prompt && body.trim().length > 0 && (prompt.includes(body) || prompt.includes(JSON.stringify(body).slice(1, -1)));
}
/** Links the reply saved in Markdown, plus links already rendered when the reply was observed. */
export function replyLinkHrefs(reply: string, rendered: readonly string[]) {
return [...new Set([...rendered, ...[...reply.matchAll(/\]\(([^)\s]+)\)/g)].map(match => match[1]!)])];
}
const labelledHeading = (body: string, label: string) => body.split(/\r?\n/).some(line => /^#{1,6}\s/.test(line) && line.includes(label));
export function documentContactRemoved(rows: ReadonlyArray<{ id: string; body?: string | null; createdByRunId?: string | null }>, latestRevisionId: unknown, consumerRunId: string, label: string) {
const number = (row: object) => Number((row as { revisionNumber?: unknown }).revisionNumber);
const revisions = [...rows].sort((a, b) => number(a) - number(b));
const final = revisions.find(row => row.id === latestRevisionId);
const saves = revisions.filter(row => row.createdByRunId === consumerRunId && (row.body ?? "").includes(label));
if (!saves.length) return !(final?.body ?? "").includes(label);
const previous = revisions.filter(row => number(row) < number(saves[0]!)).at(-1);
const hadSection = [previous, ...saves].some(row => labelledHeading(row?.body ?? "", label));
return !!final && hadSection && !labelledHeading(final.body ?? "", label);
}
export function gradeDiscard(value: unknown) {
const c = checks(), o = runtimeObservation(value);
c.add("actual-pending-and-consumed-cancellation-evidence", !!o, "Both actual human discard and separately consumed input with later new direction are required."); if (!o) return c.result();
const s = o.state, before = s.queueBefore as IssueQueuedCommentQueue, after = s.queueAfterDiscard as IssueQueuedCommentQueue;
const target = before?.entries.find(row => row.comment.id === s.targetId);
c.add("only-owned-pending-message-discarded", !!target && target.comment.authorUserId === s.humanId && !target.comment.authorAgentId
&& target.comment.body === contactText && !!after && after.issueId === before.issueId && after.entries.length === 1
&& after.entries[0]?.comment.id === before.entries.find(row => row.comment.id !== s.targetId)?.comment.id
&& after.entries[0]?.comment.body === before.entries.find(row => row.comment.id !== s.targetId)?.comment.body,
"The supported human control removes precisely the eligible owned contact request and preserves its neighbour.");
c.add("history-and-ui-retain-truthful-discard", s.discardVisible === true && s.discardedCommentStatus === 404
&& o.activity.some(row => row.action === "issue.queued_comment_discarded" && row.actorType === "user" && row.actorId === s.humanId
&& row.entityId === (s.task as Entity).id && row.details?.commentId === s.targetId) && s.discardedNeverDelivered === true,
"Actual absent pending comment, retained human audit history and consuming-run wake IDs prove this pending instruction will not be delivered.");
c.add("chat-guides-supported-human-discard", String(s.queryReply ?? "").trim().length > 0 && s.queryLinkedTask === true
&& s.targetPendingAfterReply === true && s.agentDiscardStatus === 403,
"The reply links the task whose queue holds the request, the request is still pending after the reply, and the agent cannot impersonate the person's discard.");
const followUps = Array.isArray(s.queuedFollowUps) ? s.queuedFollowUps as QueuedFollowUp[] : [], receipts = s.workerCommentReceipts as CommentReceipts | undefined;
const second = followUps.find(row => row.id === s.secondContactId), owed = owedAfterTurn(followUps, receipts);
const firstDelivery = followUps.length === 2 && !!second && !receipts?.cited?.includes(String(s.targetId)) && (owed.length
? s.firstDeliveryRunCount === 3 && s.continuationConsumerCount === 1 && s.continuationInputBound === true
: s.firstDeliveryRunCount === 2 && s.continuationConsumerCount === 0);
c.add("later-input-delivered-once-before-cancellation", firstDelivery && (handledInTurn(receipts, second) ? s.consumerRunId === s.workerRunId : owed.includes(second!) && s.consumedBeforeCancellation === true),
"Each saved follow-up is delivered once before the cancellation: the running turn read it and cited it as handled, or one ordinary continuation receives every follow-up not handled in turn and none that was. The discarded request is never cited as handled.");
c.add("already-delivered-input-cannot-be-erased", s.consumedStillReadable === true
&& s.lateDiscardStatus === 409 && s.latePhaseAttributed === true && String(s.lateReply ?? "").trim().length > 0,
"The consumed request stays readable and cannot be discarded late; the later answer is attributed to its own run.");
c.add("new-direction-reaches-exactly-one-native-continuation", s.cancelDirectionRunBound === true && s.finalQueueEmpty === true
&& s.consumedLabelSaved === true && s.finalPlanWithoutContact === true
&& s.initialRevisionRetained === true && o.runs.length === Number(s.firstDeliveryRunCount) + 2 && o.runs.every(row => row.status === "succeeded") && o.tasks.length === 1
&& o.tasks[0]?.id === (s.task as Entity).id && o.tasks[0]?.status === "done",
"A distinct saved instruction reaches one real later worker, updates the saved plan and preserves prior work/history without replaying the discarded request.");
return c.result();
}
export const runtimeDiscardCases = [runtimeDefinition("steering.discard-queued-message", ctx => humanQueuedRuntime(ctx, contactText), gradeDiscard, {
authentication: "human-session", expectedHumanMessageCount: 2, expectedRunCount: 5, minimumRunCount: 4, attemptTimeoutMs: 1_020_000, oracleVersion: "paperclip.chat-catalog.runtime-discard.v7",
sourceFiles: ["chat-catalog-domains/runtime-discard.ts", "chat-catalog-domains/runtime-queue-controls.ts", "chat-catalog-domains/runtime-queue.ts", "chat-catalog-domains/runtime-cited-delivery.ts", "chat-catalog-domains/runtime-busy-worker.ts", "chat-catalog-domains/runtime-support.ts", "chat-catalog-domains/identity-support.ts", "chat-scenarios/steering.yaml"],
setupPolicy: runtimeQueueCases[0]!.setupPolicy, verifySetup: runtimeQueueCases[0]!.verifySetup,
async act(ctx, state) {
await pollUntil({ label: "Human discard guidance while Morgan is genuinely active", deadlineAt: chatCatalogNativePhaseDeadline(ctx, Date.now() + 150_000),
load: async () => { await ctx.refreshIssue(); return { source: ctx.issue(), runs: await ctx.allRuns() }; },
accept: v => chatCatalogNativePhaseIsTimely(ctx) && (v.source?.conversationState === "waiting" && v.runs.length === 2 && v.runs.some(row => row.id === state.workerRunId && row.status === "running")
&& v.runs.some(row => row.agentId === ctx.input.fixtures.agent.id && row.status === "succeeded")) });
const answered = await observeRuntime(ctx, state);
const source = ctx.input.page.url(), task = state.task as Entity, root = `/api/issues/${task.id}`, queuePath = `${root}/queued-comments`;
const initial = await ctx.input.api.get<IssueQueuedCommentQueue>(queuePath), targetId = String(state.targetId);
state.queryReply = answered.reply; state.queryLinkedTask = hasLink({ ...answered, links: replyLinkHrefs(answered.reply, answered.links) }, "issues", task);
state.targetPendingAfterReply = initial.entries.some(row => row.comment.id === targetId && row.comment.body === contactText);
state.agentDiscardStatus = await probeAgentPermission(ctx, `${queuePath}/${targetId}`, "DELETE", { queueId: initial.queueId, revision: initial.revision });
await ctx.input.page.goto(`/${ctx.input.fixtures.company.issuePrefix}/issues/${task.identifier ?? task.id}`, { waitUntil: "domcontentloaded" });
await ctx.input.page.getByTestId(`task-chat-queued-discard-${targetId}`).click();
state.queueAfterDiscard = await pollUntil({ label: "Only the owned contact request is removed", deadlineAt: Date.now() + 20_000,
load: () => ctx.input.api.get<IssueQueuedCommentQueue>(queuePath), accept: q => q.entries.length === 1 && q.entries.every(row => row.comment.id !== targetId) });
await expect(ctx.input.page.getByTestId(`task-chat-queued-message-${targetId}`)).toHaveCount(0);
await ctx.input.page.reload({ waitUntil: "domcontentloaded" });
await expect(ctx.input.page.getByTestId(`task-chat-queued-message-${initial.entries.find(row => row.comment.id !== targetId)!.comment.id}`)).toBeVisible();
state.discardVisible = true; state.discardedCommentStatus = (await ctx.input.page.request.get(`${root}/comments/${targetId}`)).status();
await ctx.input.capture("actual-human-contact-discard", "Only the eligible contact request has left the real task queue", "runtime-discard.png");
// This new, explicit human request is a distinct later instruction. It
// deliberately reaches delivery before its cancellation.
const secondText = `I have changed my mind: add a contact section to the saved website plan, labelled ${ctx.input.nonce}. Keep the accessible-font requirement and finish this task.`;
await submitTaskReply(ctx.input.page, secondText);
const secondQueue = await pollUntil({ label: "Distinct human contact request genuinely queued", deadlineAt: Date.now() + 20_000,
load: () => ctx.input.api.get<IssueQueuedCommentQueue>(queuePath), accept: q => q.entries.length === 2 && q.entries.some(row => row.comment.body === secondText) });
const second = secondQueue.entries.find(row => row.comment.body === secondText)!;
state.secondContactId = second.comment.id;
await writeFile((state.gate as { gate: string }).gate, "The human brief is ready: save an initial website-plan task document, retaining accessible font guidance, then finish this turn normally.", "utf8");
type Delivery = { runs: Array<{ status: string }>; task: Entity; queue: IssueQueuedCommentQueue };
const delivered = (v: Delivery) => v.runs.every(row => row.status === "succeeded") && v.task.status === "done" && v.queue.entries.length === 0;
const settledInTurn = settledQueue((v: Delivery) => delivered(v) && v.runs.length === 2, 30_000);
const consumed = await pollUntil({ label: "Real later contact request consumed before cancellation", deadlineAt: Date.now() + 240_000,
load: async () => ({ runs: await ctx.allRuns(), task: await ctx.input.api.get<Entity>(root), queue: await ctx.input.api.get<IssueQueuedCommentQueue>(queuePath) }),
accept: v => settledInTurn(v) || delivered(v) && v.runs.length === 3,
reject: v => v.runs.length > 3 || v.runs.some(row => ["failed", "cancelled", "timed_out"].includes(row.status)) ? "The saved follow-ups failed or reached more than one continuation" : undefined });
const taskComments = await ctx.input.api.get<Entity[]>(`${root}/comments?order=asc`);
const followUps = secondQueue.entries.map(row => taskComments.find(comment => comment.id === row.comment.id)).filter((row): row is Entity => !!row)
.map(row => ({ id: String(row.id), updatedAt: row.updatedAt, body: String(row.body ?? "") }));
const receipts = await runCommentReceipts(ctx, String(state.workerRunId)); state.queuedFollowUps = followUps; state.workerCommentReceipts = receipts;
const successors = consumed.runs.filter(row => row.agentId === (state.worker as Entity).id && row.id !== state.workerRunId);
state.firstDeliveryRunCount = consumed.runs.length; state.continuationConsumerCount = successors.length;
const detail = successors[0] && await ctx.input.api.get<{ contextSnapshot?: { wakeCommentIds?: string[]; paperclipWake?: { comments?: Array<{ id?: string; readByEarlierTurn?: boolean }> } }; runnerProfileJson?: { nativeExecutionInput?: { task?: { prompt?: string } } } }>(`/api/heartbeat-runs/${successors[0].id}`);
const prompt = detail?.runnerProfileJson?.nativeExecutionInput?.task?.prompt;
state.continuationInputBound = !!detail && continuationCarriesOwed(followUps, receipts, { contextSnapshot: detail.contextSnapshot, prompt });
state.consumerRunId = handledInTurn(receipts, followUps.find(row => row.id === second.comment.id)) ? state.workerRunId : successors[0]?.id;
state.consumedBeforeCancellation = !!detail && detail.contextSnapshot?.wakeCommentIds?.includes(second.comment.id) === true && promptCarries(prompt, secondText);
state.discardedNeverDelivered = consumed.runs.every(row => !((row.contextSnapshot?.wakeCommentIds as string[] | undefined) ?? []).includes(targetId));
state.lateDiscardStatus = await probeConsumedHumanQueue(ctx, String(state.humanId), `${queuePath}/${second.comment.id}`, "DELETE", { queueId: secondQueue.queueId, revision: secondQueue.revision });
await ctx.input.page.goto(source, { waitUntil: "domcontentloaded" });
const message = `I later queued a different contact request on Website ${task.identifier ?? task.id}, comment ${second.comment.id}, and Morgan has already consumed it. Cancel that later contact requirement now by sending Morgan new direction to remove the contact section from the saved website plan while retaining the accessible-font requirement. Explain what happened to the already-delivered input; do not erase or rewrite it.`;
const priorIds = consumed.runs.map(row => row.id);
await sendChatMessage(ctx.input.page, message, chatCatalogNativePhaseRemainingBudget(ctx));
const final = await pollUntil({ label: "One real new-direction continuation after already-delivered cancellation", deadlineAt: Date.now() + 300_000,
load: async () => { await ctx.refreshIssue(); return { source: ctx.issue(), runs: await ctx.allRuns(), task: await ctx.input.api.get<Entity>(root), queue: await ctx.input.api.get<IssueQueuedCommentQueue>(queuePath) }; },
accept: v => v.source?.conversationState === "waiting" && v.runs.length === priorIds.length + 2 && v.runs.every(row => row.status === "succeeded") && v.task.status === "done" && v.queue.entries.length === 0,
reject: v => v.runs.length > priorIds.length + 2 || v.runs.some(row => ["failed", "cancelled", "timed_out"].includes(row.status)) ? "The declared later cancellation failed or duplicated execution" : undefined });
const later = final.runs.filter(row => !priorIds.includes(row.id)), lead = later.find(row => row.agentId === ctx.input.fixtures.agent.id), worker = later.find(row => row.agentId === (state.worker as Entity).id);
const sourceComments = await ctx.input.api.get<Entity[]>(`/api/issues/${ctx.issue()!.id}/comments?order=asc`), human = sourceComments.filter(row => !row.authorAgentId && row.body === message);
const replies = sourceComments.filter(row => row.createdByRunId === lead?.id && row.authorAgentId === ctx.input.fixtures.agent.id);
const leadInput = lead && await ctx.input.api.get<{ runnerProfileJson?: { nativeExecutionInput?: { task?: { prompt?: string } } } }>(`/api/heartbeat-runs/${lead.id}`);
state.latePhaseAttributed = human.length === 1 && !!lead && replies.length > 0 && promptCarries(leadInput?.runnerProfileJson?.nativeExecutionInput?.task?.prompt, human[0]!.id);
state.lateReply = replies.map(row => row.body).join("\n");
const comments = await ctx.input.api.get<IssueComment[]>(`${root}/comments?order=asc`), direction = comments.filter(row => row.authorAgentId === ctx.input.fixtures.agent.id && row.createdByRunId === lead?.id);
const workerInput = worker && await ctx.input.api.get<{ contextSnapshot?: { wakeCommentIds?: string[]; wakeCommentId?: string }; runnerProfileJson?: { nativeExecutionInput?: { task?: { prompt?: string } } } }>(`/api/heartbeat-runs/${worker.id}`);
state.cancelDirectionRunBound = later.length === 2 && !!worker && direction.length === 1
&& [...(workerInput?.contextSnapshot?.wakeCommentIds ?? []), workerInput?.contextSnapshot?.wakeCommentId].includes(direction[0]!.id)
&& promptCarries(workerInput?.runnerProfileJson?.nativeExecutionInput?.task?.prompt, direction[0]!.body);
state.finalWorkerRunId = worker?.id; state.consumedStillReadable = comments.some(row => row.id === second.comment.id && row.body === secondText && !row.deletedAt);
state.finalQueueEmpty = final.queue.entries.length === 0;
},
async observe(ctx, state) {
const o = await observeRuntime(ctx, state);
state.initialRevisionRetained = o.revisions.some(row => row.createdByRunId === state.workerRunId && row.createdByAgentId === (state.worker as Entity).id);
// The consumed request asked for a contact section labelled with the attempt nonce. Its
// consuming run must have saved that label, and the cancellation run's latest plan must drop it.
const label = ctx.input.nonce, worker = (state.worker as Entity).id;
state.consumedLabelSaved = o.revisions.some(row => row.createdByRunId === state.consumerRunId && row.createdByAgentId === worker && (row.body ?? "").includes(label));
const latest = o.revisions.filter(row => row.createdByRunId === state.finalWorkerRunId && row.createdByAgentId === worker
&& o.documents.some(doc => doc.id === row.documentId && doc.latestRevisionId === row.id));
state.finalPlanWithoutContact = latest.length > 0 && o.documents.every(doc => documentContactRemoved(
o.revisions.filter(row => row.documentId === doc.id), doc.latestRevisionId, String(state.consumerRunId), label));
return o;
},
async cleanup(ctx, state) { try { await cleanupIdentityProbes(ctx); } finally { await releaseRuntimeWorker(state); } },
})];