Commit Graph
4559 Commits
Author SHA1 Message Date
Devin Foley 45221a17ea test(native): give the repeated-bytes provider pack tests a 60s timeout (#22663)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Every pull request runs the server test suite in 12 CI shards
> - #22241 added tests that build and stage a provider pack with three 2
MiB copies of one file
> - Two of these tests take 6 to 7 seconds on a fast laptop and more
than the 15-second server `testTimeout` on CI runners. They also time
out on the automatic retry
> - The `General tests (server (5/12))` shard now fails on unrelated
pull requests, for example #22653 and the
`fix/gateway-session-personal-grant-owner` branch
> - This pull request gives the two tests the 60-second per-test timeout
that other native-runtime tests use
> - The benefit is that the shard passes again and unrelated pull
requests can merge

## Linked Issues or Issue Description

Refs #22241 (added the two tests). Refs #22652, #22653 (blocked by this
shard).

**What happened?**

`server/src/services/native-runtime/provider-pack-archive.test.ts` fails
on CI with `Test timed out in 15000ms` in two tests:

- `stores repeated bytes once, from an image file under another path,
without transferring them`
- `transfers repeated bytes when no image has them, and does not reuse a
changed twin`

Each test also fails on the automatic retry (about 35 seconds in total).

**Expected behavior**

The `General tests (server (5/12))` shard passes on a pull request that
does not touch the native runtime.

**Steps to reproduce**

1. Open a pull request based on `master` after #22241.
2. Wait for `ci / General tests (server (5/12))`.
3. The two tests above time out.

## What Changed

- `provider-pack-archive.test.ts`: add a 60-second timeout to the two
tests above. No test logic changes.

## Verification

- `pnpm exec vitest run
server/src/services/native-runtime/provider-pack-archive.test.ts`: 52
passed.
- On a fast laptop the two tests take 6.1 s and 6.2 s. The other tests
in the file that use the same fixture take less than 2.3 s.
- The CI shard for this pull request is the real check.

## Risks

- Low risk. The change affects only the time limit of two tests.
- The change does not explain why these two tests are slower than the
similar test in the same file. The author of #22241 can make them faster
later.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with shell, file
edit, and code execution tools.

## 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
2026-11-23 09:38:42 -08:00
DottaandClaude Opus 5.5 70d4b6524c fix(antigravity): offer the cloud candidate in the agent picker for linux-x64 environments (#22655)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Google Antigravity is a native Runner harness (#22591). Its profile
is still pending, so only a company with an operator grant can see or
run it
> - A grant can name the cloud target (linux-x64), and save, Test and
execution already accept it for a cloud environment
> - The agent picker computed the candidate only for the local target,
so a company with a valid cloud grant never saw the harness for a cloud
environment
> - This pull request binds the picker to the selected environment's
target, in the Antigravity-owned module
> - The benefit is that a granted company can pick Antigravity for the
linux-x64 cloud environments that can run it, and still sees nothing
anywhere else

## Linked Issues or Issue Description

Refs #22591

**What happened?**
`GET /api/adapters?companyId=…&environmentId=…` returned
`candidateHarnesses` only when the environment target was `local`. A
company with a valid linux-x64 Antigravity grant got no candidate for a
Core sandbox or SSH environment.

**What did you expect?**
The picker offers the candidate for a linux-x64 cloud environment when
the company holds a grant for that target, the same way save, Test and
the executor admit it.

**Steps to reproduce**
1. Set a candidate grant that names linux-x64 for a company and exact
model.
2. Request the adapter list for that company with a linux-x64 sandbox
environment.
3. `paperclip_runner` has no `candidateHarnesses`.

## What Changed

- `antigravityCandidateForRunnerTarget` (in `antigravity-release.ts`)
decides the picker candidate per environment target:
  - local: unchanged.
- Core sandbox or SSH that is linux-x64, or the managed cloud image:
only a grant that names linux-x64 and its patched closure.
- plugin Runner-task environment, unknown or other platform, unavailable
Computer: none.
  - released profile: none.
- `GET /api/adapters` uses it for every resolved target. Expired or
mismatched grants stay quiet; malformed grants still log one warning.
- The qualification plan notes the picker rule and records, as an open
decision, why plugin Runner-task environments cannot run Antigravity
yet.

### Not in this PR: plugin Runner-task environments

Paperclip Cloud's warm Agent Computer runs agents only as plugin Runner
tasks. Antigravity cannot run there yet, and the fix is outside Core
alone:
- The plugin task credential contract
(`environmentTaskCredentialSchema`) has no Gemini API key type.
- The plugin prepares the provider launch from `launch-requirements.v1`,
which carries no candidate grant. The ACPX sidecar refuses a pending
profile without one.
- The Cloud plugin's harness table lists only Codex, Claude and
OpenCode. Kimi, Copilot and Pi do not run there either.
- Antigravity Test refuses the Runner-task path.

The picker therefore offers nothing for those environments until that
work lands.

## Verification

- Red, then green: `server/src/__tests__/adapter-routes.test.ts` "offers
a cloud environment the candidate only for the company's linux-x64
grant" failed before the fix and passes after it.
- New unit tests in `antigravity-release.test.ts` run the real grant
resolver: cloud grant offered, other company / arm64 / Runner-task /
expired / host grant refused, released profile offers none.
- `npx vitest run src/__tests__/adapter-routes.test.ts
src/services/native-runtime/antigravity-release.test.ts
src/services/native-runtime/acpx-qualification.test.ts
src/services/native-runtime/antigravity-candidate-admission.test.ts`: 98
passed.
- Server `tsc --noEmit`: clean. `pnpm verify`: see the CI checks for the
final revision.
- Not run live: no Antigravity prompt has completed in any environment
yet, and the only available Gemini key is free tier. No paid runner E2E
workflow was dispatched.

## Risks

- Low risk. The change is read-only catalog output. Save, Test and
execution keep their strict admission checks.
- A company that holds a linux-x64 grant now sees Antigravity for
linux-x64 sandbox and SSH environments. Those paths already accept that
grant.

## 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
- [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>
2026-11-23 11:09:22 -06:00
DottaandClaude Opus 5.5 5f5ac15436 fix(cloud): name every durable-data blocker in the online pass result (#22641)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - A hosted server moves its durable data to shared storage in bounded
online passes while it serves work
> - Each pass reports the remaining eligibility blockers and a code for
each item it left behind
> - The pass keeps its place between calls, but each result only lists
the codes of the phases that this call visited
> - A pass that finishes a round after an earlier call ran the workspace
phase reports `workspaces_require_migration` with no workspace code
> - This pull request carries each phase's codes from its latest visit,
and names a blocker that no visit explains
> - The benefit is that every data blocker in a pass result names a
cause

## Linked Issues or Issue Description

Refs #22270, #22294

**What happened?**
A staging stack ran repeated online durable-data passes. The pass result
reported `workspaces_require_migration`, but the `deferred` map had no
`workspaces:` code.

**Expected behavior**
Every data blocker in the pass result names at least one code.

**Steps to reproduce**
1. Run a pass whose budget ends right after the workspace phase. The
result shows the workspace codes.
2. Run the next pass. It resumes after the workspace phase and completes
the round.
3. See that the completed result reports `workspaces_require_migration`
with no workspace code.

## What Changed

- The pass keeps the codes of the latest visit of each phase. A new
visit of a phase replaces its earlier codes.
- When a data blocker has no code from this call, the result includes
the codes from the latest visit of the matching phases.
- When no visit explains a data blocker, the result names
`<phase>:pending_inspection`. For example, a workspace created after the
workspace phase ran shows `workspaces:pending_inspection`.
- Instruction blockers also get a code:
`local_instruction_copies_require_settlement` reports
`agent_files:instruction_copy_unsettled` and
`external_agent_instructions` reports
`agent_instructions:external_instructions_configured` when no agent-file
code explains them.
- One table maps each phase to its code prefixes and each data blocker
to its phases and fallback code. A test reads every blocker that
readiness can push and checks that each one gets a code.

## Verification

- `cd server && npx vitest run
src/services/online-durable-data-migration.test.ts
src/services/online-durable-data-migration-postgres.test.ts`: 31 passed.
- Red/green: the three new tests fail on `origin/master` (3 failed, 24
passed) and pass with this change.
- `pnpm verify` (see the PR comments for the result).

## Risks

- Low risk. The change only adds keys to the `deferred` map of the pass
result. It does not change what the pass moves or when a stack is
eligible.
- A carried code can describe a state from an earlier call in the same
round. The next visit of that phase replaces it.

> 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, 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>
2026-11-23 10:21:27 -06:00
DottaandClaude Opus 5.5 571b4bcae9 fix(workspaces): move a workspace with only a task warning online, as offline already does (#22650)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - A hosted server moves each local workspace to shared storage in
bounded online passes while it serves work
> - A task can carry a recovery warning that is only about the task, for
example a stranded assignment or a missing disposition
> - The offline move keeps such a warning unchanged and moves the files.
The online move with a source proof does the same
> - The online move without a source proof refuses the workspace with
`workspace_recovery_unresolved`, for example an archived workspace that
is kept as a restore point
> - Staging stacks stay blocked by this code (scott-test10 reports only
this code, for 15 workspaces)
> - This pull request gives the online move without a source proof the
same result as the other two paths
> - The benefit is fewer workspaces that block an online move, with no
change to the warning or the files

## Linked Issues or Issue Description

Refs #22270, #22294

**What happened?**
Repeated online passes on staging stacks leave workspaces blocked with
`workspaces:workspace_recovery_unresolved`. For a workspace without an
online source proof, any active recovery action on its task blocks the
online move, also a warning that is only about the task.

**Expected behavior**
A task-only warning does not block the online move, the same as in the
offline move and in the online move with a source proof. The warning
stays unchanged. Warnings that are about files or a run still block.

**Steps to reproduce**
1. Create a local workspace for a task. Add an active
`stranded_assigned_issue` recovery action to the task.
2. Run `migrateRemoteWorkspace` online (without `writersStopped`).
3. See that it fails with `workspace_recovery_unresolved`. The offline
move of the same workspace succeeds.

## What Changed

- `isTaskDispositionRecovery` names the existing task-only rule: kind
`stranded_assigned_issue`, `configuration_validation`,
`missing_disposition` or `deliberate_wait_without_target`, no workspace
export cause, and no file or run evidence. The proven online hold uses
it, with no change in behavior.
- The online move without a source proof records such a warning as an
online recovery hold with its fingerprint, as the proven path does.
Publication locks the action row and checks that the fingerprint did not
change.
- All other recovery actions still block the online move without a
source proof.

## Verification

- `cd server && npx vitest run
src/services/remote-workspace-migration.test.ts
src/services/remote-workspace-online-source.test.ts
src/services/remote-workspace-cohort-migration.test.ts
src/services/online-remote-workspace-recovery-hold.test.ts
src/services/online-legacy-workspace-recovery.test.ts
src/services/finalized-workspace-recovery-migration.test.ts` (embedded
PostgreSQL): 6 files, 410 tests passed.
- Red/green: the four new online cases of "preserves a task-only
warning" fail on `origin/master` and pass with this change. The online
case checks that the warning row is unchanged and that the restored
archive has the saved file.
- New tests: a task warning that gets file evidence during the online
upload still blocks publication. A `workspace_validation`, an
`active_run_watchdog` and an export-cause action still block the online
move.
- `pnpm --filter @paperclipai/server typecheck`: passed.

## Risks

- The online move now proceeds for a workspace whose task has only a
task-only warning. A run that the warning wakes is still fenced by the
existing `active_execution` and `task_writer_bound` checks at
reservation and at publication, the same as for an idle workspace with
no warning.
- If the warning changes during the upload, publication refuses and the
workspace stays local.

> 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, 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>
2026-11-23 10:21:22 -06:00
DottaandClaude Opus 5.5 98fd412851 fix(apps): show readable Google Workspace action names on Review and Permissions (#22630)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Connectors let agents use outside apps. The Google Workspace
connector gives agents Gmail, Calendar, Drive, Docs, Sheets and Slides
actions.
> - Each connection has a Review tab and a Permissions tab. People
approve actions and turn actions on or off there.
> - Google Workspace actions had no human title. These tabs showed the
internal tool name, for example `gmail__get_message` and
`calendar__list_events`.
> - Users must not see internal names. Google's app reviewers will also
look at these screens.
> - This pull request gives every Google Workspace action a readable
name, such as "Gmail: Read a message", for both tool transports.
> - The benefit is that people and reviewers see what each action does,
in plain words.

## Linked Issues or Issue Description

**What happened?**
On the Review tab and the Permissions tab of a Google Workspace
connection, action rows showed internal tool names. Examples:
`gmail__get_message` in the "Review new actions" list and the action
list, and "Calendar Create Event" in the "Waiting for your OK" list.

**Expected behavior**
Each row shows a readable action name, for example "Gmail: Read a
message" or "Calendar: List events". No row shows a `service__tool` name
or a raw ID.

**Steps to reproduce**
1. Connect Google Workspace.
2. Open Connectors, then the connection, then Permissions. Look at the
action list.
3. Open Review. Look at "Review new actions" and "Waiting for your OK".

**Paperclip version or commit**
master at 78e4f4f130.

## What Changed

- `server/src/google-workspace-rest-tools/`: each of the 36 Paperclip
REST tool definitions now has an MCP `title` (for example `get_message`
is "Read a message"). The change stays inside each tool's own file.
`allowlist.test.ts` now checks that every tool has a short title.
- `packages/shared`: new `googleWorkspaceToolTitle(name, title)`. For an
allowlisted Google tool it returns "<Service>: <action>". When no title
is known, it uses the action name in sentence case ("Gmail: Get
message").
- `server/src/services/google-workspace-rest-dispatch.ts`: new
`googleWorkspaceCatalogToolTitle`. For a Google Workspace connection it
uses the Paperclip REST title when one exists, then the upstream title.
It works the same for `google_mcp` and `paperclip_rest`.
`GOOGLE_WORKSPACE_TOOL_TRANSPORT` does not change.
- The server applies this title when it discovers the catalog, when it
reads the catalog, in the review queue list (`toolTitle`), and in the
gateway display name. The approval card text and preview use the display
name, so new requests show the readable name too. Rows saved before a
catalog refresh also get the readable name at read time.
- UI: the Permissions action list, the "Review new actions" list, the
agent access list, the action test dialog and the "Waiting for your OK"
list use one helper, `actionLabel`. It uses the readable Google name
when the server gives no title.
- No API field, route, permission check or company scope changes.
- `tests/runner-e2e/source-sdk-public-inputs.json`: refreshed, because a
pinned shared file changed.

## Verification

- Red, then green:
`ui/src/pages/apps/app-detail/GoogleWorkspaceActionLabels.test.tsx`
renders the Review tab and the Permissions action list with Google rows
as the server sent them before this change (no title, real UUIDs in
every ID field). It checks that no `service__tool` name and no UUID is
visible.
- Before: the test failed. The Review tab showed `gmail__get_message`
and "Calendar Create Event". The Permissions list showed
`calendar__list_events` and `gmail__create_draft`.
- After: the test passes. The tabs show "Gmail: Get message", "Calendar:
Create event", "Calendar: List events" and "Gmail: Create draft" with
this UI-only fallback. With the server change, the names are the REST
titles, for example "Gmail: Read a message".
- `server/src/services/google-workspace-rest-dispatch.test.ts`: every
allowlisted tool of every service gets a "<Service>: <Action>" title
with no underscores and no UUID, for both transports. Titles from other
connections do not change.
- `packages/shared/src/google-workspace-connectors.test.ts`: tests for
`googleWorkspaceToolTitle`.
- `server/src/google-workspace-rest-tools/allowlist.test.ts` and
`boundary.test.ts` pass.
- Focused runs: UI `src/pages/apps/app-detail`,
`ReviewQueueCard.test.tsx`, `AppDetail.test.tsx` (141 tests pass).
Server Google Workspace tests, review queue test,
`tool-access-service.test.ts`, `tool-gateway-service.test.ts`,
`connection-management.integration.test.ts` (2,212 tests pass).
- `pnpm --filter @paperclipai/shared typecheck`, `pnpm --filter
@paperclipai/ui typecheck` and `pnpm --filter @paperclipai/server
typecheck` pass.
- `pnpm verify` exits 2 because the pinned input registry is a global CI
input. Required CI gives the broad coverage.

## Risks

- Low risk. The change only affects display titles of Google Workspace
actions. Tool names, policies, grants and calls do not change.
- The gateway display name of a Google tool changes from its internal
name to the readable name. Agents see this text as the tool title only.
The tool name that agents call does not change.
- Approval previews saved before this change keep their old text until
the request is resolved.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), in Claude Code with tool use
(shell, file edit, 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
- [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>
2026-11-23 09:57:23 -06:00
DottaandClaude Opus 5.5 624a78fd5d fix(logging): keep tool-call arguments out of failed request logs (#22635)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Agents call connected tools, such as Gmail, Google Drive and Google
Docs, through the tool gateway
> - The HTTP logger writes the request body for every response with
status 400 or higher
> - The logger removes only keys with credential names, so tool
arguments stay in the log
> - Tool calls often return 4xx for normal outcomes, such as 409 when an
action needs approval
> - So email recipients, email bodies and document text go into server
logs
> - This pull request removes the request body from the logs of the
tool-call routes
> - The benefit is that user content from connected accounts does not go
into log storage

## Linked Issues or Issue Description

Refs #22010 (stored connection data). No existing issue; the issue is
described here.

**What happened?**
A failed or held tool call wrote its arguments to the server log. For
example, a Gmail draft that waited for approval (HTTP 409) logged the
recipients and the full message body.

**What did you expect to happen?**
The log keeps the route, the status and the error. The log does not keep
the tool arguments.

**Steps to reproduce**
1. Start an HTTP logger with the default redaction.
2. Send `POST /api/tool-gateway/tools/call` with tool parameters, and
make the route answer with 409.
3. Read the log line. The `reqBody` field contains the parameters.

## What Changed

- Add `isPrivateToolCallHttpRequest` in
`server/src/middleware/http-log-policy.ts`. It matches these routes:
  - `/api/tool-gateway/tools/call`
  - `/api/tool-gateway/gateways/:gatewayId/mcp`
  - `/mcp/gateways/:gatewayPublicId`
  - `/mcp/native-runs/:runId`
  - `/mcp/runtime-tools`
  - `/mcp/runner`
  - `/api/mcp/project-tools`
  - `/api/issues/:issueId/mcp-app-views/:viewId/tool-calls`
  - `/api/tool-connections/:connectionId/test-calls`
- In `server/src/middleware/logger.ts`, set `reqBody` to `[REDACTED]`
for these routes when the status is 400 or higher. The log keeps the
route path, the parameters and the redacted error context.
- Add tests in `server/src/__tests__/http-log-redaction.test.ts` for
statuses 400, 403, 409, 429 and 500, and a test that other routes keep
their body.

## Verification

- Red: the new test failed for all 5 statuses before the fix. The log
contained the canary recipient, body and document text.
- Green: `npx vitest run src/__tests__/http-log-redaction.test.ts
src/__tests__/sentry.test.ts` (from `server/`): 2 files passed, 114
tests passed.
- `pnpm verify` selected 2,977 of 3,852 test files (full-suite scope),
so required CI supplies broad coverage. `tsc --noEmit` for `server`
passed.

## Risks

- Low risk. The change affects only log output for the five tool-call
routes.
- Failed tool calls no longer show their arguments in the log. To debug
a call, use the tool invocation record, which stores a redacted summary.

> 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 edit, 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
- [ ] 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>
2026-11-23 15:54:17 +00:00
DottaandClaude Opus 5.5 a3af1ac6db fix(connections): remove connection content when a task or company is deleted (#22636)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Agents call connected apps, such as Google Workspace, and Paperclip
keeps parts of the results in tool-call records, approvals, run
transcripts and files
> - #22010 added "Delete data" on a connection. It removes that content
for one connection.
> - Deleting a task or a company did not run the same cleanup. Task
deletion set the task link to null on tool calls, approvals and runs, so
their previews and transcripts stayed. Company deletion removed the rows
but left run logs and files in storage.
> - Google's restricted-scope review requires that users can delete the
Google data we hold, and that the policy matches the product
> - This pull request runs the "Delete data" steps when a task is
deleted, and removes a deleted company's run logs and files from storage
in the background
> - The benefit is that deleting a task or a company removes every copy
of connection content, and a canary test makes sure that a new store
cannot skip these paths

## Linked Issues or Issue Description

Refs #22010

**Problem**
Deleting a task leaves connection content in tool-call previews, audit
history, approval requests, results passed to later runs, run
transcripts (events, excerpts, result text and the run log in every
copy) and saved tool results over 500,000 bytes. Deleting a company
leaves run logs (object journal, archive, local file, S3 mirror) and all
stored files, including attachments and saved tool results. "Delete
data" on a connection also left saved tool results over 500,000 bytes in
storage.

**Expected behavior**
Deleting a task removes the connection content of the task's runs and
calls. Deleting a company removes its run logs and files from storage,
not only its rows. "Delete data" removes saved tool results of the runs
whose transcripts it deletes.

**Steps to reproduce**
1. Let an agent call a connection on a task, so that the run has a log,
events and a saved tool result.
2. Delete the task, or delete the company.
3. Look in `tool_invocations`, `heartbeat_runs`, `heartbeat_run_events`
and object storage. The content is still there.

## What Changed

- New table `issue_connection_content_deletions`. Task deletion records,
in the same transaction and before the task row goes, the task's runs
that used a connection or are still working, the task's calls without a
run, and the task's call events that belong to neither. Audit entries
are matched by run, call or task. The background worker then runs the
existing "Delete data" steps for that scope. Runs of the task that are
still working are recorded too, even if they have not used a connection
yet, so a connection call they make after the deletion is also cleared.
The job rechecks every 1 to 5 minutes while runs or approvals are open
and finishes as soon as they settle, for up to a day. It writes an
`issue.connection_content_deleted` activity entry with counts only, and
only when it deleted something.
- New table `stored_object_deletions`. Company deletion records every
run log and every file of the company before the rows go. The table has
no foreign key to the company, so the removal continues after the
company is gone. Each object is retried with backoff until storage
confirms the deletion. Task deletion also records the task's attached
files here, so a failed best-effort delete in the route is retried.
- `content-deletion.ts` stays the one owner of "remove connection
content". Each job table has its own typed store (load, save, finish,
activity, failure), so no per-table column can compile against the other
table. The storage ledger is in `stored-object-deletion.ts`, and the
task request is in `issue-content-deletion.ts`. The steps now take a
scope (one connection, or the runs and calls of one deleted task). The
connection path behaves as before.
- "Delete data" and task deletion now also delete saved tool results
over 500,000 bytes (`runner-api` assets) of each run whose transcript
they delete: the object in storage and the asset row. Files attached to
a task, a case or a company logo are not touched.
- The canary test scans every text and JSON column and every storage
copy (object journal, legacy mirror, local files and file storage) after
a connection deletion, a task deletion and a company deletion. It also
checks that another task and another company keep their content.
- Docs: the store inventory in `doc/memory/google-connector-memory.md`
has columns for task and company deletion. The production checklist, the
code-fixes plan, the connector playbook and the user help page
`docs/guides/board-operator/deleting-connection-data.md` are updated.

## Verification

- `cd server && npx vitest run
src/__tests__/tool-connection-content-deletion-canary.test.ts` (12
tests). Before the fix, the new task and company tests failed: the scan
found the marker in run logs, the legacy mirror, local files, saved
results and attachments. The connection test also failed on the saved
tool result file.
- `cd server && npx vitest run
src/__tests__/tool-connection-content-deletion.test.ts
src/__tests__/google-managed-connection-removal.test.ts
src/__tests__/git-restore-point-ledger.test.ts
src/__tests__/agent-observability.test.ts` (85 tests pass).
- Nine more suites that delete tasks or companies pass (456 tests), for
example `decision-target-work`, `approval-retention-work`,
`cleanup-removal-service` and `tool-gateway-service`.
- `pnpm --filter @paperclipai/db typecheck` passes, including the
migration compatibility guard (`0501` is `online_compatible`: two new
tables and their indexes).
- `cd server && pnpm typecheck` passes.
- `pnpm verify` exits 2 because a global CI input changed. Required CI
supplies the broad coverage.

## Risks

- Migration: two new tables only. The previous release does not read
them, so it keeps working during the overlap deploy.
- Task deletion runs three more indexed queries in its transaction. It
creates a job only when the task used a connection.
- Company deletion inserts one ledger row per run log and per file in
its existing transaction. The storage work is batched in the background,
50 objects at a time.
- Company deletion now removes all of the company's files and run logs
from storage. Before, they stayed in storage with no row that pointed to
them.
- `stored_object_deletions` keeps `company_id` without a foreign key,
like `execution_workspace_restore_points`, so that removal can finish
after the company is gone. It holds object keys only, no content.
- A task deletion creates a job when the task used a connection or still
has a run that is working. While runs or approvals are open, the job
rechecks every 1 to 5 minutes. It stops waiting one day after the
deletion. It then writes `issue.connection_content_deletion_incomplete`
with the counts of what was still open, and that content stays. A job
that deleted nothing and left nothing open writes no activity entry.
- A run of the deleted task that was still working is in the scope. If
it calls a connection after the task is deleted, the job waits for it
and clears that content too.
- Not changed: deleting a company does not ask Google to revoke the
grant. Raw provider traces still expire on their own.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, in Claude Code with
tool use (shell, file edit, test runs). Extended reasoning 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
- [ ] 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>
2026-11-23 15:47:02 +00:00
DottaandClaude Opus 5.5 b7dea0f070 fix(native): store repeated provider pack bytes once in each workspace (#22241)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Native agents run in managed sandboxes, and each workspace needs the
provider pack (Node, provider CLIs and provider assets) before the
provider can start
> - The fleet sandbox image has an older provider pack in `/opt`, so the
server stages its own pack into each workspace and reuses image files
with the same bytes by copying them
> - The staged pack is about 3.0 GB of a 10 GiB sandbox disk, and agent
tasks on large repositories filled the disk
> - About 0.5 GB of that pack is the same bytes stored again under other
paths: one OpenCode binary in three packages, one Node binary in two
provider runtimes
> - This pull request stores repeated bytes once, as hardlinks to one
private copy, and copies a path that the image does not have from the
same bytes under another image path instead of transferring it
> - The benefit is about 550 MB more free disk per workspace, one less
large layer to transfer, and a faster staging step

## Linked Issues or Issue Description

**What happened?**
On staging, agent tasks on the Paperclip monorepo filled their 10 GiB
managed sandboxes. In a live fleet sandbox, the workspace's
`.paperclip-runtime/paperclip-runner/provider-pack` used 3.0 GB
(`node_modules` 1.4 GB, `provider-assets` 1.6 GB).

**Expected behavior**
A staged pack stores each large file's bytes once.

**Steps to reproduce**
1. Use a fleet sandbox whose image pack is older than the server's pack.
2. Start a native run in it.
3. In the staged pack, compare the three OpenCode binaries
(`opencode-ai`, `opencode-linux-x64`, `opencode-linux-x64-baseline`) and
the Pi and Kimi `node` binaries. They have the same bytes and different
inodes.

**Paperclip version or commit**
`e4b119440e` (master on 2026-11-18).

Related: #16493 added the layered reuse. #21784 reuses an image pack
that differs only in build provenance.

## What Changed

- `provider-pack-layers.ts` (remote reuse step):
- A large file whose bytes were already copied privately for another
path in this pack is a hardlink to that private copy.
- A large file that the image does not have under its own path is copied
from an image file with the same bytes under another path, and hashed,
instead of being transferred.
- Every staged file stays a physical file inside the pack. The image is
never linked, because the runner requires pack files and provider asset
folders to be physical paths inside the pack (OpenCode launch files,
Kimi and Pi installers).

## Verification

- `pnpm vitest run
src/services/native-runtime/provider-pack-archive.test.ts` (server): 50
passed, with real GNU tar and zstd. New tests:
- repeated bytes are one private inode (`nlink` 3), not the image's
inode; a path the image lacks comes from an image twin; only the overlay
is transferred; the image is unchanged
- when the image twin has different bytes, every repeated path is
transferred and has the correct bytes
- Red/green: the first new test fails on master's code and passes with
this change. The second is a safety test and passes on both.
- Replay on real fleet sandboxes. I created fresh Daytona sandboxes from
the staging fleet snapshot `fleet-sbx-6d5b52eaeeb7`. I used the real
file list (paths, sizes, SHA-256) of the current server pack, taken from
a live staging workspace. Each replay ran the reuse step, the overlay
extraction and the verifier's tree walk.
- Disk per workspace, including the layers that are still transferred:
3,033 MB before, 2,484 MB after (−549 MB).
- Transfer: the Kimi Node binary layer (126 MB uncompressed) is no
longer transferred.
- Staging time, same sandbox, alternating order (s): before 5.78, 5.84,
7.39, 7.61; after 5.13, 5.40, 7.04, 6.73. After is faster in all 4
pairs. The reuse step alone: before 2.42–3.59 s, after 1.85–2.99 s.
- `pnpm verify`: see the comment below.

## Risks

- Repeated bytes share one inode inside the pack. A process that writes
one of these binaries also changes its twins. Provider binaries are not
written at runtime.
- The image is only read, never linked or changed.
- No migration, API, or configuration change.

## Model Used

Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used in Claude Code with
tool use and code execution (shell, Daytona API, local 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
- [ ] 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>
2026-11-23 09:33:29 -06:00
DottaandClaude Opus 5.5 06d488b430 fix(telemetry): report every Paperclip runner harness as its own adapter_type (#22637)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The server sends `agent.task_run` and `agent.task_completed`
telemetry. Each event has an `adapter_type` dimension with a fixed enum
in the generated telemetry contract.
> - #22324 made a Paperclip runner agent report its underlying harness
as `adapter_type`.
> - Seven harnesses that the runner can resolve to are not in the enum:
Copilot, Antigravity, AWS AgentCore, Claude Managed, Grok Bot, Muse and
OpenAI Dot. Delivery normalizes them to `other`, on open source and on
Cloud.
> - Thus, the adapter breakdown in analytics still has an `other` bucket
that no build can fix.
> - This pull request syncs the telemetry contract, which now lists the
seven harnesses, and sends Copilot as `copilot_runtime`.
> - The benefit is that every runner harness has its own `adapter_type`
value in analytics.

## Linked Issues or Issue Description

Refs #22324

**What happened?**
A Paperclip runner agent that uses Copilot, Antigravity, AWS AgentCore,
Claude Managed, Grok Bot, Muse or OpenAI Dot sends an `adapter_type`
value that is not in the generated contract enum. The value is
normalized to `other`. Copilot also sends `acpx:copilot`, which is not a
contract-style name.

**Expected behavior**
Each runner harness reports its own `adapter_type` value. Copilot
reports `copilot_runtime`, which is the name
`agentRuntimeSettingsHarness()` already uses.

**Steps to reproduce**
1. Create a Paperclip runner agent with `provider: "acpx"` and
`acpxAgent: "antigravity"` (or `"copilot"`).
2. Let the agent finish a run.
3. Look at the `agent.task_run` event. `adapter_type` is `other`.

**Paperclip version or commit**
`master` at 30881e6aa9.

## What Changed

- `packages/shared/src/telemetry/generated/paperclip-telemetry.ts`: sync
the generated contract. The `adapter_type` enum on `agent.task_run` and
`agent.task_completed` now lists `antigravity_runtime`,
`copilot_runtime`, `aws_agentcore`, `claude_managed`, `grok_bot`, `muse`
and `openai_dot`. The source schema changed in the telemetry backend
first, and the collector accepts these values once that change deploys.
- `server/src/services/agent-task-run-telemetry.ts`:
`telemetryAdapterType()` sends `copilot_runtime` for the `acpx:copilot`
harness. All other values are unchanged.
- `server/src/__tests__/agent-task-run-telemetry.test.ts`: the coverage
test now expects no runner harness to be missing from the contract.
Added Copilot and Antigravity cases to the runner `adapterType` table.
- `packages/shared/src/telemetry/README.md`: replace the list of known
gaps with the Copilot rename and the steps to add a new harness.
- `tests/runner-e2e/source-sdk-public-inputs.json`: refresh the pinned
inputs for the two changed shared files.
- Cloud direct delivery fixtures were regenerated with
`scripts/generate-posthog-direct-fixtures.mjs` from the updated backend.
No fixture changed.

## Verification

- Red/green: before the fix, 3 tests failed (`expected 'acpx:copilot' to
be 'copilot_runtime'`, and seven harnesses missing from both event
contracts). After the fix, `agent-task-run-telemetry.test.ts` passes
52/52.
- `npx vitest run server/src/__tests__/agent-task-run-telemetry.test.ts
server/src/__tests__/posthog-direct-telemetry.test.ts
packages/shared/src/telemetry`: 117 passed.
- `pnpm --filter @paperclipai/shared typecheck` and `pnpm --filter
@paperclipai/server typecheck`: pass.
- `pnpm verify` asked for broader coverage (exit 2) because the pinned
runner-e2e inputs changed. Required CI supplies that coverage.

## Risks

- Low risk. The change only adds enum values and renames one value that
delivery already dropped to `other`. Older collectors still accept the
events and normalize unknown values to `other`, so nothing is
quarantined while the backend deploys.
- Analytics: `copilot_runtime` replaces `other` for Copilot runner
agents. No dashboard filters on `acpx:copilot`, because that value never
reached analytics.

## Privacy Review

This is a Telemetry change under `rules/data-paths.mdc`. I request a
privacy review.

- Data added: seven new allowed values for the existing `adapter_type`
enum dimension on `agent.task_run` and `agent.task_completed`. They are
fixed harness names chosen by Paperclip code: `antigravity_runtime`,
`copilot_runtime`, `aws_agentcore`, `claude_managed`, `grok_bot`,
`muse`, `openai_dot`.
- No new field. No free text, user content, identifier, credential, URL
or host is added. The schema classification stays `non_personal`.
- These values were already sent from the app. Before this change the
receiving layer normalized them to `other`. After this change it keeps
the harness name.
- The generated contract and `packages/shared/src/telemetry/README.md`
are updated in this pull request.

## Model Used

Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use
(shell, file edits, PostHog HogQL queries).

## 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>
2026-11-23 09:32:42 -06:00
DottaandClaude Opus 5.5 78b10a43ce fix(customer-success): fit oversized inspection list pages instead of failing (#22625)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Paperclip Cloud can do audited, read-only customer-success
inspection of a stack through `/api/customer-success/v1/read`
> - The tenant rejects any inspection response over 2 MB with 422
> - Run rows are large, so a 25-row `runs` page is often over 2 MB on a
busy stack
> - Cloud reports the 422 to the agent as a refused read, so the agent
cannot tell that a smaller page works
> - This pull request makes an oversized list page return the largest
prefix of rows that fits, with `nextOffset` at the first omitted row
> - The benefit is that list reads succeed at any page size, and normal
pagination gets the rest

## Linked Issues or Issue Description

**What happened?**
A customer-success agent listed `runs` with `limit` 25 on 9 stacks. Each
read failed as refused. The same reads with `limit` 3 and `limit` 1
succeeded. A `tasks` list with `limit` 25 on the same stack succeeded.

**Expected behavior**
A list read returns rows and a `nextOffset`. The size limit must not
fail the whole page when fewer rows fit.

**Steps to reproduce**
1. Seed a company with 25 tasks that each have a 200 KB description.
2. Send a valid inspection permit for `list tasks` with `limit` 25.
3. The response is 422 "Inspection response is too large".

## What Changed

- `server/src/routes/customer-success.ts`: add `fitInspectionResponse`.
When a list response is over 2 MB, it does a binary search for the
largest row prefix that fits. It sets `nextOffset` to `offset + count`.
A single row that cannot fit still gives 422.
- `server/src/__tests__/customer-success.test.ts`: add a route test with
25 large tasks and a unit test for the helper.

## Verification

- `npx vitest run src/__tests__/customer-success.test.ts
src/__tests__/customer-success-cloud.test.ts`: 12 passed, 1 skipped.
- Red/green: with the old size check, the new route test fails with
`expected 422 to deeply equal 200`. With the fix it passes.
- On a staging stack, `runs` with `limit` 25 failed and `limit` 3
succeeded, which matches the cause.

## Risks

- Low. Only responses that already failed with 422 change. A page can
now hold fewer rows than `limit`. Callers already follow `nextOffset`.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), via Claude Code, with 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 (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>
2026-11-23 08:55:01 -06:00
DottaandClaude Fable 5.2 78e4f4f130 feat(runner): Antigravity on ACP 1.5.2 with Linux, API-key auth and Gemini 4 Neon (still pending) (#22591)
## Thinking Path

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

## Linked Issues or Issue Description

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

## What Changed

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

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

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

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

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

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

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

## Verification

Commands that passed on the final revision:

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

Known failures that also fail on `master`:

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

Live evidence, without a prompt:

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

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

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

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

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

## Risks

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

## Model Used

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

## Checklist

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

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

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-23 08:21:11 -06:00
DottaandClaude Opus 5.5 50cee0cb8f fix(recovery): do not hold a task for a retry cancelled before it started (#22262)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The heartbeat service holds a task for reconciliation when a legacy
run stops and Paperclip cannot tell which of its actions took effect
> - A task moved to backlog while its automatic retry still waited for
its scheduled time. The control plane cancelled that retry before anyone
claimed it
> - The cancelled retry had no start time, stage, process, lease or
execution events. It still got an "unknown outcome" hold, because its
chain had already spent two failure retries
> - After that, every wake was refused with
`execution_reconciliation_required`, and Retry could not clear the hold.
The rule is that a Retry button that is shown must work
> - This pull request treats an unclaimed control-plane cancellation
like the other never-started dispatch cancellations
> - The benefit is that the task continues on its next wake or Retry,
and tasks that are already stuck recover without manual work

## Linked Issues or Issue Description

Refs #20752 (related: it hardens the `queued` cancel marker; it does not
cover a cancelled `scheduled_retry`)

**What happened?**
A task had a pending scheduled retry (status `scheduled_retry`, never
started). The task moved to backlog, and the control plane cancelled the
retry (`errorCode: "cancelled"`, cancellation `source: control_plane`,
`expected: true`, initiator `system`). The chain had
`executionRetryAccounting.failureRetries = 2`. Terminalization recorded
a `legacy_execution_requires_reconciliation` hold with automatic replay
blocked. When the task moved back to todo, each new run was cancelled
before it started with `execution_reconciliation_required`. The task
showed `canRetry: false`, and a Retry press did not start a run or clear
the hold.

**Steps to reproduce**
1. Give a legacy-runtime agent a task with a pending `scheduled_retry`
run whose chain has spent two failure retries.
2. Move the task to backlog. The control plane cancels the pending retry
with `expectedStatus: "scheduled_retry"`.
3. Move the task to todo, then press Retry.

**Expected behavior**
The cancelled retry never ran, so there is nothing to reconcile. The
next wake or Retry starts a fresh run.

**Actual behavior**
The task stays held. Every wake is refused, and Retry does not start a
run.

## What Changed

- Root cause 1: cancelling a never-started run stamps "no provider work"
evidence only when its status was `queued`, not `scheduled_retry`.
- Root cause 2: `legacyExecutionNeedsReconciliation` returns "hold" when
the chain has two or more failure retries, before it reads any
no-provider-work evidence.
- `neverStartedDispatchCancellationPredicate` (and its synchronous
pre-check in `isPreDispatchReviewWaitVerified`) now also accepts an
expected system `control_plane` cancellation with `errorCode =
"cancelled"`. It requires the same retained-execution proof as the
dispatch-gate cancellations. A retry also needs a settled predecessor
(`settledRetryPredecessorPredicate`). Terminalization records a
reconciliation hold on a predecessor whose outcome is unknown, and the
scheduler does not retry such a run. So the predecessor must exist and
carry no effective or superseded reconciliation hold. A row with retry
metadata whose predecessor was deleted fails closed. Workspace-wait
chains keep their dedicated proof. The candidate check reads the
cancellation with `readRunCancellation`; the SQL predicate in
`pre-dispatch-execution-evidence.ts` is the single proof.
- The same predicate is used at terminalization (no new hold) and in
`executionBlockerPredicate` (a hold that an earlier release recorded no
longer blocks). Tasks that are already stuck therefore recover on their
next wake or Retry. The audit row is kept.
- `doc/heartbeat-internals.md` documents the rule.

## Verification

- New
`server/src/__tests__/never-started-retry-cancellation-hold.test.ts`:
- backlog cancel of a pending retry (real `cancelRun` with
`expectedStatus: "scheduled_retry"`) → no hold → todo → Retry queues a
fresh run, and the dispatch gate sees no blocker;
- a hold recorded by an earlier release plus a refused todo run → Retry
queues a fresh run, and the blocker clears;
- the hold stays when the cancelled retry shows a start time, a process,
a stage, an execution event, or an unexpected cancellation, or when its
predecessor is held or was deleted. The main case runs with three real
chains: a transient failure before provider work, an
`ai_connection_busy` wait, and an environment wait after a succeeded
run.
- Red/green: without the fix, the first two cases fail (the blocker
shows `canRetry: false` and "Automatic recovery stopped…"). With the
fix, all 11 cases pass (4 fail without it).
- Related suites pass: `explicit-native-continuation`, `task-retry`,
`legacy-execution-recovery`, `heartbeat-undispatched-execution-wait`,
`issue-scheduled-retry-routes`, `execution-blocker-read`,
`legacy-continuation-authority` (728 tests across 8 suites).
- `pnpm typecheck` in `server/` passes.
- Note: 7 tests in `chat-channels.integration.test.ts` ("reconciled chat
retry delivery ownership") fail locally when the full file runs, on
unmodified `master` too. A continuation from an earlier test in the
shared database leaks into their global delivery sweep. They pass when
run alone. This change does not cause them.

## Risks

- Low risk. The exemption needs all of these: a legacy run; `cancelled`
status with `errorCode = "cancelled"`; an expected system
`control_plane` cancellation; no retained execution evidence (start,
stage, controller, process, session, lease, finalization or execution
events); and, for a retry, a predecessor that still exists and has no
reconciliation hold. Operator Stops, failed predecessors and runs with
any execution evidence keep today's behavior.
- No migration. Historical holds are kept as audit rows. They only stop
blocking.
- Not covered here: a retry cancelled while its predecessor failed with
unknown outcomes keeps its hold. That case needs a separate decision
about where Retry should anchor.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude
Code with tool use (shell, file edits, test runs) 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
- [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>
2026-11-23 07:49:59 -06:00
7a2ee0da1c fix(connections): answer AWS setup refusals with 422 instead of 502 (#22581)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Connections let agents use outside services. The AWS connection gets
short-lived AWS credentials for each connection.
> - When AWS refuses the customer's role, key or sign-in policy, the
health check maps the failure to HTTP 502.
> - The error handler reports every 5xx response as a server crash. So a
customer's AWS trust setup error goes to Sentry as a Paperclip fault.
> - This pull request answers these AWS setup refusals with 422. An AWS
outage (`aws_unavailable`) stays a 502.
> - The benefit is that Sentry shows only real server faults, and the
customer still sees the same message that tells them what to fix.

## Linked Issues or Issue Description

**What happened?**
A staging health check for an AWS role connection failed because AWS did
not accept the role (`aws_role_access_denied`).
`healthFailureHttpStatus` returned 502. The error handler then sent "AWS
refused this connection's role. Check that the role exists and trusts
this connection." to Sentry as a crash.

**Expected behavior**
A refusal that the customer must fix in their own AWS account is a
client-side setup error. The server must answer with a 4xx status and
must not report a crash.

**Steps to reproduce**
1. Connect AWS with the role method.
2. Make the role stop trusting the connection.
3. Run a connection health check. The response is 502 and Sentry gets an
error event.

No public GitHub issue exists. Related: #22195 (AWS connector), #22233
(AWS role setup). I found no duplicate open PR.

## What Changed

- `healthFailureHttpStatus` returns 422 for AWS configuration failure
codes (`aws_*` except `aws_unavailable`). `sanitizeHttpFailure` and the
status mapping now use one shared helper for this code set.
- The AWS connector integration test now checks that a role refusal
answers 422 with code `aws_role_access_denied`.
- New unit test `failures.test.ts` checks every AWS setup code maps to
422, and that `aws_unavailable` stays 502.

## Verification

- `cd server && npx vitest run
src/services/tool-access/catalog/failures.test.ts
src/__tests__/aws-mcp-connector.test.ts` passes (9 tests).
- Without the fix, the same run fails 2 tests (`expected 502 to be
422`), so the tests prove the regression.
- `npx vitest run src/services/connectors/aws` passes (14 tests).
- The UI AWS setup screen reads the `aws_*` code, not the HTTP status,
so its copy does not change.

## Risks

- Low risk. Only the HTTP status of AWS setup failures changes, from 502
to 422. The response body, code, health status and message do not
change. AWS outages still answer 502.

## 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: paperclipbugbot <356415228+paperclipbugbot@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 21:04:11 -08:00
be08705f66 fix(workspaces): let the full-disk read-only save inventory a large workspace (#22546)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - After a remote run, Paperclip saves the sandbox workspace. When the
sandbox disk is full, #19465 copies a verified read-only source to the
controller and seals the archive there.
> - Before any transfer, the fallback inventories the sandbox tree. That
inventory refuses with `budget` once it has scanned 100,000 directory
entries.
> - Normal capture has no entry cap. Its sealed manifest is limited to
64 MiB, and the fallback seals with the same codec, so the codec already
bounds the archive.
> - #19619 made the fallback's reason visible. On staging, a full-disk
save then stopped seven times at `stage=inspect reason=budget_exceeded`.
Normal capture later saved the same workspace with 83,417 entries once
space was freed.
> - This pull request raises the scanned-entry bound so the fallback
accepts any tree normal capture can archive.
> - The benefit is that a full sandbox disk no longer blocks the save of
a large workspace, and the fallback still fails closed on runaway trees.

## Linked Issues or Issue Description

Refs #19465
Refs #19619

**What happened?**

On staging, a retained sandbox with a full disk was re-saved every ~30
minutes. Each attempt recorded:

`remote_workspace_sandbox_disk_full: the sandbox disk is full; free
space in the sandbox before saving the workspace;
remote_workspace_readonly_capture_failed: stage=inspect
reason=budget_exceeded transport=provider_error`

The fallback never started a transfer. After the provider cache was
reclaimed, normal capture saved the workspace (83,417 entries, 3.08 GB).

**Expected behavior**

The read-only fallback accepts the same trees as normal capture. Its
whole-tree work stays bounded by the shared 64 MiB manifest limit, the
command timeout, and the existing verification deadline.

**Steps to reproduce**

1. Create a workspace with more than 100,000 directory entries.
2. Call `readWorkspaceInventory` on it (the same function the sandbox
script runs).
3. On `master` it throws `remote_workspace_readonly_capture_budget`.
With this change it returns the inventory.

## What Changed

- `readWorkspaceInventory`: the whole-tree scanned-entry bound goes from
100,000 to 2,000,000. There is no separate per-directory bound: normal
capture has none, and a per-directory bound rejected flat directories
that normal capture archives. The smallest manifest entry
(`{"path":"a","type":"symlink","target":"b"}`) is about 41 bytes, so a
64 MiB manifest holds at most about 1.6 million entries. The bound
remains as a stop for runaway fan-out.
- Unchanged: the 64-repository bound, the Git config size bounds, the
refspec and settings bounds, the source-safety checks, the command
timeout, and the two-minute verification deadline. A budget or deadline
failure still keeps the disk-full code and the retained source.
- New test `remote-workspace-readonly-inventory-entries.test.ts`: a
101,202-entry tree (relative symlinks to a sibling file) is inventoried
in sandbox mode and in controller-copy mode, and both results match. A
second test checks that one directory with 100,002 entries is accepted
in both modes.

## Verification

- Red on `master` (`7671e0cf0d`): the new test fails with
`remote_workspace_readonly_capture_budget`, the error staging recorded.
- Green with this change: both new tests pass; both fail on `master`
with `remote_workspace_readonly_capture_budget`.
- Review follow-ups: `a0945b14` removed the added code comments
(CONTRIBUTING.md) and tried a per-directory bound; `335af975` removed
that bound again after review showed it rejects valid flat directories.
Related suites: 181 passed, 5 failed; the 3 listed below plus two 15 s
timeouts (`restores offline partial Git state…`, `…partial-sparse…`)
that are also flaky on unchanged `master` in this sandbox.
- From `server/`: `npx vitest run
src/services/remote-workspace-readonly-inventory.test.ts
src/services/remote-workspace-readonly-capture-budget.test.ts
src/services/remote-workspace-readonly-capture-cause.test.ts
src/services/remote-workspace-transport.test.ts`: 183 passed, 3 failed.
The 3 failures (`rejects an unsafe restore lock…: directory_shared`,
`does not run ambient checkout filters…`, `uses trusted SSH rewrites
only for clone…`) fail the same way with unchanged `master` source in
this sandbox, because its Git wrapper blocks clones. CI is the authority
for them.
- A full typecheck was not run locally (it runs out of memory in this
sandbox); CI typecheck and build must pass.
- Environment: Linux, Node v25.9.0, filtered `pnpm install` of the
server package.

## Risks

- Medium-low. The fallback can now spend longer inventorying a very
large tree. The command timeout and the verification deadline still
bound that time, and an expired deadline fails closed with the disk-full
code and the source retained.
- Per-directory names are held only while that directory is visited. The
capture codec already reads each directory's names in full and holds an
entry for every path in the tree when it seals the controller copy, so
the inventory never needs more memory than sealing the same tree. The
exclusion list keeps its 64 KiB bound.
- No retry, recovery or receipt behavior changes.

## Model Used

- Provider: Anthropic. Model: Claude Opus 5.5 (`claude-opus-5-5`), used
through Claude Code with tool use (shell, file editing, test runner,
GitHub connector). The exact context window is not shown in this
session.

## 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 (the new test passes; the
three clone/lock failures also fail on unchanged `master` here)
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes (no
change needed: no document states the entry bound)
- [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: paperclipbugbot <356415228+paperclipbugbot@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 09:47:26 -08:00
7671e0cf0d fix(identity): read a provisioned agent key without an exclusive agent row lock (#21506)
Run setup reads an existing agent identity key under FOR KEY SHARE on the agent row instead of FOR UPDATE, so it no longer joins queued-run claim deadlocks. The lock still waits for an in-progress agent deletion. First provisioning uses the same lock with ON CONFLICT DO NOTHING.

Co-Authored-By: paperclipbugbot <paperclipbugbot@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 01:17:29 -08:00
Devin FoleyandPaperclip 28ed2f1db0 fix(runner): support native OpenCode on macOS SSH hosts (#22534)
## Thinking Path
> - Paperclip coordinates agents across local, SSH, and sandbox
environments.
> - Native Runner must launch artifacts for the execution host.
> - A Linux controller currently selects Linux OpenCode assets for a
macOS SSH host.
> - Remote launch-file validation also accepts only ELF executables.
> - The standard Core image must carry a verified Mac runtime for this
host pair.
> - This pull request adds that runtime and selects it for Apple Silicon
SSH hosts.
> - Self-hosted and hosted controllers can use the same generic
implementation.

## Linked Issues or Issue Description
**What happened?**
A native OpenCode run on an Apple Silicon SSH host receives Linux
controller artifacts. Its private launch-file verifier also rejects
Mach-O files. A working legacy CLI agent does not exercise this path.

**Expected behavior**
The controller must select and verify the target's native daemon, Node,
OpenCode executable, and proxy. Existing Linux targets and legacy agents
must keep their current behavior.

**Steps to reproduce**
1. Run a standard Linux Core image.
2. Select an SSH environment on an Apple Silicon Mac.
3. Start a native OpenCode agent with a compatible model connection.
4. Observe the incompatible runtime selection before useful agent work.

**Paperclip version or commit**
Base: `324ec1f537a9ba1e84239faa81bcef326a5dd1b7`.

**Deployment mode**
Docker or another Linux controller, with macOS ARM64 execution over SSH.

Related work: #21662 covers local OpenCode confinement. #22236 covers
SSH process cleanup. This change does not depend on either PR. No
duplicate macOS OpenCode runtime PR was found.

## What Changed
- Select a verified `darwin-arm64` runtime for OpenCode SSH targets.
Preserve the Linux image default and explicit operator overrides.
- Verify Mach-O launch files against the admitted architecture, file
digests, and remote account. Keep existing Linux receipt and recovery
behavior.
- Build the Mac runtime on an Apple Silicon CI host with standalone Node
24.21.0. Keep OpenCode pinned to 1.18.34.
- Package the sealed OpenCode runtime artifacts and required package
metadata. Omit other harness distributions and their optional
qualification inventories.
- Verify archive provenance and safe extraction on Linux. Include the
runtime in standard and merge-queue Core images. Avoid storing the
transport archive in an image layer.
- Reuse artifacts only from successful protected master image builds
with identical runtime inputs. Test cache trust boundaries and register
the script tests in CI.
- Document runtime delivery, manual image inputs, and the initial Apple
Silicon scope. No Cloud source, schema, or agent configuration changes.

## Verification
- `pnpm -r typecheck` — passed.
- `pnpm build` — passed.
- Focused OpenCode artifact selection and private staging tests — 21
passed.
- Focused native executor tests for OpenCode, SSH, and provider packs —
60 passed.
- Real Rust daemon transport tests with the OpenCode protocol fixture —
4 passed.
- Installed OpenCode 1.18.34 server qualification with a local provider
fixture — 3 passed.
- Runtime packaging, cache trust, workflow, image-contract, and
merge-queue tests — 26 passed.
- The CI release-workflow test group, including canary reuse and
provenance — 218 passed.
- Docker workflow and build-stamp guards — 29 passed after adding the
Mac digest expectation, updating the excluded-source COPY expectation,
and removing the redundant production commit ARG.
- The source SDK registry, public-type, and evidence checks — 59 passed
after updating only the root package metadata hash. Lock, compiler,
parser, and model pins did not change.
- Fresh-host provider-pack upload harness — 7 passed. The new regression
first failed with `package_version:acpx`, then passed after the required
metadata was preserved.
- Node version policy — passed against a clean tracked-file snapshot.
Generated local provider assets make the direct workspace scan fail;
they are absent from the CI checkout.
- Built, packaged, installed, and verified the actual Mac runtime. Both
the controller verifier and the remote startup verifier accept its pins,
target, sealed files, manifest, and package metadata. The pre-change
private launch verifier rejects the real Mach-O files; the candidate
accepts those same files. The dedicated archive is about 101 MB.
- Live native smoke: real Mac daemon, private staged Mach-O files,
OpenCode 1.18.34, and a local GLM-5.3 backend. The model read two files,
edited the implementation, ran three tests, completed the semantic
finish call, and summarized the three passes. An independent test run
passed. The test file stayed unchanged. This used the existing `allow`
mode and a scratch account-home fixture on a Mac. It does not prove
hosted SSH dispatch.
- The full CI workflow passed on
`ae74808631f1933edec89aa1e80db7f2b756aca3`: server test shards, Runner
Rust and native server tests, type checking, builds, browser suites,
image checks, the native Mac producer, and Linux runtime installation.
Greptile is 5/5 with no unresolved threads.
- Local `pnpm test:run` used a disposable PostgreSQL 18 fixture after
embedded Postgres failed to start because its macOS package lacks
dynamic libraries. All six chat shards passed (1,971 tests). The
redundant unsharded local run was interrupted during the general-server
group after all current-head CI test jobs passed. The later local
workspace and serialized groups did not run. The owned PostgreSQL
fixture is stopped. This is not a local full-suite pass.

Retained review failures: the first PR revision omitted package metadata
and did not ignore downloaded image inputs. The fresh-host upload
regression reproduced the metadata failure before its fix. Generated
inputs are now ignored. CI also exposed a missing Node policy exception
for the pinned Mac producer; the exception is limited to that producer
job. A later policy attempt exposed an old exact-dependency assertion in
canary reuse tests. The assertion now covers the added runtime and
evaluates the publication gate for success, failure, cancellation, and
skip outcomes. The Runner support suite then found that the new test
registration changed a pinned root package input; the standard source
registry generator updated that one hash, and all 59 affected tests
passed. The server matrix then found four outdated image guard
expectations and a duplicate production commit ARG. The focused image
guards now pass after updating those expectations and keeping one commit
ARG before Mac verification.

Retained failures: the first producer attempt used Homebrew Node, which
failed the relocation check. The successful producer used standalone
Node 24.21.0. Live smoke attempts also encountered a stopped tunnel, an
upstream model failure, and the existing Rust restriction on OpenCode
permission requests in `ask` mode. The successful tool trace used the
existing `allow` mode. Its initial reporter looked for tool names in
generic item events; verification of the retained canonical tool events
and an independent rerun confirmed the result. The upstream model
failure is not explained by a later pass.

Not run locally: a full Docker image build, because the existing Docker
daemon does not respond. The PR adds native producer qualification and
Linux installation verification to CI. Hosted deployment, remote
service-account dispatch, and hosted continuation remain acceptance
steps after deployment.

## Risks
- A cold Mac runtime build adds CI time when Runner or producer inputs
change. Reuse is bounded and accepts only a successful protected master
producer. The artifact digest and runtime input identity remain
verified.
- Standard images gain a dedicated Mac runtime payload. Manual image
builds can omit it; Mac OpenCode SSH runs then fail with a named
missing-runtime error. Linux behavior remains available.
- This release covers Apple Silicon SSH distribution. It does not
qualify Intel Mac distribution or expand other harness support.
- The OpenCode permission bridge keeps its existing behavior. This PR
does not add `ask` approval support.
- No saved run/session schema or provider pin changes. Existing Linux
receipts retain their interpretation. A surviving admitted Runner
bypasses new artifact discovery. Legacy agents are not converted.
Existing account-change and old-receipt restoration tests remain in
coverage.
- No migration, cluster change, new sandbox image requirement, or Cloud
control-plane change. A staging application rebuild and deployment are
separate from this PR.

## Model Used
OpenAI GPT-6, through Codex, with repository tools, code execution,
tests, and SSH inspection. The session does not expose a more specific
model ID or context-window size.

## Checklist
- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-22 00:07:34 -08:00
7e30ba2c45 fix(recovery): report an unprepared saved skill on resume instead of a skill access change (#22395)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Native Runner executions can be suspended, for example by a server
restart, and then resumed from their saved admitted input
> - On resume, runtime selection checks that every saved skill in the
admitted runtime context is still available
> - The check treated a permitted skill whose saved version could not be
prepared on this host the same as a skill the agent can no longer read
> - The run failed as `configuration_incomplete` with "Project skill
access changed while this execution was suspended", the task went to the
board, and the real preparation error was lost
> - This pull request separates the two cases: an absent saved skill is
still an access change, and a present skill with a missing source fails
with its actual preparation detail
> - The benefit is a correct failure message and recovery route, and a
recorded cause for the underlying preparation fault

## Linked Issues or Issue Description

**What happened?**
Two resumed native runs on staging failed right after a server restart
with `ConfigurationIncompleteFailure: Project skill access changed while
this execution was suspended. Restore access or start a new execution.`
Skill access did not change. The first attempt of each run prepared all
four saved skills. After the restart, the resumed attempt failed. The
tasks went to board recovery with a "secret is not set" next action and
stayed blocked.

**Expected behavior**
Preparation already refuses a saved skill that the agent can no longer
read ("A pinned skill is unavailable or no longer permitted"). So, at
the resume guard, a saved skill that is absent from the current entries
is an access change. A saved skill that is present but whose source is
`missing` had a preparation failure (cache, storage or materialization).
That run must fail with the actual `missingDetail`, as a fresh admission
does in `materializeSelectedSkills`. It must not claim an access change.

**Steps to reproduce**
1. Admit a native run whose saved `skillVersions` pin a skill.
2. Resume it with the same skill entry, but with `sourceStatus:
"missing"` and a materialization `missingDetail`.
3. Before this change, the resume rejects with
`ConfigurationIncompleteFailure` "Project skill access changed".

## What Changed

- `selectHeartbeatRuntime` resume guard: a saved skill that is absent
from the current runtime skill entries still raises
`skill_access_changed`.
- A saved skill that is present with `sourceStatus: "missing"` now
throws a plain error that names the skill key and its preparation
detail. The admitted revision and saved skill pins stay unchanged.
- Regression test for both the unprepared case (red before, green after)
and the available case. The existing revoked-access test is unchanged
and still passes.

## Verification

- `cd server && npx vitest run
src/services/heartbeat/runtime-selection.test.ts`: 92 passed. The new
`missing` case failed before the fix with `expected
ConfigurationIncompleteFailure ... to not be an instance of
ConfigurationIncompleteFailure`.
- `cd server && npx vitest run
src/__tests__/heartbeat-runtime-skills.test.ts
src/__tests__/heartbeat-execution-configuration.test.ts`: 56 passed.
- `pnpm run typecheck` (server): passed.
- The broad `pnpm verify` selection did not finish within the local time
limit. Required CI supplies that coverage.

## Risks

- Low risk. The change is in one guard. Real access revocation keeps its
existing error and board route.
- An unprepared skill on resume now follows the ordinary failed-run path
(`adapter_failed`) instead of `configuration_incomplete`. This is the
same as a fresh admission with a missing skill source.
- This change does not fix the underlying host-side preparation fault.
It records its actual cause so that the next occurrence identifies it.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), with tool use and code execution,
through 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: paperclipbugbot <356415228+paperclipbugbot@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 19:52:24 -08:00
4ec1447a67 fix(heartbeat): deliver a saved answer on a reviewed task with open blockers (#22525)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - An agent can ask a person a question on a task. The saved answer
wakes the agent.
> - Dependencies stop task work until the blocker tasks finish. #20363
lets a verified human answer reach the assignee in a bounded turn while
blockers stay open. That turn does not check out the task.
> - Run preparation used the bounded path only when the task status was
`blocked`. A task can wait in review (`in_review`) and still have open
blockers.
> - For such a task, dispatch admitted the answer turn. Then preparation
tried the normal resolved-interaction checkout. The checkout refused the
run with "Issue is blocked by unresolved blockers" (HTTP 422).
> - The run failed `setup_failed`. The answer did not reach the agent,
and Sentry received the refusal as an unexpected run failure.
> - This pull request keeps a verified answer in the bounded turn
whenever the task still has open blockers.
> - The benefit is that the person's answer reaches the agent, and the
task and its blockers do not change.

## Linked Issues or Issue Description

Refs #20363 (deliver saved answers to dependency-blocked tasks). This
change covers the same answer on a task that is not in `blocked` status.

**What happened?**

A parent task waited in review. Some of its child blocker tasks were
still blocked. The assignee had asked a question on the parent. A person
answered it. Dispatch admitted the answer turn with
`dependencyBlockedInteraction: true`. Run preparation then called the
resolved-interaction checkout, because the task status was `in_review`,
not `blocked`. The checkout dependency check threw "Issue is blocked by
unresolved blockers". The run failed `setup_failed` about one second
after it started. The adapter did not run. Sentry received the error.

**Expected behavior**

The saved answer reaches the assignee as a bounded answer turn. The task
stays `in_review`. Its blockers and dependency edges do not change. When
the last blocker has already finished, the task checks out normally, as
before.

**Steps to reproduce**

1. Assign a task to an agent and set its status to `in_review`.
2. Add a `backlog` task that blocks it.
3. Save an agent question on the task and answer it as a person.
4. Dispatch the resolved-interaction wake.
5. Observe that the run fails `setup_failed` with "Issue is blocked by
unresolved blockers".

**Paperclip version or commit**

Seen on a hosted staging server. The new regression case fails on
`master` at a722935dbc and passes with this change.

## What Changed

- `server/src/services/heartbeat.ts`: run preparation treats a verified
dependency-blocked answer as a bounded turn without checkout when the
task is `blocked` (unchanged) or when its dependencies are still not
ready. Before this change, only the `blocked` status qualified.
- The answer still needs the same proof as before: the stored
interaction is human-resolved, belongs to this task and agent, and
matches the wake's status and kind.
- `server/src/__tests__/heartbeat-dependency-scheduling.test.ts`: the
existing saved-response matrix gets two cases:
- `in_review_answered`: a reviewed task with an open blocker receives
the answer once and stays `in_review`.
- `in_review_blocker_finishes`: when the blocker finishes before
preparation, the reviewed task checks out normally and becomes
`in_progress`. The answer is delivered once.

## Verification

- Red before the fix, green after: `delivers only a saved human response
while dependencies remain blocked: in_review_answered`. Before the fix
the run ended `{ status: "failed", errorCode: "setup_failed", error:
"Issue is blocked by unresolved blockers" }`, which is the staging
failure. After the fix it succeeds.
- Safety case `in_review_blocker_finishes` passes before and after the
fix. A reviewed task with no open blockers keeps its normal checkout.
- The existing cases still pass. They cover a pending, missing,
wrong-task, or agent-resolved response that stays blocked, a response
that changes before dispatch, workspace waits, and a blocked task whose
blocker finishes.
- Commands (local, Node 25, embedded Postgres, branch at `master`
a722935dbc plus this change):
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/heartbeat-dependency-scheduling.test.ts
src/__tests__/heartbeat-agent-directory-busy.test.ts
src/modules/run-dispatch/domain/wake-context.test.ts
src/modules/run-dispatch/domain/policy.test.ts
src/__tests__/deferred-execution-receipt-work.test.ts
src/services/explicit-native-continuation.test.ts` (613 passed)
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/heartbeat-clean-continuation-dispatch.test.ts
src/__tests__/heartbeat-isolated-continuation-hold.test.ts
src/__tests__/issue-thread-interactions-service.test.ts
src/__tests__/agent-interaction-acceptance.test.ts` (148 passed)
  - `pnpm --filter @paperclipai/server typecheck` (passed)

## Risks

- Low risk. The change applies only to a wake that dispatch already
admitted as a verified dependency-blocked answer, and only while the
task still has open blockers. Before this change, that run always failed
at checkout.
- The bounded turn does not check out the task, change its status, or
resolve a blocker. Pause, ownership, approval, budget, and execution
gates are unchanged.
- No migration. No change to the API or to stored data.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), through Claude Code with tool use
(shell, file edit, and test 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
- [ ] I have updated relevant documentation to reflect my changes (no
doc change: the code comment and tests record the contract)
- [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: paperclipbugbot <356415228+paperclipbugbot@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 19:47:47 -08:00
DottaandClaude Opus 5.5 7a4a5bba8a test(server): advance the maintenance fake clock only after database connections finish startup (#22523)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The maintenance server tests boot the real server in a child process
with a fake clock. The test moves the clock forward (up to 30 s per
step) to reach deadlines fast.
> - The fake clock also replaces the timers of the PostgreSQL driver.
The driver starts a 30 s connect timer when it opens a connection, and
stops it at the first ReadyForQuery.
> - If the test moves the clock 30 s while a new database connection is
still in startup, the connect timer fires at once. The query fails with
`CONNECT_TIMEOUT`, the queue goes into retry, and the server does not
settle.
> - This race stopped the Release for 856f14e507 in `verify / Serialized
tests (2/5)`.
> - This pull request makes the child wait until every database
connection has finished startup before it moves the clock.
> - The benefit is that clock steps never fire a real-network timeout,
so these tests no longer depend on runner speed.

## Linked Issues or Issue Description

**What happened?**
The Cloud readiness run 44954319430 (Release for 856f14e507) failed in
`verify / Serialized tests (2/5)`. The failed test is
`maintenance-server-routes.test.ts > assembled maintenance server
production wiring > reacts to the first ordinary status-card source
write and accepts authorized controlled summarizer output`. The error is
"Maintenance did not settle". The child log shows `write CONNECT_TIMEOUT
127.0.0.1:<proxy>` from `connectTimedOut` in postgres.js, called from
`MockTimers.tick` at `server-child.ts:86`. That line is the `advance`
command. The same log shows a false 28.6 s "event loop stall" from the
same 30 s clock step.

**Expected behavior**
A fake clock step moves only the server's own deadlines. It must not
fire the driver's connect timeout for a connection that is still in
startup on the real network.

**Steps to reproduce**
1. Run `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/maintenance-clock-database-startup.test.ts`.
2. The first test starts a PostgreSQL connection against a server that
holds its startup reply, moves fake timers by 30 s, and then lets the
reply through. The query fails with `CONNECT_TIMEOUT`. This is the CI
failure in a deterministic form.
3. The second test waits with the new startup tracker before the same 30
s step. The query succeeds.

**Paperclip version or commit**
master at 856f14e507. The race exists since the fake-clock `advance`
command came in; the parent-side guard (`proxy.starting`) did not cover
a connection that opens after the guard check.

Classification: timing flake in the test harness (fake clock against a
real-network driver timer). It is not a product regression. The test
passed in every earlier Cloud readiness run on master.

## What Changed

- New helper
`server/src/__tests__/helpers/maintenance/database-startup.ts`. It uses
the `net.client.socket` diagnostics channel to track each client socket
from `connect()` until the first ReadyForQuery from the database (or
until it closes or is not a database socket). It reads only backend
frames with the existing protocol observer.
- `server-child.ts` waits for that tracker before each `advance`, and
then moves the clock in the same synchronous step. The driver starts its
connect timer in the same synchronous call that publishes
`net.client.socket`, so no connection can start its timer between the
check and the step.
- New test
`server/src/__tests__/maintenance-clock-database-startup.test.ts` with
the red case (unguarded step gives `CONNECT_TIMEOUT`) and the green case
(guarded step succeeds).
- No product code changes. No timeout changes.

## Verification

- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/maintenance-clock-database-startup.test.ts`: 2 of 2 pass.
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/maintenance-server-routes.test.ts -t "first ordinary
status-card source write"`: passes locally.
- Full `maintenance-server-routes.test.ts`,
`maintenance-postgres-proxy.test.ts` and
`maintenance-harness-resources.test.ts`: pass locally.
- `node scripts/typecheck-test-projects.mjs
server/src/__tests__/helpers/maintenance`: passes.

## Risks

- Low risk. Test-harness change only. If a database connection never
finishes startup, `advance` now fails after 30 s with a clear message
instead of a later "did not settle".

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude
Code with tool use (shell, file edit, GitHub CLI) for investigation, the
fix and local verification.

## 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>
2026-11-21 21:25:19 -06:00
782bd8d8eb fix(chat): continue a Slack question that a person answered in Paperclip (#22524)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Agents can work on tasks that start in Slack. They can ask the
person a question, and Paperclip posts the question card to Slack.
> - The person can answer in Slack or on the Paperclip task page.
Paperclip then starts a new run to continue the chat, and that run must
prove the answer before it can start.
> - If the Slack card had a native Respond button and the person
answered on the task page, the proof refused the answer. The run failed
setup with `reviewed_chat_execution_binding_not_authorized`
(`question_response_missing`), and the task stayed blocked. The agent
did not receive the answer.
> - This pull request accepts that task-page answer when the stored
Slack tokens show that the task-page answer replaced the Slack controls.
> - The benefit is that a person can answer an agent's Slack question on
the task page, and the agent continues the work.

## Linked Issues or Issue Description

**What happened?**
A task started in Slack. The agent asked a text question. Slack showed
the card with a native "Respond" button. The person answered on the
Paperclip task page. The continuation run failed during setup with
`reviewed_chat_execution_binding_not_authorized`, denial reason
`question_response_missing`. Recovery then set the task to blocked.

**Steps to reproduce**
1. Connect a Slack bot that has actions and modals.
2. Start a task from a Slack message.
3. Let the agent ask an `ask_user_questions` text question. Slack shows
a "Respond" button.
4. Answer the question on the Paperclip task page, not in Slack.
5. The continuation run fails setup with `question_response_missing`.

**Expected behavior**
The answer reaches the agent, and the continuation run starts.

**Cause**
The task-page answer expires all Slack tokens for the question with
`interaction_resolved_elsewhere`. The answer proof in
`resolveQuestionResponseChain` accepted a Slack task-page answer only if
no Slack answer tokens existed at all and every card action was a link.
A card with a native Respond button always failed both checks.

Related: #17255 added the Slack native question forms and the task-page
answer proof.

## What Changed

- `external-chat-question-response.ts`: the task-page answer query now
ignores Slack answer tokens only when their status is `expired` with
result code `interaction_resolved_elsewhere`. Any other token state
(processed, issued, or expired for another reason) still makes the proof
use the Slack action path, as before.
- `external-chat-question-response.ts`: a Slack card can now have
callback actions, but only when each callback `actionId` matches a
superseded token (`question_answer` or `question_form_open`) of the same
interaction, publication, endpoint and conversation. GitHub cards still
must have only links.
- `external-chat-wait.integration.test.ts`: the Board-answer fixture can
now publish a Slack text question with a native form. A new regression
test answers it on the task page and attests the continuation. The
Board-answer refusal matrix now runs for this card too, with two new
cases: a Slack token that the answer did not supersede, and an unknown
callback button.

## Verification

- Red before the fix: the new test `attests a Slack question answered in
Paperclip after its native form was published` failed with denial
`["question_response_missing"]`. This is the same denial reason as the
failed run.
- Green after the fix: the same test passes. The continuation input
contains the answer.
- `pnpm vitest run
src/services/native-runtime/external-chat-wait.integration.test.ts` (in
`server`): all 301 tests pass. This includes the 14 refusal cases for
the native-form card (other user, viewer, revoked membership, revoked
identity, wrong target, wrong wake, unpublished card, processed Slack
action, deleted source message, paused endpoint, revoked resource,
changed answer hash, token not superseded, unknown callback).
- Mutation check: when I let any callback through, the
`foreign_callback` case fails. When I ignore token state, the
`unsuperseded_token` case fails.
- `photon/channel.integration.test.ts` and
`agent-action-audit-routes.test.ts` pass.
- `heartbeat-process-recovery.test.ts`: 4 sandbox-lease tests fail in my
sandbox with `isRetryableEnvironmentHttpStatus is not a function`. They
fail the same way on unmodified master, so this change does not cause
them.
- The full server `tsc` was killed by the sandbox memory limit. CI is
the type gate.

## Risks

- This change makes the answer proof accept more answers, so I kept it
narrow. A Slack task-page answer is accepted only when the stored tokens
prove that the task-page answer replaced every Slack answer token. All
other checks do not change: the same person must answer, membership and
identity link must be current, the endpoint must be active, the
publication must be published, and the answer hash must match.
- If a Slack answer and a task-page answer race, any token that the
task-page answer did not expire still refuses the proof. This fails
closed, as before.
- No migration. No change to GitHub, Speko, Photon or Slack
native-answer paths.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), 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
- [ ] 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: paperclipbugbot <356415228+paperclipbugbot@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 19:22:33 -08:00
sentry[bot] ac02de7732 fix(server): validate agentId query parameter on company activity endpoint (#22516)
<!-- Write all pull request text in Simplified Technical English
(ASD-STE100): short sentences, one instruction per sentence, simple
approved vocabulary, and the active voice. -->

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - This change is in the activity log API, `GET
/companies/:companyId/activity`.
> - The route sends the `agentId` query value directly to the database.
The `activity_log.agent_id` column is a UUID column.
> - A malformed value makes PostgreSQL fail, and the client gets a 500
response for a client mistake.
> - This pull request validates the `agentId` query value as a UUID and
returns HTTP 400 for a malformed value.
> - The benefit is that clients get a clear 400 error, and the server
does not report a false server error.

## Linked Issues or Issue Description

No public GitHub issue exists. This is the bug description.

**What happened?**

A client sent `GET /companies/:companyId/activity?agentId=dc04285a-`.
The route sent the truncated value to an `eq(activityLog.agentId, ...)`
condition. PostgreSQL failed with `invalid input syntax for type uuid:
"dc04285a-"`, and the server returned 500.

**Expected behavior**

A malformed `agentId` returns HTTP 400 with validation issues. A valid
UUID returns HTTP 200. An empty `agentId` applies no filter.

**Steps to reproduce**

1. Start the server.
2. Send `GET /api/companies/<company-id>/activity?agentId=dc04285a-` as
a board user.
3. Look at the response status. Before this change it is 500.

**Paperclip version or commit**

`master` at `68f641ba0bb7e8e8740bf62cca1cbfab45da8264` and later.

**Deployment mode**

Not specific to one deployment mode. The route is in the core server.

## What Changed

- Validate the `agentId` query on `GET /companies/:companyId/activity`
with `z.string().guid().optional()`.
- Convert an empty `agentId` value to `undefined`. This matches the
service behavior for an omitted filter.
- Throw a standard `badRequest` (HTTP 400) with validation issues for a
malformed `agentId`.
- Update `docs/api/activity.md` with the UUID requirement, the
empty-value behavior, and the 400 response.
- Add regression tests: a malformed `agentId` returns 400 and does not
call the service, and a valid UUID returns 200 and passes the filter.

## Verification

- `pnpm vitest run server/src/__tests__/activity-routes.test.ts` runs
the new validation tests.
- CI on head `ed3078339894bdd68f2093ddaf921fdb297623aa` is green,
including `ci / verify`, `ci / e2e`, and all server test shards.

## Risks

- Low risk. The change is one route and one query parameter.
- A client that sends a malformed `agentId` now gets HTTP 400 instead of
HTTP 500.
- A client that sends an empty `agentId` now gets the same result as an
omitted filter.

> 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

- Code: Sentry Seer Autofix (Claude 3.5 Sonnet, as reported by Seer),
with tool use.
- PR description update: Claude Opus 5.5 (`claude-opus-5-5`), with 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 (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)
- [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

<!-- SEER_FIXES_SENTRY_ISSUE -->
Fixes
[PAPERCLIP-BACKEND-4E](https://paperclip-e0.sentry.io/issues/7805680817/?seerDrawer=true)
<!-- /SEER_FIXES_SENTRY_ISSUE -->

<sub>`@sentry <feedback>`: Autofix iterates on these changes</sub>
<sub>`@sentry stop iterating`: Autofix stops iterating on this run</sub>

<sub>This PR was automatically generated by Sentry at no cost. You can
[adjust this
setting](https://paperclip-e0.sentry.io/settings/projects/paperclip-backend/seer/)
at any time.</sub>

---------

Co-authored-by: sentry[bot] <39604003+sentry[bot]@users.noreply.github.com>
2026-11-21 19:20:02 -08:00
scotttong 856f14e507 fix(dashboard): scope areas and responsibilities to each user (#22513) 2026-11-21 13:59:00 -08:00
f434f0e7bd fix(native): let a fresh replacement Runner publish its verified pack admission (#21498)
A new claim's own fresh Runner selection now supersedes the earlier claim's admission receipt while no provider artifacts are retained under it, so a refused reattachment no longer fails before the first provider turn as native_provider_artifacts_admission_unverified.

Co-Authored-By: Paperclip <Paperclip-Paperclip@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 04:28:57 -08:00
21f4427b78 fix(server): pass a Cloud portfolio rate limit through as 429 (#22488)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - A hosted stack reads its tenant portfolio from Paperclip Cloud
through `GET /api/cloud/stacks`
> - Paperclip Cloud can answer that read with 429 when it throttles a
stack
> - The proxy changed every non-OK upstream status into a 502, and the
error handler reports every 5xx to Sentry
> - So Cloud backpressure showed up as a server crash on a staging stack
(`upstreamStatus=429`, `phase=http_response`)
> - This pull request passes an upstream 429 through as a 429 with a
bounded `Retry-After` hint
> - The benefit is a correct status for clients and no false crash
reports for throttling

## Linked Issues or Issue Description

Refs #15340 (bounded Cloud portfolio diagnostics), Refs #19033 (retry
one Cloud portfolio connection reset).

**What happened?**
A hosted staging stack reported "Paperclip Cloud portfolio request
failed" to Sentry. The diagnostics show `upstreamStatus=429` after 44
ms. Cloud throttled the read, and the proxy answered 502 and reported a
crash.

**What did you expect to happen?**
The proxy tells the client that Cloud is rate limiting the read. It does
not report a server fault.

**Steps to reproduce**
Make the Cloud tenant portfolio endpoint answer 429, then call `GET
/api/cloud/stacks`. Before this change the route answers 502
`cloud_portfolio_upstream_error` and reports to Sentry.

## What Changed

- `server/src/routes/cloud.ts`: an upstream 429 now gives 429
`cloud_portfolio_rate_limited`.
- The route copies Cloud's `Retry-After` as whole seconds. It accepts
delta seconds or an HTTP-date and clamps the value to 1–300 seconds. It
omits the header when the value is missing or malformed.
- The route logs the bounded diagnostics at warn level. It does not
report the 429 to Sentry and does not cache the throttled answer.
- 401, 403, 503 and the other failure phases keep the 502 contract and
the crash report.
- `server/src/__tests__/cloud-routes.test.ts`: new cases for the 429
status, the `Retry-After` forms, no Sentry report, and no cache entry.
- `docs/api/cloud.md` (new, in the API Reference nav): documents `GET
/api/cloud/stacks`, its error codes, and the 429 with its bounded
`Retry-After`.
- `server/src/routes/openapi.ts`: the `/api/cloud/stacks` entry now
lists the 429 response.

## Verification

- Red: with the old `cloud.ts`, `cloud-routes.test.ts` gave 5 failed
(the new 429 cases) and 23 passed.
- Green: `cd server && npx vitest run src/__tests__/cloud-routes.test.ts
src/__tests__/sentry.test.ts src/__tests__/cloud-portfolio-error.test.ts
src/__tests__/run-failure-sentry-real-sdk.test.ts` gave 68 passed and 18
skipped.
- `npx tsc --noEmit -p server/tsconfig.json` shows no errors in the
changed files.
- After review fixes (6a8f146c55): `cd server && npx vitest run
src/__tests__/cloud-routes.test.ts src/__tests__/openapi-routes.test.ts`
gave 80 passed.

## Risks

- Low risk. Only the 429 path changes.
- The two UI consumers (`useCloudInviteUrl`, `CompanyAccess`) treat any
error the same way, so the UI needs no change.

## Model Used

- Anthropic Claude Opus 5.5 (`claude-opus-5-5`) 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
- [ ] 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: Paperclip <noreply@paperclip.ing>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: paperclipbugbot <356415228+paperclipbugbot@users.noreply.github.com>
2026-11-21 04:22:41 -08:00
4631d3b41a fix(workspaces): attach a recovered saved version once, not once per failed run (#22484)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Before a run starts in a new sandbox, Paperclip prepares the task
workspace. It also attaches the saved files of earlier failed runs under
`.paperclip-recovered/<operation>` so the agent can continue their work
> - A run that restores a saved workspace and then fails can save the
same version again. Workspace recovery keeps a receipt for that run. One
saved version can then have a receipt from each of several failed runs
> - Preparation attached the files once for each receipt. It removed
duplicates only by receipt operation ID
> - On staging, six receipts named the same 1 GB saved version. Each new
sandbox received six copies (about 6 GB and 171k entries) before its
first save. The first save then failed with
`remote_workspace_sandbox_disk_full`. The read-only fallback also
refused with `budget_exceeded`, because its inventory limit is 100,000
entries
> - The next sandbox received the same six copies. No run could succeed,
so nothing retired the copies, and the task failed in the same way about
every 30 minutes
> - This pull request attaches each saved version once
> - The benefit is that a task with several recovered failed runs gets
one copy of their saved work, and its sandbox has space for its first
save

## Linked Issues or Issue Description

Refs #22466 (names this failure `sandbox_disk_full`). Refs #22383,
#22239, #22068 (other full-sandbox-disk handling). Those changes name
the failure and stop repeats. This change removes the cause of this
case.

**What happened?**
On staging, three tasks failed during setup again and again with
`remote_workspace_sandbox_disk_full: the sandbox disk is full; free
space in the sandbox before saving the workspace`. Each run used a new
sandbox. One workspace failed its initial save 18 times in about 8
hours. Its metadata recorded six recovered attachments. All six came
from one earlier workspace, one snapshot and one sha256 (1,040,502,418
bytes, 28,576 entries). Only the source run was different. Each of those
six source runs had restored that snapshot, saved it again unchanged
(`reusedSnapshotId` equals the parent), and failed for another reason.

**Expected behavior**
The new workspace gets one copy of the saved version. Its first save has
space.

**Steps to reproduce**
1. Save a workspace (version A).
2. Start a writer that restores A, saves A again unchanged, and fails.
Record its recovery receipt.
3. Do step 2 again with a second writer.
4. Prepare a new workspace with both failed writers as recovery
predecessors.
5. See two full copies of A under `.paperclip-recovered/`.

## What Changed

- `remote-workspace-recovery-attachments.ts`:
`attachPreservedRemoteWorkspaceSnapshots` first collects the verified
receipts. It then attaches each saved version (source workspace,
snapshot ID, sha256) once, under the receipt of the earliest source run.
If any receipt of a version is retired, the version is retired. Receipt
verification, access checks, and the provenance of an attached copy do
not change.
- `remote-workspace-snapshot-reuse.test.ts`: a new database-backed test
uses the existing reused-save recovery fixture with two failed writers.
The `same` case expects one copy. The `changed` case (the second writer
saved different files) expects two copies. Both cases check that a
retired receipt retires its whole version. The recovery stamping moved
into a helper (`recoverFailedWriter`) for both writers.

## Verification

- Red: on unmodified `master`, `pnpm vitest run
src/services/remote-workspace-snapshot-reuse.test.ts -t "attaches each
saved version once"` fails for the `same` case: `expected [ {…}, {…} ]
to deeply equal [ ObjectContaining{…} ]`, which is two copies of one
version. The `changed` case passes.
- Green: with the change, `pnpm vitest run
src/services/remote-workspace-snapshot-reuse.test.ts
src/services/workspace-recovery-preparation.test.ts
src/services/remote-workspace-recovery-receipt-fallback.test.ts` passes:
3 files, 125 tests. These include the existing same-run duplicate check,
retired copies, unverifiable receipts, and storage backend selection.
- `node scripts/typecheck-layers.mjs` in `server/`: no errors in
`server/src`. My sandbox installed only the server dependencies, so
`cli/`, `ui/` and `packages/kv-demo-mcp-server` reported missing-module
errors there. CI runs the full typecheck.
- I did not run a live sandbox preparation. The staging workspace
records above give the sizes and the six duplicate receipts.

## Risks

- Low. Only duplicate copies of one saved version are skipped. Different
versions are all attached, as before.
- The agent sees one recovered folder for that version instead of
several identical folders. The recovered-files list is context for the
agent only. No settlement step needs one copy per source run.
- Existing workspaces keep their old records. In a new sandbox, the
records of copies that are not attached again are dropped, as for any
copy that is absent.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), 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
- [ ] 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: paperclipbugbot <356415228+paperclipbugbot@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 03:07:06 -08:00
Devin FoleyandPaperclip 1b1861c29d Fix skill upload conflicts blocking first-agent onboarding (#22477)
## Thinking Path

> - Paperclip manages agents and the skills they need to work.
> - First-agent setup resolves the bundled skills before onboarding can
finish.
> - Skill packages use durable upload claims to protect their
object-storage receipts.
> - A failed attempt kept its claim active for ten minutes. A concurrent
caller received an immediate conflict.
> - This pull request expires a failed owner's unpublished claim and
waits for an active upload to settle.
> - Onboarding can retry skill setup without a false upload-in-progress
error.

## Linked Issues or Issue Description

**What happened?**

First-agent onboarding could show "This skill package is being saved.
Retry after its upload settles." during the subscription connection
step. The agent's bundled skill setup called the package store. A failed
upload retained its active claim, and calls from another database client
also returned a conflict while an upload was in progress.

**Expected behavior**

A failed attempt permits an immediate retry with new object keys.
Concurrent callers reuse the completed receipt or claim the failed
attempt. They preserve another owner's active lease and every published
receipt.

**Steps to reproduce**

1. Fail the first object upload while resolving the first agent's
bundled skills.
2. Retry the same skill selection before the ten-minute lease expires.
3. Observe the upload-in-progress conflict. The new regression
reproduces this through
`companySkillService.resolveRequestedSkillEntries`.

**Paperclip version or commit**

Reproduced on `6bf312270c3e`.

**Deployment mode**

Hosted onboarding; the package-store fix also applies to self-hosted
instances.

Related implementation: #18082. Searched open and closed pull requests
and open issues for related skill-upload and lease failures. No
duplicate fix was found.

## What Changed

- Expire only the failed attempt's token-matched, unpublished upload
claim. Keep its exact keys for the existing deletion outbox. Cleanup has
a one-second client deadline and a transaction-local statement timeout.
Queued cleanup skips its write after that deadline; failed cleanup
retains the original crash lease.
- Wait for a competing package preparation within the existing
three-minute deadline. Re-read the receipt every 250 ms while this
concrete request remains active. Release the database connection between
reads and stop on cancellation. This adds no idle worker or permanent
polling.
- Preserve cancellation reasons, published receipts after lost commit
replies, and claims acquired by a newer owner.
- Add real PostgreSQL regression coverage for first-agent bundled skill
setup, cross-client contention, failed-owner takeover, crash expiry,
cancellation, ambiguous publication, and ownership changes.
- Document upload recovery behavior. No schema or public API change is
required.

## Verification

- Red: four new or updated checks failed against the original
implementation. They reproduced the exact conflict and the retained
ten-minute lease.
- Green: 189 targeted tests passed across
`skill-package-upload.test.ts`, `skill-package-store.test.ts`,
`skill-package-work.test.ts`, both package-storage migration suites, and
`agent-skills-routes.test.ts`. The combined run passed 188 tests. The
final SQL-lock regression passed separately.
- Command: `pnpm exec vitest run
server/src/__tests__/skill-package-upload.test.ts
server/src/__tests__/skill-package-store.test.ts
server/src/services/skill-package-work.test.ts
server/src/services/skill-package-storage-migration.test.ts
server/src/services/skill-package-storage-migration-postgres.test.ts
server/src/__tests__/agent-skills-routes.test.ts`.
- `pnpm --filter @paperclipai/server typecheck` passed, including source
and test layers.
- The cancellation test first exposed Node's timer wrapping the caller's
abort reason. The final implementation preserves that reason, and the
full targeted run passed.
- Greptile identified an unbounded cleanup write. Two new
real-PostgreSQL tests reproduced delayed errors and cancellations behind
an occupied one-connection pool. They now pass and prove that late
cleanup skips its write. A further row-lock test proves that the
PostgreSQL statement timeout frees the pool while another transaction
still holds the package row.
- Local setup initially lacked macOS embedded-Postgres library links.
Repaired ignored dependency links before the red and green database
tests. The initial server typecheck also lacked SDK links for excluded
plugin packages; ran the maintained `node
scripts/link-plugin-dev-sdk.mjs` helper before repeating it.
- `pnpm verify --explain` returned exit 2 and requested broader CI
coverage. No full local suite was substituted for that CI requirement.
- `git diff --check` passed. Reviewed the full diff for secrets, private
URLs, personal data, generated files, and run artifacts.
- Final revision: `4b4814ac01522599901a3dc29f650a1b33c0b4e2`. [CI
run](https://github.com/paperclipai/paperclip/actions/runs/44880245673)
passed all applicable checks, including typecheck, build, all general
and serialized server test shards, all e2e shards, Runner verification,
and the final verify gate. [Greptile
review](https://github.com/paperclipai/paperclip/pull/22477#issuecomment-7059199437)
scored this revision 5/5 with no unresolved threads. GitHub reports the
branch as mergeable and clean.

## Risks

Contended preparations now wait within their existing request deadline.
A crashed process or an unavailable cleanup database still uses the
ten-minute lease expiry. Genuine storage failures remain errors; this
change does not hide an unavailable backend. The existing object
deletion grace remains intact.

Live provider authorization and a deployed Cloud onboarding journey were
not run. Tenant release and deployment are separate from this source
fix. No production migration is needed.

## Model Used

OpenAI GPT-6.1 Sol (`gpt-6.1-sol`) through the Codex harness, with xhigh
reasoning effort 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 (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-21 00:25:10 -08:00
Devin FoleyandPaperclip 4697a50508 fix: retry verified legacy adapter preparation failures (#22464)
Accept the existing full preparation proof for the exact legacy adapter_failed source named by a saved Retry. Keep older recovery-hold ancestry checks and refusal gates intact. Add one-successor and missing-proof integration coverage, and synchronize the independent watchdog test fixture with reporter readiness.

Qualified on 36463a770a with full green CI, Apex 5/5, no unresolved review findings and no conflicts. Focused Retry/bootstrap checks and the affected server typecheck pass after the rebase; broader local tests apply to the identical source tree.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-11-20 23:33:16 -08:00
Devin FoleyandPaperclip 6bf312270c fix(ci): stabilize database-backed readiness checks (#22476)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - CI checks its recovery workers, attention routes, and external chat
admission against real PostgreSQL.
> - Large fixtures start from an empty database without statistics for
their new rows.
> - Slow query plans can exhaust test deadlines before the behavior
checks finish.
> - Route responses can also leave wakeups writing rows while teardown
deletes their agents.
> - Setup admission takes an endpoint lock that can deadlock with
resource foreign-key checks and agent invalidation.
> - This pull request prepares fixture statistics, drains pending work,
and uses a compatible endpoint lock.
> - The benefit is reliable readiness checks with the same fixtures,
assertions, and deadlines.

## Linked Issues or Issue Description

Refs: #21941, #21831, #21132. The compiler-memory mitigation in #19383
is already merged and is not repeated here.

**What happened?**

The recovery census and review-attention equivalence tests repeatedly
timed out on unrelated PRs. Recovery-action teardown also failed on an
agent-wakeup foreign key, and concurrent first GitHub mentions could
deadlock during resource admission.

Examples: [census
timeout](https://github.com/paperclipai/paperclip/actions/runs/44868742060/job/136738633187),
[review
timeout](https://github.com/paperclipai/paperclip/actions/runs/44856500775/job/136732143246),
[cleanup
failure](https://github.com/paperclipai/paperclip/actions/runs/44866635624/job/136731817497),
and [chat
deadlock](https://github.com/paperclipai/paperclip/actions/runs/44845946341/job/136667344125).

**Expected behavior**

The complete fixtures retain their regression coverage, pending wakeups
finish before deletion, and concurrent chat admission completes with
exactly one setup destination enabled.

**Steps to reproduce**

1. Run the two timeout suites against a freshly seeded database before
its statistics refresh.
2. Complete an issue-update request that schedules an assignee wake,
then delete its fixture immediately.
3. Run the new resource-admission regression on the base revision. It
forces the endpoint/agent lock order and fails with PostgreSQL SQLSTATE
`40P01`.

**Paperclip version or commit**

Base: `33ffaa5b9a2e0954c2afc063572346cb1be534a7`.

## What Changed

- Run `ANALYZE` on the populated fixture tables after seeding the
existing census and review-attention populations. No fixture reduction,
assertion removal, retry increase, or deadline increase.
- Await `drainActiveRunExecutions()` before recovery-action fixture
cleanup. This includes pending wake admission after HTTP responses.
- Use `NO KEY UPDATE` for setup endpoint admission. It still serializes
competing admission transactions and endpoint mutations while allowing
resource foreign-key `KEY SHARE` locks.
- Add a real PostgreSQL regression using the real `ensureResource`
write, with barriers that force concurrent endpoint admission and an
agent-locked resource insert. Both transactions must finish and exactly
one destination must become enabled.
- Document fixture statistics, teardown ownership, and admission locking
in `doc/test-infrastructure.md`.

## Verification

- The new concurrency regression fails on the original endpoint lock
with SQLSTATE `40P01`, then passes with `NO KEY UPDATE`.
- Both timeout suites pass with their full populations and original
deadlines: 8 tests.
- The full recovery-action suite passes: 120 tests.
- Existing GitHub first-repository and disabled-repository integration
checks pass: 7 tests.
- The new PostgreSQL concurrency regression passes: 1 test.
- The local baseline timeout suites passed slowly; the review
equivalence case took 35.8 seconds before statistics and 0.63 seconds
afterward. These are local observations, not a CI speed guarantee.
- The first broad typecheck caught an unsupported
`Promise.withResolvers` type in the new test. The barriers now use
ordinary promises compatible with the repository target. The final `pnpm
-r typecheck` passes.
- `git diff --check` passes.
- `pnpm -r typecheck` and `pnpm build` pass. The full local `pnpm
test:run` attempt stopped after all six chat shards: 1,969 tests passed
and two Slack tests failed on skill-root discovery. The remaining local
groups did not run. Both failures reproduce with the production change
reverted to `origin/master`: the resolver selects an unrelated ancestor
`skills/` directory without `slack/SKILL.md`, which also prevents the
mocked Slack run from starting. This is a confirmed baseline
local-layout issue, not a passing full-suite result. The [complete CI
run](https://github.com/paperclipai/paperclip/actions/runs/44873350026)
passes on `66c146b177b50e052a21921644dfd626c96c010d` on attempt 1. The
PR check rollup has 58 successes, three expected skips, and no pending
or failing checks. [Greptile reviewed the current head
`66c146b`](https://github.com/paperclipai/paperclip/pull/22476#issuecomment-7058185817)
at 5/5 with no actionable findings.

Review follow-up verification:

- Replaced the resource-read stub with the real
`createChatInboundAuthority(...).ensureResource` persistence path. The
revised regression fails with `FOR UPDATE` and PostgreSQL `40P01`, then
passes with `NO KEY UPDATE`.
- Scoped `ANALYZE` to the fixture tables and moved the behavior note
from `DEVELOPING.md` to `test-infrastructure.md`.
- All 9 affected tests pass after these edits; the complete server
typecheck also passes. The production lock change is unchanged from the
earlier full workspace typecheck and build passes.
- The previous CI attempt had two interrupted jobs: [Runner static
checks](https://github.com/paperclipai/paperclip/actions/runs/44872465981/job/136749952142)
and [serialized server
9/9](https://github.com/paperclipai/paperclip/actions/runs/44872465981/job/136749952782).
Both logs record a runner shutdown. The static lane reported 2,371
passing tests before cancellation; the interruption is not counted as a
pass. The final head passes the complete fresh CI run linked above,
including both lanes.

## Risks

Low scope. Production code changes only the endpoint row-lock strength.
The regression uses real foreign keys and connector invalidation
triggers; the existing integration checks retain first-destination
serialization and disabled-destination behavior. No schema, API, or
authorization changes. `ANALYZE` updates only test-database statistics.
Drain failures still fail teardown.

All current-head remote checks now pass, including typecheck, build,
tests, and e2e. The baseline local full-suite failure and unrun
remaining local groups are recorded above; focused local checks pass.
The already merged compiler-input fix does not establish the cause of
every past runner shutdown.

## Model Used

OpenAI GPT-6.1 Sol (`gpt-6.1-sol`) through the Codex harness, with xhigh
reasoning and shell/code execution. The session does not expose its
context-window size.

## Checklist

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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-20 22:52:05 -08:00
33ffaa5b9a fix(heartbeat): name a full sandbox disk that stops a workspace save during setup (#22466)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Before a run starts, Paperclip prepares the task's remote workspace
and saves it. The save builds an archive inside the sandbox
> - When the sandbox disk is full, that save fails with
`remote_workspace_sandbox_disk_full: the sandbox disk is full; ...`
> - #22383 taught the setup failure path to name a full sandbox disk
`sandbox_disk_full`. That code tells the user what to do, and automatic
retry and generic continuation recovery do not repeat it
> - The setup matcher accepts the runner's form, `sandbox_disk_full:
...`, at the start of the text or after `: `. In the save failure,
`sandbox_disk_full:` follows `remote_workspace_`, so it does not match
> - These runs therefore fail as the generic `setup_failed`. They share
one Sentry group with unrelated uncoded setup failures, and they are
started again on the same full disk
> - This pull request recognizes the exact save failure in the setup
failure path
> - The benefit is that these runs fail as `sandbox_disk_full`, get
their own Sentry group, show the existing plain-language action and are
not repeated automatically

## Linked Issues or Issue Description

Refs #22383 (names a full sandbox disk that fails a run during setup).
This PR covers the workspace save during setup, which that change does
not match.

**What happened?**
On staging, several runs failed while preparing their workspace with
`remote_workspace_sandbox_disk_full: the sandbox disk is full; free
space in the sandbox before saving the workspace`. Each run stayed in
preparation for about 19 minutes. The run had `errorCode: setup_failed`
and `resultJson.failureCause: "Error"`. The Sentry fingerprint
(`setup_failed`, adapter, `setup`, `exception:Error`) put these runs in
the same group as other uncoded setup failures. Each task was then
started again on the same sandbox and failed the same way.

**Expected behavior**
The run fails as `sandbox_disk_full`, like the other full-sandbox-disk
setup failures. The task shows the existing action (free disk space,
then press Retry). Bounded retry and generic continuation recovery do
not repeat it.

**Steps to reproduce**
1. Prepare a remote workspace in a sandbox whose disk is full.
2. Let the preparation save fail with
`REMOTE_WORKSPACE_SANDBOX_DISK_FULL`, either directly or after the
read-only fallback also fails (the fallback rethrows the same message
with the fallback failure as its cause).
3. See the run fail as `setup_failed`.

## What Changed

- `remote-workspace-transport.ts`: add
`isRemoteWorkspaceSandboxDiskFullError`. It is true when the error, or
one of its first causes, has the exact server-built
`REMOTE_WORKSPACE_SANDBOX_DISK_FULL` message. It does not match other
text.
- `run-completion.ts`: the setup failure ladder uses `sandbox_disk_full`
for that error too. The rung's position does not change, so named setup
codes (restore failure, timeout, storage and others) keep their
precedence.
- Tests in `run-completion.test.ts` with a real database: the direct
save failure, the save failure that keeps the read-only fallback failure
as its cause, and another failed save
(`remote_workspace_archive_changed`) that stays `setup_failed`. The
existing host-disk test still passes.

The message, the saved workspace preservation path and the
workspace-recovery handling are unchanged. Retry and continuation
behavior for `sandbox_disk_full` already exists
(`scheduleBoundedRetryForRun` returns `not_scheduled`; recovery lists
the code as non-retryable).

## Verification

- Red: on unmodified master, both new disk-full cases fail with
`errorCode: "setup_failed"`, the same code as the staging runs.
- Green: with the change, `pnpm vitest run
src/services/heartbeat/run-completion.test.ts
src/services/native-runtime/native-sandbox-disk-full.test.ts
src/services/remote-workspace-transport.test.ts`: 352 of 355 pass. The 3
failures are in `remote-workspace-transport.test.ts` (restore lock
`directory_shared`, ambient checkout filters, trusted SSH rewrites).
They fail the same way on unmodified master in my sandbox, so they come
from its Git setup.
- Retry and recovery behavior for the code: `pnpm vitest run
src/__tests__/failed-continuation-continues-again.test.ts
src/__tests__/heartbeat-retry-scheduling.test.ts
src/services/workspace-recovery-disk-full.test.ts
src/services/recovery/provider-failure-classification.test.ts`: 4 files,
141 tests pass.
- The full server typecheck did not run locally because the sandbox has
too little memory and disk. CI runs it.

## Risks

- Low. The change only renames a setup failure that already cannot be
repaired by starting again on the same sandbox. It reuses an existing
code with existing retry, recovery and UI handling.
- Runs that hit this failure are no longer started again automatically.
A person frees disk space and presses Retry, as for the other
`sandbox_disk_full` failures.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), 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
- [ ] 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: paperclipbugbot <356415228+paperclipbugbot@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 20:32:44 -08:00
6b9952525d build(server): omit tests from production compilation (#19383)
Use a separate production TypeScript configuration that excludes colocated tests while retaining every runtime source input and keeping tests in source typechecking. Verify the real compiler input sets and bound compiler-list capture for the larger source graph.

Validation: focused compiler-input regression passes; fresh CI has 61 passing checks and three optional skips on 181ad8d; Greptile Apex is 5/5 with no unresolved comments.

Co-Authored-By: Scott Goodson <scottgoodson@gmail.com>
Co-Authored-By: Devin Foley <devin@paperclip.ing>
Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-11-20 20:02:21 -08:00
Devin FoleyandClaude Opus 5.5 fec961b580 fix(workspaces): record why a full-disk read-only capture failed (#19619)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - A remote agent workspace is saved to durable storage after each run.
The save builds a portable archive inside the sandbox.
> - When the sandbox disk is full, #19465 starts one read-only fallback.
The fallback copies a verified source to the controller and seals the
archive there.
> - If that fallback also fails, the code keeps the original disk-full
message and puts the fallback failure in `error.cause`.
> - `remoteWorkspaceFailureCause` reads only the top message. The
recorded copy-back cause and the run error therefore say only "the
sandbox disk is full". The fallback stage and reason are lost.
> - Also, the sandbox inventory script reports every failure as
`unsafe`, and `command()` drops that token. The fallback then says
`reason=operation_failed` for a linked worktree, a budget limit, or an
unreadable file.
> - #20678 later made a transient fallback failure (a dropped
connection) surface as its own cause. Every other fallback failure is
still wrapped in the disk-full error, and that wrapped cause is still
dropped. A staging save on a release with #20678 again recorded only the
bare disk-full message.
> - This pull request keeps the disk-full code and message unchanged. It
appends the fallback's closed-grammar cause to the recorded cause, and
it names the inventory refusal.
> - The benefit is that an operator can see why a full-disk save still
failed (for example `stage=inspect reason=unsafe_source`), so the next
fix targets the real step.

## Linked Issues or Issue Description

Refs #19465
Refs #19543
Refs #20678

**What happened?**

On a release that contains #19465 and #19543, a hosted run finished its
turn, and all three workspace save attempts failed. Each recorded cause
was only `remote_workspace_sandbox_disk_full: the sandbox disk is full;
free space in the sandbox before saving the workspace`. The read-only
fallback ran on each attempt, but the record did not say at which stage
it stopped or why. Later, the existing provider-cache reclaim freed
space and the save completed. The fallback failure itself is still
unexplained, because the record does not contain it.

**Expected behavior**

The recorded cause keeps the disk-full code, so retries and cache
reclaim work as before. It also names the fallback stage, a closed
reason, and a transport label. It never includes paths, file names, or
provider text.

**Steps to reproduce**

1. Create a workspace with a `.git` file (a linked worktree pointer) or
with one unreadable file.
2. Make the normal capture report a full disk, so the read-only fallback
runs.
3. Call `remoteWorkspaceFailureCause` on the capture error.
4. On `master`, the result is only the disk-full message. With this
change, the result ends with `;
remote_workspace_readonly_capture_failed: stage=inspect
reason=unsafe_source transport=provider_error` (or `reason=fs_eacces`).

## What Changed

- `remoteWorkspaceFailureCause`: when the error message is the exact
disk-full message and `error.cause` matches the closed
`remote_workspace_readonly_capture_failed: stage=… reason=… transport=…[
code=…]` grammar (the existing `READONLY_CAPTURE_FAILURE_CAUSE` from
#20678, now also allowing digits in the reason for errno codes), append
that cause after `; `. Other causes are not attached. The thrown
message, the derived code (`remote_workspace_sandbox_disk_full`), and
the disk-full equality checks used by retry and cache reclaim do not
change.
- The sandbox inventory script now writes
`remote_workspace_readonly_capture_budget` for a budget limit and
`remote_workspace_readonly_capture_fs_<errno>` for a filesystem error
code. Other refusals still write
`remote_workspace_readonly_capture_unsafe`. It never writes error text
or paths.
- `command()` accepts only these exact tokens from a failed capture
command, so the fallback can map them.
- The fallback maps `fs_<errno>`, `disk_full` and command timeouts
(`timed_out`) to their own reasons, in addition to the existing
`unsafe_source`, `source_changed` and `budget_exceeded`.
- New test file `remote-workspace-readonly-capture-cause.test.ts` with
four cases: source changed during transfer, linked worktree refusal
before transfer, unreadable file by errno only (no private file name in
the cause), and a cause outside the grammar that is not attached.

## Verification

Rebased onto `master` at `b4cea5b5a4` (2026-11-21). The only conflict
was in `remoteWorkspaceFailureCause`, where #20678 added a direct match
for a thrown read-only cause. Both behaviours are kept, and the PR now
reuses #20678's grammar instead of adding a second regex.

- Red on `master` (`b4cea5b5a4`, with the two source files swapped back
to `master`): three of the four new tests fail, each getting only the
bare disk-full message. The grammar guard test passes on both.
- Green with this change: all four new tests pass.
- From `server/`: `npx vitest run
src/services/remote-workspace-readonly-capture-cause.test.ts
src/services/remote-workspace-readonly-inventory.test.ts
src/services/remote-workspace-transport.test.ts
src/services/native-runtime/native-run-finalizer-telemetry.test.ts`: 213
passed, 6 failed. All 6 are in `remote-workspace-transport.test.ts` and
are environmental in this sandbox:
- `does not run ambient checkout filters…`, `uses trusted SSH rewrites
only for clone…` and `rejects an unsafe restore lock…: directory_shared`
fail the same way with the unchanged `master` source (the sandbox's Git
wrapper blocks clones).
- The other three hit the 15 s test timeout under load. Run alone,
`restores offline partial Git state…` passed twice with this change, and
passed once and failed once with the unchanged `master` source.
- The finalizer telemetry suite (#20678's tests, including "hands a full
sandbox disk to saved-work recovery on the first copy-back failure")
passes. The appended cause keeps the
`remote_workspace_sandbox_disk_full:` prefix, and the saved failure code
still comes from the text before the first `:`.
- A full typecheck was not run locally: `tsc` ran out of memory in this
sandbox. CI typecheck and build must pass.
- Environment: Linux, Node v25.9.0, filtered `pnpm install` of the
server package.

## Risks

- Low risk. The thrown error message and the save failure code do not
change, so retry policy, recovery classification and full-disk cache
reclaim behave as before.
- The run error text ("Last cause: …") becomes longer for this case. It
stays below the 1024-character bound and matches the existing
`readWorkspaceFailureCause` grammar (a test checks this).
- An unreadable or vanished file now reports `fs_<errno>` instead of
`unsafe_source`. That is more exact. Both reasons keep the source
retained and do not produce a receipt.
- No documentation text changed. `doc/execution-semantics.md` says that
transfer failures "retain the original disk-full error", and that stays
true.

## Model Used

- Provider: Anthropic. Model: Claude Opus 5.5 (`claude-opus-5-5`), used
through Claude Code with tool use (shell, file editing, test runner,
GitHub connector). The exact context window is not shown in this
session.

## 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 (the new tests pass; the
two clone-dependent failures also fail on unchanged `master` here)
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes (no
change needed: the documented contract is unchanged)
- [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>
2026-11-20 19:32:44 -08:00
Nicky Leach 467fd32223 Publish tool profiles and their selectors atomically (#22455) 2026-11-20 19:02:54 -08:00
Nicky Leach 7f4cfae5e1 Narrow exact connected tool reads before loading schemas (#22457) 2026-11-20 19:02:39 -08:00
Devin FoleyandPaperclip 18978bdc1d fix(native): preserve named human unblock owners (#22438)
## Thinking Path

> - Paperclip manages work carried out by agents and people.
> - Native finalization converts a runner result into a durable task
status and follow-up effects.
> - A blocked result can name the person who must decide what happens
next.
> - The classifier discarded that identity, and the arbiter saved a
generic board owner.
> - This could replace an explicit user owner saved through the task API
and leave the decision outside that person's inbox.
> - This pull request resolves human owners against active company
membership and preserves them through commit.
> - The named person receives the existing blocker card, and the blocked
worker does not get another wake.

## Linked Issues or Issue Description

**What happened?**

Native finalization replaced a named human unblock owner with `board`.
It also overwrote an explicit user owner saved through the task API
during the turn.

**Expected behavior**

Keep a valid human unblock owner and route the blocker card to that
person's inbox. Use the board when the reference is unknown, inactive,
ambiguous, or outside the company.

**Steps to reproduce**

1. Create an active company member with a distinct display name.
2. Have a native worker report a human blocker using that name.
3. Finalize the run and read the task's unblock owner and the member's
inbox.

Related: #21265 covers named agent handoffs and retains board ownership
for people. This change covers human member routing and does not add
agent handoffs.

## What Changed

- Resolve a human owner from an explicit user ID, an API-bound user, or
one matching company member by ID, full name, or email.
- Preserve the user owner for both blocker scopes and durable dependency
waits.
- Recheck the accepted result and active membership under the status
commit lock, including board fallbacks. Rebuild the assessment on every
status retry so a newly saved owner or revoked membership cannot be
overwritten by stale evidence.
- Enforce `canAssignTasksToHumans` before binding a human owner,
including dependency waits that do not emit a `bind_blocker` effect.
- Validate the result before retiring automatic completion reviews.
Invalid results leave existing reviews pending; valid results retain the
normal cleanup path.
- Keep human blocker routing out of the agent wake queue.
- Add embedded Postgres regressions for finalization, replay, personal
attention, invalid owners, late API ownership changes, membership
revocation, permission denial, and answer continuation for human-owned
blockers.
- Make the answer-continuation fixture persist the same result it
classifies, so commit-time evidence validation sees realistic saved
evidence. Assert the resolved user owner in both blocker scopes.
- Let the recovery census clock advance at real-time pace during
delivery I/O waits. This handles callbacks and nested timers without
jumping to maintenance deadlines. Preserve the existing real-clock
timeout and recovery assertions, and name pending queues in failures.
- Document human blocker resolution and compatibility.

## Verification

- Red-green reproduction: three ownership regressions failed on the
original implementation and passed with the fix.
- Red-green race reproduction: late API ownership changes and membership
revocation failed before the commit recheck and per-retry reassessment
fixes. Each finalization invocation now has to commit; a later replay
cannot hide an exhausted retry.
- Red-green review-retirement reproduction: a new invalid result
cancelled a proven automatic review before throwing
`native_result_invalid_disposition`. The new invalid/valid regression
pair verifies that invalid results preserve the pending review and task
decision, while valid completion still retires the card.
- Red-green answer-continuation reproduction: both human-owner cases
failed with `native_status_race` while saved evidence was empty.
Persisting the classified result and asserting `{ userId }` restored all
13 answer-continuation cases, including worker resumption.
- Red-green permission reproduction: an agent with
`canAssignTasksToHumans: false` could bind a human blocker before the
permission check. Direct and dependency cases now refuse finalization
without creating a personal blocker card.
- On refreshed head `a6d37916546`, `pnpm --filter @paperclipai/server
exec node scripts/typecheck-layers.mjs` passed on macOS with Node 24.
- On refreshed head `a6d37916546`, from the repository root, `CI=true
node node_modules/vitest/vitest.mjs run
server/src/services/native-runtime/native-agent-blocker.integration.test.ts
server/src/services/native-runtime/status-arbiter.test.ts
server/src/services/native-runtime/evidence-classifier.test.ts
server/src/__tests__/native-status-reassessment-work.test.ts
server/src/__tests__/routable-blocked.test.ts
server/src/__tests__/native-status-arbiter-corpus.test.ts
server/src/services/native-runtime/native-environment-blocker.integration.test.ts
server/src/__tests__/heartbeat-blocked-question-answer.test.ts
server/src/__tests__/issue-recovery-live-run-agent-census.test.ts`
passed: 292 tests in nine files on macOS with Node 24.
- Red-green census reproduction: both post-I/O callbacks and nested
timers must settle without jumping to a future maintenance deadline. The
nested case timed out under a zero-only clock pump; the shared
automatically advancing census clock handles both.
- Final CI at `a6d37916546`: [run 44848053016, attempt
2](https://github.com/paperclipai/paperclip/actions/runs/44848053016/attempts/2)
completed successfully. Build, Canary Dry Run, policy, every server and
workspace test shard, Runner checks, serialized suites, e2e, and verify
are green. Greptile review 7 is 5/5 on the same head, Superagent and
other security checks pass, and no review threads remain unresolved. A
local merge-tree check against master `621c5577cdf` also passed with no
conflicts.
- Current CI at `a6d37916546`, [run
44848053016](https://github.com/paperclipai/paperclip/actions/runs/44848053016):
attempt 1 finished with 13 interrupted nonaggregate jobs, each with an
explicit runner shutdown signal in its log. Nine signals occurred within
three seconds on separate m6a.xlarge hosts in us-east-1a; Build and
Canary also shut down later. Aggregate e2e and verify failed on those
dependency results. The underlying termination cause remains unknown.
Shared CI settings are unchanged.
- The [automatic recovery
run](https://github.com/paperclipai/paperclip/actions/runs/44849704877)
skipped retry because Build had only the annotation `Process completed
with exit code 143.` The classifier reads logs for cancellation
annotations, but did not read this job's log. That log explicitly
records a runner shutdown at 01:10:49 UTC. The other 12 failed jobs were
recognized as runner loss. After verifying all 13 logs, manually
requested failed-job attempt 2; it completed successfully without source
or configuration changes between attempts. The shared recovery
classifier is unchanged; this false negative remains a documented
follow-up.
- Historical CI at `cf601ba`: all server shards (including the census),
Runner checks, typecheck/release registry, serialized suites, e2e, and
canary dry run passed. Build received runner shutdown signals on
attempts 1–7; aggregate verify failed because Build failed. Attempt 5
diagnostics show shutdown while the job lease was valid. Attempt 7
stopped after server dependency preparation, without a compiler error.
The termination cause remains unknown. Three recent PRs completed Build
on the same AWS fleet; this is not evidence of a fleet-wide outage.
Shared CI settings are unchanged.
- Diagnostic comparison at `cf601ba`: the server compiler passed locally
on macOS with four checkers, full typechecking, and
declaration/JavaScript emission (`node ../scripts/run-tsc.mjs --checkers
4 --extendedDiagnostics` under Node 24). The monitored process group
peaked at about 10.5 GiB RSS and finished in 25.8 seconds. This does not
establish the cause of the Linux runner shutdowns.
- Refreshed the branch onto master `611dc68581c` without conflicts; the
PR source diff is unchanged. Greptile review 7 scored head `a6d37916546`
5/5 with no new actionable findings and no unresolved review threads.
All applicable CI gates passed on attempt 2.
- Full local workspace build at `cf601ba` passed on macOS using Node 24
and the documented single-thread compiler mode:
`PAPERCLIP_TYPECHECK_LOW_MEMORY=1 npx --yes --package=node@24
--package=pnpm@9.15.4 pnpm build`. This includes typechecking and
artifact emission. The tracked working tree stayed clean.
- `pnpm verify --explain` returned exit 2 because this documentation
path requires broad CI coverage. Fresh CI will supply that coverage; the
full local test suite was not run.
- Earlier CI build and canary jobs received runner shutdown signals. The
server shard also exposed an answer-continuation fixture that saved an
empty result while classifying a named human. That mismatch was
reproduced locally, and the fixture now persists the classified result
and checks the user owner. Fresh CI is required for this revision.
- `git diff --check` and the staged gitleaks scan passed. The diff was
also checked for private issue references, identifiers, URLs, and
personal data.

## Risks

- Name and email matching ignore case. Several matches fall back to the
board. Invalid explicit IDs never fall through to another person.
- Resolution adds bounded reads only when a native result reports a
human blocker. It adds no worker, timer, or idle scan.
- No database or result-schema migration is required. Existing board and
agent decisions remain readable. Committed historical decisions are not
rewritten; new finalizations use current membership.
- This changes human routing only. It grants no access and changes no
merge, approval, or dependency policy.

## Model Used

- OpenAI GPT-6.1 Sol (`gpt-6.1-sol`) through Codex in T3 Code, with
xhigh reasoning effort, code editing, shell tools, and test 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 and contains no internal
Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-20 17:45:45 -08:00
621c5577cd fix(tasks): hide More messages when no hidden history exists (#22099)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The task page shows the instruction and the recent exchange first,
and shows a **More messages** button for older history
> - The button is visible on almost every task. A click often shows no
new message, and the button then goes away
> - The compact chat shows only the latest run, so the page treats any
task with two or more runs as a task with hidden history
> - The recent comments read also reports more comments when the omitted
comment is already pinned into the window
> - This pull request shows the button only when a message is really
hidden
> - The benefit is a clean task page and a button that always reveals
something

## Linked Issues or Issue Description

Refs #17751

**What happened?**

The task page shows **More messages** on almost every task. A click
often adds no message, and the button then goes away.

**Expected behavior**

The page shows **More messages** only when it hides an older comment or
an older run that has no visible answer.

**Steps to reproduce**

1. Create a task and let an agent answer it in two runs.
2. Open the task with a fresh application cache.
3. See **More messages** above the conversation. Click it. No new
message appears.

## What Changed

- The recent run window keeps the newest omitted run (`earlierRun`), and
it keeps that run as later turns arrive.
- The task page ignores the omitted run when the run succeeded and its
agent answer is already visible. A failed run, or a run with no visible
answer, still shows the button. The answer check is the same one the
chat thread uses (moved to `ui/src/lib/run-answer-visibility.ts`), so a
legacy withheld-run placeholder or a progress comment does not count as
an answer.
- `GET /issues/:id/recent-comments` reads seven rows instead of five. It
sets `hasMore` only when the window leaves out a comment. Older comments
that are pinned into the window (the latest human message and the first
instruction) do not count.
- Added regression tests for the page (including the placeholder case),
the run window cache and the server route.

## Verification

- `pnpm exec vitest run src/pages/IssueDetail.test.tsx
src/components/TaskChatThread.test.tsx src/lib` in `ui`: 3,637 passed, 1
skipped. The new page test fails without the fix.
- After the review fixes: `pnpm exec vitest run
src/pages/IssueDetail.test.tsx src/components/TaskChatThread.test.tsx
src/lib/issueChatBootstrapCache.test.ts
src/lib/issueDetailCache.test.ts` in `ui`: 738 passed, 1 skipped.
- `pnpm exec vitest run src/__tests__/task-cold-open.test.ts
src/__tests__/issue-chat-bootstrap-routes.test.ts` in `server`: 33
passed.
- `tsc --noEmit` in `ui` and `server`: no errors in the changed files.
- I did not do a check in the browser.

## Risks

Low risk. No schema change. The API response shape does not change. The
run window cache gets one optional field, and older saved caches without
the field keep the old behavior.

Limitation: the recent runs read returns only the two latest runs, so
the page sees one omitted run. If that run has a visible answer but an
older run failed, the page does not show the button. **More task actions
→ Show task activity** still shows that run.

## Model Used

Claude Opus 5.5 (`claude-opus-5-5`) 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: devinfoley <139239+devinfoley@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 17:41:17 -08:00
Devin FoleyandPaperclip b4cea5b5a4 fix(runner): show disk exhaustion before recovery errors (#22448)
Show the confirmed sandbox disk failure before a later lost-turn or restore error in saved run errors and both run detail views. Preserve the original diagnostics and leave scarce inodes available when preparing the existing runner relaunch reserve.

Verified focused regressions, scoped typechecks, and full CI on the reviewed revision, including Runner checks and all eight end-to-end shards. Greptile is 5/5 with all review findings resolved.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-11-20 17:08:31 -08:00
Nicky LeachandPaperclip b6a904554d Load summaries for the Access Profiles index (#22456)
## Thinking Path

> - Paperclip helps people manage AI agents for work.
> - The Access Profiles page shows profile names, counts, and agent
assignments.
> - The index loaded every selector and started detail queries for each
connection.
> - The server can compute the displayed fields with the existing
visibility and review rules.
> - A summary route lets the index fetch just the data it renders.

## Linked Issues or Issue Description

**What existing behavior does this improve?**

Opening the Access Profiles index for a company with many assigned
tools.

**Current behavior**

The index downloads full profiles and requests other resources used by
detail views.

**Proposed behavior**

Fetch summaries and agents at mount. Keep the existing full-profile
route for detail callers.

**Reason and benefit**

In a generated fixture with 166 profiles and 176,257 entries, the
uncompressed response fell from 86,879,901 bytes to 58,095 bytes. The
mounted query count fell from 28 to 2 with 22 connections.

## What Changed

- Add the typed company summary route and its OpenAPI entry.
- Compute counts with the existing projection and use the same profile
visibility rules. Group equal selectors in PostgreSQL and send their
profile memberships as ordinals.
- Read summaries from the index. Keep profile mutations invalidating the
index.

## Verification

- Local UI typecheck and 27 UI tests passed. PostgreSQL projection and
route tests checked count parity, delegated visibility, and rejected
access.
- Layered server typecheck passed. PostgreSQL tests also covered all
selector types, null and unknown legacy selectors, duplicate
memberships, and overlapping include/exclude rules.
- On a disposable database with fresh PostgreSQL statistics, 166
profiles and 176,257 memberships, four interleaved trials per summary
implementation returned identical 58,095-byte JSON responses. PostgreSQL
transferred 36,338,231 bytes for flat summaries and 1,819,600 bytes for
grouped summaries (95% less). Both used five statements. Median service
and serialization time fell from 589 to 227 ms (564–627 ms versus
216–238 ms).

## Risks

The summary still enumerates selector memberships in PostgreSQL.
Grouping raised warm PostgreSQL executor time for the selector query
from about 17 ms to 136–137 ms and used about 15 MiB for the temporary
sort in the fixture. The smaller transfer reduced total service time in
the same synthetic workload. Exact timing will vary with database
resources and profile shape.

## Model Used

OpenAI Codex (GPT-6), with GPT-6.2 Sol agents for implementation and
local verification.

## Checklist

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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-20 16:45:34 -08:00
Devin FoleyandPaperclip ae2afd525b Make harness choices deployment-configurable
Managed deployments need to control harness availability without changing Core policy. Add a generic environment contract and apply it across harness and model selectors, preserving saved supported profiles and validating import, team, and invite selections. Document deployment ownership in agent guidance.

Validation: focused local tests and typechecks passed; all applicable CI checks passed on the reviewed head. Greptile scored 5/5 with no unresolved comments.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-11-20 15:45:36 -08:00
Devin FoleyandPaperclip 9bc90cb189 Show useful task notification content (#22441)
Task notifications repeated identifiers and omitted useful activity details.

Use task titles, actor and comment previews, and concrete field changes. Share bounded secret redaction per event after viewer access checks. Suppress updates without useful details.

Verified with focused regression tests, package typechecks and server build, and the full green CI run. Greptile scored the final head 5/5 with no unresolved review threads.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-11-20 14:40:39 -08:00
Devin FoleyandPaperclip 2898acee2d fix: exclude responsibility repairs from Mine participation (#22434)
Exclude responsibility-repair audit entries from personal task
participation. Maintenance attributed to an operator no longer pulls
unrelated tasks into Mine, unread badges, or task notifications.

Preserve audit history and genuine participation through creation,
assignment, comments, deliberate edits, and pending requests. Add database
regressions and document the rule.

Verified with 174 targeted tests, server typecheck, fully green CI,
and Greptile 5/5 with no unresolved review comments.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-11-20 11:28:11 -08:00
ef18d71672 fix(workspaces): reopen an expired workspace after its move to remote storage (#22429)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Before a run starts, Paperclip can reopen a task's archived
execution workspace
> - Git cache expiration removes the local files of an idle workspace
and saves a local restore recipe
> - Remote workspace storage migration can later move that expired
workspace into a saved snapshot. The migration changes the workspace
`cwd` to `/workspaces/<id>`, but it keeps the local restore recipe. That
recipe still names the removed worktree path
> - Run setup reads the recipe through `readGitCacheExpiration` before
it reopens the workspace. The recipe no longer matches the workspace
`cwd`, so validation fails and every run on that task fails in setup
> - This pull request makes run setup read only the current lifecycle's
expiration marker for a workspace in remote storage
> - The benefit is that the task reopens from its saved snapshot. The
reopen path already does this for remote-storage workspaces

## Linked Issues or Issue Description

Refs #22419 (gave this failure its own error code,
`git_cache_restoration_failed`). Refs #19736 (restore diagnostics). I
found no open PR for this cause.

**What happened?**
On staging, runs on some tasks fail during setup with "The saved
workspace commit could not be restored. Check repository access and
retry." The stack is `selectHeartbeatEnvironment` →
`readGitCacheExpiration` → `readGitCacheRestoration`. The task's
workspace is archived with `cleanupReason:
reproducible_git_cache_expired`. It also has a `remoteWorkspace`
authority from the storage migration, and `cwd` is `/workspaces/<id>`.
Its `gitCacheRestoration.worktreePath` is still the old local worktree
path. `readGitCacheRestoration` requires `recipe.worktreePath ===
workspace.cwd`, so it throws. Automatic recovery repeats the run and the
run fails again.

**Expected behavior**
Run setup sees that git cache expiration removed the workspace, and it
reopens the workspace. `reopenClosedIsolatedExecutionWorkspaceForIssue`
restores a workspace with a remote authority from its snapshot and does
not read the local recipe.

**Steps to reproduce**
1. Archive an isolated workspace with a completed `gitCacheExpiration`
marker and a `gitCacheRestoration` recipe.
2. Apply what the remote storage migration does: set `remoteWorkspace`
authority and set `cwd` to `/workspaces/<id>`.
3. Start a run on the bound task. On current master,
`selectHeartbeatEnvironment` throws `GitCacheRestorationFailure`.

## What Changed

- `server/src/services/heartbeat/environment-selection.ts`: add
`gitCacheExpirationRemovedWorkspace`. For a workspace without a remote
authority, it uses `readGitCacheExpiration` as before, with the full
recipe check. For a workspace with a remote authority, it reads only the
`gitCacheExpiration` marker. The marker must have the expected schema,
`workspaceRemoved: true`, and a `generation` that equals the current
`lifecycleGeneration`. A marker from an earlier lifecycle does not start
a reopen.
- `server/src/services/heartbeat/environment-selection.test.ts`: add two
tests that use the real `readGitCacheExpiration`, a migrated workspace
row and a committed snapshot. One test runs the real reopen operation
through `selectHeartbeatEnvironment`. It checks that the same workspace
becomes active, keeps its `/workspaces/<id>` cwd, stays bound to the
issue, and that `lifecycleGeneration` advances from 3 to 4. One test
checks that a marker from an earlier lifecycle does not start a reopen.

## Verification

- Red/green: on unmodified master, both new tests fail (rechecked after
the review change) with "The saved workspace commit could not be
restored" and the same stack as the staging events. With the fix, they
pass.
- `pnpm exec vitest run
src/services/heartbeat/environment-selection.test.ts`: 27 passed.
- `pnpm exec vitest run src/__tests__/execution-workspace-reopen.test.ts
src/__tests__/git-workspace-restoration-diagnostic.test.ts`: all pass.
(When I ran the two files together, one reopen test hit its 25 s
timeout. It passes alone, and that file does not import the changed
module.)
- `pnpm --filter @paperclipai/server typecheck` (all layers): passes.

## Risks

- Low risk. The change only affects archived workspaces that have a
remote authority. Local workspaces keep the full recipe check.
- A remote-storage workspace now reopens through the existing remote
path. That path checks the saved snapshot first
(`inspectRemoteWorkspacePersistence`) and returns `rebuild_failed` if
the snapshot is not ready. So a missing snapshot still fails the run
with a clear reason.
- Not in scope: the migration keeps the stale local recipe in metadata.
Other readers of that recipe do not run for remote-storage workspaces in
this path.

## Model Used

Claude Opus 5.5 (`claude-opus-5-5`) via Claude Code, as the Paperclip
Sentry triage agent, 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
- [ ] I have updated relevant documentation to reflect my changes (no
documentation describes this check)
- [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: paperclipbugbot <356415228+paperclipbugbot@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 10:47:43 -08:00
Devin FoleyandClaude Opus 5.5 203c10d212 fix(api): tell agents that issue count requires attention=blocked (#17596)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Agents find REST routes through the runner API catalog
(`search_api`) and call them with `call_api`
> - The catalog shows `GET /api/companies/{companyId}/issues/count` as
"Count issues in a company". It gives no description and no query
parameters
> - The route only counts blocked issues that need attention. It returns
400 when the request does not include `attention=blocked`
> - Agents read the summary as a generic counter. They call the route
without the filter and get a 400. A hosted instance reported these 400
responses as failed HTTP operations
> - This pull request adds the route contract to the Paperclip skill API
reference. It also regenerates the catalog enrichment, so `search_api`
returns the contract with the operation
> - The benefit is that agents get the required filter and the correct
alternative before they call the route. Runtime validation does not
change

## Linked Issues or Issue Description

No public issue exists. I searched open pull requests for `issues/count`
and found no duplicate.

**What happened?**

An agent called `GET /api/companies/{companyId}/issues/count` with only
a `labelId` filter. The server returned `400 issues/count currently
requires attention=blocked`. The catalog entry that the agent read
showed only the summary "Count issues in a company", so the agent had no
way to know the filter was required.

**Expected behavior**

The catalog tells the agent that `attention=blocked` is required. It
also lists the accepted filters, says that `limit` and `offset` are
rejected, and tells the agent how to count anything else by paging
through the issue list.

**Steps to reproduce**

1. As an agent, call `search_api` with the query `count issues`.
2. Read the `GET /api/companies/{companyId}/issues/count` result. It has
no description and no `skillReference`.
3. Call the route through `call_api` with `query: { labelId:
"<label-id>" }`.
4. The server returns 400.

**Paperclip version or commit**

`master` at 2e47c42fad.

**Deployment mode**

Hosted. The behaviour is the same in every deployment mode, because the
route validation and the catalog are core code.

## What Changed

- `skills/paperclip/references/api-reference.md`:
- Add a row for `GET /api/companies/:companyId/issues/count` to the
Issues table. The row says that `?attention=blocked` is required and
that other requests return 400. It names the accepted issue-list filters
and says that `?limit=` and `?offset=` are rejected. For any other
count, it says to page through `GET /api/companies/:companyId/issues`
with `?limit=` (default 500, maximum 1000) and increasing `?offset=`
until a page is empty. A short page is not the end, because the list
route filters rows for restricted actors after the database applies the
limit.
- Merge the two `GET /api/issues/:issueId/heartbeat-context` rows into
one. The generator keeps only the last row for a route, so the first
description never reached the catalog. Merging also keeps every later
heading on its current line. The generated capability contract and
inventory record skill headings by line number, so they stay unchanged.
- `server/src/services/native-runtime/runner-api-reference.ts`:
regenerate with `node scripts/generate-runner-api-reference.mjs`. The
count route gets a new entry, which the catalog attaches to the
operation as `skillReference`. The heartbeat-context entry gets the
merged description.
- `server/src/services/native-runtime/runner-api-reference.test.ts`: new
regression test. It searches the catalog for `count issues` and checks
that the count operation's `skillReference` describes the contract and
the paging rule.

## Verification

- `node scripts/generate-runner-api-reference.mjs --check` passes. The
generated file matches the skill reference.
- `node
packages/paperclip-runner/scripts/generate-capability-contract.mjs
--check` and `node
packages/paperclip-runner/scripts/check-capability-inventory.mjs` pass.
On the first head they failed with "Generated contract drift:
generated/capability/capabilities.yaml", the cause of the Typecheck,
Build, Canary and Docker context failures there.
- The new test failed on `master` (no `skillReference` on the count
operation) and passed on the first head. That run covered the
runner-api-reference, runner-api, hiring-operational-examples and
openapi-routes suites (2019 + 1 tests) and `paperclip-skill-utils` (21
tests).
- The sandbox used for this revision did not have room to install
workspace dependencies, so I did not rerun vitest locally. Instead I
checked the regenerated catalog entry for each string the test asserts.
CI runs the full suites.
- I did not run `pnpm -r typecheck` or the full suite locally. CI runs
both.

## Risks

- Low risk. The change is documentation plus generated catalog entries.
- Route behaviour, authorization and the OpenAPI document do not change.
- The OpenAPI summary for the route stays "Count issues in a company". A
later change can also register the route in
`server/src/routes/openapi.ts` with its query schema and error
responses.

> 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 as an agent with
tool use (shell, test execution and the GitHub connector).

## 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>
2026-11-20 10:32:11 -08:00
Devin FoleyandPaperclip 42c8fee59b fix(run-log): give each object-journal read attempt its own deadline (#21508)
Give each object-journal read attempt its own deadline.

Co-Authored-By: Paperclip <Paperclip-Paperclip@users.noreply.github.com>
2026-11-20 10:31:58 -08:00
1a50bd550e fix(sentry): report a saved-sandbox resume provider outage only after its retry decision (#21510)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - A run that uses a saved (reusable) sandbox resumes that sandbox
during setup, before the provider work starts.
> - When the sandbox provider has an outage, the resume gets an HTTP 5xx
answer. Setup fails with `reusable_sandbox_resume_failed`. Paperclip
keeps the lease and schedules the bounded bootstrap retry, which resumes
the same lease when the provider recovers (#20626).
> - The setup path writes the failed status before it decides the retry.
That write sends the Sentry run-failure report. Thus each attempt during
an outage creates an "unexpected failure" event, also when the retry
recovers the run.
> - The reviewed chat setup wait had the same defect. #20205 fixed it
with a `pending` report handshake.
> - This pull request uses the same handshake for a sandbox resume that
the provider answered with an HTTP 5xx.
> - The benefit: Sentry shows a sandbox resume failure only when the
retry cannot recover it.

## Linked Issues or Issue Description

**What happened?**

Staging Sentry recorded `EnvironmentRunError: Failed to acquire lease
for environment "… Sandbox" (sandbox): Reusable sandbox lease "…" could
not be resumed (cause=provider_unavailable status=502); the lease was
preserved and no replacement was created.` The events came in bursts: 5
different tasks in one minute (HTTP 503/504), and 2 tasks in three
minutes on a different day (HTTP 502). All events had
`failure_phase=setup` and no provider work. In the source run, the
scheduled bootstrap retry got past the resume step.

**Expected behavior**

A provider outage that the bounded retry owns does not create a Sentry
event. A retry that is exhausted, not scheduled, or that fails to
schedule still creates one event. A refusal of the sandbox (an HTTP 4xx,
or no status) still reports as before.

**Steps to reproduce**

1. Use an agent with a reusable sandbox environment that has a saved
lease.
2. Make the sandbox provider answer the resume with HTTP 502.
3. Start a run. Setup fails with `reusable_sandbox_resume_failed` and
schedules the bootstrap retry.
4. See a Sentry run-failure event for each attempt.

**Paperclip version or commit**

`2756be2f32` (staging releases `d0057ee384`, `1d153f62b6`, `e23549cd9c`
also show the events).

I searched for duplicate PRs. #20626 added the retry and safe
replacement for a sandbox that will not resume. It does not change when
the failure is reported. #20205 is the precedent for the reviewed chat
wait.

Fixes PAPERCLIP-BACKEND-77

## What Changed

- `server/src/services/reusable-sandbox-resume-error.ts`:
`ReusableSandboxResumeError.providerOutage` is true only when the closed
HTTP status of the provider answer is 5xx. The text of a gateway page
does not decide.
- `server/src/services/heartbeat/run-completion.ts`: For a provider
outage, the failed-status write sets `sandboxResumeRetry: "pending"`.
After the retry decision, the setup path reports the run once with
`scheduled` or `not_scheduled`. The deferred-report code is shared with
the reviewed chat wait.
- `server/src/services/run-failure-report.ts` and
`run-failure-diagnostics.ts`: A `pending` sandbox resume write does not
report. In `unexpected` mode, a `scheduled` retry of a failed
`reusable_sandbox_resume_failed` run does not report. `all` mode still
reports it.
- Tests: `run-failure-report-sandbox-resume.test.ts` (new) covers the
report filter. `run-completion-reviewed-chat-report.test.ts` now also
covers the setup path for 502 and 504 with a scheduled retry, an
exhausted retry, no retry, a scheduler failure, a 4xx refusal and a
refusal without a status.

## Verification

- `vitest run
src/services/__tests__/run-failure-report-sandbox-resume.test.ts
src/services/heartbeat/run-completion-reviewed-chat-report.test.ts
src/services/__tests__/run-failure-report.test.ts`: 308 tests pass
(embedded Postgres).
- Red check: before the fix, the 6 new outage cases fail, because the
failed-status write reports immediately.
- Earlier, on the base commit, the related run-completion, retry
scheduling, recovery and run-failure-report suites passed (407 tests).
- `tsc --noEmit -p server/tsconfig.json`: no errors in server sources.
- The full workspace install did not fit on the agent sandbox disk, so
CI runs the complete affected-test selection.

## Risks

- Low risk. Run status, error code, the retry and lease handling do not
change. Only the time of the Sentry report changes.
- If the process stops between the failed-status write and the retry
decision, no report is sent for that attempt. The reviewed chat wait has
the same accepted behavior. A later terminal failure of the retry still
reports.
- 4xx and unclassified resume failures keep the report on the
failed-status write.

## Model Used

- Anthropic Claude Opus 5.5 (`claude-opus-5-5`), in the Claude Code
agent harness with tool use (shell, file edits, Sentry and GitHub
connectors).

## 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: Paperclip <noreply@paperclip.ing>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 09:49:17 -08:00
88469bd2bc fix(retry): wait for the failed run's sandbox to stop before repeating its chat request (#22423)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - A task from a connected chat (for example a GitHub pull request
review) can fail. Retry then repeats the exact failed chat request in a
new run
> - Before that run starts the agent, it checks again that the failed
run's executor is stopped. For a remote sandbox, the proof is a stop
receipt on the sandbox lease
> - Workspace recovery can restart the failed run's sandbox at the same
time, to save its files. While it does this, the lease has no stop
receipt
> - The check then refused the repeated request. The run failed for
good, although recovery stopped the sandbox again a few seconds later
> - This pull request makes the repeated request wait while a stop of
that sandbox is in progress, and then ask the retry authority again
> - The benefit is that a correct Retry is not lost because of a short
overlap with workspace recovery

## Linked Issues or Issue Description

Refs #22414. That PR fixes the next step of the same incident: the
system replacement run that copied the consumed retry selector. This PR
fixes the first refusal. The two PRs change different files and are
independent.

**What happened?**

On a hosted staging deploy, a GitHub review reply task failed
(`native_continuation_requires_reconciliation`). Its Daytona sandbox
went into workspace recovery. A Retry started a new run that repeats the
exact chat request, in a fresh isolated workspace. The run passed
admission and its first execution check. After about 14 seconds of
workspace preparation, the `dispatching` recheck refused it with 409
`chat_failed_run_retry_not_authorized` ("This chat request can't be
repeated exactly as it was sent."). No provider work started. The
recovery reported "Saved work recovered" 12 seconds later. The GitHub
reply request was not answered.

**Expected behavior**

The repeated request waits while the failed run's sandbox stops again,
and then continues. If the stop does not settle, the request is refused
as before.

**Steps to reproduce**

1. Make a native chat task fail on a remote sandbox with a recorded stop
receipt.
2. Start workspace recovery for that run.
`prepareStoppedSandboxForRecovery` moves the lease to `pending_cleanup`
and removes `remoteExecutionTermination` while the sandbox restarts.
3. Press Retry during that interval.
`taskChatRetryExecutionStopped(source)` is false, so
`assertFailedNativeRetryState` refuses the run at the `dispatching`
recheck.

The new test does steps 1 and 2 with the real lease transitions on an
embedded Postgres database.

**Paperclip version or commit**

`201abacd6ee5` (the staging release in the incident).

## What Changed

- Add
`server/src/services/chat-channels/failed-chat-retry-source-stop-wait.ts`:
- `failedChatRetrySourceStopPending()` is true when a non-local lease of
the failed run is `pending_cleanup` with a valid stop-only cleanup
intent (`readStopOnlyCleanup`). Workspace recovery holds such an intent
while it restarts and stops the sandbox.
- `awaitFailedChatRetrySourceStop()` runs the authorization again every
5 seconds, for up to 3 minutes, while that stop is pending. It reads the
pending stop before and after each refused attempt. If a stop was
pending before the attempt but is gone after it, the stop settled while
the refused transaction held no locks, so it reads the authorization
once more at once. If no stop is pending before or after, it returns the
refusal after one attempt, exactly as before. It waits only for the
reason-less containment refusal. It does not wait for a reasoned
refusal, a mismatched retry selector
(`FailedChatRunRetryAuthorizationError`), or any other error. It stops
when the run is stopped, and it returns the last refusal at the
deadline.
- In `heartbeat.ts`, both execution-phase checks of an exact replay (the
first check and the `dispatching` recheck) use this wait. The run log
records one line when the wait starts.

The wait grants no authority. Each attempt still runs the unchanged
`authorizeFailedChatRunRetryWake`. The controller lease is checked on
each attempt, as before.

## Verification

- `cd server && npx vitest run
src/services/chat-channels/failed-chat-retry-source-stop-wait.test.ts`:
10 tests pass. They use real lease rows and the real
`prepareStoppedSandboxForRecovery`,
`restoreSandboxStopAfterFailedRestart` and
`taskChatRetryExecutionStopped`.
- Red check: with the helper changed to make one attempt only (the old
behavior), the wait test fails with the incident's refusal: `promise
rejected "Error: This chat request can't be repeated…" { status: 409,
details: { code: 'chat_failed_run_retry_not_authorized' } }`. The abort
test also fails. Then I restored the helper.
- Red check for the review finding: with the old "no pending stop, so
refuse" line, the new test that commits the stop receipt between the
refusal and the pending-stop read fails with the old refusal. It passes
with the final read.
- A first version of that fix read the authorization again after every
refusal. CI showed this was wrong: `durable-chat-wakeup.test.ts` counts
authorization calls, and a budget-hold case in
`chat-channels.integration.test.ts` changed outcome. I reproduced both
failures locally with that version. The current version rechecks only
when a stop was pending, and those tests pass:
`durable-chat-wakeup.test.ts` (51), the CI-failing chat integration
cases by name (73), the retry-filtered chat integration run (261), and
the focused suites (300).
- Safety cases in the same file: refusal at the deadline when the
sandbox stays held; immediate refusal when no stop is in progress (an
active lease whose executor can still run); no wait for a reasoned
refusal, a selector mismatch, or another error; no wait for a run that
is not an exact replay; the wait stops when the run is stopped.
- Focused existing suites pass: `authorization-run-read.test.ts`,
`wake-queue/application/use-cases.test.ts`,
`__tests__/durable-chat-wakeup.test.ts`, `task-retry.test.ts`,
`budget-resume-continuation.test.ts` (299 tests in total, including the
new file).
- `pnpm --filter @paperclipai/server typecheck` passes.
- `pnpm verify` selects almost the full suite because `heartbeat.ts` is
a shared module. I did not run that locally. Required CI supplies that
coverage.
- I did not do a live staging reproduction. The incident timing cannot
be produced on demand. The test reproduces the lease state that the
refusal saw.

## Risks

- A repeated request can now hold its own prepared sandbox for up to 3
more minutes before it fails. This happens only while a stop of the
failed run's sandbox is in progress.
- The wait can not let a second executor run. It changes only when the
check runs, and every attempt uses the unchanged authority.
- If workspace recovery takes longer than 3 minutes, the run is refused
as before.

## Model Used

Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use
(shell, file edits and 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
- [ ] I have updated relevant documentation to reflect my changes (not
needed: the code and tests describe the behavior)
- [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: paperclipbugbot <356415228+paperclipbugbot@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 08:47:32 -08:00
Nicky LeachandClaude Opus 5.5 dce4d47f60 feat(plugins): carry Grok, Copilot and OpenCode credentials to plugin Runners (#22359)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Environment-driver plugins can run `paperclip_runner` tasks on hosts
that the plugin owns
> - Core transfers the selected managed AI credential to the plugin as a
typed task credential
> - The credential contract has only two types: a Codex auth file and a
direct Claude credential
> - Grok, GitHub Copilot and OpenCode agents in a task-capable plugin
environment therefore fail closed, although the Runner already reads
their credentials from its environment
> - This pull request adds one generic, allowlisted environment
credential for these three harnesses and accepts the Runner's Grok
launch settings
> - The benefit is that plugin-provided Runner execution can run Grok,
Copilot and OpenCode agents with their selected connection

## Linked Issues or Issue Description

**Subsystem affected**

Plugin environment tasks (`packages/plugins/sdk` task contract) and
plugin-provided Runner execution in `server`.

**Problem or motivation**

An agent with the Grok, Copilot or OpenCode harness cannot run in a
plugin environment that runs Runner tasks. Core stops at credential
preparation with "Plugin Runner does not support the selected credential
provider". A Grok agent fails before that point too. The Runner emits
`grokEffort` and `grokDisableWebSearch` in its launch requirements (Core
turns off Grok web search by default), but the strict `settings` schema
of `environmentRunnerLaunchRequirementsSchema` rejects both keys.

**Proposed solution**

Core transfers the selected connection's credential variables for these
harnesses through one typed `provider-env` credential. Each provider has
a fixed allowlist of complete variable sets. The plugin sets the
variables in the Runner process environment.

**Alternatives considered**

One credential type per harness (`grok-env`, `copilot-env`,
`opencode-env`). This adds a type for each new harness. One generic type
with an exported allowlist keeps the same strictness with less surface.

**Roadmap alignment**

The roadmap lists Grok and OpenCode as supported harnesses. This change
lets plugin environments run them. It adds no new product concept.

**Additional context**

Grok subscription login (an auth file with refresh and writeback) is out
of scope. It still fails closed, with an error that names the xAI API
key as the supported option.

## What Changed

- `packages/plugins/sdk`: Added the `provider-env` task credential: `{
type: "provider-env", provider: "grok" | "copilot" | "opencode",
environment }`. The environment must contain exactly one complete
variable set for the provider and no other variable. Values are
non-empty, NUL-free and at most 65,536 characters, as for the other
credential types.
  - `grok`: `XAI_API_KEY`
  - `copilot`: `COPILOT_GITHUB_TOKEN`
- `opencode`: `OPENROUTER_API_KEY`, or `PAPERCLIP_AI_PROVIDER_URL` with
`PAPERCLIP_AI_PROVIDER_KEY`
- `packages/plugins/sdk`: Exported the allowlist as
`ENVIRONMENT_TASK_PROVIDER_CREDENTIAL_KEY_SETS` and the
`PluginEnvironmentTaskCredentialProvider` type. `claude-env` and
`codex-auth-json` do not change.
- `packages/plugins/sdk`: Added `grokEffort` (`minimal` to `xhigh`) and
`grokDisableWebSearch` (boolean) to the launch requirements `settings`,
with the types that the Runner uses.
- `server`: `preparePluginRunnerCredentials` now transfers the selected
connection's variables for the `grok`, `copilot` and `opencode`
harnesses, with the same account identity semantics as the Claude
branch. It refuses a Grok subscription, a Grok base URL override, and an
incomplete or ambiguous set. The error never contains a credential
value.
- `server`: The submit check now matches a `provider-env` credential to
the task harness. Before, it treated every non-Codex credential as
Anthropic.
- Drift test:
`server/src/__tests__/plugin-runner-credential-names.test.ts` checks the
SDK key sets against the Runner. The SDK list stays written by hand, and
the Runner keeps its own lists of forwarded names. For `grok` and
`copilot`, each name must be in `ACPX_CREDENTIAL_NAMES`, survive sidecar
admission with the session binding that the Runner mints, and reach the
agent process. The binding requirement must match the Rust sidecar's
candidate agents. For `opencode`, each name must be in the OpenCode
proxy environment set. Each name must also be in the Rust sidecar
credential keys or the Rust OpenCode provider keys. The test reads those
from the Runner source, as the Codex security test does. A provider
without a Runner route fails the test.
`OPEN_CODE_RUNNER_ENVIRONMENT_KEYS` is now exported for this test.
- Docs: Added a "Typed credentials" section to
`doc/plugins/PLUGIN_ENVIRONMENT_TASKS.md`. It also documents the ACPX
credential binding that the Runner requires with a Copilot token.
Updated `doc/plugins/PLUGIN_RUNNER_EXECUTION.md`.

## Verification

- `npx vitest run tests/environment-task-release-resume.test.ts
tests/environment-tasks.test.ts` in `packages/plugins/sdk`: 96 passed.
The tests accept each valid shape. They reject mixed sets, two sets,
extra variables, another provider's variable, empty values, NUL bytes,
oversized values, unknown providers and extra fields, on `submit` and on
`resume`. They also check that every published allowlist set parses.
- `npx vitest run
src/services/native-runtime/plugin-runner-credentials.test.ts
src/__tests__/environment-task-runtime.test.ts` in `server`: 79 passed.
The new tests cover each provider's transfer, Grok subscription refusal,
Grok routing refusal, the fail-closed cases without value leaks, harness
matching at submit, and Runner-built Grok requirements
(`runnerProviderLaunchRequirements`) that parse through the task
contract and produce a Grok launch.
- `npx vitest run src/__tests__/plugin-runner-credential-names.test.ts`
in `server`: 4 passed. I broke each list locally to confirm that the
test fails: a renamed SDK key, an SDK provider without a Runner route,
and a dropped name in the Rust sidecar keys, the Rust candidate agents,
the Rust OpenCode keys and the TypeScript OpenCode keys. Each change
failed the test.
- `node scripts/typecheck-layers.mjs` in `server` (includes
`src/__tests__`): no errors.
- `npx vitest run
server/src/services/native-runtime/plugin-runner-probe.test.ts` (from
the root): 15 passed.
`server/src/services/native-runtime/plugin-runner-task.test.ts`: passed.
- `tsc --noEmit` for `packages/plugins/sdk` and `server`: no errors.
- I did not run the full suite locally. CI supplies that coverage.

## Risks

- Low risk for existing plugins. The change only adds a credential type
and two optional settings. A plugin that does not handle `provider-env`
gets a typed value that it does not recognize. Before this change, Core
failed these runs before it called the plugin.
- A plugin must set `PAPERCLIP_ACPX_CREDENTIAL_BINDING` for a Copilot
task. Otherwise the Runner refuses the token. The new doc section shows
the value.
- An OpenCode gateway connection without a key (`auth: none`) still
fails closed, because every value must be non-empty.

> 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`) by Anthropic, 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>
2026-11-20 08:47:18 -08:00
DottaandClaude Opus 5.5 a0fe90f24b fix(retry): never offer Retry while a live run owns the task (#22428)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Each task shows an interruption banner. The banner offers Retry when
an attempt failed and nothing will move the task forward
> - The banner reads the task's newest run. A continuation that the
system cancels before it starts can be the newest run, while a different
run owns the task and does the work
> - In a restart-chaos wave, the banner offered Retry for about 140
seconds while the owning run worked. The task then finished with no
click
> - A Retry that the user does not need breaks the rule that the
needed-Retry rate is 0%
> - This pull request makes the banner and the Retry endpoint read the
same observed run. That run is the live run that owns the task, or else
the newest real attempt
> - The benefit is that Retry shows only when nothing will advance the
task, and a shown Retry is accepted

## Linked Issues or Issue Description

**What happened?**

A restart-chaos wave (three release swaps) showed a Retry banner on one
task for 141 to 144 seconds. The reason code was
`issue_execution_lock_changed`. Nobody clicked Retry, and the task
completed.

Timeline (UTC):

- 14:32:09. Run A starts.
- 14:51:12. A user follow-up wakes run B. Run B is queued behind run A.
- 14:52:46. Run A succeeds. The system schedules continuation run C
(`retryOfRunId` = A, reason `native_agent_blocker_continuation`). Run B
starts and takes the task execution lock.
- 14:53:16. The dispatch gate cancels C before it starts with
`issue_execution_lock_changed`, because run B owns the lock. This is
correct de-duplication.
- 14:53:17. The banner shows `failed` with Retry. Run C was created
after run B, so C is the newest run. The projection reads only the
newest run and ignores that run B is running and owns the lock.
- 14:55:41. Run B succeeds and the task is done. The banner goes away.

Retry was never needed. Run B owned the task for the full banner window.

**Expected behavior**

The banner does not offer Retry while a run owns the task and is queued
or running. A run that the system cancelled before it started because
another run took the lock is not a failed attempt. When Retry is shown,
pressing it is accepted for the run that the banner shows.

**Steps to reproduce**

1. Create a task. Run A succeeds and leaves the task in progress.
2. Queue run B for the same task (for example, a user comment). Create
continuation run C after run B.
3. Start run B and set it as the task execution lock owner.
4. Cancel run C before it starts with error code
`issue_execution_lock_changed`.
5. Read the task interruption. Before this change: `state: failed`,
`canRetry: true`, observed run C. After this change: `state: working`,
`canRetry: false`, observed run B.

**Paperclip version or commit**

`fe0c4aa95d` (master at the time of the wave).

## What Changed

- `server/src/services/task-retry-eligibility.ts`: add two shared
conditions.
- `taskAttemptCondition()`: a run cancelled before it started with
`recovery_no_longer_needed`, `issue_closed_before_start` or
`issue_execution_lock_changed` is not an attempt. The first two codes
were already excluded inline in the projection.
`issue_execution_lock_changed` is new.
- `liveExecutionOwnerCondition()`: the run is the task's execution lock
owner and it is queued or running.
- `server/src/services/task-interruption-presentation.ts`: the observed
run is the live execution owner when there is one. Otherwise it is the
newest attempt, with the same native, first-class and legacy precedence
as before. The owner lookup is a primary-key read, so the per-task run
scan does not grow.
- `server/src/services/task-retry.ts`: Retry admission, the refused chat
Retry continuation and the superseded-Retry check use the same attempt
filter. Admission also accepts the live execution owner when the request
names it. The newest attempt stays acceptable, so the automatic Retry
hooks (restart, provider limit, budget resume) keep their behavior.
- `heldTaskRetryRefusals` uses the same attempt filter.
- New test
`server/src/__tests__/task-retry-banner-execution-owner.test.ts`: one
state table. Each row asserts the list and detail projection, and when
Retry is shown, presses it through `requestTaskRetry`.

### State table (tested as one table)

| Row | Runs and lock | Banner | Observed run | Retry press |
| --- | --- | --- | --- | --- |
| 1 | Continuation scheduled; follow-up running and owns the lock |
working, no Retry | follow-up | n/a |
| 2 | Continuation cancelled unstarted (`issue_execution_lock_changed`);
follow-up running and owns the lock (t032) | working, no Retry |
follow-up | n/a |
| 3 | Same as row 2, lock pointer cleared mid-transfer | working, no
Retry | follow-up | n/a |
| 4 | Scheduled continuation overdue past the 2-minute dispatch grace;
follow-up running and owns the lock | working, no Retry | follow-up |
n/a |
| 5 | Newer attempt failed; older queued run owns the lock | working, no
Retry | queued owner | automatic Retry of the failed run is still
accepted |
| 6 | Continuation superseded; follow-up then succeeded | resolved, no
Retry | follow-up | n/a |
| 7 | Continuation superseded; follow-up then failed | failed, Retry |
follow-up | accepted |
| 8 | Continuation superseded; predecessor failed; nothing else runs |
failed, Retry | predecessor | accepted |
| 9 | Continuation started, then lost the lock | failed, Retry |
continuation | accepted |
| 10 | Lock pointer left on a finished failed run | failed, Retry | that
run | accepted |
| 11 | Row 2 with native runs (`nativeIssueId`) | working, no Retry |
native follow-up | Retry naming the owner is accepted |
| 12 | Queued owner past its 15-minute move-forward wait; newer failed
attempt | working, Retry (`move_forward`) | queued owner | accepted |

Invariants that the table checks:

- Retry is never shown while something will advance the task (rows 1 to
6, 11). Row 12 offers only `move_forward` on the owner.
- A Retry press that names the live owner is accepted (rows 1, 2, 3, 5,
11, 12).
- Retry is always shown when nothing will advance the task (rows 7 to
10).
- The shared attempt filter is tested in `heldTaskRetryRefusals`,
`retireSupersededTaskRetry` and the refused chat Retry continuation
(`person_with_superseded_continuation` in
`chat-channels.integration.test.ts`).
- When Retry is shown, pressing it is accepted for the observed run
(rows 7 to 10).

## Verification

- Red: with the service changes removed, rows 1 to 8 fail (8 of 10).
Rows 9 and 10 pass on both sides.
- Green: `cd server && npx vitest run
src/__tests__/task-retry-banner-execution-owner.test.ts` passes 14 of
14.
- Related suites pass: `task-interruption-query.test.ts` (includes the
query-plan bound test), `task-interruption-automatic-path.test.ts`,
`legacy-continuation-authority.test.ts`,
`native-closed-session-retry.integration.test.ts`,
`interrupted-preparation-restore-retry.test.ts`, and the other server
tests that call `taskInterruptionPresentation`, `requestTaskRetry` or
`heldTaskRetryRefusals`.
- `npx tsc --noEmit -p server/tsconfig.json` passes.

## Risks

- Low risk. The change is read-side only. It does not change scheduling,
dispatch, the lock, or the run-dispatch gate.
- A run cancelled before start with `issue_execution_lock_changed` no
longer shows as a failed attempt. If the lock was released and nothing
else ran, the banner shows the previous attempt. A failed previous
attempt still offers Retry (row 8).
- The projection query has one more union branch. It is a primary-key
lookup through `issues.execution_run_id`. The existing query-plan bound
test passes.
- No runner, migration or API contract change.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude
Code with tool use (shell, file edit, 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

Refs #22306 (the earlier fix for a due scheduled retry shown as failed).

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 10:32:41 -06:00
0e38c80323 fix(recovery): do not auto-replace a chat Retry under its consumed exact-request authority (#22414)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Native runs that fail before they do provider work can continue
automatically. The native safe-replacement sweep schedules a system
successor run for them.
> - The successor copies the failed run's context. The sweep removes
consumed wake fields, but it keeps the `chatFailedRunRetry` selector and
`taskRetryRequestId`.
> - That selector is the authority of an exact chat Retry. It is bound
to the failed run's own chat action and to the user's Retry intent. The
successor gets a new system wakeup request, so admission can never
authorize it.
> - Thus every automatic successor of a chat Retry fails at setup with
`FailedChatRunRetryAuthorizationError`. The sweep has already retired
the task's recovery hold at that time, so the task can be left with no
owner of the next step.
> - This pull request stops the sweep from replacing a run that carries
`chatFailedRunRetry`.
> - The benefit is that the task keeps its hold. The user's next Retry
or message continues it through the normal authorized path, and no run
fails for a known reason.

## Linked Issues or Issue Description

**What happened?**
On staging, a user pressed Retry on a failed GitHub chat run. The Retry
run failed before its first claim, after a workspace restore failure.
Its own exact-request authority refused it
(`chat_failed_run_retry_not_authorized`). The pre-claim continuation
path then scheduled a `native_safe_replacement` successor. The successor
kept the copied `chatFailedRunRetry` selector under a new wakeup request
ID, and `authorizeFailedChatRunRetryWake` refused it at setup.

**Expected behavior**
An automatic system successor must not be scheduled under chat Retry
authority that it cannot hold. The task must keep its recovery hold for
the user's next Retry or message.

**Steps to reproduce**
1. Make a native run whose context has `chatFailedRunRetry` (an exact
chat Retry).
2. Fail it before its first coordinator claim, or with a provider
terminal failure, so it qualifies for safe replacement.
3. Run `reconcileSafeNativeReplacements`.
4. See that a successor run is scheduled with the copied selector. At
admission it always fails with `FailedChatRunRetryAuthorizationError`.

Related: #22413 changes the same file for a different defect (the
reviewed chat message batch on fresh-session retries). It does not touch
the eligibility predicate or `chatFailedRunRetry`. The two changes are
independent.

## What Changed

- `nativeReplacementPending()` now excludes a failed run whose context
carries `chatFailedRunRetry`. Because the shared eligibility predicate
has the guard, the pre-claim, historical listener, and provider
terminal-failure replacement paths all get it.
- New regression in `native-preclaim-continuation.test.ts`: this is the
staging shape (a pre-claim failure of an exact chat Retry after its
saved work is recovered). It schedules no successor, the hold stays
effective, and the task stays blocked.
- New paired regression in `native-safe-replacement.test.ts` for the
provider terminal-failure path. An ordinary run still gets exactly one
successor. An exact chat Retry gets none.

## Verification

- Red before the fix: the pre-claim chat Retry case failed with
`expected length 0, got 1`. The terminal-failure chat Retry case also
failed. Its ordinary-run control passed.
- Green after the fix, rebased on `fe0c4aa95d`:
- `npx vitest run src/services/native-preclaim-continuation.test.ts
src/services/native-runtime/native-safe-replacement.test.ts`: 89 passed.
- `npx vitest run
src/services/native-runtime/native-safe-replacement.test.ts
src/services/quarantined-task-retry.test.ts
src/__tests__/execution-control-work.test.ts
src/__tests__/recovery-settled-records-census.test.ts
src/__tests__/durable-chat-wakeup.test.ts`: 206 passed.
  - `pnpm --filter @paperclipai/server typecheck`: passed.
- Second-order check: `nativeInterruptionHold()` uses
`not(nativeReplacementPending())`. Thus an excluded run can now reach
the existing fresh-continuation fallback, the same as other pre-claim
runs that do not qualify. That fallback records a continuation decision
and lets normal admission build a fresh context. It does not copy the
predecessor's selector.
- `pnpm verify` selects 2,950 of 3,817 files for this widely imported
module. I ran the focused suites above and rely on required CI for the
broad coverage.

## Risks

- Low risk. The change only removes candidates from automatic
replacement. Before this change, a removed candidate always produced a
successor that failed at setup.
- Behavior shift: after a chat Retry run fails, the user (or a new chat
message) continues the task. A system successor that cannot be
authorized does not start. Ordinary chat-message runs and non-chat runs
are not changed.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use and code
execution in an agent harness.

## 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: paperclipbugbot <356415228+paperclipbugbot@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 07:53:08 -08:00
875738a8d4 fix(tool-access): keep provider-side OAuth registration failures out of Sentry (#22416)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - People connect remote MCP apps through OAuth. Paperclip registers
its own OAuth client with the provider through dynamic client
registration (RFC 7591).
> - When the provider's registration endpoint answers with an error,
Paperclip returns a 502 to the person. The error handler also sends
every 5xx `HttpError` to Sentry.
> - A provider that refuses or fails registration (401, 403, 404, 429 or
5xx) is a provider-side failure. It is not a Paperclip server fault, so
it adds noise to Sentry.
> - MCP discovery already marks the same provider statuses as expected
remote failures, and the error handler does not report them.
> - This pull request applies the same marking to the registration
response. It also adds the provider status and the allowlisted error
label to registration failures that Paperclip still reports.
> - The benefit is that Sentry shows only registration failures that can
be Paperclip faults, and each one tells which status the provider sent.

## Linked Issues or Issue Description

**What happened?**
A hosted server reported `Error: OAuth dynamic client registration
failed` three times in two minutes. The stack is `startOAuth` ->
`registerOAuthClient` -> `requestOAuthClientRegistration`. The message
is the generic fallback, so the provider sent no recognized RFC 7591
`error` code. The event did not include the provider's HTTP status.
Thus, the event did not show if the provider refused the request or if
Paperclip sent bad metadata.

**Expected behavior**
The person gets the same 502 and code
`oauth_dynamic_client_registration_failed`. Sentry does not get a crash
report when the provider refuses or fails the request on its side (401,
403, 404, 429, 5xx). Sentry continues to get a report for other
statuses, such as a 400 that rejects Paperclip's metadata. That report
includes the status, so the cause is visible.

**Steps to reproduce**
1. Point an OAuth connection at an authorization server whose
registration endpoint returns 403 (closed or token-gated registration),
404, 429 or 503.
2. Start the OAuth connection.
3. See the 502 response and one Sentry crash report.

**Paperclip version or commit**
`master` at fe0c4aa95d.

No related open PR covers this reporting path. #20433 changes which
client method Paperclip accepts after a successful registration. It does
not change failure reporting.

## What Changed

- `server/src/services/tool-access/oauth/client.ts`: A non-OK
registration response now goes through `markMcpHttpResponseFailure`.
This is the same classifier that MCP discovery uses. 401, 403, 404, 429
and 5xx become expected remote failures, so `errorHandler` does not
report them. The HTTP response does not change.
-
`server/src/services/tool-access/oauth/provider-failure-diagnostics.ts`
(new): A server-only `WeakMap` record keeps the operation, the HTTP
status and the already-normalized provider error label. It does not keep
the provider URL, body, description or headers.
- `server/src/sentry.ts`: `captureException` adds `oauth_operation`,
`oauth_provider_status` and the optional `oauth_provider_error` tags and
an `oauth_provider_failure` context for an error that has this record.
Grouping does not change (`{{ default }}`).
- Tests: `oauth-dcr-failure-reporting.test.ts` sends each status through
the real `errorHandler`. `sentry-oauth-provider-failure.test.ts` checks
the exact Sentry tags and context.

## Verification

- `cd server && npx vitest run
src/__tests__/oauth-dcr-failure-reporting.test.ts
src/__tests__/sentry-oauth-provider-failure.test.ts
src/__tests__/sentry.test.ts src/__tests__/remote-http-rebinding.test.ts
src/__tests__/openrouter-catalog-error-handler.test.ts`: all pass.
- `cd server && npx vitest run
src/__tests__/generic-mcp-connection.test.ts
src/__tests__/tool-access-client-credentials.test.ts
src/__tests__/error-handler.test.ts`: 154 tests pass. This includes the
existing hostile-provider DCR redaction test.
- Red check: without the `client.ts` change, the six provider-side
status cases and the 400 diagnostics case fail. Without the `sentry.ts`
change, the Sentry tag test fails.
- Local `tsc` was stopped by the sandbox (SIGKILL), also for a scoped
config. CI typecheck must cover this.

## Risks

- Low risk. The HTTP status, body and code for the person do not change.
- Sentry stops reporting registration failures with 401, 403, 404, 429
and 5xx status. A provider outage during registration is then visible
only in the response and logs. This is the same policy that MCP
discovery already uses.
- The new tags contain only an integer status and an allowlisted label.
No provider text goes to Sentry.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used as a coding agent
with tool use (shell, file edit and 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
- [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: paperclipbugbot <356415228+paperclipbugbot@users.noreply.github.com>
2026-11-20 07:52:23 -08:00
54972096ba fix(native): wait out a provider rate limit that refuses the session start (#22386)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The native runtime starts each agent run in a provider session on a
remote sandbox
> - A provider can refuse `session.open` because the account reached its
rate limit or quota
> - After one same-run retry, a repeat of that refusal ended the run as
`native_provider_startup_rejected`
> - That code blocks the task for a board Retry and sends the failure to
Sentry, but the limit passes by itself
> - This pull request records that refusal as a provider usage-limit
hold, which already exists for limits on a turn
> - The benefit is that Paperclip retries the task at the reset by
itself, and Sentry gets no error for an expected wait

## Linked Issues or Issue Description

Refs #20808, #19246, #18854. No public issue exists for this case.

**What happened?**
On staging, an account-wide Anthropic 429 refused `session.open` for all
runs of one agent. Each run waited the one-hour default cooldown and
retried on the same run. The retry met the same 429. The repeat check
then ended each run as `native_provider_startup_rejected`. Sentry
recorded 25 events in two bursts. Each task became blocked and waited
for a person to click Retry.

**What did you expect to happen?**
A rate limit or quota at session start must wait for the reset, the same
as a limit that the provider reports on a turn. The usage-limit hold
retries the task at the reset by itself and does not report to Sentry.

**Steps to reproduce**
1. Use a remote native runner with an ACPX provider whose account is
rate limited.
2. Start a task run. The provider refuses `session.open` with
`classification=provider_rate_limit` and a typed `providerFailure`
(`phase: "startup"`, `category: "rate_limit"`).
3. Let the same-run retry run after the cooldown while the limit
continues.
4. See that the run fails as `native_provider_startup_rejected`, the
task becomes blocked for a board Retry, and Sentry gets a `run_failure`
event.

## What Changed

- `nativeRemoteStartupRejectionCode` returns
`native_provider_usage_limit` instead of
`native_provider_startup_rejected` when the typed startup failure is
`rate_limit` or `quota_exhausted`. The first refusal with a proven
runner exit still retries on the same run after the cooldown, as before.
Other startup failures do not change.
- `readNativeUsageLimitReset` also accepts a startup refusal when the
run has no turn event. It reads the current failure (from the executor)
or the run's saved `providerFailure`, and it requires `phase:
"startup"`. A run with a turn event keeps the old rules.
- `planProviderLimitResume` accepts the current startup failure, so the
hold gets its reset before the run row records the failure.
- The hold saves the startup refusal that created it
(`providerLimitStartup`, with its observation time). When the hold
resumes, it reads that refusal first. A same-run retry keeps the run
row's first saved failure, so the run row can name an older reset.
- Tests: a classifier unit test, an integration test for the hold and
its automatic Retry, an executor-level test for two startup attempts
with different resets, and a Sentry-report test for the startup shape.

## Verification

- `npx vitest run
src/services/native-runtime/native-session-executor.test.ts -t
"session.open the provider itself rejected"`: 9 tests pass. The new test
fails on `master` with `Received: "native_provider_startup_rejected"`.
- `npx vitest run
src/services/native-runtime/native-provider-capacity.integration.test.ts
src/services/__tests__/run-failure-report-native-usage-limit.test.ts`:
26 tests pass. The new integration test fails on `master` (the plan is
not automatic without a turn event).
- `npx vitest run` on `native-startup-rejected-retry`,
`native-provider-capacity`, `native-startup-retry` and
`native-provider-limit-cooldown` (integration), and
`run-failure-report-native-usage-limit`: 76 tests pass. The new
two-attempt test fails on the first head (`c3ee40f166`) with `reason:
"reset_unknown"`.
- The full `native-session-executor.test.ts`,
`native-provider-limit-cooldown.integration.test.ts` and
`run-failure-report*.test.ts` files: 1865 tests pass and 1 fails. The
failure (`compares export process compatibility without changing
conversation identity (changed: false)`) also fails on an unchanged
`master` in the same sandbox.
- I could not run the full server typecheck locally, because the sandbox
has an 8 GiB memory limit and `tsc` stopped with an out-of-memory error.
CI runs the typecheck.

## Risks

- Low risk. The change applies only to a remote startup refusal with a
typed `rate_limit` or `quota_exhausted` category that would otherwise
end the run.
- The task still shows as blocked during the hold, as for a limit on a
turn. The hold now retries by itself at the reset, at most three times
in a row without a successful run.
- A quota without a reported reset gives the same "restore usage
capacity" action as before, so a person still decides.

> 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`) 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
- [ ] 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: paperclipbugbot <356415228+paperclipbugbot@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 07:22:34 -08:00