Files
PaperClipAI/tests/runner-e2e/antigravity-journey-flow.ts
T
DottaandPaperclip ebed7f5237 test(evals): protect Antigravity setup and two-turn delivery (#18190)
## Thinking Path

> - Paperclip manages agents and their work.
> - A provider integration must work through ordinary agent setup and
task controls.
> - The recorded Antigravity walkthrough exposed setup, delivery, and
continuation failures.
> - A repeatable check must verify real work and retain failed attempts.
> - This pull request converts all 47 recorded steps into one fixed
Product E2E journey.
> - Maintainers can rerun the case and inspect independent delivery,
cleanup, and accounting evidence.

## Linked Issues or Issue Description

Builds on merged #18187, #18188, and #18189, and consumes the shared
repairs from merged #18230 and the equivalent manual-policy declaration
from #18222. Refs #18214 for the CI task wrapper. Refs #12503 and #14938
for related legacy adapter work.

**Agent or provider**

Google Antigravity native Runner with a saved managed Google
subscription and the exact Low model.

**Why this adapter is useful**

A user must be able to add an agent, connect its account, and receive
real task results across a follow-up. Picker visibility alone is
insufficient.

**How the agent is invoked**

A fixed Playwright driver uses ordinary product controls. The agent runs
through native ACP. Independent checks use public APIs, actual
downloads, owned process observations, and native lifetime fences.

## What Changed

- Register one explicit-only case:
`antigravity-agent-journey.runner-antigravity.local.saved-subscription-two-turn`.
- Map all 47 source steps and declare saved-account prerequisites,
finite limits, and same-host macOS ARM64 scope.
- Create an agent through the ordinary picker, connect the saved
account, select Low, run Test, and wait for readiness. Save an
instruction marker, deliver a file, and update it through an ordinary
follow-up.
- Require each run's visible completed file activity, exact downloaded
bytes, committed Done result, same tagged conversation, distinct
physical owner birth, released lease, and free native fences. Verify
reload persistence.
- Stop failed native runs that still own a retry. Replay an existing
Stop with its durable request identity and wait for the matching audited
acknowledgement. A terminal reservation without a native intent remains
unconfirmed.
- Keep private evidence in the existing result, report, dashboard, and
accounting pipeline. Retain the paused QA agent and financial history
while preserving the shared account and budget policies.
- Journal only the ordinary wizard's future ID, target, name, intended
harness and expected creator before forwarding its POST unchanged. Bind
the response and interrupted recovery to exact identity reads; a pending
404 stays unconfirmed.
- Serialize private resource snapshots through temporary-file fsync,
atomic rename and directory fsync. Abort forwarding on storage failure
and preserve legacy receipts. If later journal or diagnostic writes
fail, retain the primary error, always close the browser, and attempt
the ordinary failed report.
- Add production-component browser controls and harden task-menu
readiness, alias selection, scroll restoration, failure packaging, and
one hermetic auth-test budget.
- Wait for the existing GitHub recovery fixture to register its next
deadline before asserting the original range; preserve its
nested-transaction and zero-request checks. In the decision-expiry
fixture, verify the exact saved expiry separately from the earlier
global wake of another queue.

## Verification

- Fresh registered acceptance passed on eval source
`9060f3cd01b7c3445ecdf703d72e9cf30fe42b59` and merged serving product
`61bd4ac6919c2309f766a25e62273b074cee3261`. It completed ordinary setup
and two turns with native `.5` and `gemini-3.8-flash-low`. All 16
matchers, 14 checkpoints, and cleanup passed in **165,613 ms**. Actual
downloads were **61 bytes** and **119 bytes**. Both turns passed their
own run-bound browser activity checks and reload persistence.
- Independent read-back confirms Done, a paused retained agent, the same
connected saved default account, and no active owned run. Both accepted
results have the same full tagged conversation and distinct primary
process births. All 21 observed processes retired; both leases released
and all three native fences were free after each turn. The selected `.5`
checkpoints also showed equal agent/backend session IDs; this is an
observed case requirement, not a generic ACP invariant.
- Receipts report 339,273 input tokens, 7,224 output tokens, and 202,846
cached input tokens. Subscription prices are unavailable. Billing
coverage remains incomplete, not free.
- The normal report CLI passed. All 310 files from nine original
attempts and two separate recoveries retained their hashes. The twelve
current screenshots are byte-identical, and 194 local report links are
contained and valid. The eight earlier reports were copied without
regeneration.
- Delivery source `1bf4fb04df04710b82844b3c9355767f46b5f68f` branches
from `d3f2a60e795fc60d64c8b19d1eed4d48657d5492` and merges cleanly with
current master `1d571de5f9f886d66e520800baec8fc2f67d0948`. All 41 prior
`c8b332` authored file blobs remain identical; the 42nd path is the
decision-expiry fixture contract correction. Creation ownership, the
strict durable writer, and the ordinary successful workflow remain
unchanged. Of 43 measured file blobs, 30 remain identical. The
Antigravity oracle, artifact, billing and report gates and its
suite-specific validation block remain unchanged. The actual retained
agent matches its original creator; its original request `setupId` was
not captured and is not reconstructed.
- Later master changes include model-visible workspace guidance and
rejected-terminal-report handling. Their bounded source assessment is
separate: the first actual finish failed, then a same-turn replacement
was accepted and committed. Later read-only results match both original
native-result hashes, and the complete event catalogs have no
`session.failed` event. Master #18228 also expands detection of explicit
JSON file requests. The measured create/update-and-attach `.txt` task
already required publication under both parsers; the publication
validation gate itself is unchanged. Master #18240 changes remote
workspace cache staging and adds an OpenCode index refresh. The selected
local lane returns before those paths. Master #18213 adds optional
numeric turn timing and trace boundaries. Its selected Antigravity
model, text, IDs, result and retirement semantics remain unchanged in
the bounded source review. Local diagnostic rows and awaits can change
event ordinals and latency; the oracle checks relative semantic order.
Collector coverage and latency improvement remain outside this proof.
This does not claim that the whole current runtime is byte-identical to
serving `61bd`, or relabel the measured result as a new run.
- The adopted upstream cache controls passed 3/3 with pinned real Turbo.
Forced work disables local and remote reads and writes; ordinary work
reuses local results. The original genuine-pnpm/Turbo controls remain
historical to `9060`'s earlier write-only policy. The duplicate cache
patch is superseded by #18230. Its qualification-only pnpm addition is
removed because the adopted upstream controls do not require it.
- The E2E typecheck, map checks and 277-control replay are carried from
the unchanged eval source paths. That replay passed, including the 183
Antigravity controls, catalog/connection checks and the separate
product-journey validator. The carried creation controls include 91
config/recovery cases. The final launcher suite passed 19/19, including
five real campaign finalization fault cases; the report suite passed
7/7. These final checks did not rerun the earlier 277-control group. The
canonical production-component browser spec passed in 27.4 s under its
unchanged 60 s limit before the replay. Four paused-composer cases and
the product base's build/typecheck plus 376 focused regressions were
verified earlier.
- The shipped wizard and actual API client cover persistence before
forwarding, lost response JSON, foreign/malformed requests, wrong
response identity/creator and cleanup-error preservation. Real
filesystem controls failed 5/5 before the writer repair and passed 5/5
afterward, preserving the old journal on partial-write, temporary-file
sync and rename faults. Three persistent-sync campaign controls failed
before the finalization repair and passed afterward. All five final
campaign fault cases preserve the primary failure, cleanup failure,
usage and failed report while attempting browser closure. The strict
journal still blocks the next mutation. These are provider-free
ownership controls; the Google task proof remains the original `9060` →
`61bd` acceptance.
- The decision restart check passed in the local 20-case fixture run. A
current-source real-PostgreSQL rollback control reproduced the exact
90,000 ms earlier global wake: the old equality rejected it, while the
exact durable expiry and new future-wake bound passed. The original 60 s
open-state, exact-timestamp, continuation and quiet checks remain. The
broader local run was **FAILED: 19 passed / 1 failed**, with a 15 s
timeout and a 30 s cleanup timeout in an unchanged timestamp-pagination
case. That case passed in canonical `c8b332` CI; the local timeout cause
remains inconclusive. An extra local server typecheck failed against
stale cached Runner declarations; it did not check this excluded test
file. Both limits remain recorded for fresh canonical CI.
- A broader local GitHub recovery group passed 21/22. Its unchanged
pagination case observed an unexpected config request; the log does not
establish the cause. That result remains retained, and fresh
current-head CI is the final broader gate.

- Exact delivery-head CI completed with 55 successes, two skips, and one
optional neutral review. Required `ci / verify` and `ci / e2e`, build,
typecheck, and Runner checks passed. Fresh Greptile is 5/5 with zero
unresolved threads. Optional Paperclip is neutral 4/5; its carried
recommendations are dispositioned against the public Stop contract and
selected live identity evidence.

Seven earlier converted attempts retain their failed grades and partial
evidence. Historical Paid8 and its later read-only per-run UI
observation remain separate from the fresh acceptance above. Unknown
prices and the older partial startup accounting remain explicit. Full
lineage and raw evidence remain private in the normal report bundle.

## Risks

- This case requires an authorized saved personal default Google
subscription and finite operator candidate admission. It does not test
fresh OAuth or establish global qualification.
- The physical observer supports a same-host loopback macOS ARM64
target. Cloud, Linux, and other models remain outside this case.
- A known-cost stop cannot cap missing prices or in-flight subscription
charges. Existing operator policies remain unchanged.
- Raw account/native identities stay private. Missing retirement proof
keeps resources retained. The selected cleanup mode does not test agent
purge.

## Model Used

OpenAI Codex (GPT-6). The host did not expose the exact model revision
or context limit. The model used tools for code edits, tests, browser
automation, and review.

## 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>
2026-10-29 19:51:32 -05:00

242 lines
17 KiB
TypeScript

import { randomUUID } from "node:crypto";
import { expect, type Page, type Request, type Route } from "@playwright/test";
import { ConnectionFailure } from "./connection-config.js";
import { ConnectionApi } from "./connection-target.js";
import { ANTIGRAVITY_JOURNEY_MODEL, type AntigravityJourneyConfig } from "./antigravity-journey-config.js";
import { verifyAntigravityJourneyTurn, type AntigravityJourneyEvidence } from "./antigravity-journey-evidence.js";
import type { AntigravityJourneyResources, prepareAntigravityJourney } from "./antigravity-journey-fixtures.js";
import { openAntigravityCreatedTask, assertAntigravityCleanComposer, assertAntigravityFileActivity, assertAntigravityReady, assertAntigravityTaskDone, inspectAntigravityArtifact, openAntigravityAgentFromRoster, selectAntigravityFromOrdinaryPicker } from "./antigravity-journey-ui.js";
import { submitTaskReply } from "./user-actions.js";
type Row = Record<string, any>;
export interface AntigravityJourneyFlowInput {
page: Page; api: ConnectionApi; config: AntigravityJourneyConfig; prepared: Awaited<ReturnType<typeof prepareAntigravityJourney>>;
resources: AntigravityJourneyResources; evidence: AntigravityJourneyEvidence;
checkpoint(id: keyof AntigravityJourneyEvidence["checkpoints"], page: Page): Promise<void>;
phase(id: string): Promise<void>;
persistResources(): Promise<void>;
observeRun(run: Row): Promise<void>;
beforeAdmission(): Promise<void>;
assertActive(): void;
}
export async function captureAntigravityAgentDraft(page: Page, resources: AntigravityJourneyResources,
persistResources: () => Promise<void>, submit: () => Promise<void>, expectedCreatorUserId: string): Promise<Row> {
const matches = (url: URL) => /^\/api\/companies\/[^/]+\/agents$/u.test(url.pathname);
let captured: Request | undefined;
let rejectRoute!: (error: unknown) => void;
const routeFailure = new Promise<never>((_resolve, reject) => { rejectRoute = reject; });
const handler = async (route: Route) => {
const request = route.request();
try {
if (request.method() !== "POST") { await route.continue(); return; }
const url = new URL(request.url());
let body: Row;
try { body = request.postDataJSON(); } catch { throw new ConnectionFailure("agent_creation_request_mismatch"); }
if (captured || url.origin !== resources.origin || url.pathname !== `/api/companies/${resources.companyId}/agents`
|| !body || typeof body !== "object" || Array.isArray(body) || body.name !== resources.agentName
|| typeof body.setupId !== "string" || !/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/u.test(body.setupId)
|| typeof expectedCreatorUserId !== "string" || !expectedCreatorUserId)
throw new ConnectionFailure("agent_creation_request_mismatch");
const witness = { setupId: body.setupId, companyId: resources.companyId, agentName: resources.agentName,
provider: "antigravity" as const, creatorUserId: expectedCreatorUserId, origin: resources.origin };
if ((resources.agentId && resources.agentId !== witness.setupId) || (resources.agentCreationRequest
&& Object.entries(witness).some(([key, value]) => resources.agentCreationRequest![key as keyof typeof witness] !== value)))
throw new ConnectionFailure("agent_creation_request_mismatch");
captured = request;
resources.agentCreationRequest = witness;
resources.retained = true;
await persistResources();
// Continue the ordinary UI request unchanged only after its recovery identity is durable.
await route.continue();
} catch (error) {
await route.abort("failed").catch(() => {});
rejectRoute(error);
}
};
let primary: unknown;
await page.route(matches, handler);
try {
const creation = page.waitForResponse(response => response.request() === captured);
const receipt = Promise.race([creation, routeFailure]);
// A submit failure must not leave a later response timeout unhandled.
void receipt.catch(() => {});
await Promise.race([submit(), routeFailure]);
const created = await receipt;
if (!created.ok()) throw new ConnectionFailure("agent_draft_creation_failed");
const draft = await created.json();
if (!draft || typeof draft !== "object" || Array.isArray(draft) || !resources.agentCreationRequest || draft.id !== resources.agentCreationRequest.setupId
|| draft.companyId !== resources.companyId || draft.name !== resources.agentName || draft.createdByUserId !== expectedCreatorUserId)
throw new ConnectionFailure("agent_creation_receipt_mismatch");
return draft;
} catch (error) { primary = error; throw error; }
finally {
try { await page.unroute(matches, handler); }
catch (error) {
if (!primary && !page.isClosed()) throw error;
if (primary instanceof Error) Object.assign(primary, { agentCreationRouteCleanupFailed: true });
}
}
}
export async function runAntigravityJourneyFlow(input: AntigravityJourneyFlowInput) {
const { page, api, config, prepared, resources, evidence } = input;
const { company, connection, environment } = prepared;
const marker = `ANTIGRAVITY-INSTRUCTION-${randomUUID()}`;
const followupMarker = `ANTIGRAVITY-FOLLOWUP-${randomUUID()}`;
const firstBytes = Buffer.from(`${marker}\n`), followupBytes = Buffer.from(`${marker}\n${followupMarker}\n`);
const checkpoint = async (id: keyof AntigravityJourneyEvidence["checkpoints"]) => { input.assertActive(); await input.checkpoint(id, page); };
if (!/^[A-Za-z0-9]+$/.test(company.issuePrefix)) throw new ConnectionFailure("invalid_journey_company_prefix");
const dashboard = `/${company.issuePrefix}/dashboard`;
await input.phase("agent_navigation");
await page.goto(`${api.origin}${dashboard}`);
await page.waitForURL(url => url.origin === api.origin && url.pathname === dashboard);
await page.getByRole("link", { name: "Agents", exact: true }).click();
const newAgent = page.getByRole("toolbar", { name: "Agents controls", exact: true }).getByRole("button", { name: "New Agent", exact: true });
await expect(newAgent).toHaveCount(1);
await newAgent.click();
await input.phase("agent_creation");
const nameDialog = page.getByRole("dialog", { name: "Meet your next agent", exact: true });
await expect(nameDialog.getByRole("button", { name: "Choose adapter", exact: true })).toBeDisabled();
await nameDialog.getByRole("textbox", { name: "Agent name", exact: true }).fill(resources.agentName);
const draft = await captureAntigravityAgentDraft(page, resources, input.persistResources,
() => nameDialog.getByRole("button", { name: "Choose adapter", exact: true }).click(), config.savedConnection.ownerUserId);
resources.agentId = draft.id; evidence.agentId = draft.id; evidence.cleanup.agent = false;
await input.persistResources();
await input.phase("picker_selection");
await selectAntigravityFromOrdinaryPicker(page);
await checkpoint("ordinary_picker");
await page.getByRole("dialog", { name: "Choose an adapter", exact: true }).getByRole("button", { name: "Configure agent", exact: true }).click();
await input.phase("saved_subscription");
const saved = page.getByRole("combobox", { name: "Saved subscription", exact: true });
await expect(saved).toBeVisible({ timeout: 60_000 });
await saved.selectOption(`ai:${connection.grantId}`);
await expect(saved).toHaveValue(`ai:${connection.grantId}`);
await expect(saved.locator("option:checked")).toHaveText(`${connection.name} (Your default)`);
await page.getByRole("button", { name: "Use saved subscription", exact: true }).click();
await expect(page.getByRole("heading", { name: "Configure your agent", exact: true })).toBeVisible({ timeout: 120_000 });
await checkpoint("saved_subscription");
await input.phase("model_selection");
const model = page.getByRole("combobox", { name: "Model", exact: true });
await expect(model).not.toHaveAttribute("aria-busy", "true", { timeout: 60_000 });
// Select a catalog option. A custom model shortcut would miss exact account discovery.
await expect(model.locator(`option[value="${ANTIGRAVITY_JOURNEY_MODEL}"]`)).toHaveCount(1);
await model.selectOption(ANTIGRAVITY_JOURNEY_MODEL);
await expect(model).toHaveValue(ANTIGRAVITY_JOURNEY_MODEL);
const environmentSelect = page.getByRole("combobox", { name: "Environment", exact: true });
const selectedEnvironment = await environmentSelect.inputValue();
// Empty means the instance default; do not silently replace the selected environment.
if (selectedEnvironment && selectedEnvironment !== environment.id) throw new ConnectionFailure("ui_environment_mismatch");
await checkpoint("exact_model");
await input.phase("setup_probe");
const beforeProbe = await api.get<Row[]>(`/api/companies/${company.id}/heartbeat-runs?agentId=${draft.id}&limit=100`);
if (beforeProbe.length) throw new ConnectionFailure("new_agent_already_has_runs");
const probeResponse = page.waitForResponse(response => response.request().method() === "POST"
&& new URL(response.url()).pathname === `/api/companies/${company.id}/adapters/paperclip_runner/test-environment`, { timeout: 120_000 });
resources.setupProbe = "pending";
await input.persistResources();
await page.getByRole("button", { name: "Run test", exact: true }).click();
const probe = await probeResponse, result = await probe.json();
if (!probe.ok() || result.status !== "pass" || !result.checks?.some((check: Row) => check.code === "antigravity_metadata_verified" && check.level === "info")
|| (await api.get<Row[]>(`/api/companies/${company.id}/heartbeat-runs?agentId=${draft.id}&limit=100`)).length)
throw new ConnectionFailure("prompt_free_native_setup_test_failed");
resources.setupProbe = "retired";
await input.persistResources();
await expect(page.getByText("Connection successful", { exact: true })).toBeVisible();
await checkpoint("setup_probe");
await input.phase("readiness");
await page.getByRole("button", { name: "Finish setup", exact: true }).click();
await assertAntigravityReady(page, resources.agentName);
const ready = await api.get<Row>(`/api/agents/${draft.id}`);
if (ready.companyId !== company.id || ready.name !== resources.agentName || ready.status !== "idle" || ready.lifecycleState !== "ready"
|| ready.adapterType !== "paperclip_runner" || ready.adapterConfig?.provider !== "acpx" || ready.adapterConfig?.acpxAgent !== "antigravity"
|| ready.adapterConfig?.model !== ANTIGRAVITY_JOURNEY_MODEL || ready.runtimeConfig?.aiConnection?.mode !== "responsible_user"
|| ready.runtimeConfig.aiConnection.provider !== "google" || ready.runtimeConfig.aiConnection.method !== "subscription")
throw new ConnectionFailure("saved_ready_agent_binding_mismatch");
const effectiveEnvironment = ready.defaultEnvironmentId ?? (await api.get<Row>("/api/instance/settings")).defaultEnvironmentId;
if (effectiveEnvironment && effectiveEnvironment !== environment.id) throw new ConnectionFailure("saved_agent_environment_mismatch");
// Preserve the operator's inherited accounting policy, as in the source journey.
await checkpoint("agent_ready");
await input.phase("first_composer");
await page.getByRole("button", { name: `Assign ${resources.agentName} a Task`, exact: true }).click();
await assertAntigravityCleanComposer(page, resources.agentName, ANTIGRAVITY_JOURNEY_MODEL);
await checkpoint("clean_composer");
await input.phase("close_empty_composer");
await page.keyboard.press("Escape");
await expect(page.getByRole("dialog", { name: "New task", exact: true })).toBeHidden();
await input.phase("agent_navigation");
await openAntigravityAgentFromRoster(page, resources.agentName);
await input.phase("instructions");
await page.getByRole("navigation", { name: `${resources.agentName} navigation`, exact: true })
.getByRole("link", { name: "Instructions", exact: true }).click();
await page.getByRole("group", { name: "Instruction file view", exact: true }).getByRole("button", { name: "edit", exact: true }).click();
const editor = page.locator('[contenteditable="true"]:visible,textarea[aria-label="Instruction file editor"]:visible');
await expect(editor).toHaveCount(1);
const current = await editor.evaluate(element => element instanceof HTMLTextAreaElement ? element.value : (element as HTMLElement).innerText);
if (!current.includes("You are an agent in a Paperclip company.")) throw new ConnectionFailure("default_instructions_missing");
const addition = `\nFor file verification tasks, your configured verification marker is:\n${marker}\n\nWhen a task asks for your configured verification marker, write exactly that marker as the first line of the requested proof file followed by one newline. Read the actual file back and attach it as the task result.`;
// Follow the existing instruction-persistence journey's keyboard path. The
// rich editor distinguishes real interaction from initial normalization.
await editor.click();
await editor.press("ControlOrMeta+End");
for (const line of addition.split("\n")) {
await editor.press("Enter");
if (line) await editor.pressSequentially(line);
}
const save = page.getByRole("button", { name: "Save changes", exact: true });
await expect(save).toBeEnabled();
await save.click();
await expect(save).toBeDisabled({ timeout: 30_000 });
const storedInstructions = await api.get<Row>(`/api/agents/${draft.id}/instructions-bundle/file?path=AGENTS.md&companyId=${company.id}`);
if (!storedInstructions.content?.includes(marker) || !storedInstructions.content.includes(current.trim())) throw new ConnectionFailure("instruction_ui_save_not_durable");
await checkpoint("instructions_saved");
await input.phase("task_creation");
await page.getByRole("button", { name: "Assign Task", exact: true }).click();
await assertAntigravityCleanComposer(page, resources.agentName, ANTIGRAVITY_JOURNEY_MODEL);
const prompt = "Create a proof file from your configured instruction\n\nCreate antigravity-proof.txt containing exactly your configured verification marker as its only line, followed by one newline. Read back the actual file, attach it as the task result, report its byte count, and complete this task. I will follow up to ask you to update this same file.";
if (prompt.includes(marker)) throw new ConnectionFailure("instruction_nonce_leaked_to_task_prompt");
const dialog = page.getByRole("dialog", { name: "New task", exact: true });
await dialog.getByRole("textbox", { name: "editable markdown", exact: true }).fill(prompt);
await input.beforeAdmission();
const issueResponse = page.waitForResponse(response => response.request().method() === "POST" && new URL(response.url()).pathname === `/api/companies/${company.id}/issues`);
await dialog.getByRole("button", { name: "Create task", exact: true }).click();
const response = await issueResponse;
if (response.status() !== 201) throw new ConnectionFailure("task_creation_failed");
const issue = await response.json();
if (issue.companyId !== company.id || issue.assigneeAgentId !== draft.id || typeof issue.id !== "string" || issue.description?.includes(marker)) throw new ConnectionFailure("task_creation_binding_mismatch");
resources.issueId = issue.id; resources.issueIdentifier = issue.identifier;
evidence.cleanup.runs = false;
await input.persistResources();
await expect(dialog).toBeHidden();
// Follow the persistent created-task link, as the walkthrough does.
await openAntigravityCreatedTask(page, issue);
const verifyTurn = async (expectedBytes: Buffer, afterRunIds: readonly string[]) => verifyAntigravityJourneyTurn({ api, companyId: company.id,
agentId: draft.id, issueId: issue.id, connectionId: connection.id, environmentId: environment.id, model: ANTIGRAVITY_JOURNEY_MODEL,
expectedProfileDigest: config.candidate.profileDigest, expectedBytes, afterRunIds, deadlineAt: Date.now() + config.limits.turnTimeoutMs, observeRun: input.observeRun, assertActive: input.assertActive });
await input.phase("first_turn");
const first = await verifyTurn(firstBytes, []);
evidence.turnEvidence.push(first);
await checkpoint("first_run");
await assertAntigravityTaskDone(page);
await assertAntigravityFileActivity(page, first.runId);
await inspectAntigravityArtifact(page, first.artifact.attachmentId, firstBytes);
await checkpoint("first_artifact");
await page.reload();
await assertAntigravityTaskDone(page);
await inspectAntigravityArtifact(page, first.artifact.attachmentId, firstBytes);
await input.phase("followup");
await input.beforeAdmission();
await submitTaskReply(page, `Read your existing antigravity-proof.txt. Preserve its first line exactly and append this second line followed by one newline:\n${followupMarker}\nRead back the actual updated file, attach it as the task result, report its byte count, and complete this task. Do not recreate the original first line from memory or from a task message.`);
const second = await verifyTurn(followupBytes, [first.runId]);
evidence.turnEvidence.push(second);
await checkpoint("followup_run");
await assertAntigravityTaskDone(page);
await assertAntigravityFileActivity(page, second.runId);
await inspectAntigravityArtifact(page, second.artifact.attachmentId, followupBytes);
await checkpoint("followup_artifact");
await page.reload();
await assertAntigravityTaskDone(page);
await inspectAntigravityArtifact(page, second.artifact.attachmentId, followupBytes);
await checkpoint("persisted");
}