Commit Graph
4606 Commits
Author SHA1 Message Date
DottaandClaude Opus 5.5 3cd1370141 fix(github): re-read parked response requests after the settle decision changes (#22710)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Review agents answer GitHub pull requests, and a background sweep
settles each request's status comment once its run finishes
> - The sweep parks a request it cannot progress yet with a wait key,
and a broad rebuild skips it until that key changes
> - #22672 changed how requests settle, but requests parked by the older
code kept the same key after the deploy
> - So the new code never read them: 11 inline "Working on this…"
comments stayed open on staging after #22672 deployed
> - This pull request puts a decision version at the start of the wait
key
> - The benefit is that a deploy which changes the settle decision
re-reads every parked request once, so old stuck comments settle

## Linked Issues or Issue Description

Refs #22672

**Describe the bug**
After #22672 deployed to staging, 5 of 16 stuck inline "Working on
this…" review comments settled, but 11 did not. Their tasks had no new
activity, so their wait keys did not change, and the sweep kept skipping
them.

**Steps to reproduce**
1. A request is parked by the terminal response sweep with a wait key
from older code.
2. Deploy code that changes when such a request settles.
3. Nothing on the task changes, so the key stays the same and the
request is never read again.

**Expected behavior**
A deploy that changes the settle decision re-reads every parked request
once.

## What Changed

- `GITHUB_TERMINAL_RESPONSE_DECISION_VERSION` ("v2") now starts the
terminal sweep's wait key. Keys written before this change never match,
so each parked request is read once by the current decision.
- New test: requests parked with the old key, whose own run finished
before a newer run, are all settled after the sweep starts.

## Verification

- `reads requests parked by an older decision once after a deploy`: red
without the version (0 of 120 acknowledged), green with it (120 of 120).
- `server/src/services/chat-channels/github/` tests: 65 passed.
- After deploy: the 11 open "Working on this…" comments on
staging-reviewed PRs should settle within a sweep pass.

## Risks

- One extra read of every parked request right after deploy (one batched
page read per 100 rows, then they park again under the new key). Low
risk.

## Model Used

- 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
- [ ] 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 20:35:17 -06:00
DottaandClaude Opus 5.5 d1339f1fe4 fix(tools): show agents the stable code of a connected tool's own error (#22723)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Agents call connected tools (plugin connectors and remote MCP
servers) through the tool gateway, and the runner reports a failed call
back to the model
> - The runner keeps only a leading stable error code from a failed tool
result and drops free text and 5xx errors, so internal diagnostics never
reach the model
> - The gateway raised every error a connected tool reported about
itself as a 502 with the code buried in free text, and stringified an
MCP error's content array as "[object Object]"
> - So an agent saw only "Paperclip semantic operation failed" for a
rate limit, a concurrency refusal or a validation error, and retried
blindly
> - This pull request re-raises a tool's own error as a 4xx whose
message starts with the tool's stable code
> - The benefit is that agents see why a tool refused (for example
`read_concurrency_limit` or `validation_error`) and can wait or fix
their input

## Linked Issues or Issue Description

**What happened?**
An agent refreshing a tracker ran reads in parallel. The Customer
success connector refused all but two at a time with
`read_concurrency_limit`, and Notion refused some queries with
validation errors. The agent saw "Paperclip semantic operation failed"
for every one. Cloud recorded 299 concurrency refusals against 10
completed reads before the run gave up.

**Expected behavior**
The agent sees the tool's stable error code, for example `Paperclip
semantic operation failed: read_concurrency_limit`.

**Steps to reproduce**
1. Have an assigned connected tool fail with a tool-reported error (the
gateway raises `ToolGatewayHttpError(502, "... (code:
read_concurrency_limit, retryable)", "tool_error")`).
2. Call it through the runner's assigned tools.
3. The model receives only the generic failure text.

## What Changed

- `server/src/services/native-runtime/assigned-mcp-tools.ts`: a
`tool_error` from the gateway, or an `isError` result, is re-raised as a
422 `tool_error` whose message starts with the tool's stable code. The
code comes from a plugin's `(code: ...)`, a JSON `"code"` field, or a
leading `code:` prefix, with `assigned_tool_error` as the fallback. The
message carries no provider free text.
- `server/src/services/tool-gateway.ts`: tool error messages use the
text of MCP content items instead of `String(array)`.
- Tests for each code source and the fallback; the old tests that
expected the raw 502 object now cover approval and revocation only.

## Verification

- `npx vitest run
src/services/native-runtime/assigned-mcp-tools.test.ts`: 63 passed.
- The runner's ACPX feedback already keeps a leading `code:` prefix from
a failed tool result's text (existing Rust tests), and the Codex driver
passes a thrown error's message as that text.

## Risks

- Low. Only errors that a connected tool reported about itself change.
Approval, revocation and gateway failures are unchanged. The reason code
stays `tool_error`.

## 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 20:34:27 -06:00
calvindomenicoandPaperclip 92e3ad1de9 Fix plugin SDK issues.list double-applying offset/limit (#16327)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Plugins get a scoped host SDK (`ctx.issues.list`, etc.) so they can
read company data without full server access
> - The `issues.list` handler already asks the issue service to paginate
at the SQL level, but then re-slices the already-paginated result a
second time with the same offset/limit
> - That means any page past the first (`offset >= limit`) always
returns `[]`, silently — a plugin paginating a large company's issues
loses every row past page 0
> - This pull request removes the redundant second windowing step so
`issues.list` paginates correctly on every page
> - The benefit is that plugins (e.g. a Home Assistant integration
scanning >200 issues) stop silently losing data past page 1

## Linked Issues or Issue Description

Fixes #16290.

Related prior art: #14654 attempted nearly the same fix on 2026-09-30
but was withdrawn by its own author minutes later as an accidental
branch push, never reviewed. #14673 (nagoodman) is an active,
independently-equivalent fix open since 2026-09-30 — see the
maintainer-review coordination note below.

## What Changed

- Removed the redundant `applyWindow` re-slice in the plugin-SDK
`issues.list` handler (`server/src/services/plugin-host-services.ts`);
the normalized `limit`/`offset` now pass straight into the
`issues.list(companyId, …)` service call, which already paginates at the
SQL level.
- Added an explicit `limit === 0` short-circuit to `[]`: the service's
own clamp is `Math.max(1, floor(limit))`, so passing `0` straight
through would otherwise incorrectly yield 1 row instead of 0.
- **Follow-up fix (2026-10-16, per reviewer feedback from
@BichengWang):** the `limit === 0` short-circuit originally returned
before `issues.list` ran at all, which skipped that service's filter
validation (e.g. a malformed `assigneeAgentId` silently returned `[]`
instead of the expected 422). Fixed by always running the query (floored
to `limit: 1` when the caller asked for `0`) and discarding the rows
only after it succeeds, so validation errors still surface. Added a
regression test for the malformed zero-limit case.
- Confirmed the no-limit case is unaffected: the query path skips
`.limit()` entirely when `limit === undefined`, matching the prior "no
limit → return all from offset" behavior.
- Audited every other `applyWindow` call site in the same file
(`companies.list`, `projects.list`, `agents.list`, `goals.list`): none
forward `params` into their underlying service call, so `applyWindow` is
their only windowing step — no double-apply there. Only `issues.list`
had the bug.

## Maintainer review coordination

@BichengWang flagged (2026-10-16) that #14673 is an active,
independently-equivalent fix for the same bug that already preserves the
zero-limit validation path this PR initially missed. Both PRs now cover
the same ground; whichever lands first should supersede the other. No
preference from us — happy to close this one if a maintainer prefers
#14673.

## Verification

- New regression test in
`server/src/__tests__/plugin-orchestration-apis.test.ts`: seeds 5 issues
and asserts 3 full pages — including page 2 (`offset=4`) — return their
expected slices instead of `[]`, plus `limit=0` and past-the-end cases,
plus (new) a malformed-filter-at-zero-limit case that must still reject
with 422.
- Run locally with `pnpm exec vitest run --project @paperclipai/server
server/src/__tests__/plugin-orchestration-apis.test.ts`.

### Local verification
- Commit: `9d776d12a` (rebased on current `origin/master`)
- Negative control: reverted just the service-file fix, kept the new
test — confirms it fails (`[]` returned instead of rejecting) without
the fix, passes with it.
- tier1/tier2 gate: in progress on this commit as of 2026-10-16T16:xx
UTC; will update once it reports pass/fail.
- Previous head `6a0279174`: tier1+tier2 both GATE PASSED, live GitHub
56/56 checks green, Greptile 5/5.
- Not run locally: docker-context, e2e (no Docker/Chrome on host)

## Risks

- Behavior-only change to one plugin-SDK list handler; no schema or
migration changes. Low risk.
- Revert is a clean single-commit revert of this PR.

## Model Used

Claude (Claude Agent SDK), Sonnet 5 (`claude-sonnet-5`), agentic tool
use with repository read/write 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 (#14654 withdrawn, #14673 active/overlapping)
- [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 (none
needed — internal plugin-SDK behavior, no user-facing docs reference
this handler)
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green (re-gating after the follow-up
fix; previous head was 56/56)
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
(re-review pending on the new commit)
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-23 20:26:57 -06:00
Oke Iyanuoluwa Enoch d2bdad4ae5 fix(plugins): report WORKER_UNAVAILABLE when no worker is registered for a bridge call (#19286)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Plugin UIs call their workers through the bridge routes
`bridge/data` and `bridge/action`
> - `mapRpcErrorToBridgeError` turns a worker call failure into a bridge
error code for the client
> - For a plugin with no registered worker, the worker manager rejects
with `PluginWorkerUnavailableError` and the message `No worker
registered for plugin "<id>"`
> - The mapper matched only the substrings `not running` and `not
registered`, so this case became `UNKNOWN`
> - This pull request makes the mapper recognize the typed error that
the worker manager already throws
> - The benefit is that clients get `WORKER_UNAVAILABLE` for every "no
live worker" case, and the result does not depend on message wording

## Linked Issues or Issue Description

Fixes #19092

Refs #19007 (the parent issue that #19092 was split out of)

I searched open and closed PRs for `19092`, `mapRpcErrorToBridgeError`
and `WORKER_UNAVAILABLE`. I found no related PR.

## What Changed

- `mapRpcErrorToBridgeError` in `server/src/routes/plugins.ts` returns
`WORKER_UNAVAILABLE` when `findPluginWorkerUnavailableError(err)` finds
a `PluginWorkerUnavailableError`, including one wrapped in a `cause`
chain. The existing substring checks stay as a fallback.
- Added a route test in
`server/src/__tests__/plugin-routes-authz.test.ts`. The worker manager
mock rejects with the same error and message that
`plugin-worker-manager.ts` produces when no worker is registered. The
test expects a 502 with `code: "WORKER_UNAVAILABLE"`.

## Verification

- `pnpm exec vitest run server/src/__tests__/plugin-routes-authz.test.ts
--testTimeout=60000`: 38 of 39 tests pass, including the new test.
- The one failure is `lists bundled monorepo plugin packages`. It fails
the same way on unmodified `master` on my Windows machine, because the
postinstall step could not create the plugin SDK symlinks there. It is
not related to this change.
- Without the fix, the new test receives `code: "UNKNOWN"`.

## Risks

- Low risk. Only errors that the worker manager already classifies as
worker-unavailable change their bridge code, from `UNKNOWN` to
`WORKER_UNAVAILABLE`. The HTTP status stays 502. Nothing is dispatched
to a worker in this case, before or after the change.

## Model Used

- Claude Opus 5.5 (Anthropic, model ID `claude-opus-5-5`), used through
Claude Code with tool use (shell, file editing). It assisted with code
reading, the change, tests and this description. I reviewed the change.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
2026-11-23 20:24:29 -06:00
DottaandClaude Opus 5.5 dd6db295a3 fix(workspaces): move a managed folder online when its records name a repository that is not there (#22722)
## 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
> - The online pass moves a managed folder with no repository as an
ordinary folder: it copies the files under the folder's source locks
> - On staging, two stacks keep 33 workspaces blocked with
`workspaces:source_scope_not_git_source`
> - Those records carry a repository URL or branch, so the ordinary path
skips them, but their folder holds no repository, so the Git path
refuses them too
> - The offline move copies the same folder as files
> - This pull request lets the ordinary path prove a managed folder
whose records name a repository that is not there
> - The benefit is that these workspaces move online exactly as they
move offline, with the same fence as every other ordinary folder

## Linked Issues or Issue Description

Refs #22644

**What happened?**
After repeated online passes on staging (Core 4434d12e), one stack
reports `source_scope_not_git_source` x30 (29 of them also
`overlapping_workspace_requires_maintenance`), and another reports it
x3.

**Expected behavior**
The online move accepts what the offline move accepts for the same data,
with a fence that is checked again under lock at publication. Offline
copies a folder with no repository as files, whatever its records say
about Git.

**Steps to reproduce**
1. Create a managed project folder with three task records that point at
it.
2. Set `repoUrl` and `branchName` on the records. Do not create a
repository in the folder.
3. Run `inventoryRemoteWorkspaceMigration` online. It reports
`online_workspace_source_scope_unproven` with `not_git_source`.

**Why it is safe**
- The source locks come from the folder's physical path, not from the
record's Git fields. Writers to the folder take the same project or task
lock.
- The ordinary capture runs with `requireNoGit`. If a `.git` entry
appears during the capture, the capture fails and nothing is published.
- The ordinary proof still checks every member: provider, task binding,
strategy, status, restoration state, foreign aliases. The publication
checks the scope again under lock.
- The published source keeps the record's repository URL and base ref,
the same as offline.

## What Changed

- `explainOnlineOrdinarySource` no longer skips a `local_fs` record
because it has `repoUrl` or `branchName`. It still skips such a record
when the folder has a `.git` entry, so real checkouts keep the Git path
and its cost does not change.
- `ordinaryMemberUnproven` accepts a `local_fs` member with `repoUrl` or
`branchName`. Non-`local_fs` members are still `ordinary_member_git`.
- A member with an unfinished Git cache expiration is now
`member_git_expiration_pending` on the ordinary path too. The Git path
already refuses it.

## Verification

- Rebased onto `origin/master` after #22718 and #22721. Both behaviours
are kept: members are compared by physical path (#22721), and a
`local_fs` member may carry Git fields when the folder has no repository
(this PR).
- Red on `origin/master` (b908678ea3): the never-cloned folder reports
`not_git_source` and is not eligible. The expiration guard test also
reports `not_git_source`.
- Green with the fix. The never-cloned folder is eligible, its source is
`ordinary` with all three records, and the migration publishes. The
published source is `{ kind: "git", repoUrl, ref: "main" }`. The
restored archive holds the saved file, and the local folder is
unchanged. The member with an unfinished expiration stays blocked with
no workspace operation.
- `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/remote-workspace-migration-concurrency.test.ts
src/services/online-durable-data-migration.test.ts
src/services/remote-workspace-snapshot-archive.test.ts`: 6 files, 532
tests passed after the rebase (embedded PostgreSQL).
- `cd server && pnpm typecheck`: passed.

## Risks

- Medium. More folders become movable online. The fence and the capture
are the same ones that ordinary folders already use.
- A folder with a `.git` entry that is not a repository still goes to
the Git path and stays blocked.
- A `local_fs` record at an unmanaged folder with no repository now
reports `ordinary_root_unmanaged` instead of `git_checkout_missing`
(#22718), because the unmanaged root is the reason it stays blocked. A
`git_worktree` record in the same state still reports
`git_checkout_missing`. The test covers both.

## 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 20:06:05 -06:00
DottaandClaude Opus 5.5 f144bdee34 fix(workspaces): name the overlap and missing-Git cases that keep a workspace from moving online (#22718)
## 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 stack moves only when the online pass reports no blockers, so each
blocker must name its exact cause
> - On staging, one stack reports
`workspaces:overlapping_workspace_requires_maintenance` x6 with no
detail code, and two stacks report
`workspaces:source_scope_not_git_source` x33
> - The overlap code has no detail when the workspace does not need a
proven source scope, and `not_git_source` joins two different cases
> - This pull request names how the paths overlap, why the source scope
is unproven, and which of the two Git cases applies
> - The benefit is that the next pass on each blocked stack shows which
rule applies, so the matching fix can follow

## Linked Issues or Issue Description

Refs #22644, #22696

**What happened?**
After repeated online passes on staging (Core 4434d12e), one stack
reports `overlapping_workspace_requires_maintenance` x6 with no
`source_scope_*` code. Two other stacks report
`source_scope_not_git_source` x30 and x3.

**Expected behavior**
Each blocked workspace names the exact cause. An overlap names how the
paths overlap and why the source scope is unproven. A missing Git source
says if the directory has a `.git` entry that is not a repository, or no
repository at all.

**Steps to reproduce**
1. Create a workspace at an unmanaged path, and a second task workspace
in a subfolder of it.
2. Run `inventoryRemoteWorkspaceMigration` online for either workspace.
3. The result has only `overlapping_workspace_requires_maintenance`. It
has no detail and no `sourceScopeUnproven`.

**Why no detail was emitted**
The inventory reported `sourceScopeUnproven` only when the workspace
needs a proven source scope (`requiresOnlineWorkspaceSource`). A non-Git
directory outside the managed roots does not need one. The overlap check
then blocks it, and nothing names the cause.

## What Changed

- `workspaceMigrationLayoutBlockers` returns a state with each overlap:
`same_directory`, `nested_workspace`, `enclosing_workspace` or
`imported_child_unrecorded`. The inventory adds it as
`overlapping_workspace_requires_maintenance:<state>` in `details`. The
online pass already reports details as `workspaces:<reason>:<state>`.
- The inventory now reports `sourceScopeUnproven` also when the
workspace is blocked by an overlap. Example: `ordinary_root_unmanaged`.
- `not_git_source` is now one of two codes:
- `git_marker_not_repository`: the directory has a `.git` entry that is
not a readable repository.
- `git_checkout_missing`: the record says Git (repository URL, branch or
worktree strategy), but the directory has no repository.
- The `reasons` list does not change. No rule changes: every case that
was blocked stays blocked.

## Verification

- Red on `origin/master` (b908678ea3): the four new or changed
assertions fail. The overlap result has no `details` and no
`sourceScopeUnproven`. The Git fragment and the declared Git record
report `not_git_source`.
- Green with the fix: `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-durable-data-migration.test.ts
src/services/remote-workspace-migration-concurrency.test.ts`: 5 files,
392 tests passed (embedded PostgreSQL).
- `cd server && pnpm typecheck`: passed.

## Risks

- Low risk. Only names change. The set of blocked workspaces and the
`reasons` list do not change.
- The online pass reports one more deferral key per overlapping
workspace
(`workspaces:overlapping_workspace_requires_maintenance:<state>`). This
is the same form that #22696 uses.

## 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 19:42:00 -06:00
HisarWebandClaude Opus 5.5 2b8ae371d3 perf(budgets): read only the needed run columns under the run lock (#20130)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Before a run is dispatched, `reserveRunBudget` reserves budget under
the company accounting lock, the same lock that charges and policy
changes use
> - Inside that transaction it read the full `heartbeat_runs` row `FOR
UPDATE`, including `context_snapshot` and the log columns
> - Admission and native Stop recovery read only a few of those columns
> - On one instance 5 to 8 waiters queued on the company lock while this
query took up to 1.3 s; `context_snapshot` was 28 kB on average and up
to 2.8 MB
> - This pull request selects only the columns that the reservation path
reads, with the same row lock
> - The benefit is that the large columns are not detoasted or sent
while the company lock is held, so the lock is held for a shorter time

## Linked Issues or Issue Description

No issue exists. Related, but a different part of budget admission:
#17966 (skip the accounting lock for admission that cannot block) and
#18928 (queue accounting transactions).

**What happened?**
Run dispatch waited on the company accounting lock. The lock holder was
the `SELECT * ... FOR UPDATE` on `heartbeat_runs` in `reserveRunBudget`,
which read large `context_snapshot` values.

**What did you expect?**
The reservation reads only the columns it needs while it holds the
company lock.

**Steps to reproduce**
1. Create a company with a budget policy and runs with large context
snapshots.
2. Start many runs at the same time.
3. Look at `pg_stat_activity` or the query log. The `heartbeat_runs` row
read in `reserveRunBudget` returns all columns while other transactions
wait on the company lock.

**Paperclip version**
`master` at the time of this PR.

## What Changed

- `server/src/services/budget-reservations.ts`: a new
`RESERVATION_RUN_COLUMNS` with `id`, `companyId`, `agentId`,
`nativeIssueId`, `status`, `costAccountedAt`, `resultJson`,
`runtimeMode` and `usageJson`. `reserveRunBudget` selects these columns
`FOR UPDATE` instead of the full row. These are the fields that
admission and `readClaimedNativeStopRecovery` read.
- `server/src/__tests__/budget-enforcement-scoping.test.ts`: a new test
checks that the locked query selects only these columns.

## Verification

- `cd server && npx vitest run
src/__tests__/budget-enforcement-scoping.test.ts`: passes, including the
new test.
- `pnpm --filter @paperclipai/server typecheck`: passes. The type of
`run` is now the narrow select, so a later use of a column that is not
selected fails the typecheck.

## Risks

- Low risk. The row lock, the filter and the logic do not change. If a
future change in this function needs another column, it has to be added
to `RESERVATION_RUN_COLUMNS`; the typecheck shows this.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use
(shell, git, 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 19:41:25 -06:00
DottaandClaude Opus 5.5 724693f635 fix(workspaces): move a managed folder online when another record names it by a different path (#22721)
## 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
> - An ordinary managed folder can move online when every task record
that points at it is fenced by the folder's source locks
> - On staging, one stack keeps 26 workspaces blocked with
`workspaces:source_scope_ordinary_member_locator_mismatch`
> - The check compares the text of each record's path with the folder's
physical path, so a record that names the same folder through a symlink
or with a trailing slash is refused
> - The source locks already come from the physical path, so writers
through either spelling take the same lock
> - This pull request compares physical paths, and names a record that
encloses the folder separately
> - The benefit is that these workspaces move online exactly as they
move offline, with the same fence

## Linked Issues or Issue Description

Refs #22644

**What happened?**
After repeated online passes on staging (Core 4434d12e), one stack
reports `source_scope_ordinary_member_locator_mismatch` x26.

**Expected behavior**
A managed folder moves online when every record that points at it is
fenced. The offline move captures the same folder for each record. The
online move must accept the same data, never more.

**Steps to reproduce**
1. Create a managed project folder with three task records that point at
it.
2. Change one record's `cwd` and `providerRef` to a symlink to the
folder, or add a trailing slash.
3. Run `inventoryRemoteWorkspaceMigration` online for another record. It
reports `ordinary_member_locator_mismatch`.

**Why it is safe**
- The online proof already finds members by physical path
(`physicalPath`, which resolves symlinks).
- `workspaceSourceIdentities` takes source lock keys from the canonical
path. A writer that uses the other spelling takes the same project or
task lock.
- Each member's lifecycle lock is still held. The publication still
checks the source scope again under lock, so a retargeted symlink
changes the scope and blocks the move.

## What Changed

- `ordinaryMemberUnproven` compares the physical `cwd` and `providerRef`
of each overlapping record with the folder:
  - inside the folder: `ordinary_member_nested` (unchanged);
- a parent of the folder: new code `ordinary_member_encloses_root`
(still blocked);
- the same folder by any spelling: accepted, with all other member
checks unchanged;
- a record without `cwd`, or with a locator that points somewhere else:
`ordinary_member_locator_mismatch` (unchanged).
- Only member records change. The migrating workspace's own path must
still be canonical.

## Verification

- Red on `origin/master` (b908678ea3): the trailing slash and symlink
tests report `ordinary_member_locator_mismatch`. The enclosing test
reports `ordinary_member_locator_mismatch` instead of
`ordinary_member_encloses_root`.
- Green with the fix. Both spellings are eligible and the migration
publishes. The other record stays local and the folder's files stay in
place. An enclosing record and a locator elsewhere stay blocked, with no
workspace operation.
- `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/remote-workspace-migration-concurrency.test.ts`: 4 files,
368 tests passed (embedded PostgreSQL).
- `cd server && pnpm typecheck`: passed.

## Risks

- Low to medium. More ordinary folders become movable online. The fence
does not change: path-derived source locks, each member's lifecycle
lock, and the scope recheck under lock at publication.
- A record that encloses the folder stays blocked. Its own move would
need a scope that covers the larger folder. Offline captures each record
separately.

## 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 19:41:03 -06:00
DottaandClaude Opus 5.5 f0bbd4ada9 fix(workspaces): let one online source scope hold as many locks as its alias bound admits (#22724)
## 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 Git workspace moves online only while one transaction holds the
source lock of every task and project that can write its repository
> - On staging, one stack keeps 46 workspaces blocked with
`workspaces:source_scope_source_keys_exceeded`
> - The proof refuses a scope above 128 lock keys, but the same proof
admits up to 256 alias records, and each record adds a task key
> - The fence must hold every key at the same time, so it cannot page
across passes: a writer that took a released key could change the
repository during the capture
> - This pull request raises the key bound to 512 in one shared
constant, and makes the capture's Git source root bound follow it
> - The benefit is that a repository shared by many tasks moves online
with the same fence as a small one

## Linked Issues or Issue Description

Refs #22644

**What happened?**
After repeated online passes on staging (Core 4434d12e), one stack
reports `source_scope_source_keys_exceeded` x46.

**Expected behavior**
A source scope that the alias bound admits (256 records) can take all of
its source locks. The offline move has no lock bound, because all
writers are stopped.

**Steps to reproduce**
1. Create a managed Git checkout with 133 task records that point at it.
2. Run `inventoryRemoteWorkspaceMigration` online. It reports
`source_keys_exceeded`.

**Is 128 a safety bound or a budget?**
- It cannot be a budget that pages across passes. The keys fence writers
only while one transaction holds all of them. Each pass releases its
locks.
- It bounds the advisory locks that one transaction takes. Each key is
one entry in the PostgreSQL shared lock table. That table holds
`max_locks_per_transaction` (default 64) times `max_connections`
entries, which is 6,400 with the defaults. 512 keys are 8% of that, and
one server runs one workspace migration at a time.
- The capture's Git source root bound (384) was three roots per key at
the old bound, and it would refuse the larger scope. It is now three
roots per key at the new bound.

## What Changed

- New `workspace-source-key-limit.ts` exports
`WORKSPACE_SOURCE_KEY_LIMIT = 512`.
- `withWorkspaceSourceLocks` (new scope and joined scope) and the online
proof (`source_keys_exceeded`) use the constant.
- The capture's Git source root bound is 1536 (three roots per key). The
capture code runs in a worker from its own source text and cannot import
the constant. A test ties the two values together.

## Verification

- Red on `origin/master` (b908678ea3):
  - 512 keys in one scope throw `workspace_source_scope_limit`.
  - A 133-record Git closure reports `source_keys_exceeded`.
- A capture with 1536 owned Git source roots fails with
`online_source_git_requires_shared_fence`.
- Green with the fix:
- 512 keys are held at once (`pg_locks` shows 512 advisory locks), and
513 are refused before a connection is reserved.
- The 133-record closure is eligible, its scope has 133 task keys, the
migration publishes, and the files stay in place.
  - The capture accepts 1536 roots and refuses 1537.
- `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/remote-workspace-migration-concurrency.test.ts
src/services/remote-workspace-snapshot-archive.test.ts
src/services/isolated-remote-workspace-source-lock.test.ts` (embedded
PostgreSQL): 6 files, 493 tests passed.
- `cd server && pnpm typecheck`: passed.

## Risks

- Low to medium. A large scope holds up to 512 advisory locks in one
transaction. This is within the default lock table with a wide margin,
and only one workspace migration runs at a time per server.
- Lock acquisition takes one round trip per key, so a 512-key scope adds
roughly half a second at 1 ms per round trip.
- Scopes above 256 alias records are still refused (`members_exceeded`).

## 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 19:39:56 -06:00
DottaandClaude Opus 5.5 6a642a9316 fix(cloud): name why a native session or controller source stays blocked in the move (#22717)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Hosted stacks move from a volume to volume-free storage, and the
move reports a code for each blocked item
> - Three native codes each cover several unrelated conditions
> - An operator or a fix agent cannot tell from the code which condition
holds, so stuck stacks stay stuck
> - This pull request names the exact condition next to each code,
without changing what either path accepts
> - The benefit is that the next pass says what to fix

## Linked Issues or Issue Description

**What happened?**
A stack reports
`workspaces:native_workspace_migration_identity_unproven`,
`native_controllers:artifact_unproven` and
`native_controllers:archive_source_unsettled` on every pass. Each code
is thrown from a check with up to eleven separate conditions, so the
report cannot say which saved state blocks the move.

**Expected behavior**
Each blocked item names the failing condition, and the online and
offline paths accept the same data as before.

**Steps to reproduce**
1. Save a paperclip_runner session whose resume run has no workspace
sync descriptor, then migrate its workspace.
2. Or archive a failed controller online while its coordinator holds a
lease.
3. Before this change, the reports are only
`native_workspace_migration_identity_unproven` or
`archive_source_unsettled`.

**Paperclip version or commit**
master at b2a12fab49.

## What Changed

- `inspectNativeWorkspaceMigration` throws
`native_workspace_migration_identity_rebound`, `_unsynced`,
`_other_workspace` or `_path_invalid` instead of one code. The online
pass and offline maintenance both see the same named code.
- `assertSettledControllerArchiveSource` throws
`NativeControllerArchiveSourceUnsettled` with a state
(`coordinator_missing`, `coordinator_leased`,
`coordinator_retry_scheduled`, `coordinator_unsettled`,
`coordinator_changed`, `finalization_busy`, `task_active`,
`session_selection_changed`, `run_changed`, `turn_active`,
`resume_source_changed`, `controller_files_changed`,
`controller_fingerprint_missing`). The message stays
`native_controller_archive_source_unsettled`.
- `prestageNativeControllers` keeps the existing outcome and count, and
also reports `archive_source_unsettled:<state>`. For `artifact_unproven`
it also reports `artifact_unproven:<run status>_run`, the same
`code:state` form that workspace details use.
- Previous-release story: no persisted state changes. Only error names
and report details change.

## Verification

- Red: on master the new unit test
(`native-workspace-migration.test.ts`, 4 cases) and the archive and
artifact assertions in `native-controller-migration.integration.test.ts`
fail.
- Green: `npx vitest run
src/services/native-runtime/native-workspace-migration.test.ts
src/services/native-runtime/native-controller-migration.integration.test.ts
src/services/native-runtime/native-harness-filesystem-independence.integration.test.ts
src/services/remote-workspaces.integration.test.ts` (297 passed).
- `pnpm typecheck` in `server` passes.

## Risks

- Low. Acceptance rules do not change. A dashboard that matches the
exact text `native_workspace_migration_identity_unproven` sees the new
names instead.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Claude Code 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
- [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 19:39:13 -06:00
DottaandClaude Opus 5.5 cbf67dba0a fix(cloud): record a selected harness backup whose source is gone instead of blocking the move (#22716)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Hosted stacks move from a volume to volume-free storage, offline in
maintenance or online with no outage
> - A stack moves only when no local native harness backup obligation
remains
> - A selected session can carry a backup stamp whose files are no
longer on the volume
> - Offline and online both refuse that stack forever, because nothing
can copy files that are gone
> - This pull request records "backup source was gone" for that session,
the same way offline and online, after a locked recheck
> - The benefit is that the stack moves, and the gone backup is recorded
instead of silently forgotten

## Linked Issues or Issue Description

**What happened?**
An online durable-data pass reports
`native_harness:selected_source_absent` on every pass for a stack. The
selected session has a v2 backup stamp, but `failover-backups/current`
for that scope is not on disk. The offline maintenance path also fails:
`native_harness_backups_require_migration` stays true because
`migrateNativeHarnessBackups` only visits sources on disk. The stack can
never move.

**Expected behavior**
When the backup files are already gone and the session is settled, both
paths record that the backup source was gone and stop counting it as an
obligation. A session that is still active, or a backup that the
expiration service is rotating, stays blocked with a name.

**Steps to reproduce**
1. Create a selected `paperclip_runner` session whose last run is
settled and whose environment lease has a v2 backup stamp.
2. Remove `<state base>/<scope digest>`.
3. Run `prestageNativeHarnessBackups` or `migrateNativeHarnessBackups`.
4. Before this change, `selected_source_absent` repeats and
`hasLocalNativeHarnessObligations` stays true.

**Paperclip version or commit**
master at b2a12fab49.

## What Changed

- Add `recordNativeHarnessBackupSourceAbsence`. In one transaction it
locks the selected session row, the run's finalization advisory lock,
the last run row and the finalization row. It requires a settled run
(terminal, no controller lease, no live execution control, no
finalization owner, no lease owner or scheduled retry on the
coordinator), no queued or running turn on the task or session, no
current durable backup for the scope, and stamped leases for the scope.
Then it rechecks the disk. If `current` is back, it records nothing. If
a `.retiring-*` backup exists, it returns `selected_source_retiring`. If
any other entry remains (for example `previous` from an interrupted
publish), it returns `selected_source_unsettled`. Only a scope with no
entries besides `.expired-*` trash counts as gone. Otherwise it writes
`nativeHarnessBackupSourceAbsent` on the last run (scope digest to
stamped manifest digests) and logs
`native_harness_backup_source_gone_recorded`.
- A lock timeout during the recheck returns `selected_source_busy` for
this pass instead of failing the harness phase.
- The obligation query excludes a scope only when the selected session's
last run records that exact scope and that exact stamped manifest
digest. A new turn changes the last run, and a new stamp changes the
manifest, so the obligation comes back.
- The online pass (`prestageNativeHarnessBackups`) and the offline pass
(`migrateNativeHarnessBackups`) both call the same recorder for the
obligations they could not copy. The online pass counts
`nativeHarnessBackupSourcesGone` and does not defer it.
- Previous-release story: the new key is additive run state. No resume
path reads it. A session behaves after the move exactly as it does on
the volume today without its backup. A previous release ignores the key
and still reports the obligation.

## Verification

- Red: the new tests fail on master. Online still reports
`selected_source_absent`, offline still has an obligation (`expected
true to be false`), and the retiring case is not named.
- Green: `npx vitest run
src/services/native-runtime/native-harness-online-preservation.integration.test.ts
src/services/native-runtime/native-harness-backup-obligations.integration.test.ts
src/services/online-durable-data-migration.test.ts` (62 passed,
including busy-row and previous-backup cases).
- Neighbors: `ephemeral-server-startup-run-state`,
`ephemeral-server-runtime-skill-startup`,
`native-harness-prestage(-runtime)`,
`native-harness-filesystem-independence`,
`native-harness-backup-storage` (218 passed).
- `pnpm typecheck` in `server` passes.

## Risks

- Medium. A gone backup stops blocking the move. The recorder writes
only after a locked recheck that the run is settled, no turn is active,
and the files are still absent. A backup that is rotating stays blocked.
- The record changes the last run's `runnerProfileJson`.
Filesystem-independence facts include that profile. The recorder writes
only when no valid independence receipt exists, so no existing receipt
changes.
- No schema migration.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Claude Code 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
- [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 19:38:30 -06:00
commitperclip[bot] 451c09bfbe fix: Correct OpenAPI access metadata for board-only agent session routes (#21024)
> [!NOTE]
> Opened by Prospector's automated issue-fix pipeline. A maintainer
reviews and decides; nothing here merges on its own.

## Thinking Path

- Issue #20942 reports a defect in paperclipai/paperclip.
- Root cause, as the fixing agent read it: The three session operations
were missing from BOARD_ONLY_OPERATIONS, so OpenAPI defaulted to
board_or_agent access and included AgentBearerAuth despite the handlers
requiring board access.
- This pull request: Correct OpenAPI access metadata for board-only
agent session routes

## What Changed

- `server/src/routes/openapi.ts`: Classify all three operations as
board-only while preserving existing handler permissions.
- `server/src/__tests__/openapi-routes.test.ts`: Add regression cases
for board security, authorization metadata, and forbidden responses on
each route. All three failed before the fix; all 48 OpenAPI tests and
the typecheck pass afterward.

## Verification

- Reproducing test(s), added in this PR:
`server/src/__tests__/openapi-routes.test.ts`
- They fail on the base commit and pass with the fix, each twice in a
fresh sandbox.
- 3 independent attempts wrote 3 reproductions; this fix passes every
one of them.
- The repository's compile command passes with the fix applied.
- 9 existing test file(s) near the change passed.
- The full test suite passes except for the 17 file(s) that already fail
on the base commit.

## Risks

- Written by an automated pipeline, not a person: review it as you would
an outside contribution.
- Risk tier of the touched paths: 2.
- The scope reviewer found it also changes, beyond the report:
search_api pagination using a cursor generated from the previous
catalog, for any query

## Model Used

- codex:gpt-6.1-sol, opus, sonnet (Anthropic Claude, via Claude Code;
OpenAI, via the Codex CLI), writing and checking the change in an
isolated sandbox.
- opus (Anthropic Claude, via Claude Code), reviewing it independently.

## Linked Issues

Fixes #20942

A search of paperclipai/paperclip's open and closed pull requests found
no other pull request that names #20942.

## Checklist

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

<!-- prospector:issue-fix v1 issue=20942 base=156212cfd58a
report=0d14759e2b96f394 -->

Co-authored-by: commitperclip[bot] <284812584+commitperclip[bot]@users.noreply.github.com>
2026-11-23 19:37:58 -06:00
362e3bb4e3 fix(daytona): accept regional toolbox proxy hosts such as proxy.app-eu.daytona.io (#20075)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The Daytona connection lets agents create sandboxes and run toolbox
actions in them through the tool gateway
> - Before Paperclip forwards a toolbox call with the Daytona key, it
checks the sandbox toolbox proxy host against a list of known Daytona
hosts
> - The check accepts only `proxy.app.daytona.io` and
`proxy-<name>.app.daytona.io`
> - Daytona returns `proxy.app-<region>.daytona.io` for sandboxes in
other regions. For example, EU sandboxes use `proxy.app-eu.daytona.io`
> - So every toolbox call for an EU sandbox fails with
`daytona_proxy_invalid`, and sandbox create, list and delete still work
> - This pull request lets the host check accept one optional region
suffix on `app`, and it keeps the check anchored
> - The benefit is that organizations in non-default Daytona regions can
use the toolbox actions, and the key still goes only to Daytona hosts

## Linked Issues or Issue Description

Fixes #20073

## What Changed

- `server/src/services/daytona.ts`: the toolbox proxy host pattern now
accepts `app` or `app-<region>`. The new pattern is
`^proxy(?:-[a-z0-9-]+)?\.app(?:-[a-z0-9]+)?\.daytona\.io$`.
- `server/src/__tests__/daytona-connection.test.ts`: a new test forwards
a toolbox call to `proxy.app-eu.daytona.io`. The test also makes sure
that these look-alike hosts are rejected before Paperclip forwards the
key: `proxy.app-eu.daytona.io.attacker.example`,
`proxy.app-eu.attacker.io` and `proxy.app-.daytona.io`.
- No documentation change is necessary. `doc/connections/DAYTONA.md`
says that toolbox calls accept only reviewed Daytona cloud proxy
hostnames, and that statement stays correct.

## Verification

- `pnpm exec vitest run server/src/__tests__/daytona-connection.test.ts
server/src/__tests__/daytona-http-boundary.test.ts`: 2 files and 24
tests pass, and this includes the new test. I ran only these two Daytona
files, not the full `pnpm verify` suite.
- With the old pattern back in place, the new test fails with `Daytona
returned an unrecognized toolbox address`. So the test covers the bug.
- Manual check on a self-hosted Paperclip `2026.1106.0` instance with
the same one-line change in `dist/services/daytona.js` and a Daytona
organization in the `eu` region:
- Before the change, `daytona_toolbox_execute_command` returned HTTP 502
`daytona_proxy_invalid`.
- After the change, the same call ran `node -v` in a new EU sandbox and
returned exit code 0. The sandbox was then deleted.
- Pattern check: the new pattern accepts `proxy.app.daytona.io`,
`proxy-us.app.daytona.io` and `proxy.app-eu.daytona.io`. It rejects
`proxy.app-eu.daytona.io.attacker.example`, `proxy.app-eu.attacker.io`,
`proxy.app-.daytona.io`, `proxy.app-eu-.daytona.io` and
`xproxy.app.daytona.io`.

## Risks

- Low risk. The change only widens the host pattern to Daytona-owned
`app-<region>.daytona.io` subdomains. The protocol, port, path,
credential and organization checks do not change. The DNS-pinned egress
guard still applies to every request.
- If Daytona adds a region host in a different shape, the check will
still reject it. That case needs a separate change.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

- Claude Opus 5.5 (Anthropic, model ID `claude-opus-5-5`), run as a
Claude Code agent with tool use (shell, git, GitHub CLI and the Daytona
connection). The model found the cause, wrote the change and the test,
and ran the checks.

## 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: Heron Agents <7084258+aalfath@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 19:35:59 -06:00
30dc924dc9 fix(server): reuse one pino-pretty transport per process (#12987)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The server logs through pino, and outside production it writes
through a `pino.transport` pretty-printer
> - `pino.transport` starts a worker thread and returns no handle the
caller can close
> - `server/src/middleware/logger.ts` calls it at module scope, so each
extra evaluation of that module leaks one worker thread for the life of
the process
> - A server evaluates the module once, but 46 server test files reset
the module registry in `beforeEach`, so those suites evaluate it once
per test
> - This pull request keeps one transport per process, in a cache that a
module-registry reset cannot discard
> - The benefit is that a 50-test server suite stops holding 50 dead
worker threads and about 280 MB of unused memory

## Linked Issues or Issue Description

No existing issue covers this. The problem, in the bug-report shape:

**What happened?**

`server/src/middleware/logger.ts` calls `pino.transport` at module
scope:

```ts
export const logger = isProduction
  ? pino({ ... })
  : pino({ ... }, pino.transport({ target: "pino-pretty", ... }));
```

`pino.transport` starts a thread-stream worker. The module keeps no
handle to
it, so nothing can close it. Each evaluation of the module starts one
more.

A server process evaluates the module once. The tests do not. 46 files
under
`server/src/__tests__` call `vi.resetModules()` in `beforeEach` and then
re-import a module that reaches the logger, usually to rebuild an
express app
against fresh mocks. Those suites evaluate the module once per test, so
each
test adds one worker thread, one MessagePort and one V8 isolate that
live until
the process exits.

**Expected behavior**

One pretty-print transport per process. Re-evaluating the module must
not start
another worker.

**Steps to reproduce**

Add this to any server test file on `master` and run it:

```ts
const ports = () => process.getActiveResourcesInfo().filter((r) => r === "MessagePort").length;

it("leaks a worker per evaluation", async () => {
  await vi.importActual("../middleware/logger.js");
  const before = ports();
  for (let i = 0; i < 10; i += 1) {
    vi.resetModules();
    await vi.importActual("../middleware/logger.js");
  }
  console.log(ports() - before); // 10 on master, 0 with this PR
});
```

The count rises by exactly one per evaluation. The test this PR adds is
that
check, written as an assertion.

**Measurements**

| Transports in one process | Threads | RSS |
| --- | --- | --- |
| 0 (baseline) | 8 | 60 MB |
| 100 | 108 | 276 MB |
| 200 | 208 | 1.38 GB |
| 400 | 407 | 1.68 GB |

A 50-test suite therefore carries roughly 280 MB of dead workers.
`server/vitest.config.ts` pins `maxWorkers: 1`, so these suites run one
at a
time on one runner and each pays the whole cost.

**Paperclip version or commit**

Reproduces on `master` at `856813ba3`.

**Deployment mode**

Test and CI only. A running server evaluates the module once, so it
never had
more than one transport.

**Related pull requests**

- #10865 (closed) — a different bug in the same file. It fixed unbounded
thread-stream *send buffer* growth from prettifying `req`/`res` on the
file
  target. This PR is about the *number of workers*, not the size of one
worker's buffer. That PR was closed because the `targets` array it
patched no
  longer exists on `master`; the call this PR changes does still exist.
- #8323 (open, last updated 2026-06-19) — makes the log format
configurable and
edits the same lines. It looks unmaintained. If it is revived, the cache
here
  moves into whichever branch builds the transport.

## What Changed

- `server/src/middleware/logger.ts`: `pino.transport` now runs behind
`prettyTransport()`, which caches the stream on `globalThis`. The cache
is on
`globalThis` on purpose — a module-scoped variable is discarded by the
very
module-registry reset this guards against. Production behaviour does not
change: a server evaluates the module once, so it built one transport
before
  and builds one now.
- `server/src/__tests__/logger-pretty-transport-reuse.test.ts` is new.
It
asserts that 10 re-evaluations add no MessagePorts, and that every
module
  instance shares one transport object.

## Verification

```bash
pnpm --filter @paperclipai/server exec vitest run src/__tests__/logger-pretty-transport-reuse.test.ts
```

- With the cache: 2 passed.
- With the cache defeated (`??=` changed to `=`), both tests fail:
`AssertionError: expected 10 to be less than or equal to 2`, and the
identity
  check fails on two different transport objects.

Nothing else changes behaviour, so the surrounding suites are the
regression
check:

```bash
pnpm --filter @paperclipai/server exec vitest run \
  src/__tests__/instance-settings-routes.test.ts \
  src/__tests__/http-log-redaction.test.ts \
  src/__tests__/health.test.ts
node --test scripts/__tests__/run-vitest-stable-shard.test.mjs
```

69 passed and 13 passed. `tsc --noEmit` reports no error in either
changed file.

The new suite joins the general-server group and needs no
duration-manifest
entry: the staleness check requires 50% coverage and one new file does
not
cross it.

## Risks

Low.

- A server process evaluates the module once, so the cache never engages
there.
The only behaviour it changes is that several module instances in one
process
now share one pretty-print stream, which is what a single instance
already
  did.
- The `globalThis` key is namespaced (`__paperclipPinoPrettyTransport`)
and read
  only by this module and its test.
- Merge risk sits with #8323, which edits the same lines. See the note
above.

## Model Used

Claude Opus 5 (`claude-opus-5`), via Claude Code, with extended
thinking, tool
use and code execution.

## Checklist

Verified on `8391a138b` (2026-09-08): 31 checks pass, 1 skipped
(`Storybook visual
regression`, not exercised by this diff), merge state `CLEAN`. Greptile
scored 5/5
— "safe to merge" — with no inline comments and no open findings.

- [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
- [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

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

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Co-authored-by: kronik187 <david@teasoftware.io>
2026-11-23 19:30:40 -06:00
DottaandClaude Opus 5.5 fe93b402ac fix(companies): delete a company when a late activity entry commits during the delete (#22719)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - A board user can delete a company. `deleteCompany` removes the
company rows in one transaction.
> - The transaction removes activity entries early. It then removes many
other rows, and it removes the company row last.
> - The transaction holds only a `NO KEY UPDATE` lock on the company
row. This lock does not stop the `KEY SHARE` lock that a foreign key
check takes. A background writer can add an activity entry for the
company while the delete runs.
> - The delete itself starts such a writer. It terminates the company's
agents first. Termination wakes stranded-task recovery, which marks the
agent's open task as blocked and writes an `issue.updated` activity
entry.
> - When that entry commits after the early sweep, the final delete
fails on `activity_log_company_id_companies_id_fk`, and the user gets a
500 error.
> - This pull request locks the company row `FOR UPDATE` just before the
final delete, and then removes the activity entries again.
> - The benefit is that company deletion works when a background writer
adds an activity entry during the delete.

## Linked Issues or Issue Description

Refs #22714

**What happened?**
`DELETE /api/companies/:id` sometimes returned 500. The log showed:
`update or delete on table "companies" violates foreign key constraint
"activity_log_company_id_companies_id_fk" on table "activity_log"`. The
e2e test `tests/e2e/plan-task-fixture.spec.ts` failed this way 8 times
in CI between 2026-11-20 and 2026-11-23 (for example on #22714). Each
time, a rerun passed. The failures started before #22636 and #22669, so
those changes did not cause it.

**What did you expect to happen?**
Company deletion succeeds every time. A background writer for the
company does not make the delete fail.

**Steps to reproduce**
1. Create a company with two agents that use the `process` adapter, and
pause both agents.
2. Create a task that is assigned to one of the agents.
3. Wait 300 to 1000 ms, then delete the company.
4. Repeat. On a local server, 2 of 80 deletes failed with the error
above. The failed company still had an `issue.updated` entry from
`recovery.reconcile_stranded_assigned_issue`.

## What Changed

- `server/src/services/company-deletion.ts`: three named steps lock rows
`FOR UPDATE` immediately before the `DELETE` of the same rows, and then
remove the company's activity entries again:
- `lockRunsAndSweepLateActivity` before the company's runs are deleted,
- `lockAgentsAndSweepLateActivity` before the company's agents are
deleted,
  - `lockCompanyAndSweepLateActivity` before the company row is deleted.
Each lock waits for writers that hold `KEY SHARE` on those rows and
blocks new ones. So a late activity entry that names the company, a run
or an agent cannot make the next `DELETE` fail.
- The existing comment at the start of the transaction now explains both
kinds of lock: why the first lock stays `NO KEY UPDATE`, and why the
later `FOR UPDATE` locks are safe.
- New test
`server/src/__tests__/company-deletion-concurrent-activity.test.ts`
(embedded Postgres). A second connection adds an activity entry while
the delete runs. Case 1: the writer commits after the first sweep. Cases
2 to 4: the writer keeps its transaction open, with an entry that names
the company, a run, or an agent. The test polls `pg_stat_activity` until
the delete waits on a lock, and then releases the writer. There is no
fixed sleep. The release is in a `finally` block.

## Verification

- Red: without the fix, the tests fail with
`activity_log_company_id_companies_id_fk`, the same error as in CI.
- Each lock was removed in turn. Without the run and agent locks, the
run and agent cases fail with `activity_log_run_id_heartbeat_runs_id_fk`
and `activity_log_agent_id_agents_id_fk`. Without the company lock, the
company case fails with `activity_log_company_id_companies_id_fk`. The
other cases still pass each time.
- Green: `cd server && npx vitest run
src/__tests__/company-deletion-concurrent-activity.test.ts` passes (4
tests).
- Related suites pass (413 tests): `git-restore-point-ledger`,
`tool-connection-content-deletion-canary`, `agent-observability`,
`decision-target-work`, `google-managed-connection-removal`,
`task-workspace-binding`, `tool-gateway-service` and the new test.
- `cd server && npx tsc --noEmit -p .` passes.
- Local server reproduction (the steps above, API calls only, first
commit of this PR): before the fix 2 of 80 deletes failed. After the fix
0 of 280 deletes failed, and the server log had no foreign key errors.

## Risks

- Low risk. Each new `FOR UPDATE` lock is taken immediately before a
`DELETE` of the same rows. That `DELETE` already takes a lock that
conflicts with `KEY SHARE`. So the change adds no new wait and no new
deadlock path. The first lock on the company stays `NO KEY UPDATE`, so a
native save that holds a child row is not blocked early.
- A writer that adds an activity entry after the delete commits gets a
foreign key error in its own transaction, as before. Stranded-task
recovery and the Google retry worker check that the company exists or
catch the error. In the reproduction, no worker logged an error.
- Not changed: the `activity_log` foreign keys. Only activity entries
are swept again. A late row in another table that has no cascade can
still conflict with a delete. No CI log showed that case.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, in Claude Code with
tool use (shell, file edit, embedded Postgres tests, local server).

## 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 19:26:22 -06:00
DottaandClaude Opus 5.5 506211b917 fix(run-logs): archive a finalized log that a later attempt extended (#22709)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Hosted stacks move from a volume to volume-free storage, and the
durable-data migration must move every run log first
> - Some finalized run logs grew after their size and SHA-256 were
recorded, because a later attempt of the same run appended to the same
local file
> - Both the online and offline migration refused these logs as
`legacy_length_or_digest_mismatch`, so the stack could never leave its
volume
> - This pull request archives such a log when the recorded proof
matches a prefix of the file, and names the real corruption case
distinctly
> - The benefit is that these stacks can move without deleting or hiding
any bytes, and real corruption still blocks the move

## Linked Issues or Issue Description

**What happened?**
Durable-data migration blocks a run log with
`legacy_length_or_digest_mismatch` when the local file is longer than
the size and SHA-256 recorded at finalize. The run log store never
truncates, so a later attempt that shares the run id appends to the
finalized file. The stack then cannot move to volume-free storage.

**Steps to reproduce**
1. Finalize a run log so that the run records its size and SHA-256.
2. Append more output to the same local file.
3. Run the online or offline durable-data migration.
4. See the log blocked as `legacy_length_or_digest_mismatch`.

**Expected behavior**
When the recorded size and SHA-256 match a prefix of the file, the
migration keeps every current byte, records both proofs, and lets the
stack move. When the recorded proof matches no prefix, the log stays
blocked under a distinct name.

## What Changed

- `server/src/services/run-evidence-migration.ts`: before it claims the
object journal, the migration checks if the recorded size and SHA-256
match a prefix of a longer file. If yes, it archives every current byte
as a read-only `s3_archive` log in the `<run>.archive` journal.
- The publish sets the run's size and SHA-256 to the archived bytes. In
the same transaction it writes a `run.historical_log_archived` activity
entry with the original prefix proof (`recorded`) and the new size and
SHA-256.
- A log whose recorded size and SHA-256 match no prefix (a different
longer file, a shorter file, or a same-size file with different bytes)
stays blocked as `legacy_recorded_log_not_a_prefix`. Nothing is uploaded
or published for a longer file that fails the prefix check.
- The extended log must come from the local file. A longer mirror copy
stays blocked as `mirror_completeness_unproven`, because a matching
prefix does not prove that the mirror holds the whole file.
- While the run still has a pending or leased attempt (a native
finalization with `next_attempt_at`, a lease owner, or a phase other
than `committed` or `terminal_failure`), the log stays blocked as
`legacy_writer_retry_pending`. The publish `WHERE` rechecks this
condition, so a later attempt of the same run never finds a read-only
archive.
- Both archive publications (settled native history and extended logs)
share one helper that publishes and writes the activity entry in one
transaction.
- `legacy_length_or_digest_mismatch` stays for the other cases: a source
that changed while it was read, and a run that recorded only one of size
or SHA-256.
- The online path (`migrateRunEvidencePage`) and the offline path
(`preserveHistoricalFiles`) use the same code, so the rule is the same
for both.
- `doc/run-evidence-storage.md` describes the new rule.

## Verification

- New test `server/src/services/run-evidence-migration-appended.test.ts`
uses embedded PostgreSQL, real local files and an in-memory object
store:
- online and offline: a log with appended output is archived, the run
row has the new size and SHA-256, the archive reads back every byte
after the local file is deleted, and one activity entry holds both
proofs.
- online and offline: a longer file, a shorter file and a same-size file
whose bytes differ stay blocked as `legacy_recorded_log_not_a_prefix`,
keep their local reference, and write no activity.
- online and offline: an extended log whose run has a pending attempt
stays blocked as `legacy_writer_retry_pending`, unchanged and with no
activity.
- a longer mirror copy (local file missing) stays blocked as
`mirror_completeness_unproven`.
- Red: the first 3 tests fail on master
(`legacy_length_or_digest_mismatch`). The pending-attempt and mirror
tests fail on the first commit. Green: all 5 pass with this change.
- `npx vitest run src/services/run-evidence-migration-appended.test.ts
src/services/run-evidence-migration-page.test.ts
src/services/online-durable-data-migration.test.ts`: 40 passed.
- `npx tsc --noEmit -p server`: clean.
- I did not run the opt-in S3 integration suite
(`run-evidence-migration.integration.test.ts`), because it needs an
external S3 endpoint. Its `wrong-digest` case records only a SHA-256, so
it keeps `legacy_length_or_digest_mismatch`.

## Risks

- An archived log is read-only. This is the same as the existing
historical archives. The publish requires a settled run with no writer
lease, so no attempt can still be writing.
- The prefix check reads the recorded prefix (not the whole file) one
more time before the copy. This happens only when the file is longer
than the recorded size. It lets a non-prefix file fail before anything
is uploaded.
- Low risk otherwise: logs whose bytes match their recorded proof follow
the same path as before.

## Model Used

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

## Checklist

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

Related: #22697 (archived workspaces whose files are gone) and #22698
(skills whose remote source is gone) settle the other two cases that
block the same move.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 18:32:00 -06:00
DottaandClaude Opus 5.5 2e229c311f fix(skills): settle unreachable remote skill sources when storage moves (#22698)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Hosted stacks move from a disk volume to volume-free storage, and
the durable-data migration must move every skill installation first
> - A remote skill (GitHub, skills.sh or URL) with no local files, no
complete saved version and an unreachable source blocks the move with
`skills:remote_source_unavailable`
> - Both the online and the offline migration refuse it today, so real
stacks stay on volumes forever
> - This pull request settles that case the same way in both paths:
rebuild the skill from its saved instructions, or keep it present but
unavailable until it is reinstalled
> - The benefit is that the move can finish without deleting any bytes
that still exist, and each outcome is logged

## Linked Issues or Issue Description

**What happened?**
A hosted stack could not move to volume-free storage. Two skill
installations had no local files, no complete saved version, and a
remote source that did not answer. The online and offline durable-data
migrations both reported `skills:remote_source_unavailable` and kept the
stack on its volume.

**Expected behavior**
Recovery works without manual repair. If the stored skill instructions
exist, the migration saves them as a new version and marks that version
as rebuilt. If no instructions are stored, the skill stays in the
library, is marked unavailable, is not offered to agents until it is
reinstalled, and does not block the move. The activity log records both
outcomes.

**Steps to reproduce**
1. Create a `github` skill with a pinned commit, an installed inventory
of `SKILL.md` and `reference.md`, and no saved version.
2. Make the remote source return 404.
3. Run the skill installation conversion. It reports `blocked` with code
`remote_source_unavailable`.

**Paperclip version or commit**
`master` at 8ce422e45d.

## What Changed

- `skillInstallationMaintenance().installations` takes a new
`settleUnavailableSources` option. The online and offline migrations
pass it. Direct calls keep the old blocking behavior, so a transient
remote failure outside a storage move never rebuilds a skill.
- Only a source that is gone counts as unavailable: a 404 or 410
response for an installed file. The capture path throws a typed
`RemoteSkillSourceUnavailableError` for these. Other failures (network
errors, 5xx, 429, unpinned revision, blocked scripts, package limits)
keep the `remote_source_unavailable` block.
- When the source is gone and the option is set, the migration rebuilds
the files from the saved incomplete version (if any) plus the stored
`SKILL.md` instructions. It publishes them as a version labelled
"Rebuilt from saved instructions", records
`reconstructedFromStoredContent` (time and missing files) in the skill
metadata, and writes a `company.skill_reconstructed_from_stored_content`
activity entry in the same transaction as the new version. The rebuilt
version is always a new version, never a reuse of the old one.
- When there are no stored instructions either, the migration sets the
existing `missingSource` marker with reason `remote_source_unavailable`
and writes a `company.skill_source_unavailable` activity entry. The
update is conditional on the row being unchanged. Later passes report
`source_unavailable` without calling the remote again.
- Runtime resolution returns `missing` for a marked skill unless a run
explicitly pinned a saved version, which stays usable. Otherwise it
shows with a plain message: the files could not be recovered when
Paperclip moved the company to new storage, and the user can reinstall
the skill. A reinstall replaces the metadata, which clears the marker.
- Eligibility reports `source_unavailable` for a marked skill. The data
contract and the offline skill phases accept it. The version check does
not fail the marked skill's incomplete current version, and it reports
`source_unavailable` for that version when it is an empty or incomplete
database-only snapshot (its bytes are in the database, so nothing stays
on the volume). Package-backed versions keep every check.
- The online migration counts `skillInstallationsReconstructed` and
`skillInstallationsSourceUnavailable` instead of deferring them.
- Other skill blockers (unsafe local source, catalog origin missing,
saved version incomplete without a remote failure, and so on) keep their
existing codes.

## Verification

- Red/green: with the service files from `master`, the three first tests
fail. The three review follow-up tests (503 stays blocked, empty saved
version verifies, pinned version stays available) fail on the first
commit of this PR and pass now. With this change they pass.
- `cd server && npx vitest run
src/__tests__/managed-skill-content.test.ts
src/services/online-durable-data-migration.test.ts` passes (embedded
PostgreSQL, real files, fetch mocked to 404).
- `npx vitest run src/__tests__/company-skills*.test.ts
src/__tests__/agent-runtime-skills.test.ts
src/__tests__/heartbeat-runtime-skills.test.ts`: all pass except two
`project workspace skill discovery` cases in `company-skills.test.ts`.
These fail identically on `master` in this macOS temp-dir checkout, so
they are not related to this change.
- `npx vitest run src/__tests__/ephemeral-server-data.test.ts` passes.
Its new test fails against the `master` data contract.
- `pnpm --filter @paperclipai/server typecheck` passes.
- `src/__tests__/ephemeral-migration.test.ts` needs an S3 endpoint and
was skipped locally. CI covers it.

## Risks

- A rebuilt skill keeps only the files that could be recovered. The
missing file names go to the metadata and the activity log. The old
version rows and the original remote source fields are kept, so a later
update or reinstall can fetch the exact files again.
- A 404 or 410 during a storage move is treated as final. The skill
stays recoverable through a reinstall if the source comes back. Network
errors and 5xx keep the block, so a stack with an outage at move time
waits for the next pass.
- No schema change.
- The marker guard and type now live in `company-skills.ts`, and the
maintenance module imports them.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used in Claude Code
with tool use (shell, file edits, test runs).

## Checklist

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

> - Paperclip is the open source app people use to manage AI agents for
work
> - Hosted stacks move from a volume to volume-free storage, and Core
must move every local workspace before the stack can move
> - Some archived workspaces have no files left on the volume and no
local repository that can rebuild them
> - Both the offline and the online migration refuse these workspaces
with `archived_git_source_unavailable` and
`local_source_unsafe_or_missing`, so the stack stays on its volume
forever
> - Nothing can ever move those files, because the files do not exist
> - This pull request records a "files gone" outcome for such a
workspace and moves the record without a snapshot
> - The benefit is that the stack can move, the record stays, and a
later reopen tells the user plainly that the files were not available

## Linked Issues or Issue Description

**What happened?**
An archived workspace whose folder and whose possible git sources are
all absent blocks the durable-data migration. The online pass reports
`workspaces:archived_git_source_unavailable` and
`workspaces:local_source_unsafe_or_missing` on every cycle. The offline
maintenance pass fails. Two archived workspaces on one staging stack are
in this state.

**Expected behavior**
A workspace whose files are provably gone does not block the move. The
workspace record stays. Reopen says that its files were not available at
migration time. A workspace whose files may still exist stays blocked.

**Steps to reproduce**
1. Archive a local workspace.
2. Delete its folder (and any local repository it was made from).
3. Run the online or offline durable-data migration.
4. See the workspace deferred with the two codes on every pass.

## What Changed

- `inspect` in `remote-workspace-migration.ts` marks a workspace as
"files gone" only when all of these are true: the workspace is archived,
it has no saved file reference (no `gitCacheRestoration` and no
task-directory retention record), its folder does not exist (`ENOENT`,
not a symlink or file), no retained restore point or archived git source
exists, the restore point did not expire or fail validation, and every
possible local source for its files is absent (the folder, the provider
path, the private repository source, the managed project caches, a
`file:` repository, and the project workspace folder).
- For such a workspace, the two codes leave the blocker list. Every
other blocker (writers, recovery, runtime leases, task binding) still
applies.
- `reserveMigration` then writes a remote authority with `snapshotId:
null` and no location, a `workspaceFilesUnavailable` record with the old
local path and time, and a `workspace.files_unavailable_at_migration`
activity log entry in the same company-scoped transaction. No snapshot
or operation journal is created. Cohorts, resumed journals, native
continuity and recovery sources keep the workspace blocked.
- `inspectRemoteWorkspacePersistence` (used by reopen) returns a plain
message for this record: "This workspace's files were not available when
it moved to new storage, so they cannot be restored. Continue the task
in a new workspace."
- `cleanupRemoteWorkspaceAllocation` treats such a record with no
allocation as already clean.
- The online pass counts these workspaces as moved and also as
`workspacesFilesUnavailable`. The offline pass uses the same owner, so
the rule is the same for both.
- Stays blocked with the existing codes: a folder that exists but is a
symlink or a file, an active or idle workspace with a missing folder,
and an archived workspace whose repository or cache still exists on
disk.

## Verification

- `cd server && npx vitest run
src/services/remote-workspace-migration.test.ts
src/services/online-durable-data-migration.test.ts` (254 passed,
embedded Postgres, real files).
- `cd server && npx vitest run remote-workspace-lifecycle
remote-workspace-migration-concurrency
remote-workspace-cohort-migration` (pass).
- Red/green: a fifth test moves an archived project task workspace whose
managed repository cache is also gone (the archived Git check fails with
a git command error there); it fails before and passes now.
- Red/green: a fourth test keeps a workspace with a broken saved Git or
task-directory reference blocked; it fails on the first commit and
passes now.
- Red/green: the two new "files are already gone" tests fail on
`origin/master` (the migration throws the two codes) and pass with this
change. The "files may still exist" guard test passes before and after.
- `cd server && npx tsc --noEmit -p .` passes.

## Risks

- The proof is conservative. If any possible source path exists, the
workspace stays blocked, so some archived workspaces may still need
another fix.
- The move is not reversible by the migration. It deletes no bytes,
because it acts only when nothing exists on disk.
- A reopen of such a workspace now fails with the plain message. Before
this change, the workspace could not move at all.

> 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, agentic coding with
tool use (shell, file edits, test runs) 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 18:30:33 -06:00
DottaandClaude Opus 5.5 b908678ea3 fix(connections): leave no connection behind when a first sign-in is cancelled (#22714)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Agents use apps through connections. Most app connections use an
OAuth sign-in.
> - Paperclip saves a draft connection before it opens the provider
sign-in page.
> - When the user cancels or abandons that sign-in, the draft stays. The
Apps list counts it as a connection that "needs attention".
> - The user did not ask for that connection, and the user must not
clean it up by hand.
> - This pull request hides drafts that never finished their first
sign-in and removes the draft when the user clicks Cancel.
> - The benefit is that a cancelled sign-in leaves no visible
connection, and a retry makes exactly one connection.

## Linked Issues or Issue Description

Refs #22634

**What happened?**

A workspace has one working "Google Workspace for the organization"
connection. The user clicks "Add account", chooses services, and clicks
Continue. The page shows "Opening Google Workspace…". The user clicks
Cancel before finishing at Google. The Apps page then shows "2
connections · 1 needs attention".

**What did you expect to happen?**

A cancelled sign-in leaves no visible connection. The same applies when
the user closes the page, reloads it, closes the Google tab, or refuses
consent at Google. A retry after a cancel makes exactly one connection.
A cancelled reconnect of a working connection does not change that
connection.

**Steps to reproduce**

1. Connect one Google Workspace account.
2. Open Apps, then Google Workspace, then "Add account".
3. Click "Continue to sign in", choose services, and click Continue.
4. On the "Opening Google Workspace" page, click Cancel.
5. Look at the Google Workspace card on the Apps page.

## What Changed

- Root cause: `connectApp` saves an OAuth draft (`status: "draft"`)
before sign-in (`server/src/services/tool-access.ts`, the connection
insert in the connect path). Cancel only navigated away. The Apps list
counted every draft as "needs attention"
(`ui/src/pages/apps/Browse.tsx`, `connectionState` and the attention
count).
- New module
`server/src/services/tool-access/connections/first-sign-in.ts`. It
decides if an OAuth draft never held a credential. It checks for OAuth
tokens on the connection and its grants, legacy inline tokens (the
removal module's list), a provider consent time, an external credential,
and the markers a real connection keeps when it needs a new sign-in. If
any check is not clear, the connection counts as real.
- The connection list endpoint sets `firstSignInPending: true` on those
drafts. The shared `ToolConnection` type has the new field.
- New route `POST /tool-connections/:connectionId/sign-in/cancel`. It
checks company access and configure permission. It removes the draft
with the normal removal teardown (grants, OAuth states, bindings) only
if the draft never held a credential. For any other connection it
changes nothing and returns `abandoned: false`. A removal writes the
activity entry `tool_connection.sign_in_cancelled`. The route is in the
OpenAPI registry.
- The Apps list does not show connections with `firstSignInPending`, and
it does not show an app whose only connections are such drafts. The
check is one pass with `Set` lookups.
- Cancel works in one transaction: it deletes the pending sign-in
states, locks the connection, checks it again, and parks it as
`disabled` with the marker `oauth_sign_in_cancelled`. If the connection
must stay, the transaction rolls back. Then the normal removal archives
the parked draft. Setup never reuses a parked draft, so a retry during
the removal gets its own row.
- One predicate, `connectionRemovedOrSignInCancelled`, guards
authorization start, access finish and machine sign-in. The direct,
Cloud and Vercel Connect callbacks and the access finish step lock the
connection before they write a grant or activate it, and return 409
`oauth_sign_in_cancelled` for a parked draft.
- `docs/api/tool-connections.md` documents the cancel route and the list
flag.
- The setup page calls the cancel route when the user clicks Cancel on
the sign-in screen. It does this only for a draft that this page made.
It does not do this for a resume, a reconnect, or a task-linked setup.
- Design for abandoned drafts (tab closed, reload, consent refused):
they are not listed, and the next attempt reuses them through the
existing draft reuse in setup. No background cleanup job is added.

## Verification

-
`server/src/__tests__/tool-access-cancelled-first-sign-in.integration.test.ts`
runs the real routes against embedded Postgres and a local OAuth
provider. It covers: a draft is marked and hidden; a provider token
exchange held open across Cancel ends in 409; Cancel and a retry at the
same time leave exactly one active connection; a parked draft is hidden
and refuses a new sign-in start; a legacy draft with an inline token is
not cancelled; Cancel removes it, deletes its OAuth state, logs
activity, and a late callback fails; a retry after Cancel gives exactly
one live connection (organization and personal); Cancel does not change
an active connection or a connection that needs a new sign-in; a draft
refused at the provider stays hidden and Cancel removes it; another
company cannot cancel the draft.
- `ui/src/pages/apps/Browse.test.tsx`: a pending draft is not listed and
does not add "needs attention".
- `ui/src/pages/apps/AppsConnect.test.tsx`: Google Workspace setup,
Continue, then Cancel calls the cancel route for the new draft.
- Red/green: the new Browse and setup tests fail without the UI change.
The server test fails on master because the route and flag do not exist.
- Local runs: the new server file, `openapi-routes.test.ts`,
`tool-access-oauth-protocol.integration.test.ts`, `Browse.test.tsx`,
`AppsConnect.test.tsx`, `activity-format.test.ts`, and
`src/features/connections` pass. Server typecheck passes. `pnpm verify`
exits 2 because of the pinned inputs file, so CI supplies broad
coverage.
- Not done: a real browser test against Google.

## Risks

- Low risk. The cancel route fails toward no change: it removes nothing
that shows any sign of a credential.
- Cancel and a late provider callback agree under the connection row
lock. If the callback commits first, Cancel changes nothing. If Cancel
commits first, the callback returns 409 and saves nothing. This covers
the direct, Cloud and Vercel Connect callbacks and the access finish
step.
- If the removal after Cancel fails, the draft stays parked and hidden,
and a second Cancel finishes it.
- A connection that was removed before and is now added again keeps its
old consent record. If that new sign-in is cancelled, it stays as a
visible draft, as it does today.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used in Claude Code
with tool use (shell, file edits, test runs).

## Checklist

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

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Agents use Google Workspace through Paperclip's own REST tools for
Gmail, Drive, Docs, Sheets, Slides and Calendar (#22634).
> - In a live test on staging, an agent called `gmail__list_threads`
with `query` and `q`. The tool did not have these arguments.
> - The tool ignored them and returned threads that did not match. The
agent read mail that it did not ask for.
> - Google reviews this connector for restricted scopes. A tool that
ignores a filter and reads too much data is a data-minimisation defect.
> - This pull request makes every tool refuse an argument that is not in
its input schema, before it sends a request to Google. It also adds
`query` to `list_threads`.
> - The benefit is that a filter can never be ignored. An agent gets a
clear error that names the bad argument and lists the correct arguments.

## Linked Issues or Issue Description

Refs #22634

**What happened?**
On staging, against real Google, an agent called `gmail__list_threads`
with `query` (and `q`) to list only threads with a marker. These
arguments are not in the tool's input schema. The tool dropped them and
returned unfiltered threads (5 shown, estimate 201).

**What did you expect to happen?**
The tool refuses an argument that it does not know, names it, and sends
nothing to Google. `list_threads` accepts a Gmail search query, as
`search_threads` does.

**Steps to reproduce**
1. Connect Google Workspace with Gmail read access.
2. Call `gmail__list_threads` with `{ "query": "subject:marker" }`.
3. See that the result contains threads that do not match the query.

## What Changed

- `defineTool` in `server/src/google-workspace-rest-tools/tool.ts`
checks the arguments of all 36 tools against the advertised input schema
before the zod parse. It checks the top level and structured inputs (for
example `attendees[0]`, `writeControl`). An unknown argument gives a
tool error and no request goes to Google. Example: `Invalid arguments
for list_threads: unknown argument "q". Accepted arguments: pageSize,
pageToken, query, labelIds, includeTrash, view. Nothing was sent to
Google.`
- `defineTool` sets `additionalProperties: false` on each object in the
advertised input schema that lists `properties`. Agents get the schema
from code, so existing connections see it with no reconnect and no
refresh.
- Google's batchUpdate request objects stay pass-through:
`docs__update_doc`, `slides__update_presentation` and
`sheets__update_spreadsheet` `requests[]`. The request-kind checks stay
the same.
- `gmail__list_threads` has a new optional `query`. It goes to Gmail as
`q`, with the same name and meaning as in `search_threads`. It works
together with `labelIds`. The draft and spam exclusions use the same
shared function (`queryWithExclusions`) as `search_threads`. The page
size stays default 20, maximum 50.
- The README has a new "Unknown arguments" section, a new row in the
input-differences table, a "Filters on list tools" decision list
(`search_messages` and `list_drafts` already have `query`;
`list_labels`, `list_calendars` have no REST filter; `list_events` uses
`fullText`; Drive `list_recent_files` stays without `query`, and
`search_files` is the Drive filter tool), and an updated `list_threads`
design note.
- `sheets/get-values.test.ts` expected that an unknown
`valueRenderOption` was ignored. It now expects a refusal.

## Verification

- `cd server && npx vitest run src/google-workspace-rest-tools` passes:
55 files, 1,400+ tests.
- New `strict-arguments.test.ts` makes one case for each of the 36 tools
from the tool list. Each case calls the tool with an unknown argument
and expects the exact error and zero HTTP requests. It also checks
`additionalProperties: false` on each closed object, the exact list of
pass-through paths, and that the zod schema of each tool validates the
same fields as its JSON schema. Red first: with the old `tool.ts`, 39 of
42 cases failed.
- `gmail/list-threads.test.ts`: `{ query: "x" }` reaches Google as
`q=(x) -in:draft`; `{ q: "marker" }` is refused with zero requests.
- `src/__tests__/google-workspace-rest-transport.test.ts` (embedded
Postgres, `executeTool` path): a connection with an older saved
`list_threads` schema (no `query`, no `additionalProperties`) gets the
new schema with no refresh and no Google request. A `query` call sends
the right `q`. A `q` call fails as `tool_error` with the readable
message, makes no Google request, and is recorded as a failed invocation
and one `call_failed` audit event.
- All Google-related server test files pass: 61 files, 1,542 tests. The
allowlist and boundary tests pass.
- `pnpm verify` exited 2 (the README is a broad input). Required CI
gives the broad coverage.
- Not checked against Google's servers. No request was sent to staging,
production or Google.

## Risks

- An agent that sent extra arguments before now gets an error, not a
silent drop. This is the intended change. The error lists the accepted
arguments, so the agent can correct the call at once.
- If a tool's JSON schema and zod schema do not agree, a valid argument
could be refused. A new test checks that they agree for all 36 tools.
- What Google's own MCP servers do with unknown arguments is not
recorded. We chose to refuse.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), through Claude Code, with tool
use (shell, file edits) and extended thinking.

## 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 17:37:09 -06:00
DottaandClaude Opus 5.5 b2a12fab49 fix(runner): keep tool catalogs within what a durable run attachment can carry (#22705)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Managed runs start through the Paperclip runner, which records each
run's attachment template in a durable control plane
> - That template carries the agent's authorized tool catalog, with
every tool's JSON schema
> - The runner-side catalog check admitted up to 256 tools and 768 KB,
but the durable control plane rejects any value over 10,000 canonical
JSON nodes, and durable commands cannot exceed about 522 KB
> - An agent with Notion and two GitHub connections (about 180 tools)
passed the first check and failed every run with
`durable_prp_canonical_json_too_large`
> - This pull request makes the catalog check honor what the run
attachment can carry, and gives controller-built values a node budget
that matches the command byte limit
> - The benefit is that agents with several large connectors run
normally: tools that do not fit move to on-demand search and call
instead of blocking the run

## Linked Issues or Issue Description

**What happened?**
After Notion (77 tools) and two GitHub connections (49 tools each) were
connected and installed for the company, every run for an agent failed
within seconds with `durable_prp_canonical_json_too_large`, before the
model session started. Paperclip retried each run several times.

**Expected behavior**
An agent with several connectors starts its run. When the full catalog
is too large, tools are delivered on demand.

**Steps to reproduce**
1. Build an authorized tool catalog that `runnerCodexDynamicToolsFit`
admits, for example 250 tools with enum-heavy schemas under 768 KB.
2. Stage it as a run attachment in `DurablePrpControlPlane`.
3. Staging throws `durable_prp_canonical_json_too_large`.

## What Changed

- `durable-prp-control-plane.ts`: the canonical JSON node budget is a
per-call limit. Runner-sent semantic input keeps 10,000 nodes.
Controller-built values (run attachment templates, command digests) use
a budget equal to the command byte limit, which already bounds them. New
`runAttachToolCatalogFits` checks that a tool catalog canonicalizes and
stays within 384 KB, leaving room for the rest of the run attachment.
- `runnerd-codex-transport.ts`: `runnerCodexDynamicToolsFit` also
requires `runAttachToolCatalogFits`. The server already uses this
predicate to choose between direct tools and on-demand tools.
- Tests: the densest catalog the fit check admits stages, persists and
restores through the control plane; a 180-tool connector catalog under
768 KB no longer fits and moves to on-demand tools.

## Verification

- `npx vitest run src/control-plane/durable-prp-control-plane.test.ts`
(runner): 232 passed, including the existing runner input
`over_node_limit` and `over_depth_limit` cases.
- `npx vitest run
src/services/native-runtime/assigned-mcp-tools.test.ts` (server): 61
passed. `paperclip-runner-tool-authority.test.ts`: 48 passed.
- Red/green: without the change, the control plane test fails with
`durable_prp_canonical_json_too_large`, and the server test fails with
`expected true to be false` (the oversized catalog was admitted).
- `runnerd-codex-transport.test.ts` and `runner-tool-capacity.test.ts`
have the same 79 local failures with and without this change (they need
built runner binaries). CI runs them.
- SDK public input pins: unchanged.

## Risks

- Agents whose catalog is between 384 KB and 768 KB now get on-demand
tools instead of direct tools. Before this change those runs failed, so
no working setup loses direct tools.
- Controller-built values get a larger node budget. They are bounded by
the command byte limit before they reach the runner, and runner input
keeps its strict limit.

## 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 17:27:47 -06:00
DottaandClaude Opus 5.5 1363b557b9 fix(runs): stop retrying a run whose setup is too large to start (#22707)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - When a managed run fails, Paperclip classifies the failure to decide
whether to retry it
> - A run whose setup exceeded the runner's durable limits failed with
`durable_prp_canonical_json_too_large`, which was classified as an
interrupted session
> - Paperclip retried it three times and then continued the task in a
fresh session that failed the same way: one agent produced 20 failed
runs in a few minutes, and the task showed a raw internal code
> - This pull request classifies oversized run setups as a permanent
failure with a plain-language action
> - The benefit is no pointless retries, and the user learns what to
change

## Linked Issues or Issue Description

**What happened?**
An agent's run setup was larger than the runner's durable control plane
accepts. Each attempt failed in seconds with
`durable_prp_canonical_json_too_large`. Paperclip scheduled retries and
fresh-session continuations that could never succeed, and the task
showed the raw code.

**Expected behavior**
A failure that the same input will always repeat is not retried. The
user sees what to change.

**Steps to reproduce**
1. Classify `new Error("durable_prp_canonical_json_too_large")` with
`nativeSessionFailureSourceCode`.
2. The disposition is `retryable_failure` with
`native_session_interrupted`.

## What Changed

- New `native-run-payload-too-large.ts`: the
`native_run_payload_too_large` code, its user-facing action, and the
matcher for `durable_prp_canonical_json_too_large` and
`command_payload_too_large`.
- `native-session-executor.ts`: classify those errors as
`native_run_payload_too_large`, treat it as permanent, and show the
action.
- `heartbeat/retries.ts`: do not schedule a retry for it.
- `native-sandbox-disk-full.ts`: a full disk does not relabel this code.
- Tests for classification, disposition and retry scheduling.

## Verification

- `npx vitest run
src/services/native-runtime/native-run-payload-too-large.test.ts
src/__tests__/heartbeat-retry-scheduling.test.ts`: 75 passed.
- Red/green: without the change, 4 of the new assertions fail.
- The underlying size mismatch is fixed separately in
paperclipai/paperclip#22705. This change makes any future deterministic
size failure stop at once instead of looping.

## Risks

- Low. Only these two deterministic size errors change classification.
All other failures keep their existing retry behavior.

## 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 17:27:29 -06:00
Devin FoleyandPaperclip 298026eadc fix(ai-connections): reconnect typed auth failures and stop quota retry countdowns (#22692)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Runs preserve typed provider failures so recovery can select the
right next action.
> - Authentication repair still recognized only older run error codes.
Native typed authentication failures could miss the reconnect request.
> - A typed exhausted quota with no reset also produced an estimated
one-hour admission hold. Waiting cannot repair that account.
> - This pull request uses the existing reconnect and validated adoption
flow for authentication. It asks for billing and usage repair for typed
quota exhaustion without a reset.
> - Rate limits and provider-reported resets keep their existing
automatic waits. Account authority, saved-work checks, pauses, and
approvals keep their existing gates.

## Linked Issues or Issue Description

Refs #15110. That open PR classifies the legacy Claude monthly-spend
message. This change does not duplicate its adapter parsing or change
older untyped quota recovery.

Refs #21351. That open PR changes legacy Claude edge-error
classification and repeated-failure latching. This change consumes the
typed provider category and retains the existing credential-generation
checks.

**What happened?**

A failed run with `providerFailure.category: authentication` and a
generic native error code did not create its reconnect request. A typed
`quota_exhausted` failure without a reset produced an estimated provider
cooldown, although the account needed attention. Recovery's narrow
PostgreSQL result projection also omitted typed native provider
failures.

**Expected behavior**

Ask the responsible person to repair the selected account or explicitly
adopt a compatible managed connection. Ask for billing and usage repair
when an exhausted allowance has no reported reset. Continue to wait
automatically for transient rate limits and reported allowance resets.

**Steps to reproduce**

Use a failed native run with a typed OpenAI authentication error and a
generic native error code. The existing reconnect controller should
create one card. Use typed `quota_exhausted` evidence with no reset. The
task should offer account review and manual Retry, with no invented
reset or automatic provider retry.

## What Changed

- Recognize typed authentication failures and the reported
`provider_invalid_credentials` run code. Reuse the existing
controller-only reconnect request, account freshness checks, durable
continuation, and explicit legacy adoption.
- Retain typed provider failures in the bounded PostgreSQL recovery
projection.
- Refresh the reviewed SDK public-source pin for the changed shared
interruption type with the repository generator.
- Keep typed quota exhaustion without a reset out of provider cooldown,
bounded retry, and periodic quota-recovery paths. A newer billing
refusal supersedes older reset evidence. Classify a startup billing
refusal before the remote exit-confirmed retry branch, and prevent the
startup planner from falling back to plain backoff.
- Add the derived `provider_billing` task action, an account-review
link, and a matching Inbox label. Preserve saved-work recovery and
current user gates.
- Update the connection documentation for these recovery decisions.

## Verification

- Red: five server regressions failed on current master for typed
authentication, the invalid-credential code, a false quota cooldown, and
the missing billing action. The new task notice regression also failed
before the repair.
- Green: the first focused set passed 241 tests. The final
quota/retry/UI set passed 281 tests. The database-backed reconnect set
passed seven selected cases for Claude, OpenAI, method switching, and
explicit legacy adoption. Sets overlap; these counts are not additive.
- Database tests check current account attribution, refreshed credential
generations, bounded result projection, and preservation of reported
resets. A quota without a reset must not schedule a successor. Two
additional startup regressions failed before the startup repair. The
repaired startup suites pass all 45 integration cases and 11 focused
classification cases. They check a blocked task, billing presentation,
no retry deadline, no resumable claim, and preserved retries for rate
limits and reported resets.
- `pnpm check:token-gates` and `git diff --check` passed.
- The earlier [Runner support
failure](https://github.com/paperclipai/paperclip/actions/runs/45263306284/job/138003893674)
came from a stale reviewed SDK source pin. The same three SDK evidence
files failed locally on `cacdb81`. Regenerating the pin from that
committed tree made all 59 tests in those files pass. Only the shared
`execution-projection.ts` source hash changed; lock and runtime pins
remain unchanged.
- `pnpm build` and repository-wide `pnpm -r typecheck` passed for the
initial change. The authentication/recovery policy set also passed 99
tests. Server typecheck and build also passed for the startup repair at
`cacdb81c26988394e11f934d05531bcbb121c7a2`. The full local `pnpm
test:run` stopped in chat shard 4/6 with 15 failures: fourteen
file/database-open failures during `ENFILE` file-table exhaustion and
one retry polling timeout. The failed run also reported an unhandled
`ENFILE` error. All 40 selected chat cases, including those 15 failures,
passed in a fresh process on `06c14a8`. This does not qualify the full
local suite. The complete CI workflow passed on the final head, as
recorded below.
- Local environment: isolated macOS arm64 checkout and disposable
PostgreSQL fixtures. The branch was replayed onto master at
`32375d302fbc3a233531674aedefa273adee2d97`; that base change touches an
unrelated migration test.
- Live provider account repair and the original reported credential
failure remain unverified. A read-only operational trace confirmed
retained runner checkpoint versions, but the reported runtime string was
absent from retained onboarding and run logs as well as current Core and
available Cloud source refs. Its producer remains unidentified.

- [Trusted PR CI, attempt
2](https://github.com/paperclipai/paperclip/actions/runs/45265943006/attempts/2)
completed successfully on `06c14a8cbcf2480eb9d2841bebda3337d4248bd6`,
including typecheck, build, Runner, serialized server, general test, and
browser suites. The previously cancelled serialized suite passed on that
attempt. All 59 commit checks are terminal: 56 succeeded and three
conditional checks were skipped. The Snyk commit status also passed.
- Greptile completed on `06c14a8cbcf2480eb9d2841bebda3337d4248bd6` with
5/5 and no new findings. Both earlier review threads are resolved.

## Risks

- A typed exhausted allowance without a reported reset now requires
account repair. Older untyped quota errors retain their existing
recovery policy; #15110 remains separate.
- Authentication repair must follow the recorded account rather than
infer an account from a proxy driver's upstream name. Existing
generation checks must still protect newer credentials.
- No schema migration or provider replay authority is added. Existing
stored runs keep their data. The new task action is derived at read
time.
- Live recovery of the originally reported incident remains unverified;
the operational trace did not locate the reported runtime code.

## Model Used

OpenAI `gpt-6.1-sol`, through the Codex harness in T3 Code, with xhigh
reasoning effort, tool use, code editing, and test execution. The
harness does not expose the 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-23 14:37:16 -08:00
DottaandClaude Opus 5.5 8c6e5cbbb8 fix(connections): offer Paperclip's Google sign-in on Paperclip Cloud only (#22699)
<!-- 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
> - Agents use Google Workspace through a connection. A connection can
use Paperclip's own Google sign-in ("Connect with Paperclip") or the
customer's own Google OAuth client
> - Paperclip's own Google sign-in goes through the Paperclip Cloud
broker with Paperclip's verified Google client
> - Google's restricted-scope verification and security assessment cover
only the servers that Paperclip operates
> - The owner decided on 2026-11-23: Paperclip's own Google sign-in is
for Paperclip Cloud workspaces only. Self-hosted instances use their own
Google OAuth client
> - This pull request hides and refuses Paperclip's own Google sign-in
on self-hosted instances, keeps saved connections working, and gives
clear guidance
> - The benefit is that restricted-scope Google tokens stay on servers
that Paperclip operates, and self-hosted users always see a path that
works

## Linked Issues or Issue Description

Refs #22635

**What happened?**

A self-hosted Paperclip instance offered "Connect with Paperclip" for
Google Workspace and other Google apps. That sign-in uses Paperclip's
verified Google client. It sends restricted-scope Google tokens to a
server that Paperclip does not operate. A self-hosted instance also
offered Paperclip Cloud enrollment only to use that sign-in.

**What did you expect to happen?**

Paperclip's own Google sign-in is available only on Paperclip Cloud
workspaces. A self-hosted instance shows only "Use your own Google OAuth
app", with a short reason and a link to a setup guide. Saved Google
connections on a self-hosted instance keep working until a sunset date
that the owner sets on the Paperclip Cloud broker. After that date, the
connection tells the user to reconnect with their own Google client.
Paperclip Cloud workspaces do not change.

**Steps to reproduce**

1. Run Paperclip without Paperclip Cloud markers (self-hosted).
2. Turn on the Google Workspace connector in **Settings →
Experimental**.
3. Open **Apps** and choose **Google Workspace** or **Gmail**.
4. Before this change: setup offers "Connect with Paperclip" or asks to
connect the instance to Paperclip Cloud first.

## What Changed

- `packages/shared/src/google-sign-in-deployment.ts`: new
`appDefinitionForDeployment` and `isCloudOnlyConnectionMethod`. On a
self-hosted instance they remove every Paperclip-managed Google method.
Other providers do not change. New shared message
`GOOGLE_SIGN_IN_CLOUD_ONLY_MESSAGE`.
- `server/src/services/google-sign-in-availability.ts`:
`paperclipGoogleSignInAvailable()` returns `isCloudManagedInstance()`.
This is the existing single Cloud check. No new environment variable.
- `appWithPaperclipCloudConnectorAvailability` (gallery and setup
validation) uses that check. A self-hosted gallery and setup do not show
managed Google methods.
- `authorization-start.ts`: a self-hosted instance refuses to start a
managed Google authorization before it calls Paperclip Cloud (`422`,
code `google_sign_in_cloud_only`). A broker refusal with
`PROVIDER_CLOUD_ONLY` maps to the same message, also on a Cloud
instance.
- `paperclip-cloud-connector.ts`: `PROVIDER_CLOUD_ONLY` is a known
broker reason.
- `grant-refresh.ts`: when the broker refuses a refresh with
`PROVIDER_CLOUD_ONLY` (after the sunset), the grant is marked for
reconnection. The error keeps code `oauth_reauthorization_required`,
adds reason `google_sign_in_cloud_only`, and tells the user to reconnect
with their own Google OAuth client.
- `ConnectionSetupFlow.tsx`: on a self-hosted instance (no `cloud` block
in health), Google setup uses the filtered definition. It never shows
Cloud enrollment for Google. The customer-owned Google client step shows
this note and a link to Google's client guide.
- Docs: `doc/connections/GOOGLE-WORKSPACE.md` ("Who can use Paperclip's
Google sign-in", "Self-hosted instances: use your own Google client")
and a dated decision row in `doc/memory/google-connector-memory.md`.
- `tests/runner-e2e/source-sdk-public-inputs.json`: pins the new shared
files (generated).

## Verification

- Red first, then green:
- `packages/shared/src/google-sign-in-deployment.test.ts` fails without
the new module and passes with it (4 tests).
- With the source files from `origin/master`, these new tests fail: 2 in
`server/src/__tests__/tool-access-service.test.ts` (self-hosted refusal,
refresh guidance and saved-connection refresh; broker refusal mapping),
3 in `server/src/services/paperclip-cloud-connector.test.ts`, and the
self-hosted test in `ui/src/pages/apps/AppsConnect.test.tsx`. With the
change they pass.
- Cloud path proof: "never shows the self-hosted Google notice on
Paperclip Cloud" (UI), "leaves every app unchanged on Paperclip Cloud"
(shared, identity check on every definition), "decides Cloud or
self-hosted from the instance's Cloud markers" (server). All existing
managed Google service tests (515) pass in a Cloud context.
- `npx vitest run src/__tests__/tool-access-service.test.ts` (server):
517 passed.
- `npx vitest run src/services/paperclip-cloud-connector.test.ts`
(server): 71 passed.
- `npx vitest run src/pages/apps/AppsConnect.test.tsx
src/features/connections` (ui): all passed.
- `npx vitest run` for `agent-connection-catalog.integration`,
`tool-gateway-service`, `google-access-removal`,
`connection-management.integration`, `generic-mcp-connection`,
`remote-mcp-connectors` and `plugin-connectors-circleback-parity`
(server): 446 passed, 1 skipped.
- `npx vitest run` in `packages/shared`: 1383 passed.
- `pnpm verify` exits 2 because `doc/connections/GOOGLE-WORKSPACE.md` is
a global CI input. Required CI supplies the broad coverage.
- Not run: no requests to staging, production, or Google. The reconnect
of a saved managed Google connection on a self-hosted instance after the
sunset was not run end to end in a browser.

## Risks

- Behavior change for self-hosted instances: new Paperclip-managed
Google connections stop. Saved ones keep refreshing until the broker
sunset (not set yet).
- The decision uses `isCloudManagedInstance()`. If a Cloud workspace
does not have its Cloud markers, it shows the self-hosted path. Cloud
stacks always have the tenant token, so the risk is low.
- Works with old and new brokers. An old broker does not refuse. The app
check still hides and refuses the method. A new broker refuses
self-hosted instances, and the app maps the refusal to the same
guidance.
- Deploy order: the broker change (paperclip-cloud) and this change can
deploy in any order.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use
(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
- [ ] 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 16:19:01 -06:00
DottaandClaude Opus 5.5 980caf1167 fix(workspaces): name online recovery and finalizer blockers, and move settled finalizers online as offline does (#22696)
## 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
> - Staging passes now leave workspaces with
`workspace_recovery_unresolved` (15 on one stack) and
`execution_finalization_unresolved` (3 on another)
> - The pass does not say which recovery kind or which finalizer state
blocks, so nobody can tell a safe case from a real one
> - The offline move also lets a settled native run past when its files
are already saved, but the online move refuses every unsettled finalizer
> - This pull request names the recovery kind and the finalizer state,
and lets the online move do what the offline move does for settled
finalizers that cannot touch the workspace
> - The benefit is fewer blocked moves and an exact cause for each one
that stays blocked

## Linked Issues or Issue Description

Refs #22644, #22650

**What happened?**
After repeated online passes on staging, one stack reports
`workspaces:workspace_recovery_unresolved` for 15 workspaces and another
reports `workspaces:execution_finalization_unresolved` for 3. The codes
do not say which recovery kind or which finalizer state is the cause.
For finalizers, the online move refuses every finalizer that is not
committed, even when the offline move would move the workspace.

**Expected behavior**
Each blocked workspace names the recovery kind or the finalizer state.
The online move accepts a settled finalizer in the same cases as the
offline move, when the finalizer cannot write to this workspace.

**Steps to reproduce**
1. Create a local workspace. Settle a native run on its task with a
finalized sync descriptor and a succeeded `workspace_finalize`
operation. Leave the finalizer in `retryable_failure` with no lease.
2. Run the online move. It fails with
`execution_finalization_unresolved`. The offline move of the same
workspace succeeds.

## What Changed

- Inventory returns `details`, for example
`workspace_recovery_unresolved:active_run_watchdog` or
`execution_finalization_unresolved:finalizer_leased`. The `reasons` list
does not change. The online pass reports each detail as
`workspaces:<reason>:<state>`.
- Recovery states: the action kind; `<kind>_export_cause` or
`<kind>_file_evidence` for a task-only kind that carries a workspace
export cause or file evidence; `<kind>_unrelated_task`;
`system_recovery_running`; `sibling_task` for an action on another task
in the same proven Git source.
- Finalizer states: `not_native`, `run_<status>`, `controller_leased`,
`finalizer_leased`, `sync_other_workspace`, `sync_prepared`,
`sync_finalized_without_receipt`, `remote_run`, `result_recorded`,
`legacy_finalizer_needs_maintenance`, `phase_<phase>`, and
`sibling_run`.
- A settled native run (ended, no live controller lease, no live
finalizer lease) no longer blocks the online move when its sync
descriptor is finalized and its `workspace_finalize` operation
succeeded. The offline move already accepts this case. The finalizer
retries from that receipt and does not touch this workspace.
- A settled run whose descriptor names another workspace of the task
stays blocked online as `sync_other_workspace`. The finalizer selects
the task's current workspace before the descriptor, so it could not save
the other workspace after this one moved. Only the offline batch, which
moves every local record, accepts it.
- Publication locks the finalizer and run rows of these runs (`FOR
UPDATE NOWAIT`) and inspects again. A finalizer that takes a lease
during the upload makes publication refuse.
- No change for the other states. A finalizer that is still running or
leased, a prepared descriptor, a finalized descriptor without a receipt,
a recorded result and a remote run stay blocked, as offline. A legacy
finalizer without a descriptor stays blocked online: the offline move
adopts it only because the maintenance fence stopped the old controller,
and it then releases the coordinator lease.

## 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/workspace-git-source-roots.test.ts
src/services/online-durable-data-migration.test.ts
src/services/online-durable-data-migration-postgres.test.ts
src/services/finalized-workspace-recovery-migration.test.ts
src/services/online-remote-workspace-recovery-hold.test.ts
src/services/online-legacy-workspace-recovery.test.ts` (embedded
PostgreSQL): 9 files, 473 of 474 passed. The one failure was a 15 s
timeout of `preserves archived Git edits or refuses an unavailable
restore point (nested-linked)` under the full parallel run. It passes
when run alone (19 of 19 for that group), and this change does not touch
that path.
- Red/green: 8 new tests fail on `origin/master` and pass with this
change: the online settled-finalizer move (`finalized`), the three named
blocked finalizer states (`missing-receipt`, `leased`, `prepared`), and
the three named recovery kinds, and the other-workspace run that stays
blocked (it moved on 415941f). A new test that takes the finalizer lease
during the upload checks that publication refuses.
- New pass test: details become `workspaces:<reason>:<state>` keys and
unsafe text is dropped.
- `pnpm --filter @paperclipai/server typecheck`: passed.

## Risks

- The online move now proceeds past one settled finalizer state, which
the offline move already accepts. Publication locks and rechecks the
finalizer, so a finalizer that resumes during the upload stops
publication.
- The offline publication also locks these settled runs now. With
writers stopped, nothing else holds those rows.
- The pass result gets new `workspaces:<reason>:<state>` keys.

> 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 15:45:41 -06:00
a00e31967b feat(connections): live setup progress from the person's own agent (#22626)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Several setup screens offer "Set it up with your agent": a prompt
the person pastes into their own agent (Claude Code, Codex) to do the
setup on their computer. AWS role setup is the newest
> - Once the prompt is copied, the setup page goes quiet: the person
cannot see what their agent is doing or when it is done, and has to
switch windows to find out
> - The agent already runs commands, so it can report its progress back
if we give it a safe place to send it
> - This pull request adds a live checklist the agent fills in: the page
creates it, the prompt gives the agent curl commands with a token, and
the page shows every update as it happens
> - The benefit is a setup that shows its own progress, and a reusable
piece any "Set it up with your agent" screen can use

## Linked Issues or Issue Description

Refs #22233 (the AWS setup screen this extends).

**Subsystem affected**
Connections (agent-guided setup), live updates, a new public agent API,
UI.

**Problem or motivation**
After a person copies a setup prompt into their own agent, Paperclip
shows nothing until they come back and paste a result. There is no way
for the agent to say what it is doing.

**Proposed solution**
A setup checklist a person's own agent writes to, shown live on the
setup page. The agent's requests need no Paperclip sign-in, so they
carry a narrow, expiring bearer token. Paperclip Cloud needs no
front-door change: it already forwards `/api` requests that carry an
`Authorization` header to the workspace without Cloud identity (its
machine-request lane), and these always do.

**Alternatives considered**
- Polling the page instead of live events: slower and adds load to every
open setup page. The page uses the existing live-event channel, with a
20-second backup refresh while the agent works.
- Putting the token in the URL: URLs end up in logs. The token goes in
the `Authorization` header.
- Letting the agent set the role ARN itself: the person still pastes it
(as decided for #22233). The agent's finish summary shows the ARN to
copy.

## What Changed

- `packages/db`: new `agent_setup_progress` table (company-scoped,
purpose and subject, token hash, items, status, summary, update count,
expiry). Migration `0501` is idempotent.
- `packages/shared`: `agent-setup-progress` types, limits and
validators; new live event type `agent_setup_progress.updated`.
- `server`:
- `agentSetupProgressService`: create (random `pcsp_` token, only its
SHA-256 kept), read, and the agent's set-checklist, update-item and
finish. Tokens are compared in constant time; a write is refused after
expiry (6 hours) or 300 updates, and concurrent writes are guarded by
the update counter. Finishing `done` ticks off open steps.
- Routes: board-only `POST
/api/companies/{companyId}/agent-setup-progress` and `GET
/api/agent-setup-progress/{id}`; agent routes `PUT …/checklist`, `POST
…/items/{key}` and `POST …/finish` mounted with the other public routes.
Activity entries for created, started and finished.
- Each agent write publishes `agent_setup_progress.updated`; the
live-events socket forwards it with only the checklist ID.
  - OpenAPI entries for all five routes.
- `ui`:
- Reusable `ui/src/components/AgentSetupProgress.tsx`:
`useAgentSetupProgress` (creates one checklist per setup and follows
it), `agentSetupProgressInstructions` (the prompt section with the
agent's curl commands) and `AgentSetupProgressPanel` (waiting, working,
done and failed states, using the task status glyphs).
  - `LiveUpdatesProvider` refreshes the checklist on its live event.
- AWS role step: one step (no numbering) with the prompt, the live
checklist and the Role ARN field. The prompt starts with the progress
instructions and asks the agent to put the role ARN in its finish
summary.
- Docs: `docs/api/agent-setup-progress.md` (API and how to add it to
another page) and the AWS setup section.
- Storybook: AWS step in waiting, working, done and failed states, and
the panel on its own.

## Verification

- `server/src/__tests__/agent-setup-progress.test.ts` (real routes,
embedded Postgres): set, update and finish with the prompt's token; only
the hash is stored; four live events carry the checklist ID; activity
entries. Refusals: missing token, wrong token, another checklist's token
(401), bad key (400), unknown item (404), update limit (429), expired
(410). Company boundary: another company's member gets 403 on read and
create.
- `live-events-toast.test.ts`: the socket delivers the event with only
`{ progressId }`. It failed before the socket fix (red/green), which an
end-to-end run found.
- `AgentSetupProgress.test.tsx`: the prompt section's exact commands;
the hook creates one checklist and the panel follows waiting → working →
done on live refreshes.
- `AwsRoleSetup.test.tsx`: the step creates the checklist for its
connection, waits for the agent, and the prompt leads with progress
reporting.
- Totals: shared 1362, server (new, OpenAPI, live events, AWS) 101, UI
(components, connections, apps, live updates) 1469. Typecheck clean for
db, shared, server and UI (except Storybook's generated catalog, not
built in this worktree).
- End to end on a local instance: Playwright opened the real AWS setup
step, read the prompt, sent the agent's requests with its token, and the
page showed each update within 1.5 seconds (inside the 20-second backup
refresh, so from live events) through "Your agent set up AWS" with the
role ARN summary. No page errors.
- Not run yet: Paperclip Cloud staging (after deploy) and an agent
running the prompt on its own.

## Risks

- New anonymous routes. The token is the only credential: 32 random
bytes, stored as a hash, scoped to one checklist, six hours, 300
updates. Text from the agent is shown as plain text (no links or
markup), so the worst a leaked token can do is change one checklist's
wording until it expires.
- One new table and migration (idempotent).
- Live delivery is per server process, like every other live event; the
20-second refresh covers a missed event.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use
(shell, file edits, Storybook and Playwright screenshots, the in-app
browser against a local dev server).

## 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: Paperclip <noreply@paperclip.ing>
2026-11-23 15:44:44 -06:00
b0d2500a63 test(server): split the Cloud SSH workspace heartbeat runs into per-harness files (#22629)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Each pull request runs CI, and the slowest check sets the time until
a reviewer sees a result
> - The server tests run in 12 shards, and the slowest shard sets that
time
> - In PR run
[45186146272](https://github.com/paperclipai/paperclip/actions/runs/45186146272),
the slowest check was **General tests (server (3/12))** at **872s**
> - One file in that shard,
`server/src/services/ssh-remote-workspace.integration.test.ts`, took
**317s** on one worker, because its 11 heartbeat runs against a real SSH
server ran one after another
> - This pull request moves the shared setup into a fixture and divides
the heartbeat runs into four files that can run in parallel
> - The benefit is a shorter slowest server shard and more even shards

## Linked Issues or Issue Description

No public issue exists. This is the problem:

**Problem / motivation**
The file `ssh-remote-workspace.integration.test.ts` took 317s in CI
(`PAPERCLIP_TEST_TIMING`). The next slowest file in the same shard took
206s. The slowest files in the other shards took about 110s or less. The
file was also over the 180s limit for oversized test files. Most of the
time came from the 11 `it.each` heartbeat runs. Each run does a full
heartbeat and a follow-up against a real SSH server.

**Proposed solution**
Move the shared embedded-Postgres and SSH setup and the heartbeat-run
body into a fixture. Divide the heartbeat runs into one file for each
large harness family, and one catch-all file for the other harnesses.

**Alternatives considered**
Increase the shard count. That makes every server shard pay the setup
cost again and does not make the 317s file shorter. Run the `it.each`
cases concurrently in one file. That puts many heartbeat runs on one
shared SSH server and one database, which can cause flaky tests.

## What Changed

- `__tests__/ssh-remote-workspace-fixture.ts` now holds the shared
embedded-Postgres/SSH setup (`useSshWorkspaceFixture`), the harness
table, and the heartbeat-run body (`describeSshHeartbeatRuns`). The body
was moved without changes.
- `ssh-remote-workspace.integration.test.ts` keeps its two
durable-workspace tests and uses the shared fixture.
- The heartbeat runs are now in four files:
  - `ssh-remote-workspace-heartbeat-claude` (2 runs)
  - `ssh-remote-workspace-heartbeat-codex` (2 runs)
  - `ssh-remote-workspace-heartbeat-gemini` (2 runs)
- `ssh-remote-workspace-heartbeat-cli` (5 runs). This file uses
`exclude`, so it runs every harness that does not have its own file. A
new harness gets coverage automatically.
- Each file gets its own Postgres, temporary root and sshd. Company
`issuePrefix` values still come from the global run index, so they stay
unique.

**Expected savings:** The largest single file goes from about 317s to
about 60–120s. After the timing-weighted balancer has data for the new
files, shard 3/12 should go from about 872s to the level of the other
server shards (about 790–855s). That is about **20–80s off the slowest
server shard**. The PR critical path gets the same saving when this
shard is the last to finish.

## Verification

- Run `pnpm --filter @paperclipai/server exec vitest run
src/services/ssh-remote-workspace` on a machine with sshd. Locally with
sshd and embedded Postgres: **5 files passed, 13 tests passed** (2 + 11,
the same count as before), 210s wall time with the files in parallel.
- CI on this PR: all server shards, the serialized suites and typecheck
passed.
- Compare the timing of the new files in the CI timing output of a later
run.

## Risks

- Low risk. The change only affects test files. Product code does not
change.
- Each new file starts its own embedded Postgres and sshd. This adds a
small setup cost per file, but the files run on different workers.
- If a harness is added to the `claude`, `codex` or `gemini` include
lists but is not added to the `exclude` list of the catch-all file, it
runs twice. It is not skipped.

## Model Used

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

## Checklist

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

> - Paperclip is the open source app people use to manage AI agents for
work
> - Native harness runs end with a result from the agent's finish tool
and a provider terminal
> - A provider can refuse a later request in the same turn after the
finish was accepted (Antigravity 1.5.2 streams its final reply after the
finish)
> - Paperclip counted that run as failed and retried it, so the agent
did the work again and posted the same reply again
> - The product rule is that recovery is automatic and that finished
work is never repeated visibly
> - This pull request makes an accepted done report the run's outcome
when the only later failure is a transient provider refusal (capacity or
rate limit), for every native harness
> - The benefit is one reply per task and no retry for work that is
already done

## Linked Issues or Issue Description

**What happened?**
In a local run of Google Antigravity 1.5.2 (Google sign-in,
`gemini-3.8-flash-low`), Google refused 10 of 17 runs with 503 "No
capacity available". In two runs the agent's finish was already accepted
when the refusal came. Paperclip failed those runs and scheduled the
capacity retry. One task got the same answer three times.

**Expected behavior**
When the agent's done report was accepted and the only later failure is
a transient provider refusal, the run succeeds, the task closes as for
any done report, and no retry starts. A real failure (model not
available, exhausted allowance, rejected sign-in, untyped failure,
cancelled run, no accepted finish) stays a failure.

**Steps to reproduce**
1. Run a native task whose finish tool is accepted.
2. Make the provider fail the same turn afterwards with a typed
`overloaded` or `rate_limit` failure (or Codex `serverOverloaded`).
3. See that the run fails and a capacity retry is scheduled.

**Agent adapter(s) involved**
Not adapter-specific (core bug). Observed with Google Antigravity; the
same path applies to Codex and other native harnesses.

## What Changed

- `native-provider-failure.ts`: the rule
`nativeAcceptedResultOutlivesProviderFailure`. It reads only the
committed terminal and its typed failure. It is true only for a failed
turn with an accepted `done` report and a transient `overloaded` or
`rate_limit` failure (or the classified Codex overload). Other accepted
dispositions keep the bounded capacity retry.
- `native-accepted-outcome.ts` (new): the decision is made once, when
`PaperclipControlPlanePort.completeRun` accepts the result, and saved as
`acceptedOutcome` beside the raw terminal in
`native_run_results.result_json`. The raw terminal does not change,
because it is part of the accepted result's integrity digest. No
migration: the field is optional JSON, and a row saved by an older
release keeps its raw terminal as before.
- Every reader of the run outcome uses that saved value: the executor's
adapter result, the finalizer, the projection repair pass
(`native-run-projection.ts`, also in SQL), accepted-result settlement,
and the run's saved `prpRunTerminalState` (read by the exhausted and
superseded finalization paths).
- The run records a closed diagnostic
`providerFailureAfterAcceptedResult: { provider, category }` and no
provider text. Its warm provider session stays open
(`nativeRetainsWarmSession`): the refusal came from the remote model
service and the turn ended cleanly, so closing it would only cold-start
the next message.
- `doc/plans/2026-11-22-antigravity-qualification.md`: records the first
completed prompts on 1.5.2 and the open decisions below.

## Verification

-
`server/src/services/native-runtime/native-provider-overload.integration.test.ts`
(embedded Postgres, executor and finalizer, replayed twice):
- New: accepted finish, then a typed capacity refusal, a typed rate
limit, or Codex `serverOverloaded`: the run succeeds, the task is done,
no successor run, no failure report. Red before the fix (3 failed),
green after.
- New: after the finalizer commits, a restart that leaves the run
`running` is settled by the projection repair pass as succeeded, with no
failure report; the saved `prpRunTerminalState` is `succeeded`. Red
before the stored outcome (projection flipped the run to failed).
- New: a row saved without the accepted outcome (older release) stays
failed through finalizer and projection.
- New guards: accepted finish, then model unavailable, exhausted
allowance, rejected sign-in or an untyped failure: the run still fails
and the task is not done.
- Existing capacity-retry cases (accepted `needs_review` result) still
retry after one and two minutes, then block.
- `server/src/services/native-runtime/native-provider-failure.test.ts`:
new unit cases with the real Antigravity observation (503 and 429
outlive the finish; model, quota, sign-in, unknown retryability,
timeout, `needs_review` and cancelled do not). 70/70 pass.
- `tsc --noEmit` for `server`: clean.
- 40 neighbouring test files that import the port, projection,
settlement or finalizer: 4,193 passed, 10 failed. The same 10 fail with
the base source (missing local bundled skill file and a runnerd fixture
directory), so they are local-environment failures.
- `pnpm verify` selected 2,980 of 3,857 test files (core native-runtime
modules changed), which is a full-suite run. I stopped it after its
first group (4 files, 85 tests) passed and left the broad suite to
required CI, as AGENTS.md section 7 says.
- Not run live: the fixed behavior has not been re-run against Google.
The evidence came from a local instance before this change. Daytona and
the API-key route were not run.

## Risks

- Behavior change for every native harness: a failed turn with an
accepted done report and a transient refusal now ends as success. A done
report still goes through the same completion policy, deliverable
evidence check and review stages as any done report.
- A run whose result was saved by the previous release and finalized by
this one keeps its raw failed terminal (old behavior), consistently in
the finalizer and the projection (tested).
- Not fixed here, open for an owner decision:
- A capacity refusal before any accepted result takes the saved-work
replacement path (about 30 s, task shown as blocked meanwhile). One
after an accepted result takes the bounded capacity retry. The
Antigravity classifier already types both as `overloaded`/`transient`;
the split is by path. Moving the first kind to the capacity retry skips
the replacement's stop proof and unconfirmed-action check.
- Antigravity 1.5.2 streams the provider's error text as agent text
before it ends the turn, so the live transcript shows it like a reply. A
fix belongs in the runner driver.
- Follow-ups seen in the same evidence, not fixed here: the finish tool
once refused a reply that cited a workspace-only file before the agent
registered a deliverable.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use
(shell, file edits, local test runs).

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [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:31:58 -06:00
DottaandClaude Opus 5.5 0aaf946227 fix(connections): keep retrying when Google does not confirm a revoked grant (#22669)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Paperclip Cloud can manage the Google sign-in for a Google Workspace
connection. The app keeps the refresh token. Cloud keeps no token.
> - When a user removes the connection, the app asks Cloud to end the
access at Google (#22065).
> - Before this change, the app deleted the token after that call,
whatever Cloud answered. If Google or Cloud could not be reached, the
access stayed open at Google, and no retry was possible.
> - The owner decided on 2026-11-23: the app keeps the token in a
pending record and retries until Google answers. Cloud still never
stores a provider token.
> - This pull request adds that pending record and a background retry.
It also covers company deletion and a Cloud-removed instance.
> - The benefit is that a removed Google connection does not keep access
at Google because of a short outage, and the user does not need to do
anything.

## Linked Issues or Issue Description

Refs #22065

**What happened?**
A managed Google connection was removed while Paperclip Cloud or Google
was unavailable. The removal result was `not_ended`, and the refresh
token was deleted. Paperclip could not try again, so Google access
stayed open.

**What did you expect?**
Paperclip keeps the token only for the retry, and retries automatically
until Google confirms or gives a final answer. The user sees that
Paperclip keeps trying, and does not need to act.

**Steps to reproduce**
1. Connect Gmail through Paperclip Cloud.
2. Make the broker revoke fail (Cloud unavailable, or Google 5xx).
3. Remove the connection. The token is deleted and nothing retries.

## What Changed

- New table `google_pending_revocations` (migration `0502`, additive,
`CREATE TABLE` only). It has `company_id` with no foreign key, so a row
outlives a deleted company. It stores the token as the same
`local_encrypted` material as the connection secret version. It never
stores plaintext. It is not a company secret: it is not listed, an agent
cannot bind it, and no route reads it.
- `google-access-removal.ts`: before the broker call, the app copies the
sent token version into a pending row (lease 2 minutes, so a restart
during the call resumes). A final outcome deletes the row. A retryable
outcome (`provider_revocation_failed`, `revocation_in_progress`,
`broker_unavailable`, `broker_error`, `unexpected_error`) keeps it, and
the result is the new `retrying`. If the connection secret is still live
after the conditional delete (for example, the user signed in again
during the call), the row is deleted.
- New worker on the `google-pending-revocation` delivery queue
(`registerDeadlineWork`; it registers the real next deadline and has no
deadline when the table is empty). Each attempt takes a lease on the row
and calls the broker with a 15-second timeout. Backoff is 1, 2, 4 ...
minutes, up to 6 hours. The hard stop is 30 days. The worker stops
without a call if a live company secret holds the same token.
- When a retry ends, the worker writes a
`connection.google_access_retry` audit event and a
`tool_connection.google_access_ended` or
`tool_connection.google_access_not_ended` activity entry (labels added
to the activity feed). For a deleted company, it writes only a log line.
- Company deletion queues every managed Google token of the company
inside the delete transaction, before the secrets are deleted (`reason =
company_deleted`).
- When the Cloud connection status check finds the instance `removed`,
the app queues every managed Google token (`reason = instance_removed`),
then deletes each connection secret.
- `ManagedGoogleAccessRemoval.result` gets `retrying` (shared type and
OpenAPI schema). The removal message for `retrying`: "Google didn't
confirm that Paperclip's access has ended yet. Paperclip will keep
trying automatically." It has no link and asks for no action.
- Docs: `doc/connections/GOOGLE-WORKSPACE.md` ("Pending revocation"),
`docs/api/tool-connections.md`, the help page
`docs/guides/board-operator/deleting-connection-data.md`, and a dated
decision row in `doc/memory/google-connector-memory.md`.
- `tests/runner-e2e/source-sdk-public-inputs.json` refreshed for the
changed shared type, as `pnpm verify` asks.

## Verification

- `npx vitest run
src/__tests__/google-managed-connection-removal.test.ts` (embedded
Postgres): 46 pass. Without the fix, 15 fail (red), with the fix all
pass (green). New cases:
- an unconfirmed token is kept only in the pending row, encrypted, not
in the secrets list; the worker retries and deletes the row when Google
confirms; audit and activity are written;
- the row exists during the broker call, so a fresh worker after a
restart revokes it;
- `binding_not_known`, `other_connections_remain` and
`provider_revocation_disabled` stop the retry;
- backoff 1 minute to 6 hours, and give-up at 30 days with a final audit
and activity entry;
  - a live secret with the same token stops the retry without a call;
  - an older broker's `403 INSTANCE_SUSPENDED` is retried;
- company deletion queues the token and the worker revokes it after the
company is gone;
- a removed instance queues every token, drops the secrets, does not
queue again, and the worker revokes.
- `npx vitest run
src/__tests__/paperclip-cloud-connector-status.test.ts`: the
removed-instance hook runs only for `removed`, and a failure does not
change the status.
- `ui`: `npx vitest run
src/features/connections/googleAccessRemoval.test.ts` (7 pass, the new
`retrying` case is red without the change).
- Also passed: `tool-connection-content-deletion`, its canary,
`delivery-work-coordinator`, `idle-local-work`, `packages/db` tests;
`server` `tsc --noEmit`.
- `pnpm verify` exits 2 (global doc input changed), so required CI
supplies the broad coverage.
- Not verified: any call to a real broker or to Google. No request was
sent to staging, production or Google.

## Risks

- Migration is additive (`CREATE TABLE` and indexes on the new table):
`online_compatible`.
- Paperclip now holds an encrypted token for at most 30 days after
removal when Google did not confirm. The token is never usable for tool
calls: no grant or connection refers to the row.
- Instance removal deletes the managed Google connection secrets. Those
connections then need a reconnect after a new enrollment. They could not
refresh anyway, because Cloud refuses a removed instance.
- Deploy order: either order is safe. With the current production
broker, a removed instance's revoke gets `403` and the app retries until
the hard stop. The Cloud broker change that accepts it is a separate PR
in the private Cloud repository.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`) through Claude Code, with tool use
(shell, file edits, embedded Postgres tests), standard 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 15:28:07 -06:00
Dotta 4434d12e2f fix(setup-token): back off cleanup retries after failed sweeps (#19446)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - A setup-token login keeps a durable cleanup record. The setup-token
reaper releases its provider lease and removes the record
> - A sweep that fails keeps the record and retries on the next
30-second tick, for as long as the failure lasts
> - During a provider outage, that is a steady stream of provider calls
and log lines with no recovery benefit
> - This pull request backs off consecutive failed sweeps from 30
seconds to 30 minutes and resets after a successful sweep
> - The benefit is less load and log noise during outages, with the same
recovery once the provider is back

## Linked Issues or Issue Description

Refs #14777 (fixed by #15200 and #22667; this pull request adds the
retry backoff that the report also asked about).

This pull request was rebased onto `master` and reduced to the backoff.
#15200 already makes a blank lease lookup return null, and #22667
already logs the failure class and code and covers a restart with a
PostgreSQL test. The earlier redacted-message logging is removed,
because the reaper now logs no error message.

**What happened?**

When a setup-token cleanup sweep fails, for example because the sandbox
provider is down, the cleanup worker retries every 30 seconds until the
failure ends. Each retry calls the provider again and logs again.

**Expected behavior**

Repeated failures back off. A successful sweep returns to the normal
interval.

**Steps to reproduce**

1. Make `releaseById` fail for a reapable setup-token record.
2. Watch the setup-token cleanup worker. It retries the release every 30
seconds without a limit.

## What Changed

- `setup-token-reaper.ts`: count consecutive failed sweeps (a sweep with
a failed record, or a sweep that throws). `retryDelayMs()` returns 30 s,
60 s, 120 s and so on up to 30 min, and 0 after a successful sweep.
- `login-cleanup-work.ts` and `index.ts`: the setup-token cleanup duty
passes `retryDelayMs` to the shared scheduler. The next run waits for
the larger of the configured interval and the backoff delay.
- `setup-token-session.ts`: skip the provider call for a reapable record
with no lease id and remove the record directly.
- `index.ts`: the sweep log line says "cleared records", because a
record without a lease is cleared with no release.
- `setup-token-session.ts`: the failure log line says "a cleanup
failed", because a failure can now come from removing the record as well
as from the provider release.
- `doc/heartbeat-internals.md`: document the retry behavior.
- Tests: backoff to the cap and reset (`setup-token-reaper.test.ts`),
backoff after a thrown sweep, removal of records without a lease, and
the scheduler honoring the backoff across notifications for both a sweep
with failed records and a sweep that throws
(`login-cleanup-work.test.ts`).

## Verification

- `pnpm exec vitest run server/src/services/setup-token-reaper.test.ts
server/src/__tests__/login-cleanup-work.test.ts
server/src/services/setup-token-session.test.ts`: 3 files, 98 tests
passed.
- The seven new tests fail without the source changes.
- `pnpm --filter @paperclipai/server typecheck` passes.

## Risks

- The backoff applies to the whole setup-token cleanup worker. While one
record keeps failing, new cleanup can wait up to 30 minutes. Records
stay in the database, so nothing is lost.
- The failure count lives in memory and resets on restart. The retained
rows rebuild the cleanup work.

## Model Used

- Original change by the pull request author. Rebased and reduced by
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 13:15:08 -08:00
DottaandClaude Opus 5.5 8ce422e45d fix(github): keep published reviews and settle every status comment (#22672)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Review agents answer GitHub pull requests through one shared main PR
comment and one comment per inline request
> - Paperclip writes status notices into these comments: "Work is
paused", "This turn ended without publishing a final response", "Working
on this…"
> - On recent PRs these notices replaced finished reviews, and many
never changed again, even after the task was done
> - People then see a stale status instead of the review, and work that
waits on the review slows down
> - This pull request keeps published reviews in place and makes every
status comment settle
> - The benefit is that the PR always shows the latest real review, and
no placeholder stays open after the task is idle

## Linked Issues or Issue Description

**Describe the bug**
Review bot comments on GitHub pull requests show "Work is paused. Your
request is saved." or "This turn ended without publishing a final
response." after the review finished. The comment never updates. Inline
replies stay at "Working on this…".

**Steps to reproduce**
1. A review agent publishes a review in the main PR comment.
2. Two more review requests arrive. The task becomes blocked for a short
time, or the run for a request ends without a reply.
3. The main PR comment now shows the status notice. The review is gone.
4. Separately: request A's run ends and request B's run starts a few
seconds later. A's inline comment stays "Working on this…" forever.

**Expected behavior**
A status notice for one request never replaces a published review in the
shared main PR comment. Every request comment settles once the run that
woke for it is finished and the task is idle.

**Evidence**
GitHub edit history shows the overwrite on all six settled stuck
comments across #22528, #22591, #22611, #22626 (two bots) and #22635.
Example: on #22626 the "Ponytail Paperclip Review — 3/5" body was
replaced by "Work is paused" at 14:28 and again at 14:56; Feynman's
reply was replaced and then patched nine times in four minutes. The task
ran 15 back-to-back runs about 3 seconds apart, so the old "latest run
only" check never matched the earlier requests.

## What Changed

- `writeGitHubResponseComment` takes a `status` flag. In the shared main
PR comment, a status notice never replaces a published reply or a newer
response. That request settles as final against the existing comment
(`published_response_kept` / `status_superseded`) instead of throwing
and retrying.
- Status notices carry a `paperclip-response-kind:status` marker. Known
status texts posted before this change count as status too, so a later
status may still replace them.
- `readGitHubResponseRun` / `readGitHubResponseRuns` return
`finishedRequestRunId`: the latest finished run that woke for the
request. It is part of the same statement, so the batched sweep keeps
its statement budget.
- `githubResponseExecution` settles a request from that run once the
task's latest run is finished, the latest run belongs to another
request, and the task is not blocked.
- `processTerminalResponses` selects a request when any finished run
woke for it, not only the latest run.

## Verification

- New red/green integration tests in
`server/src/__tests__/chat-channels.integration.test.ts`:
- `keeps the published review in the main GitHub PR comment when a later
request has only a status: ended_without_reply / paused` (red before:
body became the status text)
- `settles a GitHub working comment whose run finished just before
another request's run started` (red before: body stayed "Working on
this…")
- Updated older tests that asserted the old rule (status replaces the
review) to assert the review stays and the request settles final.
- `response-run-state.test.ts` equivalence reference now also computes
the finished request run; passes over the randomized fixture.
- `terminal-response-work.test.ts` statement budget passes (the first
fallback did one query per row; it now reads in the same statement).
- Local: all GitHub tests in the integration file passed (536) before
the batching refactor; after it, the targeted tests plus
`server/src/services/chat-channels/github/` and related files pass
(438). `tsc --noEmit` for server is clean. CI covers the full suite.

## Risks

- Behavior change: when a newer request is paused or ends without a
reply, the main PR comment keeps the earlier review instead of showing
the status. The status stays visible in the Paperclip task.
- A request whose run finished without a reply now settles to "ended
without publishing a final response" once the task is idle, even if a
later continuation run covered it in another thread.
- No migration.

## Model Used

- 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
- [ ] 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 14:54:42 -06:00
DottaandClaude Opus 5.5 32375d302f test(cloud): read durable-data blocker names from the check() calls (#22686)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The online durable-data migration pass names every blocker that the
volume-free readiness check can report
> - A test reads the blocker names from `ephemeral-server-contract.ts`
with a regex, and checks that the pass names each one
> - #22641 added that test. It looks for `blockers.push("...")`
> - #22646 merged at about the same time. It moved each check into a
`check(area, blocker, inspect)` helper, so the regex now finds no names
> - The test fails on master, in `ci / General tests (server (8/12))`,
on every pull request
> - This pull request changes the regex to read the blocker name from
each `check(...)` call
> - The benefit is that shard 8/12 is green again, and the test again
covers every blocker

## Linked Issues or Issue Description

Refs #22641 (added the test). Refs #22646 (changed the source the test
reads). Refs #22682 (blocked by this failure).

**What happened?**

`server/src/services/online-durable-data-migration.test.ts > names every
durable-data blocker that readiness can report` fails on master
`b865dd112b`:

```
- Expected
+ Received
- ArrayContaining [ "workspaces_require_migration", "local_instruction_copies_require_settlement", "external_agent_instructions" ]
+ [ "runtime_skill_assets_require_migration" ]
```

**Why?**

The regex `/blockers\.push\("([a-z_]+)"\)/g` matched nothing after
#22646. Only the constant that the test adds by hand stayed in the list.

**Expected behavior**

The test finds the 10 blocker names (9 from the source, plus
`RUNTIME_SKILL_ASSETS_BLOCKER`) from the `check(...)` calls and checks
each one.

## What Changed

- Change the scan regex in the test to
`/(?:blockers\.push\(|check\(\s*"[a-z_]+",)\s*"([a-z_]+)"/g`. It reads
the blocker name from each `check(area, blocker, ...)` call, also when
the call spans lines. It still reads the old `blockers.push("...")`
form.
- No product code changes.

## Verification

- `cd server && npx vitest run
src/services/online-durable-data-migration.test.ts`
  - On master: 1 failed, 31 passed (the failure above).
  - With this change: 32 passed.
- The existing `arrayContaining` check still fails if a later refactor
makes the scan find nothing again.

## Risks

- Low risk. Only one test regex changes.

## 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

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 14:41:47 -06:00
DottaandClaude Opus 5.5 427d13c38c fix(connections): clean up audit-only task traces and wait without rescanning content (#22658)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - #22636 removes connection content (for example Google results) when
a task or a company is deleted
> - Review on #22636 found two more gaps after it merged
> - A task whose only connection trace is an audit entry (for example a
denied call) got no cleanup job, so the argument preview stayed after
the task was deleted
> - A cleanup job that waits for open runs re-ran all content steps on
every recheck, which is wasted database work
> - This pull request queues a job for audit-only tasks and adds a
`waiting` phase that only counts open work
> - The benefit is that no audit preview of a deleted task is left
behind, and a waiting job stays cheap

## Linked Issues or Issue Description

Refs #22636

**Problem**
1. Deleting a task whose only connection trace is a
`tool_access_audit_events` row with the task's ID creates no cleanup
job, so its argument preview stays.
2. While a task cleanup job waits for open runs or approvals, every
recheck runs the six content steps again from the start.

**Expected behavior**
1. The audit preview is cleared after the task is deleted.
2. A waiting job only checks whether work is still open, and runs the
content steps once when the work settles.

**Steps to reproduce**
1. Write a denied policy audit entry with the task's ID and no call or
call event. Delete the task. The preview stays.
2. Delete a task while one of its runs is working. Each recheck scans
every content table of the task again.

## What Changed

- `issue-content-deletion.ts`: when the task has no recorded runs, calls
or call events, check for an audit entry with the task's ID. If one
exists, queue the job. The audit step already matches by task ID.
- `content-deletion.ts`: new `waiting` phase. After a content pass with
open work, the job moves to `waiting` instead of restarting. Each
recheck counts open runs, open calls, open approvals and open wakes with
results for the task. When the count is zero, or after the one-day
bound, the job runs the content steps once more and finishes.
- Moved the pure JSON cleaning helpers to `content-cleaning.ts` to keep
`content-deletion.ts` under 1,000 lines. No behaviour change.
- Two canary tests: a task with only an audit entry, and a waiting job
that leaves new content alone on a recheck and clears it after the open
run settles. Both failed before the fix.
- The working memory note is updated.

## Verification

- `cd server && npx vitest run
src/__tests__/tool-connection-content-deletion-canary.test.ts
src/__tests__/tool-connection-content-deletion.test.ts
src/__tests__/server-startup-feedback-export.test.ts` (156 tests pass).
The two new tests failed before the fix.
- `cd server && pnpm typecheck` passes.

## Risks

- Task deletion with no other connection trace runs one more query on
`tool_access_audit_events` for the company, with `limit 1`. That table
has no index on the task ID in its details.
- No schema change.

## 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 14:00:36 -06:00
Devin Foley ff68490d03 fix(ai-connections): say why a local sign-in attempt ended (#22668)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Onboarding and the agent setup screen connect a subscription account
with local sign-in (`useLocalAiLogin`) when the login environment is
local and the server supports it
> - A local sign-in attempt lasts 30 minutes. The client polls `POST
/companies/:id/ai-connections/local/check`
> - The check answers `{ status: "expired" }` whenever the attempt is no
longer waiting for the user, not only after the deadline
> - So a cancelled attempt, an attempt that "Start sign-in again"
replaced, and an attempt that already connected the account all show
"This sign-in attempt expired"
> - This pull request keeps the status and adds the real reason as the
error text that the sign-in panel already shows
> - The benefit is that people see why sign-in stopped, and support can
tell an expiry from a replacement

## Linked Issues or Issue Description

**What happened?**

A person saw "This sign-in attempt expired. Start sign-in again." during
subscription sign-in, well inside the 30-minute attempt window. In
`localAiLoginService().check`, any attempt whose status is not
`waiting_for_user` answers `{ status: "expired" }`. That includes
`cancelled` (a cancel, or a replacement by "Start sign-in again" in
another tab or step), an attempt whose cancel is still in progress, and
`authenticated` (already connected).

**Expected behavior**

"Expired" appears only when the 30-minute deadline has passed. A
cancelled, replaced or completed attempt says what happened.

**Steps to reproduce**

1. Start local sign-in for an account.
2. Choose "Start sign-in again" (or cancel the attempt).
3. Check the first attempt. It answers `{ status: "expired" }`, and the
panel shows "This sign-in attempt expired".

**Paperclip version or commit**

`master` at `5f5ac154368`.

**Deployment mode**

Any deployment where local sign-in is available, including onboarding.

## What Changed

- `local-ai-login.ts` `check()`: an attempt that is `authenticated` or
has a connection answers `{ status: "expired", error: "This sign-in
already connected the account." }`. An attempt that is `cancelled`, or
whose cancel is still in progress, answers `{ status: "expired", error:
"This sign-in attempt was cancelled or replaced by a newer one. Start
sign-in again." }`. An attempt past its deadline or `timed_out` still
answers `{ status: "expired" }`.
- The `LocalAiLoginStatus` type and the client do not change.
`useLocalAiLogin` already shows a server `error` before its default
expiry text.
- Test: `ai-legacy-compatibility.test.ts` covers a replaced attempt, a
cancelled attempt, and a completed attempt.

## Verification

- `pnpm exec vitest run
server/src/__tests__/antigravity-local-ai-login.test.ts
server/src/__tests__/ai-connections.test.ts
server/src/__tests__/ai-legacy-compatibility.test.ts`: 3 files, 186
tests passed.
- The new test fails on `master`.
- `pnpm --filter @paperclipai/server typecheck` passes.

## Risks

- Low risk. The status values stay the same, so client logic does not
change. Only the error text changes for cancelled, replaced and
completed attempts.
- A completed attempt still answers `expired`, so the panel offers
"Start sign-in again". Answering `ready` would let the client reconnect
the same attempt, but it would also start the client's connect flow
again, so this change keeps the existing status.

## 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 11:53:02 -08:00
Devin Foley 7f343549db fix(ai-connections): tell people why an API key could not be verified (#22666)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - During onboarding, a person can connect a model with a provider API
key. Paperclip checks the key with one request to the provider before it
stores it
> - `validateAiApiKey` returns "The provider rejected this API key."
only for 401 and 403. Every other answer, and every network error,
returns "The provider could not verify this account. Try again."
> - The server does not log the upstream status, so nobody can tell
later what the provider said
> - A person whose key is valid but whose account has no credit, is
rate-limited, or hits a provider outage cannot know what to fix
> - This pull request gives each case its own code and message, and logs
the status and the provider's error type without the key
> - The benefit is that people can fix the real problem, and support can
see the provider's answer in the logs

## Linked Issues or Issue Description

**What happened?**

During onboarding, a person entered a Claude API key and saw "Could not
store the API key: The provider could not verify this account. Try
again." They then switched to a Claude subscription. The server log did
not show which status the provider returned.

**Expected behavior**

The person learns whether the key is wrong, the account has no credit,
the provider is limiting requests, or the provider is down. The server
logs the upstream status.

**Steps to reproduce**

1. Call `validateAiApiKey("anthropic", key, request)` with a `request`
stub that returns 400, 402, 429 or 500.
2. Observe that all four throw `ai_connection_verification_failed` with
the same message.

**Paperclip version or commit**

`master` at `5f5ac154368`.

**Deployment mode**

Hosted onboarding. Self-hosted installs use the same check.

Refs #12675 (related: server-owned user-secret definitions for
onboarding API keys).

## What Changed

- `ai-api-key-failures.ts` (new): one code and message for each result.
The codes are `ai_connection_api_key_rejected` (unchanged),
`ai_connection_billing_required`, `ai_connection_rate_limited`,
`ai_connection_provider_unavailable`,
`ai_connection_verification_timeout`,
`ai_connection_provider_unreachable`, and
`ai_connection_verification_failed` (unchanged, for all other answers).
- `ai-api-key-test.ts`: map 401/403 to rejected (unchanged); 402, or the
error type `billing_error`, `insufficient_quota` or
`insufficient_credits`, to billing; 429 to rate limited; 5xx (including
Anthropic's 529) to provider unavailable. A `TimeoutError` maps to
timeout, and other network errors map to unreachable.
- Log the provider, the HTTP status, the provider's error type and the
result code. The error type comes from `error.type`, `error.code` or
`error.status` in at most 8 KiB of the error body. It is used and logged
only when it is on a closed list of documented provider error types
(Anthropic, OpenAI and xAI, Google, OpenRouter). Any other value is
ignored. The key and the response text are never logged. 401/403 bodies
are not read.
- `adapters/registry.ts` and `agent-environment-test.ts`: keep the
specific code in the environment check instead of collapsing it to
rejected or failed.
- The billing check looks at `error.type`, `error.code` and
`error.status` together, so a 429 with `type: invalid_request_error` and
`code: insufficient_quota` is a billing problem, not a rate limit.
- `tests/runner-e2e`: the connection harness keeps every new code in
`creationFailure` instead of saving it as `connection_request_rejected`.
One shared list feeds `connection-flow.ts`, `connection-evidence.ts` and
`result-validation.ts`, and a test keeps it equal to the server's codes.
- Tests: `ai-api-key-test.test.ts` (17 tests) and
`connection-support.test.ts`.

**The user-facing text needs a person's review.** The new messages are a
first draft. They read after the onboarding prefix "Could not store the
API key:":

| Code | Message |
|---|---|
| `ai_connection_billing_required` | The provider account for this API
key has no credit or billing set up. Add credit with the provider, then
try again. |
| `ai_connection_rate_limited` | The provider is limiting requests for
this account right now. Wait a minute, then try again. |
| `ai_connection_provider_unavailable` | The provider is having problems
right now. Try again in a few minutes. |
| `ai_connection_verification_timeout` | The provider did not answer in
time. Try again. |
| `ai_connection_provider_unreachable` | Paperclip could not reach the
provider. Check this server's network connection, then try again. |

## Verification

- `pnpm exec vitest run server/src/services/ai-api-key-test.test.ts`: 17
passed. On `master`, 11 of the original 15 fail.
- Callers: `ai-connections.test.ts`, `adapters/registry.test.ts`,
`agent-environment-test-status.test.ts` and
`agent-test-environment-routes.test.ts` with the new file: 5 files, 331
tests passed.
- `pnpm --filter @paperclipai/server typecheck` passes.
- Not run: a live check against each provider. The billing mapping uses
the documented error types (`billing_error` for Anthropic,
`insufficient_quota` for OpenAI, 402 for OpenRouter). The models
endpoint may not report a billing problem for every provider.

## Risks

- Low risk. The HTTP status of the store request stays 422, and 401/403
behavior does not change.
- An answer that does not match a known case still returns
`ai_connection_verification_failed`, as before.
- A code that consumers compare by value can now be one of five new
values. No UI code compares these codes, and the server callers now pass
them through.

## 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 11:52:56 -08:00
Devin Foley eada94a6d2 fix(storage): answer storage throttling with 503 and retry skill archive uploads (#22664)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - First-agent setup saves the agent's skill packages to object storage
(S3 on hosted installs)
> - S3 can answer an upload with `503 SlowDown` when it limits the
request rate
> - The S3 provider retries a throttled upload, but when the retries run
out the error reaches the HTTP error handler unclassified
> - The person then sees "Internal server error", and the server reports
a handler crash for a transient storage condition
> - This pull request answers a storage-unavailable error with 503 and
retry guidance, and makes the skill archive upload always use the
retryable file-source path
> - The benefit is that a throttle is retried, persistent throttling
gives a clear retryable answer, and crash reports stay for real faults

## Linked Issues or Issue Description

**What happened?**

During first-agent setup, a skill package upload hit S3 request-rate
throttling (`SlowDown`, HTTP 503). The person saw "Internal server
error". The server logged `error.handler_crash` with
`error_code=SlowDown`. A retry soon after got "This skill package is
being saved. Retry after its upload settles." on a build before #22477.

**Expected behavior**

A transient throttle is retried. Persistent throttling answers with a
retryable status and guidance. The same person can retry at once.

**Steps to reproduce**

1. Use S3 storage and make the bucket answer `PUT` with `503 SlowDown`
until the provider's retries run out.
2. Start first-agent setup, or call `skillPackageStore().prepare` for a
new package.
3. The request fails with 500, and the error handler reports a crash.

**Paperclip version or commit**

`master` at `5f5ac154368`.

**Deployment mode**

Hosted (S3 storage). Self-hosted installs with S3-compatible storage
behave the same way.

Refs #22477 (failed upload claims expire at once, so an immediate retry
no longer gets 409). Refs #22404 (throttle backoff for small uploads
without a source file).

## What Changed

- `error-handler.ts`: a recorded storage-unavailable error (throttling,
5xx, timeouts, network failures, as `isStorageUnavailableError` already
defines) answers `503` with `Retry-After: 30` and code
`storage_unavailable`. The response text is fixed. The handler logs the
fixed-shape storage diagnostics (operation, error code, HTTP status,
request id) as a warning, not as a crash. Storage credential rejections
still report as server faults.
- `error-handler.ts`: the client-abort shortcut (`aborted` with
`ECONNRESET`, answered as 499) no longer catches a recorded storage
failure. A storage read that the backend reset now answers 503 while the
caller is still connected.
- `storage-unavailable.ts`: add the response text and
`recordedStorageFailureDiagnostics`.
- `skill-package-store.ts`: pass the staged archive as `sourceFile`. The
S3 provider then re-reads the file on each attempt, so it can resend the
archive after a throttle even when the shared upload buffer is full. The
upload also gets a Content-MD5 check.
- The claim behavior from #22477 does not change: a failed attempt's
claim expires at once, its exact keys go to the deletion outbox, and a
retry uses fresh keys.
- New test `storage-unavailable-error-handler.test.ts`: a storage
connection reset answers 503, and a storage credential rejection still
reports as a server fault.
- New test `skill-package-storage-throttle.test.ts` (real PostgreSQL,
the real S3 provider, and a local S3 stand-in): a transient `SlowDown`
is resent and the package publishes; persistent throttling answers 503
with no crash report, and an immediate retry by the same caller
succeeds.

## Verification

- `pnpm exec vitest run
server/src/__tests__/skill-package-storage-throttle.test.ts`: 2 passed.
Both tests fail on `master` (no Content-MD5 on the archive upload; 500
instead of 503).
- Related suites (skill package store and upload, error handler, sandbox
outage handler, storage-unavailable, S3 throttle and backoff): 17 files,
175 tests passed.
- `pnpm --filter @paperclipai/server typecheck` passes.

## Risks

- Other routes that fail on a storage outage now answer 503 instead of
500 and do not send a crash report. This is the intent, but storage
outages are now visible only as warning logs, not as crash reports.
- The archive upload now hashes the archive for Content-MD5 before it
sends it. Skill archives are small, so the cost is low.
- This change does not explain why one company's prefix hit the S3
request-rate limit. That needs a separate operations check.

## 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 11:52:50 -08:00
Devin Foley 0bff5abd04 fix(setup-token): log why a reaper release fails and guard restart cleanup (#22667)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - A Claude subscription login in a sandbox environment runs `claude
setup-token` and keeps a durable cleanup row with the session and its
provider lease
> - The setup-token reaper releases the lease and removes the row when
the session is terminal, past its deadline, or consumed
> - #14777 reports a reaper that failed to release the same leases every
30 seconds forever after a restart, and logged no cause
> - #15200 later fixed the cause: a session with no lease had a blank
lease id, and the UUID lookup for it failed on every sweep
> - The reaper still discards the error, so the next permanent failure
will be just as hard to diagnose, and no test covers the restart case
> - This pull request logs the error class and code, and adds a
PostgreSQL regression test for the reported restart case
> - The benefit is that operators can see why a release fails, and the
restart cleanup stays fixed

## Linked Issues or Issue Description

Fixes #14777

Refs #15200 (the blank lease id fix). Overlapping open pull requests for
the same issue: #15363 (logs the full error message), #16663, #18706,
#19446, #18088, #14236.

## What Changed

- `setup-token-session.ts`: when a lease release fails, the reaper logs
`Cause: <error class> (<code>)` for the error and up to three of its
causes, for example `DrizzleQueryError > PostgresError (22P02)`. It does
not log the error message, because a database or provider message can
quote input values. A thrown value that is not an `Error` logs `unknown
error`. The record stays retryable, as before.
- `setup-token-reaper.test.ts`: three tests for the log line, including
a database error wrapped by the query layer. They check that the message
text is not logged.
- `login-cleanup-work.test.ts`: a PostgreSQL test with the production
reaper. A restart left two sandbox setup-token sessions in `submitting`
past their deadline, one with no lease and one with a lease. One sweep
releases both, the lease goes through the environment driver, and the
next sweep finds nothing. With the #15200 guard removed, this test fails
with `{ released: 1, failed: 1 }`, which is the reported symptom.

What the issue reported, and where it stands on `master`:

| Report | State |
|---|---|
| Release fails every 30 s forever | Fixed by #15200. This PR adds the
regression test. |
| Reaper swallows the cause | Fixed here. |
| Cancel answers `200 {}` and cancels nothing after a restart | The
route now falls back to a durable cancel for `starting` and
`awaiting_code`. A `submitting` session is not cancellable on purpose (a
credential write may be in progress), and the route keeps its uniform
`200` answer. Such a session leaves `/active` when its 5-minute deadline
passes, and the next sweep releases it. |
| No cancel in the UI | The UI now calls the cancel route. |
| Local subscription logins | They now use a separate flow
(`local-ai-login.ts`). This reaper skips `local_subscription` rows. |

## Verification

- `pnpm exec vitest run server/src/services/setup-token-session.test.ts
server/src/services/setup-token-reaper.test.ts
server/src/__tests__/login-cleanup-work.test.ts`: 3 files, 90 tests
passed.
- The two log tests fail on `master`. The restart test fails when the
#15200 guard is removed.
- `pnpm --filter @paperclipai/server typecheck` passes.

## Risks

- Low risk. The change adds a log field and tests.
- This pull request does not add a startup sweep that ends every live
session at boot. In a rolling deploy, an old process can still be
completing a login while the new one starts, so the 5-minute deadline
stays the recovery path.

## 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 11:52:43 -08:00
DottaandClaude Opus 5.5 d28becf0f5 fix(server): run person-opened gateway sessions as their opener for personal connection grants (#22643)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The tool gateway lets an agent run call connected apps through a
short-lived session
> - A person on the board can also open a gateway session for a running
agent
> - Such a session resolved credentials for the run's responsible
person, not for the person who opened it
> - A member could therefore use another member's personal connection
grant through that member's running agent
> - This pull request limits personal grants in a person-opened session
to the grant owner and requires permission to act on the agent
> - The benefit is that a personal connection is used only by its owner
or by the owner's own agent runs

## Linked Issues or Issue Description

Refs #22635

**What happened?**
`POST /api/tool-gateway/sessions` let any non-viewer member open a
session for any running agent in the company. Tool calls in that session
used the personal grant of the run's responsible person.

**What did you expect to happen?**
A person who opens a session can use a personal (user-owned) grant only
when they own it. The person needs permission to act on the agent.
Company-shared connections and agent-opened sessions work as before.

**Steps to reproduce**
Two members are in one company. Member A has a personal grant on a
connection that agent X uses. While a run of X is active, member B opens
a gateway session for that run and calls a tool on that connection. The
new route test covers this case.

**Impact**
Access-control hardening for personal connection grants.

## What Changed

- Add the nullable column `tool_gateway_sessions.created_by_user_id`
(migration `0502`, which also adds `tool_mcp_tasks.created_by_user_id`).
The route sets it when a person (not a local implicit board) opens a
session.
- Grant resolution for such a session acts as the person who opened it.
That person's own personal grant is used, or a connect card is addressed
to that person. Another member's personal grant is never selected, and
that member gets no card.
- The opener is recorded on the tool invocation (server-written
`policyExplanation.sessionOpenedByUserId`) and restored when an approved
action runs. An approved call from that session therefore uses the same
person's grant.
- A guard after grant resolution refuses a user-owned grant of another
person with `403` and `reasonCode: personal_grant_owner_required`, as
defense in depth.
- Saved-call replay is scoped to the opener: idempotency keys get an
opener suffix for such sessions, and approval replay matches only
invocations recorded with the same opener. The lookup of keys saved
before this change still runs: a saved call that can be attributed to
the same person replays, one attributed to another person does not, and
one that cannot be attributed returns the existing
`legacy_tool_idempotency_unverifiable` conflict instead of running the
write again.
- Long-running provider tasks (`tool_mcp_tasks`) record the opener in a
new `created_by_user_id` column (same migration) and restore it on each
background poll, so the task keeps the opener's grant and is attributed
to the opener.
- Managed GitHub identity selection uses the opener, in the first and
the fallback selection.
- A call attaches to an existing long-running provider task only when
the task uses the same grant the call resolves to. On a personal grant
it must also be the same person (an agent session matches only tasks
with no opener; the grant owner may also collect a legacy task with no
opener). On a shared grant any person may collect. The wake for a
finished task now carries the task id, so the agent's continuation
resolves the opener's grant and collects the result instead of calling
the provider again.
- `POST /api/tool-gateway/sessions` checks the existing `agent:wake`
permission for a board caller, the same check as invoking the agent.
- Agent-opened sessions do not set the column, so agent runs and the
recovery of interrupted runs do not change.
- Document the rule in `doc/MCP-ACCESS-GOVERNANCE.md`.
- I checked the sibling routes. Named gateway tokens minted by a person
need `tools:admin` and carry no responsible person. Board test calls and
MCP app view calls already run as the caller. Stored MCP task
continuations stay pinned to the grant they started with.

## Verification

- New route tests in `server/src/__tests__/tool-gateway.test.ts`:
- Three members, two with personal grants, on a run that belongs to the
first. A session opened by the second member uses only that member's
credential. The run owner's session and an agent-opened session use the
run owner's credential. A member with no grant gets `409
user_authorization_required`, the card is addressed to that member, and
the remote server gets no request. A reviewed call from the second
member's session, once approved, runs with that member's credential. The
same write from two people's sessions runs once for each person, and
only the same person's retry replays.
- A pre-upgrade saved write retried by the same person replays (or
conflicts when it cannot be attributed) and never reaches the provider
twice; another person's identical write runs.
- `mcp-tasks.test.ts`: a person-started task keeps the opener's grant
through a background poll; an agent retry never receives that task's
result and keeps its own task; the continuation after a wake collects
once with no new provider call; on a shared grant another person
collects the task, including a task started before openers were
recorded.
- `tool-gateway-service.test.ts`: an opener with their own managed
GitHub grant uses it; an opener without one is refused and the run
owner's grant is never used.
  - A viewer cannot open a session for the agent.
- Before the fix, the second member's session used the run owner's
credential, and the viewer got `201`. Both tests pass now.
- `npx vitest run src/__tests__/tool-gateway.test.ts
src/__tests__/connection-management.integration.test.ts
src/__tests__/mcp-tasks.test.ts`: with `tool-access-service.test.ts` and
the policy tests, 833 tests pass.
- `tsc --noEmit` for `server` passes.
- `pnpm verify` exits 2 because a global CI input (a doc) changed.
Required CI gives the broad coverage.

## Risks

- A person who opened a session for another member's run used that
member's personal grants before. Now the session uses the opener's own
grants. This was not an intended flow. Shared connections and agent runs
do not change.
- A person-opened session that repeats exactly the same side-effecting
call an agent session already made in the same run gets a `409` conflict
instead of a second write, because that earlier call has no recorded
opener. Use a new explicit idempotency key for an intentional repeat.
- The migration only adds nullable columns. Sessions and review requests
created before this change have no opener record and keep the previous
behavior until they expire (15 to 60 minutes).

- Follow-up, out of scope: in the experimental MCP Tasks path, a call
with a new explicit idempotency key and the same arguments still
attaches to the same person's open task under the same grant. That is
the existing de-duplication for every caller and does not depend on the
opener rule.

## Model Used

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

## Checklist

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

> - Paperclip is the open source app people use to manage AI agents for
work
> - The built-in Google Workspace connector gives agents Gmail, Drive,
Docs, Sheets, Slides and Calendar actions through one connection
> - Google's hosted Workspace MCP servers are a Developer Preview, so
Paperclip cannot offer them to the public
> - Paperclip has its own REST tool set for all 36 allowlisted actions,
but every service still sent its calls to Google's MCP servers
> - The owner decided on 2026-11-23 to launch all six services on REST
now and to live-test on the staging tester after deploy
> - This pull request switches the six services to `paperclip_rest` and
fixes what the switch breaks
> - The benefit is that the connector no longer depends on Developer
Preview servers, and agents get all 36 actions, including the two Gmail
actions Google's live server did not offer

## Linked Issues or Issue Description

Refs #22016 (the transport switch), #22000, #22014, #22017, #22027,
#22028, #22029 (the REST tool set).

**Subsystem affected**
Built-in Google Workspace connector (`google-workspace`,
`workspace.all`): transport setting, catalog publication, tests and
docs.

**Problem or motivation**
All six launch services used Google's hosted MCP servers. These servers
are a Developer Preview and are not available to the public. Google's
live Gmail MCP server also did not offer `gmail__list_threads` and
`gmail__search_messages`.

**Proposed solution**
Set Gmail, Drive, Docs, Sheets, Slides and Calendar to `paperclip_rest`
in `GOOGLE_WORKSPACE_TOOL_TRANSPORT`. Keep Chat, People and Search on
`google_mcp`. Fix the catalog refresh so that an existing connection
keeps its actions active after the switch.

**Alternatives considered**
Switch one service at a time after a live test (the Nov 17 rule). The
owner replaced this rule on Nov 23: switch all six now and fix forward.

**Roadmap alignment**
This is the planned launch step for the Google Workspace connector. It
does not overlap other core work.

## What Changed

- `packages/shared/src/google-workspace-connectors.ts`: set `gmail`,
`drive`, `docs`, `sheets`, `slides` and `calendar` to `paperclip_rest`.
`chat`, `people` and `search` stay `google_mcp`.
- Connections saved before the switch keep Google's MCP definitions in
their catalog. Two changes make them work with no user action:
- New resolver `paperclipDefinedTool(connection, toolName)` in
`server/src/services/connectors/paperclip-defined-tools.ts` (typed
result). It is the one place that says which tools are
Paperclip-defined; for a `google-workspace` connection it calls
`googleWorkspaceRestToolDefinition` in the dispatch adapter, which
returns the REST definition when the service is on `paperclip_rest`.
- `server/src/services/tool-gateway.ts`: when the gateway lists a
connection's tools, it takes the input schema, output schema,
description and annotations of a Paperclip-defined tool from the
resolver, not from the saved row. Routing and the advertised definition
read the same transport setting in the same process. This is an
in-memory lookup, so it adds no request to the turn start. Example: an
agent gets the REST `docs__update_doc` schema, where
`writeControl.requiredRevisionId` is required, not Google's schema,
where it is optional.
- `server/src/services/tool-access/catalog/publication.ts`: catalog
publication asks the same resolver. It never holds a Paperclip-defined
action for review, and it clears the review hold (`quarantined`,
`pending_review`) of an action held only because a remote definition
changed. Clearing the hold does not count the action as new, so it is
never added to the profile: Off stays Off and Ask first stays, also for
a held action. Only actions the connection never had (Gmail
`list_threads` and `search_messages`) get the default for new actions.
Before this fix, a refresh after the switch put every action of an
existing managed connection into `pending_review` (10 of 10 in the
regression test).
- `server/src/__tests__/google-workspace-rest-transport.test.ts`: the
fake Google now answers the Docs, Sheets and Slides REST hosts and the
Drive and Calendar paths. New tests:
- The transport map has exactly the six launch services on
`paperclip_rest`.
- A full read and write grant lists exactly the 36 allowlisted actions
(with `gmail__list_threads` and `gmail__search_messages`) and sends no
MCP request. A read-only grant lists the 23 read actions. Gmail, Drive
and Calendar group grants list exactly their actions.
- One read and one write per service run through the real `executeTool`
path on REST with the default policy (no approval request). Each call
records the invocation and the `call_completed` event with the
connection ID (the "Delete data" bookkeeping keys), and audits the
protocol `Google Workspace REST` with the service endpoint.
- Injected instructions in Docs, Sheets, Slides, Drive and Calendar REST
results are blocked.
- An existing connection discovered over MCP keeps its actions active
after the switch and can call the new Gmail actions.
- Migration without refresh: a connection saved with Google's MCP
schemas (`update_doc` with `writeControl` optional) advertises the REST
schemas after the switch with no refresh, and `read_doc` then
`update_doc` with the revision succeed over REST.
- The first refresh after the switch releases an action held for
`pending_review`, keeps an Off action unlisted and keeps Ask first
(`approval_required`).
- An action that is both Off and held stays Off, and one that is both
Ask first and held stays Ask first, after the switch and after two
refreshes.
  - The MCP-path test pins Gmail and Docs to `google_mcp` explicitly.
- `server/src/__tests__/helpers/google-workspace-transport.ts`: new
helper `useGoogleMcpTransport()`. Tests whose fixtures act as Google's
MCP servers use it (`tool-access-service`, `tool-gateway-service`) or
pin the transport in `beforeAll`
(`google-workspace-injection-screening`). These tests still cover the
MCP path, which stays available for Chat, People, Search and a switch
back.
- `packages/shared/src/google-workspace-connectors.test.ts`: assert the
new transport map.
- Docs: `doc/connections/GOOGLE-WORKSPACE.md` and the REST folder
`README.md` say that the six services run on REST.
`doc/memory/google-connector-memory.md` has three dated Nov 23 decisions
(all six switched to REST, writes default to Allowed, image-by-URL
inserts allowed), and the two items are removed from "Still open".

## Verification

- Red: after the flip, 50 tests failed in four files because their
fixtures act as Google's MCP servers. These are fixture assumptions, not
product bugs.
- Red: without the gateway change, the migration test gets Google's
saved schema; without the publication change, the held action stays
`quarantined`; without excluding released rows from the new-action
default, the Off and held action comes back. All green with the fixes.
- Red: the new test "keeps an existing connection's actions usable when
its services move from Google's MCP servers to REST" failed before the
`publication.ts` fix: 10 catalog entries were `quarantined` with
`pending_review`. Green after the fix.
- `cd server && npx vitest run
src/__tests__/google-workspace-rest-transport.test.ts
src/__tests__/google-workspace-injection-screening.test.ts
src/__tests__/tool-gateway-service.test.ts
src/__tests__/tool-access-service.test.ts
src/services/google-workspace-rest-dispatch.test.ts
src/google-workspace-rest-tools`: with
`connection-management.integration.test.ts` added: 60 files, 2232 tests
pass. `google-workspace-rest-transport.test.ts`: 52 tests pass.
- `cd packages/shared && npx vitest run
src/google-workspace-connectors.test.ts`: 14 tests pass.
- `npx tsc -p server/tsconfig.json --noEmit`: no errors.
- Trace of a read (`gmail__get_message`) and a write
(`gmail__create_draft`) through `executeTool` in
`server/src/services/tool-gateway.ts`: policy decision and invocation
record (13723, 13731), approval gate (13820), `call_allowed` audit
(13885), dispatch to `executeRemoteHttpTool` (13915), prompt-injection
screening of the result (13964), `call_completed` event and audit
(14022, 14044), failure audit (14187). In `executeRemoteHttpTool` the
grant scope check (8172) runs before the REST branch (8276), which
rechecks the current grant and returns before any MCP session, MCP Task
or elicitation code. The REST adapter
(`google-workspace-rest-dispatch.ts`) calls `google-http.ts` only
through the gateway's guarded fetch.
- Not verified: calls against real Google. The live test on the staging
tester runs after deploy.

## Risks

- Real Google answers can differ from the fixtures. The REST tools are
not yet run against real Google. The live test on the staging tester
runs after this deploys, and problems are fixed forward.
- The OAuth client on the staging tester is marked for AI agents and was
only used through MCP. If Google refuses REST calls from that client,
all six services fail on the tester until the client changes.
- Existing connections keep their stored MCP schemas until a catalog
refresh, but agents receive the REST definitions at once. The stored
risk level of the four update actions stays `write` until that refresh,
then becomes `destructive`. The two new Gmail actions appear after a
refresh.
- Input differences between Google's MCP schemas and the REST tools are
listed in the REST folder `README.md` ("Input differences an agent meets
after a switch"). Agents receive the REST schemas, so these differences
are visible to them. No `tools/list` from Google's servers is recorded,
so the check uses Google's published references.
- Accepted risk (owner decision, 2026-11-23): Docs and Slides edits may
insert an image from any public web address. Google, not Paperclip,
fetches the address, and Paperclip's own requests still go only to the
allowed Google hosts. The residual risk is that an agent could put data
in the address it chooses. Links to Drive or Docs files stay refused.
- Update actions (`update_doc`, `update_presentation`,
`update_spreadsheet`, `update_event`) are labelled destructive on REST,
as decided on Nov 17. This does not add an approval step: write actions
stay Allowed by default.
- A switch back to `google_mcp` stays possible with a one-line change.
The MCP path tests still run.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude
Code with tool use (shell, file edits, test runs).

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] 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 13:12:16 -06:00
DottaandClaude Opus 5.5 e856a607ed fix(cloud): name why an online workspace source scope is unproven (#22644)
## 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
> - Before a Git or managed workspace moves online, the server must
prove which tasks and projects can write its files
> - Staging stacks stay blocked with many
`online_workspace_source_scope_unproven` workspaces after repeated
passes
> - The proof has more than 30 separate checks, and the pass does not
say which check failed
> - This pull request names the failed check for each workspace
> - The benefit is that the next pass on a blocked stack shows the exact
cause, so the right fix can follow

## Linked Issues or Issue Description

Refs #22270, #22294

**What happened?**
After repeated online passes, staging stacks report
`workspaces:online_workspace_source_scope_unproven` for 26 to 49
workspaces each. The code does not say which part of the source proof
failed. Most of the same workspaces also report
`overlapping_workspace_requires_maintenance`, because a workspace
without a proven scope cannot treat its Git siblings as one unit.

**Expected behavior**
The pass names the part of the source proof that failed for each
workspace.

**Steps to reproduce**
1. Create a nested Git wrapper workspace with a linked worktree.
2. Remove the linked worktree directory without `git worktree prune`.
3. Run the online inventory. It reports only
`online_workspace_source_scope_unproven`.

## What Changed

- `explainOnlineWorkspaceSource` and `explainOnlineOrdinarySource`
return `{ unproven: <code> }` for each failed check.
`inspectOnlineWorkspaceSource` and `inspectOnlineOrdinarySource` keep
their old `null` result.
- Inventory returns `sourceScopeUnproven` with the code. The `reasons`
list does not change.
- The online pass reports the code as `workspaces:source_scope_<code>`
next to `workspaces:online_workspace_source_scope_unproven`.
- The linked-worktree reader throws `workspace_git_link_stale` when a
registered worktree directory is gone, and
`workspace_git_links_exceeded` above 256 links. Both still reject the
proof.
- Codes include `git_link_stale`, `git_link_unregistered`,
`git_links_unreadable`, `member_status_unsupported`,
`member_task_binding_missing`, `member_locator_mismatch`,
`member_git_expiration_pending`, `source_keys_exceeded`,
`members_exceeded`, `foreign_alias`, `companion_recovery_unresolved`,
`companion_copyback_unresolved`, `ordinary_member_nested` and others.

## 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/workspace-git-source-roots.test.ts
src/services/online-durable-data-migration.test.ts
src/services/online-durable-data-migration-postgres.test.ts
src/services/finalized-workspace-recovery-migration.test.ts` (embedded
PostgreSQL): 7 files, 407 tests passed.
- Red/green: the linked-worktree test now checks the code for five cases
(unregistered, wrong backlink, wrong pointer, symlinked backlink,
stale). On `origin/master` the result has no `sourceScopeUnproven`
field. The new pass test fails on `origin/master` because the pass has
no `source_scope_` key.
- `pnpm --filter @paperclipai/server typecheck`: passed.

## Risks

- Low risk. No proof accepts more than before. Each check returns the
same accept or reject result. Only the reported code is new.
- The pass result gets new `workspaces:source_scope_<code>` keys.
Readers that count deferral keys see more keys.

> 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 12:56:12 -06:00
DottaandClaude Opus 5.5 348749305c fix(connections): keep managed sign-in when Paperclip Cloud is busy or unreachable (#22662)
<!-- 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
> - On Cloud workspaces, connectors such as GitHub use managed sign-in
through Paperclip Cloud
> - Paperclip asks the Cloud connector broker which sign-ins this
instance has and whether its registration is active
> - When the broker rate-limits or fails that check, Paperclip treats
the failure as "no Cloud sign-ins" and "not registered"
> - The GitHub card then says "Add key", and the connect screen offers
self-hosted Cloud registration, which cannot succeed on a Cloud
workspace
> - This pull request keeps the last answer Cloud confirmed when the
broker does not answer, and shows a retry instead of registration
> - The benefit is that a busy or unreachable broker no longer changes
what the user sees, or sends them into a setup flow that cannot work

## Linked Issues or Issue Description

**What happened?**
On a production Cloud workspace, the GitHub card on the Connectors page
said "Add key" instead of "Connect". On the GitHub connect screen,
"Connect with Paperclip" failed with "Paperclip Cloud enrollment could
not be started". On another production workspace, "Continue to GitHub"
failed with "Internal server error".

**Steps to reproduce**
1. Open Connectors on a Cloud workspace while the Cloud connector broker
returns 429 to the workspace's signed requests.
2. Look at the GitHub card. It says "Add key".
3. Open Connect GitHub. The self-hosted registration card shows. Its
button fails.

**Expected behavior**
The card says "Connect". A broker that is busy or unreachable gives a
retry, not a registration flow that cannot succeed.

**Root cause**
The broker rate-limited signed requests from production stacks (`429
RATE_LIMITED`; Sentry shows it from 8 production stacks in 7 days, and
none on staging). The fix for that is in
paperclipai/paperclip-cloud#1751. In this repository,
`getCapabilities()` mapped every error to an empty list and cached it
for 60 seconds. The enrollment status check mapped every error to
`unverified`, and the connect screen treated `unverified` like "not
registered".

Refs paperclipai/paperclip-cloud#1751

## What Changed

- `paperclip-cloud-connector.ts`: a 429, a 5xx, or an unreachable broker
is now a "no verdict" failure
(`isTransientPaperclipCloudConnectorError`).
- On a "no verdict" failure, capability and instance-status checks
return the last answer Cloud confirmed for this connector identity.
`invalidatePaperclipCloudConnectorCapabilities()` clears those saved
answers.
- `paperclipCloudConnectorCapabilitiesFromEnv` keeps an unanswered check
for only 5 seconds, not 60. Gallery reads soon ask Cloud again, but a
failing broker does not get one request per read.
- `paperclip-cloud-connector-status.ts`: when Cloud does not answer the
status check (429, 5xx, or network), the status is the new
`unreachable`. Incomplete managed settings now report `misconfigured`:
the connect screen and the Connections banner tell the user to ask their
administrator, because registration cannot run there. `unverified` stays
for a saved identity that belongs to another broker, which keeps the
registration step.
- `Connections.tsx`: the Cloud banner shows a message without the Enable
button for `unreachable` and `misconfigured`.
- A Cloud rejection, or a confirmed removed or suspended registration,
clears the saved sign-ins and the gallery's cached list. An unreadable
answer (a non-JSON body) or a 408 counts as no verdict. An answer from a
request that started before an invalidation is not saved.
- `ConnectionSetupFlow.tsx`: when the Cloud status is `unreachable`, the
screen shows "Paperclip couldn’t reach Paperclip Cloud to start GitHub
sign-in. Try again in a moment." with a Try again button. It no longer
offers registration. Try again reloads both the gallery and the Cloud
status.

## Verification

- New file
`server/src/services/paperclip-cloud-connector-saved-answers.test.ts` (7
tests): the last confirmed sign-ins and status are kept through 429 and
503 responses; a busy broker with no earlier answer gives no verdict; a
rejection or removal is not undone by a later 429; a late answer does
not replace a newer one; a 429 capability check is kept for only 5
seconds; `unreachable` and `unverified` are reported separately. They
fail without this change and pass with it.
- `ui/src/pages/apps/AppsConnect.test.tsx`: an `unreachable` status
shows the retry and not "Connect with Paperclip"; an `unverified` status
still shows registration.
- Server connector tests (saved-answers, connector, enrollment): 94/94
pass. Cloud-related AppsConnect tests: 4/4 pass.
- `pnpm verify` selected a broad set of server tests and was stopped
(exit 143) under machine load. The Cloud-floor tests that it reported as
failing pass when run alone (`company-cloud-floor.test.ts` 3/3). CI
covers the full suite.

## Risks

- Low risk. The saved answers live in memory and are cleared by the
existing invalidation and by a restart. A workspace whose Cloud
registration was removed still sees that on the next confirmed answer: a
401 maps to `removed` as before.
- A saved `active` status can stay in use while the broker keeps
failing. This is intended: a failure gives no new information.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use
(shell, browser, Sentry reads).

## 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 12:55:29 -06:00
DottaandClaude Opus 5.5 fd6317de23 fix(cloud): name a retained runtime skill run whose bundle left the disk and keep saving the runs after it (#22648)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - A hosted server copies the runtime skill bundles that retained runs
still need to shared storage before it moves to a volume-free shape
> - The online pass copies them a page at a time with
`migrateRuntimeSkillAssets`
> - The page fails at the first run whose bundle is no longer on the
disk, so the later runs on that page are never saved and the pass names
only the first failure
> - The offline migration continues past such a run, collects it as
unsaved, and refuses at the end
> - This pull request gives the online page the same behavior and names
each unsaved run
> - The benefit is that the pass saves every bundle it can and reports
each one it cannot

## Linked Issues or Issue Description

Refs #22190, #22294, #22641

**What happened?**
On staging, one stack reports `runtime_skill_assets_require_migration`.
Its passes showed
`runtime_skill_assets:runtime_skill_source_absent:missing` as a
whole-page failure: the runs after the first missing bundle were not
visited.

**Expected behavior**
The page saves every run whose bundle is on the disk and names each run
whose bundle is gone.

**Steps to reproduce**
1. Keep two retained native runs with unversioned skill bundles. Remove
the bundle of the first run from the disk.
2. Run `migrateRuntimeSkillAssets` with `apply`.
3. See that it throws `runtime_skill_source_absent:missing` and does not
save the second run.

**Additional context**
#22641 already makes every blocker in the pass result carry a code. This
pull request was reduced to the runtime skill page after #22641 merged.

## What Changed

- `migrateRuntimeSkillAssets` returns `{ status: "unsaved", code:
"runtime_skill_source_absent:<reason>" }` for a run whose bundle is not
on this disk, and continues. Other errors still stop the page, as in the
offline migration.
- The result type is a discriminated union, so `unsaved` always carries
a code.
- The online pass reports each unsaved run as
`runtime_skill_assets:<code>`.
- `migrate-skill-packages --phase=runtime-assets` prints the unsaved
rows and exits 1 when any run stays unsaved.

## Verification

- Red: `cd server && npx vitest run
src/services/online-durable-data-migration.test.ts
src/__tests__/runtime-skill-preservation.test.ts` failed 2 new tests:
the real page (embedded PostgreSQL, real bundle files) threw
`runtime_skill_source_absent:missing` before it saved the next run, and
the pass had no code for unsaved runs.
- Green: the same files and
`online-durable-data-migration-postgres.test.ts` pass (42 tests).
- `pnpm --filter @paperclipai/server typecheck` passes.
- Local `pnpm verify` selects most of the suite for this change (2,979
of 3,855 files). Required CI supplies that coverage.

## Risks

- No migration rule changes. A run whose bundle is gone still blocks the
move, online and offline.
- The maintenance command now exits 1 when a run stays unsaved, as it
did before when the page threw.

> 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 12:51:59 -06:00
DottaandClaude Opus 5.5 949bc3765c fix(cloud): preserve a settled harness backup whose session is not selected, as offline does (#22647)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - A hosted server copies its Runner harness backups to shared storage
before it moves to a volume-free shape
> - The online pass copies a settled backup only when exactly one task
session selects the backup's native session
> - Some stacks stay blocked with
`native_harness:source_session_not_selected`, but the offline migration
publishes the same backup
> - A selected session whose backup source is not on the disk is
reported with no code at all
> - This pull request applies the offline outcome online with a
selection fence, and names the missing-source case
> - The benefit is that these stacks can move, and the native harness
blocker always says why it remains

## Linked Issues or Issue Description

Refs #19715, #22294

**What happened?**
On staging, two stacks stay ineligible with
`native_harness_backups_require_migration`. Each online pass defers one
backup as `native_harness:source_session_not_selected`. That code means
that no task session, or more than one, points at the backup's native
session.

**Expected behavior**
The online pass gives a settled backup the same outcome as the offline
migration. The offline migration publishes the backup whether or not a
session selects it.

**Steps to reproduce**
1. Keep a sealed backup of a failed native run with a settled
coordinator and a verified lease stamp.
2. Delete the task session that selects it (or add a second one for the
same native session).
3. Run the online pre-copy. It defers the backup as
`source_session_not_selected`. The offline migration publishes it.

**Additional context**
The selection check exists so that publication does not race a change of
the selected session. It does not need exactly one selection for that.

## What Changed

- The settled-source owner records the exact set of task sessions that
select the native session: none, one or several. Publication rechecks
the same set under a share lock. A changed selection keeps the source
local (`source_changed`), as before. The `session_not_selected` reason
is removed.
- The run, coordinator, task, lease, finalization lock and payload
checks do not change.
- After the source walk, the pre-copy lists the selected sessions that
still need a backup. A selected scope with no source on this disk is
reported as `selected_source_absent`. Before, it produced no outcome.

## Verification

- Red (embedded PostgreSQL, real files): `cd server && npx vitest run
src/services/native-runtime/native-harness-online-preservation.integration.test.ts`
failed 4 new tests: unselected and ambiguous sources were deferred, and
a missing selected source produced no outcome.
- Green: the same file passes (20 tests). New tests show that an
unselected or ambiguous source publishes, the run and task sessions do
not change, the backup restores the exact bytes, and a selection that
appears before publication keeps the receipt pending.
- `native-harness-backup-storage.integration.test.ts`: the former
`source_session_not_selected` expectation now expects publication by the
settled-source owner (activity `native_harness_backup_preserved`), not
by the offline owner.
- `npx vitest run` of all 8 files that use these owners (startup gate,
prestage command, filesystem independence, obligations, storage, online
preservation): 240 tests pass.
- `pnpm --filter @paperclipai/server typecheck` passes.
- `pnpm verify` result is in a comment below.

## Risks

- A settled backup of an unselected session now moves to shared storage
online. The offline migration already does this, and the source files
stay on the disk.
- The pre-copy now runs the obligation scan once after the source walk.
This is the same scan that the eligibility read runs.
- Pass deferral codes change:
`native_harness:source_session_not_selected` is gone, and
`native_harness:selected_source_absent` is new.

> 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 12:51:32 -06:00
DottaandClaude Opus 5.5 574448e910 fix(server): apply the issue interaction resolution policy to direct tool review decisions (#22656)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - When an agent's tool call needs review, Paperclip creates a tool
action request and an approval card on the task
> - A person can decide it on the card (the issue thread path) or
through `POST /api/tool-gateway/action-requests/:id/approve|decline`
> - The issue thread path applies the interaction resolution policy, but
the direct routes checked only company membership
> - So the two paths could give different answers for the same review,
for example in another member's private chat
> - This pull request puts the human rule for tool reviews in one shared
function and applies it to every human decision on a pending review
> - The benefit is that the direct routes and the card always agree on
who can decide a tool review

## Linked Issues or Issue Description

Refs #22635

**What happened?**
The direct approve and decline routes for tool action requests skipped
the issue-interaction resolution policy. A member could decide a tool
review that the issue thread path refuses, for example a review in a
chat conversation that another member owns.

**What did you expect to happen?**
Both paths use the same policy and give the same result.

**Steps to reproduce**
Open a chat conversation as one member, let the agent request a reviewed
tool call, then approve it through the direct route as a different
member. The new test covers this case.

**Impact**
Access-control hardening for tool reviews.

## What Changed

- Add `evaluateHumanToolReviewResolution`,
`assertHumanToolReviewResolution` and
`conversationInteractionResponderAllowed` to
`server/src/services/issue-thread-interaction-resolution.ts`. The rule
applies the personal-conversation visibility rule, the conversation
owner rule and the existing audience evaluator
(`evaluateIssueThreadInteractionResolverAudience`, as a governed
action).
- `commitToolActionReview` applies this rule inside its decision
transaction, on the issue and interaction rows it already locks. Both
the issue thread path and the direct routes reach it, so one rule
decides for both.
- The direct approve and decline routes call the same rule function
first, for pending and settled reviews, before any state change or
detail is returned (for example a cancelled request after a signature
failure, expiry, or formal approval details). The in-transaction check
stays the authoritative one.
- A settled request with no task or interaction can be read only by the
person who requested it; others get `404`. Only the explicit internal
recovery flag skips the check.
- A decision with no user identity is refused with
`human_review_required`; the code no longer substitutes a placeholder
identity.
- The issue thread route uses `conversationInteractionResponderAllowed`
for its existing conversation owner check.
- Recovery of an already approved review passes an explicit internal
flag and skips the human check, so interrupted executions still resume
with no user action.

## Verification

- New table test in `server/src/__tests__/tool-gateway.test.ts` mounts
the real issue routes and the gateway routes on one database, for a chat
owned by one member, a personal dashboard conversation and an ordinary
task. For approve and decline it compares both paths for the owner and
another member. It also checks settled reviews through the direct route,
the recovery of an approved review, that a non-owner cannot cancel a
review with an unverifiable signature or see expiry details, that a
decision without a user is refused, and that a detached settled request
is visible only to its requester. Before the fix the direct route let
the other member approve a chat review and the action ran (`200`,
`executed`). After the fix both paths refuse the other member for chats
(`403`) and personal dashboards (`404`), both allow the other member for
ordinary tasks, and both allow the owner.
- `npx vitest run` on `tool-gateway`, `issue-thread-interaction-routes`,
`agent-conversations`, `connection-management.integration`, `mcp-tasks`
and `prompt-injection-gateway`: 497 tests pass.
- `tsc --noEmit` for `server` passes.

## Risks

- A member who is not the owner of a private chat can no longer approve
or decline its tool reviews through the direct routes. The card already
refused this.
- Low risk otherwise. Ordinary task reviews have no addressee and stay
open to non-viewer members, as before.

## Model Used

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

## Checklist

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

> - Paperclip is the open source app people use to manage AI agents for
work
> - A hosted server moves from a volume to a volume-free shape without
an outage
> - Before the move, Cloud reads `GET
/api/instance/ephemeral-enrollment/eligibility`, and the stack moves
only when the read has no blockers
> - On two staging stacks the read answers HTTP 500, so Cloud shows only
"eligibility unavailable: HTTP 500"
> - Each durable-data check in the read can throw, and one throw fails
the whole read without a reason
> - This pull request makes each check that throws report a named
blocker with the owner's code
> - The benefit is that a stack that cannot move always says which check
stopped it and why

## Linked Issues or Issue Description

Refs #22240, #22294, #22337

**What happened?**
On current Core, the eligibility read answers HTTP 500 for some hosted
stacks. The online durable-data pass also fails, because it reads the
same eligibility at the end of each pass.

**Expected behavior**
The read always answers. When a check cannot finish, the read reports a
named blocker, and the move stays blocked.

**Steps to reproduce**
1. Keep a failed Runner run whose session is selected and whose local
controller file has a second hard link (or another source that the
controller check refuses, such as an execution input that no longer
parses).
2. Call `readOnlineEphemeralEnrollmentEligibility`.
3. See that it throws `native_controller_migration_unsafe_source`. The
route answers 500.

**Additional context**
Every check in `readEphemeralServerDataEligibility` can throw: the
native controller scan reads files and parses saved execution input, the
harness scan reads files, and the other checks query the database. The
controller scan is the first one that throws on old Runner state.

## What Changed

- `readEphemeralServerDataEligibility` runs each check through one
guard. A check that throws adds `<area>_check_failed`, plus `:<code>`
when the error message is a code such as
`native_controller_migration_unsafe_source`. The guard logs the error.
- The same blockers reach the startup gate, the offline migration and
online preparation. Each of them still refuses, as before, but now with
the named blocker instead of the raw error.

## Verification

- Red: `cd server && npx vitest run
src/services/native-runtime/native-controller-migration.integration.test.ts
-t eligibility_unreadable` failed with `Error:
native_controller_migration_unsafe_source` thrown from
`readEphemeralServerDataEligibility` (embedded PostgreSQL, real
controller file with a second hard link).
- Green: the same test passes. The read returns
`native_controllers_check_failed:native_controller_migration_unsafe_source`,
the online read returns `eligible: false` with that blocker, and the
controller file is unchanged.
- `npx vitest run src/__tests__/ephemeral-server-data.test.ts
src/services/ephemeral-enrollment.test.ts
src/__tests__/runtime-skill-preservation.test.ts` and the
`volume_free_owner` controller scenario pass.
- `pnpm --filter @paperclipai/server typecheck` passes.
- `pnpm verify` result is in a comment below.

## Risks

- Low risk. A check that throws still blocks the move, the startup gate
and the offline migration. Only the shape of the refusal changes: a
named blocker instead of an exception.
- Cloud receives new blocker names of the form
`<area>_check_failed[:code]`. Cloud shows unknown blockers as they are
and does not move the stack.

> 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 12:50:27 -06:00
DottaandClaude Opus 5.5 ba1b0585bc fix(server): send deployment OAuth client secrets only to the token endpoint they are configured for (#22649)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - App connections sign in with OAuth, and an operator can set a
deployment-wide OAuth client with `PAPERCLIP_TOOL_OAUTH_*` variables
> - The server picked that client by a provider name, and a connection's
own settings could set both the provider name and the token URL
> - So a deployment client secret could go to a token URL that the
deployment did not choose
> - A deployment secret must go only to the endpoint of the app it was
set up for
> - This pull request pins each deployment client to the token endpoint
that its app definition fixes, and fails closed for any other endpoint
> - The benefit is that member-entered or custom endpoints get only a
member-entered client

## Linked Issues or Issue Description

Refs #22635

**What happened?**
`configuredOAuthClientForConnection` returned the deployment client for
any connection whose provider name matched, or the unsuffixed client for
any connection. The token exchange then sent that client secret to the
connection's token URL.

**What did you expect to happen?**
A deployment client goes only to the token endpoint that its app
definition fixes. A custom endpoint needs a client that the member adds.

**Steps to reproduce**
Set a provider-specific deployment client. Create a custom connection
that names that provider and a different token URL, and start sign-in.
The new unit tests cover this case.

**Impact**
Secret-handling hardening for deployment OAuth clients.

## What Changed

- `configuredOAuthClientForConnection` now takes the token URL that the
caller will post to. It returns a deployment client only when the
connection comes from a real app definition, the provider is that app,
the method lists `customer` ownership, and the token URL equals the
method's `defaults.tokenEndpoint` (or, when the method fixes no token
endpoint, is on the exact host of its fixed server, discovery, metadata
or authorization URL).
- A pasted (custom) server never gets a deployment client, including the
unsuffixed one. It needs a client of its own, or CIMD or dynamic
registration.
- The token URL is required at every call site: start, callback,
connection refresh and grant refresh.
- When a deployment client exists but the endpoint does not match, and
the connection has no client of its own, sign-in fails with
`oauth_instance_client_endpoint_mismatch` and a clear message.
- Pin `defaults.tokenEndpoint` in the Asana and Railway definitions,
whose token endpoints are on another host than their MCP servers.
- Update `doc/connections/GENERIC-REMOTE-MCP.md` and
`doc/connections/CONNECTOR-PLAYBOOK.md`.

## Verification

- New `server/src/services/tool-access/oauth/client-settings.test.ts`
(16 tests): other hosts, a path that resolves elsewhere, plain HTTP,
vendor subdomains, another port, a missing URL, empty or padded gallery
markers, colliding host names, a custom connection that names a
provider, the unsuffixed client on a custom connection, and a connection
that names another app's provider all get no deployment client. Slack's
fixed endpoint, Notion's server host and the pinned Asana and Railway
endpoints still get it. These cases failed before the fix and pass now.
- `server/src/__tests__/generic-mcp-connection.test.ts` and the
machine-to-machine test in `tool-access-service.test.ts` now check that
a pasted server never receives the deployment client or secret. Both
failed before the fix. Two other pasted-server tests now use a client of
their own.
- A positive test sends the Slack deployment client to Slack's pinned
token endpoint, with its secret, and nowhere else.
- The connect route keeps the draft and returns `manualClientRequired`
with a plain reason when a deployment client cannot be used (route and
UI tests).
- `npx vitest run` on the OAuth service and connection tests: 686 tests
pass. Shared app-definition tests pass. `tsc --noEmit` for `server`
passes.
- `pnpm verify` exits 2 because a global CI input (a doc) changed.
Required CI gives the broad coverage.

## Risks

- A self-hosted deployment that used `PAPERCLIP_TOOL_OAUTH_*` for a
pasted server must add a client to that connection. Sign-in shows a
clear error instead of sending the secret.
- A gallery app with `customer` ownership whose token endpoint is on
another host than its fixed URLs needs `defaults.tokenEndpoint` to keep
using a deployment client. Asana and Railway are pinned here. Box,
Notion, PostHog, Sentry and Xero rely on the same-host rule: if their
discovery returns a token endpoint on another host, a deployment-wide
client is refused until the endpoint is pinned, and a client added to
the connection always works. A test lists these apps by name, so a new
app must choose. Gallery apps with a fixed token endpoint (Slack,
Linear, Google) do not change.

## Model Used

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

## Checklist

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

> - Paperclip is the open source app people use to manage AI agents for
work
> - Agents use tools through connectors: catalog connectors, custom MCP
servers, and aggregator gateways (Composio, Arcade, Executor) that reach
many apps
> - Connector telemetry sends every custom MCP connector as
`connector_key: "custom"`, and it sends nothing about apps behind an
aggregator
> - The team cannot see which services people add as custom servers, or
which aggregator apps people try to connect and which ones they finish
> - This pull request adds a reduced `server_domain` to the connection
events for custom connectors, and two aggregator app events
> - The benefit is a privacy-safe view of connector demand: no URL, no
subdomain, and no provider-controlled string leaves the installation

## Linked Issues or Issue Description

No issue exists. This follows the feature request template
(`.github/ISSUE_TEMPLATE/feature_request.yml`).

**Subsystem affected**

Server connector telemetry
(`server/src/services/connector-telemetry.ts`), the aggregator app sync
and setup paths
(`server/src/services/tool-access/catalog/aggregator-accounts.ts`), the
tool gateway, and the shared telemetry contract
(`packages/shared/src/telemetry`).

**Problem or motivation**

Connector telemetry sends every connector outside the first-party
catalog as `connector_key: "custom"`, and every app behind Composio as
the `composio` connector. Arcade and Executor apps are hidden the same
way. This hides which servers and apps people actually connect to. It
also hides what they try to connect and fail to connect. The team cannot
use telemetry to decide which connectors to add to the catalog or where
setup fails.

**Proposed solution**

For custom connectors only, send the registrable domain of the server
(`server_domain`), with IP, private, and local hosts reduced to
`private` and stdio servers to `stdio`. Send `connection.app_requested`
when a person or agent asks an aggregator to add an app, with the
result, and `connection.app_linked` when that app becomes connected. The
app is a slug from the checked-in aggregator catalog, or `other`. No
user-controlled string leaves the process.

**Alternatives considered**

Sending the full host was rejected: subdomains can name a customer or
tenant. Hashing the host was rejected: it cannot be read in an insight,
and short domains are easy to reverse. Sending the provider's toolkit
name was rejected: Executor and custom integrations use names that
people choose.

## What Changed

- Sync the generated telemetry contract. The telemetry backend registers
`server_domain` and the two new events first, so nothing is dropped as
unregistered.
- `server/src/services/connector-telemetry.ts`:
- `serverDomainForUrl()` reduces a configured address to its registrable
domain (ICANN public suffix plus one label, from `tldts`).
`mcp.smithery.ai/sse?token=…` becomes `smithery.ai`. IPs, loopback,
single-label hosts, non-ICANN or special-use suffixes (`.local`,
`.internal`, `.home.arpa`, `.onion`), non-HTTP schemes, and unparsable
values become `private`. A final pattern check makes sure nothing
URL-shaped can pass.
- `server_domain` goes on `connection.created`, `connection.updated`,
and `connection.invoked` only when `connector_key` is `custom`. Local
stdio servers send `stdio`. A remote connection with no address yet
omits it.
- `aggregatorAppTelemetrySlug()` returns a slug from the shared
aggregator catalog, or `other`. This is the same rule as
`connector_key`.
- `newlyLinkedToolkits()`, `emitAggregatorAppsLinked()`,
`emitAggregatorAppsRequested()`, and
`emitAggregatorAppRequestsFromToolCall()`. All are best-effort and never
throw.
- `aggregator-accounts.ts`: the Composio list check and the
Arcade/Executor inventory sync read the previous snapshot status before
the write. They send `connection.app_linked` only for a change to
`connected`. The Composio check sends it right after each saved row, so
a later app that fails in the same check does not lose it, and it
updates the stored status after each write, so an app named twice in one
check sends one event. The Composio upsert now returns its row, so a
write that loses to a newer observation sends nothing. App setup `start`
and account `add` send `connection.app_requested` (`origin: user`) with
`succeeded`, `needs_auth`, or `failed`.
- `tool-gateway.ts`: one call after the remote MCP response is parsed.
An agent's `COMPOSIO_MANAGE_CONNECTIONS` call with `add` sends one
`connection.app_requested` (`origin: agent`) per app.
`composioAddOutcomes()` parses the response once and reads each app's
own result node: connected is `succeeded`, its own sign-in link is
`needs_auth`, an error or no node is `failed`. A sibling's link never
counts; the response-wide link counts only when one app was added. An
Arcade tool call that answers with an authorization step sends
`needs_auth`.
- `connection-methods.ts`: `remoteEndpointValue()` shares the `url` →
`endpoint` → `remoteUrl` order with `remoteEndpoint()`.
- `server/package.json`: add `tldts` 7.4.10 as a direct dependency. It
is already in the lockfile through `tough-cookie`. The lockfile is left
to CI.
- Shared telemetry: typed helpers `trackConnectionAppLinked` and
`trackConnectionAppRequested`, `server_domain` on the three connection
helpers, retention class `operational_enum_count` for the new events,
and a "Connector Events" section in the telemetry README.

## New Dependency

`tldts` 7.4.10 (MIT) is added to `server/package.json`.

- Why: `server_domain` must be the registrable domain (eTLD+1), so
`mcp.example.co.uk` gives `example.co.uk` and not `co.uk`. That needs
the Public Suffix List. No runtime dependency in the repo parses it.
`new URL()` and `node:net` give only the hostname and IP detection.
Splitting on the last two labels is wrong for multi-part suffixes such
as `co.uk` and would leak or merge domains.
- Already in the tree: `tldts` 7.4.10 is in `pnpm-lock.yaml` through
`jsdom` → `tough-cookie`, a dev-only path. This PR makes it a direct
server dependency at the same version, so no new package is downloaded.
- Size: about 125 KB minified (`dist/index.cjs.min.js`), with one
dependency, `tldts-core` (same author). It bundles the suffix list, so
it does no network or file reads at run time.
- Maintenance: actively maintained (latest release this month), widely
used (it is the suffix parser in `tough-cookie`), with typed exports.

## Verification

- `pnpm exec vitest run src/services/connector-telemetry.test.ts`
(server): 65 pass, including a sibling's link, a top-level link with
several apps, and the one-app fallback. New cases cover domain reduction
(paths with tokens, userinfo, ports, uppercase, trailing dot, IDN,
`github.io` and `vercel.app` subdomains dropped), `private` for IPv4,
IPv6, loopback, `.local`, `.internal`, `.home.arpa`, `.onion`,
single-label, unknown suffix, `ftp:`, and non-strings, a payload check
that no part of a secret-bearing URL appears in any of the three events,
catalog-or-`other` for every provider, a check that every catalog slug
matches the registered `app` pattern, and the transition rule.
- `pnpm exec vitest run src/__tests__/composio-app-setup.test.ts
src/__tests__/aggregator-app-sync.test.ts` (embedded Postgres): 36 pass,
including an app named twice in one check (fails without the fix).
Composio: setup `start` sends one `needs_auth` request; refreshes while
the account is only initiated send nothing; activation sends exactly one
`app_linked` over three refreshes and a `complete`; an app saved before
a later app fails in the same check keeps its `app_linked`; an
unconfirmed `add` sends `failed`. Executor: two syncs send one
`app_linked`; a disconnect sends nothing. Agent requests: mixed per-app
results give `succeeded`, `needs_auth`, and `failed` separately.
- Red check: with the previous-status check or the domain reduction
removed, 13 of these tests fail.
- `pnpm exec vitest run src/telemetry` (shared): 46 pass, including the
real client sending `server_domain` and both new events.
- Related suites still pass: connector telemetry for tool access and the
gateway, Circleback parity, aggregator fallback, connection intents, MCP
protocol versions, MCP tasks, remote MCP connectors, remote MCP pending
(265 tests).
- `tsc --noEmit` reports no errors in the changed files.
- `tests/runner-e2e/source-sdk-public-inputs.json` is regenerated with
`node tests/runner-e2e/source-sdk-public-inputs.mjs <HEAD> --write`,
because it pins the shared telemetry files. `--check` and
`source-sdk-public-inputs.test.mjs` (13) pass.
- CI note: on d501fe5272, `General tests (server (5/12))` failed on a 15
s timeout in
`src/services/native-runtime/provider-pack-archive.test.ts`. That test
does not touch this change, and it passes locally (52/52). `Build` and
`e2e shard (2/8)` were cancelled by a runner shutdown. The next push
re-ran all three.

## Privacy Review

Privacy review: approved by repo owner (@cryppadotta) on 2026-11-23, for
sending the registrable domain of custom MCP servers, with domains seen
in fewer than 3 workspaces hidden in dashboards.

Privacy review requested. This is a Telemetry change under
`rules/data-paths.mdc`: it updates the generated contract and the
telemetry README, and it adds one reduced host value. Please confirm:

- `server_domain` is sent only for `connector_key: "custom"`. It holds
only the registrable domain. The path, query, port, credentials, and
subdomains are dropped in the app, and the registered schema pattern
rejects them too.
- IP, loopback, private, single-label, and special-use hosts send the
fixed value `private`. Local servers send `stdio`.
- `app` on the two new events is a slug from the checked-in aggregator
catalog, or `other`. The provider's toolkit string, app name, and
account name are never sent.
- `provider`, `origin`, and `outcome` are closed enums.
- Retention for the two new events is `operational_enum_count` (90
days).
- Analyses must hide domains seen in fewer than 3 workspaces.

## Risks

- Low product risk. Every emitter catches its own errors, and the
gateway call sits before existing control flow without changing it.
- Privacy: a self-hosted MCP server on a personal domain still sends
that domain. Analyses hide domains seen in fewer than 3 workspaces.
- `connection.app_linked` is best-effort. Two syncs for the same person
that run at the same time can both read the old status and send twice.
- Agent requests that fail before a response is parsed (HTTP error,
timeout) are not counted. Executor approval steps are not counted as app
requests.
- Each agent retry of a call that needs authorization sends one more
`needs_auth` request.

## Model Used

Claude Opus 5.5 (`claude-opus-5-5`) via Claude Code, with tool use and
code execution.

## Checklist

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

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 12:05:43 -06:00
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