test: qualify active chat handoff, worker retry and grounded answers

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip committed 2026-09-21 16:25:46 -05:00
1 parent 846336e5a0
commit 3ca6d25e0d
11 files changed
+376 -11

No files matched your search

+8
View File
@@ -224,3 +224,11 @@ without that record, the helper will refuse to overwrite an existing prefix.
Verify the public page and its links after publication. This manual refresh
does not add a scheduled workflow. Preserve the measurement date when choosing
a newer rendering of the same campaign.
Remaining native chat boundaries are in the explicit-only
`agent-chat-qualification` suite: active task reassignment, user Retry after
verified worker process loss, and multi-turn answers grounded in actual task
records. See the [workflow and qualification limits](../tests/runner-e2e/README.md#remaining-native-agent-chat-qualification).
The 26 native `first-task` cells exercise onboarding before native selection
becomes the UI default. Live results and semantic answer reviews must accompany
any qualification claim; catalog presence alone is not a pass.
+8
View File
@@ -207,3 +207,11 @@ must recover a brief reference absent from both prompts; the revision oracle
also reads the actual conversation plan. Fixture setup never enables native API
tools for this suite. Do not describe its prepared-agent settings case as a
production onboarding qualification.
The `agent-chat-qualification` local fixtures use public APIs to seed two workers
and a task with a saved plan, or read-only tasks with contradictory historical
comments. Ordinary Node file waits in the isolated agent workspace establish
observable active execution; no provider output or database outcome is fabricated.
A worker-crash case sends SIGKILL only to a positively identified running native
worker PID, then uses the production Retry button. Each gate is released in a
finally block. Source facts and boundary state are retained with the attempt.
+44 -1
View File
@@ -251,7 +251,7 @@ Missing provider credentials fail paid preflight and are not passing coverage.
The default `--all` selection is 171 cells (148 local and 23 Daytona) and 371
expected paid agent turns. The explicit-only everyday suite adds 38 catalog cells
and chat hardening adds 18; chat stories adds six. All three are excluded from
`--all`. The full catalog has 233 cells.
`--all`. The full catalog has 239 cells.
Follow-up steps remain ordered within their cell; all other
cells are independent. Narrow selectors are strongly recommended while
developing fixtures.
@@ -886,3 +886,46 @@ fetched snapshots does not trigger this rejection. Successful work alone does
not prove that this recovery path was tested.
The native `agent-chat.create-backlog` case saves a plan and assigned backlog task, then asks for its status. It checks the original creation audit, absence of all task runs, plan persistence, and exactly one task, so creating runnable work and correcting its status afterward fails the eval.
### Remaining native Agent Chat qualification
`agent-chat-qualification` is an explicit-only, local suite with six cells:
`active-reassignment`, `worker-crash-retry`, and `grounded-answer-quality`, each
on native Codex and native Claude. Run with
`pnpm test:e2e:runner -- --suite agent-chat-qualification`.
Active reassignment waits for a real worker to save a draft and enter a bounded
file wait. The lead then transfers the same task through Agent Chat. The oracle
requires cancellation with `issue_reassigned`, no overlap with the successor,
one successor run, unchanged scope and plan, retained draft, and a completed
successor-owned document. It budgets three provider runs.
Worker recovery kills only the exact running native worker PID from the public
run record, after verifying its command-line run ID and the isolated local
workspace. The real UI must show one Retry button. Clicking it must produce one
successful attempt, consume the original message once, preserve the saved plan,
and return a reference that was supplied only after the crash. This qualifies
**user-initiated Retry after worker process loss**, not automatic recovery of
arbitrary provider failures. It budgets two provider runs. Unexpected failures
remain fatal; only the positively identified injected-fault run is exempted.
Answer quality uses two read-only turns over public fixture tasks and conflicting
historical comments. Exact structured propositions grade current blockers,
backlog versus active work, stale claims, and unknown facts. The written answers
and source records are retained for separate semantic review of factual grounding,
correction, uncertainty, usefulness, and clarity. Deterministic facts do not certify
all prose quality. This case explicitly enables the existing experimental API
context tools; the two recovery cases use the default native tool surface.
All cells have a 15-minute deadline. Evidence includes boundary and final run
records, documents, source facts, chat comments, and screenshots. Gates are
released on failure and normal isolated-instance cleanup removes the workspace.
The usual provider billing and partial-attempt reporting apply. No production
prompts, onboarding defaults, or provider permissions are changed.
For pre-default native onboarding qualification, select all `first-task` cases
with profiles `runner-codex,runner-acpx-claude` (26 cells). The existing public-API
runtime switch occurs after the real wizard creates its first agent and before
any provider work. It preserves the wizard's model, persona, skills, and task.
This tests the native first-task process in advance of the UI/default rollout;
it does not certify a native option in the wizard, which is not offered yet.
+10
View File
@@ -239,3 +239,13 @@ Rotate the affected credential immediately if a secret-scanning failure or
unexpected public object is observed. Preserve the access-controlled Actions
artifact and S3 object versions for incident analysis; do not weaken scanning
to make a campaign publish.
`agent-chat-qualification.worker-crash-retry` is local-only and explicit-only.
The fault target comes from the public run detail, must be native and running,
and must have an exact `--run-id` command argument. PID 1, the harness PID,
noninteger PIDs, remote profiles, and mismatched identities are refused. The
fixture workspace must be within the disposable instance root. This is one
specific process signal, never a name-based or machine-wide process kill.
The bounded fixture command is released even on failure; normal instance cleanup
still owns all disposable processes and files. No credentials enter the prompt,
fault metadata, or structured grading fixtures.
+3 -3
View File
@@ -71,10 +71,10 @@ describe("runner E2E catalog", () => {
expect(localIntegrityTasks).toHaveLength(2);
expect(openRouterBreadthTasks).toHaveLength(3);
expect(runnerSuites.map((suite) => suite.expectedMatrixSize)).toEqual([
23, 38, 52, 28, 18, 6, 42, 14, 10, 2,
23, 38, 52, 28, 18, 6, 6, 42, 14, 10, 2,
]);
expect(validateRunnerCatalog()).toHaveLength(233);
expect(new Set(runnerMatrix.map((entry) => entry.id)).size).toBe(233);
expect(validateRunnerCatalog()).toHaveLength(239);
expect(new Set(runnerMatrix.map((entry) => entry.id)).size).toBe(239);
expect(
runnerMatrix.filter((entry) => entry.suite.id === "core-compatibility"),
).toHaveLength(42);
+10 -1
View File
@@ -2,7 +2,7 @@ import { continuationTasks } from "./continuation-cases.js";
import { everydayTasks, productionStoryProfile } from "./everyday-cases.js";
import { firstTaskTasks } from "./first-task-cases.js";
import { chatTasks, chatHardeningTasks, chatStoryTasks } from "./chat-cases.js";
import { chatTasks, chatHardeningTasks, chatStoryTasks, chatQualificationTasks } from "./chat-cases.js";
import { createHash } from "node:crypto";
import { createAgentSchema } from "../../packages/shared/src/validators/agent.js";
import { createEnvironmentSchema } from "../../packages/shared/src/validators/environment.js";
@@ -968,6 +968,15 @@ export const runnerSuites: readonly RunnerSuiteFixture[] = [
environments: [localEnvironment], tasks: chatStoryTasks, expectedMatrixSize: 6,
definitionMetadata: { version: 3, setup: "configured-native-agent", permissions: "production-defaults", interruptionBoundary: "provider-file-wait-in-agent-workspace", grading: "persisted-comments-and-plan-run-attributed", scheduling: "explicit-only" },
},
{
id: "agent-chat-qualification", label: "Agent Chat Remaining Qualification", manualOnly: true,
description: "Active ownership transfer, user recovery after worker loss, and grounded answer quality.",
groups: ["chat", "native"],
profiles: runnerProfiles.filter(profile => ["runner-codex", "runner-acpx-claude"].includes(profile.id))
.map(profile => productionStoryProfile(defaultPermissionProfile(profile))),
environments: [localEnvironment], tasks: chatQualificationTasks, expectedMatrixSize: 6,
definitionMetadata: { version: 1, permissions: "production-defaults", instructions: "production", crashBoundary: "verified-native-worker-pid-at-file-wait", recovery: "user-visible-retry", answerGrading: "exact-grounded-propositions-plus-separate-semantic-review", scheduling: "explicit-only" },
},
...(process.env.PAPERCLIP_RUNNER_E2E_CONNECTION_REVIEWS === "1" ? [connectionReviewSuite] : []),
{
id: "core-compatibility",
+7 -1
View File
@@ -54,9 +54,15 @@ export const chatStoryTasks = buildChatTasks([
]).map(task => ({ ...task, ...(task.id === "enable-disable-resume" ? {} : { minimumExpectedRunCount: 1 }) }));
export function chatNeedsApiTools(suiteId: string, caseId: string): boolean {
return suiteId === "agent-chat-hardening" && ["hire-delegate-reuse", "blocked-status-review"].includes(caseId);
return (suiteId === "agent-chat-qualification" && caseId === "grounded-answer-quality") || suiteId === "agent-chat-hardening" && ["hire-delegate-reuse", "blocked-status-review"].includes(caseId);
}
export function isManagedHiringCase(suiteId: string, caseId: string): boolean {
return (suiteId === "everyday-workflows" && caseId === "hire-reuse") ||
(suiteId === "agent-chat-hardening" && caseId === "hire-delegate-reuse");
}
export const chatQualificationTasks = buildChatTasks([
["active-reassignment", "Reassign an executing task and preserve its saved work", 3],
["worker-crash-retry", "Recover from worker process loss through visible Retry", 2],
["grounded-answer-quality", "Ground status, correct stale claims, and acknowledge uncertainty", 2],
]);
+12 -4
View File
@@ -10,6 +10,7 @@ import { isBlockedUnstartedWake } from "./non-execution-wake.js";
import { chatMarker } from "./chat-cases.js";
import { assertChatRememberedAfterRestart, assertChatStartupStopped, isChatStopReady, runChatHardeningFlow } from "./chat-hardening.js";
import { enableChatThroughSettings, runChatInterruption, runChatSettingsLifecycle } from "./chat-stories.js";
import { runActiveReassignment, runWorkerCrash, runAnswerQuality } from "./chat-qualification.js";
import { matchesRunCount, minimumRunCount } from "./run-count.js";
// Public API observations only: this driver never fabricates provider results or writes DB state.
@@ -309,6 +310,7 @@ export async function runChatFlow(input: ChatFlowInput) {
const caseId = execution.task.id;
const stopCase = ["stop-new-resume", "stop-startup-new-resume"].includes(caseId);
const interruptionCase = ["followup-while-running", "revise-while-running"].includes(caseId);
const expectedStops = new Map<string, string>();
let issue: ChatIssue;
let runs: ChatRun[] = [];
const settings = await api.get<Record<string, unknown>>(
@@ -352,7 +354,7 @@ export async function runChatFlow(input: ChatFlowInput) {
activeRuns: runs
.filter((run) => ["queued", "running"].includes(run.status))
.map((run) => run.id),
failure: chatRunFailure(runs, stopCase),
failure: chatRunFailure(runs.filter(run => expectedStops.get(run.id) !== run.status), stopCase),
};
},
reject: (state) => state.failure ?? inconsistentIdle(state),
@@ -384,7 +386,13 @@ export async function runChatFlow(input: ChatFlowInput) {
expect(await api.get(chatPath)).toBeNull();
expect(await allRuns()).toHaveLength(0);
if (caseId === "enable-disable-resume") {
if (execution.suite.id === "agent-chat-qualification") {
const context = { input, marker, issue: () => issue!, idle, allRuns, comments, expectedStops,
refreshIssue: async () => { issue = await api.get<ChatIssue>(chatPath); input.observe(issue, await allRuns()); } };
if (caseId === "active-reassignment") await runActiveReassignment(context);
else if (caseId === "worker-crash-retry") await runWorkerCrash(context);
else await runAnswerQuality(context);
} else if (caseId === "enable-disable-resume") {
await runChatSettingsLifecycle({ input, marker, issue: () => issue!, idle, allRuns, comments });
} else if (interruptionCase) {
await runChatInterruption({ input, marker, issue: () => issue!, idle, allRuns, comments,
@@ -925,9 +933,9 @@ export async function runChatFlow(input: ChatFlowInput) {
for (const run of runs.filter((run) => !isResetRun(run))) {
expect(run.runtimeMode).toBe(execution.profile.expectedRuntimeMode);
expect(run.status).toBe(
stopCase && run.status === "cancelled"
expectedStops.get(run.id) ?? (stopCase && run.status === "cancelled"
? "cancelled"
: "succeeded",
: "succeeded"),
);
}
await input.evidence("api-state.json", {
+1 -1
View File
@@ -11,7 +11,7 @@ type Agent = {
type Comment = { id: string; body: string; authorAgentId?: string; clientRequestId?: string };
type Document = { id: string; body: string; latestRevisionId: string; createdByAgentId?: string };
function mutableIssueSnapshot(issue: ChatIssue) {
export function mutableIssueSnapshot(issue: ChatIssue) {
// Follow the public mutation contract as it grows. Include relationships and
// fields governed by dedicated endpoints; omit derived read projections such
// as inbound references, which a legitimate status reply can add to the chat.
@@ -0,0 +1,76 @@
import { describe, expect, it } from "vitest";
import { assertActiveHandoff, assertAnswerFacts, assertCrashRecovered, assertWorkerIdentity } from "./chat-qualification.js";
import { runnerMatrix } from "./catalog.js";
import { buildRunnerE2EProcessEnvironment } from "./harness-env.js";
const run = { id: "old", agentId: "original", companyId: "company", runtimeMode: "native", status: "cancelled", errorCode: "issue_reassigned", finishedAt: "2026-09-21T00:01:00Z", contextSnapshot: { issueId: "task" } };
const successor = { ...run, id: "next", agentId: "successor", status: "succeeded", startedAt: "2026-09-21T00:01:01Z" };
const before = { id: "task", assigneeAgentId: "original", description: "Preserve scope", projectId: null };
const plan = { body: "Friday REFERENCE", latestRevisionId: "revision" };
const handoff = { before, after: { ...before, status: "done", assigneeAgentId: "successor" }, oldRun: run, boundary: { ...run, status: "running" }, runs: [run, successor], successorId: "successor", planBefore: plan, planAfter: plan, draft: { body: "REFERENCE" }, output: { body: "REFERENCE", createdByAgentId: "successor" }, reference: "REFERENCE", audit: [{ action: "issue.reassigned", details: { source: "paperclip_runner_protocol" } }], taskIds: ["task"] };
const recovery = { boundary: { ...run, status: "running" }, failed: { ...run, status: "failed" }, runs: [{ ...run, status: "failed" }, successor], issueId: "task", prompt: "Read my brief", comments: [{ body: "Read my brief" }, { body: "REFERENCE MARKER", authorAgentId: "original", createdByRunId: "next" }], reference: "REFERENCE", marker: "MARKER", planBefore: { body: "plan MARKER", latestRevisionId: "v1" }, planAfter: { body: "plan MARKER", latestRevisionId: "v1" } };
describe("remaining native chat qualification", () => {
it("requires a stopped original worker before exactly one successor executes", () => {
expect(() => assertActiveHandoff(handoff)).not.toThrow();
for (const change of [
{ boundary: { ...handoff.boundary, status: "succeeded" } },
{ oldRun: { ...run, status: "succeeded" } },
{ oldRun: { ...run, errorCode: "unrelated_cancellation" } },
{ runs: [run, { ...successor, startedAt: "2026-09-21T00:00:59Z" }] },
{ runs: [run, successor, { ...successor, id: "duplicate" }] },
{ runs: [run] },
{ taskIds: ["replacement"] },
{ planAfter: { ...plan, body: "rewritten" } },
{ draft: { body: "no saved progress" } },
{ output: { body: "REFERENCE", createdByAgentId: "original" } },
{ audit: [] },
]) expect(() => assertActiveHandoff({ ...handoff, ...change })).toThrow();
});
it("requires successful run-attributed recovery preserving input and saved work", () => {
expect(() => assertCrashRecovered(recovery)).not.toThrow();
for (const change of [
{ boundary: { ...recovery.boundary, status: "succeeded" } },
{ failed: { ...recovery.failed, id: "unrelated" } },
{ runs: [recovery.runs[0]!, { ...successor, status: "failed" }] },
{ runs: [recovery.runs[0]!, { ...successor, contextSnapshot: { issueId: "new-chat" } }] },
{ comments: [...recovery.comments, recovery.comments[0]!] },
{ comments: [recovery.comments[0]!, { ...recovery.comments[1], createdByRunId: "old" }] },
{ comments: [recovery.comments[0]!, { ...recovery.comments[1], body: "MARKER" }] },
{ planAfter: { ...recovery.planAfter, latestRevisionId: "rewritten" } },
]) expect(() => assertCrashRecovered({ ...recovery, ...change })).toThrow();
});
it("refuses unknown PIDs, nonnative or nonlocal processes and partial run identities", () => {
const running = { id: "run-123", status: "running", runtimeMode: "native", processPid: 123456 };
expect(() => assertWorkerIdentity(running, "node runner --run-id run-123 --worker", "local")).not.toThrow();
for (const command of ["node server", "node runner --run-id run-1234", "node runner run-123 --run-id other"])
expect(() => assertWorkerIdentity(running, command, "local")).toThrow();
for (const processPid of [undefined, 0, 1, -20, process.pid, 1.2])
expect(() => assertWorkerIdentity({ ...running, processPid }, "node runner --run-id run-123", "local")).toThrow();
expect(() => assertWorkerIdentity(running, "node runner --run-id run-123", "daytona")).toThrow();
expect(() => assertWorkerIdentity({ ...running, runtimeMode: "legacy" }, "node runner --run-id run-123", "local")).toThrow();
});
it("grades factual propositions rather than matching words in misleading prose", () => {
const facts = { currentBlocker: "VENUE", confirmedAttendance: null, printingStarted: false };
const explanation = "The venue is still unconfirmed, so printing remains deferred. No attendance count is recorded.";
expect(() => assertAnswerFacts(JSON.stringify({ facts, explanation }), facts)).not.toThrow();
for (const wrong of [
{ ...facts, currentBlocker: "BUDGET" }, { ...facts, confirmedAttendance: 40 },
{ ...facts, printingStarted: true }, { ...facts, madeUpMetric: 50 }, {},
]) expect(() => assertAnswerFacts(JSON.stringify({ facts: wrong, explanation }), facts)).toThrow();
expect(() => assertAnswerFacts(JSON.stringify({ facts, explanation: "" }), facts)).toThrow();
expect(() => assertAnswerFacts("VENUE confirmedAttendance null printingStarted false", facts)).toThrow();
});
it("exposes exactly six explicit local native cells with bounded run counts", () => {
const cells = runnerMatrix.filter(c => c.suite.id === "agent-chat-qualification");
expect(cells).toHaveLength(6);
for (const cell of cells) {
expect(cell.suite.manualOnly).toBe(true);
expect(cell.environment.id).toBe("local");
expect(cell.profile.generation).toBe("native");
expect(cell.task.expectedRunCount).toBe(cell.task.id === "active-reassignment" ? 3 : 2);
expect(buildRunnerE2EProcessEnvironment({}, [cell]).PAPERCLIP_RUNNER_API_TOOLS_ENABLED)
.toBe(cell.task.id === "grounded-answer-quality" ? "true" : undefined);
}
});
});
+197
View File
@@ -0,0 +1,197 @@
import { expect } from "@playwright/test";
import { execFileSync } from "node:child_process";
import { randomUUID } from "node:crypto";
import { readFile, writeFile } from "node:fs/promises";
import path from "node:path";
import { resolveDefaultAgentWorkspaceDir } from "../../server/src/home-paths.js";
import { prepareChatBrief } from "./chat-stories.js";
import { mutableIssueSnapshot } from "./chat-hardening.js";
import { sendChatMessage, readChatOutputDocument, type ChatFlowInput, type ChatIssue, type ChatRun } from "./chat-flow.js";
type Row = Record<string, any>;
type Context = {
input: ChatFlowInput; marker: string; issue(): ChatIssue;
allRuns(): Promise<ChatRun[]>; comments(): Promise<Row[]>; idle(count: number): Promise<void>;
refreshIssue(): Promise<void>; expectedStops: Map<string, string>;
};
export function assertWorkerIdentity(run: Row, command: string, environment: string) {
expect(environment).toBe("local");
expect(run).toMatchObject({ status: "running", runtimeMode: "native" });
expect(Number.isSafeInteger(run.processPid) && run.processPid > 1).toBe(true);
expect(run.processPid).not.toBe(process.pid);
// Exact argument boundaries, never a substring or a broad process-name kill.
expect(command.trim().split(/\s+/)).toEqual(expect.arrayContaining(["--run-id", run.id]));
expect(command).toMatch(new RegExp(`(?:^|\\s)--run-id ${run.id.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?:\\s|$)`));
}
export function assertActiveHandoff(e: {
before: Row; after: Row; oldRun: ChatRun; boundary: ChatRun; runs: ChatRun[];
successorId: string; planBefore: Row; planAfter: Row; draft: Row; output: Row;
reference: string; audit: Row[]; taskIds: string[];
}) {
expect(e.boundary).toMatchObject({ id: e.oldRun.id, status: "running", agentId: e.before.assigneeAgentId });
expect(e.after).toMatchObject({ id: e.before.id, status: "done", assigneeAgentId: e.successorId, description: e.before.description, projectId: e.before.projectId });
expect(e.taskIds).toEqual([e.before.id]);
expect(e.oldRun).toMatchObject({ status: "cancelled", errorCode: "issue_reassigned" });
const workers = e.runs.filter(r => r.contextSnapshot?.issueId === e.before.id);
expect(workers).toHaveLength(2);
const successor = workers.find(r => r.agentId === e.successorId)!;
expect(successor).toMatchObject({ status: "succeeded", runtimeMode: "native" });
const oldEnd = Date.parse((e.oldRun as Row).finishedAt);
expect(Number.isFinite(oldEnd)).toBe(true);
expect(Date.parse(successor.startedAt!)).toBeGreaterThanOrEqual(oldEnd);
expect(e.planAfter).toEqual(e.planBefore);
expect(e.draft.body).toContain(e.reference);
expect(e.output.body).toContain(e.reference);
expect(e.output.createdByAgentId).toBe(e.successorId);
expect(e.audit.filter(a => a.action === "issue.reassigned")).toHaveLength(1);
expect(e.audit.find(a => a.action === "issue.reassigned")?.details).toMatchObject({ source: "paperclip_runner_protocol" });
}
export function assertCrashRecovered(e: {
boundary: Row; failed: Row; runs: ChatRun[]; issueId: string; prompt: string;
comments: Row[]; reference: string; marker: string; planBefore: Row; planAfter: Row;
}) {
expect(e.boundary.status).toBe("running");
expect(e.failed).toMatchObject({ id: e.boundary.id, status: "failed", runtimeMode: "native" });
expect(e.runs).toHaveLength(2);
expect(e.runs.map(r => r.id)).toContain(e.failed.id);
const retry = e.runs.find(r => r.id !== e.failed.id)!;
expect(retry).toMatchObject({ status: "succeeded", runtimeMode: "native", contextSnapshot: { issueId: e.issueId } });
expect(e.comments.filter(c => !c.authorAgentId && c.body === e.prompt)).toHaveLength(1);
const replies = e.comments.filter(c => c.authorAgentId && c.body.includes(e.marker));
expect(replies).toHaveLength(1);
expect(replies[0]).toMatchObject({ createdByRunId: retry.id });
expect(replies[0]!.body).toContain(e.reference);
expect(e.planBefore.body).toContain(e.marker);
expect(e.planAfter).toEqual(e.planBefore);
}
async function brief(input: ChatFlowInput, agentId: string) {
const workspace = resolveDefaultAgentWorkspaceDir(agentId);
const relative = path.relative(path.dirname(input.workspacePath), workspace);
if (relative.startsWith("..") || path.isAbsolute(relative)) throw new Error("Crash fixture escaped isolated instance");
return prepareChatBrief(workspace, input.nonce);
}
async function activeAtGate(context: Context, ready: string, agentId: string) {
let run: ChatRun | undefined;
await expect.poll(async () => {
if (await readFile(ready, "utf8").catch(() => "") !== "waiting") return false;
run = (await context.allRuns()).find(r => r.agentId === agentId && r.status === "running");
return Boolean(run);
}, { timeout: 150_000 }).toBe(true);
return run!;
}
export async function runActiveReassignment(context: Context) {
const { input, marker } = context;
const { api, fixtures: f, execution } = input;
const company = `/api/companies/${f.company.id}`;
const config = execution.profile.buildAgent({ environmentId: f.environment.id, environmentFixtureId: "local", workspacePath: input.workspacePath, secretRefs: f.secretRefs, executionId: input.nonce });
const first = await api.post<Row>(`${company}/agents`, { ...config, name: "Riley Original", role: "engineer", reportsTo: f.agent.id });
const second = await api.post<Row>(`${company}/agents`, { ...config, name: "Morgan Successor", role: "engineer", reportsTo: f.agent.id });
const wait = await brief(input, first.id);
const reference = `REFERENCE${randomUUID().replaceAll("-", "")}`;
await api.patch(`/api/agents/${first.id}`, { instructionsBundle: { entryFile: "AGENTS.md", files: { "AGENTS.md": `First save a draft Paperclip document on the assigned task containing the reference from its plan. Then run node ${wait.scriptPath} and wait for the brief before finishing. Do not finish before the command returns.` } } });
const task = await api.post<Row>(`${company}/issues`, { title: `Launch checklist ${input.nonce}`, status: "todo", assigneeAgentId: first.id,
description: `Write a short launch checklist as a Paperclip document on this existing task. Use the saved plan and preserve any draft. Include its reference and ${marker} in the final checklist, then complete this task.`,
initialPlan: `Welcome beginners on Friday at a free meetup. Reference: ${reference}` });
try {
const boundary = await activeAtGate(context, wait.ready, first.id);
const planBefore = await api.get<Row>(`/api/issues/${task.id}/documents/plan`);
const draft = await readChatOutputDocument(api, task.id, reference);
// Only this positively observed run may be cancelled. Every other failure remains fatal.
context.expectedStops.set(boundary.id, "cancelled");
await sendChatMessage(input.page, `Reassign the currently running task ${task.identifier} from Riley Original to Morgan Successor now. Stop Riley's active execution as part of the handoff. Preserve the task, its description, saved plan, and draft; Morgan should complete the checklist on the same task. Do not create replacement work. Explain the handoff here.`);
await context.idle(3);
const e = { before: task, after: await api.get<Row>(`/api/issues/${task.id}`), boundary,
oldRun: await api.get<ChatRun>(`/api/heartbeat-runs/${boundary.id}`), runs: await context.allRuns(), successorId: second.id,
planBefore, planAfter: await api.get<Row>(`/api/issues/${task.id}/documents/plan`), draft,
output: await readChatOutputDocument(api, task.id, marker), reference,
audit: await api.get<Row[]>(`/api/issues/${task.id}/activity`), taskIds: (await api.get<Row[]>(`${company}/issues`)).map(t => t.id) };
await input.evidence("chat-active-reassignment.json", e);
assertActiveHandoff(e);
} finally {
await writeFile(wait.gate, reference);
await input.evidence("chat-reassignment-final.json", { task: await api.get(`/api/issues/${task.id}`), runs: await context.allRuns() });
}
}
export async function runWorkerCrash(context: Context) {
const { input, marker } = context;
const wait = await brief(input, input.fixtures.agent.id);
const reference = `REFERENCE${randomUUID().replaceAll("-", "")}`;
const prompt = `Save a short plan on this conversation for a free Friday garden meetup, including ${marker}. If that plan already exists, preserve it without rewriting it. Then run node ${wait.scriptPath} to wait for my brief. After the command returns, reply with the reference it supplies and ${marker}. This is discussion only; do not create projects or execution tasks.`;
try {
await sendChatMessage(input.page, prompt);
const boundary = await activeAtGate(context, wait.ready, input.fixtures.agent.id) as ChatRun & Row;
await context.refreshIssue();
const planBefore = await input.api.get<Row>(`/api/issues/${context.issue().id}/documents/plan`);
const command = execFileSync("ps", ["-p", String(boundary.processPid), "-o", "command="], { encoding: "utf8" });
assertWorkerIdentity(boundary, command, input.execution.environment.id);
await input.evidence("chat-worker-fault.json", { boundary, planBefore, fault: "SIGKILL exact public run processPid", recovery: "visible Retry button" });
process.kill(boundary.processPid, "SIGKILL");
context.expectedStops.set(boundary.id, "failed");
await expect.poll(async () => (await input.api.get<ChatRun>(`/api/heartbeat-runs/${boundary.id}`)).status, { timeout: 120_000 }).toBe("failed");
const failed = await input.api.get<Row>(`/api/heartbeat-runs/${boundary.id}`);
await input.capture("worker-failed", "Worker loss before user Retry", "worker-failed.png");
await writeFile(wait.gate, reference);
const retry = input.page.getByRole("button", { name: "Retry", exact: true });
await expect(retry).toHaveCount(1, { timeout: 60_000 });
await retry.click();
await context.idle(2);
const e = { boundary, failed, runs: await context.allRuns(), issueId: context.issue().id,
prompt, comments: await context.comments(), reference, marker, planBefore,
planAfter: await input.api.get<Row>(`/api/issues/${context.issue().id}/documents/plan`) };
await input.evidence("chat-worker-recovery.json", e);
assertCrashRecovered(e);
expect(await input.api.get(`/api/companies/${input.fixtures.company.id}/issues`)).toEqual([]);
} finally {
await writeFile(wait.gate, reference);
await input.evidence("chat-worker-final.json", { runs: await context.allRuns(), comments: await context.comments() });
}
}
export function assertAnswerFacts(reply: string, expected: Row) {
const body = reply.trim().replace(/^```(?:json)?\s*/, "").replace(/\s*```$/, "");
const answer = JSON.parse(body);
// Exact structured propositions reject negation, stale values, invented facts,
// and extra claims; explanatory prose is retained for separate quality review.
expect(answer.facts).toEqual(expected);
expect(typeof answer.explanation).toBe("string");
expect(answer.explanation.trim().length).toBeGreaterThan(40);
}
export async function runAnswerQuality(context: Context) {
const { input } = context;
const { api, fixtures: f } = input;
const base = `/api/companies/${f.company.id}`;
const blocked = await api.post<Row>(`${base}/issues`, { title: "Venue confirmation", status: "blocked", description: "Confirm where our Friday launch will be held." });
const deferred = await api.post<Row>(`${base}/issues`, { title: "Print invitations", status: "backlog", description: "Only start after the venue is confirmed." });
const stale = `BUDGET${randomUUID().replaceAll("-", "")}`;
const current = `VENUE${randomUUID().replaceAll("-", "")}`;
await api.post(`/api/issues/${blocked.id}/comments`, { body: `Earlier obstacle: ${stale}. Budget was missing.` });
await api.post(`/api/issues/${blocked.id}/comments`, { body: `Budget is resolved. The only current blocker is ${current}: venue confirmation. No confirmed venue or attendance count is recorded.` });
const before = await Promise.all([blocked, deferred].map(t => api.get<ChatIssue>(`/api/issues/${t.id}`)));
const prompts = [
`Read ${blocked.identifier} and ${deferred.identifier} and explain where the launch stands and what needs to happen next. Reply as JSON with facts {blockedIssue, blockedStatus, currentBlocker, deferredIssue, deferredStatus, activeRunCount, confirmedAttendance} and explanation (a useful short plain-language update). Use null for any unknown attendance count. Do not change or start work.`,
`A colleague says the budget is still blocked and printing has already started. Are those claims supported by the current records? Also, can you tell me the confirmed venue and guaranteed launch date? Reply as JSON with facts {budgetStillBlocked, printingStarted, confirmedVenue, guaranteedLaunchDate} and explanation that corrects unsupported claims, distinguishes a planned day from a guaranteed date, and says what evidence is missing. Use null for unknown facts. Do not change or start work.`,
];
const expected = [
{ blockedIssue: blocked.identifier, blockedStatus: "blocked", currentBlocker: current, deferredIssue: deferred.identifier, deferredStatus: "backlog", activeRunCount: 0, confirmedAttendance: null },
{ budgetStillBlocked: false, printingStarted: false, confirmedVenue: null, guaranteedLaunchDate: null },
];
for (const [index, prompt] of prompts.entries()) {
await sendChatMessage(input.page, prompt);
await context.idle(index + 1);
const reply = (await context.comments()).filter(c => c.authorAgentId).at(-1)?.body ?? "";
await input.evidence(`chat-answer-quality-${index + 1}.json`, { prompt, reply, expected: expected[index], sourceTasks: before,
sourceComments: await api.get(`/api/issues/${blocked.id}/comments?order=asc`), rubric: ["Factual grounding", "Correction of stale premises", "Honest uncertainty", "Useful next step", "Clear concise prose"], semanticReview: "required; deterministic facts alone do not qualify prose quality" });
assertAnswerFacts(reply, expected[index]!);
}
const after = await Promise.all([blocked, deferred].map(t => api.get<ChatIssue>(`/api/issues/${t.id}`)));
expect(after.map(mutableIssueSnapshot)).toEqual(before.map(mutableIssueSnapshot));
expect((await api.get<Row[]>(`${base}/issues`)).map(t => t.id).sort()).toEqual([blocked.id, deferred.id].sort());
expect((await context.allRuns()).every(r => r.contextSnapshot?.issueId === context.issue().id)).toBe(true);
}