mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-08 11:23:40 +01:00
## Thinking Path > - Paperclip manages work done by AI agents. > - A completed delegated task must report its result to the originating chat. > - That report uses a real provider turn and must stay in cost accounting. > - Ordinary first-task proposals must also support the promised chat acceptance path. > - A revision response can reject an older proposal before it creates the replacement. > - The old rejection transition clears that active response's ownership and blocks its next tool. > - This change proves required completion work, guides ordinary proposal policy and preserves the revision turn under the existing locks. ## Linked Issues or Issue Description No separate issue exists. The original failures remain in [the complete Product run](https://github.com/paperclipai/paperclip/actions/runs/41915965118). The independent continuation repair is #19076. Related #12209 concerns prior-run confirmation binding. This change fixes the ownership reset during rejection, rather than changing binding authorization. **What happened?** The complete 20-case run finished with 13 passes and 7 failures. Three delegated-chat cases counted one required `chat_task_completed` provider turn as unexpected work. Two first-task agents chose optional human-only cards, then correctly received 403 when they tried conversational acceptance. A [reviewed two-case candidate run](https://github.com/paperclipai/paperclip/actions/runs/41931445311) then used the changed first-task skill. Both models inherited the ordinary resolver policy. Clarify/propose/accept passed all 12 predicates. Revise/accept failed after the new response rejected its predecessor's proposal. The saved rejection was followed by `paperclip_runner_tool_binding_not_authorized` on its next tools. The final `native_session_lease_lost` label followed those binding failures; this PR does not assume lease expiry caused them. Both cells cleaned up and published their original grades. **Expected behavior** Keep the existing ordinary-turn bounds and account for one independently proved completion notification. Inherit the normal resolver policy for ordinary proposals that accept chat replies. When an active response rejects an older proposal, save the rejection and retain that response's current ownership so it can create the revised proposal. Keep human, current-source and native completion-review rejection behavior and all real approval restrictions. **Steps to reproduce** The original full run used `4740d251`. The two-case candidate used trusted workflow `7d1e9b34` and target `74da56c4`. Run the focused provider-free controls below. The dual-run API regression first fails because rejection changes the issue to `todo` and clears the newer run's execution and checkout fields. ## What Changed - Prove one completion notification only for native Codex/local `multi-repository`, `clarify-reuse` and `plan-handoff`. Keep the ordinary bounds of 2, 3 and 4. Preserve actual totals of 3, 4 and 5, all run IDs and all usage. - Read those declared totals from the current catalog, which now includes the completion reply. Check the total once and prove that exactly one turn is the required notification. Do not add another turn while waiting. The required-server controls use the actual catalog tasks. - Bind the notification to the same company, agent, conversation generation, completed child, single delivery, accounted native run, saved reply and rendered result link. Reject extra work, duplicate deliveries, unknown events and mutations, including native work without a Paperclip tool call. - Collect workspace operations through the real run API for these three proofs. Keep other collector calls unchanged. Keep the proof controls in the existing required server test lane. - Stop idle polling on a permanent completion-proof error. Continue to retry transient observations within the original 240-second window. - Guide ordinary chat-accepting first-task proposals to omit optional `resolverPolicy` and inherit server/company defaults. Preserve explicit and governed human-only restrictions. Do not lower or recreate saved restricted cards. - Under the existing locked issue and interaction rows, preserve the active responding run when it rejects a different source run's proposal. Change only the ordinary requeue predicate. Keep the saved rejection, notifications, activity and existing Telemetry calls. Keep global status, lease and tool-authority guards unchanged. - Extend the existing native API controls with the actual dual-run rejection/revision sequence and policy, provenance, human, current-source and native completion-review countercontrols. No new workflow or test framework is needed. ## Verification - Current combined head is `a8567ded67e5ab811675390e9a5c5ed2194aee2f`, integrated cleanly on `fb96537e28c4c7bfced4939909cb334392320868`. The upstream completion-reply waiter is preserved. [Current required CI](https://github.com/paperclipai/paperclip/actions/runs/41940780852) passes. Actual test checkout `ff93c034d7bb40f3df7bc75cf51828fd07bb0d29` merges this head into `9c6993f0aab7ebb22a26d78f5d227accb35a6ad1`. - Fresh Greptile is 5/5 on exact head `a8567ded`, with no blocking finding. All addressed review threads are resolved. The separate automated reviewer emitted a paused-work response; that response is not a review approval. - Current required server CI actually passed all 11 native confirmation API cases, 46 completion-proof controls and 13 onboarding asset checks. Canonical typecheck, Build, the native package/server suites, all browser and serialized shards, `ci / e2e` and `ci / verify` pass. No current-head CI retry was needed. - Local dual-run RED: the unmodified transition returned HTTP 200 and saved rejection, then changed the issue to `todo` and cleared the newer run's execution/checkout fields. Whole setup and check took 28.95 seconds; the case took 596 ms. - Local treatment: all 11 real native/API cases pass. The same-session response retains execution/checkout ownership, reads task context and persists the recorded-shape revised confirmation. Its stored lease receipt stays intact and one rejection activity is saved. Human-only rejection, current-source rejection, human rejection with/without a newer owner, Plan/Ask, foreign provenance, authentication and formal approval controls pass. - All 59 existing confirmation resolver controls pass in 16.62 seconds. These cover cancellation, lost ownership, company/user scope, policy changes, transactional rollback, concurrent retries and stale revisions. - All 46 completion controls pass in 4.07 seconds. The two added clock controls preserve the original idle deadline and prove immediate permanent-proof failure plus transient observation retry. The existing live collector-to-proof and native mutation negatives remain in this required server file. - The first current-catalog integration check failed 5 controls in 2.70 seconds. The old consumer added the already-declared reply again and could accept an extra ordinary turn. The corrected consumer passes all 46 controls using the actual catalog. The existing full 20-case catalog/reporting compatibility check also passes in 4.93 seconds. Case identities, configured models and reporting match the declared 20. - The API controls used one owned loopback PostgreSQL instance through existing supported test hooks. It was stopped and removed. Earlier missing-library/setup failures and one corrected current-source test expectation remain retained; they are not counted as product failures or passes. - The unchanged first-task skill has SHA-256 `b789090996e7925676590c006418eb8b57f4514e646f6bca18ffd7b2b8e864de`. Both candidate runtime copies matched it. The inherited policy was observed in both models; one complete acceptance journey passed. This does not qualify the new rejection repair. - The three retained real completion streams pass the stronger local proof, including native items, workspace observations and recorded DOM links. Their original failed grades stay unchanged. - Earlier related checks passed 153 hiring/non-execution controls and 13 asset checks. Their source is unchanged. Required discovery includes the completion, API and asset files exactly once. - Prior candidate `74da56c4` passed all required CI, including canonical typecheck and build, in [CI run 41929148958](https://github.com/paperclipai/paperclip/actions/runs/41929148958). Its fresh Greptile was 5/5. This is prior-head evidence. - The intermediate `053150d9` head also received Greptile 5/5. Its [CI run](https://github.com/paperclipai/paperclip/actions/runs/41940014165) and review stay retained as superseded evidence. They do not qualify the final catalog correction. - A clean full local typecheck/build is not claimed because the reused dependency cache has stale adapter-utils/Runner declarations. No source or lock workaround was made. Fresh canonical CI must pass before merge. - The original full-plan result remains 13/20. The separate two-case probe remains 1/2. A fresh complete saved-plan run against delivered source is required for acceptance. No case, assertion, model, budget, timeout or failed grade is changed. Focused commands: ```sh # From server/; database URLs point only to an owned disposable local instance. node ../node_modules/vitest/vitest.mjs run src/__tests__/chat-completion-proof.test.ts PAPERCLIP_TEST_DATABASE_URL="$OWNED_TEST_DATABASE_URL" node ../node_modules/vitest/vitest.mjs run src/services/native-runtime/confirmation-comment-api.integration.test.ts PAPERCLIP_TEST_POSTGRES_ADMIN_URL="$OWNED_TEST_DATABASE_URL" node ../node_modules/vitest/vitest.mjs run src/__tests__/confirmation-comment-resolution.test.ts ``` ## Risks - The ownership exception applies only to an agent acting as the current execution run against a different non-null source run. Human, unowned and current-source requeue behavior must stay intact. Native completion-review handling remains separate. - The completion proof fails closed on new native tools or event shapes. A new shape needs review. - A stored unchanged lease receipt is supporting local evidence. The final real journey must prove full revision, execution and delivery. - The new head still needs normal protected merge approval. The optional queued Paperclip review is not a passing review. No causal repair of unrelated CI intermittency is claimed. ## Model Used OpenAI `gpt-6.1-sol` in Codex, with `max` reasoning effort. The runtime reports a 475,000-token context window. Used reasoning, code editing, shell tools and provider-free controls. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
1201 lines
57 KiB
TypeScript
1201 lines
57 KiB
TypeScript
import { runHiringTemplateFlow } from "./hiring-template-flow.js";
|
|
import { gradeHiringTemplateTurns } from "./hiring-template-turn-accounting.js";
|
|
import type { HiringTemplateEvidence } from "./hiring-template-scoring.js";
|
|
import { runAmbiguousConfirmationReply, runUnansweredQuestionReturn } from "./confirmation-replies.js";
|
|
import { expect, type Page } from "@playwright/test";
|
|
import { pollUntil, type RunnerApi } from "./api.js";
|
|
import type {
|
|
AskUserQuestionsPayload,
|
|
PaperclipQuestionSetPayload,
|
|
} from "../../packages/shared/src/types/issue.js";
|
|
import type { LiveFixtureValues } from "./live-fixtures.js";
|
|
import type { MatrixExecution } from "./types.js";
|
|
import { chatProviderRuns, classifyPreDispatchExecutionWait, isBlockedUnstartedWake, isReassignedUnstartedWake, verifyChatAdmissionWaitCoverage, type ChatAdmissionWait } from "./non-execution-wake.js";
|
|
import { collectRunEvents } from "./run-observations.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";
|
|
import { runChatCompletionUpdate } from "./completion-update-flow.js";
|
|
import { CHAT_FEATURE_SUITE } from "./chat-feature-cases.js";
|
|
import { runChatFeatureFlow } from "./chat-feature-flow.js";
|
|
import { needsChatCompletionProof, verifyChatCompletion, type ChatCompletionEvidence } from "./chat-completion-proof.js";
|
|
|
|
export function retryChatCompletionObservation(error: unknown) {
|
|
return !(error instanceof Error && error.message.startsWith("Chat completion proof:"));
|
|
}
|
|
|
|
/** Keep the ordinary-turn bound. Required completion delivery is separately proved real work. */
|
|
export function assertChatFlowRunCount(input: {
|
|
suiteId: string; task: Parameters<typeof matchesRunCount>[0] & { id?: string }; runs: ChatRun[];
|
|
profileId?: string; environmentId?: string; completionEvidence?: ChatCompletionEvidence;
|
|
hiringEvidence?: HiringTemplateEvidence; hiringApiState?: unknown;
|
|
}) {
|
|
const completion = needsChatCompletionProof(input.suiteId, input.task.id, input.profileId, input.environmentId)
|
|
? verifyChatCompletion(input.runs, input.completionEvidence) : undefined;
|
|
expect(matchesRunCount(input.task, completion?.totalProviderRuns ?? input.runs.length),
|
|
completion ? "Declared total provider-run bounds with one proved completion turn" : "Declared total provider-run bounds").toBe(true);
|
|
if (input.suiteId !== "hiring-templates") return;
|
|
const accounting = gradeHiringTemplateTurns({
|
|
evidence: input.hiringEvidence ? { ...input.hiringEvidence, runs: input.runs } : undefined,
|
|
apiState: input.hiringApiState,
|
|
});
|
|
expect(accounting.passed, `Hiring lifecycle: ${accounting.predicates.filter(p => !p.passed).map(p => p.id).join(", ")}`).toBe(true);
|
|
return accounting;
|
|
}
|
|
|
|
// Public API observations only: this driver never fabricates provider results or writes DB state.
|
|
export interface ChatIssue {
|
|
id: string;
|
|
companyId: string;
|
|
title: string;
|
|
status: string;
|
|
identifier?: string;
|
|
conversationState?: string;
|
|
conversationSessionGeneration?: number;
|
|
conversationBoundaryCommentId?: string;
|
|
parentId?: string | null;
|
|
projectId?: string | null;
|
|
assigneeAgentId?: string | null;
|
|
scheduledRetry?: unknown;
|
|
activeRecoveryAction?: unknown;
|
|
}
|
|
export interface ChatRun {
|
|
id: string;
|
|
companyId: string;
|
|
agentId: string;
|
|
status: string;
|
|
error?: string | null;
|
|
errorCode?: string | null;
|
|
runtimeMode?: string;
|
|
runtimeModeResolvedAt?: string | null;
|
|
logStore?: string | null;
|
|
logRef?: string | null;
|
|
contextSnapshot?: Record<string, unknown>;
|
|
resultJson?: Record<string, unknown>;
|
|
sessionIdBefore?: string | null;
|
|
sessionIdAfter?: string | null;
|
|
startedAt?: string | null;
|
|
nativeIssueId?: string | null;
|
|
}
|
|
type Comment = {
|
|
id: string;
|
|
body: string;
|
|
authorAgentId?: string;
|
|
createdByRunId?: string;
|
|
conversationSessionGeneration?: number;
|
|
};
|
|
type Plan = { body: string; latestRevisionId: string; updatedAt: string };
|
|
type ChatOutputDocument = Plan & { id: string; issueId: string; key: string };
|
|
|
|
export function assertChatBacklogCreation(input: {
|
|
tasks: ChatIssue[];
|
|
runs: ChatRun[];
|
|
ownerId: string;
|
|
plan: Plan;
|
|
marker: string;
|
|
activity: Array<{ action: string; details?: Record<string, unknown> }>;
|
|
}) {
|
|
expect(input.tasks).toHaveLength(1);
|
|
expect(input.tasks[0]).toMatchObject({ status: "backlog", parentId: null, assigneeAgentId: input.ownerId });
|
|
expect(input.runs.filter(run => run.contextSnapshot?.issueId === input.tasks[0]!.id)).toHaveLength(0);
|
|
expect(input.plan.body).toContain(input.marker);
|
|
expect(input.plan.latestRevisionId).toBeTruthy();
|
|
const created = input.activity.filter(row => row.action === "issue.created");
|
|
expect(created).toHaveLength(1);
|
|
// Correcting todo after creation still permits an unauthorized start race.
|
|
expect(created[0]!.details).toMatchObject({ status: "backlog", source: "paperclip_runner_protocol" });
|
|
}
|
|
|
|
/** Clarification may request information imperatively rather than end in a question mark. */
|
|
export function isChatClarificationReply(body: string): boolean {
|
|
if (body.includes("?")) return true;
|
|
// A present-tense request can introduce the required information directly,
|
|
// without a noun such as "brief" or "details" before the list.
|
|
const listRequest = body.match(/\b(?:I|we)(?:'ll|\s+will)?\s+need\s*:\s*([\s\S]*)/i);
|
|
if (listRequest) {
|
|
const items: string[] = [];
|
|
let paragraphBoundary = false;
|
|
// Only the directly introduced list belongs to this request. A later
|
|
// paragraph can introduce a separate plan without invalidating it.
|
|
for (const line of listRequest[1].split(/\r?\n/)) {
|
|
if (!line.trim()) {
|
|
paragraphBoundary = true;
|
|
continue;
|
|
}
|
|
const item = line.match(/^\s*(?:[-*]|\d+[.)])\s+(.+)$/);
|
|
if (!item) {
|
|
// Markdown permits soft-wrapped item text without indentation. A
|
|
// separate paragraph or heading ends the introduced information list.
|
|
if (items.length && !paragraphBoundary && !/^\s*#|:\s*$/.test(line)) {
|
|
items[items.length - 1] += ` ${line.trim()}`;
|
|
continue;
|
|
}
|
|
break;
|
|
}
|
|
items.push(item[1].replace(/^\[[ xX]\]\s*/, "").replace(/^[*_`]+/, ""));
|
|
paragraphBoundary = false;
|
|
}
|
|
// Positively identify questions or brief fields. Unknown bullets are not
|
|
// evidence of clarification merely because their verbs are unlisted.
|
|
const information = /^(?:(?:who|what|where|when|whether|how)\b|(?:(?:any|the|your|preferred|intended|required|target|desired|existing|delivery|must-include)\s+){0,3}(?:(?:club|company|project|team|event|organization)\s+name|audience|readers|recipients|tone|voice|format|length|deadline|date|purpose|context|details|requirements|constraints|examples|links|name|budget|location|venue|schedule|timezone|language|accessibility|contact|scope|goals|background|references|assets|brand|style)\b)/i;
|
|
if (items.length >= 2 && items.every(item => information.test(item))) return true;
|
|
}
|
|
const request = body.match(
|
|
/\b(?:please\s+(?:share|provide|clarify|confirm)|tell me|let me know)\b([\s\S]*)/i,
|
|
) ?? body.match(
|
|
/\b(?:I|we)(?:'ll|\s+will)?\s+need\s+(?:(?:a|some|the|your|more|following|compact|short|few|additional)\s+){0,4}(?:brief|details|information|context|clarification)\b([\s\S]*)/i,
|
|
);
|
|
return Boolean(request && /[\p{L}\p{N}]/u.test(request[1]));
|
|
}
|
|
|
|
export function assertChatExecutionOutput(
|
|
body: string,
|
|
marker: string,
|
|
supersededMarker?: string,
|
|
): void {
|
|
expect(body).toContain(marker);
|
|
if (supersededMarker) expect(body).not.toContain(supersededMarker);
|
|
}
|
|
|
|
/** A requested output document may have a descriptive key; a copied plan is not output. */
|
|
export async function readChatOutputDocument(
|
|
api: { get<T>(route: string): Promise<T> },
|
|
issueId: string,
|
|
marker: string,
|
|
): Promise<ChatOutputDocument> {
|
|
const summaries = await api.get<Array<{ key: string }>>(
|
|
`/api/issues/${issueId}/documents`,
|
|
);
|
|
const documents = await Promise.all(
|
|
summaries
|
|
.filter((document) => document.key !== "plan")
|
|
.map((document) =>
|
|
api.get<ChatOutputDocument>(
|
|
`/api/issues/${issueId}/documents/${encodeURIComponent(document.key)}`,
|
|
),
|
|
),
|
|
);
|
|
const output = documents.find(
|
|
(document) => document.issueId === issueId && document.body.includes(marker),
|
|
);
|
|
if (!output)
|
|
throw new Error(
|
|
`Execution task ${issueId} has no non-plan output document containing ${marker}; document keys: ${summaries.map((document) => document.key).join(", ") || "none"}`,
|
|
);
|
|
expect(output.id).toBeTruthy();
|
|
expect(output.latestRevisionId).toBeTruthy();
|
|
return output;
|
|
}
|
|
|
|
export const isResetRun = (run: ChatRun) =>
|
|
run.contextSnapshot?.conversationReset === true ||
|
|
run.resultJson?.conversationReset === true;
|
|
/** The source chat's automatic turn that reports one completed handoff. */
|
|
export const isChatCompletionReply = (run: ChatRun, chatIssueId: string, taskId: string) =>
|
|
run.contextSnapshot?.issueId === chatIssueId &&
|
|
run.contextSnapshot?.wakeReason === "chat_task_completed" &&
|
|
Array.isArray(run.contextSnapshot?.chatCompletionUpdates) &&
|
|
(run.contextSnapshot.chatCompletionUpdates as Array<{ id?: unknown }>).some((update) => update?.id === taskId);
|
|
export function chatRunFailure(
|
|
runs: ChatRun[],
|
|
allowCancelled = false,
|
|
): string | undefined {
|
|
const failed = runs.find(
|
|
(run) =>
|
|
["failed", "timed_out"].includes(run.status) ||
|
|
(!allowCancelled && run.status === "cancelled"),
|
|
);
|
|
return failed
|
|
? `run ${failed.id} ${failed.status}${failed.errorCode ? ` (${failed.errorCode})` : ""}${failed.error ? `: ${failed.error}` : ""}`
|
|
: undefined;
|
|
}
|
|
|
|
export function chatTaskCompletionFailure(
|
|
task: ChatIssue,
|
|
runs: ChatRun[],
|
|
): string | undefined {
|
|
if (
|
|
task.scheduledRetry ||
|
|
task.activeRecoveryAction ||
|
|
runs.some((run) => ["queued", "running"].includes(run.status))
|
|
)
|
|
return undefined;
|
|
return chatRunFailure(runs);
|
|
}
|
|
|
|
/** Require two settled observations so an in-flight finalization is not a failure. */
|
|
export function createChatIdleFailureDetector(minimumProviderRuns: number) {
|
|
let priorInconsistentState: string | undefined;
|
|
return (state: {
|
|
resolved: boolean;
|
|
status?: string;
|
|
conversationState?: string;
|
|
providerRunCount: number;
|
|
activeRuns: string[];
|
|
}): string | undefined => {
|
|
const inconsistentState =
|
|
state.resolved &&
|
|
state.providerRunCount >= minimumProviderRuns &&
|
|
state.activeRuns.length === 0 &&
|
|
state.conversationState === "waiting" &&
|
|
["blocked", "done", "cancelled"].includes(state.status ?? "")
|
|
? `${state.status}:${state.providerRunCount}`
|
|
: undefined;
|
|
const stable =
|
|
inconsistentState !== undefined &&
|
|
inconsistentState === priorInconsistentState;
|
|
priorInconsistentState = inconsistentState;
|
|
return stable
|
|
? `chat_idle_state_invariant: conversation is ${state.status} while waiting after ${state.providerRunCount} settled provider runs`
|
|
: undefined;
|
|
};
|
|
}
|
|
|
|
/** Match the shared question form's durable/native presentation, including custom labels. */
|
|
export function chatQuestionPresentation(
|
|
payload: AskUserQuestionsPayload,
|
|
): PaperclipQuestionSetPayload {
|
|
if (payload.questionSet) return payload.questionSet;
|
|
return {
|
|
schema: "paperclip.question_set.v1",
|
|
...(payload.submitLabel ? { submitLabel: payload.submitLabel } : {}),
|
|
questions: payload.questions.map((question) => {
|
|
const freeText = question.options.find((option) => option.freeText);
|
|
return {
|
|
id: question.id,
|
|
prompt: question.prompt,
|
|
required: question.required === true,
|
|
answerMode:
|
|
question.selectionMode === "multi" ? "multi_select" : "single_select",
|
|
...(freeText
|
|
? { customAnswer: { enabled: true as const, label: freeText.label } }
|
|
: {}),
|
|
};
|
|
}),
|
|
};
|
|
}
|
|
|
|
export function assertChatTaskHandoff(
|
|
task: ChatIssue,
|
|
runs: ChatRun[],
|
|
source: ChatIssue,
|
|
) {
|
|
expect(task.parentId).toBeNull();
|
|
expect(task.projectId).toBeTruthy();
|
|
expect(task.assigneeAgentId).toBe(source.assigneeAgentId);
|
|
expect(runs.length).toBeGreaterThan(0);
|
|
}
|
|
|
|
/** A running row can precede creation of its log file. Only that expected 404 is retryable. */
|
|
export async function readRunningChatLog(
|
|
api: Pick<RunnerApi, "request">,
|
|
runId: string,
|
|
): Promise<string | undefined> {
|
|
const response = await api.request.get(
|
|
`/api/heartbeat-runs/${runId}/log?limitBytes=65536`,
|
|
);
|
|
if (response.status() === 404) return undefined;
|
|
if (!response.ok())
|
|
throw new Error(`Run ${runId} log returned ${response.status()}`);
|
|
return ((await response.json()) as { content?: string }).content;
|
|
}
|
|
|
|
/** Reset/blocked runs and proven pre-provider failures may have no provider log.
|
|
* Preserve their durable events; missing logs for real provider work still fail. */
|
|
export async function collectChatRunEvidence(
|
|
api: Pick<RunnerApi, "get">,
|
|
run: ChatRun,
|
|
allowAdmissionWait = false,
|
|
includeWorkspaceOperations = false,
|
|
) {
|
|
const admissionEvents = allowAdmissionWait ? await collectRunEvents((afterSeq, limit) =>
|
|
api.get(`/api/heartbeat-runs/${run.id}/events?afterSeq=${afterSeq}&limit=${limit}`),
|
|
) : null;
|
|
const admissionWait = admissionEvents ? classifyPreDispatchExecutionWait(run, admissionEvents) : null;
|
|
const recovery = run.resultJson?.executionRecovery as Record<string, unknown> | undefined;
|
|
const providerNeverStarted = run.runtimeMode === "legacy" && !run.runtimeModeResolvedAt &&
|
|
run.logStore === null && run.logRef === null && ["failed", "interrupted"].includes(run.status) &&
|
|
recovery?.kind === "bootstrap" && recovery.providerWorkStarted === false;
|
|
const reassignedBeforeStart = isReassignedUnstartedWake(run);
|
|
return {
|
|
runId: run.id,
|
|
...(providerNeverStarted ? { logOmissionReason: "provider_not_started" } : {}),
|
|
...(admissionWait ? { logOmissionReason: "pre_dispatch_execution_wait" } : {}),
|
|
...(reassignedBeforeStart ? { logOmissionReason: "assignee_changed_before_start" } : {}),
|
|
log: isResetRun(run) || isBlockedUnstartedWake({ ...run }) || providerNeverStarted || admissionWait || reassignedBeforeStart
|
|
? null
|
|
: await api.get(`/api/heartbeat-runs/${run.id}/log?limitBytes=1048576`),
|
|
events: admissionEvents ?? await collectRunEvents((afterSeq, limit) =>
|
|
api.get(`/api/heartbeat-runs/${run.id}/events?afterSeq=${afterSeq}&limit=${limit}`),
|
|
),
|
|
...(includeWorkspaceOperations ? {
|
|
workspaceOperations: await api.get<Array<Record<string, unknown>>>(`/api/heartbeat-runs/${run.id}/workspace-operations`),
|
|
} : {}),
|
|
};
|
|
}
|
|
|
|
export function assertChatHandoff(
|
|
task: ChatIssue,
|
|
plan: Plan,
|
|
runs: ChatRun[],
|
|
source: ChatIssue,
|
|
) {
|
|
assertChatTaskHandoff(task, runs, source);
|
|
expect(plan.body.trim()).not.toBe("");
|
|
for (const run of runs) {
|
|
expect(Date.parse(plan.updatedAt)).toBeLessThanOrEqual(
|
|
Date.parse(run.startedAt!),
|
|
);
|
|
}
|
|
}
|
|
export async function sendChatMessage(page: Page, message: string) {
|
|
const composer = page.getByTestId("task-chat-composer-input").last();
|
|
const takeover = page.getByTestId("task-chat-composer-takeover").last();
|
|
await expect(composer.or(takeover).first()).toBeVisible();
|
|
if (await takeover.isVisible()) {
|
|
// Close the card's composer view without answering, skipping, or approving it.
|
|
await takeover.getByRole("button", { name: /^Dismiss / }).click();
|
|
}
|
|
await composer
|
|
.locator('[contenteditable="true"], textarea')
|
|
.first()
|
|
.fill(message);
|
|
await page.getByTestId("task-chat-composer-send").last().click();
|
|
}
|
|
|
|
|
|
/** Independent durable oracle: prose alone cannot make a reassignment pass. */
|
|
export function assertChatReassignment(input: {
|
|
readyId: string; queuedId: string; teammateId: string; tasks: ChatIssue[]; runs: ChatRun[];
|
|
audit: Array<{ action: string; details?: Record<string, unknown> }>; outputBody: string; marker: string;
|
|
}) {
|
|
expect(input.tasks.map(task => task.id).sort()).toEqual([input.readyId, input.queuedId].sort());
|
|
expect(input.tasks.find(task => task.id === input.readyId)).toMatchObject({ status: "done", assigneeAgentId: input.teammateId });
|
|
expect(input.tasks.find(task => task.id === input.queuedId)).toMatchObject({ status: "backlog", assigneeAgentId: input.teammateId });
|
|
const successor = input.runs.filter(run => run.contextSnapshot?.issueId === input.readyId);
|
|
expect(successor).toHaveLength(1);
|
|
expect(successor[0]).toMatchObject({ agentId: input.teammateId, status: "succeeded", runtimeMode: "native" });
|
|
expect(input.runs.filter(run => run.contextSnapshot?.issueId === input.queuedId)).toHaveLength(0);
|
|
expect(input.audit.filter(row => row.action === "issue.reassigned" && row.details?.source === "paperclip_runner_protocol")).toHaveLength(1);
|
|
expect(input.outputBody).toContain(input.marker);
|
|
}
|
|
|
|
export interface ChatFlowInput {
|
|
page: Page;
|
|
api: RunnerApi;
|
|
fixtures: LiveFixtureValues;
|
|
execution: MatrixExecution;
|
|
nonce: string;
|
|
workspacePath: string;
|
|
deadlineAt: number;
|
|
restart: () => Promise<void>;
|
|
observe: (issue: ChatIssue, runs: ChatRun[]) => void;
|
|
capture: (id: string, label: string, file: string) => Promise<void>;
|
|
evidence: (name: string, data: unknown) => Promise<void>;
|
|
check?: (id: string, passed: boolean, detail: string) => void;
|
|
}
|
|
export async function runChatFlow(input: ChatFlowInput) {
|
|
const { page, api, fixtures: f, execution, nonce } = input;
|
|
const chatPath = `/api/companies/${f.company.id}/chats/${f.agent.id}`;
|
|
const route = `/${f.company.issuePrefix}/chats/${f.agent.id}`;
|
|
const marker = execution.task.buildVisibleMarker(nonce);
|
|
const draftMarker = chatMarker("DRAFT", nonce);
|
|
const caseId = execution.task.id;
|
|
const completionAccounting = needsChatCompletionProof(execution.suite.id, caseId, execution.profile.id, execution.environment.id);
|
|
let completionChildId: string | undefined;
|
|
let completionEvidence: ChatCompletionEvidence | undefined;
|
|
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 admissionAccounting = execution.suite.id === "kimi-qualification" && caseId === "stop-new-resume" && execution.profile.generation === "native";
|
|
let admissionWaits: ChatAdmissionWait[] = [];
|
|
let stoppedForSessionReset: string | undefined;
|
|
const providerRuns = () => admissionAccounting ? chatProviderRuns(runs, admissionWaits) : runs.filter(run => !isResetRun(run));
|
|
const settings = await api.get<Record<string, unknown>>(
|
|
"/api/instance/settings/experimental",
|
|
);
|
|
const allRuns = async () => {
|
|
const rows = await api.get<ChatRun[]>(
|
|
`/api/companies/${f.company.id}/heartbeat-runs?limit=100`,
|
|
);
|
|
return Promise.all(
|
|
rows.map((row) => api.get<ChatRun>(`/api/heartbeat-runs/${row.id}`)),
|
|
);
|
|
};
|
|
const tasks = () =>
|
|
api.get<ChatIssue[]>(`/api/companies/${f.company.id}/issues`);
|
|
const comments = async () =>
|
|
(
|
|
await api.get<Array<Comment & { createdAt: string }>>(
|
|
`/api/issues/${issue.id}/comments?order=asc`,
|
|
)
|
|
).sort(
|
|
(a, b) =>
|
|
a.createdAt.localeCompare(b.createdAt) || a.id.localeCompare(b.id),
|
|
);
|
|
const finalAdmissionEvidence = async () => ({
|
|
comments: await comments(),
|
|
runEvidence: await Promise.all(runs.map(run => collectChatRunEvidence(api, run, true))),
|
|
sources: await Promise.all(admissionWaits.map(async wait => ({
|
|
runId: stoppedForSessionReset!, recoveryActionId: wait.recoveryActionId,
|
|
response: await api.get(`/api/issues/${issue!.id}/recovery-actions?inspectSourceRunId=${stoppedForSessionReset}&inspectSourceActionId=${wait.recoveryActionId}`),
|
|
}))),
|
|
});
|
|
const idle = async (minimumProviderRuns: number, requireCompletion = false) => {
|
|
const inconsistentIdle = createChatIdleFailureDetector(minimumProviderRuns);
|
|
await pollUntil({
|
|
label: "chat turn settles to waiting",
|
|
deadlineAt: Date.now() + 240_000,
|
|
intervalMs: 1000,
|
|
retryOnError: retryChatCompletionObservation,
|
|
load: async () => {
|
|
const resolved = await api.get<ChatIssue | null>(chatPath);
|
|
if (resolved) issue = resolved;
|
|
runs = await allRuns();
|
|
if (admissionAccounting) {
|
|
admissionWaits = [];
|
|
for (const run of runs.filter(row => row.errorCode === "execution_reconciliation_required")) {
|
|
const evidence = await collectChatRunEvidence(api, run, true);
|
|
const wait = classifyPreDispatchExecutionWait(run, evidence.events);
|
|
expect(wait?.companyId).toBe(f.company.id);
|
|
expect(wait?.agentId).toBe(f.agent.id);
|
|
expect(wait?.issueId).toBe(resolved?.id);
|
|
admissionWaits.push(wait!);
|
|
}
|
|
}
|
|
if (resolved) input.observe(resolved, runs);
|
|
let admissionReady = true;
|
|
if (admissionAccounting && admissionWaits.length && minimumProviderRuns === 3 &&
|
|
providerRuns().length === 3 && runs.every(run => ["succeeded", "cancelled"].includes(run.status))) {
|
|
const proof = await finalAdmissionEvidence();
|
|
admissionReady = !proof.sources.some(source => {
|
|
const inspection = (source.response as { sourceInspection?: { status?: string; failureCode?: string } }).sourceInspection;
|
|
return inspection?.status === "blocked" && inspection.failureCode === "workspace_writer_active";
|
|
});
|
|
if (admissionReady) verifyChatAdmissionWaitCoverage({ runs, runEvidence: proof.runEvidence, comments: proof.comments,
|
|
issue: issue!, companyId: f.company.id, agentId: f.agent.id, stoppedRunId: stoppedForSessionReset, recoverySources: proof.sources });
|
|
}
|
|
let completionReady = !requireCompletion;
|
|
if (requireCompletion && providerRuns().length >= minimumProviderRuns
|
|
&& runs.every(run => run.status === "succeeded")) {
|
|
const notifications = runs.filter(run => run.contextSnapshot?.wakeReason === "chat_task_completed");
|
|
expect(notifications, "one required completion delivery").toHaveLength(1);
|
|
expect(completionChildId, "the existing delegated task must be retained").toBeTruthy();
|
|
const [source, child, finalTasks, sourceComments] = await Promise.all([
|
|
api.get<ChatCompletionEvidence["issue"]>(chatPath),
|
|
api.get<ChatCompletionEvidence["child"]>(`/api/issues/${completionChildId}`), tasks(),
|
|
api.get<ChatCompletionEvidence["comments"]>(`/api/issues/${issue!.id}/comments?order=asc`),
|
|
]);
|
|
const replies = sourceComments.filter(comment => comment.createdByRunId === notifications[0]!.id);
|
|
const renderedLinks = (await Promise.all(replies.map(async reply => {
|
|
const hrefs = await page.locator(`[id=${JSON.stringify(`comment-${reply.id}`)}] a[href]`)
|
|
.evaluateAll(elements => elements.map(element => element.getAttribute("href")!));
|
|
return hrefs.map(href => ({ commentId: reply.id, href }));
|
|
}))).flat();
|
|
// Wait for the real reply to render inside this existing idle deadline.
|
|
// Never extend the scenario or retry a provider to obtain the proof.
|
|
if (replies.length && renderedLinks.some(link => link.href.includes("/issues/"))) {
|
|
const companyPrefix = f.company.issuePrefix;
|
|
if (!companyPrefix) throw new Error("Chat completion proof: company_prefix_missing");
|
|
completionEvidence = { companyId: f.company.id, agentId: f.agent.id,
|
|
companyPrefix, baseURL: api.baseURL, issue: source, child,
|
|
tasks: finalTasks, comments: sourceComments, renderedLinks,
|
|
runEvidence: [await collectChatRunEvidence(api, notifications[0]!, false, true)] };
|
|
verifyChatCompletion(runs, completionEvidence);
|
|
completionReady = true;
|
|
}
|
|
}
|
|
return {
|
|
completionReady,
|
|
admissionReady,
|
|
resolved: Boolean(resolved),
|
|
status: resolved?.status,
|
|
conversationState: resolved?.conversationState,
|
|
providerRunCount: providerRuns().length,
|
|
activeRuns: runs
|
|
.filter((run) => ["queued", "running"].includes(run.status))
|
|
.map((run) => run.id),
|
|
failure: chatRunFailure(runs.filter(run => expectedStops.get(run.id) !== run.status), stopCase),
|
|
};
|
|
},
|
|
reject: (state) => state.failure ?? inconsistentIdle(state),
|
|
accept: (state) =>
|
|
!state.failure &&
|
|
state.completionReady &&
|
|
state.admissionReady &&
|
|
state.resolved &&
|
|
state.providerRunCount >= minimumProviderRuns &&
|
|
state.activeRuns.length === 0 &&
|
|
state.status === "in_review" &&
|
|
state.conversationState === "waiting",
|
|
});
|
|
};
|
|
const turn = async (text: string, count: number) => {
|
|
await sendChatMessage(page, text);
|
|
await idle(count);
|
|
};
|
|
const noTasks = async () => expect(await tasks()).toHaveLength(0);
|
|
let hiringEvidence: HiringTemplateEvidence | undefined;
|
|
let refreshHiringEvidence: (() => Promise<HiringTemplateEvidence>) | undefined;
|
|
try {
|
|
if (caseId === "enable-disable-resume") await enableChatThroughSettings(input);
|
|
else await api.patch("/api/instance/settings/experimental", {
|
|
enableAgentChat: true,
|
|
enableClassicTaskInterface: false,
|
|
});
|
|
expect(await api.get(chatPath)).toBeNull();
|
|
// Cold Vite startup can keep unrelated assets loading after the chat is
|
|
// interactive. The composer assertion below verifies actual UI readiness.
|
|
await page.goto(route, { waitUntil: "domcontentloaded", timeout: 60_000 });
|
|
await expect(page.getByTestId("task-chat-composer-input")).toBeVisible();
|
|
expect(await api.get(chatPath)).toBeNull();
|
|
expect(await allRuns()).toHaveLength(0);
|
|
|
|
if (execution.suite.id === CHAT_FEATURE_SUITE) {
|
|
return await runChatFeatureFlow({ input, issue: () => issue, allRuns,
|
|
refreshIssue: async () => { issue = await api.get<ChatIssue>(chatPath); if (issue) input.observe(issue, await allRuns()); } });
|
|
} else if (caseId === "confirmation-ambiguous") {
|
|
await runAmbiguousConfirmationReply({ input, issue: () => issue!, idle, comments });
|
|
} else if (caseId === "unanswered-question-return") {
|
|
await runUnansweredQuestionReturn({ input, issue: () => issue!, idle, comments });
|
|
} else if (caseId.startsWith("handoff-completion-")) {
|
|
await runChatCompletionUpdate({ input, marker, allRuns, issue: () => issue!,
|
|
refreshIssue: async () => { issue = await api.get<ChatIssue>(chatPath); if (issue) input.observe(issue, await allRuns()); } });
|
|
} else if (execution.suite.id === "hiring-templates") {
|
|
const hiring = await runHiringTemplateFlow({ input, issue: () => issue!, turn, tasks, allRuns });
|
|
hiringEvidence = hiring.evidence;
|
|
refreshHiringEvidence = hiring.refresh;
|
|
} else 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,
|
|
refreshIssue: async () => { issue = await api.get<ChatIssue>(chatPath); input.observe(issue, await allRuns()); } });
|
|
} else if (
|
|
["continuity-restart", "new-session", "stop-new-resume", "stop-startup-new-resume"].includes(caseId)
|
|
) {
|
|
const secret = chatMarker("OLDCONTEXT", nonce);
|
|
await turn(
|
|
`For this conversation only, remember the phrase ${secret}. Just acknowledge briefly; no project or task is needed.`,
|
|
1,
|
|
);
|
|
const initialId = issue!.id;
|
|
const before = providerRuns()[0]!;
|
|
await noTasks();
|
|
await page.reload({ waitUntil: "domcontentloaded", timeout: 60_000 });
|
|
if (caseId === "continuity-restart") {
|
|
await turn(
|
|
"What phrase did I just ask you to remember? Reply with the phrase only.",
|
|
2,
|
|
);
|
|
expect(
|
|
(await comments()).filter((c) => c.authorAgentId).at(-1)?.body,
|
|
).toContain(secret);
|
|
const count = runs.length;
|
|
await input.restart();
|
|
// Re-enter the canonical route after the server replaces its browser
|
|
// transport; reloading the stale document can target a detached page.
|
|
// The restarted dev server can leave DOMContentLoaded pending after the
|
|
// app is interactive. Require the actual chat composer after navigation.
|
|
await page.goto(route, { waitUntil: "commit", timeout: 60_000 });
|
|
await expect(page.getByTestId("task-chat-composer-input")).toBeVisible({ timeout: 60_000 });
|
|
await idle(2);
|
|
expect(runs).toHaveLength(count);
|
|
await turn(
|
|
`What phrase did I ask you to remember earlier? Reply with that remembered phrase followed by ${marker}; no further work.`,
|
|
3,
|
|
);
|
|
assertChatRememberedAfterRestart(
|
|
(await comments()).filter((comment) => comment.authorAgentId).at(-1)?.body ?? "",
|
|
secret,
|
|
marker,
|
|
);
|
|
} else {
|
|
let cancelledId: string | undefined;
|
|
if (stopCase) {
|
|
await sendChatMessage(
|
|
page,
|
|
"Explain the history of gardening at length here, in 100 numbered paragraphs. This is discussion only; do not create work.",
|
|
);
|
|
await expect
|
|
.poll(
|
|
async () => {
|
|
runs = await allRuns();
|
|
const active = runs.find(
|
|
(run) => run.status === "running" && run.id !== before.id,
|
|
);
|
|
if (!active) return false;
|
|
const events = await api.get<Array<Record<string, unknown>>>(
|
|
`/api/heartbeat-runs/${active.id}/events?limit=1000`,
|
|
);
|
|
if (execution.profile.generation === "native") {
|
|
if (!isChatStopReady(events, caseId === "stop-startup-new-resume" ? "startup" : "active")) return false;
|
|
} else if (!(events.length || (await readRunningChatLog(api, active.id))?.length)) return false;
|
|
cancelledId = active.id;
|
|
stoppedForSessionReset = active.id;
|
|
await input.evidence("chat-stop-boundary.json", {
|
|
phase: caseId === "stop-startup-new-resume" ? "startup" : "active",
|
|
runId: active.id, events,
|
|
});
|
|
return true;
|
|
},
|
|
{ timeout: 120_000 },
|
|
)
|
|
.toBe(true);
|
|
await page.getByTestId("task-chat-composer-stop").click();
|
|
await expect
|
|
.poll(
|
|
async () =>
|
|
(await api.get<ChatRun>(`/api/heartbeat-runs/${cancelledId}`))
|
|
.status,
|
|
{ timeout: 30_000 },
|
|
)
|
|
.toBe("cancelled");
|
|
}
|
|
const oldComments = await comments();
|
|
await sendChatMessage(page, "/new");
|
|
// Stop can be acknowledged before workspace preservation retries.
|
|
// Observe the reset within the existing case deadline.
|
|
await expect
|
|
.poll(
|
|
async () =>
|
|
(await api.get<ChatIssue>(chatPath))
|
|
.conversationSessionGeneration,
|
|
{ timeout: stopCase ? Math.max(1, input.deadlineAt - Date.now()) : 30_000 },
|
|
)
|
|
.toBe(1);
|
|
await expect
|
|
.poll(async () => (await allRuns()).some(isResetRun))
|
|
.toBe(true);
|
|
await turn(
|
|
`Without reading older history or files, if you have a remembered phrase in your current context return it; otherwise reply exactly ${marker}. Do not look it up.`,
|
|
caseId === "new-session" ? 2 : 3,
|
|
);
|
|
const fresh = runs
|
|
.filter((run) => !isResetRun(run) && run.status === "succeeded")
|
|
.sort((a, b) => Date.parse(a.startedAt!) - Date.parse(b.startedAt!))
|
|
.at(-1)!;
|
|
expect(fresh.contextSnapshot?.conversationSessionGeneration).toBe(1);
|
|
expect(fresh.sessionIdBefore).toBeFalsy();
|
|
expect(
|
|
String(fresh.contextSnapshot?.paperclipTaskMarkdown ?? ""),
|
|
).not.toContain(secret);
|
|
if (before.sessionIdAfter && fresh.sessionIdAfter)
|
|
expect(fresh.sessionIdAfter).not.toBe(before.sessionIdAfter);
|
|
const replies = (await comments()).filter(
|
|
(c) => c.createdByRunId === fresh.id && c.authorAgentId,
|
|
);
|
|
expect(replies.map((c) => c.body).join("\n")).toContain(marker);
|
|
expect(replies.map((c) => c.body).join("\n")).not.toContain(secret);
|
|
const reset = runs.filter(isResetRun);
|
|
expect(reset).toHaveLength(1);
|
|
expect(
|
|
(await comments()).filter(
|
|
(c) => c.authorAgentId && c.createdByRunId === reset[0]!.id,
|
|
),
|
|
).toHaveLength(0);
|
|
expect(
|
|
(await comments()).filter((c) =>
|
|
oldComments.some((old) => old.id === c.id),
|
|
),
|
|
).toHaveLength(oldComments.length);
|
|
if (cancelledId)
|
|
expect(
|
|
(await comments()).filter((c) => c.createdByRunId === cancelledId),
|
|
).toEqual(
|
|
oldComments.filter((c) => c.createdByRunId === cancelledId),
|
|
);
|
|
if (caseId === "stop-startup-new-resume" && cancelledId) {
|
|
const stopped = await api.get<ChatRun>(`/api/heartbeat-runs/${cancelledId}`);
|
|
const events = await api.get<Array<{ eventType?: unknown; createdAt?: string }>>(`/api/heartbeat-runs/${cancelledId}/events?limit=1000`);
|
|
await input.evidence("chat-startup-stop-result.json", { stopped, events });
|
|
assertChatStartupStopped(stopped, events);
|
|
}
|
|
await page.reload({ waitUntil: "domcontentloaded", timeout: 60_000 });
|
|
await expect(
|
|
page.getByText("New session", { exact: true }),
|
|
).toHaveCount(1);
|
|
}
|
|
expect(issue!.id).toBe(initialId);
|
|
await noTasks();
|
|
} else if (["hire-delegate-reuse", "blocked-status-review", "committed-send-retry"].includes(caseId)) {
|
|
await runChatHardeningFlow({ input, marker, issue: () => issue!, turn, idle, tasks, allRuns, comments });
|
|
} else if (caseId === "create-backlog") {
|
|
const project = await api.post<{ id: string }>(`/api/companies/${f.company.id}/projects`, {
|
|
name: `Later planning ${nonce}`, description: "Repository-free plans to save for later.",
|
|
});
|
|
await turn(`Create exactly one task titled Later checklist ${nonce} in the existing Later planning ${nonce} project. Assign it to yourself but keep it in backlog: do not start or execute it. Save a concise three-step initial plan that contains ${marker}. Reply with its identifier and status. Do not create a replacement task or change other tasks.`, 1);
|
|
const saved = (await tasks())[0]!;
|
|
expect(saved).toBeTruthy();
|
|
const plan = await api.get<Plan>(`/api/issues/${saved.id}/documents/plan`);
|
|
await turn(`What are the current owner and status of ${saved.identifier}? Just report its saved state. Do not execute it, change its status, or create another task.`, 2);
|
|
const observedTasks = await tasks();
|
|
// Issue activity also links the conversation run that created the task.
|
|
// Inspect actual run bindings to distinguish creation from execution.
|
|
const observedRuns = await allRuns();
|
|
const activity = await api.get<Array<{ action: string; details?: Record<string, unknown> }>>(`/api/issues/${saved.id}/activity`);
|
|
const persistedPlan = await api.get<Plan>(`/api/issues/${saved.id}/documents/plan`);
|
|
assertChatBacklogCreation({ tasks: observedTasks, runs: observedRuns, ownerId: f.agent.id, plan: persistedPlan, marker, activity });
|
|
expect(observedTasks[0]).toMatchObject({ id: saved.id, projectId: project.id });
|
|
expect(persistedPlan).toEqual(plan);
|
|
expect((await comments()).filter(c => c.authorAgentId).at(-1)?.body).toMatch(/backlog/i);
|
|
await page.reload({ waitUntil: "domcontentloaded", timeout: 60_000 });
|
|
await expect(page.getByTestId("task-chat-composer-input")).toBeVisible();
|
|
await expect(page.getByRole("link", { name: saved.identifier! }).first()).toBeVisible();
|
|
await input.capture("chat-backlog", "Planned backlog task without execution", "chat-backlog.png");
|
|
await input.evidence("chat-backlog.json", { tasks: observedTasks, runs: observedRuns, activity, plan: persistedPlan });
|
|
} else if (caseId === "reassign-task") {
|
|
const config = execution.profile.buildAgent({
|
|
environmentId: f.environment.id, environmentFixtureId: execution.environment.id,
|
|
workspacePath: input.workspacePath, secretRefs: f.secretRefs, executionId: nonce,
|
|
});
|
|
const teammate = await api.post<{ id: string }>(`/api/companies/${f.company.id}/agents`, {
|
|
...config, name: "Riley Reassignment", role: "engineer", reportsTo: f.agent.id,
|
|
instructionsBundle: { entryFile: "AGENTS.md", files: { "AGENTS.md": "Complete the assigned work and save the requested Paperclip document." } },
|
|
});
|
|
const queued = await api.post<ChatIssue>(`/api/companies/${f.company.id}/issues`, {
|
|
title: `Later checklist ${nonce}`, description: `Preserve this deferred scope ${draftMarker}.`,
|
|
status: "backlog", assigneeAgentId: f.agent.id,
|
|
});
|
|
const ready = await api.post<ChatIssue>(`/api/companies/${f.company.id}/issues`, {
|
|
title: `Ready checklist ${nonce}`, status: "todo",
|
|
description: `Write a short launch checklist as a Paperclip document attached to this task, including ${marker}. Complete this task after saving it.`,
|
|
});
|
|
await turn(`Assign the existing Ready checklist ${nonce} task to Riley Reassignment so Riley completes it. Also move the existing Later checklist ${nonce} task from you to Riley, keeping it in backlog. Preserve both tasks and their descriptions. Explain the handoff briefly here. Do not create replacement tasks or start the backlog work.`, 2);
|
|
const observedTasks = await tasks();
|
|
const readyAfter = await api.get<ChatIssue>(`/api/issues/${ready.id}`);
|
|
const queuedAfter = await api.get<ChatIssue>(`/api/issues/${queued.id}`);
|
|
const output = await readChatOutputDocument(api, ready.id, marker);
|
|
const activity = await api.get<Array<{ action: string; details?: Record<string, unknown> }>>(`/api/issues/${ready.id}/activity`);
|
|
assertChatReassignment({ readyId: ready.id, queuedId: queued.id, teammateId: teammate.id, tasks: observedTasks, runs,
|
|
audit: activity, outputBody: output.body, marker });
|
|
expect(queuedAfter).toMatchObject({ assigneeAgentId: teammate.id, status: "backlog", description: `Preserve this deferred scope ${draftMarker}.` });
|
|
expect(readyAfter).toMatchObject({ assigneeAgentId: teammate.id, status: "done" });
|
|
expect(issue!).toMatchObject({ assigneeAgentId: f.agent.id, conversationState: "waiting" });
|
|
await page.reload({ waitUntil: "domcontentloaded", timeout: 60_000 });
|
|
await expect(page.getByTestId("task-chat-composer-input")).toBeVisible();
|
|
await expect(page.getByRole("link", { name: readyAfter.identifier! }).first()).toBeVisible();
|
|
await input.capture("chat-reassignment", "Reassignment completed in Agent Chat", "chat-reassignment.png");
|
|
await input.evidence("chat-reassignment.json", { tasks: observedTasks, runs, activity, output, teammateId: teammate.id });
|
|
} else {
|
|
let existingProject: { id: string; name: string } | undefined;
|
|
let acceptedPlan: Plan | undefined;
|
|
let repositoryCatalogBefore:
|
|
{ repositories: Array<{ id: string; url: string }> } | undefined;
|
|
const expectedRepositoryUrls = [
|
|
"https://github.com/octocat/Hello-World",
|
|
"https://github.com/octocat/Spoon-Knife",
|
|
];
|
|
if (caseId === "clarify-reuse") {
|
|
existingProject = await api.post(
|
|
`/api/companies/${f.company.id}/projects`,
|
|
{
|
|
name: `Garden ${nonce}`,
|
|
description: "Garden club welcome notes and event announcements.",
|
|
},
|
|
);
|
|
await turn(
|
|
"I need a welcome note for our club. Help me clarify what information you need before assigning the work.",
|
|
1,
|
|
);
|
|
await noTasks();
|
|
const questions = await api.get<
|
|
Array<{
|
|
status: string;
|
|
kind: string;
|
|
payload: AskUserQuestionsPayload;
|
|
}>
|
|
>(`/api/issues/${issue!.id}/interactions`);
|
|
const pendingInteraction = questions.find(
|
|
(row) =>
|
|
row.status === "pending" && row.kind === "ask_user_questions",
|
|
);
|
|
const questionSet = pendingInteraction
|
|
? chatQuestionPresentation(pendingInteraction.payload)
|
|
: undefined;
|
|
const pendingQuestions = questionSet?.questions;
|
|
expect(
|
|
Boolean(pendingQuestions?.length) ||
|
|
(await comments()).some(
|
|
(c) => c.authorAgentId && isChatClarificationReply(c.body),
|
|
),
|
|
).toBe(true);
|
|
const clarification = `It is the garden club; use the existing Garden ${nonce} project. Make one assigned task for yourself to write a two-sentence welcome note. Include ${marker} in that note, save it as a Paperclip document attached to that execution task, and finish that execution task. Please get it started now.`;
|
|
if (pendingQuestions?.length) {
|
|
for (const [index, question] of pendingQuestions.entries()) {
|
|
const textInput = page
|
|
.getByTestId("question-text-answer-composer")
|
|
.last();
|
|
if (await textInput.isVisible()) {
|
|
await textInput
|
|
.locator('[contenteditable="true"],textarea')
|
|
.first()
|
|
.fill(clarification);
|
|
} else {
|
|
await page
|
|
.getByRole(
|
|
question.answerMode === "multi_select" ? "checkbox" : "radio",
|
|
{
|
|
name: question.customAnswer?.label ?? "Other",
|
|
exact: true,
|
|
},
|
|
)
|
|
.last()
|
|
.click();
|
|
await page
|
|
.getByTestId("question-other-answer-composer")
|
|
.last()
|
|
.locator('[contenteditable="true"],textarea')
|
|
.first()
|
|
.fill(clarification);
|
|
}
|
|
await page
|
|
.getByRole("button", {
|
|
name:
|
|
index === pendingQuestions.length - 1
|
|
? (questionSet?.submitLabel ?? "Submit answers")
|
|
: "Next",
|
|
exact: true,
|
|
})
|
|
.last()
|
|
.click();
|
|
}
|
|
await idle(3);
|
|
} else await turn(clarification, 3);
|
|
} else if (caseId === "plan-handoff") {
|
|
await page.getByTestId("task-chat-composer-add").click();
|
|
await page.getByTestId("composer-add-plan").click();
|
|
await turn(
|
|
`Let's plan a two-sentence garden club welcome note. The finished welcome note itself must contain the exact phrase ${draftMarker}. Write a plan in the plan panel that includes this requirement, and present it for approval. When I approve the final revision, create a suitable repository-free project and an assigned task for yourself, copy the plan into that task, and have it save the note as a Paperclip document attached to that execution task and finish. Do not create the project or task before approval.`,
|
|
1,
|
|
);
|
|
const draft = await api.get<Plan>(
|
|
`/api/issues/${issue!.id}/documents/plan`,
|
|
);
|
|
expect(draft.body).toContain(draftMarker);
|
|
await noTasks();
|
|
await input.capture(
|
|
"chat-plan-draft",
|
|
"Draft plan in the conversation",
|
|
"chat-plan-draft.png",
|
|
);
|
|
const initialInteractions = await api.get<
|
|
Array<{
|
|
status: string;
|
|
kind: string;
|
|
payload?: {
|
|
target?: { revisionId?: string };
|
|
rejectLabel?: string;
|
|
};
|
|
}>
|
|
>(`/api/issues/${issue!.id}/interactions`);
|
|
const initialApproval = initialInteractions.find(
|
|
(row) =>
|
|
row.status === "pending" &&
|
|
row.kind === "request_confirmation" &&
|
|
row.payload?.target?.revisionId === draft.latestRevisionId,
|
|
);
|
|
expect(
|
|
initialApproval,
|
|
"draft has a revision-bound approval",
|
|
).toBeTruthy();
|
|
const reviseButton = page
|
|
.getByRole("button", {
|
|
name: initialApproval!.payload?.rejectLabel ?? "Reject",
|
|
exact: true,
|
|
})
|
|
.last();
|
|
await reviseButton.click();
|
|
await page
|
|
.getByTestId("plan-revision-composer")
|
|
.last()
|
|
.locator('[contenteditable="true"],textarea')
|
|
.first()
|
|
.fill(
|
|
`Revise the plan: the finished welcome note itself must contain the exact phrase ${marker} instead of ${draftMarker}. Include that requirement in the revised plan. The execution task should save that welcome note as a Paperclip document attached to that task. Present this revised plan for approval; wait for that approval before handing it off as agreed.`,
|
|
);
|
|
await reviseButton.click();
|
|
await idle(2);
|
|
const revised = await api.get<Plan>(
|
|
`/api/issues/${issue!.id}/documents/plan`,
|
|
);
|
|
expect(revised.body).toContain(marker);
|
|
// A revision-history section may quote the superseded requirement.
|
|
// The executed output below must use only the accepted requirement.
|
|
expect(revised.latestRevisionId).not.toBe(draft.latestRevisionId);
|
|
acceptedPlan = revised;
|
|
await noTasks();
|
|
const interactions = await api.get<
|
|
Array<{
|
|
id: string;
|
|
status: string;
|
|
kind: string;
|
|
payload?: {
|
|
target?: { revisionId?: string };
|
|
acceptLabel?: string;
|
|
};
|
|
}>
|
|
>(`/api/issues/${issue!.id}/interactions`);
|
|
const approval = interactions.find(
|
|
(row) =>
|
|
row.status === "pending" &&
|
|
row.kind === "request_confirmation" &&
|
|
row.payload?.target?.revisionId === revised.latestRevisionId,
|
|
);
|
|
expect(approval, "approval targets the revised plan").toBeTruthy();
|
|
await input.capture(
|
|
"chat-plan-revised",
|
|
"Revised plan before handoff",
|
|
"chat-plan-revised.png",
|
|
);
|
|
await page
|
|
.getByRole("button", {
|
|
name: approval!.payload?.acceptLabel ?? "Approve",
|
|
exact: true,
|
|
})
|
|
.last()
|
|
.click();
|
|
await idle(4);
|
|
await input.evidence("chat-plan-revisions.json", {
|
|
draft,
|
|
revised,
|
|
approval,
|
|
source: await api.get(`/api/issues/${issue!.id}/documents/plan`),
|
|
});
|
|
} else {
|
|
repositoryCatalogBefore = await api.get(
|
|
`/api/companies/${f.company.id}/project-repositories`,
|
|
);
|
|
expect(
|
|
repositoryCatalogBefore!.repositories.filter((repository) =>
|
|
expectedRepositoryUrls.includes(repository.url),
|
|
),
|
|
).toHaveLength(0);
|
|
await turn(
|
|
`Create a project called Repository Discussion ${nonce} for work spanning https://github.com/octocat/Hello-World and https://github.com/octocat/Spoon-Knife. These existing public repositories are not in our catalog; register both URLs. Then make one assigned task for yourself to write a two-sentence description of the intended project as a Paperclip document attached to that execution task, containing ${marker}, and complete that task. No code changes or remote repository creation are needed.`,
|
|
2,
|
|
);
|
|
}
|
|
const children = await tasks();
|
|
expect(children).toHaveLength(1);
|
|
const child = children[0]!;
|
|
if (completionAccounting) completionChildId = child.id;
|
|
await pollUntil({
|
|
label: `execution task ${child.id} completes`,
|
|
deadlineAt: Date.now() + 240_000,
|
|
intervalMs: 1000,
|
|
load: async () => ({
|
|
task: await api.get<ChatIssue>(`/api/issues/${child.id}`),
|
|
runs: await api.get<ChatRun[]>(`/api/issues/${child.id}/runs`),
|
|
}),
|
|
accept: (state) => state.task.status === "done",
|
|
reject: (state) => chatTaskCompletionFailure(state.task, state.runs),
|
|
});
|
|
// A completed handoff returns to the source chat (#14408) as one
|
|
// correlated provider turn. Observe that delivery instead of racing it.
|
|
const completionReply = await pollUntil({
|
|
label: `completion of ${child.id} is reported in the chat`,
|
|
deadlineAt: Date.now() + 240_000,
|
|
intervalMs: 1000,
|
|
load: async () => {
|
|
const rows = await allRuns();
|
|
const reply = rows.filter((run) => isChatCompletionReply(run, issue!.id, child.id));
|
|
return { runs: rows, reply, comments: await comments() };
|
|
},
|
|
// A native reply comment is presented after its run succeeds, so wait
|
|
// for the comment too; a failed reply turn settles immediately.
|
|
accept: (state) => state.reply.length > 0 &&
|
|
state.reply.every((run) => ["succeeded", "failed", "cancelled", "timed_out"].includes(run.status)) &&
|
|
(state.reply.some((run) => run.status !== "succeeded") ||
|
|
state.comments.some((c) => c.authorAgentId === f.agent.id && state.reply.some((run) => run.id === c.createdByRunId))),
|
|
});
|
|
expect(completionReply.reply.map((run) => run.status), "one completion reply turn").toEqual(["succeeded"]);
|
|
expect(completionReply.comments.filter((c) => c.authorAgentId === f.agent.id &&
|
|
c.createdByRunId === completionReply.reply[0]!.id), "completion reply posted in the chat").toHaveLength(1);
|
|
runs = completionReply.runs;
|
|
input.observe(issue!, runs);
|
|
const plan =
|
|
caseId === "plan-handoff"
|
|
? await api.get<Plan>(`/api/issues/${child.id}/documents/plan`)
|
|
: null;
|
|
const taskRuns = runs.filter(
|
|
(run) => run.contextSnapshot?.issueId === child.id,
|
|
);
|
|
if (plan) {
|
|
assertChatHandoff(child, plan, taskRuns, issue!);
|
|
expect(plan.body).toContain(marker);
|
|
const sourcePlan = await api.get<Plan>(
|
|
`/api/issues/${issue!.id}/documents/plan`,
|
|
);
|
|
expect(sourcePlan.body).toBe(acceptedPlan!.body);
|
|
expect(sourcePlan.latestRevisionId).toBe(
|
|
acceptedPlan!.latestRevisionId,
|
|
);
|
|
} else assertChatTaskHandoff(child, taskRuns, issue!);
|
|
const output = await readChatOutputDocument(api, child.id, marker);
|
|
assertChatExecutionOutput(
|
|
output.body,
|
|
marker,
|
|
caseId === "plan-handoff" ? draftMarker : undefined,
|
|
);
|
|
await input.evidence("chat-execution-output.json", {
|
|
taskId: child.id,
|
|
document: output,
|
|
revisions: await api.get(
|
|
`/api/issues/${child.id}/documents/${encodeURIComponent(output.key)}/revisions`,
|
|
),
|
|
executionRunIds: taskRuns.map((run) => run.id),
|
|
});
|
|
expect(
|
|
(await comments())
|
|
.filter((c) => c.authorAgentId)
|
|
.map((c) => c.body)
|
|
.join("\n"),
|
|
).toMatch(new RegExp(`${child.id}|${child.identifier}`));
|
|
const projects = await api.get<
|
|
Array<{
|
|
id: string;
|
|
name: string;
|
|
workspaces: Array<{ id: string; name: string; repoUrl?: string }>;
|
|
}>
|
|
>(`/api/companies/${f.company.id}/projects`);
|
|
expect(projects).toHaveLength(1);
|
|
if (existingProject) {
|
|
expect(child.projectId).toBe(existingProject.id);
|
|
await expect(
|
|
page.getByRole("article", { name: /Project created:/ }),
|
|
).toHaveCount(0);
|
|
} else {
|
|
await expect(
|
|
page.getByRole("article", { name: /Project created:/ }),
|
|
).toHaveCount(1);
|
|
if (caseId === "multi-repository") {
|
|
expect(projects[0]!.workspaces.map((w) => w.repoUrl).sort()).toEqual(
|
|
[...expectedRepositoryUrls].sort(),
|
|
);
|
|
// URL registration is persisted as project workspaces; the discovery
|
|
// catalog continues to reflect authorized GitHub connections only.
|
|
expect(
|
|
projects[0]!.workspaces.every((workspace) => Boolean(workspace.id)),
|
|
).toBe(true);
|
|
expect(
|
|
new Set(projects[0]!.workspaces.map((workspace) => workspace.id))
|
|
.size,
|
|
).toBe(2);
|
|
const persistedProject = await api.get<{
|
|
workspaces: Array<{ id: string; repoUrl?: string }>;
|
|
}>(`/api/projects/${projects[0]!.id}`);
|
|
expect(
|
|
persistedProject.workspaces.map(({ id, repoUrl }) => ({
|
|
id,
|
|
repoUrl,
|
|
})),
|
|
).toEqual(
|
|
projects[0]!.workspaces.map(({ id, repoUrl }) => ({ id, repoUrl })),
|
|
);
|
|
await input.evidence("chat-repository-registration.json", {
|
|
catalogBefore: repositoryCatalogBefore,
|
|
projectId: projects[0]!.id,
|
|
registeredWorkspaces: persistedProject.workspaces,
|
|
});
|
|
const projectCard = page.getByRole("article", {
|
|
name: /Project created:/,
|
|
});
|
|
// Repository labels may be customized; verify the actual destinations.
|
|
for (const repositoryUrl of expectedRepositoryUrls) {
|
|
await expect(
|
|
projectCard.locator(`a[href="${repositoryUrl}"]`),
|
|
).toBeVisible();
|
|
}
|
|
} else
|
|
expect(projects[0]!.workspaces.filter((w) => w.repoUrl)).toHaveLength(
|
|
0,
|
|
);
|
|
await page.reload({ waitUntil: "domcontentloaded", timeout: 60_000 });
|
|
await expect(
|
|
page.getByRole("article", { name: /Project created:/ }),
|
|
).toHaveCount(1);
|
|
}
|
|
await input.evidence("chat-handoff.json", {
|
|
source: issue!,
|
|
task: child,
|
|
plan,
|
|
output,
|
|
projects,
|
|
});
|
|
}
|
|
await idle(minimumRunCount(execution.task), completionAccounting);
|
|
if (execution.suite.id === "hiring-templates") {
|
|
// Refresh the whole consistent evidence generation for the final guard.
|
|
hiringEvidence = await refreshHiringEvidence!();
|
|
runs = hiringEvidence.runs;
|
|
}
|
|
const finalAdmission = admissionAccounting ? await finalAdmissionEvidence() : undefined;
|
|
const finalComments = finalAdmission?.comments;
|
|
const admissionRunEvidence = finalAdmission?.runEvidence;
|
|
const admissionWaitSources = finalAdmission?.sources ?? [];
|
|
if (admissionAccounting) admissionWaits = verifyChatAdmissionWaitCoverage({ runs, runEvidence: admissionRunEvidence!, comments: finalComments!, issue: issue!,
|
|
companyId: f.company.id, agentId: f.agent.id, stoppedRunId: stoppedForSessionReset, recoverySources: admissionWaitSources });
|
|
assertChatFlowRunCount({ suiteId: execution.suite.id, task: execution.task,
|
|
profileId: execution.profile.id, environmentId: execution.environment.id, completionEvidence,
|
|
// Hiring must account for every actual company run, including unexpected resets.
|
|
runs: execution.suite.id === "hiring-templates" || completionAccounting ? runs : providerRuns(),
|
|
hiringEvidence, hiringApiState: execution.suite.id === "hiring-templates"
|
|
? hiringEvidence!.turnApiState : undefined,
|
|
});
|
|
if (completionAccounting) await input.evidence("chat-completion-proof.json", verifyChatCompletion(runs, completionEvidence));
|
|
for (const run of providerRuns()) {
|
|
expect(run.runtimeMode).toBe(execution.profile.expectedRuntimeMode);
|
|
expect(run.status).toBe(
|
|
expectedStops.get(run.id) ?? (stopCase && run.status === "cancelled"
|
|
? "cancelled"
|
|
: "succeeded"),
|
|
);
|
|
}
|
|
await input.evidence("api-state.json", {
|
|
issue: issue!,
|
|
runs,
|
|
...(admissionAccounting ? { admissionWaitSources } : {}),
|
|
runGroups: {
|
|
...(admissionAccounting ? { admissionWaits: admissionWaits.map(wait => wait.runId) } : {}),
|
|
resets: runs.filter(isResetRun).map((run) => run.id),
|
|
cancelled: runs
|
|
.filter((run) => run.status === "cancelled")
|
|
.map((run) => run.id),
|
|
conversation: runs
|
|
.filter(
|
|
(run) =>
|
|
providerRuns().some(provider => provider.id === run.id) && run.contextSnapshot?.issueId === issue!.id,
|
|
)
|
|
.map((run) => run.id),
|
|
handoff: runs
|
|
.filter((run) => run.contextSnapshot?.issueId !== issue!.id)
|
|
.map((run) => run.id),
|
|
},
|
|
comments: finalComments ?? await comments(),
|
|
activity: await api.get(`/api/issues/${issue!.id}/activity`),
|
|
runEvidence: admissionRunEvidence ?? await Promise.all(runs.map(run => collectChatRunEvidence(api, run))),
|
|
});
|
|
await input.capture(
|
|
"final-state",
|
|
"Chat waiting after its verified workflow",
|
|
"final-state.png",
|
|
);
|
|
return { issue: issue!, runs };
|
|
} finally {
|
|
await api.patch("/api/instance/settings/experimental", {
|
|
enableAgentChat: settings.enableAgentChat,
|
|
enableClassicTaskInterface: settings.enableClassicTaskInterface,
|
|
});
|
|
}
|
|
}
|