Files
PaperClipAI/packages/paperclip-runner/scripts/patch-antigravity-runtime.tool-lifecycle.test.py
T
DottaandClaude Fable 5.2 78e4f4f130 feat(runner): Antigravity on ACP 1.5.2 with Linux, API-key auth and Gemini 4 Neon (still pending) (#22591)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The native Runner starts each agent harness and owns its lifecycle,
credentials and recovery
> - Google Antigravity is Google's only first-party coding harness, and
it is the harness for Gemini 4 Neon
> - The Runner had an Antigravity integration, but only as a pending
candidate: ACP server 1.4.3, macOS ARM64 only, Google sign-in only,
closed unless an operator opened it for one company and one model
> - Cloud sandboxes run Linux and use API keys, so the candidate could
not run there, and it had one attended test cell
> - This pull request moves the integration to ACP server 1.5.2, makes
it run on Linux and with a Gemini API key, adds the tests the other ACPX
harnesses have, and removes the code paths that would block recovery
after release
> - The benefit is that the release of Antigravity becomes a small
declaration change after the live suites pass. The profile stays
`pending` in this pull request.

## Linked Issues or Issue Description

Refs #98
Refs #6559
Refs #8523
Refs #21121 (a separate legacy-style `agy_local` adapter that uses the
CLI print protocol; this pull request does not replace or include it)

## What Changed

**Runtime**
- Pin Antigravity ACP server 1.5.2 (was 1.4.3). Owned admission patch is
`1.5.2-paperclip.2`.
- Verified patched closures for `darwin-arm64`, `linux-x64` and
`linux-arm64`. `darwin-x64` stays inventory-only.
- The patcher reads Mach-O and ELF builds. It signs macOS output only.
One admission source serves all platforms.
- Platform gates in TypeScript, Rust, the sidecar schema and the server
admit each host that has a verified closure.

**Auth and models**
- Gemini API-key auth reaches an exact-model session receipt. Admission
accepts a model only when the base model and the thinking level both
match the requested ID.
- API-key connections get a model list on local and cloud environments.
The list is generated at build time from the pinned runtime. The server
starts no process to read it.
- Gemini 4 Neon, Carbon, Argon and Hydrogen are selectable. The picker
marks them "needs a paid Gemini API plan" for API-key connections.
- One shared module maps model ID to family and thinking level.
- `google/gemini-4-neon` is added to the OpenCode model list. A new
model audit is in `doc/adapter-model-audit-2026-11-22.md`.

**Lifecycle and failures**
- A provider error no longer completes the turn. The driver classifies
it: overloaded, rate limit, quota, auth rejected, model unavailable.
- Overload retries are bounded (3 attempts, about 14 seconds).
- A refused session reload maps to incompatible saved state, so the
automatic replacement conversation applies.
- Server gates that refused restart recovery, remote targets and shared
state for Antigravity now apply only while the profile is pending.
- A Google sign-in connection with a cloud environment is refused at
save and at Test, with a plain message.
- A released profile rejects candidate grants in TypeScript and in Rust.

**Launch cost and integrity (all native ACPX providers)**
- Each closure is verified one time into a sealed read-only store. Later
launches check file identities and hash the exact executable they start.
- Remote provider-pack verification is recorded per sandbox lease. Later
runs check kernel identity and fall back to the full hash on any
difference.
- Superseded stores are removed in the background after a launch.

**Provider pack and image**
- The provider pack carries Antigravity for `linux-x64` as a candidate
provider. It becomes an ordinary provider from the profile status alone.
- The Daytona image build accepts the candidate. A credential-free smoke
runs in the build.

**Tests and CI**
- New `antigravity-qualification` suite: 24 cells, local and Daytona.
- New model lineup suites: 14 API-key cells and 14 Gemini 4 cells. Each
cell requires the exact model in the Runner receipt.
- Antigravity can run the `chat-features` cases with `--profile
runner-acpx-antigravity`.
- `runner-full-stack-e2e.yml` passes `GEMINI_API_KEY` for the new
profile and derives candidate providers from the selected Daytona cells.

**Docs**
- `doc/plans/2026-11-22-antigravity-qualification.md` is the current
release contract, acceptance ledger and operator recipe.

## Verification

Commands that passed on the final revision:

- `pnpm build`
- Typecheck for all packages, including the runner-e2e test projects
- `pnpm test:e2e:runner:unit`: 11,665 Vitest tests passed, 25 skipped;
386 node tests passed
- `cargo test -p paperclip-runner-core -- --test-threads=4`: 1,199
passed, 2 failed. The 2 failures are Codex transport timing tests that
pass alone and on `master`.
- `cargo fmt --check`, `check:acpx-profiles`, `check:protocol-types`,
`node scripts/check-maps.mjs`
- Native patch tests: 9 of 9 on `darwin-arm64` and 9 of 9 on `linux-x64`
- UI picker tests: 397 of 397

Known failures that also fail on `master`:

- 11 runner package script tests (browser, Pi and package-boundary
checks)
- 6 `runtime-selection` tests that read an untracked local skill file

Live evidence, without a prompt:

- Clean provisioning on `darwin-arm64` and on `linux-x64` in a Daytona
sandbox. The closure digests reproduce. A changed or missing file is
rejected.
- `initialize` reports 1.5.2. An API-key session returns a receipt for
exactly `gemini-3.8-flash-low` and the exact instruction bytes, on both
platforms.
- All 28 model IDs (14 Gemini 3, 14 Gemini 4) return an exact receipt
under an API key.
- A session survives a process kill and resumes in a new process with
exact receipts, on both platforms.
- The server's remote path verifies the provider pack in a Daytona
sandbox.
- Run start to native `initialize`: 3.45 s to 1.46 s on macOS, 3.65 s to
1.74 s on Linux x64, before the per-launch executable hash was restored
(about 60 ms on macOS; not measured on Linux).
- Remote pack verification on a reused sandbox lease: about 4.3 s to
about 0.25 s.

Live evidence, with a prompt, on an already-released harness:

- Pi native, `pi-native.runner-acpx-pi.local.agent-files-fresh-run`, on
`darwin-arm64` at `427e9b088b`: 1 of 1 passed, 14 of 14 checks, both
native runs succeeded (25.5 s and 25.7 s). The process started from the
new launch store with no fallback warning.
- The same cell and `native-pending-controller-restart` failed in the
paid workflow on this branch and on `master` in the same way, before any
native start. The workflow does not install the Pi runtime for local
cells, so the agent setup check fails. That is a workflow gap, not part
of this change.

**Not run.** No Antigravity prompt completed on 1.5.2 on any platform.
The only Gemini key available is on the free tier, and Google returned
503 or 429 for each attempt on two days. These gates are open:

- All 24 `antigravity-qualification` cells
- Both model lineup suites, including inference on Gemini 4 Neon
- The attended Google sign-in journey on 1.5.2
- The chat cases under Antigravity
- Image pull time and startup time on a published image
- A native start on `linux-arm64`
- A live provider-death cell for Kimi, Pi or Copilot on the new launch
store (one ordinary Pi cell passed live; see above)

## Risks

- **The launch store changes how every native ACPX provider starts**
(Kimi, Copilot, Cursor, Pi), not only Antigravity. A review found two
defects in the first version (an executable swap was possible, and Pi
launches broke). Both are fixed with tests. One live Pi cell passed on
this branch on macOS. No live provider-death cell and no Linux cell ran
for those providers.
- The profile digest changes. Saved Antigravity candidate sessions and
existing candidate grants stop working. The new release refuses old
state by name and starts a replacement conversation.
- The Linux provider pack and the Daytona image grow by about 834 MB
(about 274 MB compressed) when Antigravity is included.
- The pack verification record is in server memory. The first run after
a server restart pays the full hash again.
- Antigravity 1.5.2 reads the workspace `GEMINI.md` and `AGENTS.md` as
user rules. This is deliberate and matches Codex. Any other rule file is
refused.
- Orchestrator mode is not available. ACP server 1.5.2 does not expose
it.
- Antigravity stays `pending`. Normal users cannot run it until a later
change removes the pending status.

## Model Used

- Claude Fable 5.2 (`claude-fable-5-2`) planned, briefed and integrated
the work, with tool use.
- Claude Opus 5.5 (`claude-opus-5-5`) subagents wrote the code and ran
the tests, with tool use and code execution.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [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

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-23 08:21:11 -06:00

165 lines
8.7 KiB
Python

"""Credential-free regressions executed in the real pinned hermetic SDK."""
def _paperclip_tool_lifecycle_regressions():
import asyncio
import contextlib
import json
import socket
import subprocess
import sys
from pathlib import Path
from types import SimpleNamespace
from unittest import mock
from acp import schema
from google.antigravity import types as sdk_types
from google.antigravity.connections.local.event_processor import LocalHarnessEventProcessor
from google.antigravity.proto import localharness_pb2 as pb
from google.antigravity.tools.tool_context import ToolContext
from google.antigravity.tools.tool_runner import ToolRunner
from google3.cloud.developer_experience.antigravity_extensions.acp_server import tools
from google3.cloud.developer_experience.antigravity_extensions.acp_server.server import AgyAdapter, SessionInfo
sid = "offline-tool-lifecycle"
workspace = Path(os.environ["HOME"]) / "tool-workspace"
workspace.mkdir(parents=True)
class FileClient:
def __init__(self):
self.updates = []
self.blocked = asyncio.Event()
self.release = asyncio.Event()
async def session_update(self, session_id, update):
assert session_id == sid
self.updates.append(update)
async def write_text_file(self, session_id, path, content):
assert session_id == sid
Path(path).write_bytes(content.encode("utf-8"))
async def read_text_file(self, session_id, path, line=None, limit=None):
assert session_id == sid
if Path(path).name == "blocked.txt":
self.blocked.set()
await self.release.wait()
return schema.ReadTextFileResponse(content=Path(path).read_bytes().decode("utf-8"))
class Adapter(AgyAdapter):
# 1.5.2 observes usage through the live agent, which this fixture omits.
async def _observe_usage(self, session_id):
pass
def forbidden(*args, **kwargs):
raise AssertionError("offline lifecycle regression reached network or process launch")
async def run():
client = FileClient()
adapter = Adapter()
adapter._client = client
info = SessionInfo(agent=SimpleNamespace(), stack=contextlib.AsyncExitStack(), cwd=str(workspace), current_model_id="offline")
adapter._sessions[sid] = info
runner = ToolRunner(tools=[tools.make_client_view_file(client, [str(workspace)]), tools.make_client_create_file(client, [str(workspace)]), tools.make_client_edit_file(client, [str(workspace)])])
runner.set_context(ToolContext(SimpleNamespace(conversation_id=sid)))
wire = []
async def send(event):
assert event.HasField("tool_response")
wire.append(event.tool_response)
processor = LocalHarnessEventProcessor(send_input_event_fn=send, tool_runner=runner)
opened = {}
async def drain():
steps = []
while not processor.step_queue.empty():
step = processor.step_queue.get_nowait()
steps.append(step)
await adapter._stream_live_step(sid, step, opened)
return steps
async def call(name, call_id, args, permission_frame=None):
if permission_frame:
info.pending_permission_frames[name] = [permission_frame]
await processor.handle_tool_call(pb.ToolCall(id=call_id, name=name, trajectory_id=sid, arguments_json=json.dumps(args)))
steps = await drain()
assert len(steps) == 2, "actual client ToolResult must yield an ACTIVE and terminal step"
assert [s.tool_calls[0].id for s in steps] == [call_id, call_id]
assert all(s.id == call_id and s.tool_calls[0].step_id is None for s in steps), "preserve the callback protocol's real identity without inventing a step id"
assert wire[-1].id == call_id
frame = permission_frame or call_id
terminals = [u for u in client.updates if u.tool_call_id == frame and u.status in ("completed", "failed")]
assert len(terminals) == 1
assert frame not in opened
return steps[-1], terminals[0], wire[-1]
proof = workspace / "proof.txt"
exact = " exact café 🧷\n"
terminal, update, response = await call("client_create_file", "create-call", {"target_file": str(proof), "code_content": exact}, "create-permission")
assert terminal.status == sdk_types.StepStatus.DONE and terminal.content == ""
assert update.status == "completed" and update.raw_output == ""
assert proof.read_bytes() == exact.encode("utf-8")
assert json.loads(response.response_json) == {"result": None}
terminal, update, response = await call("client_view_file", "read-call", {"absolute_path": str(proof)})
# 1.5.2 returns numbered lines under a header; the same native result must
# reach the step, the ACP update and the harness response unchanged.
assert exact.strip() in terminal.content
assert update.raw_output == terminal.content
assert json.loads(response.response_json) == {"result": terminal.content}
edited = "replacement\n"
await call("client_edit_file", "edit-call", {"target_file": str(proof), "code_content": edited})
assert proof.read_bytes() == edited.encode("utf-8")
failed_path = workspace / "missing-parent" / "failed-write.txt"
terminal, update, response = await call("client_create_file", "failed-write-call", {"target_file": str(failed_path), "code_content": "must not exist"})
assert terminal.status == sdk_types.StepStatus.ERROR and update.status == "failed"
assert update.raw_output == terminal.error == response.error_message
assert not failed_path.exists()
# A real pending callback overlaps a different callback's actual failure.
(workspace / "blocked.txt").write_bytes(b"still independent\n")
pending = asyncio.create_task(processor.handle_tool_call(pb.ToolCall(id="pending-call", name="client_view_file", trajectory_id=sid, arguments_json=json.dumps({"absolute_path": str(workspace / "blocked.txt")}))))
await client.blocked.wait()
await drain()
assert "pending-call" in opened
terminal, update, response = await call("client_view_file", "missing-call", {"absolute_path": str(workspace / "missing.txt")}, "missing-permission")
assert terminal.status == sdk_types.StepStatus.ERROR and terminal.error
assert update.status == "failed" and update.raw_output == terminal.error
assert response.error_message == terminal.error
assert "pending-call" in opened, "a genuine callback failure must not fail its concurrent sibling"
assert not [u for u in client.updates if u.tool_call_id == "pending-call" and u.status == "failed"]
client.release.set()
await pending
await drain()
assert "pending-call" not in opened
assert "still independent" in [u for u in client.updates if u.tool_call_id == "pending-call" and u.status == "completed"][0].raw_output
# Native errors close only the failing call, including permission identity.
def native_step(call_id, status, error="", calls=True):
return sdk_types.Step(id="native-step", trajectory_id=sid, type=sdk_types.StepType.TOOL_CALL, status=status, error=error, tool_calls=[sdk_types.ToolCall(id=call_id, step_id="native-step", name="native_tool")] if calls else [])
info.pending_permission_frames["native_tool"] = ["native-permission"]
await adapter._stream_live_step(sid, native_step("native-execution", sdk_types.StepStatus.ACTIVE), opened)
opened["unrelated"] = "native_other_tool"
await adapter._stream_live_step(sid, native_step("native-execution", sdk_types.StepStatus.ERROR, "exact native failure"), opened)
assert "native-permission" not in opened and "unrelated" in opened
failures = [u for u in client.updates if u.status == "failed"]
assert {u.tool_call_id for u in failures} == {"failed-write-call", "missing-permission", "native-permission"}
assert failures[-1].raw_output == "exact native failure"
before = len(client.updates)
await adapter._stream_live_step(sid, native_step("unattributed", sdk_types.StepStatus.ERROR, "turn-only error", calls=False), opened)
assert len(client.updates) == before and "unrelated" in opened, "an unattributed error has no authority to fail an unrelated tool"
# The existing failed-turn cleanup still settles unresolved work, without
# copying an unrelated step's error or fabricating completed callbacks.
await adapter._close_open_tool_calls(sid, set(opened), "failed")
assert client.updates[-1].tool_call_id == "unrelated" and client.updates[-1].status == "failed"
assert client.updates[-1].raw_output is None
with contextlib.ExitStack() as stack:
for owner, name in ((socket, "create_connection"), (subprocess, "Popen"), (asyncio, "create_subprocess_exec")):
stack.enter_context(mock.patch.object(owner, name, side_effect=forbidden))
asyncio.run(run())
sys.stderr.write("paperclip-tool-lifecycle-regressions: passed\n")
_paperclip_tool_lifecycle_regressions()