mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-16 03:31:44 +01:00
21bf7ebcee4f9bd898cfafee3baabfff93aefa17
2537
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
21bf7ebcee |
feat(connectors): connect Tailscale networks to SSH environments (#20617)
## Thinking Path > - Paperclip manages work for AI agents. > - SSH environments run tasks on computers that users own. > - A Paperclip server needs network access before it can reach a private computer. > - A reusable Tailscale connection belongs in Connectors. > - Connected machines should become choices in the existing SSH environment form. > - This change connects a tailnet and resolves selected machines through a private network client. > - Agents retain their choice of harness and AI account. ## Linked Issues or Issue Description **Subsystem affected** Connectors, environment settings, SSH execution, company secret storage, and runtime packaging. **Problem or motivation** Entering a Tailscale address in the SSH form does not connect the Paperclip server to that tailnet. Requiring a separate device key for every environment also duplicates network setup. **Proposed solution** Add a Tailscale Connector with **Connect Tailscale Network**. Use brokered OAuth consent to enroll one private network client per connection. Let SSH environments select a connected network and stable machine identity. Preserve the enrolled node state through the company vault so a restart does not reuse the one-time token. **Alternatives considered** A separate Tailscale environment type would duplicate SSH behavior and mix network access with harness selection. This change uses the existing `ssh` driver. Related #15648 adds OAuth client credentials and a health check; this change uses user consent and supplies outbound task execution. Related #11743 concerns HTTPS brokering. **Roadmap alignment** This extends the existing Connected Apps, environment, and Personal & Shared AI Accounts capabilities. This PR is stacked on #21248, which provides SSH account selection independently of Tailscale. The hosted OAuth broker is a companion control-plane change. ## What Changed - Preserve Cloud reauthentication in the current browser tab. Explain canceled or failed consent in the connector and offer a retry of the same authorized saved connection. - Record Cloud enrollment starts initiated through the Tailscale connector in the company activity log. - Check install-preparation descendant liveness through the kernel process table in the Runner support test. Keep the direct child’s strict reaping assertion and reject any non-zombie descendant. - Align the application image stage contract with the Tailscale client stage after the upstream Runner-image refactor. Keep the exact stage list and check every application stage, including `tailscale-client`, for prohibited Runner compiler commands. - Group Tailscale consent, discovery, daemon lifecycle, pairing, and deletion under `server/src/services/connectors/tailscale/`, with their service tests. Update existing route, runtime, environment, vault, and company-deletion imports. Keep the existing contracts, authorization, audit, and transaction owners. - Handle early stdin closure in the Kubernetes real-shell test helper. Stop the input stream on `EPIPE`, preserve nonzero child exits, and reject a zero exit when input was lost. Add two real-process regression cases. Production transfer code and confinement checks are unchanged. - Read configured Tailscale executable paths when a client starts, after supported `.env` loading. Keep explicit command overrides available. - Discard pending pairing results after switching to Direct SSH or closing the form. Retain the existing company, connection, machine, and port checks. - Store network credentials with an immutable server-owned purpose from their first vault row. Exclude them from generic catalogs, bindings, environment projection, and value reads. Use a dedicated audited server consumer for pinned connector reads. Block unclassified legacy serialized node state at the same value boundary. Keep SSH private-key binding separate from connector credentials. - Gate network queries and setup on verified local-implicit or instance-admin access. Hide Tailscale catalog rows for other members, show an admin requirement on direct setup navigation, and avoid device discovery before management access is known. - Keep failed-client cleanup in the network manager. A failed request cannot disconnect a newer retry for the same identity; explicit connector disconnect and enrollment retirement still stop their networks. - Check for readable Ed25519, ECDSA, or RSA host public keys before pairing edits `authorized_keys`. Print a known-hosts entry for every available key, or fail before changing authorized keys if none are available. - Return self-hosted Cloud enrollment to the Tailscale connector. Save the unprefixed setup path and let the shared callback add the verified company prefix. Keep external and unrelated destinations rejected. - Hide pairing instructions after an SSH port change. Ignore late key-selection results for the old port. Operators prepare again for matching known-hosts output. - Retire connector references before deleting a company or its vault credential. Stop company daemons after the database commit. Keep failed secret retirement retryable and prevent late node-state writes from restoring deleted connections. Discard retired state without blocking behind the vault deletion lock. - Reload a mismatched credential before replacing a ready daemon. Recheck the active entry and manager generation after the read. An older request cannot stop a newer healthy socket or cross shutdown. - Pin connector credentials to the exact vault version and SHA-256 digest recorded by trusted enrollment and node-state writes. Ignore generic secret rotations. Advance both fields with a compare-and-set guard. Reject unpinned or tampered credentials before network startup. - Save an explicit Direct SSH selection and clear old Tailscale fields after config merging. Preserve the operator's entered direct host. - Route all Tailscale SSH runtime access through the connection service after SSH-key loading. Pin access to the environment's saved connector identity and recheck after device discovery. Remove standalone key-based daemon startup and reject raw enrollment keys or credential-only network configurations. Align the shared config type and SDK pins. - Correct two E2E assumptions exposed during connector qualification. Keep the two-window chat fixture stale until its own mutation. Validate the original failed run and its permitted write-revocation timestamp in the legacy recovery browser test. - Add the Tailscale Connector page, catalog entry, OAuth return flow, connected-network management, device discovery, and disconnect. Document all six routes in OpenAPI and the API reference, including their instance-admin requirement. - Add company-scoped connection storage in `0480_lazy_lethal_legion`, trusted credential version/digest fields in `0481_round_pet_avengers`, and server-owned secret purpose/backfill in `0482_aberrant_rumiko_fujikawa`. Generate all three migrations through the maintained command and retain the five newest snapshots. - Add machine pairing that generates a fresh SSH key per request, stores its private half in the company vault, and uses the generated public half in the install command. Do not trust editable saved metadata. Preserve existing authorized keys, including a file without a final newline. Keep SSH username, workspace, and trusted host keys explicit. - Use the existing SSH driver. Resolve the machine's current address from its stable device ID. Reject disconnected, removed, offline, and wrong-company selections. - Hide Network when Direct is the only option. Select a sole connected tailnet automatically and hide its selector. Remove the requested setup helper copy. Do not restrict the harness to Claude. - Run a private userspace Tailscale daemon with a separate socket. Persist its node state before execution. Restore it after restart, bound startup, serialize reconnect cleanup, and close it during server shutdown. - Guard OAuth completion with a durable attempt marker. Disconnect and newer authorization invalidate older callbacks. Close replaced daemons and remove cancelled enrollment secrets without changing newer connection state. - Preserve SSH host verification and tailnet-specific session identity. Honor the configured Tailscale executable path, including spaces and OpenSSH percent escaping. - Package checksum-pinned Tailscale clients and their license in the standard runtime image. Exercise the client build stage in PR CI and include it in image smoke checks. ## Verification - Merge status: all CI and image checks pass, and current-head Apex is 5/5 with no unresolved comments. GitHub rejected a direct merge because the active master ruleset requires code-owner approval for `.github/workflows/pr-trusted.yml`. The [CODEOWNERS workflow pattern](https://github.com/paperclipai/paperclip/blob/master/.github/CODEOWNERS#L3) applies; eligible maintainers already have review requests. Auto-merge is enabled with the squash method for the verified head. The PR remains open pending that required approval; no branch policy was bypassed. - Final revision: `fdb29b2cc366f4945b7f4c3e2b2d25070329a21b`, including master `999709b0a6dd416af335b5debded13e1de7fcb7a`. [Final CI verification passed](https://github.com/paperclipai/paperclip/actions/runs/43518584814/job/132213508320). All required checks pass, all applicable test/build gates are green, and the branch is mergeable against master. SSH prerequisite #21248 and Cloud broker paperclipai/paperclip-cloud#1314 are already merged. - [Apex reviewed this exact revision at 5/5](https://github.com/paperclipai/paperclip/pull/20617#issuecomment-6776629437). There are no unresolved review threads. The PR is classified as Critical impact. - Final image qualification passes for the [application Runner path](https://github.com/paperclipai/paperclip/actions/runs/43518584522/job/132206784267), [amd64 Runner image](https://github.com/paperclipai/paperclip/actions/runs/43518584544/job/132207296198), and [arm64 Runner image](https://github.com/paperclipai/paperclip/actions/runs/43518584544/job/132207296156). Typechecks, Runner support, native/Rust tests, provider tests, serialized-server suites, browser shards, and the remaining applicable CI checks pass. This is source/image CI qualification, not a production rollout. - The last master conflict affected only Docker stage declarations and their boundary test. Both the checksum-pinned Tailscale stage and upstream `runner-lockfile` guard are retained, including the upstream `deps` inheritance. The Tailscale client stage is byte-identical. All 180 cases across five Docker/image contract suites pass locally, along with server and UI typechecks. The maintained 543-input SDK check has no drift. Runtime and lock pins are unchanged. Secret/PII and whitespace scans pass. - Seven OAuth regression cases failed before the fixes. The current-tab test uses the real handoff helper, checks that the session is stored before reauthentication navigation, mounts the shared return page, resumes consent, and verifies handoff cleanup. Callback tests check trusted saved-connection context, fixed safe outcomes, failure audit metadata, denied membership and expired-state rejection, JSON API errors, and no provider text in browser returns. UI retries require a connection in the current company's catalog. All 80 OAuth route/service/UI/shared-handoff cases pass; server and UI source/test typechecks pass. - [Server shard 4/12 on the prior refresh](https://github.com/paperclipai/paperclip/actions/runs/43510727031/job/132180301436) passed 2,784 cases and skipped 21, then failed a reassignment fixture's `TRUNCATE companies CASCADE` cleanup with PostgreSQL `40P01`. Its automatic retry found the surviving `REA` prefix. The unchanged test passes all three cases locally. A controlled reader/cleanup overlap reproduces the same deadlock, but the exact competing CI query was not logged. Each case now has a distinct company prefix and identifier; the owned database is removed at suite end. The three test bodies and assertions are byte-identical. Eight local reassignment/lock-release cases pass, and the [final server shard 4/12 passes](https://github.com/paperclipai/paperclip/actions/runs/43518584814/job/132207159392). Production reassignment logic, deadlines, and retries are unchanged. - The initial master integration passed 330 cases across 17 suites. Coverage includes connector state, device discovery, network lifecycle, pairing, routes, SSH binding and exports, environment persistence, and connector UI. All three unpublished migrations were regenerated after master's `0479_short_darkstar`: `0480_lazy_lethal_legion`, `0481_round_pet_avengers`, and `0482_aberrant_rumiko_fujikawa`. Each SQL body is byte-identical to its earlier unpublished migration. Generated snapshots preserve existing master tables and add only the intended Tailscale table and secret-purpose column. Exactly five snapshots remain, 0478–0482. Numbering, safety, compatibility, and snapshot-drift checks pass. The later Docker refresh did not alter this migration sequence. - Earlier attempts remain part of the verification record. On `1c020a0`, Rust cache restoration and server shard 5/12 were interrupted by shutdown signals, Runner shard 2/3 lost communication with no retrievable log, and an amd64 provider download failed with npm `ECONNRESET`. Same-head retries recovered, without establishing the cause of the communication loss. Later superseded runs also had cancellations with incomplete logs. These interrupted attempts are not counted as passes. The final revision has fresh successful CI. - Local platform limits remain recorded. The Kubernetes suite on macOS passed 191 cases, failed 12 Linux `/proc/self/fd` transfer cases, and skipped four Linux-only cases. Unchanged source reproduced the same 12 failures. An initial run also lacked provider dependencies until the maintained preparation command installed them. Those local attempts are not green qualification. Final Linux provider CI passes. Local Docker qualification was unavailable; final image checks passed in CI. - Before PR separation, a live tailnet/SSH Claude Code task completed on Ubuntu ARM64 without provider login for the remote user. The selected Paperclip subscription ran it, wrote the expected file, posted completion, and marked the task done. File contents and private runtime cleanup were checked. This is prior live evidence; the final revision was not live-retested. Other providers have automated coverage only. Hosted registration for unrelated tailnets and production concurrency remain qualification limits below. - The Superagent security and supply-chain reports remain neutral and inconclusive. Earlier attempts to restart the failed security scan returned HTTP 404. Supply-chain intelligence lacked coverage for extracted pinned dependencies and the shared workflow reference. These reports do not establish successful security qualification. The required CI and review gates pass; this external coverage gap remains disclosed. ## Risks - The Superagent security and supply-chain reports are inconclusive. The security scan re-run request returned HTTP 404, and the supply-chain scanner lacks coverage for the extracted dependencies and shared workflow reference. These neutral results are not successful security qualification. - The server-owned secret purpose is internal database metadata, not an HTTP-writable field. The generic secret service owns enforcement so direct API reads and runtime projection share the same restriction. Previously copied node state remains valid outside Paperclip until the enrolled device is revoked in Tailscale; a local disconnect cannot stop an external copy. - Tailscale network configurations now require a connected Connector and selected machine. The unreleased key-only path is removed; any saved configuration from that path needs Connector setup. - The connector remains a pilot. The local test used an OAuth app registered in the consenting user's tailnet. Qualify hosted app registration for unrelated customer tailnets before general availability. - This implementation supports one serving process per instance. Concurrent replicas need exclusive ownership of the persisted network identity before production rollout. Preserve the database and company vault master key across restarts. - Each machine-pairing preparation creates a new vault secret. Unused generated keys follow the existing secret deletion lifecycle. A saved SSH key remains available as an explicit choice. - Apply additive migrations `0480_lazy_lethal_legion`, `0481_round_pet_avengers`, and `0482_aberrant_rumiko_fujikawa` before application rollout. The new credential version and digest columns are nullable. Existing unpinned connections require fresh OAuth consent; the migration deliberately does not trust or backfill a generic secret value. Regenerate or renumber migrations if master advances the sequence before merge. - The target needs an SSH server, its chosen harness, and allowed tailnet access. A reachable network does not grant SSH or provider authorization. Pairing reads standard `/etc/ssh` host-public-key files; custom host-key locations require manual known-hosts configuration. - Roll back the application revision to remove new entry points. Existing connection secrets and registered Tailscale nodes retain their separate lifecycle. Do not drop the table or delete node state as part of an application rollback. - Production qualification still needs denied-policy, revocation, cancellation, and deployment-overlap checks. Local Docker and a production deployment were not performed. ## Model Used OpenAI Codex, gpt-6.1-sol, xhigh reasoning, with local code execution and tool use. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used - [x] I have checked ROADMAP.md and this extends existing connector and environment features - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have described the issue in-PR using the feature request fields - [x] I have not referenced internal issues, local URLs, or private machine identifiers - [x] My branch name describes the change - [x] I have run focused tests locally and they pass - [x] I have added tests for new behavior and failure paths - [x] I have updated documentation - [x] I have documented migration and runtime risks - [x] All Paperclip CI gates are green - [ ] Required code-owner approval received for the workflow change - [x] Greptile Apex is 5/5 on the final head with no unresolved comments - [x] I will address CI and review findings before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing> |
||
|
|
1d112a504f |
feat(acpx): convert raw Claude session updates the way ACPX does (#21420)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Paperclip Runner runs Claude Code through the ACPX sidecar. > - Claude can start a shell command in the background and end its turn. When the command finishes, Claude Code starts a cycle of its own to continue. Today the Runner stops Claude at the end of the turn, so the command stops and the run fails with `native_finalization_missing`. > - A stack of pull requests lets the Runner accept that cycle as a new turn of the same run, when a controller asks for it. > - The Runner sees each raw ACP message before ACPX does. A cycle that Claude starts by itself is not a part of an ACPX prompt, so ACPX gives no events for it. > - To show that cycle in the same form as a normal turn, the Runner must convert the raw messages itself. ACPX 0.22 does not export its converter. > - This pull request adds a copy of that converter with a test that compares it with ACPX. Nothing uses it yet. > - The benefit is that a later pull request can show the cycle of Claude with the same events as a normal turn. ## Linked Issues or Issue Description No public issue exists. The issue is described here. This pull request is one part of a change that was first opened as one large pull request (#21316). The parts, in stack order after #21311: 1. #21419: sidecar preparation (a refactor). 2. #21420: converter for raw ACP session updates. 3. #21421: cycle stream at the adapter. 4. #21422: contract for provider-started turns. 5. #21423: `paperclip-runnerd` waits for a provider-started turn. 6. #21316: the sidecar adopts a cycle. This is part 2. Its base branch is `refactor/acpx-sidecar-runtime-event-step`. After each part, a production run does the same as today, because no controller sends the opt-in. Refs #19912 (design). **What existing behavior does this improve?** Nothing yet. It adds a module that a later part uses. **Subsystem affected** Paperclip Runner: `src/drivers/acpx`. One new direct dependency in the Runner and the server. **Current behavior** - ACPX converts `session/update` messages to runtime events inside a prompt. The function is private. - The Runner has no way to make the same events from a raw message. **Proposed behavior** - `acp-session-update-event.ts` converts a raw `session/update` to the event that ACPX 0.22 makes for the same update. - It validates the message with `@agentclientprotocol/sdk` 1.9.0. This is the version that ACPX 0.22 already installs. - No production code imports the module in this pull request. **Reason and benefit** A copy with a comparison test is a smaller risk than a patch of ACPX. The test fails when the two differ. ## What Changed - `src/drivers/acpx/acp-session-update-event.ts` (new, 367 lines). - `acp-session-update-event.test.ts` and `acpx-runtime-adapter.claude-session-update-events.test.ts` (new, 363 lines). - `packages/paperclip-runner/package.json` and `server/package.json`: `@agentclientprotocol/sdk` 1.9.0 as a direct dependency. The server needs the line because it copies the Runner build with no `node_modules`. - `pnpm-lock.yaml` is not in this pull request. The lockfile workflow owns it. ## Verification At the head of this branch, from `packages/paperclip-runner`: - `npx tsc --noEmit -p tsconfig.json`, `npx tsc --noEmit -p tsconfig.test.json`, `pnpm run typecheck:typescript`, `pnpm run build:typescript`, `node --test test/acpx-sidecar-contract.test.mjs test/protocol-contract.test.mjs`, the server check `node scripts/verify-runner-vendor-dependencies.mjs`, `node --test scripts/__tests__/runner-release-crate-cache.test.mjs`, `cargo fmt --check` and `cargo build -p paperclip-runner-core --bins` (no new warning): all passed. - The two new test files and the sidecar suite: 130 passed. - The comparison test runs the real ACPX runtime with the pinned `claude-agent-acp` and a local fake Anthropic API, and gives the same raw updates to the copy. The events are the same. - A second test fails if the SDK version of the Runner is not the version that ACPX resolves. With 1.4.0 in `package.json` it fails. Not run: the full suite. CI supplies that coverage. ## Risks - **A new direct dependency.** It is already installed through ACPX, so no new package is downloaded. The version test keeps the two the same. - **The converter is a copy of ACPX code.** An ACPX upgrade must run the comparison test. - **The module is not used yet.** It is used in part 3. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Claude Fable 5.2 (`claude-fable-5-2`) in Claude Code planned the change and the split, reviewed the diff, and ran a part of the verification again. - Claude Opus 5.5 (`claude-opus-5-5`), as a Claude Code subagent with tool use (shell, file edits, local test runs), wrote the change and the tests and cut this slice from the full change. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
055a0a3c54 |
refactor(acpx-sidecar): extract the runtime event step and the test process helper (#21419)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Paperclip Runner runs Claude Code through the ACPX sidecar. > - Claude can start a shell command in the background and end its turn. When the command finishes, Claude Code starts a cycle of its own to continue. Today the Runner stops Claude at the end of the turn, so the command stops and the run fails with `native_finalization_missing`. > - A stack of pull requests lets the Runner accept that cycle as a new turn of the same run, when a controller asks for it. > - The last part of that stack adds a second kind of turn to the sidecar. It needs two pieces of the code of a normal turn. > - This pull request moves those two pieces into functions, and moves a test helper to a file of its own. It changes no behavior. > - The benefit is that the later pull request shows only new behavior, not moved code. ## Linked Issues or Issue Description No public issue exists. The issue is described here. This pull request is one part of a change that was first opened as one large pull request (#21316). The parts, in stack order after #21311: 1. #21419: sidecar preparation (a refactor). 2. #21420: converter for raw ACP session updates. 3. #21421: cycle stream at the adapter. 4. #21422: contract for provider-started turns. 5. #21423: `paperclip-runnerd` waits for a provider-started turn. 6. #21316: the sidecar adopts a cycle. This is part 1. Its base branch is `refactor/remove-direct-gateway-path`. After each part, a production run does the same as today, because no controller sends the opt-in. Refs #19912 (design). **What existing behavior does this improve?** Nothing for a user. The structure of the ACPX sidecar code. **Subsystem affected** Paperclip Runner: `src/cli/acpx-runtime-sidecar.ts` and its test. **Current behavior** - `pumpTurn` has the code that prepares each runtime event for the Runner, and the code that sends the terminal frame of a turn, inline. - The sidecar test file has the `SidecarProcess` helper that starts a sidecar process. **Proposed behavior** - `createRuntimeEventStep` has the event code. `emitTurnTerminal` has the terminal code. `pumpTurn` calls both. - `src/test-support/acpx-sidecar-process.ts` has the helper, so a second test file can use it. - No protocol, event or timing change. **Reason and benefit** A later pull request adds a turn that Claude starts by itself. It uses the same two functions, and its tests use the same helper. ## What Changed - `src/cli/acpx-runtime-sidecar.ts`: 74 lines added and 56 removed. The code moved with its comments, with no change. - `src/cli/acpx-runtime-sidecar.test.ts` and `src/test-support/acpx-sidecar-process.ts`: the helper moved, 138 lines added and 132 removed. ## Verification At the head of this branch, from `packages/paperclip-runner`: - `npx tsc --noEmit -p tsconfig.json`, `npx tsc --noEmit -p tsconfig.test.json`, `pnpm run typecheck:typescript`, `pnpm run build:typescript`, `node --test test/acpx-sidecar-contract.test.mjs test/protocol-contract.test.mjs`, the server check `node scripts/verify-runner-vendor-dependencies.mjs`, `node --test scripts/__tests__/runner-release-crate-cache.test.mjs`, `cargo fmt --check` and `cargo build -p paperclip-runner-core --bins` (no new warning): all passed. - `npx vitest run src/cli/acpx-runtime-sidecar.test.ts`: 125 passed. The tests are the same as before, apart from the import of the helper. Not run: the full suite. CI supplies that coverage. ## Risks - **A refactor of the turn loop of each ACPX agent.** The moved code runs for Claude, Codex, Pi, Kimi, Cursor, Copilot and Grok. The existing sidecar suite covers it. No new test is necessary, because no behavior changes. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Claude Fable 5.2 (`claude-fable-5-2`) in Claude Code planned the change and the split, reviewed the diff, and ran a part of the verification again. - Claude Opus 5.5 (`claude-opus-5-5`), as a Claude Code subagent with tool use (shell, file edits, local test runs), wrote the change and the tests and cut this slice from the full change. ## 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 Opus 5.5 <noreply@anthropic.com> |
||
|
|
0ead74b4f3 |
feat(slack): show useful progress without extra messages (#20827)
## Thinking Path > - Paperclip helps people manage AI agents and their work. > - Chat connectors show agent work in the source conversation. > - Slack progress uses a small set of general status messages. > - Native runtimes already mark some completed assistant notes as public progress. > - The server can select those notes and control their size and rate. > - This pull request keeps one progress message and sends the final answer as a new reply. > - Users can follow useful changes without reading each tool event. ## Linked Issues or Issue Description **What existing behavior does this improve?** Automatic progress updates in Slack task threads. **Current behavior** Users see general messages such as “Maya is making progress”. The first answer can replace that message. A source update that arrives during the progress delay can be lost if no later event arrives. **Proposed behavior** Show the latest short public note in one message. Wait 10 seconds before the first update and at least 30 seconds between updates. Recover pending work after a restart. Send the final answer as a fresh reply. **Reason and benefit** Users can see what the agent checks and what it found. The thread stays short. The model needs no new tool call or summary model. Related change: [resolved-card chat bindings](https://github.com/paperclipai/paperclip/pull/20825). This branch includes that master revision. The progress change uses the existing source authority checks. ## What Changed - Select completed `agentMessage` items from the normalized PRP `progress` channel. Keep unknown channels, reasoning, tool output, and raw provider fields out of progress text. - Sanitize each note. Keep at most two sentences and 400 characters. Add a task link when a public board URL is available. - Prefer public notes over general tool status. Remove repeated text and combine bursts into the latest pending note. - Use run events and the publication outbox as saved state. Use the shared deadline worker for the grace period and update delay. A delivery receipt wakes the worker when an earlier update is still in flight. Settled history does not poll. - Apply the run's registered-secret filter before text selection or storage. Reuse the latest usable note within a sweep. Invalidate the cache when the source event or secret registry changes. - Reuse the exact source-bound Slack fast-response receipt when it replaced the working placeholder. Check its current outbound message link before editing it. - Send Slack answers as new replies. After delivery, queue a separate cleanup edit for a generic working message. Keep its current outbound link as the edit authority. Leave useful public notes in place. Cancel pending public progress when an answer, question, or terminal run takes over. Keep the existing delivery policy for other connectors. - Add one short Slack prompt instruction. Update product documentation and regression tests. The Slack module owns public-note selection, cadence, lane eligibility, and cleanup. The shared progress service holds its existing issue and run locks and calls a narrow provider policy. The secret registry supplies redaction and a version token for the per-sweep note cache. The existing outbox owns delivery, retries, and authority checks. The Slack module owns receipt reuse. Shared delivery changes supply the receipt wake and select the Slack reply policy. No schema or configuration change is required. ## Verification - The initial content-selection regression failed before the implementation and passed after it. - The follow-up reproduced two review defects before the fixes. A registered synthetic secret appeared in saved progress. A generic working message stayed active after the answer. Both regressions now pass. - The final content, database-worker, query, protocol-boundary, and redaction selection passes 78 tests across four files. - The earlier affected transport selection passes all 65 cases. It covers public progress, native cadence, separate answers, Slack and Telegram retry isolation, FIFO restart, and cleanup ownership. Its first run passed 64 cases and found one old assertion that rejected the intended cleanup edit. The corrected assertion checks the exact successor message ID. - Full server typecheck passes: `PAPERCLIP_TYPECHECK_LOW_MEMORY=1 pnpm --filter @paperclipai/server typecheck`. An earlier attempt found two transaction type errors. The helper contracts now accept their actual database operations. The final run passes all source and test layers. - The broad Slack selection stopped after 189 passing cases when the sandbox killed its worker with SIGKILL. That attempt is not a pass. The focused transport run above supplies affected local coverage. Required CI must supply broad coverage on the final head. - `pnpm verify --explain` returns exit 2 because the product documentation change requires broad CI coverage. No full local suite was started. - Preflight installed dependencies and built the SDK. Cargo is absent, so local Rust checks could not run. No Rust source changed. - [CI on `02552bb584`](https://github.com/paperclipai/paperclip/actions/runs/43493597242) passed build, typecheck, policy, all browser shards, Runner/Rust checks, and the other test lanes. One chat shard failed in three Slack cases. Each expected one edit after an answer was already sent. The intended cleanup adds a “Response sent.” edit before the later failure notice. All three failures reproduced locally. The test assertions now check both exact edit texts and the original run's message ID. They also check that another sweep adds no edits. - The latest local run passes all 85 selected transport cases. It includes all 18 Slack/Telegram answer and failure orders, plus progress, deferred FIFO, retry isolation, and cleanup coverage. Command: `pnpm exec vitest run server/src/__tests__/chat-channels.integration.test.ts -t 'preserves selected answer and failure lanes|public progress|native progress|keeps intermediate.*agent comments|keeps a.*retry.*queue|FIFO'`. - [Final CI](https://github.com/paperclipai/paperclip/actions/runs/43499797545) passed on `55ec4c053fe5263d9033d807777dbf2e679407e3`. All 52 executed jobs passed. This includes build, typecheck, general tests, serialized tests, all eight browser shards, Runner/Rust checks, and the required aggregates. The affected chat shard now passes. The test-file selection job was skipped because this run used full coverage. - [Greptile](https://github.com/paperclipai/paperclip/runs/132142301124) completed on the same head with 5/5 and no new findings. All four inline review threads are resolved. The review job and Socket checks passed. Of 61 check runs, 57 succeeded, three were skipped, and one was neutral. No checks remain pending or failed. The PR is mergeable with a clean state. - [Superagent Security Scan](https://github.com/paperclipai/paperclip/runs/132142345827) returned a neutral result with “PR scan workflow failed”. It supplied no security verdict. Do not count it as a successful scan. - Live Slack notification and unread behavior has not been tested. Service tests use real PostgreSQL and a fake provider runtime. ## Risks - Only runtimes that map commentary to the explicit public `progress` channel supply contextual prose. Other runtimes retain general status messages. - Slack final answers now create a fresh reply. This is an intended delivery change. - Public commentary must suit the current conversation audience. Text sanitization adds protection; it does not authorize sharing unrelated private material. - Source events and outbox rows supply recovery state. No new timer table or recurring idle scan is added. - The existing large integration suite retains its provider fixtures and lifecycle assertions. No source file crosses the 1,000-line threshold in this change. ## Model Used OpenAI Codex, GPT-6 family, with reasoning and code tools. The exact deployment ID was not supplied. ## 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> |
||
|
|
5df1ada9c1 |
feat(plugins): send configured environment on plugin task resume (#21352)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - #21335 lets a plugin task provider that restarts the Runner on `resume` opt in (`resumeCredentialVersion: 1`) to receive the claimant run's harness credential > - A provider restarting the Runner also needs the agent's configured environment, which Core sends on `resume` only during a session handoff > - Without it, a Runner a provider moves to a new computer starts without the agent's configured environment variables > - This pull request widens that opt-in to both launch inputs, under a name that says so, before any provider adopts the old name > - The benefit is that a provider can restart a parked Runner on resume with the same credential and environment a `submit` would carry ## Linked Issues or Issue Description Refs #21289 Follows: #21335 **What existing behavior does this improve?** The opt-in resume launch inputs added in #21335. **Subsystem affected** Plugin SDK environment task schema (`describe` capability), the plugin Runner task owner's `resume`, and the plugin environment task docs. **Current behavior** With `resumeCredentialVersion: 1`, `resume` carries `credential`. `configuredEnvironment` is sent on `resume` only for a session handoff. **Proposed behavior** The capability is renamed `resumeLaunchInputsVersion: 1`. With it, `resume` carries `credential` as before and also `configuredEnvironment` (same builder as `submit`) when the provider advertises `configuredEnvironmentVersion: 1`. Session handoff is unchanged. **Reason and benefit** A provider that restarts the Runner on resume gets both launch inputs it needs. **Breaking changes** The capability name changes from `resumeCredentialVersion` to `resumeLaunchInputsVersion`. No provider advertises the old name yet (it merged in #21335 and has no adopter), so nothing changes behavior. ## What Changed - Rename `resumeCredentialVersion` → `resumeLaunchInputsVersion` in the SDK `describe` result schema, executor plumbing, owner input, docs and tests. - With the capability, `resume` also adds `configuredEnvironment` when the provider advertises `configuredEnvironmentVersion: 1`. A normal resume does not mark the variables as delivered, since a live Runner keeps the environment it started with. - Docs: the "Release and resume" section describes both fields; the "Configured environment" section points to it. - The runner-e2e SDK public-input pin is updated. ## Verification - SDK vitest `tests/environment-task-release-resume.test.ts` and `tests/environment-tasks.test.ts`: 68 passed. - Server vitest `plugin-runner-task.test.ts` and `environment-task-runtime.test.ts`: 153 passed, including a normal resume with the capability (credential sent, variables added only with `configuredEnvironmentVersion: 1`, delivered flag unset) and redaction of both fields from metadata writes and sanitized errors. - `native-session-executor.test.ts -t "uses a task-only"`: 5 passed. - runner-e2e `source-sdk-evidence.test.ts` and `source-sdk-public-type.test.ts`: 46 passed. - `pnpm typecheck` in `server/` (builds shared and plugin-sdk) passed. - Not run locally: the full suite and `pnpm verify`; required CI covers them. ## Risks - A provider restarting the Runner gets the claimant run's current variables, which can differ from the ones the parked Runner started with. That is intended. - Rollback: revert this pull request. No migration. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use (shell, file edits, test runs), implemented by a sub-agent and reviewed before opening. ## 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 Opus 5.5 <noreply@anthropic.com> |
||
|
|
342fb308bd |
perf(run-events): commit streaming text deltas in batches (#21460)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - One server process stores every event of every running native agent in `heartbeat_run_events` > - Text deltas (`item.delta`) are about 85% of that process's SQL statements: each delta is one transaction of four statements on the shared 10-connection pool > - At 50 agents and 20 deltas per second, the process falls behind and unrelated agent requests wait for the pool > - This pull request commits text deltas in batches: one transaction for all deltas that arrive within 250 ms, with one multi-row insert > - The benefit is about 7 times fewer transactions and 5–6 times fewer statements per delta, with no delay for the first text of an item ## Linked Issues or Issue Description Refs #21435 (this pull request is stacked on it). Refs #21131. Item 1a of the agent scaling plan in #21418. **What existing behavior does this improve?** The persistence of native text deltas. `native-session-runtime` awaited `PaperclipControlPlanePort.appendEvent` for each event, and the port ran one transaction per event. **Subsystem affected** Server run event ingest (`paperclip-control-plane-port.ts`, `heartbeat-run-events.ts`) and the runner package's turn consumer (`native-session-runtime.ts`). **Current behavior** Each delta takes one transaction: BEGIN, run lock, append, COMMIT. In the load model with 50 agents (deltas only), that is about 4.0 statements and 1.0 transaction per delta. **Proposed behavior** The turn consumer starts the next append without waiting for a delta's receipt. The port collects deltas and commits them in one transaction with one insert. In the same load model, that is about 0.7 statements and 0.14 transactions per delta. **Reason and benefit** Fewer transactions free the shared pool and the main thread for other agents' requests. This is the largest per-agent cost in the scaling plan. **Breaking changes** None. The row shape does not change. A port without the new capability keeps the earlier serial behavior. ## What Changed - `appendHeartbeatRunEventBatch` (`heartbeat-run-events.ts`) appends native source events of one run and one source in one transaction. When the events continue the stored source cursor (from #21435), it sends four statements for the whole batch: the run lock, one replay probe, one `insert ... select from jsonb_array_elements(...)` of every row, and the commit. Any other batch (a replay, a gap, an event with a wake, or a run without a cursor) appends its events one by one in the same transaction, with the single-append checks. - **Storage choice: one row per delta, written by one statement per batch.** I did not store one row per batch. The transcript, live events, run log export, chat progress, replay (`replayEvents`), recovery cursors and the UI all read one row per delta. One statement per batch keeps every reader unchanged, and rows written before this change read the same. - `PaperclipControlPlanePort` sets `pipelinesStreamingEvents`. An `item.delta` appended with the new `streaming` option goes into a queue: - It commits at once until a delta with text commits after the latest other event. So the first text of each item, and the time to first token, never wait for the timer. - Later deltas commit after at most 250 ms, or at once when the batch has 100 deltas. - Every other event, `checkpointSession`, `completeRun`, `replayEvents` and `provesNoRunProviderWork` first commit the queue. A non-streaming event is never committed before the deltas that preceded it. - A delta appended without `streaming` commits at once, so callers that wait for each receipt are not slowed. - The receipt of a delta settles only after its batch commits and its observers (live event, executor callback) run, in order. - If a batch fails, every delta in it rejects and nothing from it is stored. - `native-session-runtime` `consumeTurn` appends deltas with `streaming` and does not wait for their receipts (at most 256 pending). Before any other event, any result, and the governed-wait settlement, it calls `flushStreamingEvents()` and then waits for all pending receipts, so a boundary never waits for the timer. A failed delta stops the turn before a later event is appended. The consumer joins every pending delta append before it settles, also when the provider stream fails. - If one observer of a committed batch fails, only that delta's receipt rejects. The other rows are still published and observed. - `ControlPlanePort` contract: optional `pipelinesStreamingEvents`, `flushStreamingEvents()` and `AppendControlPlaneEventOptions.streaming`. ## Verification - Red/green. The new tests failed before the change and pass after it: - Runner: "starts text delta appends without waiting and flushes them before any other event" (`native-session-runtime.test.ts`). The port in the test has no timer, so the turn finishes only if the boundary flushes. Before: the appends were serial, and later the boundary waited for the timer. - Runner: "joins pending delta appends before a failed turn settles". Before: the turn settled while a delta commit still ran. - Port: "observes every committed delta of a batch when one observer fails". - Port: "commits the first text delta at once and later deltas in one batch before the next other event". It checks one transaction and one insert for five deltas, flush before a non-streaming event, receipts only after commit, and immediate commit of the first delta with text. Before: each delta committed alone. - Port: "flushes queued deltas on the timer and before a replay read, and rejects every delta of a failed batch". It checks the crash-before-commit case: a revoked writer fails the batch, nothing is stored, and the resent deltas commit idempotently (the stored one is a duplicate). - Store: four new tests in `heartbeat-run-event-atomic-append.test.ts`: one lock, one probe and one insert per batch; replay idempotency and payload conflict; a batch that fails before commit stores nothing and its resend commits; the one-by-one path for no cursor and for gaps. - Focused suites pass: `heartbeat-run-event-atomic-append`, `heartbeat-run-event-sequencing`, `paperclip-control-plane-port` (including the package conformance suite), `paperclip-semantic-conformance`, `native-observer-replay`, `native-event-boundary-golden`, `live-recovery-work`, `native-interaction-bridge`, `chat-native-progress-work`, and `native-session-runtime.test.ts` in the runner package. - `pnpm --filter @paperclipai/paperclip-runner run typecheck:typescript` and `pnpm --filter @paperclipai/server run typecheck` pass. `pnpm check:module-boundaries` passes. - Load model (`scripts/benchmark-agent-scaling-load.ts` from #21418, `AGENTS=50 SECONDS=20`, local embedded PostgreSQL). The load model calls the store directly, so for this run I added a local `BATCH_MS` mode that applies the port's batching rules (first delta at once, 250 ms timer, 100 cap, flush before other events) and does not wait for delta receipts. That mode is not in this pull request. The machine was very busy (load average 40–60), so absolute figures are noisy; per-delta ratios are the stable result: | Deltas only | Statements/s | Transactions/s | Deltas done of offered | Statements per delta | Transactions per delta | Lateness p50 / p99 | | --- | --- | --- | --- | --- | --- | --- | | One transaction per delta | 2,920 | 730 | 14,668 of 20,000 | 3.98 | 1.00 | 3,074 / 5,384 ms | | Batched (250 ms) | 704 | 141 | 19,940 of 20,000 | 0.71 | 0.14 | 668 / 2,858 ms | | One transaction per delta (repeat) | 1,712 | 428 | 8,575 of 20,000 | 3.99 | 1.00 | 6,558 / 11,464 ms | | Batched (250 ms, repeat) | 856 | 172 | 20,000 of 20,000 | 0.86 | 0.17 | 187 / 556 ms | With all sources on, the machine was saturated (event-loop utilization 0.96–0.98) in both modes and the results were not usable (764 and 12,800 of 20,000 deltas done). ## Risks - **Ack and crash (read first).** In the live runnerd path the runner's ack does not wait for the `heartbeat_run_events` row today. `DurablePrpControlPlane.#event` acks after the in-memory journal commit. Streaming events are not in the controller checkpoint. So a delta that is acked but not yet appended is lost if the server crashes, and the runner does not resend it. This is the earlier behavior. This pull request makes that window up to 250 ms longer. The final text still survives through `item.completed`, which commits immediately and in order. This pull request does not change `durable-prp-control-plane.ts`. - Live text in the UI arrives in steps of up to 250 ms after the first text of an item. - A delta failure now surfaces at the next non-delta event or at the end of the turn, not at the delta. The turn stops before it appends a later event. - The governed-wait drain and the control-event replay still append one event at a time. They do not carry deltas. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use and code execution in Claude Code. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
0aaab644fe |
refactor(runner): remove the direct assigned-gateway path (#21311)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - An agent reaches the tools of its app connections through an MCP gateway. > - Before #21274, some native harnesses got the gateway URL and a bearer token and connected to the gateway directly. The Runner has code for that: an HTTP MCP server for ACPX providers, a server entry in the Codex `config.toml`, a server entry in the OpenCode config, and the lists that pass the three `PAPERCLIP_NATIVE_MCP_*` variables to a sidecar. > - #21274 gives each native harness its gateway tools through the PRP relay. Core removes the three variables from each Runner environment. The direct code path gets no binding. > - Code that cannot run still needs maintenance, and it can still put a token in a provider process if a variable arrives by another way. > - This pull request deletes the direct path from the Runner. > - The benefit is one path for assigned gateway tools, and no Runner code that can give a gateway token to a provider. ## Linked Issues or Issue Description No public issue exists. The issue is described here. This pull request is in a stack. Its base branch is `fix/keep-quiet-claude-provider-between-turns` (#21293). It depends on #21274, which is the bottom of the stack. On `master` without #21274, the direct path is still in use. **What existing behavior does this improve?** The Runner code that connects a provider directly to the assigned MCP gateway. **Subsystem affected** Paperclip Runner: the TypeScript drivers and the Rust `runner-core` environment lists. **Current behavior** After #21274, Core never gives `PAPERCLIP_NATIVE_MCP_NAME`, `PAPERCLIP_NATIVE_MCP_URL` or `PAPERCLIP_NATIVE_MCP_TOKEN` to a Runner. The Runner still has the code that reads them and configures a direct gateway server for ACPX providers, Codex and OpenCode. **Proposed behavior** The Runner has no code that reads the three variables to configure a provider. If the variables are in the environment of a Runner, no provider environment, sidecar, Codex `config.toml` or OpenCode config gets them. **Reason and benefit** Less code, one path, and no way for a gateway token to reach a provider process through the Runner. ## What Changed - Deleted `packages/paperclip-runner/src/drivers/native-mcp.ts` (`nativeMcpLaunchBinding`). - `drivers/acpx/runtime-host.ts`: removed the native gateway server entry and the name conflict check. The admission gate keeps its message. A run with a binding id is admitted when the sidecar uses the PRP transport with its tool bridge, as the production sidecar always does. - `drivers/acpx/environment.ts`: the name and the URL are not in the provider allowlist. - `drivers/runtime-context-materializer.ts` and `live/runnerd-codex-transport.ts`: the Codex home functions have no `nativeMcp` parameter. The sidecar token pass-through is gone. - `drivers/opencode/opencode-server-driver.ts`: removed the read of the binding, its trace redaction value, and the gateway server entry in the OpenCode config. - `drivers/stdio-mcp.ts` and `runner-core/src/stdio_mcp.rs`: removed the reservation of the gateway server name. No gateway server exists, so no name can conflict. The names `paperclip` and `paperclip_runner_*` stay reserved. - `runner-core/src/acpx_sidecar_transport.rs` and `codex_provider.rs`: the three variables are not in the pass-through lists. - `control-plane/durable-prp-control-plane.ts`: the three variables are not in the platform environment list. - `packages/paperclip-runner/README.md`: the text about direct callers and assigned servers. - Kept: the three names stay in the reserved lists (`src/configured-environment.ts`, `runner-core/src/configured_environment.rs`). A user cannot configure them. Tests in both languages now check all three names. - No server code changed. The relay needs the gateway token and URL on the control plane. 23 files, 73 lines added and 211 lines removed. ## State saved by the previous release - This pull request changes no persisted shape. The provider server lists, the launch profile digests, the protocol versions and the sidecar contract are the same as with #21274. - A Runner or sidecar that the previous release started keeps its own code until its run ends, as #21274 describes. - A kept Codex home that has the old gateway server in `config.toml` is written again at the next start and at a recovery of the same run. A test covers this. - If the old variables reach a new Runner, no provider gets them. Tests cover this for ACPX, Codex and OpenCode. ## Verification From `packages/paperclip-runner`: - `npx vitest run src/drivers/acpx/runtime-host.test.ts src/live/runnerd-codex-transport.test.ts src/drivers/acpx/environment.test.ts src/drivers/opencode/opencode-server-driver.test.ts src/live/runnerd-codex-transport-warm-attachment.test.ts src/drivers/runtime-context-materializer.test.ts src/drivers/agent-observability.test.ts src/drivers/stdio-mcp.test.ts src/control-plane/durable-prp-control-plane.test.ts src/configured-environment.test.ts`: `10 passed (10)` files, `807 passed` tests. - `npx tsc --noEmit -p tsconfig.json` and `-p tsconfig.test.json`: no errors. - `cargo fmt --manifest-path runner/Cargo.toml --all -- --check`: no changes. - `cargo test -p paperclip-runner-core --test acpx_sidecar_transport`: 20 passed. `cargo test -p paperclip-runner-core --lib`: 639 passed, 4 ignored. Tests that failed with the old code and pass now: - `runtime-host.test.ts`: "admits a relayed … run with a binding id and ignores a previous-release gateway binding", for Claude, Codex and Cursor. - `runnerd-codex-transport.test.ts`: "drops a previous-release gateway binding from the … runner environment", for ACPX Claude, Codex, Pi, Cursor, Copilot and Kimi, and for OpenCode. - `opencode-server-driver.test.ts`: the OpenCode config has only the task bridge. - `runnerd-codex-transport-warm-attachment.test.ts`: a restored Codex home has no gateway server and no gateway credential in `config.toml`. - `environment.test.ts`: a provider environment has none of the three variables. - Rust `previous_release_gateway_binding_and_unrelated_secrets_never_reach_the_sidecar`: a Runner that starts with the old variables gives none of them to the sidecar, for five agents. Mutation check: with the three names put back in the Rust pass-through list, the Rust test fails. Not run: a live run with a real provider. Not run: `pnpm verify` and the full suite. CI supplies that coverage. ## Risks - **This pull request is safe only after #21274.** The stack order keeps that. - **A developer who sets the three variables by hand for `eval-session`** no longer gets direct gateway tools. No document describes that use. - **The warm attachment test uses the staged Runner binary from preflight.** That binary does not have the Rust changes of this pull request. The Codex path of that test does not use the changed lists. - The evidence that no entry point supplies a binding comes from a read of the code: Core removes the variables before it builds each Runner environment, and a native run cannot use the in-process path. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Claude Fable 5.2 (`claude-fable-5-2`) in Claude Code planned the change, reviewed the diff, and ran the verification and a mutation check again. - Claude Opus 5.5 (`claude-opus-5-5`), as a Claude Code subagent with tool use (shell, file edits, local test runs), traced each code path and wrote the change and the tests. ## 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> |
||
|
|
12aa08721c |
feat(ssh): use the agent AI account in new environments (#21248)
Use the agent-selected AI account for new SSH environments. Preserve
remote-machine authentication for existing environments and expose it as
an advanced option. Keep managed credentials private while preserving
supported conversation state and credential refreshes across turns.
Validated with focused route, adapter, lifecycle, and real-process tests;
final CI passed on
|
||
|
|
2a8b485140 |
fix(runner): accept object fields sent as JSON text and name wrong-type rejections (#21485)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The Paperclip runner checks each tool call from the model against the tool's input schema before it sends the call to the control plane > - Some model hosts send an object argument as its JSON text. On the DigitalOcean host, `paperclip_finish` arrived with `continuation` as a string > - The runner rejected these calls, and the repeated-rejection guard then told the model that its arguments "did not arrive", which is wrong when every field arrived with the wrong type > - This pull request makes the runner parse such a string back into its object when that is safe, records each coercion as a run event, and makes the guard name the actual problem > - The benefit is fewer stuck finish calls, and guidance that points the model at the real fault ## Linked Issues or Issue Description Refs #21398 **What happened?** Chat-eval cohort 13 ran OpenCode with `openrouter/deepseek/deepseek-v4.1-flash-1017` on master `df1b12ad8e`. On the DigitalOcean host, 6 of the 8 remaining "Invalid tool input" rejections were `paperclip_finish` calls with `continuation` sent as a JSON string (`/continuation must be object,null`). Examples: `gateways-profiles.rotate-token`, `instance-operations.restart-service`, and `questions-and-approvals.multi-part-question`. The run diagnostic recorded `continuationShape: "string"`. After the second identical rejection, the guard from #21398 said "If you meant to send other arguments, they did not arrive". Every argument had arrived; one had the wrong type. **Expected behavior** When a schema field is object-typed, does not allow text, and the text parses to a plain JSON object that makes the call valid, the runner accepts the call with the parsed object and logs a run event. When a call stays invalid, the guard says which required fields are missing and which fields have the wrong type. **Steps to reproduce** 1. Start the OpenCode MCP bridge. 2. Call `paperclip_finish` with `reportedWorkDisposition: "yielded"` and `continuation` as `JSON.stringify({ kind: "response_wake", ... })`. 3. Before this change, the bridge returns `Invalid tool input: /continuation must be object,null`. ## What Changed - Added `packages/paperclip-runner/src/drivers/tool-input-coercion.ts`. `admitToolInput` validates the arguments. If they are invalid, it parses a string in an object-typed field back into its object. It does this only when the field's schema declares `object`, does not allow `string`, the text parses to a plain JSON object, and the whole coerced call validates. It applies to any object-typed field at any depth, not only `continuation`. - The OpenCode MCP bridge and the runner tool bridge use `admitToolInput`. They dispatch the coerced arguments, and they send one `paperclip.runner.tool-input-coerced/v1` diagnostic per accepted coercion. The OpenCode driver already records bridge diagnostics as run events. The diagnostic names the tool and the field paths. It never contains the values. The runner tool bridge has a new optional `onDiagnostic` option. - When parsed text is still invalid, the rejection describes what is wrong inside the parsed object, for example `/options/mode must be string`. - The repeated-rejection guard now says "Required fields X did not arrive" only for missing required fields. For fields with the wrong type, it says "Every field you sent arrived, but one has the wrong type: continuation must be an object or null, not text". ## Verification - `cd packages/paperclip-runner && npx vitest run src/drivers/opencode/mcp-bridge.test.ts src/drivers/runner-tool-bridge.test.ts` (63 tests pass). - Red/green: with the source changes reverted and the new tests kept, 5 tests fail: coercion acceptance and its run event (both bridges), no coercion for text fields or non-object text, the wrong-type guard wording, and the missing-field guard wording. With the change, all of them pass. - `npx tsc --noEmit -p packages/paperclip-runner` passes. - A narrow paid run of `questions-and-approvals.multi-part-question`, `runs-adapters.inspect-failed-run` and `budgets-costs.explain-hard-stop` ran on a branch that combines this PR with the two sibling cohort-13 PRs. The results are in a PR comment. ## Risks - Low risk. Coercion runs only after a call fails validation, and the call is accepted only if the coerced form validates. A field that allows text is never parsed, so a valid string never changes meaning. - Previous-release story (upgrade-safe run state): this change adds no persisted run, session, launch or pack state. It changes only how one in-flight tool call is admitted. Saved state carries forward unchanged. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Anthropic Claude Opus 5.5 (`claude-opus-5-5`), used through Claude Code with tool use and code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [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 Opus 5.5 <noreply@anthropic.com> |
||
|
|
0ebe6d846d |
perf(runner): keep a quiet Claude provider between turns of a run (#21293)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Paperclip Runner runs Claude Code through the ACPX sidecar. The Runner stops and starts the sidecar and Claude at each turn boundary. > - The reason was that a late tool call from an earlier turn could run in a later turn. #21278 removes that reason for Claude: the sidecar refuses a call that the active turn did not announce. > - A second reason remains. Claude Code works by itself between prompts. When a background task finishes, Claude starts a cycle of its own. If the process stayed alive with a live background task, that cycle could start between turns or mix with the next turn. > - So the Runner can keep the process only when it knows that Claude has no background work. > - This pull request adds that knowledge and uses it. After a Claude turn that completed with no background work, the Runner keeps the process for the next turn of the same run. > - The benefit is that a later turn of the same run starts with no provider restart. This is also the base for the next step, which lets a run continue when background work finishes. ## Linked Issues or Issue Description No public issue exists. The issue is described here. This pull request is stacked on #21278. Its base branch is `fix/bind-claude-tool-calls-to-turn`. Refs #19912 (design), #12419 (restart at turn start), #20145 (restart at park) and #20190 (restart at turn end). **What existing behavior does this improve?** The provider restart between turns of the same run, for Claude through ACPX. **Subsystem affected** Paperclip Runner: the ACPX sidecar (TypeScript) and the ACPX provider session in `runner-core` (Rust). Claude only. **Current behavior** - When a completed turn settles, the Runner restarts the sidecar and Claude (`restart_session_after_turn`, #20190). - If that restart did not run, the next turn restarts them at its start (`start_turn`). - The Runner does not know if Claude has background tasks. **Proposed behavior** - The sidecar asks `claude-agent-acp` for its async task reports. This is an optional capability of the pinned `claude-agent-acp` 0.73.0. The patch does not change. - A tracker reads those reports and the id of each background Bash command. It reports `{ live: 0 }` only when it knows that this process never had a background task and that Claude did not act between prompts. In all other cases the state is unknown. - The sidecar adds `backgroundTasks` to the terminal event of a completed Claude turn, and to `session.snapshot`. - The Runner keeps the process between two turns only when all of these are true: - the agent is Claude; - the turn completed (not failed, cancelled or interrupted); - the terminal event reported `backgroundTasks: { "live": 0 }`; - each existing condition of the turn-end restart is true; - before the next turn, a new `session.snapshot` reports the same identity and run, no active turn, no pending work, and `{ "live": 0 }`; - the settled-turn ledger and the tool replay ledgers are not full. - In each other case the Runner restarts as before. - A kept process keeps its tool call-id tombstones and its settled turn identities. **Reason and benefit** - A turn that follows a quiet turn in the same run starts without a restart. - The decision is safe by default: unknown state means a restart. ## What Changed TypeScript (`packages/paperclip-runner/src`): - `drivers/acpx/claude-background-tasks.ts` (new): `ClaudeBackgroundTaskTracker`. It reads raw ACP messages. It reports unknown when the capability is not negotiated, when a task finished, when a live task is not a shell command, when an update is malformed, when a limit is reached, when Claude acts with no client request in flight, or when Claude calls `CronCreate` or `ScheduleWakeup`. - `drivers/acpx/provider-failure.ts` and `acpx-runtime-adapter.ts`: Claude sessions also advertise the `asyncTasks` capability. The raw ACP observer gives each message to the tracker. ACPX 0.22 drops the `async_task_*` updates before the turn event stream, so only the raw observer sees them. - `drivers/acpx/runtime-host.ts`: `backgroundTaskState()`. - `cli/acpx-runtime-sidecar.ts`: the terminal event of a completed Claude turn carries `backgroundTasks` in the same payload as `goalAtTerminal`, with the same size limit. `session.snapshot` carries it when no turn is active. - `drivers/acpx/claude-tool-use-admission.ts`: `hasRoomForAnotherTurn()`. When the admitted-id ledger cannot hold one more full turn, the sidecar reports unknown, so the Runner restarts before the ledger is full. Rust (`packages/paperclip-runner/runner/crates/runner-core`): - `acpx_provider_session.rs`: the session records a quiet turn from the terminal event. `start_turn` continues in the same process only under the conditions above, and then uses `prepare_turn`, which keeps the tombstones. - `acpx_provider_generation.rs`: `can_continue_after_turn`, `continue_after_quiet_turn`, and the snapshot check `background_work_is_quiet`. - `acpx_park_preparation.rs`: the turn-end restart does not run for a quiet Claude turn. - `acpx_provider_backend.rs`: `session.reconciled` reports a replaced process only when the turn start replaced it. - `bin/fake-acpx-sidecar.rs`: new option `--background-tasks` for tests. - `runner/DURABLE_TRANSPORT.md`: the rule for a kept sidecar. Contract (`packages/paperclip-runner/protocol`): - The `backgroundTasks` report is `$defs.backgroundTasks` in `provider-schemas/acpx-sidecar.schema.json`: an object with only `live`, a non-negative integer. The schema validates it on `runtime.turn_terminal`. - `scripts/generate-acpx-sidecar-contract.mjs` generates the TypeScript type and reader and the Rust reader from it. The tracker, the sidecar and the Rust session use the generated code. - `fixtures/provider-boundary/acpx-background-tasks.json` has shared test documents. The TypeScript reader, the Rust reader and the schema are tested with the same accepted and refused shapes. - This changes the contract digest of the provider pack (`prp.acpx-sidecar` and `rust`). Older image packs are not reused. No provider `commandDigest` and no profile version changes. Not changed: park and run attachment. A process that ran a turn is still restarted at park, and only a process that ran no turn is bound to the next run. Other ACPX agents and Codex do not change. The `claude-agent-acp` patch does not change. ## State saved by the previous release - This pull request adds no persisted state. The three new fields of the session are in memory only. - A terminal event or a snapshot without `backgroundTasks` means unknown. An older sidecar therefore gets the restart, as before. - An older Runner with a new pack ignores the field and restarts at each turn, as before. - After a Runner restart, the in-memory state is gone. The next turn restarts the provider, as before. A test covers this. ## Verification From `packages/paperclip-runner`: - `npx vitest run src/drivers/acpx/claude-background-tasks.test.ts src/drivers/acpx/acpx-runtime-adapter.claude-background-tasks.test.ts src/drivers/acpx/acpx-runtime-adapter.claude-tool-use.test.ts src/drivers/acpx/claude-tool-use-admission.test.ts src/cli/acpx-runtime-sidecar.test.ts src/drivers/acpx/acpx-runtime-adapter.test.ts src/drivers/acpx/runtime-host.test.ts`: `7 passed (7)` files, `363 passed` tests. - `npx tsc --noEmit -p tsconfig.json` and `npx tsc --noEmit -p tsconfig.test.json`: no errors. - `pnpm run typecheck:typescript` (it includes the contract checks): no errors. `node --test test/acpx-sidecar-contract.test.mjs`: 17 passed. - `cargo fmt --manifest-path runner/Cargo.toml --all -- --check`: no changes. - `cargo test -p paperclip-runner-core --test acpx_quiet_turn_continuation --test acpx_park_preparation --test acpx_park_readiness --test acpx_provider_turns --test acpx_provider_session --test acpx_warm_attachment --test native_provider_backend`: 4, 33, 8, 31, 12, 6 and 47 passed. No test failed. - `cargo test -p paperclip-runner-core --lib`: 637 passed, 4 ignored. - Mutation check: when the Rust code accepts each live count as quiet, two tests in `acpx_park_preparation` fail. New tests: - **Real ACP runtime** (`acpx-runtime-adapter.claude-background-tasks.test.ts`), with the pinned `claude-agent-acp`, the pinned Claude Code client and a local fake Anthropic API. A foreground Bash turn reports `{ live: 0 }`. A background Bash in the same process reports `{ live: 1 }` at the terminal event, and unknown after Claude ran its own cycle for the finished task. Each turn has its own usage receipt. One process serves all turns. - **Tracker unit tests** (13): spawn, completion, failure, stop, pause, a task that is not a shell, a subagent, no negotiation, malformed updates, activity between prompts, scheduling tools, session load replay, limits. - **Sidecar tests**: the terminal event carries the state for Claude and not for Codex. A full ledger reports unknown. - **Rust** `tests/acpx_quiet_turn_continuation.rs` (4) and `tests/support/acpx_quiet_turn_restart.rs` (7): - a quiet Claude turn continues in the same process, and a replay of a settled call id is refused; - live, unknown and malformed reports restart; - background work that appears after the terminal event restarts at turn start; - failed, cancelled and interrupted turns restart; - Codex with a quiet report restarts; - an active goal restarts; - 4,096 kept turns, then the next turn restarts; - park after a kept process still prepares a new process, and the next run attaches to it; - a Runner restart after a kept process resumes in a new process. - The existing restart tests did not change. The fake sidecar sends no report by default, so they are the tests for the unknown case. Live run with a real Claude account, not in CI: the real ACP runtime (ACPX 0.22, the patched `claude-agent-acp`, the pinned Claude Code client), a real tool bridge, and the real Anthropic API with model `claude-sonnet-5-5`, on the code at the top of this stack. A turn that started one background shell reported `{ live: 1 }`. A turn that started two reported `{ live: 2 }`, then `{ live: 1 }` and `{ live: 0 }` as each shell finished. A turn in which Claude waited for its background shell in the foreground reported the unknown state. Not run: server integration tests (the fake sidecar there sends no report, so their process counts do not change), Linux, and a live run through the real sidecar process and runnerd. ## Risks - **All Claude sessions now negotiate the `asyncTasks` capability.** `claude-agent-acp` then sends `async_task_*` updates and adds a marker to a background Bash update. ACPX drops the updates. No other behavior of `claude-agent-acp` changes, from a read of its code. - **Park after a kept process pays the restart again**, as it did before #20190. With real Claude that restart was about 1.5 s. - **A small window remains** between the snapshot and the prompt of the next turn. Claude can start a cycle of its own in that window only without a background task, because a process that had a background task is not kept. - **Activity between prompts is found only when no client request is in flight.** A request that never gets a response would hide such activity. - **Background watchers cannot be told apart from other tasks**, so each task that is not a shell command makes the state unknown. - **Each kept turn adds one `session.snapshot` request.** - A multi-turn run with real Claude now uses one provider process. This path has tests with the fake sidecar and with the real ACP runtime. It has no test with the real sidecar host. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Claude Fable 5.2 (`claude-fable-5-2`) in Claude Code planned the change, reviewed the diff, and ran the TypeScript and Rust verification again. - Claude Opus 5.5 (`claude-opus-5-5`), as a Claude Code subagent with tool use (shell, file edits, local test runs), investigated the signals and wrote the change and the tests. ## 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> |
||
|
|
969cf246ae |
perf(run-events): keep each native source's cursor on the run row (#21435)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - One server process stores every event of every running native agent in `heartbeat_run_events` > - Each native source event append counted all retained events of its source (`count(*)`, `max(source_seq)`) to compute the acknowledgement cursor > - So the cost of each append grew with the length of the run, and long runs made every text delta slower > - This pull request keeps the gap-free cursor of each source on the run row and moves it in the same UPDATE that reserves the event sequence > - The benefit is that an in-order append stops reading other events, so its cost does not grow with run length ## Linked Issues or Issue Description Refs #21131 (earlier reduction of statements per event). Item 1b of the agent scaling plan in #21418. **What existing behavior does this improve?** The append of a native source event (`appendNativeSourceEvent` in `server/src/services/heartbeat-run-events.ts`). It ran a `retained` CTE that counted every event of the source on every append. **Subsystem affected** Server run event ingest (`heartbeat_run_events`, `heartbeat_runs`). **Current behavior** On a run that already holds 50,000 events, one in-order append takes about 10–13 ms (p50) on a local PostgreSQL. On a run with 400 events it takes about 3.3 ms. **Proposed behavior** The append reads the stored cursor in the run lock statement that it already sends. An in-order event moves the cursor and does not count events. On the same 50,000-event run an append takes about 1.7–3.3 ms (p50). **Reason and benefit** Text deltas are about 85% of the server's statements in the load model. Their cost must not grow with run length. **Breaking changes** None. The new column is nullable. The previous release ignores it. ## What Changed - Add the nullable column `heartbeat_runs.native_source_cursors` (`jsonb`, `{"<source instance id>": <seq>}`). Migration `0479` is `ADD COLUMN` only and classifies as `online_compatible`. - The run lock read of a native append also reads the cursor of its source. - When the event sequence is at most cursor + 1, the append statement has no `retained` CTE. It moves the cursor in the UPDATE that reserves the sequence, and the receipt uses the cursor. - Every other case (no cursor, a gap, or a cursor behind the stored events) runs the earlier recount. In the same UPDATE it stores the cursor when the source has no gap, and removes it when the source has a gap. So the event that fills a gap recounts. - The cursor is a lower bound. A writer that does not keep it (the previous release during a deploy overlap, or `NativeRunCoordinatorStore`) can only make it lag. The next out-of-order event then recounts and corrects it. ## Verification - `cd server && npx vitest run src/__tests__/heartbeat-run-event-atomic-append.test.ts src/__tests__/heartbeat-run-event-sequencing.test.ts` passes (19 tests). - Red/green: before the change, 3 tests failed: the two new tests and the updated lock-read statement test. After the change, all pass. - New: "keeps the source cursor on the run so an in-order append does not count the run's events" checks that the append statement has no `count(` and that a replay returns the cursor. - New: "recounts a source whose run has no cursor or a cursor behind its stored events" covers rows saved before the change, rows from a writer that does not keep the cursor, a gap, and the event that fills the gap. - Focused related tests: `paperclip-control-plane-port.test.ts`, `native-observer-replay`, `native-event-boundary-golden`, `chat-native-progress-work`, `live-recovery-work`, `native-interaction-bridge`. - `pnpm check:module-boundaries` passes. `pnpm verify` returned exit 2 (broader CI coverage required) because of local benchmark scripts that are not in this pull request. Required CI supplies the broad coverage. - Append cost on a run with many events (local embedded PostgreSQL, 1,000 in-order appends, busy machine, load average about 20–40): | Events already in run | Before p50 / p90 | After p50 / p90 | | --- | --- | --- | | 50,000 (run 1) | 10.4 / 15.8 ms | 1.7 / 3.7 ms | | 50,000 (run 2) | 12.9 / 21.6 ms | 3.3 / 5.9 ms | | 400 | 3.3 / 6.2 ms | 3.7 / 7.7 ms (noise) | - Statements per event do not change: BEGIN, run lock read, one append statement, COMMIT (4). The append statement no longer scans the source's events. - Load model (`scripts/benchmark-agent-scaling-load.ts` from #21418, `AGENTS=50 SECONDS=20`): the machine was too busy for a stable result. Deltas only: before 20,000 of 20,000 done at 3,999 statements/s. After: 13,796 and 14,817 of 20,000 in two runs. All sources: before 6,346 of 20,000 deltas done. After: 20,000 and 2,083 in two runs. A 20-second window gives only 400 events per run, so it cannot show this change. The long-run figures above are the evidence. ## Risks - Low. The column is nullable and the previous release does not read it. Runs that are in flight during a deploy have no cursor. Their first append recounts once and stores the cursor. - A stale cursor can only make the acknowledgement lag, never pass the stored events. Event rows are deleted only with their company or agent. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use and code execution in Claude Code. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
0199c963e2 |
feat(apps): ship the redesigned sign-in step for a pasted MCP server (#21469)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - Apps lets an operator connect a remote MCP server by pasting its
address ("Connect your own MCP server")
> - Step 2 of that flow put every sign-in choice in an "Advanced
authentication" box with wrapped pill buttons and a hint paragraph
> - The box hid the choice behind a vague label, and its shape did not
match the access line ("Connects for everyone… Change") right below it
> - The owner approved a redesign: a stated sign-in default with a
Change link, and five options with their fields directly below each
option
> - This pull request wires that redesign into the real screen, removes
the old step, and updates copy that named the removed box
> - The benefit is a screen that reads as two stated answers and one
action, with the same default path (paste the address, press Check link)
## Linked Issues or Issue Description
No public issue exists. Enhancement:
**What existing behavior does this improve?**
The sign-in section of the "Connect your own MCP server" step in Apps.
**Subsystem affected**
UI: Apps connection setup (`ui/src/features/connections`). Small copy
changes in the server OAuth client registration message and docs.
**Current behavior**
Step 2 shows an "Advanced authentication" collapsible with five wrapped
pill buttons and a hint paragraph below them. The fields for the chosen
mode appear further down. Guidance banners tell the operator to look
"under Advanced authentication". The page also shows the "Unverified
server" badge twice (header and body). The stepper reads "Pick app · Add
your key", even when the server needs no key.
**Proposed behavior**
Step 2 states the sign-in choice in one line ("Paperclip asks the server
how to sign in.") with a Change link. Change shows five radio cards: Let
Paperclip check, Key or token, Browser sign-in, Custom headers, No
sign-in needed. The fields for the selected option are directly below
it. Done collapses the list to a one-line summary (for example "Signs in
with 1 custom header."). The list stays open while the chosen option
still needs a value. Client ID and secret are behind "Use your own
client ID" unless they have values or the server asked for them. The
stepper reads "Pick app · Connect".
**Reason and benefit**
The choice is visible as a stated default in the same shape as the
access line. Each option keeps its fields next to it. No copy points at
a box that does not exist.
**Breaking changes**
None. The five auth modes and their request payloads do not change.
**Additional context**
Related open PRs change server behavior for the same flow. They are not
duplicates. Refs #15192, Refs #15450.
## What Changed
- `ui/src/features/connections/GenericMcpConnectStep.tsx`: new step
component (same props as the old `LinkConnectStep`). It uses stable
field ids `generic-mcp-key`, `generic-mcp-client-id`,
`generic-mcp-client-secret` and a `data-testid` on the sign-in
Change/Done link.
- `ui/src/features/connections/ConnectionSetupFlow.tsx`: render
`GenericMcpConnectStep`; delete `LinkConnectStep`,
`GENERIC_AUTH_MODE_OPTIONS`, `SegmentedOption` and unused imports;
change the pasted-link stepper label from "Add your key" to "Connect"
(`STEP_LABELS` is used only by the pasted-link flow; curated apps keep
their own `["Add your key"]`).
- `ui/src/pages/apps/generic-mcp-connect.ts`: `oauth_challenge` and
`oauth_manual_client_required` guidance now say "below" instead of
"under Advanced authentication".
- `server/src/services/tool-access/oauth/client-registration.ts`: the
manual-client message no longer names the removed box.
- `doc/connections/GENERIC-REMOTE-MCP.md`: describe the sign-in line,
Change, and the five options.
- Comments in `packages/shared` and `server/src/services/tool-access.ts`
reworded. `tests/runner-e2e/source-sdk-public-inputs.json` regenerated
for the two shared files (blob hashes only).
- `ui/storybook/stories/connection-setup/byo-mcp-sign-in.stories.tsx`:
14 stories for the shipped component; annotation is now `current` /
`production`.
- Tests: `AppsConnect.test.tsx` generic MCP block uses the sign-in
toggle and radio options; new tests for the collapsed summary, the
open-while-empty-key rule, and a single "Unverified server" label. New
`GenericMcpConnectStep.test.ts` unit-tests `genericMcpAuthSummary`.
Before: "Advanced authentication" box with pill buttons and a hint;
fields below the pills; two "Unverified server" badges; stepper "Pick
app · Add your key".
After: one sign-in line with Change; five radio cards with fields under
the selected card; one "Unverified server" badge in the header; stepper
"Pick app · Connect". Storybook: `byo-mcp-sign-in--choosing`,
`byo-mcp-sign-in--server-asked-for-key`.
## Verification
- `cd ui && pnpm exec vitest run src/pages/apps/AppsConnect.test.tsx
src/pages/apps/generic-mcp-connect.test.ts
src/features/connections/GenericMcpConnectStep.test.ts
src/features/connections/ConnectionSetupFlow.architecture.test.ts
src/features/connections/ConnectionSetupFlow.oauth.test.ts`: 5 files,
300 tests pass.
- `cd ui && node ../scripts/run-tsc.mjs -b`: pass.
- `pnpm -s typecheck` in `packages/shared` and `server`: pass.
- `pnpm check:token-gates`: all gates clean.
- `node scripts/storybook-catalog.mjs`: pass (generated indexes not
committed).
- `pnpm verify`: exit 2 (broader verification required, because
`doc/connections/GENERIC-REMOTE-MCP.md` is a global CI input). Required
CI supplies that coverage. The focused files above were rerun on the
final revision after the rebase.
- Headless Playwright against the Storybook dev server: the Default,
Choosing and Server-asked-for-key stories render the new step, the new
guidance copy, and the "Pick app · Connect" stepper.
## Risks
- Low risk. UI change on one screen; request payloads
(`genericConnectPayload`) do not change.
- Tests that click the first collapsed "Change" button now skip the
sign-in toggle, because the access line also has a "Change" button.
- The server message for `oauth_manual_client_required` changes text. No
code matches on the text; the client uses the error code.
## Model Used
- Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use
(shell, file edits, headless Playwright).
## Checklist
- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
|
||
|
|
ef2a49b6df |
fix(daytona): bound the duplex channel close so a stalled kill cannot retire the worker (#21471)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Cloud agent runs use the Daytona sandbox provider plugin. One shared plugin worker process serves all Daytona calls on a server. > - The host closes a duplex channel through the worker. The host waits 10 seconds for the close acknowledgement. When the acknowledgement is late, the host retires the whole worker with SIGKILL. > - The worker close waits for the remote PTY kill before it releases the socket. The Daytona SDK sends that kill as a toolbox request with a 24-hour default timeout. A stalled sandbox can hold it open for longer than 10 seconds. > - Then the host kills the shared worker. Every other call in flight on that worker fails with `Worker process exited (code=null, signal=SIGKILL)`. This includes other runs' workspace preparation and restore. > - This pull request limits the wait for the remote kill to 5 seconds. Then the worker releases the socket and acknowledges the close. > - The benefit is that one slow sandbox no longer stops unrelated runs on the same server. ## Linked Issues or Issue Description **What happened?** On a hosted staging server, the host logged `duplex channel close not acknowledged; retiring worker` six times in about 90 minutes. Each time, the Daytona worker exited with SIGKILL. Each time, all in-flight calls on that worker failed. Runs in workspace preparation failed with `setup_failed` and `Worker process exited (code=null, signal=SIGKILL)`. Several runs failed together in each burst. **Expected behavior** A slow close of one duplex channel does not stop calls that belong to other channels or other runs. **Steps to reproduce** 1. Open a duplex channel on a Daytona lease. 2. Make the Daytona PTY kill request stall (the SDK default request timeout is 24 hours). 3. Close the channel from the host. The worker does not acknowledge within 10 seconds. 4. The host retires the worker with SIGKILL. All other pending calls fail. **Relevant logs or output** ``` info duplex channel close not acknowledged; retiring worker info retired worker process exited code=null signal=SIGKILL willRestart=true JsonRpcCallError: Worker process exited (code=null, signal=SIGKILL) ``` **Additional context** The login PTY close does not have this problem. It only does the local socket disconnect. A kill that rejects already gets a close acknowledgement, because the session close ignores kill errors. This change gives a slow kill the same result. No related public PR exists. I searched open and closed PRs for this failure. ## What Changed - `duplex-command-stream.ts`: `close()` waits for the remote `kill()` for at most `DUPLEX_CHANNEL_CLOSE_KILL_TIMEOUT_MS` (5 seconds). Then it always releases the socket with `disconnect()`. The kill continues in the background. A kill that answers in time keeps the old order: kill, then disconnect, then the acknowledgement. - `duplex-close-deadline.test.ts` (new): regression tests at the session close and at the worker `onDuplexChannelClose` boundary, and a check that the deadline stays well inside the host deadline. ## Verification - Red before the fix: with the old `duplex-command-stream.ts`, `acknowledges a bound close inside the host deadline when the remote kill never settles` fails (no acknowledgement after 9 seconds), and the session close test times out. - Green after the fix: `pnpm --dir packages/plugins/sandbox-providers/daytona exec vitest run --config vitest.config.ts src/duplex-close-deadline.test.ts src/duplex-command-stream.test.ts src/plugin.test.ts` passes 453 of 453. This includes the existing tests `joins pending teardown for concurrent closes while all channel authority stays revoked` and `does not turn a rejected retired close into an acknowledgement`. - The safety case `still waits for a kill that answers inside the deadline before it releases the socket` passes before and after the fix. - `tsc --noEmit` for the Daytona plugin passes. - In the full Daytona plugin suite, two GNU tar tests in `file-sync.test.ts` fail in my sandbox. They also fail on unchanged `master` in the same sandbox, so they are environment failures. CI covers them. - I did not run a live staging workflow. After the deploy, the staging logs must show no new `duplex channel close not acknowledged; retiring worker` lines from slow kills. ## Risks - Low risk. The change is in one Daytona plugin function. - After a kill timeout, the gateway process can stay alive in the sandbox until the background kill completes or the lease teardown stops the sandbox. The socket is closed, so no bytes can move on the channel. The route stays retired, so the host route cannot open again. This is the same state as when a kill rejects today. - The host contract does not change. A malformed or mismatched acknowledgement still retires the worker. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude Code with tool use and code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: devinfoley <139239+devinfoley@users.noreply.github.com> |
||
|
|
7773b52f05 |
fix(codex): preserve sandbox certificate trust in Codex shell commands (#20364)
<!-- Written in ASD-STE100 style: short sentences, active voice. --> ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The Paperclip Runner and the Codex adapters run agent shell commands inside a sandboxed Codex session with a strict environment allowlist > - The controller builds `shell_environment_policy.include_only` before the sandbox injects certificate-trust variables such as `SSL_CERT_FILE` and `GIT_SSL_CAINFO` > - The allowlist drops the injected variables, so managed `git` and `gh` commands cannot verify HTTPS against a runtime-provided CA > - This pull request allows the certificate-trust variable names through every environment policy stage, from the Rust process supervisor to the shell allowlist > - The benefit is that managed `git` and `gh` work again in sandboxes that require a runtime CA, while provider-credential isolation and the bounded allowlist stay in place ## Linked Issues or Issue Description - Fixes: #20019 - Refs #20038 — community pull request for the same defect. This change reviews the approach independently. The commit credits the community author as co-author. ## What Changed - Add `CERTIFICATE_ENVIRONMENT_KEYS` (`SSL_CERT_FILE`, `SSL_CERT_DIR`, `GIT_SSL_CAINFO`, `NODE_EXTRA_CA_CERTS`, `DENO_CERT`, `REQUESTS_CA_BUNDLE`, `CURL_CA_BUNDLE`) to `packages/paperclip-runner/src/configured-environment.ts` - Native Codex shell policy (`codex-security-config.ts`): always put the certificate names in `include_only`; set inheritance to `"all"` with `ignore_default_excludes=true`, bounded by the explicit allowlist - Pass the certificate names through the app-server environment filter, the ACPX spawn environment filter, the ACPX runtime sandbox `include_only`, the runner platform environment keys, and the Rust process supervisor base key list - Legacy and ACPX-engine Codex shell allowlists (`packages/adapter-utils/src/codex-shell-environment.ts`): always include the certificate names - Add a synthetic private-CA HTTPS journey test: a real `git ls-remote` fails TLS verification without the injected CA and succeeds with it, through the policy-filtered child environment - Document the contract in `doc/sandbox-shell-environment.md` and link it from `doc/DEVELOPING.md` ## Verification - `pnpm --filter @paperclipai/paperclip-runner exec vitest run src/drivers/codex/codex-security-config.test.ts src/configured-environment.test.ts src/drivers/codex/codex-shell-certificate-trust.test.ts src/drivers/codex/codex-app-server-driver.context-control.test.ts src/drivers/acpx/runtime-sandbox.test.ts` — 104 tests pass - `pnpm --filter @paperclipai/adapter-utils exec vitest run src/codex-shell-environment.test.ts src/acpx-engine/execute.test.ts` — 270 tests pass - `pnpm --filter @paperclipai/adapter-codex-local exec vitest run src/server/execute.test.ts` — 10 tests pass - Codex driver lifecycle, conformance, recovery, and boundaries suites pass (103 tests); environment-builder suites pass (307 tests) - Red proof: with only the source fix reverted, the new regressions fail. The journey test shows `GIT_SSL_CAINFO` is undefined in the shell environment, and `git` fails TLS verification against the private-CA fixture - `cargo check` passes for `paperclip-runner-core`; `rustfmt --check` passes for the edited Rust file - The journey test needs `git` and `openssl`; it skips when either tool is absent ## Risks - The native shell policy now always sets `shell_environment_policy.inherit="all"` with `ignore_default_excludes=true`. Before, it set `"none"` when no credentials or task keys were projected. The explicit `include_only` allowlist still bounds every inherited name, so no new secret names can cross - The allowlist grows by seven non-secret certificate-trust names. Their values point at CA files. The sandbox filesystem policy still controls access to those files; this change grants no filesystem access - No persisted run, session, or launch identity changes shape. Sessions saved by the previous release resume unchanged; the new policy applies when the next launch builds its arguments - Provider credentials keep their existing exclusions at every stage ## Model Used - Claude Fable 5 (Anthropic, model ID `claude-fable-5`), extended thinking, agentic tool use, run through Claude Code. The implementation was written and reviewed independently against the community design in #20038; the community author is credited as co-author in the commit. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green (pending: checks run after this PR opens) - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups (pending review) - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: everlastingcrown <everlastingcrown@users.noreply.github.com> Co-authored-by: Claude Fable 5 <noreply@anthropic.com> |
||
|
|
7866e9ef05 |
fix(acpx): admit a Claude tool call only for a tool use its turn announced (#21278)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Paperclip Runner runs Claude Code through the ACPX sidecar. Claude calls Paperclip tools through a Runner-owned MCP endpoint, the tool bridge. > - The bridge identifies a call by its JSON-RPC request id. That id does not say which turn sent the call. The sidecar binds a call to the turn that is active when the call arrives. > - Because of this, the Runner stops and starts the Claude process at each turn boundary. A late call from an earlier turn then cannot run in a later turn. This restart also stops all background work that Claude started. > - Claude Code already sends the missing identity. Each MCP `tools/call` has `_meta["claudecode/toolUseId"]`. It is the id of the ACP `tool_call` that the provider announces first, inside one turn. > - This pull request uses that id. The sidecar admits a Claude tool call only if the active turn announced its tool use. > - The benefit is that a call from an earlier turn is refused by its identity. This is the first step to keep the Claude process alive between turns. This pull request does not change the restart. ## Linked Issues or Issue Description No public issue exists. The issue is described here. Refs #19912 (the design for turn-scoped ACPX MCP authority), #12419 (the restart at turn start) and #20190 (the restart at turn end). This pull request is the bottom of a stack. #21274 is merged, so the base branch is `master`. It uses no code from #21274. The stack order lets a later pull request remove the direct gateway path after both. **What existing behavior does this improve?** How the Runner decides which turn a Claude tool call belongs to. **Subsystem affected** Paperclip Runner: the tool bridge and the ACPX sidecar, for the Claude provider only. **Current behavior** - The bridge keys a call by the JSON-RPC request id (`runner-tool-bridge.ts`). - The sidecar gives the call to the active turn (`waitForTool` in `acpx-runtime-sidecar.ts`). - After `session/cancel`, Claude Code does not stop an MCP request that is in flight. A test run showed two calls from two turns live at the same time on one MCP session. Request ids cannot tell them apart. **Proposed behavior** - The bridge can read a provider tool-use id from `params._meta` and give it to the handler. It keys replays by that id. - For Claude, the sidecar admits a call only when the turn event stream of the active turn contains the ACP `tool_call` with the same id, and no earlier call used that id. - The announcement and the call use different channels. If the call arrives first, the sidecar waits for the announcement for a maximum of 5 seconds. The wait stops when the turn ends or the call is cancelled. - A call with no id, an id from an earlier turn, an id that was never announced, or an id that was used before gets a tool error. There is no fallback. - The call id that the sidecar sends to runnerd is `tool-use:<id>` for Claude. **Reason and benefit** - A late call from an earlier turn cannot run in a later turn. The identity of the call prevents this, not only the process restart. - A later change can stop the restart between turns. ## What Changed - `packages/paperclip-runner/src/drivers/runner-tool-bridge.ts` - New option `providerToolUseIdMetaKey`. Without it the bridge does not change. - With it, the bridge reads `params._meta[key]`. It refuses a value that is not a bounded string. It gives a valid value to the handler as `providerToolUseId`. - The replay key is the tool-use id. A retry with a new request id replays the first result. The same id with different arguments is refused. - `notifications/cancelled` still finds the call by its request id. - `packages/paperclip-runner/src/drivers/acpx/claude-tool-use-admission.ts` (new): `ClaudeToolUseAdmission`. - `observe` records an id only from an event with `type === "tool_call"` and `tag === "tool_call"`. A `tool_call_update` does not count, so a late update about an old tool use cannot admit it. - `admit` applies the rule above. An id is used when it is admitted. Limits: 4,096 announcements for each turn and 8,192 admitted ids. At a limit, new calls are refused. - `packages/paperclip-runner/src/cli/acpx-runtime-sidecar.ts` - The sidecar creates the admission object only for `agent === "claude"` and sets the bridge option only for Claude. - `pumpTurn` gives each turn event to `observe`. `waitForTool` calls `admit` and then checks the turn and run again. - The internal `get_task_context` call for a completion continuation does not go through admission. - The Claude call id does not use the per-process namespace, because a tool-use id is unique. - No change to Rust, the sidecar contract, the `claude-agent-acp` patch, the server, or restart, park and turn lifecycle code. Other ACPX agents and Cursor Cloud use the same code path as before. Why 5 seconds: the measured time between the announcement and the call is 1.1 ms to 14.7 ms. The limit must also include queue and event-loop delay. 5 seconds is far above that, and a call that cannot be attributed still gets a fast answer. ## Verification Commands, from `packages/paperclip-runner`: - `npx vitest run src/drivers/acpx/acpx-runtime-adapter.claude-tool-use.test.ts src/drivers/acpx/claude-tool-use-admission.test.ts src/drivers/runner-tool-bridge.test.ts src/drivers/runner-tool-bridge.claude-tool-use.test.ts src/drivers/runner-tool-bridge.claude-schema.test.ts src/cli/acpx-runtime-sidecar.test.ts src/drivers/acpx/acpx-runtime-adapter.test.ts src/drivers/cursor-cloud/cursor-cloud-driver.test.ts`: `8 passed (8)` files, `384 passed` tests. - `npx tsc --noEmit -p tsconfig.json`: no errors. New tests: - **Real ACP runtime** (`acpx-runtime-adapter.claude-tool-use.test.ts`). It uses the real `openCodexAcpxRuntime`, ACPX 0.22, the pinned and patched `claude-agent-acp`, the pinned Claude Code client and a real tool bridge, against a local fake Anthropic API. - Turn 1: two parallel tool uses are admitted as `tool-use:<id>`. The model receives both results. The turn completes. - Turn 2 in the same session: a replay of a turn 1 id returns the cached result and does not dispatch again. The same id with different arguments is refused. `admit` refuses the old id. - In five runs each call arrived 6.9 ms to 13.2 ms after its announcement. No call waited. - **Qualification** (`runner-tool-bridge.claude-tool-use.test.ts`). The pinned Claude Code client sends `_meta["claudecode/toolUseId"]` on each `tools/call`, with the id that the API issued. This test must pass before a Claude Code version change. - **Admission unit tests** (19): announced then called, called then announced, never announced, turn end during the wait, cancel, an id from the previous turn, reuse, two concurrent calls with one id, two turns with live calls, a subagent call, a bad id. - **Sidecar process tests** (2), with a fake host, for Claude and for Codex. The Codex run shows no change. - **Bridge unit tests** (5). Mutation checks: - Change the announcement predicate so that it matches nothing: the real ACP test and one unit test fail. - Remove the bridge option in the real ACP test: the test fails. - Count only `tool_call_update`: the unit test "counts only an opening ACP tool_call event as an announcement" fails. Live run with a real Claude account, not in CI: the real ACP runtime (ACPX 0.22, the patched `claude-agent-acp`, the pinned Claude Code client), a real tool bridge, and the real Anthropic API with model `claude-sonnet-5-5`, on the code at the top of this stack. In three sessions, 8 Paperclip tool calls were admitted and none was refused. This includes calls in a prompt turn, in a cycle that Claude started itself, and in a later turn of the same process. Each call arrived 0.8 s to 1.7 s after its announcement, so no call waited for a late announcement. Not run: a turn through the real sidecar process with the real host. That needs a qualified provider installation, the runtime sandbox and the provider lifetime lease. Not run: the Linux builds of the pinned client and a test under load. Not run: `pnpm verify` and the full suite. CI supplies that coverage. ## Risks - **This changes each Paperclip tool call that Claude makes.** If the announcement does not reach the turn event stream in production, the sidecar refuses the call after 5 seconds. The real ACP test covers the stream of ACPX 0.22 with the pinned provider. It does not cover the real sidecar host. - **The 5 second limit is not tested under load.** A slow host can delay the announcement. The call is then refused, and Claude sees a tool error. - **A Claude Code version that stops sending the id breaks all Claude tool calls.** The qualification test finds this before the version changes. - **The admitted-id ledger is in sidecar memory.** Today the sidecar restarts at each turn boundary, so the ledger is small. The limit of 8,192 ids refuses new calls when it is full. - **Subagent calls and calls from a cycle that Claude starts itself** are covered by unit tests and fake-host tests, not by the real ACP stream. - **An admitted call that is in flight when its turn ends** is refused by the existing turn cleanup. Claude Code can leave the HTTP request open. The bridge stops it only on its own cancel or close, as before. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Claude Fable 5.2 (`claude-fable-5-2`) in Claude Code planned the change, reviewed the diff, asked for the real ACP runtime test, and ran the verification and a mutation check again. - Claude Opus 5.5 (`claude-opus-5-5`), as a Claude Code subagent with tool use (shell, file edits, local test runs), wrote the change and the tests. ## 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 - [ ] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com> |
||
|
|
38821e061f |
perf(runner): serialise only changed journal records for a checkpoint (#21437)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - One server process controls every running agent, and its main thread limits how many agents can run at the same time > - Each agent has a controller journal. The controller saves a checkpoint of this journal after each control event and before each frame it sends > - Each checkpoint converted every command and every event of the journal to JSON again, also when only one record changed. The cost grew with the journal length (up to 500 commands and 4,096 events) > - This pull request keeps the JSON of each record and uses it again while the record does not change > - The benefit is that a checkpoint converts only the records that changed, so the main thread does less work for each agent ## Linked Issues or Issue Description Refs #21411 (this change sits on top of its checkpoint queue). **What existing behavior does this improve?** The controller journal checkpoint in `packages/paperclip-runner/src/control-plane/durable-prp-control-plane.ts`. Each flush calls `captureCheckpoint`, which runs `JSON.stringify` on every command and every recovery event of the journal. **Current behavior** A flush after one new event converts the full journal to JSON. With 4,096 events, one flush made about 5 MB of new JSON strings and used about 14 ms of CPU on the event loop. A hosted CPU profile with about 50 agents showed about 3% of the main thread in this path. **Proposed behavior** A flush converts only the records that changed since the last flush. The other records use the JSON that the controller made before. The saved records are byte-identical to the records of the full conversion. **Reason and benefit** The target is 1,000 agents in one controller process. Checkpoint CPU must not grow with journal length. After this change, one flush with 4,096 events makes about 2.5 KB of new JSON and uses about 2 ms of CPU. ## What Changed - Add `CheckpointRecordCache` to `durable-prp-control-plane.ts`. It keeps the JSON and the part name of each command and event record, keyed by the record object. It uses the JSON again only when the record has the same keys, in the same order, with the same values (`===`). Commands change some fields in place (`status`, `result`, `controllerSeq`), and this comparison finds these changes. - `captureCheckpoint` accepts the cache as an optional fourth argument. Only `setCheckpointPersistence` and `flushCheckpoint` pass it. All other callers (decode, legacy import, bootstrap inspection) do the full conversion as before. - `checkpointChanges` uses loops instead of array copies. Records that did not change keep the same string, so the comparison is by reference. - `queueCommand` stores a copy of the command payload (`structuredClone`). The journal must own its nested objects, because the cache compares nested objects by reference. - `durableRecoveryInternals` exposes `captureCheckpoint` and `createCheckpointRecordCache` for tests. - Regions changed: `checkpointChanges` and the new cache above `captureCheckpoint`; `captureCheckpoint`; `durableRecoveryInternals`; one field of `DurablePrpControlPlane`; the `captureCheckpoint` calls in `setCheckpointPersistence` and `flushCheckpoint`; the `payload` field in `queueCommand`. The `#event` path is not changed. - No change to what a checkpoint saves, when a flush is awaited, or the order of event commit, acknowledgement and checkpoint. The "at most one waiting checkpoint" behavior from #21411 is not changed. ## Verification - New `durable-prp-checkpoint-records.test.ts`: - A journal with 499 commands and 4,000 events gets one new command. The test counts `JSON.stringify` calls on journal records during the flush. Before: 4,499. After: 0 calls on existing records, at most 2 in total (the size check of the new command and its checkpoint record). The delta contains only `command:500`. The test then restores a new controller from the checkpoint and compares its records with a full conversion without the cache. I saw this test fail on `origin/master`. - A property-style test with 5 seeds and 600 random steps each: add, settle and remove commands (with `controllerSeq` renumbering), add, replay and evict events, streaming and usage events, `structuredClone` and spread copies of the state, header counters, the same value written again, and a key-order change. After each step, the records with the cache must be byte-identical to the records without the cache, in the same order. I checked that this test fails when the field comparison is removed (cache by object only). - Existing `durable-prp-control-plane.test.ts` passes. On this loaded machine, some 5-second timing tests time out with and without this change (they also time out on `origin/master`), and pass when I run them alone. - Benchmark: `PAPERCLIP_CHECKPOINT_FLUSH_BENCHMARK=1 pnpm exec vitest run src/control-plane/durable-prp-checkpoint.benchmark.test.ts` (from `packages/paperclip-runner`). Each case commits one new event and flushes with a no-op save, 200 times. CPU time is noisy (load average about 40), the byte and record counts are exact. | Journal | CPU per flush, before | CPU per flush, after | JSON bytes per flush, before | after | Records converted per flush, before | after | | --- | --- | --- | --- | --- | --- | --- | | 10 commands, 10 events | 207 µs | 64–80 µs | 20,975 | 2,465 | 20 | 1 | | 500 commands, 10 events | 1,874 µs | 505–511 µs | 375,068 | 2,466 | 510 | 1 | | 10 commands, 4,096 events | 14,013 µs | 1,655–2,343 µs | 5,174,786 | 2,473 | 4,106 | 1 | - `pnpm check:module-boundaries` passes. `tsc -p packages/paperclip-runner/tsconfig.json --noEmit` passes. ## Risks - The cache assumes that nested `payload`, `result` and `envelope` objects of journal records are not edited in place after they enter the journal. I checked the module: results are stored with `structuredClone`, envelopes with `structuredClone`, and events are replaced, not edited. This change also copies the payload in `queueCommand`. If a later change edits a nested object in place, the checkpoint could keep old JSON. The property test shows top-level edits are found. - Some per-record work is still proportional to the journal (a Map of part names and a field comparison for each record). It is about 0.4 µs for each record. Removing it needs dirty tracking in every state mutator, which this change does not do. - No change to the saved format, so old and new servers read the same checkpoints during a deploy overlap. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use (shell, file edits) in Claude Code. ## 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 - [ ] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
80f7989f4b |
fix: Wait for the SSH export pipeline to drain before importing the bundle (#20708)
> [!NOTE] > Opened by Prospector's automated issue-fix pipeline. A maintainer reviews and decides; nothing here merges on its own. ## Thinking Path - Issue #16567 reports a defect in paperclipai/paperclip. - Root cause, as the fixing agent read it: SSH process closure ended the destination stream while the progress Transform still held buffered bytes. Transfer success now requires both pipeline completion and SSH completion. - This pull request: Wait for the SSH export pipeline to drain before importing the bundle ## What Changed - `packages/adapter-utils/src/ssh.ts`: Use Node's pipeline to drain the stream chain, propagate stream errors, and release streams on failure while preserving SSH stderr errors. - `packages/adapter-utils/src/ssh-export-stream.test.ts`: Reproduced truncation and confirmed the fix passes with and without progress. Added failure cleanup cases; their final run and typecheck have not returned, and live SSH fixtures skipped because ssh is unavailable. ## Verification - Reproducing test(s), added in this PR: `packages/adapter-utils/src/ssh-export-stream.test.ts`, `packages/adapter-utils/src/ssh-export.test.ts` - They fail on the base commit and pass with the fix, each twice in a fresh sandbox. - 3 independent attempts wrote 3 reproductions; this fix passes every one of them. - The repository's compile command passes with the fix applied. - 10 existing test file(s) near the change failed, and fail on the base too, so they cannot show whether the change breaks them. - The full test suite passes except for the 17 file(s) that already fail on the base commit. ## Risks - Written by an automated pipeline, not a person: review it as you would an outside contribution. - Risk tier of the touched paths: 2. ## Model Used - codex:gpt-6.1-sol, opus, sonnet (Anthropic Claude, via Claude Code; OpenAI, via the Codex CLI), writing and checking the change in an isolated sandbox. - opus (Anthropic Claude, via Claude Code), reviewing it independently. ## Linked Issues Fixes #16567 #16567 also mentions, without asking this fix for it: - Add git bundle verify or a remote size check to provide a clearer diagnostic for short files. (The report calls this 'A cheap extra guard would be git bundle verify (or a size check sent by the remote script) before git fetch'; it is an optional additional safeguard. Empty or malformed output that ends normally still reaches the existing git fetch validation at packages/adapter-utils/src/ssh.) Other pull requests that name #16567: - #16613 (open): fix: prevent truncated SSH Git exports ## 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) - [ ] 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) - [ ] 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 - [ ] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [ ] I will address all Greptile and reviewer comments before requesting merge <!-- prospector:issue-fix v1 issue=16567 base=5ab98b006359 report=6118c07135df7c3a --> Co-authored-by: commitperclip[bot] <284812584+commitperclip[bot]@users.noreply.github.com> |
||
|
|
f4159e25e4 |
fix: Remove the unused OpenCode remote config guard and document host staging (#20045)
> [!NOTE] > Opened by Prospector's automated issue-fix pipeline. A maintainer reviews and decides; nothing here merges on its own. > [!WARNING] > This change crosses a trust boundary. See Risks. ## Thinking Path - Issue #17372 reports a defect in paperclipai/paperclip. - Root cause, as the fixing agent read it: The helper's unused targetIsRemote guard contradicted both callers, which intentionally stage configuration on the host and transfer it to remote targets as xdgConfig. - This pull request: Remove the unused OpenCode remote config guard and document host staging ## What Changed - `packages/adapters/opencode-local/src/server/runtime-config.ts`: Remove the unused option and contradictory guard while preserving both callers' staging behavior. - `packages/adapters/opencode-local/src/server/runtime-config.test.ts`: Add a regression for isolated staging, generated configuration, cleanup, and operator config preservation. Confirmed failure before the fix; all 50 focused tests pass afterward. Typecheck was started but has not returned a result. - `packages/adapters/opencode-local/README.md`: Document host staging for local and remote execution, remote asset transfer, path replacement, and host cleanup. ## Verification - Reproducing test(s), added in this PR: `packages/adapters/opencode-local/src/server/runtime-config.test.ts` - They fail on the base commit and pass with the fix, each twice in a fresh sandbox. - 3 independent attempts wrote 3 reproductions; this fix passes every one of them. - The repository's compile command passes with the fix applied. - 9 existing test file(s) near the change passed. - The full test suite passes except for the 16 file(s) that already fail on the base commit. ## Risks - Written by an automated pipeline, not a person: review it as you would an outside contribution. - Risk tier of the touched paths: 2. - It crosses a trust boundary. Check each crossing against what the issue asked for, and against who asked: - validation (packages/adapters/opencode-local/src/server/runtime-config.ts:107): Removes the targetIsRemote early-return check that prevented host configuration staging when explicitly set, although neither production caller supplies it. ## Model Used - codex:gpt-6.1-sol, opus, sonnet (Anthropic Claude, via Claude Code; OpenAI, via the Codex CLI), writing and checking the change in an isolated sandbox. - opus (Anthropic Claude, via Claude Code), reviewing it independently. ## Linked Issues Fixes #17372 #17372 also mentions, without asking this fix for it: - The remote per-run directory is never removed. (The report explicitly says: “Related but distinct: #14527 covers the remote per-run directory never being removed.”) A search of paperclipai/paperclip's open and closed pull requests found no other pull request that names #17372. ## 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) - [ ] 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) - [ ] 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 - [ ] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [ ] I will address all Greptile and reviewer comments before requesting merge <!-- prospector:issue-fix v1 issue=17372 base=ca34bed25797 report=0010c91463516eaf --> Co-authored-by: commitperclip[bot] <284812584+commitperclip[bot]@users.noreply.github.com> |
||
|
|
1e33415f67 |
test(runner): run Kimi layout suites once in prep (#20487)
<!-- All text in Simplified Technical English. -->
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work.
> - The Runner package has node:test suites that verify the pinned Kimi
Code native runtime layout.
> - `test:typescript:prep` selects each Kimi layout suite directly. The
same command also selects the `build-verified-provider-entrypoints`
aggregator. The aggregator imported the same four Kimi suites.
> - One command therefore registered every Kimi layout test twice.
Commit
|
||
|
|
8aaf983151 |
perf(db): send a transaction's work notifications in one statement at commit (#21436)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - The server signals queue work with database work signals, and it
sends a PostgreSQL notification for each signal so that another server
can wake during a deploy overlap
> - Each signal sends its own `select pg_notify($1, $2)`, inside the
open transaction, and waits for it
> - On staging this is the most-called statement in the database: 31.8
per second, 15.1 million calls in total against 7.5 million `begin`,
about 3.7 awaits per transaction
> - Every await inside an open transaction holds its locks and its
connection for one more turn of a saturated event loop
> - This pull request collects a transaction's notifications and sends
them in one statement just before commit
> - The benefit is at most one notification round trip per transaction,
with the same payloads delivered at the same commit
## Linked Issues or Issue Description
**What existing behavior does this improve?**
Database work signals send one `pg_notify` statement per signal, inside
the transaction.
**Subsystem affected**
`packages/db` work signals, used by every delivery queue in the server.
**Current behavior**
`signalDatabaseWork` and `notifyDatabaseWorkOnCommit` each run `select
pg_notify(channel, payload)` on the transaction and wait for it.
`notifyIssueRecovery` alone signals 7 queues per call, and a transaction
often calls it several times. A local legacy run (wake, start, 20 output
lines, finish) sends 424 notification statements. Staging measures 31.8
per second, 8.5 `begin` per second.
**Proposed behavior**
A signal inside a transaction records its payload on that transaction.
Before the outermost commit, the transaction sends every distinct
payload in one statement. Payloads and the channel are byte-identical to
today's, and PostgreSQL still delivers them only on commit.
**Reason and benefit**
At most one notification statement per transaction instead of one per
signal. Fewer awaits while a transaction holds its locks and its
connection.
**Breaking changes**
None. The listener protocol and the payload format do not change.
## What Changed
- `packages/db/src/work-signals.ts`: a signal records `(channel,
payload)` on the current transaction level. A released savepoint merges
its records into its parent; a rolled-back savepoint drops them. The
outermost transaction sends all distinct payloads in one statement
(`select pg_notify(channel, payload) from
jsonb_array_elements_text($2::jsonb)`) after its callback returns and
before commit. A transaction that signals nothing sends no extra
statement.
- The record lives on the transaction object only. A retried callback
gets a new transaction object and starts empty.
- `publishDatabaseWorkHint` (outside a transaction) is unchanged and
still sends at once.
- `packages/db/src/work-signals.test.ts`: tests on real PostgreSQL with
a LISTEN client.
## Verification
- `pnpm --filter @paperclipai/db exec vitest run
src/work-signals.test.ts`: 22 pass. 6 of the new tests fail on master.
- New tests (real PostgreSQL, LISTEN client, asserting what is delivered
as well as what is sent):
- Distinct topics in one transaction: one statement at commit. The
payloads delivered are identical to the format on master (`{version,
origin, topic}`), in first-signal order.
- A transaction that signals nothing: no notification statement.
- Savepoints: a released savepoint two levels deep keeps its topic. A
rolled-back savepoint drops its topic. A topic from a rolled-back
savepoint that the outer level signals again is still delivered.
- The callback throws: nothing is sent or delivered.
- The commit-time send fails: the transaction fails and rolls back its
write, and nothing is delivered.
- 500 distinct topics: one statement, all 500 delivered.
- Sequential, concurrent and retried transactions each start clean.
- Server suites that use notifications pass: `deployment-notifications`,
`run-start-handover`, `heartbeat-run-start-handover`,
`agent-runtime-hooks`, `legacy-controller-lease`,
`heartbeat-run-dispatch-lifecycle` (99 tests). Two of them hit statement
timeouts once on a loaded machine and then passed 41/41 when run alone.
- Before and after, one local legacy run (embedded PostgreSQL, process
adapter, 20 output lines 50 ms apart, uninstrumented pass, alternating
arms):
`TSX_DISABLE_CACHE=1 UNITS=legacy TASKS=50 AGENTS=3
NODE_OPTIONS=--expose-gc pnpm --filter @paperclipai/server exec tsx
scripts/query-cost/drive.ts` (harness from #21413)
| Per legacy run | Before (2 runs) | After (2 runs) |
| --- | --- | --- |
| Statements | 883, 883 | 474, 491 |
| `pg_notify` statements | 424 | 21 (one per signalling transaction) |
| Notification round trips per signalling transaction | about 20 | 1 |
| Transactions (BEGIN plus COMMIT) | 72 | 72 |
| Allocated | 81.1, 79.3 MB | 76.3, 74.3 MB |
| Wall time | 5.0, 5.2 s | 4.1, 7.7 s (noisy: loaded machine) |
Statement counts are exact and stable. Allocation fell by about 5 MB per
run (about 6%). Wall time varies too much on this machine to compare.
- Staging, measured by the coordinator (Neon statistics, 64 seconds):
31.8 `pg_notify` per second, 8.5 `begin` per second. At about 44 KB of
allocation per statement, notifications cost about 1.4 MB/s, about 2.4%
of the 57.6 MB/s. The allocation saving is part of that, about 2%, and
it is not the reason for this change. The reason is round trips inside
open transactions: at most one notification statement per transaction
instead of about 3.7. The per-second effect on staging is an estimate
until it is measured after deploy.
## Risks
- A failure of the notification send now surfaces at commit time, not at
the signal call. No caller catches errors around a signal call and
continues: the only `.catch` near a signal (`notifyBudgetStopsSettled`)
wraps a root-level call that is not in a transaction and already fails
before this change.
- Order within a transaction: notifications are sent in first-signal
order. A savepoint's records join its parent when the savepoint is
released, which matches the order of sequential code. Listeners do not
depend on order: each payload is an independent hint, and PostgreSQL
already removes duplicate payloads within a transaction.
- The notification is sent after the transaction's last statement
instead of in the middle. Delivery still happens only at commit, as
before.
Remaining work, not in this pull request: sending stops being useful
when no other server listens. The listener is open only during a startup
handoff, while this process owns a native execution, or during a
run-start handover, and a server drops its own notifications. A later
change could send only while an overlap is possible. It would have to
prove this interleaving: a new server announces itself, the old server
is still outside its own window, and the old server must start sending
before the new server relies on a hint. Otherwise the new server waits
for its next reconciliation pass.
## Model Used
- Claude Opus 5.5 (claude-opus-5-5), Anthropic, with tool use and code
execution in Claude Code.
## 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 (no
documentation describes the send timing)
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
|
||
|
|
d9b977baf2 |
fix(runner): answer a live Runner's commands while it replays its backlog after a reconnect (#21442)
**DO NOT MERGE until the coordinator confirms the Daytona validation.**
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - A native run on a remote sandbox is driven by a Runner process. The
server talks to it over PRP and saves the controller state in a
checkpoint.
> - After a release swap, the incoming server reconnects to Runners that
kept working while no server was attached. Each Runner first replays the
events it built up.
> - The server answered commands one at a time and only after every
event queued ahead of them. It wrote one checkpoint and one
acknowledgement per event. A recovery read sent at reconnect therefore
timed out at 30 s behind the replay, although the Runner was alive and
had answered.
> - A tool call that the previous server started and never answered
blocked every later command, and a failed close was replayed forever.
> - This pull request lets read and barrier answers pass the replay,
extends a wait while the replay still commits, acknowledges a replayed
burst once per batch, delivers every pending command at attach, settles
an orphaned tool call at attach, and retries a close whose drain timed
out.
> - The benefit is that a live Runner is reached after a late reconnect
instead of being declared unanswered and then replaced, which lost its
turn.
## Linked Issues or Issue Description
**What happened?**
Hosted staging, release swaps on 2026-11-13 (06:05Z to 09:45Z). For each
run that crossed a swap we measured the gap from the last Runner output
to the moment the new server recorded the Runner's process identity:
- gap under 150 s: 0 of 9 runs failed
- gap over 420 s: 14 of 15 runs failed
- median gap: 180 s for runs that resumed, 470 s for runs that failed
Authentication took under 1 s. The identity was recorded 4 to 7 minutes
later, because it is written only after the Runner answers `run.attach`,
`runner.drain` and the thread read. Those answers waited behind the
replayed event backlog. The failure codes on the first attempt were:
- `PRP command session.snapshot timed out` and
`codex_history_read_failed: thread/turns/list read failed` (all 10
`ingress` runs in the sample)
- `PRP command runner.drain timed out (runner connected; pending ahead 2
[semantic_tool.result] oldest 1023s)` on the retry
A separate class, `cleanup_quarantined` (23 failures in 3 hours, no swap
involved), showed "prior session cleanup remains incomplete" on every
retry, because a close that failed once kept replaying the same
rejection.
A live Daytona capture showed the stale `semantic_tool.result`: Codex
waited for the result of an exec tool call that the stopped server
owned. It was not an unacknowledged frame.
**Expected behavior**
A live Runner answers recovery commands within its deadline after a late
reconnect. A tool call left by an earlier controller is settled once
(with its durable receipt, or as interrupted with an unknown outcome,
never executed again). A close that failed only because its journal
drain timed out reaches its real outcome on the next close.
**Steps to reproduce**
1. Start a control plane with a commit callback that takes 50 ms per
event.
2. Connect a Runner that replays 1,000 events, then send
`session.snapshot`.
3. On master the snapshot times out at its 30 s deadline. The new test
`answers a command issued during a 1,000-event replay within its
deadline` does this.
**Paperclip version or commit**
`master` at
|
||
|
|
df1b12ad8e |
fix(runner): advertise flat tool schemas and stop repeated runner-side input rejections (#21398)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - Agents act through Paperclip tools. The runner shows each tool to
the model with an input schema and checks every call against that schema
before it runs
> - Some tool schemas had a root `oneOf`, `anyOf`, `allOf` or
`if`/`then`. `handoff_case` had no top-level `properties` at all
> - Some model hosts convert such a schema into an empty argument list.
The model then calls the tool with no arguments, and the runner rejects
the call as "Invalid tool input"
> - The repeated-failure guard from #21360 does not see these
rejections, because they happen in the runner before the call reaches
the control plane. The model sent the same rejected call again and again
> - This pull request gives every agent-facing tool a plain object
schema with named properties, checks the old cross-field rules with
named errors, and adds a runner-side guard for identical "Invalid tool
input" rejections
> - The benefit is that models on these hosts can see and send the
arguments, and a dropped argument ends in a clear correction or a stop,
not a long loop
## Linked Issues or Issue Description
**What happened?**
In a chat eval cohort with OpenCode and
`openrouter/deepseek/deepseek-v4.1-flash-1017`, the hosts Wafer and
DigitalOcean served most model calls. In the case handoff case,
`handoff_case` arrived with no arguments on all 10 calls across two
cases. The runner rejected each one with "must have required property
idempotencyKey, case, toAgentId, ...". The model's reasoning said that
the tool showed an empty property list. The model fell back to
`call_api`, but the reply waiter had already expired, so the case
failed. In the preserve-draft case, `request_human_input` was rejected 9
times in a row with the same root `then` error.
**Expected behavior**
Every tool that an agent sees has a plain object schema with named
properties, so every host can show its arguments. When the same call is
rejected twice with the same arguments, the model gets a correction that
lists the expected properties. On the third identical call, the model is
told to change the arguments or stop.
**Paperclip version or commit**
`master` at
|
||
|
|
0ece025749 |
perf(ci): cut repeated CPU work in the Runner support suite (#21390)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Every pull request runs the "Runner support suite" CI job (`pnpm test:e2e:runner:unit`) > - That job took 8.1–10.6 minutes, depending on the spot instance type, and was one of the last PR jobs to finish > - The target for every PR job is 7 minutes or less > - Measurement showed the suite is CPU-bound: each of the 693 Vitest files loads `@playwright/test`, the runner catalog and shared modules again in its own worker, and a few modules did quadratic or repeated work when they loaded > - This pull request removes that repeated work and reuses compiled code across workers > - The benefit is a job 75–86 s (13–16%) shorter on each instance type, with the same files, tests and assertions. It does not reach 7 minutes; the floor is explained below ## Linked Issues or Issue Description **What existing behavior does this improve?** The duration of the "Runner support suite" PR job. **Subsystem affected** CI, the Runner E2E support suite under `tests/runner-e2e/`, and one shared module (`packages/shared/src/connection-routing.ts`). **Current behavior** In 26 recent green PR runs the job took a median of 526 s on `m7i-flex.xlarge` (17 runs), 549 s on `m7i.xlarge` (3 runs) and 604 s on `m6a.xlarge` (6 runs). Vitest ran 693 files on 3 workers. The CPU was about 82% busy. 52% of the tracked time was module evaluation. **Proposed behavior** The job is shorter on every instance type. The same files and tests pass, and no assertion changes. **Reason and benefit** The PR workflow finishes sooner, so every pull request gets its result sooner. **Breaking changes** None. ## What Changed Measurements below are from the job's own runs on this PR. The spot fleet picks `m7i-flex`, `m7i`, `m6a` or `m5a` (all 4 vCPU); speed differs by up to 2x between them, so each comparison uses the same instance type. This suite has no Vitest retries, so a flaky test fails the job. ### Baseline (recent green PR runs on master, before this PR) | Run (job id) | Job | Test step | Vitest wall | Vitest split | | --- | --- | --- | --- | --- | | 131933126599 | 523 s | 474 s | 469.8 s | import 52%, tests 43%, transform 5% | | 131932775003 | 510 s | 461 s | 457.1 s | import 51%, tests 44%, transform 5% | | 131926764360 | 527 s | 479 s | 475.2 s | import 51%, tests 43%, transform 5% | | 131924082813 | 541 s | 496 s | – | – | | 131912527065 | 517 s | 468 s | – | – | - One Vitest invocation (693 files, 3 workers, the Vitest default of CPUs − 1), then 386 `node:test` tests in about 3 s. About 45–50 s of the job is checkout and dependency restore before the test step. - Summed tracked time was about 1,297 s for 470 s of wall time: effective concurrency 2.76 of 3 workers. Module evaluation was 674 s: 4,164 modules evaluated 77,699 times, because each file runs in a fresh isolated worker. - A CPU sampler (temporary, removed) showed 82% average CPU use with 3 workers and 95–99% with 4 workers. With 4 workers and no other change the wall time did not improve (455 s). The suite was CPU-bound, not idle. - Top modules by summed evaluation time (diagnostic run): `@playwright/test` 158 s over 390 files, `tests/runner-e2e/catalog.ts` 56 s over 141 files, `packages/shared/src/connection-routing.ts` 40 s over 317 files, `acpx/dist/runtime.js` 39 s. - Slowest files: `chat-rendered-links` 43 s, `results-root` 43 s, `chat-feature-flow` 43 s, `report` 40 s, `manual-private-transfer` 26 s, `private-framework-report` 24 s, `chat-catalog-fingerprint` 24 s, `hire-delegate-flow` 23 s, `source-sdk-evidence` 19 s, `unit-launcher` 16 s. No single file is near the 7-minute target, so there is no longest-file floor. - Slowest tests: the 256 MiB archive-cap test 23 s, the reload-once reply wait 20 s (plus two at 10 s), the documented pnpm validation 16 s, the retained name-only identity replay 14 s, the selected-case fingerprint replay 13 s. ### Changes, one at a time, with what each one bought 1. **Compile cache.** `run-unit.mjs` sets `NODE_COMPILE_CACHE` to `<tmpdir>/paperclip-runner-e2e-compile-cache` unless it is already set. Vitest workers and the Node processes that tests start reuse V8 compiled code. Node validates each entry against the source. `@playwright/test` evaluation went from 158 s to 107–124 s, `acpx` from 39 s to 26–27 s, and `zod` from 17 s to 9–10 s. Vitest went from 478 s to 441 s on a comparable run (this run also included change 2). 2. **Reuse import scans in the chat catalog fingerprint.** `fingerprintChatDependencyClosure` ran one esbuild parse for each of about 2,300 files on every call. The parse result is now cached by file path and content SHA-256 for the process. The fingerprint inputs and digest are unchanged. `chat-feature-flow` went from 43 s to 12–14 s, `chat-catalog-fingerprint` from 24 s to 11–13 s, and `chat-campaign-identity` from 13 s to 8 s. 3. **Hash each suite definition once.** `buildRunnerMatrix` computed `suiteDefinitionHash(suite)` for every execution, thousands of times, every time a test file loaded the catalog. It now computes it once per suite. The values are the same. `catalog.ts` evaluation went from 51 s to 9.6 s. Vitest went from 441 s to 389 s. 4. **Fake timers for the reload-once reply waits.** These three tests in `chat-rendered-links.test.ts` waited out the real 10 s render floor twice. They now advance fake time with `vi.runAllTimersAsync()`. The assertions on results, reload counts and attempt phases are unchanged. The file went from 43 s to 2.8 s. This freed a worker slot; on its own it did not shorten the CPU-bound run. 5. **Derive each aggregator identity once.** `connection-routing.ts` called `aggregatorAppIdentity` (two regex replaces) for every index entry for each of the 133 Arcade apps while it loaded, in 317 test files and in the server. The identity of each entry is now computed once. I compared the resulting `AGGREGATOR_SUPPORT_INDEX` (1,579 entries) and `searchAggregatorServices` results with master: they are identical. The SDK public input pins are refreshed for this change. 6. **Not shipped: four workers.** With the CPU work above removed, four workers cut Vitest from 379 s to 341 s (job 418 s). In the next run, `chat-installed-lane.test.ts` failed: the descendant of a timed-out preparation child was still visible to `process.kill(pid, 0)` right after cleanup. This is the process-tree-under-load risk, so the suite keeps the Vitest default of 3 workers. Docs: `tests/runner-e2e/README.md` describes the compile cache, how to turn it off, why the worker count stays at the default, and the cost of work at module load. ### Result | Run | Job | Test step | Vitest wall | Effective concurrency | | --- | --- | --- | --- | --- | | Baseline median, `m7i-flex` (17 runs) | 526 s | 465 s | 462 s | 2.76 | | Baseline median, `m7i` (3 runs) | 549 s | 476 s | 473 s | – | | Baseline median, `m6a` (6 runs) | 604 s | 535 s | 531 s | – | | This PR, `m7i-flex` (job 132007703795) | 440 s | 383 s | 379 s | 2.79 | | This PR, `m7i` (job 132027384596) | 474 s | 424 s | 420 s | 2.78 | | This PR, `m6a` (job 132033745288) | 526 s | 471 s | 466 s | 2.79 | | This PR, `m5a` (job 132040621237; dependency cache miss) | 880 s | 768 s | 761 s | – | The last three rows are the final configuration. The `m7i-flex` row is the same code before a README-only change. Module evaluation fell from 77,699 to 63,135 evaluations; part of that drop came from master changes merged into this branch, so I attribute time only to the per-change measurements above. ## Verification - CI on this PR is the experiment. Every push ran the real job on the real runner. The table above lists each run. - Local correctness checks, one process at a time: `chat-rendered-links.test.ts` (58 passed), the six chat fingerprint test files (37 passed), `catalog.test.ts` (92 passed), `packages/shared` `connection-routing.test.ts` and `connection-search.test.ts` (21 passed), and `node tests/runner-e2e/run-unit.mjs connection-auth.test.ts` (launcher path, 386 node:test passed). - Equivalence check for the connection routing change: the index and search results are byte-identical to master. - Flakiness: 10 runs of this branch with 3 workers (including the three final runs on `m7i`, `m6a` and the 2x slower `m5a`) passed with 0 failed tests and 0 timeouts. No port conflicts, OOM kills or `ps` timeouts appear in the logs. The suite has no retries. The 4-worker setting failed once in 3 runs, so it is not used. ## Risks - Low risk. No test is skipped or removed. No assertion is weakened. - The worker count is unchanged, so the load on process, port and temp-directory tests is lower than before (less CPU work per file). - The compile cache directory lives in the OS temp directory. Node rejects a stale or partial entry and compiles again. `NODE_DISABLE_COMPILE_CACHE=1` turns it off. - The connection routing change runs in the server too. It produces the same index, and it makes loading the module cheaper. ### What sets the remaining floor The job is about 45–55 s of checkout and dependency restore plus the Vitest run. The Vitest run is CPU-bound on 4 vCPU (2 physical cores). A fourth worker gives about 40 s more but fails a process-tree cleanup test under load (`chat-installed-lane.test.ts`, which checks the descendant immediately after cleanup). The largest remaining cost is per-file isolation: every file loads `@playwright/test` (about 0.3 s CPU each, 390 files), `zod` schemas from `packages/shared`, and `acpx` again. Vitest estimates that `isolate: false` would save about 140 s now. I did not use it: 116 files use `vi.mock`, and module state shared between files would make failures depend on which files share a worker. If more headroom is needed, the next step is a split across two machines (out of scope here because it changes `.github/`). Two duration-balanced halves (`vitest --shard=1/2` and `--shard=2/2`, about 190–235 s of Vitest each on `m7i-flex`/`m6a`) would put each job at about 4–5 minutes on every instance type except `m5a`. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Claude Code agent with tool use (shell, GitHub CLI) and extended reasoning. ## 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 (one test moved to fake timers; behavior changes are equivalence-checked) - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
84a4d345b3 |
refactor(docker): take the application image's Runner from the runner-artifacts stage (#21332)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The Runner is the part that executes agent work. `master` publishes it alone as the image `ghcr.io/paperclipai/paperclip-runner`, built by the `runner-artifacts` stages of the `Dockerfile` > - The application image does not use those stages. It has five stages of its own that compile the daemon, it builds the Runner again inside the server build, and it builds a second provider pack > - So one `Dockerfile` holds two recipes for the Runner, and the two results differ: another base image and another daemon binary > - This pull request removes the second recipe. The application image copies the Runner out of the `runner-artifacts` stage, which the same build runs once > - The benefit is one Runner recipe, and an application image whose Runner is the Runner the contract describes. A later pull request can replace the stage with the published image ## Linked Issues or Issue Description This is the second part of a chain. The first part is #21331, which removes the cache check that cannot run on this `Dockerfile`. Refs #21204, #21229, #21230 (the Runner image), #21306 (the no-rebuild mode of the vendor step), #21307 (the pull-request check of the application image) and #21312. No issue exists for this change. **Problem or motivation** The stages `rust-toolchain`, `rust-chef`, `runner-plan`, `runner-deps` and `runner-build` compile the daemon on Debian trixie. The server build then runs the full build of the Runner package. The `runner-provider-pack` stage builds the provider pack. The `runner-artifacts` stages do all of that again for the Runner image, on Debian bookworm, with a stripped daemon. **Proposed solution** Read only the `runner-artifacts` stage from the application stages. Build it inline in every build. Do not pass a published image yet. **Alternatives considered** - Pass the published Runner image to the build in this pull request. That needs the resolver, labels and a rule for commits without an image. It is the next step, and this one must be safe alone. - Keep the old stages as a fallback. Two recipes is the problem. ## What Changed - `Dockerfile`: remove the five stages. `build` starts from `base`. It copies `/runner-package/dist` and the build stamp from `runner-artifacts`, sets `PAPERCLIP_RUNNER_VENDOR_REQUIRE_CURRENT=1` and runs the vendor check before the first application build. - `Dockerfile`: `runner-provider-pack` starts from `base`. One `RUN` with a bind mount of `runner-artifacts` copies the pack, the receipt and the archives, and moves the large files to their own tree. `build` and `runner-provider-pack` now come after the stages they read. - `Dockerfile`: the three `COPY` instructions of `production` that take the pack are byte-identical. A test pins all three. - `Dockerfile`: `build` declares the build argument `PAPERCLIP_RUNNER_EXPECT_INPUTS_DIGEST`, empty by default, and one step runs the new `scripts/check-runner-image-expectation.mjs` on `/runner-image.json` of `runner-artifacts`. **This pull request declares the argument. No build sets it. The next pull request, which gives a published Runner image to the build, is its first user.** With the argument set, the build fails unless `runner-artifacts` is the published image of exactly those inputs. `docker-app-check.yml` also runs when the script changes. - Comments: the `Dockerfile` has 220 comment lines, down from 247. The comments of the two moved stages moved with them, unchanged, so the diff shows them as added lines. Eight comments that named a removed stage or a step that moved get the smallest correction. Two comments in `prepare-runner-vendor.mjs` and `build-inputs.mjs` said that the `Dockerfile` relies on the standalone rebuild; that clause is removed. - Tests: replace the two cargo-chef tests of `docker-build-stamp.test.ts` with three tests of the new shape. Update the pack test, `docker-image-layer-reuse.test.ts`, `vite-build-commit.test.ts`, the stage rules of `runner-image-identity.test.ts`, and the include-layout test of `runner-release-crate-cache.test.mjs`, which now reads `runner-artifacts-runnerd`. - Docs: `doc/DOCKER.md`, `doc/DEVELOPING.md`, and a new section "The application image" in `doc/runner-image-contract.md`. ## Verification All builds: `linux/arm64`, local, `--build-arg PAPERCLIP_BUILD_COMMIT=<sha>` with one commit for every build. The builds ran before the rebase onto `master`, on the head of #21310 as it was before it merged. `master` changed neither the `Dockerfile` nor an input of the Runner in between. - `docker buildx build --target production`, cold, before and after: 506 s and 410 s. Compressed size: 2,971 MB and 2,900 MB. - The image config and the text of all 33 history rows are identical. The row `COPY /provider-pack-transport/ /opt/paperclip-runner/ # buildkit` matches the pattern of `retained-provider-pack-oci.ts` exactly once. - A comparison of every file of the two images (path, type, size, mode, link target, and SHA-256 under `/app` and `/opt`). The differences are in "Risks". All other files are byte-identical, the root `node_modules` included. - From the image after: the four `/app/packages/paperclip-runner/...` paths and the contents of `/opt/paperclip-runner/` exist. `paperclip-runnerd --build-metadata` runs. `provider-pack.json` has `runnerSourceRevision` equal to the build commit and no `runnerInputsDigest`. The entry points `index.js`, `live/index.js` and `testing.js` of the Runner import. - The vendor step logged `reusing the current Runner build` in both of its runs. Every `Compiling` line of the log is in `runner-artifacts-runnerd`. - `--target build`, `--target runner-provider-pack` and `--target cloud` built. The `build` stage has no `gcc`, `cc`, `cargo`, `rustc` or `pkg-config`. - `--target runner-artifacts` and `runner-artifacts-slim`, before and after: `runner-image-layout.mjs check` and `runner-image-oci.mjs check-layers` pass on both, in `node:24.22.3-bookworm`. The daemon, `provider-pack.json` and the two stable layers have the same digests before and after. - Without a build commit: `build` and `runner-provider-pack` built, and the pack was skipped with the same message. This run was on the next branch of this chain, after the rebase. The last steps of `production` were not run for this case. - The expectation argument, on this `Dockerfile`, `--target build --output type=cacheonly`, after the rebase: - No argument, inline Runner: the build passes (233 s). The step passes. - Argument, inline Runner: the build fails at the step. The message says that the `runner-artifacts` of the build are not a published Runner image. - Argument `d4df566f…` and the published image of those inputs as `--build-context runner-artifacts=docker-image://ghcr.io/paperclipai/paperclip-runner@sha256:0cd8250b…`: the step passes, and the build runs no Runner stage. The vendor step then fails with `inputs changed since the recorded build`, because this tree differs from the tree of that image by one comment line in `build-inputs.mjs`. With that line put back, the same build completes, and the vendor step reuses the published build. - Another digest with the same context: the build fails at the step. The message names the inputs the image has. - A tree whose lockfile is behind the manifests of the Runner fails at the frozen install of the Runner stages, after 169 s, with the message that stage already had. - `docker buildx build --check`: no warning, before and after. `scripts/check-docker-deps-stage.mjs` and `scripts/check-node-version-policy.mjs` pass. - Tests, on macOS and in `node:24.22.3-bookworm`, after the rebase: the changed server test files with the other tests that read the `Dockerfile` or the image workflows (231 pass in 10 files on Linux), `vite-build-commit.test.ts` (10 pass), `runner-release-crate-cache.test.mjs` (11 pass), `docker-deps-postinstall.test.mjs`. The changed server test files typecheck. - Not run: the full test suite, any `linux/amd64` build, `podman`, the workflows and the release pipeline. Only CI can prove amd64, `docker.yml`, `docker-merge-group.yml`, `release.yml`, `docker-app-check.yml` and `runner-image.yml`. ## Risks - **The digest of the Runner image changes.** Its identity covers the whole `Dockerfile`. The next `master` push publishes a new `inputs-<digest>`. The contents do not change: see the comparison above. - **A build that is given a Runner of other inputs fails; it does not ship that Runner.** With the argument, it fails at the expectation step. Without the argument, it fails at the vendor step when the build inputs of the Runner differ. One comment line in `build-inputs.mjs` changes those build inputs in this pull request, so the image published before this pull request cannot be vendored into a tree after it. - **What a consumer of the application image sees** (measured on `linux/arm64`): - The daemon is the stripped binary compiled on Debian bookworm: 23.2 MB, was 36.4 MB, at `/app/packages/paperclip-runner/dist/bin/paperclip-runnerd` and at the vendored copy in `server/dist`. Its hash changes. It has no symbols for a crash backtrace. - `/app/packages/paperclip-eval-kernel/dist` is absent. Only `dist/eval/workflow-harness.js` of the Runner imports that package. Only `eval/index.js` exports the harness again, and no module imports that file. The server runtime bundle does not name the package. - The provider pack: `provider-pack.json` is byte-identical. Two provider executables and one licence file are hard links to their other copy in the pack, where they were separate files. One empty directory is absent. The pack is 195 MB smaller, and the layer of its large files gets a new digest once. - The transport archives have other bytes, because the Runner build gives large files a fixed timestamp. The receipt names the same files with the same digests. - Paths, modes, owners, the image config and the layer order do not change. - **What a contributor and a maintainer of the image build see:** - **The image build does not run the drift checks of the Runner.** Before, the server build ran the full `build` script of the Runner, so a failed drift check failed the image build on `master`. Now the Runner stages run only the output steps of that script. Repository CI runs the checks on every pull request. `.github/docker-context-checks.Dockerfile` and three exceptions in `.dockerignore` exist for those checks in the image build; a separate follow-up removes them, and this chain does not edit them. - **The dependency-caching layer of the daemon is gone.** Before, cargo-chef compiled the Rust dependencies in a layer of their own, and a change to the Rust source compiled only the Runner's own crates. Now such a change compiles the dependencies again (146 s here for the whole daemon). A change to the server, the UI or the Runner's TypeScript still reuses the compiled daemon. - **A lockfile behind the manifests of the Runner fails the build.** Before, `docker build` resolved it inside the image. The image workflows refresh the lockfile first. A local build prints the command to run. The next pull request makes this failure early and clear. - **The build needs more disk**: about 25 GB of builder storage here, was about 20 GB, with the image export. - Rollback: revert this pull request. Images that exist do not change. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Claude Fable 5.2 (`claude-fable-5-2`), from Anthropic, through Claude Code. The model used tools: it edited files, ran the tests and ran the Docker builds that this description reports. ## 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> |
||
|
|
2de4787f41 |
fix(db): release a postgres.js connection's receive buffer once it is fully read (#21432)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - The server reads PostgreSQL through postgres.js, with a patched
driver in `patches/postgres@3.4.9.patch`
> - A hosted server keeps about 0.5 GB of `external` memory (Buffers)
for its whole life, with 340 open database connections
> - postgres.js keeps a zero-length view of the buffer of each
connection's last read. The view keeps the whole buffer alive until that
connection reads again
> - An idle connection therefore pins the socket chunk or the whole
buffer of its largest recent message, which can be one MB or more
> - This pull request replaces a fully read buffer with an empty one in
the driver patch
> - The benefit is that idle connections hold no receive buffers. At 340
connections that each read a 1 MB row, external memory drops from about
320 MB to 0
## Linked Issues or Issue Description
**What happened?**
A hosted Paperclip server holds 455 to 520 MB of `external` memory for
its whole life. It has about 340 open database connections. Each idle
postgres.js connection keeps the buffer of its last read.
**Steps to reproduce**
1. Open 80 or 340 pool connections.
2. Read a 1 MB row on each connection.
3. Drop the results, let the connections go idle, and force garbage
collection.
4. Measure `process.memoryUsage().external`. Each idle connection still
holds about 0.95 MB.
**Expected behavior**
An idle connection holds no buffer from a result that it has completely
read.
**Environment**
postgres.js 3.4.9 with the Paperclip patch, Node.js 24 and 26,
PostgreSQL 17/18.
## What Changed
- `patches/postgres@3.4.9.patch`: in `data()` of `src/connection.js` and
`cjs/src/connection.js`, the driver now replaces the receive buffer with
an empty buffer when it has handled every message in it. A partly read
buffer is not changed. The other hunks of the patch are unchanged. I
regenerated the patch with `pnpm patch postgres@3.4.9`, edited the two
files, and ran `pnpm patch-commit`. I did not commit the lockfile change
from that command.
- `packages/db/src/postgres-receive-buffer.test.ts` and
`packages/db/src/__fixtures__/postgres-receive-buffer.mjs`: a regression
test for ESM and CommonJS on real PostgreSQL.
- It checks that results are reassembled correctly for a 3 MB row, for
161 row sizes around one 64 KB socket chunk (to land message boundaries
at the end of a chunk), and for 20,000 small rows that arrive many to a
chunk.
- It records a weak reference to each large receive buffer and checks
that none of them stays alive after the connection becomes idle.
- `packages/db/scripts/benchmark-postgres-receive-buffer.ts`: one
command that reports heap, external and rss per connection, before and
after large rows.
- `doc/DATABASE.md`: documents the new patch behavior, the test and the
benchmark.
## Verification
- Red/green: with the new line removed from the installed driver, the
fixture fails for ESM and CommonJS ("an idle connection must not keep
the receive buffer of its last result"). With the line in place it
passes, repeated twice for each format.
- `pnpm --filter @paperclipai/db exec vitest run
src/postgres-receive-buffer.test.ts
src/postgres-connection-recovery.test.ts`: 20 passed.
- `pnpm --filter @paperclipai/db exec vitest run src/backup-lib.test.ts
src/backup-lib-binary.test.ts src/client-disconnect-replay.test.ts
src/client-teardown-registry.test.ts src/work-signals.test.ts`: 36
passed. In 1 of 4 runs, the JavaScript backup test (COPY and cursor
reads) timed out on a machine with load average 20 to 34. It took 39 s
and 25 s with the change and 21 s without it in passing runs. Read
throughput is the same with and without the change: a 200,000-row select
plus a COPY TO STDOUT has a median of 319 and 348 ms with it, and 329 ms
without it.
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/prepared-statements-driver.test.ts
src/__tests__/prepared-statements.test.ts`: 5 passed.
- `pnpm --filter @paperclipai/db typecheck`: passed.
- Benchmark: `node --expose-gc --import tsx
packages/db/scripts/benchmark-postgres-receive-buffer.ts` with a 1 MB
row on each connection, numbers after garbage collection:
| Connections | External per idle connection, before | After | External
held in total, before | After |
| --- | --- | --- | --- | --- |
| 80 | 917 KB | 1 KB | 72 MB | 0 MB |
| 340 | 960 KB | 0 KB | 319 MB | 0 MB |
The rss per connection also went down (80 connections: 1,555 to 1,375
KB; 340 connections: 1,308 to 714 KB). The allocator keeps some freed
memory, so rss changes less than external memory.
## Risks
- Low risk. The change runs only when the buffer has no unread bytes. A
message split across chunks keeps the same reassembly path. The test
covers split messages, exact chunk boundaries and many messages in one
chunk.
- This saves external memory (Buffers outside the JavaScript heap). It
does not reduce `heapUsed`. It does not fix the out-of-memory crashes of
the hosted server by itself.
- The patch must be removed or ported when Paperclip upgrades
postgres.js. The test fails if a driver version keeps the buffer again.
## Model Used
- Claude Opus 5.5 (Anthropic, model ID `claude-opus-5-5`), used in
Claude Code with tool use (shell, file editing, local PostgreSQL), heap
snapshots and allocation measurement.
## Checklist
- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
|
||
|
|
594f9d3ec2 |
perf(runner): keep at most one checkpoint waiting behind a slow write (#21411)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - The native Runner control plane saves a checkpoint of each run's
controller state before it acknowledges an event or sends a command
> - Each new state revision captured a full snapshot and queued it
behind the write in progress
> - Inbound events wait for their own checkpoint, so they do not pile
up. Commands that the server queues do not wait, so they can
> - When the database or the event loop is slow, the queue of full
snapshots grows without limit, and events wait behind the whole queue
> - This pull request keeps at most one snapshot waiting per run. A
newer flush replaces the waiting snapshot of the same run
> - The benefit is bounded memory and fewer database writes under slow
persistence, with the same durability guarantee
## Linked Issues or Issue Description
**What happened?**
A hosted server ran out of JavaScript heap at intervals of 47 to 105
minutes. A retained-memory sample attributed about 16% of the memory
that stayed alive to `captureCheckpoint` (from `flushCheckpoint`) and to
`#capturePublishedState` in
`packages/paperclip-runner/src/control-plane/durable-prp-control-plane.ts`.
**Expected behavior**
Memory for checkpoints stays proportional to the number of live runs,
not to the number of state revisions that wait for a slow write.
**Steps to reproduce**
1. Create control planes with checkpoint persistence that takes 1 second
per write.
2. Commit events at 13 per second and queue commands at 2 per second for
each run.
3. Measure the heap in the middle of the run.
`node --import ./server/node_modules/tsx/dist/loader.mjs
scripts/benchmark-runner-checkpoint-backlog.ts` does these steps.
**Paperclip version or commit**
`master` at
|
||
|
|
e7e28ba241 |
feat(queue): show tasks waiting for an agent's slot as waiting, with their place in line (#21405)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Each agent runs at most `runtimeConfig.heartbeat.maxConcurrentRuns` tasks at once. Other runs wait in the agent's queue with status `queued` > - On hosted staging, one agent had all 20 slots full and 295 queued runs. Some tasks waited 3 to 7 hours and never started > - The UI showed these tasks as live or working: a pulsing "Live" badge in the task header and in task rows, a spinning "Working … for 4 hours" in the task chat, and "N live" counts that included every queued run > - People could not tell that work was waiting, why it waited, or what to change > - This pull request makes a deep queue an honest, visible state: "Waiting for Codie · 20 slots max · 41 of 295 in line · Configure" > - The benefit is that operators see the real state and the one setting that changes it ## Linked Issues or Issue Description Refs #21391, #21349, #21242 **What happened?** A queued run that never started looked the same as a running run. The task header, the task rows in lists and the inbox, the task chat and the sidebar counts all showed queued runs as live or working. **Expected behavior** A run that waits for one of its agent's concurrency slots shows that it waits. It names the agent, the agent's limit and the run's place in line, and it links to where the limit is set. The place in line is the order in which the server starts the agent's queued runs. **Why does it matter?** With a deep queue, the UI said "working" for hours while nothing ran. Operators could not see the cause or the fix. ## What Changed - Server: a new module `server/src/services/heartbeat/queued-run-line.ts` now holds the facts that the queued-run dispatcher orders by (`queuedRunDispatchFacts`). The dispatch path in `queue.ts` and the new "place in line" read use this one builder, so the line the UI shows is the dispatch order. The logic moved without change, including the recovery-share fix from #21391. - Server: `executionProjectionsForRuns` adds `agentQueue` (agent, limit, running count, position, queued count) and the label "Waiting for <agent>" with cause `agent_at_capacity` to a queued, never-started run when its agent has no free slot. It reads one batch of agents and running counts. Then it builds one line per full agent (at most 8 agents per read), using only the three context keys that ordering needs. No new polling. - Server: the place in line uses `queuedRunDispatchLine`, an O(n log n) replay of the dispatcher. The plain replay rescans the queue after each step, which is quadratic (measured: 3.6 ms at 300 runs, 76 ms at 3,000, 600 ms at 10,000, all on the event loop). Dispatch itself is unchanged: it stops after the free slots. Each agent's line is memoized for 5 s and shared by concurrent reads. In a preview worktree, the line applies the same creation-time cutoff as dispatch. - Server: the task list summary adds `runningDescendantCount` (descendants whose run started) next to `liveDescendantCount`. `liveDescendantCount` still decides whether a blocked parent is covered. The "n live below" chip uses the new count. - Shared: the new `ExecutionAgentQueue` type and the optional field `ExecutionProjection.agentQueue`. - Server: `/companies/:companyId/live-runs` lists running runs before queued runs, so a deep queue cannot push running work out of the 50-row limit. - UI: a new `AgentQueueWait` component shows "Waiting for Codie · 20 slots max · 41 of 295 in line · Configure", with no spinner and no elapsed timer. Configure opens the agent's Advanced view, where the run policy (`maxConcurrentRuns`) is edited. The task chat (both renderers), the run ledger and the Storybook story use it. - UI: the task header and the task rows (task list, inbox, legacy views) show a quiet "Waiting" instead of the pulsing "Live" when every live run of the task has not started. The full sentence shows on hover. "n live below" counts only started sub-tasks. A waiting sub-task still covers its blocked parent. - UI: the sidebar "N live" counts (Dashboard, agents) count only started runs. - UI: the task chat pill now names other server holds on a queued run (for example "Waiting for maintenance") instead of "Working". - Docs: DESIGN.md records the waiting-for-slot hold. - Storybook: `runs-agent-queue-wait` stories (full line, task chat, task row, one slot, mobile), with play checks. ## Verification - Red/green server test: `server/src/services/execution-projection-agent-queue.test.ts` (embedded Postgres). Before this change, the projection has no `agentQueue`. Now it checks the agent name, limit, running count, positions 1 to 4 in dispatch order (a person's retry first, then priority, not creation order), no wait while a slot is free, and isolation from other companies' runs. It also checks that the positions equal the line that the dispatch builder produces. - `pnpm exec vitest run` on the new test, `queued-run-dispatch-order`, `recovery-wake-herd`, `heartbeat-queued-run-claim-isolation` and `agent-live-run-routes` in `server/`. - Runtime cost (rule `runtime-dependency-boundaries`): the assumption is that the line stays cheap for a deep queue. `queued-run-line.test.ts` checks that `queuedRunDispatchLine` equals the dispatcher's claim-every-run order over 400 random queues (ages around the aging boundary, recovery and person runs, blocked runs, deferred share runs, all share counters). It also orders 10,000 runs in under 250 ms (the quadratic replay takes about 600 ms). The DB test projects a 300-run queue end to end with correct positions 1 to 300. Remaining limit: the line is up to 5 s stale. - Red/green: `issue-list-assignee-filter-routes.test.ts` now asserts `runningDescendantCount: 0` for a parent whose only live descendant is queued and never started. - UI tests: `liveIssueIds.test.ts` (waiting tasks, started runs keep "Live", no "running below" count for waiting sub-tasks) and `TaskChatLiveRunPill.test.tsx` (waiting line with no spinner and the Configure link, other holds named). The suites for the run ledger, sidebar, sidebar agents, task detail, task columns and task chat also pass. - The Storybook stories render in headless Chromium and their play checks pass. - After deploy: open a queued task on staging and confirm the waiting state. ## Risks - Cost on read: a projection read that includes a queued run of a full agent now reads that agent's queued runs (only small columns) and the dispatch facts. This is at most one line per full agent every 5 s, for at most 8 agents per read. Reads with no queued, never-started runs do no more work. - The place in line is the server's prediction of dispatch order. A claim that is refused at start time (a gate, a blocker) can let the next run start first. The position updates on the next refresh. - The process-local "declined aged claim" hint that the dispatcher uses is not visible to other servers, so the projection does not use it. This can change only the aged-oldest share step. - Configure opens the agent's Advanced view (the YAML run policy). The agent's Runtime tab hides the run-policy fields today. - Low risk otherwise: no schema change and no migration. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use (shell, file edits, headless browser) and subagents for the UI survey. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [ ] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
b7774a01cf |
fix: name activity actors and explain stopped tasks in plain words (#21406)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - People must never see internal jargon or raw ids in chat replies or
task comments
> - Chat eval cohort 12 found three sources: activity records show the
board user only as the raw id `local-board`, agents turn internal field
names such as `checkoutRunId` into words like "no checkout", and a
recovery notice says "the original assignee is not invokable"
> - The recovery notice appeared on 170 fixture tasks. It is not a loop:
each task got it once, because recovery blocked every in-progress task
of an agent that a person had paused
> - This pull request names activity actors, lists these internal terms
in the chat guidance, rewords the notice, and leaves in-progress work of
a manually paused agent alone
> - The benefit is plain replies and no false "blocked" tasks after a
person pauses an agent
## Linked Issues or Issue Description
**What happened?**
- `activity.audit-change`: the agent read `GET
/api/issues/{id}/activity` and wrote that the change was made by "the
board user identity (`local-board`)". Activity rows carry only
`actorType` and `actorId`.
- `activity.company-overview`: the agent wrote "no checkout" to explain
why no one is working on a task.
- `tasks.organize-open-work`: 170 of 501 fixture tasks got one system
comment each: "Paperclip cannot safely continue automatic recovery
because the original assignee is not invokable...". The owners were
paused by a person, and the stranded-work sweep blocked each in-progress
task. The existing rule already keeps `todo` work of a manually paused
agent, because blocking it fights the pause and strands the task after
resume.
**Expected behavior**
Replies name actors by name ("Board", a member's name, an agent's name)
and describe states in plain words. A person's pause does not block the
agent's in-progress work. A stopped-task notice says what happened and
what to do, in plain words.
**Steps to reproduce**
1. Change a task's priority as the local board user, then ask the chat
agent who changed it.
2. Pause an agent that owns in-progress tasks with no active run, and
let the stranded-work sweep run.
## What Changed
- `server/src/services/activity.ts`, `server/src/routes/activity.ts`,
`packages/shared/src/types/activity.ts`: company and task activity reads
add `actorName` (agent name, member name, "Board" for `local-board`,
"Paperclip" for the system). Raw ids stay in their existing fields.
- `server/src/services/agent-conversations.ts`: the existing "no raw IDs
or internal codes" rule now names checkout, native run and local-board
as internal terms, and tells the agent to name an actor by `actorName`.
- `server/src/services/recovery/service.ts`: the notice is now "<agent>
can't run right now, so Paperclip stopped this task instead of retrying
it. It is still assigned to them. To continue, resume or fix the agent,
or assign the task to someone else." The manual-pause skip now covers
`in_progress` as well as `todo` work with no run.
## Verification
- `cd server && npx vitest run
src/__tests__/heartbeat-paused-assignee-new-task.test.ts`: 4 pass. With
the old recovery service the two new tests fail (`expected 'blocked' to
be 'in_progress'`, and the old notice text).
- `cd server && npx vitest run src/__tests__/activity-service.test.ts -t
"names each activity actor"`: passes (the method did not exist before).
- `cd server && npx vitest run
src/__tests__/agent-conversations.test.ts`: passes.
- `src/__tests__/activity-routes.test.ts` has three tests that time out
locally on unchanged master code too; CI runs them.
- Paid eval run of `activity.audit-change` and
`budgets-costs.spend-breakdown` on a branch with this change.
## Risks
- The chat prompt grows by about 40 words. This is a small part of the
existing directive, so time to first token does not change in a
measurable way.
- A budget- or error-paused agent still gets the notice, now in plain
words. Only a manual pause keeps in-progress work as is; the sweep picks
it up after resume.
## Model Used
- Claude, claude-opus-5-5, with tool use and code execution in Claude
Code.
## 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 Opus 5.5 <noreply@anthropic.com>
|
||
|
|
944b1c64d7 |
feat(mcp): keep long provider calls durable with the MCP Tasks extension (#21263)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Agents use connected apps through Paperclip's MCP client in the tool gateway > - Some provider actions run for minutes: CI runs, deploys, batch jobs > - Today such a call is lost if it outlives the tool timeout or if Paperclip restarts or deploys mid-call, and a retry can start the work a second time > - Recovery must just work, and the target rate of runs that need a manual retry is 0% > - This pull request implements the MCP Tasks extension (`io.modelcontextprotocol/tasks`, 2026-07-28) in the MCP client > - The benefit is that a long provider call becomes a durable task: it survives timeouts, restarts, and deploys, and it is never started twice ## Linked Issues or Issue Description **Problem** A long provider tool call holds an HTTP request open. When it passes the tool timeout, or when Paperclip restarts or deploys during the call, the result is lost. The agent then often repeats the call, and the provider does the work again. **Proposed solution** Implement the client side of the MCP Tasks extension. Declare it on stateless tool calls. Store each returned task durably, wait on it during the call, keep polling it in the background after the call ends, and let the same call attach to the stored task instead of sending `tools/call` again. **Why it matters** CI, deploy, and batch actions are where agents lose the most work today. A durable task handle makes these actions safe across timeouts, restarts, and deploys, without a person. Refs #21119, Refs #21140, Refs #21219 (the MCP Apps, stateless MCP client, and MCP Skills work this builds on). ## What Changed - **Off by default:** MCP Tasks are behind the new instance experimental setting `enableMcpTasks` ("Durable app actions (MCP Tasks)"), default off. When it is off, Paperclip never declares the extension, nothing attaches to or polls tasks, pending rows do not block idle sleep, and behavior matches master. A test covers the off state. - `mcp-http.ts`: the tasks extension is declared per request, only on HTTP `tools/call` and `tasks/*`. Discovery, listings, and stdio servers do not declare it. `tasks/*` requests put the task ID in `Mcp-Name`. - New `mcp-tasks.ts`: parses task results, bounds the server's timing hints, sends `tasks/get`, `tasks/update`, and `tasks/cancel`, and seals task IDs at rest (AES-256-GCM, bound to company and connection; a keyed hash gives uniqueness). - New company-scoped table `tool_mcp_tasks` (migration `0475`, online-compatible). It links the task to the call, run, task, connection, and grant. It stores no provider result. - `tool-gateway.ts`: - A returned task is recorded, then polled up to the normal tool timeout. Its result goes through the same validation, redaction, and recording as a direct result. - Past the timeout, or when the caller disconnects, the agent gets `provider_task_pending` ("call again with the same arguments"). The task stays durable. - A call with the same endpoint, tool, full arguments, grant, agent, task, and actor attaches to the undelivered task. A retry with the same idempotency key also attaches, and it can never start different work under that key. - Input: URL requests show the provider link (Paperclip never answers them). Form requests become a question card; only the person's answer is sent with `tasks/update`. Other requests stop with a clear "needs input" error. - Stopping the run sends `tasks/cancel` and marks the task cancelled. A caller that only disconnects keeps the task. - `failed` becomes a tool error with the provider's message. An unknown task or a passed TTL becomes `provider_task_expired`. Every task stops being tracked at its TTL, or after 7 days at most. - Audit entries: `tool_gateway.task_started`, `task_input_sent`, `task_cancelled`. - New `mcp-task-work.ts`, registered at startup with the shared deadline scheduler: it resumes polling pending tasks after a restart, cancels tasks whose task closed or run was stopped, and wakes the assignee once when a task settles after its run ended. - Docs: `doc/connections/MCP-TASKS.md`, linked from `doc/connections/README.md`. Background work (per `rules/sleep-aware-background-work.mdc`): trigger is a task row write or release (`mcp-tasks` queue) and one startup pass. The deadline is the earliest `next_poll_at`. Cadence is the server's `pollIntervalMs` within 5 s – 5 min, with backoff; 5 min while waiting for a person. It is quiet when no row has a next poll. This is the narrow external-source exception: providers give no wake Paperclip can receive, and polling stops with the task. ## Verification - `server/src/__tests__/mcp-tasks.test.ts`: 20 tests with a fake 2026-07-28 server that returns tasks only to a client that declares the extension and checks `Mcp-Name`. They cover: - polling to completion, with the result identical to a synchronous call; - timeout, then an attaching call with no second `tools/call`; - a keyed retry, and a reused key with different arguments (refused); - restart mid-task: a fresh gateway with no in-memory state polls the row, wakes the agent once, and the recovered run gets the result once with no second `tools/call`; - no wake while the run is still going; - URL input (link, never answered), and form input (question card, then `tasks/update` with the answer); - cancellation by the run, by closing the task, and no cancellation when only the caller leaves; - failure, an unknown task, and TTL expiry (ends in under 3 s, no hang); - another agent never attaches; - synchronous calls unchanged and older servers never see the extension. - Red/green: with attach disabled, the timeout, keyed-retry, and restart tests fail (3). With `tasks/cancel` disabled, both cancellation tests fail (2). Before `tools/call` declared the extension, 13 end-to-end tests failed. All pass with the change. - Existing suites pass: `mcp-protocol-versions`, `mcp-http`, `mcp-apps`, `mcp-skills`, `server-startup-feedback-export`, `tool-gateway`, `tool-gateway-discovery-http`, `remote-mcp-connectors` (342 tests). - `tsc --noEmit -p server` is clean. `pnpm --filter @paperclipai/db check:migrations` passes (the migration is classified online-compatible). Snapshots pruned to five. - Agent boot and time-to-first-token: no change in the boot or first-turn path. The only new per-call cost is one indexed lookup on stateless tool calls. - Not run: a live provider that returns tasks. No public MCP server that returns tasks was available without new credentials. ## Risks - Shipped off by default. Review findings that only affect the setting-on path after this merge are tracked as follow-ups. - Migration: a new table with indexes and foreign keys to `companies`, `tool_invocations`, and `tool_connections`. Online-compatible. - Behaviour change only for servers that return tasks, which they may do only to clients that declare the extension. Older servers and stdio servers are unchanged. - A task that settles while nobody is waiting stays attachable for 1 hour, so a deliberate repeat of the same call within that hour collects the earlier result instead of starting new work. - The wake after a background task settles uses the generic task wake; the agent must call the tool again to collect the result. - Follow-ups: `notifications/tasks` via `subscriptions/listen`; sampling and roots input requests; showing a long action's progress in the task chat. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, in Claude Code with tool use (shell, file edits, local test runs). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [ ] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
8af889f612 |
feat(mcp-apps): view messages with consent, app context, full screen and provider tool icons (#21266)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - MCP Apps (#21119) show interactive widgets from MCP servers, such as Circleback meeting cards, with the agent's reply in the task chat. > - The first version deferred three parts of the MCP Apps spec. A widget could not propose a chat message (`ui/message`). It could not give the agent context (`ui/update-model-context`). It could not go full screen. > - Paperclip also ignored the `icons` that MCP servers declare on tools (SEP-973). > - The security review of #21119 showed what these features need from day one: explicit consent, untrusted-data labels and strict icon sanitizing. > - This pull request adds the three host features and provider tool icons, with those protections built in. > - The benefit is that widgets can now work with the person and the agent, not only display data. ## Linked Issues or Issue Description Refs #21119 **Subsystem affected** MCP Apps host (task chat widgets), tool catalog, run wake prompt. **Problem or motivation** The MCP Apps host refused `ui/message` (-32601), dropped `ui/update-model-context` and kept every view inline. MCP tool `icons` were not parsed or shown. So widgets could not ask the agent a follow-up, the agent could not see what the person selected in a widget, large widgets were cramped, and tool rows used only generic icons. **Proposed solution** Add consent-gated view messages, per-view app context delivered to the task's next run as untrusted data, a full-screen dialog, and sanitized provider icons. Details are under "What Changed". **Alternatives considered** - Send view messages with a new server route that creates the comment itself. Rejected: comment creation has many rules (agent chat ownership, paused conversations, queued delivery, wakeups, receipts). The widget's Send button uses the same send path as the composer. A small route then records which view the comment came from. - Keep the iframe in place for full screen with CSS. Rejected: chat containers can create containing blocks that break `position: fixed`. A moved iframe always reloads, so the dialog hosts a new frame instead. **Roadmap alignment** Continues the MCP feature work after #21119, #21140 and #21219. It does not touch the MCP Tasks work (gateway `tools/call` polling and elicitation). ## What Changed - **`ui/message`.** The host shows "<App> wants to send: …" with **Send** and **Dismiss** under the widget (and inside the full-screen dialog). Nothing is sent before the click. Send posts the text as the viewer's own comment through the chat's normal send path (`handleThreadAdd`). `POST /api/issues/:issueId/mcp-app-views/:viewId/messages` then logs `issue.mcp_app_message_sent`. It accepts only the caller's own comment on the same task, matched by `clientRequestId`, from the last 10 minutes. One proposal per view can wait at a time. The view gets `{}` after the send, or -32000 "Message sending denied" after Dismiss. Only `user` text up to 8,000 characters is accepted. - **`ui/update-model-context`.** `PUT /api/issues/:issueId/mcp-app-views/:viewId/model-context` stores the latest context per view in `tool_mcp_app_views.model_context` (text blocks and `structuredContent`, 16 KB at most). Updates are applied in order and deduped in the browser and on the server. A change logs `issue.mcp_app_context_updated`, and an empty update clears the context. The task's next run gets the three most recently updated contexts as an `## App context (untrusted)` wake-prompt section. The section quotes the data as JSON and says it is third-party data, not instructions. The read runs in parallel with the other run preparation and never fails the run. CLI adapters and the native runner render it through the same `renderPaperclipWakePrompt`. - **Who may do this.** Messages and context need a signed-in person with `issue:comment` on the task. Agents and API keys get 403. Other tasks and companies get 404. `message` and `updateModelContext` are advertised in `hostCapabilities` only where the viewer can send messages. - **Full screen.** The host advertises `availableDisplayModes: ["inline","fullscreen"]` and handles `ui/request-display-mode`. It honors the view's declared modes and answers with the resulting mode. It sends `host-context-changed` with `displayMode` and the container (fixed `height`/`width` in full screen), and again when that container resizes. A new **Open full screen** control sits next to "Widget from …". Full screen is a Paperclip dialog that closes with Exit, Escape or the view's own request. - **Provider tool icons.** `icons` on MCP tool descriptors are sanitized into the new `tool_catalog_entries.icons` column, outside the version hash, so a new icon never quarantines a reviewed tool. Only `https:` URLs and `data:image/*` URIs are kept, and SVG only as `data:`. A `data:` icon is at most 32 KB, a URL at most 2,048 characters, with at most 4 icons per tool. `GET /api/companies/:companyId/tool-icons` lists them keyed by gateway tool name, in one cached request per chat. Task chat tool rows and the app's actions list show them through `ProviderToolIcon`. It renders `<img referrerPolicy="no-referrer">` at a fixed size and never inlines markup. It checks the source again before rendering and falls back to the taxonomy icon. - **Schema.** Migration `0477` adds `tool_catalog_entries.icons`, `tool_mcp_app_views.model_context` and `model_context_updated_at`, all nullable. - **Docs and stories.** `doc/connections/MCP-APPS.md` documents the new behavior, and the finished items are removed from "Limits and follow-ups". `Tasks/MCP App views` has new stories: "View asks to send a message", "Full screen" and "Tool rows with provider icons". The fixture view now uses `ui/message`, `ui/request-display-mode` and `ui/update-model-context`. ## Verification - `pnpm exec vitest run server/src/__tests__/mcp-apps.test.ts server/src/__tests__/tool-catalog-publication.test.ts server/src/__tests__/openapi-routes.test.ts packages/shared/src/mcp-icons.test.ts packages/shared/src/mcp-apps.test.ts`: pass (embedded Postgres). These tests cover: - Context: stored, deduped, logged once, 413 when too large, cleared, scoped to the task and company, refused for agents (403), and rendered into the wake prompt as untrusted data. - Messages: attributed only to the viewer's own recent comment on the same task. A teammate's comment, an unknown request id or an old comment gets 404. An agent gets 403. - Icons: stored sanitized, and the version hash and status do not change. Another company sees nothing. - `cd ui && pnpm exec vitest run src/components/mcp-app/ src/components/ProviderToolIcon.test.tsx src/pages/apps/app-detail/`: 69 pass. These tests cover: - The host protocol for each new method: capabilities, consent wait, one proposal at a time, invalid input, ordered and deduped context, the size limit, and the display-mode rules. - The consent card (nothing sent without Send). - The full-screen dialog (one frame at a time). - Icon rendering (no-referrer `img`, no inline SVG, fallback). - `cd ui && pnpm typecheck` (including Storybook) and `tsc --noEmit` for the server: clean. - Red/green: the new route and host tests fail on `master`, where the routes do not exist and the host answers -32601 or drops updates. The icon descriptor test failed when the publication write was removed. - Not run locally: the full suite, and `packages/adapter-utils/src/server-utils.test.ts › runChildProcess › does not crash when the child closes stdin before a delayed write`. That test times out on this Mac with or without this change, so it is a local platform issue. CI covers both. ## Risks - Migration risk is low: three nullable columns, no backfill. - Every run on a task now does one extra indexed read, in parallel with the other preparation. Errors are logged and the run continues without app context. - If the attribution request fails after the comment is sent, the comment stays without the `mcp_app_message_sent` activity row. This is documented. - Switching between inline and full screen restarts the view, so state inside the widget resets. This is documented as a limit. - Icon names shortened with a hash by the gateway (very long names) do not match, and those rows keep the taxonomy icon. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use and code execution. One subagent (the same model) built the provider-icon part. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [ ] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
d9b42b50fd |
feat(presentation): let a person move a waiting continuation forward without starting a second run (#21373)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - When a run is interrupted, Paperclip records a fresh continuation and continues the task by itself. Since #21353 the task reads as continuing (`working`, no Retry) for as long as that continuation waits > - That is truthful, but a person has no control while it waits. On hosted staging one agent had 21 running and 209 queued runs, and continuations waited 30 to 110 minutes. Pacing (#21234, #21354) admits a waiting continuation into the agent's queue within minutes, so most of that wait is in the queue, behind other work > - #21353 removed Retry from this state because a Retry started its own run, which raced the continuation and could give the task two runs > - A Retry that observes the queued continuation run cannot start a run: admission sees a queued run and joins the Retry to it (`coalesced`, `runId` = that run). Under #21234's ranking, a queued run that a person joined starts ahead of system recovery and ordinary work > - This pull request keeps the continuing state and, once the queued continuation has waited 15 minutes, also offers Retry labelled "Move it forward now" > - The benefit is that a person can move a long-waiting task to the front of its agent's queue, and the click can never create a second run ## Linked Issues or Issue Description Refs #21353, #21348, #21234, #21354, #21264, #21320, #21200 **What happened?** On hosted staging, tasks with a recorded continuation waited 30 to 110 minutes behind a deep agent queue. The task showed "continuing" with no action. The person could only wait. **Expected behavior** The task still never shows "failed". After a long wait the person can move the waiting continuation forward. The click must not start a second run. ## Which states a Retry joins (established before building) I read #21348's fold (`foldWaitingRetriesIntoContinuation`) and its tests, and drove the real click path (`requestTaskRetry` followed by `resumeTaskRetry`, as the route does) in a probe against each record state: | Continuation state | What a Retry does today | Offer Retry? | |---|---|---| | Recorded, waiting for delivery (`continuationDelivery: "pending"`, no run yet) | The Retry is admitted at once as its own `task_retry` run, for every isolation (`fresh_isolated_workspace`, `writer_ended`, native). The delivery pass then marks the record delivered (superseded). #21348's fold never runs: it folds only a Retry that is still `deferred_issue_execution` when the continuation run is created, and only for `fresh_isolated_workspace`. Nothing keeps the Retry deferred, so the click races the delivery pass. | **No** (unchanged) | | Delivered, continuation run `queued` | `requestTaskRetry` sees the latest run is busy and records the Retry as `coalesced` into that run in the same transaction. No run is created; `resumeTaskRetry` acts only on deferred Retries. The run is now ranked as a person's (`joinedByUser` in `queue.ts`). | **Yes, after 15 minutes** | | Continuation run `running` | Same join, but the run already started, so there is nothing to move forward. | No | | Continuation ended | A Retry gets its own run (the existing failed-run path). | Existing behaviour | So the Retry offered here is joined by the existing busy-run admission in `requestTaskRetry`, not by #21348's fold. Its source run is the queued continuation itself (the run the presentation names as `observedRunId`), not the run the continuation was created for. ## What Changed - `server/src/services/task-interruption-presentation.ts`: for a task whose latest run is `queued`, created 15 minutes ago or more, and named as `continuationRunId` by a delivered fresh-continuation record, the projection returns `state: "working"`, `canRetry: true`, `retryAction: "move_forward"`, responsibility `system`, `observedRunId` = that queued run. It does not offer this when a person's wake already joined the run, when the run's agent is not the assignee, or when a person-owned wait applies (approval, reconnect, budget, pause and the others are checked first). Two small reads run only for queued runs older than 15 minutes. The existing restore-hold check that withdraws `canRetry` also withdraws `retryAction`. - `packages/shared/src/types/execution-projection.ts`: new optional `retryAction?: "move_forward"` on `TaskInterruptionPresentation`. It only changes the label; `canRetry` still decides whether Retry is offered. - `ui/src/components/ExecutionBlockerNotice.tsx`: a `working` presentation with `retryAction: "move_forward"` shows "Waiting for the agent to finish other work. Paperclip continues this task by itself." and a "Move it forward now" button that calls the same task Retry. Token-only classes; `pnpm check:token-gates` is clean. - One join-only action, `move_forward`, carried from the offer to admission (contracts kept in sync): - `packages/shared/src/validators/issue.ts`: `taskRetrySchema` accepts `retryAction: "move_forward"`. The route already passes the body to `requestTaskRetry`. - `server/src/services/task-retry.ts` (`admitTaskRetry`): right after the stale check, still under the task row lock and before any other Retry path, a `move_forward` Retry whose observed run is no longer `queued` or `running` returns `{ accepted: false, alreadyMovedOn: true, requestId: null }` and writes nothing. This block was cleared with the owner of Retry admission. The owner will later extend it so that "continuation recorded, not yet delivered" also counts as actionable, after their pending-delivery change lands (about two lines on their side). Until then this presentation never offers the button in that state, so the early return cannot misfire from our UI. - `ui/src/api/issues.ts` and `ui/src/hooks/useTaskRetry.ts`: the click sends `retryAction: "move_forward"` when the offer has it. `alreadyMovedOn` shows "The task already moved on, so nothing new was started. It now shows its current state." - What a click does at each timing: continuation `queued` → joined to that run (moves it forward); `running` → joined (nothing more to do); ended → "already moved on", nothing started. - A joined click cannot become a run later. The busy path writes it as `coalesced` with `runId` set to the continuation and `finishedAt` set (`task-retry.ts:456-461`). Promotion after a run ends (`heartbeat/run-control.ts:944` `releaseIssueExecutionAndPromote`; `modules/wake-queue/adapters/postgres.ts:89` `DEFERRED_WAKE_STATUS` and the selects near `:1358`), `resumeTaskRetry` (`run-control.ts:833-839`) and `resumeExecutionWaitComments` (`:876`) pick up only `deferred_issue_execution` wakes. - `ui/src/pages/Inbox.tsx`: the failed-run row does not show its Retry for this state. That row sends the failed run as the observed run, which is no longer the latest run, so its Retry would be refused as stale. - `doc/execution-semantics.md`: one paragraph on the offer, when it ends, and why there is none before delivery. ## Verification - Red (before the product change, new tests only), in `server/`: `pnpm exec vitest run src/__tests__/task-interruption-automatic-path.test.ts src/__tests__/recovery-wake-herd.test.ts`: 2 failed, 58 passed. Both failures are the missing offer (`canRetry: false`, no `retryAction`) for a continuation queued 15+ minutes. - Green after merging master |
||
|
|
681af53fa6 |
fix(runner): ask once more for a text answer when a turn that did tool work ends empty twice (#21359)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - The Runner drives OpenCode turns and decides when a turn has a final
answer
> - A turn can do real tool work and then end with no text and no
completion call
> - The driver asks once for a final response. That request can also
come back empty, and then the run fails
> - The person then sees a failed run, although the requested work was
saved
> - This pull request adds one bounded request, text answer first, for a
turn that already did tool work
> - The benefit is that finished work gets a reply instead of a failed
run
## Linked Issues or Issue Description
**What happened?**
An agent saved a requested document with a tool. Its next response had
no text and no completion call. The driver asked once for a final
response, and that response was empty too. The run failed with
`opencode_empty_response` and showed a failure message to the person.
**Expected behavior**
When the work is done, the person gets a short final answer. An empty
response is a recoverable state, not a hard failure.
**Steps to reproduce**
1. Use an OpenCode agent on an OpenRouter model.
2. Ask it to write and save a plan document.
3. Let the provider host return an empty response after the save, and
again for the correction.
4. See the run fail although the document exists.
**Paperclip version or commit**
`master` at
|
||
|
|
9fbfd93c9b |
fix(runner): record an OpenCode call's serving host when the call ends (#21358)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - OpenCode runs that use OpenRouter record which host served each
model call in the run log
> - Operators use this host to compare quality and failures between
OpenRouter hosts
> - About one in three of the first model calls in a turn had no
recorded host, while later calls had a host about 93% of the time
> - The provider proxy cleared the recorded host when each request
started, and this clear raced the usage report of the step before
> - This pull request records a call's host when the call ends, not when
the next call starts
> - The benefit is that each step's usage names the host that served it,
so host comparisons are complete
## Linked Issues or Issue Description
**What happened?**
In an evaluation cohort of OpenCode runs through OpenRouter, 128 of 356
first usage events in a run (36%) had no `usage.upstreamProvider`. For
later usage events the rate was 168 of 2,362 (7%).
Root cause:
- OpenCode 1.18.34 sends a step's final token count only 14 to 20 ms
before it sends the next model request. We measured this three times
with the real OpenCode binary and a local fake provider.
- The provider proxy cleared the recorded host when each request
started. The driver reads OpenCode's event stream. When the next request
started before the driver handled the token event, the clear won, and
the step's usage had no host.
- If the next call's first chunk had arrived first, the step's usage
would show the next call's host.
- The first call of a turn lost the race most often, because the driver
is busiest at turn start.
**Expected behavior**
Each step's usage names the host that served that step's model call. A
call whose host the proxy cannot read carries no host. A call never
inherits another call's host.
**Steps to reproduce**
1. Start an OpenCode session through the OpenRouter provider proxy.
2. Complete one model call that names a host.
3. Start a second model call and keep its response open.
4. Let OpenCode report the first step's usage.
5. See that the usage has no `upstreamProvider`.
**Paperclip version or commit**
origin/master
|
||
|
|
3fc2198759 |
fix(runner): treat tool-call markup in OpenCode text as an unexecuted call (#21361)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The Paperclip Runner drives OpenCode and turns its event stream into the run's progress, reply, and completion result > - Some model hosts return a tool call as raw tool-call syntax inside the assistant text, not as a structured tool call > - The OpenCode driver streamed that syntax as progress and accepted it as the final answer, so the run succeeded with markup as its reply and the intended tool call never ran > - This pull request treats leaked tool-call markup as an unexecuted, malformed tool call > - The benefit is that the person never sees raw call syntax as a reply, and the agent gets one bounded correction to make the call properly ## Linked Issues or Issue Description **What happened?** An agent run that uses an OpenRouter model can end with raw tool-call markup as its reply. The model meant to call the completion tool. The host put the call into the message text as DeepSeek DSML markup (for example `<|DSML| invoke name="...">`). The runner accepted that text as the final answer and settled the run as succeeded. The completion call did not run, so follow-up automation repeated the work. **Steps to reproduce** 1. Run an OpenCode agent with a DeepSeek model through an OpenRouter host that leaks tool-call syntax into text. 2. Let the model end its turn with a completion call that the host returns as text. 3. Look at the run reply. **Expected behavior** The runner does not show the markup and does not accept it as the reply. It tells the model that the tool did not run and asks it once to call the tool through the tool interface. **Paperclip version or commit** `master` at the time of this pull request. **Additional context** Today the markup streams as progress and becomes the run's final reply. The run succeeds without its completion call. ## What Changed - Added `tool-call-markup.ts` in the OpenCode driver. It detects leaked tool-call markup in one linear scan: DSML and DeepSeek call-token sentinels anywhere, and `<function_calls>` / `<tool_call>` wrappers only at a line start with a call body. It ignores fenced code blocks. - The driver holds markup (and a trailing fragment that can still become markup) out of streamed progress text. - A completed text part that contains markup is not a final-answer candidate. The driver emits the `opencode_tool_call_markup_discarded` diagnostic and records the position, so earlier text cannot become the reply either. - The turn then goes through the existing one-shot empty-response correction. The correction text says the tool did not run and asks the model to call tools only through the tool interface. - Regression tests: detection cases (recorded DSML shape, other families, prose and code-fence negatives, streaming monotonicity) and a driver case that replays the recorded markup. ## Verification - `cd packages/paperclip-runner && npx vitest run src/drivers/opencode/` passes (20 files, 263 tests). - Red/green: the new `tool-call-markup` case in `empty-response.test.ts` fails on the unchanged driver (the markup is selected as the final reply) and passes with this change. - `npx tsc --noEmit -p packages/paperclip-runner` passes. - Cost: the scan adds about 22 µs for each streamed update of a 20 KB answer with `<` on every line (43 ms over 1,960 updates), and 0.05 ms for each completed part. It adds no waits and does not touch boot or the start of a turn. ## Risks - Low risk. A real answer that puts DSML sentinels or a `<function_calls>`/`<tool_call>` wrapper with a call body outside a code fence is now treated as an unexecuted call. The correction then asks once for a proper answer. - If the model leaks markup again after the correction, the existing empty-response failure path applies. - No schema, API, or saved run-state change. ## Model Used - Claude (Anthropic), model ID `claude-opus-5-5`, used through Claude Code with tool use (shell, file edits, test runs). ## 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 Opus 5.5 <noreply@anthropic.com> |
||
|
|
cb94108484 |
fix(native): finish the run from a provider turn a timed-out start left running (#21338)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - A native Codex run talks to a remote Runner through a controller. A
deploy or a same-run retry can reattach a new controller to the live
Runner.
> - A slow turn start can make the first controller give up with
"runnerd did not report the provider turn identity". Codex still runs
that turn.
> - The retry reattaches the Runner and adopts that turn, because the
Runner accepted it for this run's latest turn.start.
> - If the adopted turn finishes while recovery still runs, the saved
checkpoint has no active turn. The runtime then tries to start a fresh
turn, and the run fails with "session cannot start another turn". The
Runner is lost and the task needs a Retry.
> - This pull request makes the runtime treat a terminal that the
recovered session newly settled as the adopted provider terminal when
the saved checkpoint bound no turn.
> - The benefit is that a turn which a timed-out start left running
finishes the same run on the reattached Runner, with its session
context, and with no second turn/start.
## Linked Issues or Issue Description
**What happened?**
On staging, Codex runs on a remote Runner lost the Runner after a
same-run reattachment. Each chain started with a turn.start that timed
out ("runnerd did not report the provider turn identity") while Codex
ran the turn anyway. After the reattachment, the run failed with a
protocol integrity fault (thread_binding_mismatch,
tool_binding_mismatch, or native_event_replay_conflict "Provider
authoritative notification item/started did not name its execution
owner"). The task then fell back to a fresh session and lost its
context. A local reproduction with the real runnerd and the fake Codex
app server shows the same trigger also fails when the abandoned turn
finishes during the reattachment: the runtime tries a new turn and fails
with "session cannot start another turn".
**Expected behavior**
A turn that a timed-out turn.start left running belongs to the same run.
The reattached run adopts it, binds its late notifications, and finishes
from its outcome. Recovery does not kill the Runner and does not need a
manual Retry. A real cross-run or cross-task binding violation still
fails closed.
**Steps to reproduce**
1. Start a native Codex run on a remote Runner whose provider is slow to
emit turn/started after it accepts turn/start.
2. Let the controller give up with "runnerd did not report the provider
turn identity" while the Runner stays alive.
3. Let the same-run retry reattach the Runner.
4. Let the provider turn start and finish after the reattachment.
5. See the run fail instead of finishing from the adopted turn.
**Paperclip version or commit**
master at
|
||
|
|
43aabb7080 |
fix(runner): keep configured secret values out of OpenCode output, storage and model requests (#21330)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - A person can configure a secret that Paperclip delivers to an agent's commands as an environment variable > - The value must stay out of what the agent runtime stores and what it sends to the model > - With the OpenCode runtime, a command that printed the variable put the value in OpenCode's tool output. OpenCode stored that output in its session database and sent it to the model. Paperclip's own run log already redacted it > - Paperclip did not tell the runner which configured values are secrets, so the runner could not protect them without also hiding ordinary settings > - This pull request sends secret names (never values) to the runner, filters exact secret values before OpenCode captures any tool output, redacts them from model requests, and tells the agent how to check a secret without printing it > - The benefit is that a configured secret stays out of model context and out of runtime storage, even when an agent prints it ## Linked Issues or Issue Description **What happened?** The `chat-features.runner-opencode.local.secrets.personal-secret` eval failed because the persisted-state scan found a configured secret value in OpenCode's session database. The person entered the value through the normal secret entry form. Nobody pasted it in chat. The agent ran a shell command that printed the environment variable it was given. Paperclip's run log redacted the value. OpenCode stored the raw output in its database and included it in the next model request. **Expected behavior** A configured secret must never reach model context or runtime persistence. Ordinary configured values must not be redacted. **Steps to reproduce** Configure a secret environment variable for an OpenCode agent. Have the agent run a command that prints the variable. Then search the OpenCode session data and the model requests for the value. ## What Changed - **Secret names cross to the runner.** `configuredEnvironmentProjection` takes the controller's secret key names and adds `PAPERCLIP_SECRET_ENV_KEYS`. This marker holds only the names of configured entries that came from secrets. It travels with the configured projection across the TypeScript and Rust runner boundaries (`configured-environment.ts`, `configured_environment.rs`). The server passes `secretKeys` in `runtime-execution.ts`. - **Command output is filtered before OpenCode reads it.** For a launch that has configured secrets, the runner sets OpenCode's `shell` to a small POSIX wrapper (`drivers/opencode/output-custody.ts`). The wrapper runs the shell OpenCode would use anyway. It sends stdout and stderr through an `awk` filter that replaces exact secret values. OpenCode never receives the raw bytes, so its streamed previews, its database and its model requests stay clean. The wrapper keeps the exit status. It does not wait for background processes. The values come from the environment that OpenCode already holds and are never written to disk. - **Other tool results are rewritten before they are saved.** A local OpenCode plugin rewrites completed non-shell results (file reads, searches, MCP results) in `tool.execute.after`. OpenCode runs that hook before it stores or returns the result. The wrapper refuses to run any command until the plugin has started for the current launch (per-launch nonce). So no command can write a secret to a file that a later read returns without filtering. - **Model requests are redacted as a second layer.** The OpenCode provider proxy removes exact secret values from the string values of each parsed model request. Field names and other literals are never changed. A quick byte scan for each value, raw and JSON-escaped, sends the original bytes unchanged when no value is present. - **The agent gets guidance.** Native task prompts list the configured secret names. They say to check a secret with `[ -n "$VAR" ]` and never to print, echo, log or write a secret value. - **No added startup delay.** The wrapper is content-addressed under the runtime directory and reused across launches, so it is not rewritten on every launch. OpenCode's plugin-dependency install is marked as already done, so loading the plugin does not add wait time to the first tool call. - **Only exact values are redacted.** Command output is filtered line by line, so each line of a multi-line value that has at least 4 characters is redacted too. If a configured secret has no line of 4 or more characters, the launch is refused with `opencode_output_custody_unavailable` instead of running unprotected. ## Verification - `packages/paperclip-runner/src/drivers/opencode/output-custody.test.ts` (10 tests): the wrapper filters stdout, stderr and a partial last line; keeps exit codes (7, and 143 for SIGTERM); filters each line of a multi-line value; refuses to run before plugin readiness or with an old nonce; returns at once when a background process keeps running; leaves ordinary values unchanged. The plugin rewrites nested results. Model-request redaction covers raw and JSON-escaped values and never changes field names or literals (a secret equal to `true` leaves `"stream": true` intact). Secrets the filter cannot match are refused. No value is written to disk. - `opencode-server-driver.test.ts`: one saved session launches three times. First with no secret marker (older controller), then with the marker, then with no marker again (rollback). The first launch is unchanged, the second applies custody, and the third launch still starts. This test fails without the driver change. - `configured-environment.test.ts`: the marker names only secret entries, crosses the runner spawn and OpenCode boundaries, reads as "no secrets" when absent, and is refused when malformed. Rust: `secret_name_marker_crosses_only_with_its_projection`. - `server/src/__tests__/configured-secret-guidance.test.ts`: guidance content, and no guidance when there are no secrets. - Real OpenCode 1.18.34 qualification (`PAPERCLIP_OPENCODE_QUALIFY=1 node --test scripts/qualify-opencode-runtime.test.mjs`). A fake model asks for a command that prints the secret and writes it to a file, then a read of that file. Unprotected baseline: the value is in the session database and in model requests (red). With custody: it is in neither, and the exit status is kept (green). - **Latency** (local, macOS, real OpenCode, 8 runs each): boot 629 ms vs 697 ms baseline; first model request after the prompt 678 ms vs 698 ms (no regression); first command 139 ms vs 191 ms; each later command +9 ms (36 vs 27 ms). Proxy cost per request when no secret is present (the normal case): 33 µs at 50 KiB, 164 µs at 300 KiB, 0.55 ms at 1 MiB, 2.3 ms at 4 MiB. When a secret is present: 91 µs, 0.48 ms, 1.6 ms and 6.8 ms. The scan runs only for launches that have configured secrets, and it adds nothing to OpenCode's own startup. - A narrow paid run of `chat-features.runner-opencode.local.secrets.personal-secret` on this branch is linked in a comment. ## Risks - **Previous-release story.** The marker is new and optional. A runner that receives no marker (older controller) launches exactly as before. An older runner drops the marker at its environment boundary. The change saves no new run or session state. OpenCode configuration is regenerated on every launch, so sessions saved before this change resume under custody (covered by the cutover test). Warm-process reuse keys include the marker, so a warm process from before the deploy is not reused for a run that has secrets. - **Commands go through the wrapper.** Output arrives line by line. Output written after the shell exits is dropped, which matches how OpenCode stops reading at exit. If `awk`, `mkfifo` or `rm` is missing, the launch is refused with `opencode_output_custody_unavailable` and does not run unprotected. - **Scope.** Only exact values are redacted. An agent that encodes a value (for example base64) is out of scope. The model-request layer applies when Paperclip routes the model through its proxy (OpenRouter and Paperclip connections). ## Model Used - Claude Opus 5.5 (Anthropic), model ID `claude-opus-5-5`, used through Claude Code with tool use and code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [ ] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
0986c3eb3a |
fix(native): let a same-run reattachment take over its own retained remote Runner cleanup (#21328)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Native runs on a remote sandbox (Daytona) use a detached `paperclip-runnerd`. After a recoverable failure, the server resumes the same run and reattaches to that Runner > - #20923 keeps an unreachable remote Runner alive when the failed attempt closes, so that the same-run reattachment can adopt it > - The same close also leaves the session in the in-process cleanup quarantine. The quarantine refuses every new session of the task, and that includes the reattachment that the Runner was kept for > - Close retries cannot settle it. After the first close fails, the Runner transport returns the same rejected close for every retry > - On staging, this was the largest failure class: 14 Codex runs in one hour failed with `native_session_cleanup_quarantined`, while only 5 runs succeeded. Each task then needed Retry > - This pull request lets the same run's reattachment to that Runner, in the same remote sandbox, take over its own retained cleanup > - The benefit is that the task continues on its own, with no spent attempt, no failed run and no Retry ## Linked Issues or Issue Description Refs #20923, #21031 **What happened?** A remote native run (Codex on Daytona) failed a turn with a recoverable error, for example `runnerd did not report the provider turn identity` or `native_finalization_missing: session returned no semantic result`. The close then logged `runner did not prove durable suspension before checkpoint` and `remote runner left alive unsettled for same-run reattachment`. Each later same-run reattachment was refused at admission: - When the close error was retryable, admission waited out the grace and failed with `native_session_cleanup_quarantined: prior session cleanup remains incomplete`. That spent a same-run attempt. After the attempt budget, the run failed. All close retries replayed the same failed close within milliseconds (`runner transport close requested: native session quarantined cleanup recovery`), so they could never settle the quarantine. - When the close error was `native_session_close_unrecoverable` (operator-required), the next attempt failed at once with `native_session_cleanup_quarantined: the previous session is still shutting down; Paperclip finishes the cleanup automatically and the saved work is kept.` That code is a permanent failure. "Paperclip finishes the cleanup automatically" did not happen in the process. Only a server restart (a deploy) removed the in-memory quarantine, and by then the run had failed and the task waited for Retry. Staging restarts every 20 to 45 minutes, so attempts often end mid-cleanup and meet this gate. **Expected behavior** The same run's reattachment adopts the Runner that its earlier attempt kept for it. It does not wait for a close that cannot settle, and it does not spend an attempt. The task continues without Retry. Other runs of the task and other sandboxes stay gated. **Steps to reproduce** 1. Start a remote native run, and let its turn fail with a recoverable transport error while the Runner cannot prove suspension. 2. The close keeps the Runner alive and quarantines the session. 3. The server schedules the same-run reattachment 30 s later. 4. The reattachment fails with `native_session_cleanup_quarantined`, and the task needs Retry. **Paperclip version or commit** Deployed Core `c730872974` on staging. Reproduced on `master` at `49f0030f06`. **Deployment mode** Hosted cloud (staging), Daytona remote sandboxes. **Agent adapter(s) involved** `paperclip_runner` native runtime with the Codex app server backend. ## What Changed - `packages/paperclip-runner/src/native-session-runtime.ts`: `executeNativeSession` takes a new option `retainedRunnerReattachment`. With a remote cleanup scope, admission retires quarantine entries that belong to the same run in the same remote scope. Removal stops later close retries. A close attempt that is still in flight stays an admission owner until it settles, so the old and new controllers do not overlap. Other runs, other sandboxes and local backends keep the gate. - `server/src/services/native-runtime/native-session-executor.ts`: sets `retainedRunnerReattachment` only for a `reattach_remote_runner` recovery of the same run. - `doc/execution-semantics.md`: records the takeover. - Tests: - `packages/paperclip-runner/src/native-session-runtime.test.ts`: four new cases. An operator-required close with a retained Runner. A retryable close whose retries replay one failure. A close that a deploy interrupts while it is in flight (the reattachment waits for it, then takes over). Controls: another run, a run without the takeover option and a local backend stay refused. - `server/src/services/native-runtime/native-session-executor.test.ts`: asserts that the option is set for a same-run remote reattachment and is not set for a fresh sandbox run. ## Verification - Red on `master` (runtime source restored): 3 of the 4 new runtime cases fail with exactly the two staging errors (`the previous session is still shutting down…` and `prior session cleanup remains incomplete`). The control case passes. - Red on `master` (executor source restored): the 3 executor assertions fail. - Green with this change: - `cd packages/paperclip-runner && npx vitest run src/native-session-runtime.test.ts` (294 passed) - `cd server && npx vitest run src/services/native-runtime/native-session-executor.test.ts -t "exact Stop cleanup|fresh sandbox|retirement"` (46 passed) - `cd server && npx vitest run src/__tests__/heartbeat-native-cleanup-admission-hold.test.ts src/services/quarantined-task-retry.test.ts src/__tests__/completed-turn-cleanup-hold-settle.test.ts` (61 passed) - `npx tsc --noEmit` in `packages/paperclip-runner` and `server` passes. - Staging evidence: runs `7b7ded99` and `27c487ef` show the sequence above in their events and logs. ## Risks - The takeover applies only when the server recovers the same run with `reattach_remote_runner` in the same remote cleanup scope. This is the case that #20923 keeps the Runner alive for. After a deploy the quarantine is already gone and the same reattachment runs today, so the takeover gives the in-process retry the same behavior as a restart. - A close attempt that is in flight is never overlapped. The reattachment waits for it within the existing admission grace. - The reattachment still verifies Runner ownership and its controller generation before it adopts the Runner. If the Runner is gone, the existing relaunch or reconciliation path handles it. - No persisted shape changes. Saved state from the previous release is not affected because the quarantine lives only in process memory. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use and code execution in Claude Code. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
22c9300dac |
fix(recovery): a run that fails before the agent is asked anything continues by itself on a fresh computer (#21297)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - A native run on a remote sandbox opens a provider session and then
waits at a launch gate before the first prompt goes to the provider
> - On remote OpenCode sandboxes the gate saves the provider launch
files; when that save fails, no prompt was ever sent
> - Today that failure ends as `native_session_interrupted` with
ambiguous recovery evidence, so the task goes blocked and the user must
press Retry
> - Nothing was sent to the provider, so nothing can be duplicated: the
system can safely continue by itself
> - This pull request types that failure, proves it from the Runner turn
ledger at the failure point, and continues the task on a fresh sandbox
in the existing interrupted-preparation lane
> - The benefit is that a setup failure before the first prompt no
longer needs a human, and the user sees plain words instead of internal
codes
## Linked Issues or Issue Description
Refs #21287
Refs #21304
**What happened?**
On a remote OpenCode sandbox, the provider launch-files gate failed
before the first prompt (for example
`native_provider_artifacts_transfer_timeout`). The run ended blocked
with a Retry banner. The run error showed internal codes and raw byte
counts to the user.
**Expected behavior**
A failure that happens before any prompt reaches the provider continues
automatically on a fresh sandbox. The task shows as working while the
continuation is pending. The visible text is plain and has no internal
codes or raw numbers.
**Steps to reproduce**
1. Use an OpenCode agent on a Daytona sandbox environment with
controller persistence.
2. Arm the crash point `native.provider_artifacts.before_capture` in
fail mode (or let the launch-file upload time out).
3. Start a task. The first run fails at the gate before any prompt.
4. On master the task goes blocked with Retry. With this change a
successor starts on a new sandbox and the task completes.
**Agent adapter(s) involved**
OpenCode (native runtime, remote sandbox).
## What Changed
- New typed cause `native_failed_before_provider_turn`
(`server/src/services/native-runtime/failed-before-provider-turn.ts`).
The executor raises it only when the launch gate fails, the run was not
cancelled, and the Runner turn ledger proves that no turn command was
issued. The proof is taken at the failure point, before the session
closes. In all other cases the original error is rethrown and today's
path stays.
- The executor quarantines the failed run's session root, so the
successor starts in a new root.
- `heartbeat/predecessor-retirement-fallback.ts` accepts the new cause:
it records the proof on `runnerProfileJson.failedBeforeProviderTurn`,
marks the run's reusable sandbox leases for replacement, and schedules
the successor in the existing `interrupted_preparation` lane (same cap
of 12 and the same backoff).
- `remote-workspace-unchanged-proof.ts` accepts the runner process,
runner command and pre-turn events only when that proof record is
present. It still refuses any turn evidence, an unsettled save by
another run on the same workspace, and setup writes. When the proof
refuses, the run's epoch is abandoned unapplied: the files are kept and
recorded, and the next run restores the last committed save into a fresh
root.
- When the proof refuses and the epoch is abandoned, the replacement
mark stays. The next acquisition replaces the sandbox. #21304's
retention hold makes `retireReplacedReusableSandboxLease` park the old
lease as `retained` instead of `pending_cleanup`, so the task continues
on a fresh sandbox and the sandbox that holds the abandoned files is
kept. When the proof holds (only the Runner's own session folder was
written), the old sandbox is replaced and cleaned up as usual.
- `task-interruption-presentation.ts` shows a pending
`interrupted_preparation` retry as `working` with no Retry until it is
due (plus the dispatch grace).
- The visible run error is now plain: "Setting up the computer took too
long, so the task is continuing on a fresh one." (for a setup timeout)
or "The computer could not be set up before the agent started, so the
task is continuing on a fresh one." The technical cause code stays in
`runnerProfileJson.failedBeforeProviderTurn.technicalCause`, the server
log and the run log.
- New crash point `native.provider_artifacts.before_capture` (fail mode
throws the typed transfer timeout at the gate).
`tests/runner-e2e/source-sdk-public-inputs.json` is refreshed for the
changed registry file.
- `tests/restart-chaos/main.ts`: `RESTART_CHAOS_EXTERNAL_CRASH_CONTROL`
lets an outside driver arm fail-mode crash points without a restart
fault.
## Verification
Local (targeted):
- `server/src/__tests__/heartbeat-native-predispatch-retry.test.ts`: 8/8
pass. New cases: fresh remote sandbox and fresh plugin-task sandbox
continuation (now also asserts the plain visible text with no
identifier-looking tokens, and the technical cause in the proof record),
the ambiguous hold when the ledger cannot prove no turn, and backoff
plus the lane cap.
- `server/src/services/remote-workspace-unchanged-release.test.ts`:
27/27 pass. New cases: hand-on when the ledger proves no turn; refusal
on a recorded turn, an unsettled predecessor save, and setup writes. Two
more cases follow the marked lease through the next acquisition's
replacement decision (`readReplaceBeforeReuseMarker` +
`reusableSandboxReplacementPlan` + `retireReplacedReusableSandboxLease`)
and then through `sweepPendingCleanupLeases`. "replaces the marked
sandbox when the failed run provably left its files unchanged": the old
lease goes to `pending_cleanup` and the sweep destroys it. "continues on
a fresh sandbox and parks the one that holds abandoned files, which
cleanup leaves alone": the old lease is `retained` with the
abandoned-files reason and is held by the receipt, the sweep does not
destroy it, and the file is still there.
- Red without the product change (product files reset to the base, tests
kept): 8 failed, 25 passed of 33. All 8 failures are the new cases. The
visible-text assertion alone was red on the previous commit: the error
read "The computer could not be prepared before the agent started
(native_provider_artifacts_transfer_timeout: the upload of 536870912
bytes did not finish within 120 s). The task continues on a fresh
computer."
- `task-interruption-presentation.test.ts`,
`native-provider-artifact-gate.test.ts`,
`crash-point-call-sites.test.ts`: 79/79 pass.
`packages/shared/src/crash-points.test.ts`: 16/16.
`tests/restart-chaos/crash-points.test.ts`: 12/12.
- `tsc --noEmit` clean for `server`, `packages/shared` and
`tests/restart-chaos`.
Daytona (local servers, Daytona sandboxes, image `sha256:787c3e9c…`,
these commits rebased onto
|
||
|
|
41998d551c |
feat(plugins): send the claimant's credential on plugin task resume (#21335)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Plugin environment drivers run agent tasks on remote computers, and a warm follow-up run resumes a parked Runner through the `resume` task operation > - `resume` carries only the durable identity and a bootstrap ticket, which is enough while the parked Runner process is still alive > - A provider sometimes has to start the Runner again to resume the session: after it moved the parked session to a new sandbox, or after the computer rebooted > - A Claude Runner cannot start without its credential, and today only the portable handoff path (`handoffCredential`) delivers one > - This pull request lets a provider opt in to receiving the claimant run's harness credential on `resume` > - The benefit is that a provider can continue a parked session on a new computer without Core orchestrating a handoff ## Linked Issues or Issue Description Refs #21289 Related: #21305 **What existing behavior does this improve?** Warm resume for plugin task providers that restart the Runner to resume a session. **Subsystem affected** Plugin SDK environment task schema, the server's plugin Runner task owner, and the plugin environment task docs. **Current behavior** `submit` can carry the harness credential (`credential`), but `resume` cannot. A provider that must start the Runner again on resume has no credential for a Claude task. **Proposed behavior** A provider that returns `resumeCredentialVersion: 1` from `describe` receives `credential` on `resume` whenever Core would send it on `submit`, resolved for the claimant run. Other providers see no change. **Reason and benefit** Providers can restart a Claude Runner on resume without the Core-run handoff protocol. **Breaking changes** None. The field is opt-in: the SDK worker parses operations strictly, so Core sends it only to providers that advertise the capability. ## What Changed - `resume` gains an optional `credential`, with the same schema and validation as `submit`'s. - `describe` gains an optional `resumeCredentialVersion: 1` capability. - The plugin Runner task owner adds the credential on `resume` when the provider advertised the capability and Core resolved a credential, using the same resolution as `submit` (`preparePluginRunnerCredentials`). After a warm rebind, the claimant run's credential is sent. - `doc/plugins/PLUGIN_ENVIRONMENT_TASKS.md` documents the field and its handling rules. - The runner-e2e SDK public-input pin is updated. `handoffCredential` on the session handoff path is unchanged. ## Verification - SDK vitest `tests/environment-task-release-resume.test.ts` and `tests/environment-tasks.test.ts` (68 passed): `resume` accepts and rejects the same 11 credential cases as `submit`; the capability is optional and rejects other versions; a resume credential reaches the plugin through the serialized worker RPC. - Server vitest `plugin-runner-task.test.ts` and `environment-task-runtime.test.ts` (151 passed): credential sent with the capability and a resolved credential; omitted without a credential or without the capability; the rebound claimant's credential is sent; the credential appears in no metadata write and not in the sanitized error, even when the worker error echoes it. - `native-session-executor.test.ts -t "uses a task-only"` (5 passed): the executor forwards the capability to the owner. - runner-e2e `source-sdk-evidence.test.ts` and `source-sdk-public-type.test.ts` (46 passed). - `tsc --noEmit` for `packages/plugins/sdk` and `server`. - Not run locally: the full suite and `pnpm verify`; required CI covers them. ## Risks - No server-side provider check on resume, unlike `submit`: the lease has no reliable harness at resume time. Protection relies on the owner, whose rebind refuses a changed harness, account or credential identity. - The credential is the claimant run's current one, which can be newer than the one that started the parked Runner. That is intended. - A provider must advertise the capability only after its SDK pin includes this schema; roll Core out first. - Rollback: revert this pull request. No migration. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use (shell, file edits, test runs), implemented by a sub-agent and reviewed before opening. ## 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 Opus 5.5 <noreply@anthropic.com> |
||
|
|
7e7452e88f |
fix(native): keep a reattached Runner alive when its provider recovery deadline ends (#21321)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - Native Codex runs on remote sandbox Runners. A same-run reattachment
adopts a live Runner after a failed attempt or a server deploy.
> - On staging, a remote Codex Runner is often gone when the next
attempt reattaches (`process_verification` / `process_not_running`). The
task then continues in a fresh session and loses its context.
> - The deploy does not stop the Runner. The logs show `controller
authority detached for restart; durable runner left alive`, and the new
controller adopts the same Runner after the deploy.
> - Our own cleanup stops it. The adopted Runner answers its recovery
reads slowly while its in-flight turn runs. The 900 s provider recovery
deadline then aborts the recovery, and the abort closes the transport
with `turn.stop` and `runner.suspend` and signals the process.
> - This pull request makes the recovery deadline detach from the
Runner, as a recovery read timeout already does. The server marks the
failure as an unanswered adopted Runner, so the next attempt replaces
the Runner from its saved journal and resumes the same provider thread.
> - The benefit is that a deadline no longer kills a live Runner and no
longer forces a fresh session. The task keeps its session context.
## Linked Issues or Issue Description
Refs #21314, #21272, #21161, #21023
**What happened?**
Codex runs on Daytona remote Runners failed often on staging. In three
sampled chains (attempt 2 of each), the same-run reattachment adopted
the live Runner, authenticated in under 1 s, and then waited the full
deadline: `native session provider recovery timed out after 900000ms`
(909 s, 930 s and 915 s). The deadline cleanup sent `turn.stop` and
`runner.suspend` (`provider turn stop timed out before runner
suspension`). The next attempt found the Runner gone 25–180 s later
(`process_not_running`, `runnerLifecycle: ready`, empty stderr) and
continued in a fresh session. During the 900 s wait, the in-flight turn
was still running Paperclip tools (`tool.execute` spans at 04:43 in a
recovery that started at 04:29).
**Expected behavior**
A remote Runner survives a recovery deadline and a control-plane deploy.
The next attempt continues the same provider session. A Stop still stops
the Runner.
**Steps to reproduce**
1. Start a Codex run on a remote Runner and let a turn start.
2. Fail the attempt so that its close keeps the Runner (for example, a
turn start that outlives its bound).
3. Let the same-run reattachment adopt the Runner, and make the Runner
stop answering recovery commands.
4. Let the provider recovery deadline expire.
5. See that the Runner process is gone and the next attempt reports
`process_not_running`.
**Paperclip version or commit**
master at
|
||
|
|
d9a4bb23fe |
fix(runner): wait for a slow Codex turn start while it reports progress (#21329)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Codex agents run through the Paperclip runner, and the server-side transport starts each provider turn > - After Codex accepts a turn, the transport waits a fixed 30 s for that turn's `turn/started` before it reports the turn identity > - Codex starts its MCP servers before it starts the turn, so a healthy cold start in a loaded sandbox often takes longer than 30 s > - The transport then failed a live turn with `runnerd did not report the provider turn identity`, and the abandoned turn's late notifications broke the reattachment (`did not name its execution owner`, `runner_harness_state_mismatch: resumed_not_suspended`) > - This pull request sizes the start window to the measured cold start and extends it while the provider keeps reporting startup progress > - The benefit is that slow but healthy Codex starts succeed on the first attempt, and a dead start still fails at a bound ## Linked Issues or Issue Description **What happened?** On staging, Codex runs on Daytona failed at turn start with `native_session_interrupted: runnerd did not report the provider turn identity`. The run log shows the same sequence each time. The runner accepts the turn. Codex then reports startup progress (a bubblewrap config warning, `account/updated`, and `mcpServer/startupStatus/updated` failures for an MCP server that is not logged in) for about 30 s. The transport gives up 30 s after acceptance. A few seconds later, Codex sends the turn's `turn/started`, which now arrives at a closed turn (`protocol_failure:turn_binding_mismatch`). The same-run reattachment then hits that orphaned turn. It fails with `Provider authoritative notification item/started did not name its execution owner.` or `runner_harness_state_mismatch: resumed_not_suspended`. Of 198 recent runs in the staging company, 52 contain this turn identity failure. In 68 successful starts, submit to `turn/started` took p50 25 s, p75 37 s, p90 50 s, p95 54 s and max 76 s. The fixed 30 s wait sits near the median. **Expected behavior** A slow but healthy Codex start succeeds. A start that makes no progress, whose Runner exits, or that the runner fails still fails at a bound and recovers through the normal same-run resume. **Steps to reproduce** 1. Start a Codex turn whose provider accepts the turn but sends `turn/started` after the 30 s default window (on staging: several MCP servers and a loaded sandbox). 2. Let the provider report startup notices during the wait, and let the runner not prove the accepted turn live in time (on staging no turn was adopted). 3. See `runnerd did not report the provider turn identity`, then the reattachment conflict. The new tests reproduce this with the fake Codex app server (`--turn-started-delay-ms` with `--turn-started-progress-ms`) and a runner snapshot that cannot prove liveness. **Paperclip version or commit** Staging Core `c730872974` (`2026.1106.0+2253`). Base of this PR: `origin/master`. **Deployment mode** Authenticated, public, managed cloud (staging). Remote runner on Daytona. **Agent adapter(s) involved** `paperclip_runner` with the Codex provider (`gpt-6.1-sol`). ## What Changed - `runnerd-codex-transport.ts`: the default wait for an accepted turn's `turn/started` is now 90 s (measured max 76 s), not 30 s. An explicit `turnStartTimeoutMs` keeps its old bound. - The wait restarts its window each time the runner commits a provider notice, or a runner diagnostic that names the accepted turn. The total wait stops at 180 s (option `turnStartProgressCeilingMs`, so tests can lower it). A provider relaunch after the accepted `turn.start` does not extend it. - The adoption check (runner snapshot proves the accepted turn live) now runs before each window end, not only before the first one. A Runner exit and a runner failure of the pending turn still fail at once. - `fake-codex-app-server`: new `--turn-started-progress-ms` flag sends `mcpServer/startupStatus/updated` failures while it delays `turn/started`. - `doc/execution-semantics.md`: documents the start window, the progress rule and the staging measurements. ## Verification - Red on `origin/master` transport (with the new fake flag): `keeps waiting for an accepted Codex turn while its startup keeps reporting progress` failed after 4.6 s, and `gives a silent Codex cold start the measured default start window` failed after 30.9 s. Both failed with `runnerd did not report the provider turn identity`. - Green: `npx vitest run src/live/runnerd-codex-transport-deadlines.test.ts` passes 9/9. This includes a ceiling test: provider notices every 1 s and no `turn/started` fail at an 8 s test ceiling, and the test goes red with the ceiling cap removed. It also includes the existing adoption, no-adoption-within-bound and runner-failure tests, and a new test that a silent start still fails within its bound. - `npx vitest run` on the adoption, cut-turn-start, stall, turn-start-timeout-retention, remote-retention, restart-continuation and controller-outage transport suites passes 48/48. - `npx vitest run src/live/runnerd-codex-transport.test.ts src/live/live-session.test.ts src/live/turn-stream.test.ts`: 391/392 pass. The one failure (`stops a lost runnerd's provider and escaped tool job from its lineage journal (journal=true)`, 1 s, process-lineage timing under full-suite load) passes when run alone, both on this branch and on `origin/master`. - `tsc --noEmit` for `packages/paperclip-runner` and `cargo fmt --check` pass. ## Risks - A silent dead start (no Runner exit, no provider output, no runner failure) now fails after 90 s, not 30 s. The Runner exit and runner-failure paths still fail at once, so this applies only to a provider that stops without a trace. - A provider that keeps sending notices but never starts the turn waits at most 180 s. - No schema, API or UI change. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use (shell, file edits, browser reads of staging run data). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [ ] I will address all Greptile and reviewer comments before requesting merge Refs #21272, #21120 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
314b893678 |
fix(native-runtime): deliver assigned gateway tools to every native harness through the PRP relay (#21274)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work.
> - An agent can have app connections. Paperclip gives the agent the
tools of those apps through an MCP gateway, with its approval and audit
rules.
> - Native harnesses reach the gateway in two ways today. In the relay,
the server keeps the gateway token and offers the tools over the
authenticated Runner channel. In the direct way, the server gives the
gateway URL and a bearer token to the harness.
> - Which way a harness uses comes from a list of special cases that
grew one harness at a time. Local Codex and all ACPX agents use the
direct way. The others use the relay.
> - The direct way puts a run-scoped token in a provider process. A
process that the agent starts can read it. A provider process that
serves more than one run can hold a revoked token.
> - This pull request replaces the list with one rule. Each native
harness gets its assigned gateway tools through the relay.
> - The benefit is one behavior for all native harnesses, and no gateway
token in a provider process.
## Linked Issues or Issue Description
No public issue exists. The issue is described here.
Refs #13942 (the relay), #17149 (ACPX accepts relayed tools) and #19912
(the design for turn-scoped ACPX MCP authority).
**What existing behavior does this improve?**
How a native harness reaches the tools of its assigned MCP gateway.
**Subsystem affected**
Native runtime in the server (`native-session-executor.ts`,
`native-session-resume.ts`). One Runner test file. One Rust test.
**Current behavior**
- `relayAssignedMcp` is true for plugin tasks, Cursor Cloud, OpenCode,
Codex on a remote target, and Dot.
- For local Codex and for each ACPX agent (Claude, Codex, Cursor, Pi,
Kimi, Grok, Copilot, Antigravity), Core puts
`PAPERCLIP_NATIVE_MCP_NAME`, `PAPERCLIP_NATIVE_MCP_URL` and
`PAPERCLIP_NATIVE_MCP_TOKEN` in the Runner environment. The ACPX host
gives them to the provider as an HTTP MCP server. The local Codex home
gets them in `config.toml`.
- The token is run-scoped. Core revokes it when the run ends.
**Proposed behavior**
- A native run that has an assigned gateway uses the relay. The
condition names no provider.
- Core builds the gateway tools on the control plane, offers them with
the other Runner tools, dispatches each call over PRP, and authorizes
each call again through the gateway.
- Core removes the three `PAPERCLIP_NATIVE_MCP_*` variables from each
Runner environment.
- The tool contract fingerprint has the relay marker for each target,
not only for remote targets.
**Reason and benefit**
- All native harnesses have the same behavior.
- No provider process holds a gateway token.
- A sandbox does not need to reach the gateway URL of the host.
## What Changed
- `server/src/services/native-runtime/native-session-executor.ts`
- The list of special cases is gone. Core validates the binding and
builds the relayed tools when a binding is present.
- Core does not list the gateway for a review run, Grok Bot or Muse. The
tool authority never offered app tools to those. A gateway error can
therefore not fail those runs.
- OpenCode keeps its `on_demand` catalog. That option depends on the
provider, not on the relay.
- Core removes the three variables from each Runner environment.
- `server/src/services/native-runtime/native-session-resume.ts`: the
relay marker in the tool contract fingerprint is unconditional.
- `doc/execution-semantics.md`: the text about the tool contract
fingerprint now states the rule, the tool names and the cutover.
- App tool schemas. New module
`packages/paperclip-runner/src/drivers/tool-input-schema.ts` compiles
each schema by itself, in its declared dialect (draft-07, 2019-09 or
2020-12), with no shared `$id` registry. Core uses it when it builds the
relayed tools (`assigned-mcp-tools.ts`). Core does not offer a tool
whose schema has an unsupported dialect or does not compile, and writes
a log entry with the tool name and the reason. The run does not fail.
The ACPX tool bridge and the OpenCode MCP bridge use the same function.
The tools of Paperclip itself stay strict.
- Large arguments. The ACPX sidecar sends the arguments of a tool call
to runnerd with no display limit. The limit is the tool-call admission
limit of runnerd, 256 KiB. A larger call fails with a tool error that
gives the limit. The sidecar does not dispatch it.
- Tests in `native-session-executor.test.ts`,
`native-session-resume.test.ts`, `runtime-context-materializer.test.ts`
and `acpx_provider_backend.rs`.
Not changed in this pull request: the direct code path. It is still in
the Runner, but it receives no binding. #21311 deletes it.
## Behavior that each harness sees
| Harness | Before | After |
|---|---|---|
| Codex on a remote target, OpenCode, Cursor Cloud, Dot, plugin tasks |
Relay | No change |
| Local Codex | Direct: a `paperclip-assigned` server in `config.toml` |
Relay. App tools are dynamic tools named `app_<name>_<digest>` |
| ACPX agents | Direct: a second HTTP MCP server | Relay. App tools are
on the `paperclip` bridge as `mcp__paperclip__app_<name>_<digest>` |
| ACPX with a preconfigured home | No gateway | No change |
| Grok Bot, Muse | Got the variables and ignored them | Do not get the
variables |
- A relayed tool name has a maximum of 64 characters. With the
`mcp__paperclip__` prefix it has a maximum of 80.
- Permission behavior keeps the same intent. For Claude in the
`approve-reads` and `approve-paperclip` modes, app tools ask for
approval, as before. For the other ACPX agents the permission decision
does not use the server name.
- In a planning run or an ask run, the relay offers only tools with read
risk. The direct gateway offered all tools. This is stricter.
- When the catalog is too large, each harness gets the two compact tools
`paperclip_search_assigned_tools` and `paperclip_call_assigned_tool`.
- The four helper tools for resources and prompts
(`paperclip_list_resources`, `paperclip_read_resource`,
`paperclip_list_prompts`, `paperclip_get_prompt`) are not in the relay.
No harness loses them: a run token permits only `tools/list` and
`tools/call` (`run-preparation.ts`), so these four tools already fail
with `gateway_token_action_denied` on the direct path.
## State saved by the previous release
- **Local sessions of each provider start again one time.** The tool
contract fingerprint changes for local targets. The next run sees a
different fingerprint, starts a new provider session with the full task
context in the same workspace, and keeps the old saved state. This is
the existing rotation for a tool contract change. Codex needs it,
because Codex cannot add tools to a thread that it resumes. For the
local providers that already used the relay, the restart is not
necessary. It is accepted so that the rule names no provider.
- **Remote sessions continue.** Their fingerprint does not change. For
ACPX, the attach of the next run replaces the saved tool set.
- **A kept Codex home.** Paperclip writes `config.toml` again at each
start and recovery. The old gateway server and its token are removed.
- **A deploy lands during a run, and the Runner survives.** The
controller attaches to the same Runner for the same run. The old
provider keeps its direct gateway connection. The controller detach
keeps the gateway token of that run, and Paperclip revokes it when the
run ends.
- **A deploy lands during a run, and the Runner is dead.** The Runner
starts again for the same run with its saved tool set and no direct
gateway. The assigned app tools are not available for the remainder of
that one run. The next run gets them through the relay. This applies to
each harness that moves to the relay. It has no test.
- Paperclip refuses no saved state and discards none.
## Verification
- `cd server && npx vitest run
src/services/native-runtime/native-session-executor.test.ts
src/services/native-runtime/native-session-resume.test.ts`: `1508 passed
| 7 skipped`, 1 failed. The failed test is "archives a damaged prior
epoch before completing guarded same-task replacement with real runnerd"
(`ENOENT … authority-epochs`). It fails in the same way on `master` at
|
||
|
|
2483cb46c2 |
feat(plugins): deliver configured environment to plugin Runner tasks (#21280)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - An agent gets environment variables from its execution environment, its own configuration, its project, and its routine. Secrets are resolved for each run. > - A plugin environment can run the agent as a native Runner task on its own host, through the environment task contract. > - That contract has no field for the agent's variables. Runs on a plugin environment get only the variables that the plugin sets itself. > - This pull request adds a versioned contract field for the values, sends them on a session handoff, lets Codex commands inherit the variables in an external sandbox, and lets a plugin protect the variables that it sets itself. > - The benefit is that plain and secret variables work on plugin environments in the same way as on local environments. ## Linked Issues or Issue Description Refs #21233. That pull request by @lucktastic finds the same gap and proposes the same capability and field names (`configuredEnvironmentVersion: 1`, `configuredEnvironment`). This pull request uses the same names, so providers implement one contract. It differs in these places: - Codex commands get the variables through an external-sandbox denylist, not through key names sent at `prepare`. A retained Runner does not need a new preparation when a key is added or removed. - A session handoff `resume` gets the values, because it starts a new Runner on another computer. Value changes on the same computer need no new field: Core's process reuse key includes the values, so Core starts a new task. - A driver can declare `protectedEnvironmentKeys`. Paperclip rejects or warns when one is saved. - The run log names skipped variables only for an older provider. Thank you to @lucktastic for the diagnosis and the contract shape. **What happened?** An agent has environment variables, plain and secret. Its runs on a plugin task environment do not get them. `PAPERCLIP_CONFIGURED_ENV_KEYS` in the run lists only the variables that the plugin sets. **Expected behavior** Each run gets the agent's configured variables. **Steps to reproduce** 1. Set a plain and a secret environment variable on an agent. 2. Assign the agent to a plugin environment that provides Runner tasks. 3. Start a run. Read the names in `PAPERCLIP_CONFIGURED_ENV_KEYS` in a command that the agent runs. 4. The agent's names are not in the list. ## What Changed - **SDK contract** (`packages/plugins/sdk/src/environment-tasks.ts`): - A provider advertises `configuredEnvironmentVersion: 1` on `describe`. - `submit` gets `configuredEnvironment`. `resume` gets it only for a session handoff. - Names, count, and sizes have the same limits as the Runner projection. - **Server**: - `createRunnerdBackendWithinSessionClaim` gives the run's configured projection to the plugin task owner. The projection has no provider credentials and no generated runtime keys. - `createPluginRunnerTaskOwner` sends the fields only to a provider with the capability. An older provider gets no new field, and the run log names the variables that were not set. The log never prints values. - **Codex** (`codex-security-config.ts`): - An externally sandboxed launch uses `inherit="all"`, `ignore_default_excludes=true`, and an `exclude` list of Codex's own credentials, instead of an `include_only` list fixed at preparation time. - A test reads the Runner's Codex environment keys, and fails if a new key is not classified. - Host launches keep the bounded allowlist. - **runnerd** (`codex_provider.rs`): `runtime_notification_codex_args` still grants the notification files to read-only profiles when no allowlist is present. Plan mode in an external sandbox needs these grants. - **Protected keys**: - An environment driver can declare `protectedEnvironmentKeys` in its manifest. - Paperclip rejects a protected key on an agent or environment that uses the driver. The 422 has code `protected_environment_variable`. - On a project, a routine, or another agent, Paperclip saves the key. The response has a `configurationWarnings` notice that names the environments. The project and routine pages show the notice as a toast. The agent pages already show configuration warnings. - **Docs**: `doc/plugins/PLUGIN_ENVIRONMENT_TASKS.md` describes the provider obligations. - `tests/runner-e2e/source-sdk-public-inputs.json`: refresh the reviewed SDK source pin. ## Verification - `packages/plugins/sdk`: `vitest run tests/environment-tasks.test.ts` (38 pass). Accepts bounded values. Rejects bad names, NUL bytes, too many variables, and oversized values. - `server`: `vitest run src/services/native-runtime/plugin-runner-task.test.ts` (95 pass). Values go only to a provider with the capability, never in `prepare`. `resume` sends values only for a handoff. - `server`: `vitest run src/services/protected-environment-keys.test.ts src/__tests__/project-routes-env.test.ts` (10 pass). Rejection, notices, and the project route response. - `server`: all route suites that import the project, routine, environment, or agent routes (45 files, 1689 pass). - `packages/shared`: `vitest run src/validators/plugin.test.ts` (64 pass). - `packages/paperclip-runner`: `vitest run src/drivers/codex src/configured-environment.test.ts src/live/runner-provider-launch.test.ts` (444 pass). - `packages/paperclip-runner/runner`: `cargo test -p paperclip-runner-core --lib runtime_notification` (9 pass, 2 ignored as before). - `pnpm typecheck` in `packages/shared`, `packages/plugins/sdk`, `packages/paperclip-runner`, `server`, and `ui`. - Not run locally: `pnpm verify --full` and browser suites. Required CI covers the final revision. ## Risks - **Existing providers:** low risk. Core sends no new field to a provider without the capability. Their runs behave as before, with one added log line when variables were skipped. - **Codex in an external sandbox:** commands now see every variable in the Runner environment except Codex's own credentials. The execution environment builds that environment from an allowlist. If the Runner gives Codex a new credential, the drift test fails until the key is classified. - **Saving env:** new rejections happen only when an installed driver declares `protectedEnvironmentKeys`. No driver declares them today. - **Providers:** they must keep the values transient and never save or log them. The doc lists these obligations. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, in Claude Code with tool use and code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [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 Opus 5.5 <noreply@anthropic.com> |
||
|
|
4f4d823cfc |
feat(environments): forward the warm idle window to plugin lease acquisition (#21305)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Plugin environment drivers run agent tasks on remote computers, and warm leases keep a parked Runner between runs for an idle window that Core records > - Some providers stop an idle computer on their own schedule (for example a sandbox auto-stop interval) > - If that provider timer is longer than the Runner idle window, the provider keeps paying for a computer whose Runner is already gone; if it is shorter, a warm resume can find the computer stopped > - The plugin cannot align the two because it never sees the idle window at acquire > - This pull request forwards the warm idle window to `environmentAcquireLease` as `runnerLifecyclePolicy` > - The benefit is that a provider can stop its computer just after the Runner idle window, without Core knowing anything about the provider's placement ## Linked Issues or Issue Description Refs #21289 Refs #21066 **What existing behavior does this improve?** Warm lease setup for plugin environment drivers. **Subsystem affected** Server environment runtime (`createPluginEnvironmentDriver`) and the plugin SDK acquire parameters. **Current behavior** Core records the warm lifecycle policy (`runnerTaskLifecyclePolicy`, including `idleTimeoutMs`) on the lease, but `environmentAcquireLease` does not receive it, so a provider with its own idle shutdown has to guess. **Proposed behavior** For a warm lease, `environmentAcquireLease` receives `runnerLifecyclePolicy: { mode: "warm", idleTimeoutMs }`, the same value Core records. Other lifecycle modes do not receive the field. **Reason and benefit** A provider can align its idle shutdown with the Runner idle window. **Breaking changes** None. The field is optional and additive. ## What Changed - `PluginEnvironmentAcquireLeaseParams` has a new optional `runnerLifecyclePolicy`. - Core sends it only for warm leases. - `doc/plugins/PLUGIN_RUNNER_EXECUTION.md` documents the field. - The runner-e2e SDK public-input pin is updated for the SDK change. An earlier revision of this PR also made Core try `environmentResumeLease` before a session handoff. That part is removed: placement is the plugin's decision, so Core should not decide to retry the same computer before moving the session. The plugin will own that inside its own resume instead. ## Verification - `pnpm typecheck` in `server/` (builds shared and plugin-sdk) passed. - `vitest run src/__tests__/environment-runtime.test.ts -t "portable task placement|delegates plugin environment leases with acquisition budget"` passed (5 cases). The portable test asserts the first warm acquire receives `runnerLifecyclePolicy` and the lease records `runnerTaskLifecyclePolicy`; the non-warm delegation test asserts the field is absent. Making the forwarding unconditional fails both delegation cases. - The full suite was not run locally; required CI covers it. ## Risks - A plugin that does not know the field ignores it. - Rollback: revert this pull request. No migration. Note: the branch name still reflects the earlier scope (resume before handoff). ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use (shell, file edits, test runs). ## 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 Opus 5.5 <noreply@anthropic.com> |
||
|
|
49f0030f06 |
fix(heartbeat): rank a person's joined comment first and refill free run slots (#21277)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The heartbeat queue starts each agent's queued runs, up to the agent's `maxConcurrentRuns` > - #21234 starts person-initiated runs before system recovery runs, and it reads "person-initiated" from the run's own wake request > - When a person comments on a task that already has a queued system run, the comment joins that run. The run keeps its system wake, so dispatch ranks the person's message as system work > - Dispatch is event driven. The queued-run re-drive backstop covers only agents with no live run, so an agent with several slots keeps a free slot empty until one of its runs finishes, and runs can take hours > - This pull request makes dispatch read the person wakes that joined each queued run, and makes the re-drive backstop cover an agent that still has a free slot > - The benefit is that a person's comment starts first, and free slots fill within about a minute instead of waiting for an unrelated run to finish ## Linked Issues or Issue Description Refs #21234, #20986 **What happened?** On staging, one agent had `maxConcurrentRuns` 20, 18 running runs and 76 queued runs at 03:12Z. No run started on that agent from 03:01:33Z to 03:16:57Z (15.4 minutes). From 03:11:10Z, after a run finished, at least 2 slots were free. Other agents in the same company started runs during that time. Runs started again only after the next deploy restarted the server. Five queued runs came from a person: comments at 02:43Z, 02:44Z and 02:45Z, and Retries at 02:46Z, 02:49Z and 03:01Z. The comment runs had the wake reasons `issue_reopened_via_comment` and `issue_commented`, the invocation source `automation`, and no person on the run's own wake request. **Expected behavior** A run that carries a person's comment ranks as person-initiated, also when the comment joined an existing queued run. When an agent has a free slot and a queued run is ready, the run starts promptly, without waiting for another run on the agent to finish. **Steps to reproduce** 1. Give an agent `maxConcurrentRuns` 3. Start 2 runs on it. 2. Queue a third run while no dispatch signal reaches the queue (for example, a claim declines it while a gate is still closed, and the gate then clears). 3. See that `listUndispatchedQueuedRuns` returns nothing, because the agent has a live run. The run stays queued until one of the 2 running runs finishes. 4. Separately, queue a system run on a task, then post a person's comment on the task so that the comment wake coalesces into that queued run. Queue older system runs on other tasks of the same single-slot agent. 5. See that dispatch starts the older system runs first. **Root cause** 1. `coalesceIntoActiveExecutionRun` (`server/src/modules/wake-queue/adapters/postgres.ts`) merges the person's comment context into the queued run and records the person's wake as a separate `coalesced` row with `runId` set to that run. The run's own `wakeupRequestId` still points to the system wake. `queuedRunDispatcherForAgent` (`server/src/services/heartbeat/queue.ts`) only read the wake behind `wakeupRequestId`. The task routes do record the comment author as the requester (`requestedByActorType: "user"`). The person was lost only at dispatch time. 2. `listUndispatchedQueuedRunPage` (`server/src/services/queued-run-dispatch-liveness.ts`) skipped every agent with any `running` or `scheduled_retry` run. That rule assumes one slot per agent. For an agent with several slots, a lost or declined dispatch is not re-driven until a run on that agent finishes. This change is not in `claimQueuedRun`, the fresh-isolated preflight, the wake-queue promoter or `fresh-continuation-fallback.ts`. **Paperclip version or commit** Staging Core `ddc0aacad8` (contains #21234 `ade7e0643f`). This branch is based on master `6cb0dd0c6b`. **Deployment mode** Authenticated, public, Paperclip Cloud managed staging. **Agent adapter(s) involved** `paperclip_runner` (Codex native runtime). The fix is adapter-independent. ## What Changed - `queuedRunDispatcherForAgent` also reads person wakes whose `runId` is a queued run of the agent (by `run_id IN (queued run ids)`, so an earlier saved comment that a run adopted is included). A run with such a wake ranks as person-initiated and is never counted as system recovery. - `listUndispatchedQueuedRuns` now returns a queued run when its agent has fewer `running` plus `scheduled_retry` runs than its `maxConcurrentRuns`, and its task has no `running` or `scheduled_retry` run. The re-drive backstop and the ownership I7 check use this query. - The query counts each agent's live runs once, in one grouped subquery that is joined to the queued runs. - Migration 0476 adds `agent_wakeup_requests_company_run_idx` (`company_id`, `run_id`, partial on a non-null run) with `CREATE INDEX CONCURRENTLY IF NOT EXISTS`. It is listed in `MIGRATIONS_WITH_TOP_LEVEL_STATEMENTS` and classifies as `online_compatible`. `doc/DATABASE.md` describes it. - Added `maxConcurrentRunsSql()` to `timer-policy.ts`. It reads the same limit as `parseHeartbeatPolicy`, including the single-run runner providers, which now share one constant. ## Verification - Red/green: `server/src/__tests__/recovery-wake-herd.test.ts` "starts a queued run that a person's comment joined ahead of older system work". It fails on master (`expected null not to be null`: the older system run started first) and passes with this change. - Red/green: `server/src/__tests__/ownership-reconciliation-report.test.ts` "re-drives a queued run while its agent still has a free slot, and not once every slot is running". It fails on master (`expected [] to deeply equal [ Array(1) ]`) and passes with this change. - Red/green: "starts a queued run that adopted a person's comment saved before every queued run". It fails with a `requestedAt` bound and passes with the `run_id` lookup. - Red/green: "counts an agent's live runs in one grouped aggregate, not once per queued run" runs EXPLAIN on the page query. It fails with a per-row correlated count and passes with the grouped subquery. - New: "uses the agent's single-run limit for a runner provider that runs one turn at a time". - Two existing tests now set `maxConcurrentRuns: 1` so that they keep testing "the agent's only slot is busy". - `npx vitest run src/__tests__/recovery-wake-herd.test.ts src/services/heartbeat/queued-run-dispatch-order.test.ts src/__tests__/ownership-reconciliation-report.test.ts src/services/queued-run-dispatch-liveness.test.ts src/services/heartbeat/dispatch-work.test.ts`: 71 passed. - `npx tsc --noEmit -p server/tsconfig.json`: no errors. ## Risks - The re-drive backstop now also covers multi-slot agents with live runs. Each queued run is re-driven at most on its existing backoff (1 minute, then doubling to 15 minutes). A queued run whose task already has a live run is not re-driven. - The ownership I7 report can now list a queued run on a multi-slot agent that has a free slot. This is the stall that this change targets. - One more indexed read per dispatch pass (`agent_wakeup_requests` by company and run id). The new index is built concurrently, so the previous release keeps writing during the build. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude Code with tool use (shell, file edits, read-only staging API reads in a browser tab). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
ff91bfe2dc |
fix(runner): withhold Claude's self-scheduling tools from Paperclip ACPX sessions (#21276)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Paperclip owns scheduling. An agent uses Paperclip tools such as task monitors and routines to continue work later. > - Paperclip Runner runs Claude Code through the ACPX sidecar. > - Claude Code offers its own scheduling tools to the model: `CronCreate`, `CronDelete`, `CronList` and `ScheduleWakeup`. With these tools the provider can wake itself. Paperclip does not see or govern that work. > - Today the Runner stops the Claude process when a turn ends, so these tools have little effect. A later change keeps the Claude process alive between turns. > - This pull request removes the four tools from Claude sessions that Paperclip starts through ACPX. > - The benefit is that a Claude agent schedules work only through Paperclip. ## Linked Issues or Issue Description No public issue exists. The issue is described here. Refs #19912 (the design for turn-scoped ACPX MCP authority). **What existing behavior does this improve?** The set of tools that Claude Code offers the model in a Paperclip ACPX session. **Subsystem affected** Paperclip Runner, ACPX provider (Claude). **Current behavior** A Paperclip ACPX Claude session offers the model 26 built-in tools. Four of them are `CronCreate`, `CronDelete`, `CronList` and `ScheduleWakeup`. **Proposed behavior** - The Claude settings that Paperclip writes into the session home deny the four tools. Claude Code then does not offer them. - Each Claude launch sets `CLAUDE_CODE_DISABLE_CRON=1`. This stops the cron scheduler of Claude Code and removes the three cron tools. - All other tools stay. `SendMessage`, `ListAgents`, `Workflow`, `Agent` and `TaskStop` do not change. **Reason and benefit** The provider cannot schedule its own wake-ups. Paperclip tools stay the only way to schedule work. ## What Changed - `packages/paperclip-runner/src/drivers/acpx/permission-policy.ts`: new constant `CLAUDE_SELF_SCHEDULING_TOOLS` with the four tool names. - `packages/paperclip-runner/src/drivers/acpx/runtime-sandbox.ts`: the Claude `settings.json` now always has `permissions.deny` with the four tools, in each permission mode. The `allow` rules do not change. - `packages/paperclip-runner/src/drivers/acpx/environment.ts`: `createSanitizedAcpxSpawnInput` sets `CLAUDE_CODE_DISABLE_CRON=1` for each Claude launch. The host cannot override it. - New test `claude-scheduling-tools.claude-acp.test.ts`. It prepares the session home with the production `prepareAcpxRuntimeSandbox`. It then runs the pinned `claude-agent-acp` and the pinned Claude Code client against a local fake Anthropic API. It reads the tools that the client offers the model. - Unit tests in `environment.test.ts` and `runtime-sandbox.test.ts`. One assertion in `runtime-host.test.ts` now expects the `deny` list. - No change to the `claude-agent-acp` patch, the lockfile or a pinned digest. No change to Codex. ## State saved by the previous release - A session that the previous release saved continues with no change. The new restriction is not part of a saved identity or digest. - Each time Paperclip starts Claude for a session, it writes its own `settings.json` again with the deny list and sets `CLAUDE_CODE_DISABLE_CRON`. This includes a resumed session and a start after an upgrade. - A resumed session keeps its identity, its home and its transcript. It loses the four tools from its next start. - A Claude process that the previous release started keeps its tools until it stops. Paperclip does not refuse it and does not classify it differently. Its next start gets the restriction. - No refusal code is necessary, because no saved state becomes incompatible. ## Verification - `cd packages/paperclip-runner && npx vitest run src/drivers/acpx/claude-scheduling-tools.claude-acp.test.ts` - Without the product change: `2 failed` (`expected [ Array(26) ] to not include 'CronCreate'`). - With the product change: `2 passed`. - `npx vitest run src/drivers/acpx/claude-scheduling-tools.claude-acp.test.ts src/drivers/acpx/environment.test.ts src/drivers/acpx/runtime-sandbox.test.ts src/drivers/acpx/runtime-host.test.ts`: `4 passed (4)` files, `147 passed` tests. - `npx tsc --noEmit -p tsconfig.json` in `packages/paperclip-runner`: no errors. - Tools offered after the change, isolated home: the same 26 tools without `CronCreate`, `CronDelete`, `CronList` and `ScheduleWakeup`. - `npx vitest run src/drivers/acpx/runtime-host.test.ts -t "previous release"`: the new test "resumes a Claude session saved by the previous release and withholds self-scheduling tools on relaunch" fails without the product change and passes with it. The test saves a session, puts its home into the shape of the previous release, and resumes it through `AcpxRuntimeHost.open`. - `npx tsc --noEmit -p tsconfig.test.json` in `packages/paperclip-runner`: no errors. - The fixture in `claude-scheduling-tools.claude-acp.test.ts` now stops the process group of the provider and waits for it before it removes the fixture directory. - Not run: a live run with a real Claude account, and a remote Runner. Not run: `pnpm verify` and the full suite. CI supplies that coverage. ## Risks - **A preconfigured home still offers `ScheduleWakeup`.** In that mode Paperclip does not write the Claude settings of the user, so the deny list does not apply. The environment variable removes only the three cron tools. To remove `ScheduleWakeup` there, the Runner must pass `disallowedTools` to the session. ACPX 0.22 does not forward that option. This is a follow-up. - **The new test runs the real pinned Claude Code client.** It needs the platform binary, as `runner-tool-bridge.claude-schema.test.ts` does today. It uses no credentials and no network. - **A prompt or skill that tells Claude to use these tools no longer works.** No Paperclip instruction refers to them. - The prepared harness home and remote Runners use the same code path. They are not tested separately. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Claude Fable 5.2 (`claude-fable-5-2`) in Claude Code planned the change, reviewed the diff and ran the verification again. - Claude Opus 5.5 (`claude-opus-5-5`), as a Claude Code subagent with tool use (shell, file edits, local test runs), investigated the options and wrote the change and the tests. ## 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 - [ ] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com> |
||
|
|
bcadbde449 |
feat(runner): record the OpenRouter host that served each OpenCode model call (#21298)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - OpenCode agents can use models through OpenRouter, and the Runner proxies those model calls > - OpenRouter routes one model across many hosts, and these hosts use different quantizations (fp4, mxfp4, fp8) > - Chat evaluations with identical prompts behave very differently between runs, but the run log does not record which host served a call > - The run usage shows `provider: "deepseek"` and `biller: "openrouter"`, and `providerRequestId` is always `null` > - This pull request records the serving host and the OpenRouter generation ID for each model call in the run log > - The benefit is that we can compare evaluation cohorts by host, and the cost event names a real OpenRouter generation ## Linked Issues or Issue Description **Subsystem affected** Runner OpenCode provider proxy, runnerd usage normalization, and native run usage accounting. **Problem or motivation** OpenRouter's default routing sends a request to one of many hosts. Each host can use a different quantization. Chat evaluation results change a lot between runs with identical prompts. Paperclip does not record which host served a call, so we cannot compare results by host. `usageJson.providerRequestId` is always `null` for OpenCode runs. **Proposed solution** Every OpenRouter completion response has a top-level `provider` field and an `id` (the generation ID). Each streamed chunk has them too. The Runner proxy reads them from the first chunk after it forwards the bytes. The Runner attaches them to the usage of that call. The values go to the run log, and the run's first generation ID goes to `usageJson.providerRequestId`. **Alternatives considered** A new PRP event type such as `provider.upstream.served` would need a new event enum value. An older control plane rejects an unknown event type. A `harness.diagnostic` event shows in the task chat as a diagnostic. The usage payload already flows to every consumer, and older consumers ignore extra fields. Thus this change uses the usage payload. **Additional context** Run-log change only (AGENTS.md section 7). The data stays in `heartbeat_run_events` and `heartbeat_runs.usageJson`. It does not touch `packages/shared/src/telemetry/` or OpenTelemetry. ## What Changed - New `createUpstreamServedTap` (`packages/paperclip-runner/src/drivers/opencode/upstream-served.ts`). It is a pass-through stream. It pushes each chunk downstream first, then it reads `provider` and `id` from the first SSE `data:` event (or from a JSON body at its end). It scans at most 64 KiB of a stream and 1 MiB of a JSON body. It skips encoded bodies and unknown content types. Any parse problem or recorder error stops the scan and leaves the response unchanged. - `startOpenCodeProviderProxy` uses the tap only for 2xx responses. The OpenCode session keeps the most recent served call. Each `item.completed` usage payload and `session.usage()` now carry `upstreamProvider` and `providerRequestId`. The usage dedupe fingerprint does not include these fields, so the number of usage events does not change. - The OpenCode app-server proxy adds the two fields to `thread/tokenUsage/updated`. Rust `usage.reported` now fills its existing `providerRequestId` field and adds an optional `upstreamProvider`. The TypeScript runnerd transport keeps both fields when it rehydrates the usage notification. `usage.schema.json` documents `upstreamProvider` (the protocol manifest and schema bundle are regenerated). - Server native turn accounting keeps the first generation ID the run reports. The usage checkpoint and the native adapter result carry it as `providerRequestId`, so `usageJson.providerRequestId` and the final cost event name it. - `doc/run-log-events.md` documents the fields in a new "OpenRouter serving host" section. ## Verification - Red/green: `opencode-server-driver.test.ts` "passes OpenRouter's stream through unchanged and records the host that served it on the turn's usage". The test sends a streamed fixture with a comment line, a host chunk, a malformed chunk, and `[DONE]` through the proxy. It checks that the bytes are identical and that the turn's usage names `Novita` and the generation ID. The test fails without the proxy wiring. - `upstream-served.test.ts`: streamed fixture, chunk split inside a multibyte character, non-streamed JSON, malformed chunks, a truncated JSON body, an encoded body, the 64 KiB limit, and a recorder that throws. - `opencode-proxy-usage.test.ts`, `runnerd-codex-transport.test.ts` (rehydration), Rust `provider_events::tests::carries_the_serving_host_and_generation_on_proxy_usage`, and server `native-usage-accounting.test.ts` (first generation ID stays stable across turns). - Local: OpenCode driver, OpenCode proxy, and runnerd transport suites (31 files, 596 tests) pass. `cargo test -p paperclip-runner-core` passes (one timing test failed once under load and passed alone). Runner and server `tsc --noEmit` pass. Protocol manifest, type, and coverage checks pass. - Latency: a local benchmark proxied a 400-chunk SSE stream 200 times with the tap and 200 times without it. The median time to first byte was 292 µs with the tap and 259 µs without it (+33 µs, which is the extra stream stage). The total stream time changed from 491.4 ms to 492.5 ms. The tap spends about 5.5 µs of CPU to inspect the first chunk, after it has forwarded that chunk. OpenRouter time to first token is hundreds of milliseconds. - Paid evidence: one single-case run of `chat-features.runner-opencode.local.skills.fork-read-only` on this branch. The result is in a comment on this pull request. ## Risks - Low risk. All new fields are optional and additive. An older control plane ignores the extra usage fields. `usage.schema.json` is not bound by the event schema, and no validator enforces it on `usage.reported`. - Saved state from the previous release: this change adds no persisted run, session, checkpoint, or launch state. A saved session resumes unchanged. A run that is in flight during a deploy reports usage without the new fields until its Runner is new. `usageJson.providerRequestId` then stays `null`, as before. - `providerRequestId` on the run and its cost event is the run's first generation ID, not each call's ID. The value is stable, so a late usage receipt still matches the posted charge. Per-call IDs and hosts are in the run log. - If OpenCode starts a new model call before it reports the usage of the previous call, a usage event can name the newer call. OpenCode reports a message's usage when its step ends, so this is not expected. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Anthropic Claude Opus 5.5 (`claude-opus-5-5`), used through Claude Code as an agent with tool use (shell, file edits, test runs). Extended reasoning was on. ## 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 Opus 5.5 <noreply@anthropic.com> |
||
|
|
e65a3095a7 |
fix(runner): quiesce the Core-dialed route once the Runner commits its suspend (#21245)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - Core runs agent sessions through the Paperclip Runner. With provider
ingress, Core dials the Runner over a PRP WebSocket.
> - When Core closes a session, it asks the Runner to suspend. The
Runner suspends, reports the result, and exits.
> - Core's ingress connection did not know that this exit was expected.
It treated the drop as a transport loss and redialed the Runner. Each
redial got a 404 until the close released the route.
> - The release (park) path already quiesces the connection before the
Runner goes away. The suspend path did not.
> - This pull request makes the suspend close quiesce the route in the
same way, once the Runner commits its suspend.
> - The benefit is that a clean suspend no longer looks like a lost
Runner. A drop before the suspend is committed still redials and
recovers as before.
## Linked Issues or Issue Description
**What happened?**
After a provider-ingress session closed cleanly, Core redialed the
Runner's ingress endpoint several times and got 404 each time. The
Runner state was `suspended`, `runner.drain` and `runner.suspend` had
both completed, and the Runner had exited with code 0. The redials
followed the outbound reconnect backoff (about 250, 500, 1000 and 2000
ms) and stopped when the registration release closed the outbound.
**Expected behavior**
After Core commits to `runner.suspend` and the Runner reports it
completed, the Runner's exit is expected. Core must not redial or
classify the drop as a transport loss. The release path already works
this way: it calls `outbound.quiesce()` before it releases the task.
**Steps to reproduce**
1. Open a session through a Core-dialed route (plugin provider ingress
or the `listen_ws` driver).
2. Close the session. Core drains, queues `runner.suspend`, and the
Runner suspends and exits.
3. See that the outbound reconnect loop redials the gone Runner until
the registration release closes it.
**Paperclip version or commit**
`master` at
|
||
|
|
717aae060a |
fix(environments): let same-run recovery create a replacement once its sandbox is proven stopped (#21223)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Agent runs execute on environment leases, and `createOwnedSandbox` records each sandbox creation so that a lost reply never creates a second sandbox > - The record key is company, environment, run and request key. The plugin request key is the environment fingerprint, so it is the same for every attempt of one run > - A same-run recovery can need a new environment after the first lease is closed with successful cleanup and a termination receipt > - The old record is still `attached` to the closed lease, so the recovery fails with "Sandbox creation has already transferred ownership" before the provider is called > - This pull request lets the creation fence accept the same stop proof that recovery already requires. A creation record whose sandbox is proven stopped becomes resolved, and a resolved record no longer holds its key > - The benefit is that same-run recovery gets one replacement sandbox, while unconfirmed cleanup still blocks a second sandbox ## Linked Issues or Issue Description Fixes #21214 Refs #20755. That pull request fixes the same failure with a different rule. It retries under a new key generation (`<key>#2`, `#3`, ...) when the recorded lease has ended, and it accepts any ended status, including `failed`, without a termination receipt. A lease whose cleanup is not confirmed can then produce a second sandbox while the first one can still run. This pull request keeps the original key and requires the same stop proof that Core uses elsewhere (`hasRemoteTerminationReceipt`). It does not add a key generation. ## What Changed - `server/src/services/sandbox-creation-operations.ts`: when `createOwnedSandbox` finds the key held by an `attached` operation whose lease is not active, it checks the same stop proof that same-run recovery requires before it acquires: `hasRemoteTerminationReceipt(resolveRemoteTerminationLease(lease))`, for the sandbox that this operation created (`creationProviderLeaseId`, or the lease's `providerLeaseId`). - With that proof, it runs the same admission transaction one more time. That transaction first marks the old operation `resolved` (`WHERE id AND state = 'attached' AND lease_id`), and then inserts the new operation. - Without that proof, it throws exactly as before. - The check covers every source of a stop receipt: `releaseLease`, the Runner `complete` operation (which writes receipts with direct SQL for reusable leases), stop-and-retain settlement, and the receipt that `resolveRemoteTerminationLease` derives for an expired reusable lease. - A task replacement can leave an earlier operation attached to a lease that now holds another sandbox. That operation is not proven and keeps its key. - Concurrent recoveries serialize on the row update. The second one updates nothing, finds the first one's unresolved operation through the partial index, and replays or refuses as before. There is one provider call. - Migration `0475_sandbox_creation_owner_unresolved.sql` recreates `sandbox_creation_operations_owner_idx` under the same name as a partial unique index (`state <> 'resolved'`). The drop and the create are in one migration transaction. The Drizzle schema matches. - The conflict lookup in `createOwnedSandbox` ignores resolved rows. An active attached lease is still replayed. Pending and `needs_reconciliation` rows still refuse. `releaseLease` does not change. - `doc/DATABASE.md` and `doc/idle-environment-cleanup.md` describe the operation lifecycle. ## Verification - `pnpm --filter @paperclipai/db generate` - `pnpm --filter @paperclipai/db typecheck` and `pnpm --filter @paperclipai/server typecheck` - `vitest run src/migration-snapshot-drift.test.ts` (db) - `vitest run src/__tests__/sandbox-creation-operations.test.ts`: 48/48. With the service change reverted, the 5 replacement tests fail. - The 9 other server test files that read `sandbox_creation_operations`, plus `environment-runtime.test.ts`: 564/564 - `pnpm check:migrations` passes New tests in `sandbox-creation-operations.test.ts`: - A stop receipt from `releaseLease` (sandbox driver, and the plugin driver through `acquireRunLease` in the #21214 sequence), from the `complete` operation's direct write on a retained reusable lease, and derived only from the destroyed successor of an expired reusable lease each let the next creation resolve the old operation and create exactly one replacement. A retry replays that replacement. These tests fail before the fix. - Failed cleanup, success without a receipt, a receipt for another lease or another provider task, a retained lease, and pending cleanup each still throw "transferred ownership" with no provider call. - An earlier task's operation that a task replacement left attached keeps its key. - Two concurrent recoveries make one provider call. This test fails before the fix. - Reapplying migration 0418 keeps the partial index. I did not run `pnpm verify` or the full suite locally. CI runs them. ## Risks - Migration: the drop and the rebuild of the index take an exclusive lock on `sandbox_creation_operations`. The table has one small row for each sandbox creation, so the lock is short. - Rolling deploy: the migration is marked `online_compatible`. The previous release uses an untargeted `ON CONFLICT DO NOTHING`, which also matches a partial unique index. Its conflict lookup has no state filter, so it can find a resolved row and throw. That fails closed and never creates a second sandbox. - A legacy runner-task operation without `creationProviderLeaseId` matches any lease it is attached to. Runner-task operations record this field before they attach, so this is only a theoretical gap. - An operation stays `attached` until the next creation with the same key checks it. This is the same as before when no recovery comes. - Stop-and-retain settlement is not tested directly. The shared receipt check covers it. - The fence is unchanged for every case without a stop receipt. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use (shell, file edits, sub-agents) and extended thinking. One sub-agent wrote the change. A second session reviewed it before this pull request. ## 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 Opus 5.5 <noreply@anthropic.com> |
||
|
|
497ccba8f1 |
fix(native): replace a reattached Runner that left its recovery read unanswered (#21272)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Native Codex runs execute in a remote Runner that the server controls over the durable PRP channel > - When a run is interrupted, a same-run retry reattaches the live Runner and reads its session (`session.snapshot`) before it continues > - On staging, the reattached Runner authenticated and restored its session, and then did not answer the read > - The recovery kept that Runner, so each later attempt adopted the same Runner and failed the same way until the attempt budget ended the run > - This pull request makes the next attempt replace that Runner with a fresh Runner over its saved journal, and makes a failed Codex history read say what failed > - The benefit is that an interrupted Codex run continues without a manual Retry, and its provider turn is not sent again ## Linked Issues or Issue Description Refs #21161, Refs #21053, Refs #20853 **What happened?** A Codex agent on Daytona ran recovery runs (wake `issue_recovery_action_restored`). In one hour, 11 of about 35 finished runs failed. All failed the same way: - `native_session_recovery_failed: HarnessCapabilityUnavailableError: read is unavailable: Error: runnerd exited while waiting for session.snapshot` (8 runs) - `native_session_recovery_failed: HarnessReconciliationError: codex_history_read_failed: thread/turns/list requires supported paginated history; Error: provider_transport_failed: PRP command session.snapshot timed out (runner connected; pending ahead 0; last runner event seq 338 76s ago)` (3 runs) The run log of each run shows one sequence: 1. Attempt 1 fails with `runnerd did not report the provider turn identity`. The close leaves the Runner alive and unsettled for the same-run reattachment. 2. Attempt 2 adopts that Runner (same PID). The Runner authenticates. The log shows `runnerd restored its durable PRP session and provider thread`. Then the driver's recovery read (`thread/read` or `thread/turns/list`, which both send `session.snapshot`) gets no answer. The Runner still answers WebSocket pings, but it sends no command result and almost no events (`pending ahead 0`, last event 76 s to 391 s earlier). The recovery treats this as transient and detaches. The Runner stays alive. 3. Attempt 3 adopts the same Runner again and fails the same way. In some runs a protocol fault (`thread_binding_mismatch`) closes the transport during the read, so the message is `runnerd exited while waiting for session.snapshot`. 4. The provider attempt budget ends the run. #21161 did not help. Its wait extension applies only while a queued answer is being committed. Here the Runner sent no answer at all. The `paginated history` text was also wrong. `codex-history.ts` called every failed history read unsupported, also a transport timeout. **Expected behavior** A Runner that left a recovery read unanswered is not adopted again. The next attempt starts a fresh Runner from the saved journal, resumes the provider session from the saved checkpoint, and does not send the provider turn again. A failed history read reports the real failure. A Codex build that refuses paginated history falls back to one complete thread read. **Steps to reproduce** 1. Start a Codex run in a remote (Daytona) Runner. 2. Let the first attempt fail at turn start, so that the close keeps the Runner alive. 3. Let the reattached Runner stop answering commands after it authenticates (for example, stop the Runner process after its first answer). 4. See `PRP command session.snapshot timed out (runner connected; pending ahead 0; ...)` on attempt 2 and the same failure on attempt 3, with the same Runner PID. **Paperclip version or commit** Staging Core `57aeda190b` (contains #21161 and #21120). Fixed on `master` after `53608bd1d6`. **Deployment mode** Hosted (staging), remote Daytona sandbox Runner. **Agent adapter(s) involved** Codex (native Runner, `paperclip-runnerd`, `codex_app_server`). ## What Changed - `nativeRecoveryCommandUnanswered` (executor) finds a `native_session_recovery_failed` whose Runner did not answer a recovery command (`PRP command <type> timed out` or `runnerd exited while waiting for <type>`). Identity, authority, integrity and incompatibility refusals do not match. - When such a failure ends a `reattach_remote_runner` attempt on a sandbox target, the failure detail records `adoptedRunnerUnanswered: true`. - `claimNativeRestartRecoveries` copies it to the next claim as `replaceUnansweredRunner: true`, in the same way as `exitedBeforeSessionOpen`. - `verifyRemoteRunnerOrSettledExit` with `replaceUnansweredRunner` keeps all identity checks. When the old Runner is still alive, it returns no adopted process, and the attempt launches a fresh Runner from the saved journal. The existing launch fence stops the old `paperclip-runnerd` on that state folder and its whole lineage, and fails the launch closed when it cannot prove them gone. A Runner that already exited mid-turn keeps the existing fail-closed path, because its provider or tool processes can survive where the fence cannot find them. The task then continues in a fresh session from the saved work. The attempt budget is unchanged. - `codex-history.ts`: a history read that fails without a provider answer is now `codex_history_read_failed: <method> read failed; <error>`. A provider refusal of the method (`-32601` or `-32600`) on the first page falls back to one `thread/read` with `includeTurns: true`. That fallback fails closed when the thread differs, or when turns, items or turn identities are missing. A refusal on a later page still fails closed. - `doc/execution-semantics.md` describes both rules. The launch-fence code comment now names the replacement case. ### Changed existing test `codex-history.test.ts` "does not turn an interrupted page or unsupported method into idle history" used a plain `Error("method not found")` on page 2 and expected the `supported paginated history` text. A plain error is now a failed read, not an unsupported method. The test now uses a real provider refusal (`CodexRpcError` `-32601`) on page 2 and still expects a fail-closed rejection. A new test covers the failed-read message. ## Verification - Red before the fix, green after: - `server/src/services/native-runtime/native-session-executor.test.ts` › "a same-run reattachment whose adopted Runner never answered its recovery read": the replacement and staging-message tests failed on the old code (the Runner was adopted again, the three staging messages were not recognized). Two further tests ("never resumes beside an exited unanswered Runner's lineage") failed on the first revision of this PR, which relaunched beside an exited mid-turn Runner, and pass now. All 15 pass. - `native-runner-restart-recovery.integration.test.ts` › "asks the same-run reattachment to replace a Runner that left its recovery read unanswered" (embedded Postgres): the claim had no `replaceUnansweredRunner` on the old code. Now passes. - `codex-history.test.ts`: 7 new tests failed on the old code. All 16 pass. - Real `paperclip-runnerd` and fake Codex: `runnerd-codex-transport-remote-retention.test.ts` › "continues the same provider thread from a fresh Runner over the journal of a retained Runner that stopped answering, without replaying its turn". It runs the staging sequence: turn started, close keeps the stopped Runner, a second controller adopts it, the Runner stops answering and the controller detaches, the Runner and provider are killed (the launch fence), and a fresh Runner over the same journal returns the same thread. The fake Codex call log shows one `thread/start` and one `turn/start`. - Focused suites: `packages/paperclip-runner` `src/drivers/codex/` plus the remote-retention, adoption and cold-restore transport suites (442 tests). Two suites timed out under parallel load and pass alone. Server: `native-session-executor`, `native-restart-recovery`, `native-runner-restart-recovery.integration`, `runner-lost-mid-turn-continuation` (1714 passed, 21 skipped). - `pnpm typecheck` in `server` (all layers) and `tsc` for `paperclip-runner` source and tests pass. - Not run locally: the container-gated remote Runner suites (`PAPERCLIP_TEST_RUNNER_CONTAINER`) and the full suite. CI covers the full suite. ## Risks - Medium. The replacement relaunches a Runner over a journal that is not settled, but only while the old Runner is alive. Safety comes from three facts: the launch fence stops the old Runner and its lineage with proof or fails the launch; the Runner restores its own durable journal (as local `resume_dead_runner` does); and the real-runnerd test shows that the turn is not sent again. An exited Runner is never relaunched beside its possible survivors. - If the previous close left a `runner.suspend` pending, a fresh Runner can execute it and exit. The attempt then fails as it does today. The usual detach path after an unanswered read sends no suspend. - The replacement uses the existing attempt budget. It does not add attempts. ## Model Used Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude Code with tool use (shell, file edits, browser reads of staging run events and logs), extended reasoning. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |