Commit Graph
963 Commits
Author SHA1 Message Date
TonioandPaperclip d1207c31d4 Left-align wrapped Inbox filters with search (#22720)
## Thinking Path

> - Paperclip helps people manage agents and tasks.
> - The Inbox toolbar lets people search and filter decisions.
> - Its dropdowns wrap when the sidebar leaves too little room.
> - An automatic margin pushes the wrapped row away from Search.
> - This change distributes space between controls on the same row and
aligns wrapped controls with Search.

## Linked Issues or Issue Description

Refs #22675.

**What happened?**

At intermediate widths, Inbox filters wrapped onto a second row and left
a large blank space at its start.

**Expected behavior**

The first wrapped button lines up with Search.

**Steps to reproduce**

Open Inbox and narrow the content area until the filters wrap below
Search.

## What Changed

Use flexbox space distribution on the Inbox toolbar and clear the filter
group's automatic start margin.

## Verification

All 38 CoordinatorNeedsYou tests passed at 536c7385ce. Local browser
measurements during development confirmed aligned left edges at 320px
and 890px and a right-aligned filter group at 1200px.

## Risks

The layout depends on Search and the filter group being the toolbar's
two direct children.

## Model Used

OpenAI Codex (GPT-6), with code execution and browser verification.

## Checklist

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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-23 17:05:27 -08: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
fe2db1c32b feat(ui): show the Cloud Slack invitation in the workspace sidebar (#22702)
## Thinking Path

> - Teams use Paperclip to manage agents and their work.
> - Hosted teams can have a private Slack channel with the Paperclip
team.
> - A workspace member needs to know whether they can open the channel
or still need the owner's invitation.
> - Cloud supplies that information for the selected organization.
> - This change puts a Slack button in the sidebar footer. It opens a
dialog with the next action.

## Linked Issues or Issue Description

**Subsystem affected**

Workspace sidebar and the Cloud onboarding browser journey.

**Problem or motivation**

After setup, a user can lose track of the invitation to their
organization's private feedback channel.

**Proposed solution**

Show the invitation status in a dialog. Offer a channel link when Cloud
confirms the connection.

**Roadmap alignment**

This extends the existing hosted workspace navigation. The roadmap has
no separate item for this shortcut.

## What Changed

- Both sidebar variants use the existing portfolio request to show the
Slack shortcut when Cloud supplies invitation details.
- The icon uses grayscale at rest and brand colors on hover or keyboard
focus. The button has an accessible name and a tooltip.
- The Cloud onboarding journey selects Codex and confirms feedback
intent when the first-account welcome appears.
- Storybook covers pending and connected channels.

## Verification

- The sidebar suite passed 36 tests. The Cloud onboarding journey suite
passed 10 tests covering both the current and previous gateway layouts.
- The Storybook catalog regenerated successfully.
- In a local browser run, a fresh user completed signup, connected a
test model, hired an agent, opened its chat, and opened and dismissed
the Slack invitation. The test used a local Slack fixture.
- The incremental verifier selected broad CI coverage for the runner
journey change.

All applicable checks passed on `ea9779abda`. A GitHub runner shut down
during a server test shard. The shard and final verification gate passed
on retry. [CI
run](https://github.com/paperclipai/paperclip/actions/runs/45276376121/attempts/2)
· [Greptile review
(5/5)](https://github.com/paperclipai/paperclip/pull/22702#issuecomment-7115303606)

## Risks

An older Cloud service can omit the optional feedback field. In that
case, the sidebar keeps the existing layout. Cloud controls the channel
destination and the invitation state.

## Model Used

OpenAI GPT-6 in Codex, with repository tools and browser verification.

## Checklist

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

---------

Co-authored-by: Scott Tong <1504818+scotttong@users.noreply.github.com>
Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-23 14:38:55 -08: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
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
TonioandPaperclip 4e1d49067c Align Inbox, Tasks and Audit toolbar controls (#22675)
## Thinking Path

> - Paperclip helps people manage agents and tasks.
> - Operators switch between Tasks, Inbox, and Audit to review work.
> - Inconsistent menus and shifting controls make those pages harder to
use.
> - Shared dropdown components keep the controls familiar.
> - This change aligns the menus and keeps room for both Audit
descriptions.

## Linked Issues or Issue Description

**What happened?**

Inbox used native dropdowns. Menus could touch the edge of a phone
screen. The Audit scope control moved when its description wrapped.

**Expected behavior**

Menus keep at least 8px of clearance. Switching Audit scope preserves
the control position.

**Steps to reproduce**

Open each Inbox filter and the Tasks view and filter menus at 320px and
390px. Switch between Activity and Agent Actions on Audit.

## What Changed

- Use Tasks-style menus and shorter filter labels in Inbox.
- Give Inbox and Tasks menus 8px of collision padding.
- Align Audit segments and reserve space for the taller scope
description.

## Verification

- All 129 tests across the Inbox, Audit feed, Tasks page and filter
suites passed after rebase at 88a68f9594.
- Before rebase, browser checks covered mobile menu clearance and Audit
scope switching at 320px and 390px.

## Risks

Inbox filters now use keyboard-navigable menu buttons. This changes how
assistive technology announces the controls.

## Model Used

OpenAI Codex (GPT-6), with local code execution and browser
verification.

## Checklist

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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-23 13:32:14 -08: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
DottaandClaude Opus 5.5 7906db1ac9 fix(apps): title the Google AI connector "Google Antigravity and Gemini" (#22673)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The Connectors page lists the services and model providers that a
company can connect
> - The Google model-provider connector has the title "Google"
> - That title does not tell people that this connector is for Google
Antigravity sign-in and Gemini API keys. It is easy to confuse with the
Google Workspace connectors
> - This pull request changes the connector title to "Google Antigravity
and Gemini"
> - The benefit is that people can find the correct connector for their
Google AI accounts

## Linked Issues or Issue Description

**What existing behavior does this improve?**
The title of the Google model-provider connector on the Connectors page.

**Subsystem affected**
UI: the Connectors page (`/<company>/apps`) and the shared app
definition for `google`.

**Current behavior**
The connector title is "Google". The title does not name the products
that it connects, and people can confuse it with the Google Workspace
connectors.

**Proposed behavior**
The connector title is "Google Antigravity and Gemini".

**Reason and benefit**
People can find the correct connector for Google Antigravity sign-in and
Gemini API keys.

**Breaking changes**
None. The provider id, the app slug, and all stored values stay the
same.

## What Changed

- Change the `name` of the `google` app definition
(`packages/shared/src/app-definitions/google.json`).
  - Before: `Google`
  - After: `Google Antigravity and Gemini`
- These texts read the name, so they also change:
  - Card heading: `Google` -> `Google Antigravity and Gemini`
- Card button accessible name: `Connect Google` -> `Connect Google
Antigravity and Gemini`. The visible button text stays `Connect`.
- Setup screen heading: `Connect Google` -> `Connect Google Antigravity
and Gemini`
- The service name that new connection requests show to agents and in
chat cards.
- Add a Connectors page test that checks the new card title,
description, and button name.
- Resync `tests/runner-e2e/source-sdk-public-inputs.json`, because the
app definition is a pinned input.

Not changed, on purpose:
- The provider id `google`, the app slug `google`, and all stored
values. Existing application rows are found by their
`app-gallery:google` key, not by name.
- The short provider name `Google` in
`ui/src/components/ai-connections/model.ts` and
`packages/shared/src/ai-connections.ts`. Sentences such as "Your Google
default" and default account names such as "My Google API account" use
this name. Account names are stored when people create them, and the
long title makes these sentences awkward.
- The `Google` choice in the model provider picker, next to `OpenAI`,
`Anthropic`, and `xAI`. Its description already says "Antigravity
sign-in or Gemini API key".
- The Google Workspace and Search Console connectors.

## Verification

- Red/green: `cd ui && npx vitest run src/pages/apps/Browse.test.tsx -t
"Antigravity and Gemini"` fails with the old name and passes with the
new name.
- `cd ui && npx vitest run src/pages/apps/Browse.test.tsx` passes (119
tests).
- `cd ui && npx vitest run src/components/ai-connections
src/pages/apps/AppsConnect.test.tsx` passes (362 tests).
- `cd packages/shared && npx vitest run src/app-definitions` passes (50
tests).
- `pnpm verify` exits 2 because the pinned-input registry changed.
Required CI supplies the broad coverage.

## Risks

- Low risk. This is a display text change.
- Old chat cards keep the service name that they stored when they were
created ("Google"). This is only display text.
- The Connectors page matches aggregator apps by slug and name. The slug
`google` does not change, so the match does not change.

## 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 14:18:19 -06: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
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 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
github-actions[bot]andlockfile-bot 6efa3eb2d2 chore(lockfile): refresh pnpm lockfiles (#22678)
## Thinking Path

> - Paperclip uses a dependency lock for reproducible builds.
> - Dependency changes on master need matching lock entries.
> - Paid eval reports also pin a reviewed offline correction.
> - Reports must install before paid model work starts.
> - This automated PR keeps the lock and report proof together.

## Linked Issues or Issue Description

**What happened?**

Dependency manifests on master changed after the last committed lock
refresh.

**Expected behavior**

Frozen installs must match those manifests. Eval reports must retain
matching offline lock proof.

**Steps to reproduce**

Run a frozen install before and after this lock refresh.

## What Changed

- Refresh the dependency lock from the manifests on master.
- Refresh the sandbox provider lockfiles from their manifests on master.
- Include the matching offline report correction and hashes.
- Resync the SDK public source proof's lock pins from the refreshed
lock.

## Verification

- Pinned pnpm resolution completed with lifecycle scripts disabled.
- The report proof refresh accepted the reviewed committed baseline.
- The workflow rejected changes outside the lock and report proof files.

## Risks

The lockfile bot merges this PR without CI or review when it verifies
every added version on npm and all versions outside the harness
allowlist are at least 3 days old. Otherwise the PR waits for a
maintainer, and the daily refresh tries again. The bot merges only the
exact commit this workflow generated from manifests already reviewed on
master. Unknown report lock baselines remain blocked. This update
changes no permissions or paid enable gates.

## Model Used

None — generated by pnpm and the deterministic report-lock updater.

## Checklist

- [x] Thinking path and problem description included
- [x] Generated lock and matching report proof included
- [x] Release-age gate decides between bot merge and maintainer review

Co-authored-by: lockfile-bot <lockfile-bot@users.noreply.github.com>
2026-11-23 18:21:06 +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
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 9a6e61cf36 fix(connectors): show Anthropic as "Anthropic (Claude)" so a Claude search finds it (#22631)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The Connectors catalog shows each provider as a card with a name and
a short description.
> - The Anthropic card shows the name "Anthropic". People who search for
"Claude" do not find it.
> - The card description says "Use Anthropic APIs with a restricted
key." This text describes an obsolete REST setup. The connector now
offers only a Claude subscription or a Claude API key.
> - This pull request changes the card name to "Anthropic (Claude)" and
the description to "Connect to Claude with Anthropic."
> - The benefit is that a search for "Claude" finds the connector, and
the description matches what the connector does.

## Linked Issues or Issue Description

No public issue exists. This is an enhancement.

**What existing behavior does this improve?**

The Anthropic card in the Connectors catalog. The card name and the card
description change.

**Subsystem affected**

UI: the Connectors catalog (Apps). Shared: the Anthropic app definition.

**Current behavior**

The Connectors catalog shows the Anthropic connector as "Anthropic" with
the description "Use Anthropic APIs with a restricted key." A search for
"claude" in the Connectors search box does not show the Anthropic card.

**Proposed behavior**

The card shows the name "Anthropic (Claude)" and the description
"Connect to Claude with Anthropic." The slug stays `anthropic`.

**Reason and benefit**

Most people know the product as Claude. They search for "Claude" and do
not find the connector. The old description refers to a "restricted
key", which the connector does not use. After this change, a search for
"Claude" finds the connector, and the description is correct.

**Breaking changes**

None. The slug, the setup links, the saved connections, and the AI
provider bindings do not change.

## What Changed

- `packages/shared/src/app-definitions/anthropic.json`: Change `name` to
"Anthropic (Claude)". Change `description` to "Connect to Claude with
Anthropic."
- `scripts/ingest-app-definitions.mjs`: Make the same change in the
generator source. A regeneration now gives the same `anthropic.json`.
- `ui/src/pages/apps/Browse.test.tsx`: Add a test. The test searches the
Connectors catalog for "claude". It checks that the Anthropic card shows
the new name and description, and that the "Connect Anthropic (Claude)"
button is present.
- `tests/ai-connections-app/app.spec.ts`: Update the opt-in browser test
to find the "Connect Anthropic (Claude)" button. The test now escapes
the provider name for the regular expression.
- `tests/runner-e2e/source-sdk-public-inputs.json`: Refresh the pinned
hash of `anthropic.json` with `node
tests/runner-e2e/source-sdk-public-inputs.mjs <sha> --write`.

## Verification

- `cd ui && npx vitest run src/pages/apps/Browse.test.tsx`: 118 passed.
The new test fails on the old definition and passes on the new
definition.
- `cd ui && npx vitest run src/pages/apps/AppsConnect.test.tsx
src/pages/apps/AppDetail.test.tsx
src/pages/apps/app-connect-policy.test.ts
src/pages/apps/app-detail/AdvancedPanel.render.test.tsx`: 369 passed.
- `npx vitest run packages/shared/src/app-definitions.test.ts
packages/shared/src/connection-instructions.test.ts
packages/shared/src/app-definitions-url.test.ts`: 59 passed.
- `node --test scripts/app-definition-overrides.test.mjs`: 3 passed.
- `cd server && npx vitest run
src/__tests__/connection-intents-service.test.ts -t "obsolete Anthropic
tool requests"`: 1 passed. Agent connection search for "Anthropic" still
finds the connector through the `anthropic` slug.
- `node scripts/ingest-app-definitions.mjs --definitions-only` in a
temporary copy: the generated `anthropic.json` is the same as the
committed file.
- `pnpm verify` asks for broad CI coverage because
`scripts/ingest-app-definitions.mjs` is a global CI input. CI supplies
that coverage.

## Risks

- Low risk. The change is display text only.
- The slug stays `anthropic`. Saved connections, setup links, and AI
provider bindings do not change.
- Connection request cards and setup headers that use the connector name
now show "Anthropic (Claude)". This is the intended result.
- The AI method labels ("Claude subscription", "Claude API key") do not
change.

## Model Used

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

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [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 10:00:00 -06:00
DottaandClaude Opus 5.5 98fd412851 fix(apps): show readable Google Workspace action names on Review and Permissions (#22630)
## Thinking Path

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

## Linked Issues or Issue Description

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

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

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

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

## What Changed

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

## Verification

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

## Risks

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

## Model Used

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

## Checklist

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

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 09:57:23 -06:00
DottaandClaude Opus 5.5 ad163d0e36 fix(ui): open and link only http(s) or same-origin URLs from user and agent content (#22639)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The board UI shows content that agents and people write: comments,
tool results, work products, approval cards and runtime links
> - Some of this content becomes a link, an image or a new window
> - Some of these places did not limit the URL scheme, and the chat
image click opened the URL without `noopener`
> - A URL with a script scheme must never open or navigate from the
board, because it would run with the board origin
> - This pull request adds one URL helper and routes the content-fed
link, image-click and window sinks through it
> - The benefit is that only http(s) or same-origin URLs can open from
user or agent content, and new windows never get an opener

## Linked Issues or Issue Description

**What happened?**
The issue-reference parser accepted a URL with any scheme when its path
contained an issue path. The markdown renderer trusted that match and
kept the URL. The chat image click then gave the URL to `window.open`
with no scheme check and no `noopener`. Several other components had
their own copies of a scheme check, and some links used content URLs
with no check.

**What did you expect?**
The board opens or links only http(s) URLs and same-origin paths from
user or agent content. New windows open with `noopener,noreferrer`.

**Steps to reproduce**
Render markdown with an image whose URL uses a non-http scheme and an
issue path, then click the image. The new unit tests cover this case.

**Impact**
Defense-in-depth hardening of the board UI against unsafe URLs in stored
content.

## What Changed

- Add `ui/src/lib/safe-url.ts` with `safeNavigableUrl` (http(s) or
same-origin), `safeExternalHttpUrl` (absolute http(s) only) and
`openSafeUrl` (opens with `noopener,noreferrer`).
- `parseIssueReferenceHref` in `packages/shared` now accepts only
relative paths and http(s) URLs.
- `MarkdownBody` keeps the issue-reference shortcut only for safe URLs.
The image click handler gets only a safe URL.
- The task chat image click, the work products panel and MCP app links
open through `openSafeUrl`.
- The plugin bridge does a top-level navigation only to an http(s) URL.
- Replace the local scheme checks in the task chat thread, protocol
activity row, transcript adapter, MCP app host, workspace detail pages
and artifact cards with the shared helper.
- Apply the helper to artifact rows, rich artifact source and download
links, approval result links, request-confirmation target links,
attachment links in chat bubbles, provider source links, action test
result links and runtime service links.
- Refresh `tests/runner-e2e/source-sdk-public-inputs.json` for the
changed shared files.

## Verification

- `ui/src/lib/safe-url.test.ts`: one table of hostile inputs (script,
data, file, blob, about and custom schemes, whitespace and
control-character variants, non-string values) runs against each helper.
It also checks that `openSafeUrl` uses `noopener,noreferrer`.
- `ui/src/components/MarkdownBody.interaction.test.tsx`: an image with
an unsafe URL never reaches the click handler. An http image still does.
This test failed before the fix (the unsafe URL reached the handler) and
passes now.
- `packages/shared/src/issue-references.test.ts`: non-http schemes with
an issue path return `null`. These cases failed before the fix and pass
now.
- A headless Chromium check confirmed the risk of the old call: a script
URL opened with `window.open(url, "_blank")` ran with access to the
opener. With `noopener,noreferrer` it did not reach the opener.
- `npx vitest run` on the affected UI folders: 116 files, 2119 tests
pass. `tsc --noEmit` for `ui` has no errors in `src`.
- `pnpm verify` exits 2 because the pinned-input registry changed.
Required CI gives the broad coverage.

## Risks

- Low risk. A link from content with a non-http scheme (for example
`mailto:` in an artifact source link) no longer renders as a link in the
changed components. Markdown links keep the existing `react-markdown`
URL rules.
- Mention chips with their own schemes (agent, project, user, skill,
routine) 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 09:37:06 -06:00
DottaandClaude Opus 5.5 06d488b430 fix(telemetry): report every Paperclip runner harness as its own adapter_type (#22637)
## Thinking Path

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

## Linked Issues or Issue Description

Refs #22324

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

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

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

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

## What Changed

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

## Verification

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

## Risks

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

## Privacy Review

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

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

## Model Used

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

## Checklist

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

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 09:32:42 -06:00
DottaandClaude Fable 5.2 78e4f4f130 feat(runner): Antigravity on ACP 1.5.2 with Linux, API-key auth and Gemini 4 Neon (still pending) (#22591)
## Thinking Path

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

## Linked Issues or Issue Description

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

## What Changed

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

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

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

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

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

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

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

## Verification

Commands that passed on the final revision:

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

Known failures that also fail on `master`:

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

Live evidence, without a prompt:

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

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

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

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

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

## Risks

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

## Model Used

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

## Checklist

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

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

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-23 08:21:11 -06:00
DottaandClaude Opus 5.5 cb4129a918 test(restart-chaos): record why each hosted request failed and split gate D health failures into client-side and server-side (#22611)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The restart-chaos harness has a hosted mode. Its gate D requires 0
failed health probes across 10 consecutive releases on a hosted test
stack.
> - The harness runs on a home Mac over Wi-Fi. Three classes of failed
probe occurred: isolated 503s from the cloud idle sweep (a real bug, now
fixed), timeouts while the Mac slept with the lid closed, and `fetch
failed` errors during a Wi-Fi access point change.
> - The records keep only the status, the duration and `fetch failed`.
Each failure needs a manual investigation, and a client-side network
fault fails the gate the same way as a server outage.
> - This pull request records the evidence for every failed request and
gives each failure a class: client-side, server-side or unclassified.
> - The benefit is that a gate D failure explains itself, and only
server-side or unclassified failures fail the gate.

## Linked Issues or Issue Description

**What happened?**
Gate D failed on health probes that the stack did not cause. On
2026-11-23 at 02:28Z, the Mac slept: a 10 s abort fired after 18.5 s,
and the 2 s probe loop had a 16 s gap. At 08:05:35Z and 08:05:55Z,
undici reported `fetch failed` after 42 ms and 1240 ms, during a Wi-Fi
access point change. The saved records showed only `{status, ms, error:
"fetch failed"}`.

**Expected behavior**
Each failed request records why it failed: undici's error cause, the
socket, the connection reuse, the answer headers and body, the client
clock, and a control probe to a neutral endpoint. Gate D counts only
server-side and unclassified failures. Client-side failures stay visible
in `SUMMARY.md` as information.

**Steps to reproduce**
Run hosted gate D from a laptop on Wi-Fi, and sleep the laptop or change
the access point during the run. Before this change, the gate fails with
a bare `fetch failed` record.

## What Changed

- New `tests/restart-chaos/hosted-diagnostics.ts`:
- A fresh-connection client for the health probe (`node:https` with
`agent: false` and `connection: close`). Each probe opens and closes its
own connection, so a keep-alive race cannot look like an outage. It
records DNS, connect, TLS and first-byte times and the remote address.
- A connection tracker on undici's diagnostics channels. It tags each
API request's socket as new or reused, with the remote address, connect
time and time to first byte.
- Error-cause capture: `code`, `errno`, `syscall`, `hostname`,
`address`, `port`, message, and the socket's addresses and byte counts
for `UND_ERR_SOCKET`.
- Answer evidence for a non-2xx answer: status, the listed headers only
(`x-paperclip-status`, `retry-after`, `server`, `via`,
`x-railway-request-id`, `x-railway-edge`, `cf-ray`, `date`,
`content-type`, `cache-control`, `connection`), the first 512 bytes of
the body, and the parsed `error` and `statusPage.code`.
- Client clock: `timerLagMs` (elapsed minus timeout when an abort
fires), wall clock against monotonic clock, `monitorEventLoopDelay`
maximum, and the pause before each health probe.
- The classifier (`classifyFailure`) and the summary lines for
`SUMMARY.md`.
- `hosted-api.ts`: every failed request runs one control probe to
`https://www.cloudflare.com/cdn-cgi/trace` and, for a GET that did not
time out, one immediate retry of the same URL (2 s limit). The failure
is recorded at once; the control and retry outcomes are attached in the
background, and `settleDiagnostics()` waits for them before grading and
before `requests.jsonl` is saved. Concurrent failures share one control
probe per second. The control probe and the retry are not counted as
requests. The retry logic of the API client does not change. Only the
live entry point sets `live: true`, which turns on the fresh-connection
health client and the control probe; unit tests never reach the network.
- The fresh-connection client follows up to 3 same-origin redirects. A
cut-short answer keeps its status, headers and partial body beside the
error. A retry whose body cannot be read is recorded as failed.
- `hosted-gate.ts`: the health-probe check counts `server +
unclassified` from one class summary built from each failure's stored
class. The check line shows the three counts. Without class evidence,
every failure counts as unclassified.
- `hosted-release.ts`: release detection skips client-side failures, so
a client-side failure in a swap gap does not make a release
stop-then-start.
- `hosted-main.ts`: a failed probe's line is written to `health.jsonl`
when its evidence is complete, with a `hosted_health_failure_classified`
timeline event.
- `hosted-grade.ts` and `hosted-main.ts`: `SUMMARY.md` lists each health
probe failure with its class, reason and evidence. Client-side failures
are marked as information. The request breakdown lines show the class
counts. The timeline's `hosted_health_failed` event carries the class
and reason.
- Classes:
- Server-side: any HTTP answer that is not a readable 2xx; a reset or
refused connection while the control probe succeeded; a timeout while
the control probe succeeded and the client did not stall.
- Client-side: a `client_stall` (abort more than 1 s late, clock jump
over 1 s, event-loop delay over 1 s, or a pause before the probe longer
than twice the interval); a failed control probe; a client DNS failure
(`EAI_AGAIN`, or an `ENOTFOUND` that the immediate retry does not
repeat).
  - Unclassified: all other failures. They fail gate D.
- The macOS Wi-Fi BSSID and RSSI capture is not included. On current
macOS it needs `sudo wdutil` or location permission, so it is not
simple.
- README: a "Failure evidence" paragraph and the new gate D health rule.

## Verification

- `npx vitest run --config tests/restart-chaos/vitest.config.ts`: 74
files, 939 tests pass.
- `node scripts/typecheck-test-projects.mjs tests/restart-chaos`:
passes.
- New tests in `tests/restart-chaos/hosted-diagnostics.test.ts`:
- `counts a reset as server-side when the control probe to the neutral
endpoint succeeded`
  - `counts a reset as client-side when the control probe failed too`
- `counts a stalled client timer as client-side even when the control
probe succeeded`
  - `counts a client DNS failure as client-side`
- `leaves a failure without enough evidence unclassified, and gate D
fails on it`
- `passes gate D with only client-side failures and keeps them visible
as informational lines`
- `records the 503's status, headers, body excerpt, parsed error and
statusPage code, and counts it server-side`
- `records undici's error cause and socket for a reset, and classifies
it by the control probe`
  - `does not repeat a failed non-GET request as the immediate retry`
  - `passes the gap before each probe to the health check`
- `opens a fresh connection for every health probe and records its
phases`
  - `tags an API request's socket as new or reused`
- `reports a reset on a fresh connection with the socket's addresses and
byte counts`
- A manual smoke run against the control endpoint recorded `reused:
false`, the remote address, and DNS, connect, TLS and first-byte times.
An unknown host recorded `ENOTFOUND` with `syscall: getaddrinfo`.

## Risks

- Low risk. The change is in the test harness only. No product code
changes.
- Each failed request now adds one control probe and, for a GET that did
not time out, one retry with a 2 s limit. They run in the background, so
the health probe cadence and the API client's own retries do not wait
for them. The grade waits for them before it classifies; a diagnosis
that is still pending counts as unclassified.
- Each request sends an extra `x-restart-chaos-request` header to the
stack. The server ignores it.
- The client-side rules can hide a real server fault only when the
client also could not reach the neutral endpoint, or when the client
stalled. Every other failure counts against the gate.
- Release detection and the swap-shape check still read every failed
probe. That behavior does not change.

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

## Model Used

- Provider: Anthropic. Model: Claude Opus 5.5 (`claude-opus-5-5`), run
in Claude Code as an agent with tool use (shell, file edits, test runs).
Standard context window.

## Checklist

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

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

---------

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-22 00:07:34 -08:00
DottaandClaude Opus 5.5 e5f0e1508b test(restart-chaos): drain a max-hours hosted run from the end of arrivals, skip slot-queued tasks, count per-run loop-guard notices as information (#22533)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The restart-chaos harness has a hosted mode. It runs real agent
tasks on a hosted test stack and grades the stack's own deploys with
Gate D.
> - A 16 h hosted run saw only 2 releases. Both were clean. The run then
stopped at `--hosted-max-hours` and Gate D failed on 7 open tasks and 2
duplicated comments.
> - The artefacts show that the harness caused the failures, not the
product. The drain ended after 0.9 s. The grade aged run activity
against a late clock. The duplicate check counted a once-per-run product
notice as a duplicate.
> - A gate that fails on harness artefacts hides real product failures
and wastes long runs.
> - This pull request fixes the three harness artefacts and keeps the
gate strict for real stalls.
> - The benefit is that a max-hours run grades its last tasks after they
finish, and Gate D fails only on real problems.

## Linked Issues or Issue Description

**What happened?**
A hosted Gate D run stopped at the 16 h cap, 15 h after its last
release. `drainHosted` computed the drain cap from the last release
(14:12Z), so the cap was already in the past. The drain ended 0.9 s
after arrivals ended, with 5 runs still progressing. Tasks launched 2 to
10 min earlier were graded as open. 4 of the 7 finished hands-off within
8 min (05:38Z to 05:43Z). Cleanup cancelled the other 3 while they were
running. The grade also took its clock after about 533 task view reads,
so it aged run activity by several extra minutes. Two healthy running
tasks became "nothing pending". Two subtasks were queued behind the
agent's full 5-slot cap and were graded as stalled. The two "duplicated
agent comments" were the product's loop-guard notice, posted once by
each of two different runs on the same task.

**Expected behavior**
A run that stops at the max-hours cap drains for the bounded
`--hosted-drain-minutes` after arrivals end. Run activity is aged from
the moment the runs were read. A task whose only live runs are provably
queued behind a full agent slot cap is not graded. A loop-guard notice
that each run posts once is information, not a duplicate.

**Steps to reproduce**
1. Run `tests/restart-chaos/hosted.ts --hosted-releases 10
--hosted-max-hours 16` against a stack that deploys fewer than 10 times.
2. Let the run stop at the hours cap.
3. See `hosted_settling` with a `capAt` in the past, and
`hosted_drained` with reason `cap` less than 1 s later.

**Paperclip version or commit**
master at 324ec1f537.

## What Changed

- `drainHosted` counts the drain cap from the later of the last release
and the start of the drain. It records `drainFrom` on `hosted_settling`.
The drain is still bounded by `--hosted-drain-minutes`.
- `gradeHosted` takes the grade clock immediately before it reads the
runs. Activity age now matches the run snapshot.
- New `slotQueuedRuns` and `queuedBehindSlotCap` in `hosted-gate.ts`. A
never-started run is slot-queued only when its agent's running runs fill
`maxConcurrentRuns` and `queueWaitFairnessFrom` finds no idle slot and
no newer assignment run started ahead of it. An open task whose every
live run is slot-queued is not graded. `SUMMARY.md` names it on a `Not
graded` line, and `hosted-release-swap.json` lists it under `notGraded`.
The runs that hold the slots are still graded.
- New `isNoticeRepeat` in `release-swap-grade.ts`. The loop-guard notice
is information when each copy has a different `createdByRunId`. Two
copies from one run, or a copy without a run, are still a duplicate. The
hosted reader and the local RS1 grader both use it.
- README and SCENARIOS describe the new drain start, the `Not graded`
line and the loop-guard rule.

## Verification

- `npx vitest run --config tests/restart-chaos/vitest.config.ts
tests/restart-chaos`: 73 files, 918 tests pass.
- `npx tsc -p tests/restart-chaos/tsconfig.json`: clean.
- Red/green: the new `hosted-cutoff.test.ts` fails 6 of 8 tests with
master's `hosted-grade.ts` and `hosted-readers.ts`, and passes with this
change.
- New tests: the drain runs past a release from 15 h earlier until it is
quiet; the drain still stops at its cap; activity is aged from the run
read; queued subtasks behind a full cap are not graded and the gate
still fails on the slot holder; a queued subtask with a free slot is
still graded as "nothing pending"; loop-guard notices from different
runs are information and from one run are a duplicate, for the hosted
and the local grader.

## Risks

- Low risk. The change is in the test harness only.
- A max-hours run now takes up to `--hosted-drain-minutes` longer
(default about 57 min) before it grades.
- The not-graded rule could hide a stall only if the slot proof is
wrong. The rule needs the agent cap, a full set of running runs, and a
fair queue wait. The gate still grades and fails the runs that hold the
slots.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude
Code with tool use (shell, file edits, read-only API reads of the test
stack).

## Checklist

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

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 00:33:43 -06:00
scotttong 856f14e507 fix(dashboard): scope areas and responsibilities to each user (#22513) 2026-11-21 13:59:00 -08:00
DottaandClaude Opus 5.5 558dbb0132 test(restart-chaos): grade hosted runs with R1 and a strict release-swap gate (#22490)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The restart-chaos harness (`tests/restart-chaos`) proves that agent
work survives a control-plane release swap
> - Local waves grade each task with rules R1–R6. R1 is the time budget,
with credit for a provably fair queue wait (#22446, #22452)
> - Hosted mode (`hosted.ts`) runs the same proof on a real test staging
instance that takes automatic releases
> - Hosted mode passed a run when every task finished hands-off. It did
not apply R1, and banners, failed health probes, duplicates and the swap
shape were only reported
> - The next acceptance gate needs 10 consecutive hosted releases with
100% hands-off, 0 Retry banners and 0 failed health probes, so the exit
code must enforce these rules
> - This pull request adds hosted R1 and a strict "Gate D" verdict to
the hosted grade
> - The benefit is that one hosted run gives a single pass or fail with
the same R1 rule as the local waves

## Linked Issues or Issue Description

Refs #22446
Refs #22452
Refs #21153

**What happened?**

A hosted run (`hosted.ts --hosted-releases N`) exited 0 when every
started task finished without a person. The run did not grade R1. A
Retry banner that cleared by itself, a failed `/api/health` probe, a
duplicated agent comment, a stop-then-start release or a release with no
live run did not fail the run. These were only lines in `SUMMARY.md`.

**Expected behavior**

A hosted run passes only when every task finishes hands-off and inside
the R1 budget (with the same fair queue-wait credit as the local waves),
no Retry banner shows, no health probe fails, no work is duplicated, no
release is stop-then-start, and each release carries at least one live
run.

**Steps to reproduce**

1. Run `hosted.ts --hosted-releases 1` against a test staging instance
whose deploy is stop-then-start.
2. Let all tasks finish by themselves after the outage.
3. See exit 0, although health probes failed during the release.

**Paperclip version or commit**

`95ba0a7de6` (master)

## What Changed

- `hosted-gate.ts` (new): `hostedR1` builds the R1 input from API rows
and calls `gradeR1` from `grader.ts`. It uses the staging-mix budget
(`stagingMixBudgetMs`), outage time only for a release whose health
probes failed before the new build answered, and the fair queue-wait
proof (`queueWaitFairnessFrom`) from the company run list and each
agent's `maxConcurrentRuns`. A follow-up run's wait is not credited,
because the API has no wake evidence. `hostedGate` lists seven checks
and passes only when all hold.
- `hosted-readers.ts`: run rows keep `invocationSource`, `retryOfRunId`
and the wake comment ids.
- `hosted-grade.ts`: grades every started task with R1, adds the `Gate
D` block to `SUMMARY.md`, adds `gate` and `r1` to
`hosted-release-swap.json`, and returns the gate as the pass.
- `hosted-main.ts`: passes the task records to the grade.
- `README.md`: documents the gate and the API proxies for per-release
hand-off and reach.

## Verification

- `npx vitest run --config tests/restart-chaos/vitest.config.ts
tests/restart-chaos/hosted` passes (8 files, 56 tests). The new
`hosted-gate.test.ts` covers R1 pass and fail, a fair and an unfair
queue wait, outage credit, Retry and open tasks, and each gate check.
- `npx tsc -p tests/restart-chaos/tsconfig.json --noEmit` is clean.
- No hosted run was started for this change. It changes only how a
finished run is graded.

## Risks

- Low risk. The change is in the test harness only.
- Hosted runs that passed before can now fail on R1, a banner, a failed
probe, a duplicate, a stop-then-start release or an unloaded release.
This is intended.
- A follow-up run's queue wait gets no credit on hosted runs, so R1 can
be stricter than in local waves when follow-ups queue for a long time.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used 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-21 07:33:25 -06:00
Devin FoleyandPaperclip b4cea5b5a4 fix(runner): show disk exhaustion before recovery errors (#22448)
Show the confirmed sandbox disk failure before a later lost-turn or restore error in saved run errors and both run detail views. Preserve the original diagnostics and leave scarce inodes available when preparing the existing runner relaunch reserve.

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

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

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

## Linked Issues or Issue Description

**What existing behavior does this improve?**

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

**Current behavior**

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

**Proposed behavior**

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

**Reason and benefit**

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

## What Changed

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

## Verification

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

## Risks

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

## Model Used

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

## Checklist

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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-20 16:45:34 -08:00
DottaandClaude Opus 5.5 e64872fcdb test(restart-chaos): credit a provably fair follow-up queue wait in R1 (#22452)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The restart-chaos harness (`tests/restart-chaos`) grades each task
of a wave against rules R1–R6
> - #22446 lets R1 credit the first run's queue wait when the harness
can prove that wait was fair
> - The staging-mix shape gives each agent about 21 assignments on 4
slots, all within about 2.5 minutes. A follow-up comment that arrives
later also waits 20–26 minutes in a fair FIFO queue
> - The R1 budget (`1.5 × turn + 20 min`) cannot absorb that wait.
Recent grade summaries show a follow-up queued-wait p50 of about
450–1,100 s, so the problem is structural
> - This pull request extends the same fairness proof to the queue wait
of a run that a board follow-up comment started
> - The benefit is that a fair capacity queue no longer fails R1, while
deploy-caused waits and real dispatch-fairness bugs still fail

## Linked Issues or Issue Description

Refs #22446

**What happened?**

In wave `w-20261120T224738-s7106`, task t007 failed R1 as
`no_rest_within_budget (last status in_progress)`. Its first assignment
run ran from 22:49:15Z to 23:00:21Z and succeeded. The harness then
posted a follow-up comment, which created run `dde4d929` (invocation
source `automation`) at 23:00:21Z. That run sat queued for 1,558 s,
until 23:26:19Z, behind its agent's older assignments. It succeeded at
23:27:45Z, 17 s after the observer's deadline, so the observer stopped
watching. All 32 tasks finished hands-off, with 0 Retry banners, 0
duplicates and clean swaps.

**Expected behavior**

A task whose follow-up run waited fairly for agent capacity is not
marked late because of that wait. A follow-up run that a newer fresh
assignment overtook, or that waited while a slot was idle, still fails
R1. Waits of retries and recovery runs still count against the budget.

**Steps to reproduce**

1. Run a staging-mix wave with 32 arrivals and 4 slots per agent (for
example the plan in `w-20261120T224738-s7106`).
2. Find a task whose follow-up comment is posted while its first run
works.
3. See that the follow-up run queues for more than 20 minutes after the
first run ends, and that R1 fails although every slot was busy.

**Paperclip version or commit**

`104f323bee` (master, after #22446)

## What Changed

- `grader.ts`: `runSelection` chooses the runs whose queue wait R1 may
credit. The rules, in order:
1. If any run on the task has no parseable `createdAt`, nothing is
credited (`no createdAt for <ids>, so runs cannot be ordered`).
2. The first run (earliest `createdAt`) is a candidate unless it is a
retry.
3. For each harness follow-up comment (`followUp`,
`stagingMix.followUp`, `stagingMix.afterEndFollowUps`): without a send
time, nothing is credited for it (`no send time for follow-up comment
<id>`). Otherwise the candidate is the earliest run that carries the
comment, was created at or after the send time (`followUp.sentAt ?? at`;
the staging-mix `at` is taken before the request), and was not cancelled
before it executed (cancelled with no start, or a pre-dispatch
cancellation such as `continuation_task_ownership_changed`).
4. That run counts only if it is not a retry, the previous executed run
succeeded and finished at or before its `createdAt`, and the wake
evidence shows a comment wake reason (`issue_commented`,
`issue_comment_mentioned`, `issue_reopened_via_comment`) and no
continued or interrupted run. Without wake evidence nothing is credited
(`no wake evidence for follow-up run <id>`).
5. Each candidate's wait (`createdAt` to `startedAt`, clipped to the
task's `createdAt..restAt`, minus outage time) is credited only when
`queueWaitFairnessFrom` proves it fair. Any provably unfair wait fails
as `unfair_queue_wait` and names the run. An unproven wait is not
credited, and the detail says why.
- `grader.ts`: `gradeR1` adds the credited waits to the allowed time. A
candidate that never started gives `<kind> <id> never started`.
- `wave-grade-inputs.ts`, `types.ts`: `prepare` now adds `runWakes`
(each run's wake reason and continued run ids, from
`wake-evidence/<task>.json`) to the record before grading.
- `observer.ts`: the observer holds the timeout while any credited run
is queued (up to one more budget). It extends the deadline once per
credited run by that run's wait when the run starts.
- `README.md`: documents the follow-up credit.
- No product code changes.

## Verification

- `pnpm exec vitest run --config tests/restart-chaos/vitest.config.ts`:
71 files, 884 tests pass.
- `pnpm exec tsc -p tests/restart-chaos/tsconfig.json --noEmit`: clean.
- New tests in `grader.test.ts` (`R1 follow-up queue wait credit`):
- credits a fair 1,558 s follow-up queue wait behind the agent's older
assignments
- fails as unfair when a newer fresh assignment started ahead of the
follow-up
  - fails as unfair when a slot sat idle while the follow-up was queued
  - does not credit the wait of a retry or a recovery run
- does not credit a follow-up run created while the previous run was
still running
- credits a fair wait of a run woken by an after-end follow-up, but not
after a recovery
  - refuses follow-up credit when an earlier run has no createdAt
- does not credit a recovery run that carries the comment after a
success
- reads each run's wake reason and continued runs from the wake evidence
- does not credit a run created before its follow-up comment was posted
- credits a run created after the comment request was sent but before it
returned
  - credits nothing when the earliest run has no createdAt
- credits the first executed carrier, never a run cancelled before it
executed
  - refuses follow-up credit without wake evidence
  - credits only the part of a wait inside the task's own lifetime
  - does not credit outage time inside the follow-up's wait
  - sums the fair waits of the first run and a follow-up
- New tests in `observer.test.ts`:
- waits while a follow-up run is queued and extends the deadline by its
queue wait once it starts (fails before the change)
  - does not hold the deadline for a queued run that a recovery created
- Offline re-grade of the saved wave `w-20261120T224738-s7106` with a
scratch script (not committed). The old `gradeR1` reproduces all 32
saved R1 details first. Records go through the new `prepare`, so
`runWakes` come from the saved wake evidence (t007: `dde4d929` has wake
reason `issue_commented` and no continued run).
  - The other 31 tasks: no R1 verdict changes (31 pass).
- t007 as saved: still `no_rest_within_budget`, because the old observer
timed out 17 s before the task finished.
- t007 as the new observer records it (deadline extended by the 1,558 s
wait to 23:53:26Z, task done at 23:27:45Z): `pass — done after 2310s
(allowed 3851s incl. 1558s fair queue wait)`. The wave's
`agent-slots.json` has `createdAt` for every run, so the proof is
complete.
- The same t007 record without slot evidence: `done_too_late 2310s >
2293s (queue wait not credited: no agent slot evidence …)`.

## Risks

- Low risk. The change is in the test harness only.
- Tasks inside their base budget grade exactly as before.
- A follow-up wait is credited only with wake evidence. Waves without
`wake-evidence/<task>.json` get no follow-up credit, and the R1 detail
says so.
- The observer cannot see wake reasons while it runs, so it may watch a
little longer than the grader later credits. The grader decides the
verdict.
- An observer can watch a task for longer, up to each credited run's
queue wait. This can make a wave a little longer when queues are long.

> 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, via Claude Code with
tool use (shell, file edits). Extended reasoning enabled.

## Checklist

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

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 18:41:34 -06:00
DottaandClaude Opus 5.5 104f323bee test(restart-chaos): credit a provably fair first-run queue wait in R1 (#22446)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The restart-chaos harness (`tests/restart-chaos`) grades each task
of a wave against rules R1–R6
> - R1 allows the workload budget plus outage time, but it ignores the
time the first run waits for a free agent slot
> - In a staging-mix wave, 32 tasks arrive in about 2.5 minutes and each
agent has 4 slots, so the last arrivals wait 21–25 minutes even with
perfect FIFO dispatch
> - One task (t031) is the tightest in every wave. Its margin went from
+165 s and +142 s to −87 s, and the wave failed R1 for a fair wait
> - This pull request credits the first run's initial queue wait in R1
only when the harness can prove the wait was fair
> - The benefit is that a fair queue no longer fails R1, and a real
dispatch-fairness bug fails with its own reason

## Linked Issues or Issue Description

**What happened?**

In wave `w-20261120T190100-s7106`, task t031 failed
`R1:no_rest_within_budget` by 87 s. Its first assignment run sat queued
from 19:04:31Z to 19:32:43Z. Its opencode agent was at its 4-run limit
for the whole wait, and the run started in the same second that a slot
freed. The R1 budget (`1.5 × turn + 20 min`) does not include queue
wait.

**Expected behavior**

A task whose first run waited fairly for agent capacity is not marked
late because of that wait. A task whose run was overtaken by a newer
run, or that waited while a slot was idle, still fails R1.

**Steps to reproduce**

1. Run a staging-mix wave with 32 arrivals and 4 slots per agent (for
example the plan in `w-20261120T190100-s7106`).
2. Look at the last task assigned to the busiest agent.
3. See that its first run queues for more than 20 minutes and that R1
fails although every slot was busy.

**Paperclip version or commit**

`f7db7312b4` (master)

## What Changed

- `agent-slots.ts`: `agentSlotsFromRows` records each run's `createdAt`,
`invocationSource` and `retryOfRunId`. New `queueWaitFairnessFrom`
decides if a run's queue wait was fair. It returns `unfair` when a newer
fresh assignment run of the same agent started during the wait, or when
the agent had an idle slot for more than 2 s
(`QUEUE_HANDOFF_TOLERANCE_MS`) outside a server outage. Newer follow-ups
and retries rank higher in the dispatcher by design, so they do not
count as overtaking. It returns `unproven` when slot evidence,
`createdAt` or the invocation source is missing, or when the only idle
slot overlapped an outage.
- `grader.ts`: new `firstRun`, `firstRunQueuedMs` and
`firstRunQueueWait`. `gradeR1` always checks fairness (it defaults to
"no slot evidence"). When the task is over its base budget, R1 adds the
first run's initial wait minus any fault overlap if the wait is fair. A
provably unfair wait fails as `unfair_queue_wait`. An unprovable wait
(including a first run that never started) is not credited and the
detail says why. Waits of retries and later runs are never credited.
Tasks inside the base budget grade exactly as before.
- `observer.ts`: the observer does not time a task out while its first
run is still queued (up to one more budget), and it extends the deadline
once by that run's queue wait when it starts, so it watches long enough
for the grader to apply the credit.
- `wave-grade-inputs.ts`: passes the fairness check to `gradeTask`.
- `README.md`: documents the R1 queue-wait credit.
- No product code changes.

## Verification

- `pnpm exec vitest run --config tests/restart-chaos/vitest.config.ts`:
71 files, 865 tests pass.
- `pnpm exec tsc -p tests/restart-chaos/tsconfig.json --noEmit`: clean.
- New tests in `grader.test.ts` (`R1 fair queue wait credit`):
- credits a fair 1,509 s FIFO queue wait that left the task 87 s over
the old budget
- fails as an unfair queue wait when a newer run started ahead of the
queued run
- fails as an unfair queue wait when the agent had an idle slot during
the wait
- credits the wait when a newer follow-up or retry that the dispatcher
ranks higher started ahead
  - does not call an idle slot during a server outage unfair
  - says so when the first run never started
  - allows a same-second slot hand-off within the tolerance
  - does not credit a wait it cannot prove fair
  - leaves a short queue wait unchanged
- credits only the first run's initial wait, not outage time inside it
or later retries
- New tests in `observer.test.ts`: extends the deadline once by the
first run's queue wait when it starts; does not time out while the first
run is still queued, up to one more budget.
- Offline re-grade of the saved wave `w-20261120T190100-s7106` with the
new `gradeR1` (all 32 saved R1 verdicts reproduce first):
  - No verdict changes for the other 31 tasks.
- t031 with the wave's saved evidence: `done_too_late 2291s > 2183s
(queue wait not credited: no createdAt for 4 runs …)`. This wave's
`agent-slots.json` predates `createdAt`, and 4 of the 10 runs that
started during the wait are subtask runs that the per-task wake evidence
does not cover. The grader cannot prove FIFO from the saved files, so it
does not credit the wait.
- t031 with those 4 runs taken as created earlier (as the earlier DB
diagnosis found): `pass — done after 2291s (allowed 3701s incl. 1518s
fair queue wait)`.
- New waves record `createdAt` for every run, so the check is complete
from the next wave.
- `--replay` re-executes a task on a live server. It is not a re-grade,
so I did not use it.

## Risks

- Low risk. The change is in the test harness only.
- Tasks inside their base budget grade exactly as before. Only a task
that is over budget can change verdict. An over-budget R1 detail now
also says why a queue wait was not credited; the failure signature is
unchanged.
- The fairness rule models the dispatcher coarsely: only a newer fresh
assignment run counts as overtaking. Readiness and priority are not
compared, and all harness tasks use the same priority.
- An observer can watch a task for longer, up to the first run's queue
wait. This can make a wave a little longer when queues are long.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, via Claude Code with
tool use (shell, file edits). Extended reasoning enabled.

## Checklist

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

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 16:44:42 -06:00
github-actions[bot]andlockfile-bot f4a3f85b89 chore(lockfile): refresh pnpm lockfiles (#22435)
## Thinking Path

> - Paperclip uses a dependency lock for reproducible builds.
> - Dependency changes on master need matching lock entries.
> - Paid eval reports also pin a reviewed offline correction.
> - Reports must install before paid model work starts.
> - This automated PR keeps the lock and report proof together.

## Linked Issues or Issue Description

**What happened?**

Dependency manifests on master changed after the last committed lock
refresh.

**Expected behavior**

Frozen installs must match those manifests. Eval reports must retain
matching offline lock proof.

**Steps to reproduce**

Run a frozen install before and after this lock refresh.

## What Changed

- Refresh the dependency lock from the manifests on master.
- Refresh the sandbox provider lockfiles from their manifests on master.
- Include the matching offline report correction and hashes.
- Resync the SDK public source proof's lock pins from the refreshed
lock.

## Verification

- Pinned pnpm resolution completed with lifecycle scripts disabled.
- The report proof refresh accepted the reviewed committed baseline.
- The workflow rejected changes outside the lock and report proof files.

## Risks

The lockfile bot merges this PR without CI or review when it verifies
every added version on npm and all versions outside the harness
allowlist are at least 3 days old. Otherwise the PR waits for a
maintainer, and the daily refresh tries again. The bot merges only the
exact commit this workflow generated from manifests already reviewed on
master. Unknown report lock baselines remain blocked. This update
changes no permissions or paid enable gates.

## Model Used

None — generated by pnpm and the deterministic report-lock updater.

## Checklist

- [x] Thinking path and problem description included
- [x] Generated lock and matching report proof included
- [x] Release-age gate decides between bot merge and maintainer review

Co-authored-by: lockfile-bot <lockfile-bot@users.noreply.github.com>
2026-11-20 18:33:27 +00:00
Nicky LeachandClaude Opus 5.5 dce4d47f60 feat(plugins): carry Grok, Copilot and OpenCode credentials to plugin Runners (#22359)
## Thinking Path

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

## Linked Issues or Issue Description

**Subsystem affected**

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

**Problem or motivation**

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

**Proposed solution**

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

**Alternatives considered**

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

**Roadmap alignment**

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

**Additional context**

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

## What Changed

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

## Verification

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

## Risks

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

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

## Model Used

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

## Checklist

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

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 08:47:18 -08:00
16dfa200ac fix(environments): clean up an unconfirmed setup sandbox and answer a provider outage with 503 (#22377)
A provider outage during an interactive custom-image setup start left a
provisional sandbox with no cleanup owner, and the raw RPC error reached
the HTTP error handler as a 500 crash report.

- Keep the creation-cleanup envelope and create status for
  environmentStartInteractiveSetup errors at the worker RPC boundary.
- Record an in-scope unconfirmed setup sandbox as a pending-cleanup lease
  that the existing sweep destroys.
- Pin failed-creation cleanup (probe and teardown) to the plugin that
  created the sandbox.
- Answer a transient provider refusal with 503
  environment_provider_unavailable instead of a crash report.

Co-Authored-By: Paperclip <Paperclip-Paperclip@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 04:57:36 -08:00
Devin FoleyandPaperclip c41145e72a fix: wait on pending questions and quiet provider holds (#22363)
## Thinking Path

> - Paperclip manages agents and the tasks they work on.
> - Recovery should continue unfinished work when it is eligible.
> - An active unanswered question is a persisted reason to wait for a
person.
> - Treating a later Retry as an answer makes the recovery sweep
repeatedly request continuations that admission refuses.
> - Provider-limit holds also produce one cancellation toast per task,
even though provider work never started.
> - This PR aligns recovery with persisted interaction status and
presents these waits accurately.

## Linked Issues or Issue Description

Refs: #20466. This addresses the question blocker presentation and
automatic recovery loop; it preserves the existing
interaction-resolution policy.

Related work: #19420 schedules provider quota retries, and #21570
handles notices and reply ownership in agent chats. This change concerns
assigned-task reconciliation, task/inbox status, and per-run
cancellation toasts.

**What happened?**

The assigned-work sweep ignored pending interactions whenever a newer
run carried `explicitUserContinuation`. Continuation admission still
refused the pending question, so repeated sweeps recorded unsuccessful
continuation attempts. The task could meanwhile show an older provider
error as its current blocker. Separately, each pre-dispatch
provider-limit hold generated a cancellation toast, and the one-hour
fallback was described as a known reset and promised start time.

**Expected behavior**

Wait quietly while the question remains active under the shared
interaction eligibility rules, then react to the existing resolution
notification. Dismissed or historical ordinary questions remain
answerable without blocking work; governed requests keep their gates.
Show the current question on task and inbox surfaces. Keep provider
failure history, suppress cancellation toasts for expected provider
holds, and describe scheduled availability checks without promising the
provider will accept work.

**Steps to reproduce**

1. Leave an `ask_user_questions` interaction pending with
`supersedeOnUserComment: false`.
2. Create a later failed/interrupted explicit Retry and run
assigned-work reconciliation repeatedly.
3. Observe that the question remains pending while the sweep attempts
fresh continuations.
4. Separately, let an agent with recent provider rate-limit evidence
receive automatic task wakes without a reported reset time.

## What Changed

- Remove inferred question supersession from both assigned-work fact
loading and candidate selection. Use the existing active-interaction
predicate consistently in those reads, fresh-continuation admission, and
the task projection. Cover dismissed/historical ordinary questions,
retained governed gates, repeated checks, idle workers, and the existing
resolution notification.
- Add the `question` interruption action, load active pending question
IDs alongside approvals in one company-scoped query, and show that
blocker on tasks and inbox rows. Preserve a supported manual Retry after
a failed attempt, suppress duplicate actions for saved input, and keep
other current user gates authoritative. This preserves the existing
issue-detail SQL statement budget. Historical run failures remain
intact. Refresh the shared source SDK input pin.
- Suppress cancellation toasts specifically for cancelled
`provider_limit_wait` runs. Label provider retry deadlines as
availability rechecks, retain relative-time formatting, and record
successful scheduling as an informational lifecycle event.
- Document the wait contract in the continuation architecture guide.

## Verification

- Demonstrated failing regressions before the implementation:
continuation loop, task projection, task notice, cancellation toast,
provider deadline wording, and deadline formatting.
- Initial focused Vitest qualification: 642 tests passed across 14
files, using:

  ```sh
  pnpm exec vitest run \

server/src/__tests__/{assigned-work-invariant,assigned-work-recheck-idle,heartbeat-provider-limit-wait,task-interruption-query}.test.ts
\

server/src/services/{task-interruption-presentation,execution-projection,fresh-continuation-fallback,issue-thread-interactions}.test.ts
\
    server/src/services/recovery/assigned-work-invariant.test.ts \

ui/src/{components/ExecutionBlockerNotice.test.tsx,context/LiveUpdatesProvider.test.ts,context/LiveUpdatesProvider.hook.test.tsx,lib/provider-limit-message.test.ts,pages/Inbox.test.tsx}
  ```
- `pnpm --filter @paperclipai/shared typecheck` — passed.
- Review follow-up: 157 tests passed in `assigned-work-invariant`,
`task-interruption-query`, and `fresh-continuation-fallback`; 575 passed
in `task-interruption-query`, `assigned-work-recheck-idle`,
`task-interruption-presentation`, `issue-question-context`,
`issue-thread-interactions`, and `explicit-native-continuation` (the
query file overlaps). The strengthened final
dismissed/historical/governed projection regression also passed
separately.
- Final query-consolidation verification: 157 tests passed across five
files, including the unchanged 64-statement issue-detail census and
mixed approval/question batches:

  ```sh
  pnpm exec vitest run \

server/src/__tests__/{issue-detail-statements,task-interruption-query,assigned-work-invariant,assigned-work-recheck-idle}.test.ts
\
    server/src/services/task-interruption-presentation.test.ts
  ```
- `pnpm --filter @paperclipai/server typecheck` — passed, including test
layers.
- Manual-recovery follow-up: 204 tests passed across seven
projection/recovery/notice suites, and all 104 Inbox tests passed. The
lost-runner integration still starts exactly one run from a manual Retry
and leaves the question unanswered. The saved-decision census verifies
one decision batch query for a 41-task list, with at most three
statements referencing interactions; the overall 64-statement
issue-detail limit remains unchanged.
- `pnpm --filter @paperclipai/ui typecheck` — passed.
- `pnpm --filter @paperclipai/ui build` — passed.
- `node tests/runner-e2e/source-sdk-public-inputs.mjs $(git rev-parse
HEAD) --check` — passed.
- `pnpm verify` — exit 2: broader CI is required for changed global
inputs. Focused tests and package checks supply local evidence; broad CI
remains required.
- `git diff --check` and a local secret/instance-data scan — passed.
- Final CI on `1c16fe7c0d8`: [trusted CI
workflow](https://github.com/paperclipai/paperclip/actions/runs/44650155842)
passed, including all server shards, native-server verification, build,
canary, e2e, release registry, and serialized suites. All PR checks are
complete, with no failures; the branch is conflict-free.
- Greptile reviewed the latest revision, `1c16fe7c0d8`, at 5/5 with no
actionable findings or unresolved review threads.

The focused tests cover genuine provider failures, live work and
terminal tasks, unchanged task locks/retry delivery, preservation of
historical failures, and question resolution waking the affected task
while other active pending questions remain quiet. Review regressions
also cover dismissed/historical ordinary questions retaining Retry and
governed requests retaining their gates. No live task was retried or
answered for validation.

## Risks

- An active pending question now consistently blocks automatic
assigned-work recovery. Shared interaction eligibility determines when
ordinary conversation input becomes deferred or historical; governed
requests retain their authority. Automatic recovery no longer infers
that a newer Retry resolved an active question.
- Manual Retry keeps its existing admission policy and recovery checks.
The question notice preserves that supported action after a failed
attempt without changing approval or credential authority; pending saved
input prevents duplicate actions.
- The shared interruption action gains `question`; the task and inbox
consumers are updated together. The pending-question query returns only
task IDs and uses the existing company/task/status index.
- Provider cooldown policy, quotas, credentials, routing, cancellation
history, and durable retry timing are unchanged. The actual provider can
still return a rate limit at the recheck.
- No migration is required. Existing large owner modules receive small
localized changes; no code file crosses 1,000 lines.

## Model Used

OpenAI `gpt-6.1-sol` through the Codex harness in T3 Code, xhigh
reasoning effort, with code execution and tool use.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (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 linked existing issues or 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
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-19 19:54:15 -08:00
19a7381398 feat: restore personal archiving in task views (#22358)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - People use Tasks to see shared work and manage the work that needs
their attention.
> - The old inbox already let each person archive a task and undo that
action.
> - The combined Tasks surface needs the same controls in Unread and in
task table rows.
> - The existing inbox archive rules determine when new activity brings
a task back.
> - This pull request adds an Archived view so people can find and
restore their archived tasks.

## Linked Issues or Issue Description

**What existing behavior does this improve?**

Personal task archiving in Tasks. Related work includes the combined
Inbox and Tasks surface (#15100), the Coordinator workspace (#17983),
moving Mine into Tasks (#19363), and the existing inbox archive rules
(#9931).

**Subsystem affected**

Cross-cutting. The UI and task list API reuse the existing inbox archive
state.

**Current behavior**

Mine has an archive action. Unread and the task table have no equivalent
action. The Tasks menu has no dedicated view for restoring archived
tasks.

**Proposed behavior**

Add Archive and Undo to the task views. Let people restore tasks from
Archived. Keep archived tasks available in All tasks.

**Reason and benefit**

People can clear their personal lists and still find the original task.

**Breaking changes**

The task list API adds an optional archive filter and viewer archive
field. Existing callers use the same response and filters unless they
opt in.

## What Changed

- Reuse the current inbox archive and restore actions, activity rules,
and authorization.
- Add Archive and Restore to task table rows, Archive and Undo to
Unread, and a personal Archived view.
- Give each archived task its own Undo control, including when people
archive tasks quickly.
- Add tests for the archive list, account isolation, new activity, row
actions, and Undo.
- Document the archive flow and API filter. Refresh the generated SDK
source input registry.

## Verification

- Passed 287 focused tests in 12 Vitest files. These cover the task
views, row actions, archive cache, and PostgreSQL routes.
- Passed local server and UI typechecks. The source input registry check
also passed.
- Reproduced a missing Undo action when archiving two tasks in a row.
After the fix, the 158 task and inbox tests and the 2 toast tests
passed.
- On macOS with Chrome, archived a task from Mine and restored it using
Undo. Archived another task from All tasks, reloaded Archived, restored
it, and verified its Todo status and return to Mine.
- A human tester also verified Archive, Undo, and Restore in the local
browser.

- On commit `c5526fd9b1`, GitHub's
[verification](https://github.com/paperclipai/paperclip/actions/runs/44630156078/job/135950130662)
and [browser
tests](https://github.com/paperclipai/paperclip/actions/runs/44630156078/job/135946228919)
passed. A targeted retry passed after the first attempt hit a watchdog
self-test failure and two cancelled jobs.
- [Greptile scored
5/5](https://github.com/paperclipai/paperclip/pull/22358#issuecomment-7024083610)
on the same commit. Both review threads are resolved.

## Risks

- An incorrect visibility rule could hide a task from a personal list.
The archived filter uses the same activity predicate as Mine. The
PostgreSQL test covers isolation between people and resurfacing after a
reply.
- The archive state is already stored per person and company. No
database migration is required.

## Model Used

- OpenAI Codex, GPT-6, with shell, code editing, and browser
verification tools. The serving model ID and context size were
unavailable in this session.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [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: Scott Tong <1504818+scotttong@users.noreply.github.com>
Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-19 16:22:07 -08:00
github-actions[bot]andlockfile-bot a640b4dac8 chore(lockfile): refresh pnpm lockfiles (#22231)
## Thinking Path

> - Paperclip uses a dependency lock for reproducible builds.
> - Dependency changes on master need matching lock entries.
> - Paid eval reports also pin a reviewed offline correction.
> - Reports must install before paid model work starts.
> - This automated PR keeps the lock and report proof together.

## Linked Issues or Issue Description

**What happened?**

Dependency manifests on master changed after the last committed lock
refresh.

**Expected behavior**

Frozen installs must match those manifests. Eval reports must retain
matching offline lock proof.

**Steps to reproduce**

Run a frozen install before and after this lock refresh.

## What Changed

- Refresh the dependency lock from the manifests on master.
- Refresh the sandbox provider lockfiles from their manifests on master.
- Include the matching offline report correction and hashes.
- Resync the SDK public source proof's lock pins from the refreshed
lock.

## Verification

- Pinned pnpm resolution completed with lifecycle scripts disabled.
- The report proof refresh accepted the reviewed committed baseline.
- The workflow rejected changes outside the lock and report proof files.

## Risks

The lockfile bot merges this PR without CI or review when every added
package version is at least 3 days old on npm. Otherwise the PR waits
for a maintainer, and the daily refresh tries again. The bot merges only
the exact commit this workflow generated from manifests already reviewed
on master. Unknown report lock baselines remain blocked. This update
changes no permissions or paid enable gates.

## Model Used

None — generated by pnpm and the deterministic report-lock updater.

## Checklist

- [x] Thinking path and problem description included
- [x] Generated lock and matching report proof included
- [x] Release-age gate decides between bot merge and maintainer review

Co-authored-by: lockfile-bot <lockfile-bot@users.noreply.github.com>
2026-11-19 12:40:12 -08:00
DottaandClaude Opus 5.5 b7177db6aa fix(telemetry): report a Paperclip runner agent's underlying harness as adapter_type (#22324)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The server sends product telemetry. Two events describe agent work:
`agent.task_run` and `agent.task_completed`.
> - Each event has an `adapter_type` dimension. The generated telemetry
contract gives this dimension a fixed enum.
> - A Paperclip runner agent stores `paperclip_runner` as its adapter
type. The enum does not have this value.
> - The collector and Cloud direct delivery change a value that is not
in the enum to `other`.
> - Thus, as more agents use the runner, the adapter breakdown in
analytics becomes mostly `other`. The data is not lost, but it is in one
bucket.
> - This pull request makes a runner agent report the harness that it
runs, for example `claude_local` or `codex_local`.
> - The benefit is that the adapter breakdown shows the real harness
again.

## Linked Issues or Issue Description

Refs #8818 (this PR added the generated telemetry contract and its
`adapter_type` enum).

I did not find an existing issue. This is the bug description:

**What happened?**

`agent.task_run` and `agent.task_completed` send the stored
`agents.adapter_type`. For a Paperclip runner agent, this value is
`paperclip_runner`. The `adapter_type` enum in
`packages/shared/src/telemetry/generated/paperclip-telemetry.ts` does
not include `paperclip_runner`. The telemetry normalizer changes the
value to `other`. In analytics, almost all runner agent events show
`adapter_type = other`.

**Expected behavior**

A runner agent reports the harness that it runs. The server already
resolves this harness with `agentHarnessType()` from
`@paperclipai/shared`. For example, a runner agent with the Claude ACP
configuration must report `claude_local`.

**Steps to reproduce**

1. Create a Paperclip runner agent (`adapterType: "paperclip_runner"`).
2. Let the agent complete a heartbeat run, or let it set a task to
`done`.
3. Look at the `agent.task_run` or `agent.task_completed` event.
`adapter_type` is `paperclip_runner` before delivery, and `other` after
normalization.

**Paperclip version or commit**

`master` at 1355f93546.

**Agent adapter(s) involved**

Paperclip runner (all harnesses).

## What Changed

- `server/src/services/agent-task-run-telemetry.ts`: new
`telemetryAdapterType(agent)` helper. It returns
`agentHarnessType(agent.adapterType, adapterConfig)`. `agent.task_run`
sends this value as `adapterType`.
- `server/src/routes/issues.ts`: `agent.task_completed` calls the same
helper. Thus, the two events cannot report different adapter types for
the same agent.
- A legacy agent (for example `claude_local`) sends the same value as
before. `agentHarnessType()` returns a legacy adapter type without a
change.
- `server/src/__tests__/agent-task-run-telemetry.test.ts`:
- New tests for the default, Claude, and OpenCode runner configurations.
They expect `codex_local`, `claude_local`, and `opencode_local`.
- New contract test. It resolves every runner provider and every ACPX
agent through `telemetryAdapterType()`, and compares the result with the
generated `adapter_type` enum of both events. The test fails when a
runner harness is missing from the contract and is not in the known-gap
list.
- `server/src/__tests__/issue-telemetry-routes.test.ts`: new test that a
runner agent with the Claude ACP configuration sends `claude_local` on
`agent.task_completed`.
- `packages/shared/src/telemetry/README.md`:
- The `agent.task_run` section tells what `adapter_type` means for a
runner agent, and lists the runner harnesses that the contract does not
have yet.
- The `Emission Boundary` section tells why runner harness resolution is
not an alias map. The receiving layer does not get the agent
configuration, so it cannot derive the harness from `paperclip_runner`.
The emitter sends the resolved value raw and does not fall back to
`other`.
- `tests/runner-e2e/source-sdk-public-inputs.json`: refreshed pin for
the changed README. I ran `node
tests/runner-e2e/source-sdk-public-inputs.mjs <HEAD> --write`.

## Verification

- Red-green: before the fix, the new emitter tests failed with
`paperclip_runner`. After the fix, they pass.
- `cd server && npx vitest run
src/__tests__/agent-task-run-telemetry.test.ts
src/__tests__/issue-telemetry-routes.test.ts
src/__tests__/posthog-direct-event-shape.test.ts` and the three native
tests that mock the telemetry service: 182 tests pass.
- The contract test fails when I remove one known gap (`muse`) from the
list. Then it passes again when I restore the list.
- `cd server && pnpm typecheck`: passes.
- `node tests/runner-e2e/source-sdk-public-inputs.mjs <HEAD> --check`:
`changed: false`.
- Before the rebase, I sent the old and new values through the real
PostHog normalizer. The default, Claude, and OpenCode runner
configurations changed from `other` to `codex_local`, `claude_local`,
and `opencode_local`.
- I did not run the full local suite. `pnpm verify` asks for broader
coverage because the pin registry is a global CI input. CI supplies that
coverage.

## Risks

- Low risk. The change affects only the telemetry dimension value. It
does not change agent behavior, the database, or an API.
- Eight of the fifteen runner harnesses map to enum values:
`codex_local`, `opencode_local`, `claude_local`, `cursor`,
`cursor_cloud`, `grok_local`, `pi_local`, and `kimi_local`.
- Seven runner harnesses continue to show `other`: `acpx:copilot`,
`antigravity_runtime`, `aws_agentcore`, `claude_managed`, `grok_bot`,
`muse`, and `openai_dot`. The fix for these is a change to the contract
in the telemetry backend.
- After this change, `adapter_type` does not show the difference between
a runner agent and a legacy agent with the same harness. A separate
dimension in the telemetry contract can show this difference later.
- Events from before this change keep `other`.

## Privacy Review Request

`rules/data-paths.mdc` requires a privacy review for a telemetry change.
I request a privacy review from a maintainer. This is my analysis:

- The change does not add an event, a dimension, or an enum value. Thus,
the generated contract does not change. The contract comes from the
telemetry backend, and this repository must not edit it.
- The new value comes from `agentHarnessType()`. On each validated write
path (create, hire, PATCH, config rollback, and company import), the
server accepts only a closed set of runner `provider` and `acpxAgent`
values. Thus, the emitted value is a fixed harness identifier, not user
text.
- An agent row that does not pass these checks (for example, a
plugin-managed hire or a direct database write) can hold a different
`provider` string. Before this change, the emitter already sent the raw
`agents.adapter_type` string, which has the same exposure. The receiving
layer changes any value that is not in the enum to `other` before
analytics.
- The value never contains a prompt, a credential, a path, a model
output, or a person's name.

> 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`) from Anthropic, in Claude Code. It
used tool use (shell, file read and edit, `gh`) and extended reasoning.

## Checklist

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

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 11:20:01 -06:00
deacaf727c feat(connections): guided AWS role setup with a per-connection CloudFormation template (#22233)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The AWS connector (#22195) lets agents use AWS with credentials
minted per connection. Its role method stores no AWS keys
> - That method needs the customer to create an IAM role that trusts
exactly one Paperclip connection, but setup only offered the generic
form and a doc
> - The connect API also refused the draft step this method needs, so
the role method could not be set up through the UI at all
> - This pull request adds a guided setup screen. Paperclip saves a
draft, hands the user a prompt for their own agent that creates the
role, takes back the role ARN the agent reports, and tests the same
draft. CloudFormation and IAM steps are there under "Or do it by hand"
> - The benefit is that a person can connect AWS without stored keys and
without typing account details, using a template AWS has validated

## Linked Issues or Issue Description

Refs #22195.

**Subsystem affected**
Connections (AWS connector setup), UI, tool-access API.

**Problem or motivation**
The AWS role method must save a connection before AWS can trust it. The
API rejected `saveDraft` for every method except custom MCP servers, so
the UI could not complete this flow. There was also no screen that
showed the issuer, the subject, the trust policy or a template.

**Proposed solution**
- The connect API accepts `saveDraft` for methods that declare
`credentialMinter`.
- `GET /tool-connections/:id/aws-setup` returns the setup values and a
CloudFormation template generated for that connection.
- A new `AwsRoleSetup` step runs between saving the draft and testing
it. The role is named after the connection and CloudFormation fills in
the account, so the first form no longer asks for a role ARN; the user
pastes it back once the role exists.

**Alternatives considered**
- A one-click CloudFormation quick-create link. Rejected: AWS accepts
quick-create templates only from Amazon S3, so Paperclip would need to
host a public template bucket. The screen offers a download and a
console link instead.
- Instructions in a doc only. Rejected: too many hand-copied values.
- Asking for the role ARN up front. Rejected: the role does not exist
yet, so users had to invent an ARN and then match it exactly.
- Letting the user's agent report the role ARN to Paperclip itself,
through a short-lived link. Not done here: it needs a new
unauthenticated endpoint (and a Paperclip Cloud front-door change). The
user pastes the ARN instead.

## What Changed

- `packages/shared`:
  - The `saveDraft` validation allows methods with minted credentials.
  - New `AwsConnectionSetup` type.
- `server/src/services/connectors/aws/setup.ts` builds the setup values:
  - The issuer, audience and connection subject.
  - The provider host and the trust policy.
- A CloudFormation template with an optional identity provider
(`CreateIdentityProvider`), a role named `paperclip-<connection id>`,
`AccessPolicyArn` (`ReadOnlyAccess` by default for read-only
connections) and `AWSMCPSignInOAuthAccessPolicy`. The account comes from
CloudFormation, so the template needs no edits.
- The service method `getAwsSetup` and the route `GET
/api/tool-connections/{connectionId}/aws-setup`:
  - The route requires `connections:configure`.
  - It returns 422 for a connection that is not an AWS role connection.
- It reports whether the issuer key is published and any role ARN
already saved.
- It returns `available: false` (`address_changed`) when the instance
address changed after the draft was saved, since a role set up for the
old address could never pass the test.
  - It is registered in OpenAPI.
- UI:
- The AWS form no longer shows a Role ARN field (it is hidden with an
empty default).
- `AwsRoleSetup.tsx` shows, by default, only "Set it up with your agent"
(a copyable prompt that checks the AWS account, deploys the template
with `aws cloudformation deploy`, and reports the role ARN) and a field
to paste that ARN. "Or do it by hand" reveals the CloudFormation steps
(download, console link, parameter notes, IAM acknowledgement) and the
IAM console / AWS CLI steps with copyable values; the CLI commands read
the account ID themselves.
- It shows an access-key message when AWS cannot reach the instance, and
asks the user to save again when the instance address changed.
- Failed tests appear in place. AWS error codes show the server's own
plain message, because the shared error copy replaces every 502 with
"temporarily unavailable".
- `useAwsRoleSetupStep` owns the AWS sequence; `ConnectionSetupFlow`
only asks it for request options, hands back results and renders its
step:
- The first Connect for `aws-role` saves a draft and opens the AWS step.
  - "Test connection" resumes the same draft with the pasted role ARN.
- Back keeps the draft, so a later Connect updates it and does not
create a second one. Returning to an unfinished draft reopens the step.
- Docs: the `doc/connections/AWS.md` setup section and the plan's phase
table. The SDK public input pins are refreshed.

## Verification

- `server/src/__tests__/aws-mcp-connector.test.ts` covers a new
API-level case through the real route validation:
- Saving an `aws-role` draft over HTTP works without a role ARN, and
stores the keys the screen uses to reopen it.
- `aws-setup` returns the issuer, subject and the connection's role
name.
- The template's trust condition keys equal `<issuer host>:aud` and
`<issuer host>:sub`.
  - The template provider URL equals the issuer.
- After an address change it returns `address_changed`, and saving the
draft again records the new address.
  - An access-key connection returns 422.
  - No response field looks like a secret.
- `ui/src/features/connections/AwsRoleSetup.test.tsx` covers:
- Only the agent setup shows by default; Test connection stays off until
a valid role ARN is pasted, then sends it.
  - A saved role ARN is filled in.
- The by-hand steps and CLI commands; the agent prompt for read-only and
full access.
  - The template download (filename and object URL cleanup).
  - The unreachable-instance message.
  - The in-place error and the address-changed message.
  - The AWS message mapping.
- `ui/src/pages/apps/AppsConnect.test.tsx` covers the full two-step
flow: the form has no Role ARN field, the first Connect sends
`saveDraft: true` with no role ARN and does not finish, the AWS step
loads the setup, and "Test connection" resumes `aws-draft` with the
pasted role ARN and finishes. A second test reopens the step for a
returning draft.
- Red/green:
  - Removing the API change fails the API test.
  - Removing the draft-first wiring fails the flow test.
- Totals: server AWS, OpenAPI and connector tests (75), shared
`app-definitions` (42), UI connections and apps pages (1108). Typecheck
is clean for shared, server, UI (except Storybook's generated catalog,
which this worktree has not built) and all four server test-tree layers.
- Browser, on a real dev server with an HTTPS public address:
  - AWS appears in Connectors with its logo.
- The form has only region and access level. Connect saves the draft
(reusing an earlier one) and shows only the agent prompt and the role
ARN field; "Or do it by hand" reveals the CloudFormation and IAM steps.
- The copied prompt names the connection's role and stack, and the
template.
- Test connection with a pasted role ARN showed AWS's refusal in place
(no such role, placeholder issuer), as expected. An earlier run found
the generic 502 copy problem, which is fixed and re-checked.
- AWS CloudFormation `validate-template` (dev account, read-only)
accepts the current generated template (role named after the connection)
and reports `CAPABILITY_NAMED_IAM`. The screen tells the user to
acknowledge it.
- Not run: an agent actually running the prompt and creating a stack in
AWS, and Paperclip Cloud staging.

## Risks

- The feature is still behind `enableAwsConnector` (off by default). No
migration.
- The template creates IAM resources in the customer's account, and the
customer must acknowledge that. The role trusts only this connection's
subject.
- If the customer already has an identity provider for the issuer and
leaves `CreateIdentityProvider` at true, AWS fails the stack with a
clear error. The screen explains the parameter.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use
(shell, file edits, the in-app browser against a local dev server, AWS
CLI `validate-template` in the dev account, an exploration subagent).

## 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-19 10:53:53 -06:00
575ef12575 feat(responsibilities): file company skills under responsibilities (#22275)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - A responsibility shows the skills of the agents doing its work.
People cannot say which skills a responsibility needs.
> - The maintainer chose to file skills under responsibilities like
projects, tasks and routines.
> - Agents also need to set a skill's catalog details without rewriting
its SKILL.md.
> - This pull request lets people and agents file, move and remove
company skills under a responsibility, and adds `update_skill_details`.
> - The benefit is that a responsibility lists the skills it needs,
beside the skills its agents already hold.

## Linked Issues or Issue Description

Refs #22253, #22261 and #22274; this pull request is stacked on them.

**Subsystem affected**

Database (`responsibility_links`), shared types and validators, server
responsibility service and routes, Dashboard versions, native runner
tools, and the responsibility page UI.

**Problem or motivation**

Skills under a responsibility are only computed from the agents doing
its work. A person cannot record that "Hiring needs interviewing", and
an agent cannot file a skill when it maps work for a person.

**Proposed solution**

Add a nullable `skill_id` to `responsibility_links` and allow it as the
one target of a link. Show filed and computed skills together. Let the
file, unfile, lookup and link routes and tools take skills. Keep filed
skills in Dashboard versions so undo covers them. Add a small live tool
for a skill's tagline and categories.

**Alternatives considered**

Keeping skills computed only, and giving the skill to the agent that
runs the responsibility, was the other option. It was not chosen.
Extending `update_skill` would change its scenario contract, whose mock
needs `markdown`, so the details tool is separate.

## What Changed

- Review fixes: the default responsibility view's Skills "+" adds an
existing skill, removes a filed one, or opens an agent's skills page. A
newest Dashboard version without a skill list is upgraded in place, so
the first skill filed after it is undone. Undo files again, or removes,
only skills the restoring person can see. A read scope without a skill
condition sees no filed skill. `update_skill_details` with only
`skillId` is a no-op, as its schema allows.

- Migration `0499`: add `responsibility_links.skill_id` (FK to
`company_skills`, on delete cascade). Widen the single-target check to
four targets. Add a unique `(responsibility_id, skill_id)` index and a
`skill_id` index. The migration is idempotent and online-compatible (NOT
VALID then VALIDATE, and the indexes are built CONCURRENTLY). It is
listed in `MIGRATIONS_WITH_TOP_LEVEL_STATEMENTS`.
- Shared: `ResponsibilityLink.skillId`;
`ResponsibilitySkillSummary.linkId` and `computed`; `skillId` in the
link and lookup schemas; `skill` in `RESPONSIBILITY_FILE_ITEM_KINDS`;
optional `skillIds` in Dashboard snapshot links.
- Server: filing checks the reader's skill visibility
(`skillAccessService`). The detail merges filed and computed skills into
one card each. Lookup accepts `skillId`. Dashboard capture, restore and
summary include filed skills. A version without `skillIds` leaves filed
skills as they are when it is restored.
- Tools: `file_under_responsibility`, `remove_from_responsibility` and
`find_responsibilities_for` accept `kind: "skill"`. `get_responsibility`
returns `linkId` and `computed` for each skill. Add
`update_skill_details` (tagline and categories).
- UI: the responsibility page has "Add existing skill". A filed skill
shows "Filed here" and a remove button. Computed skills keep their
holders.

## Verification

- Server: the `responsibilit*` tests (new: file, find, move and unfile a
skill; one card for a skill that is both filed and computed; undo of a
filed skill from the Dashboard history), `skill-tools.test.ts` (new
`update_skill_details` cases), `responsibility-tools`, `routine-tools`,
`routines-routes`, `paperclip-runner-tool-authority`, `runner-api` and
`openapi-routes`: 24 files, 2723 tests passed.
- UI: responsibility page and component tests (16 files, 158 tests,
including a new filed-skill test) pass. `pnpm --filter @paperclipai/ui
typecheck` passed.
- `@paperclipai/db` `check:migrations` passes and reports the override.
The snapshot drift test passes. `tsc` passes for `db`, `shared` and the
server layers.
- Runner: catalog and semantic-tool tests (317) pass. All generator
checks pass.

## Risks

- The migration changes a check constraint on `responsibility_links`.
The replacement accepts every row that the old check accepted. It is
swapped as NOT VALID and then validated. The previous release never sets
`skill_id`.
- Deleting a company skill removes its links (cascade).
- Filed skills follow the reader's skill visibility. A skill the reader
may not see is not listed.

## 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
- [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-19 09:30:49 -06:00
b7319eb581 feat(routines): let agents list and change their person's routines in plain terms (#22274)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Routines are recurring work that an agent runs on a schedule,
webhook or request. People file them under their responsibilities.
> - #22253 and #22261 let agents read and change areas and
responsibilities. Agents still have no dedicated routine tools, and they
can change only routines assigned to themselves.
> - When a person says "move my weekly digest to Monday mornings" or
"map my routines to my responsibilities", the agent must use the generic
API, write cron, and it is refused for the person's routines.
> - This pull request adds `list_routines` and `update_routine`. It also
lets an agent change routines that the person its run works for is
responsible for.
> - The benefit is that an agent can find routines under no
responsibility, file them, and change their schedule in plain terms.
Each change is a routine revision the person can restore.

## Linked Issues or Issue Description

Refs #22261 (phase 2; this pull request is stacked on it), #22253 (phase
1).

**Subsystem affected**

Server (routine routes, native runner tool authority), the native runner
tool catalog, and the `paperclip` skill.

**Problem or motivation**

An agent can list and change only its own routines through the generic
API. It cannot change the schedule of a routine its person is
responsible for. It must write cron expressions, and it cannot find the
routines that are filed under no responsibility.

**Proposed solution**

Make the existing scenario operation `list_routines` live, with filters
for words, status, agent, project, responsible person, a responsibility
and "unfiled". Add `update_routine` for the title, instructions, agent,
project, status, priority, a plain `schedule`, and filing under a
responsibility. Let an agent manage a routine when the person its run
works for is responsible for it. Handing the routine to another agent
needs that person to have `tasks:assign`.

**Alternatives considered**

A new `routines` permission grant would add a setting with no current
need. Routine revisions already give an undo path, so this change adds
no new history.

## What Changed

- `list_routines` is now live (it was a scenario-only mock) and keeps
its scenario mock.
- Add `update_routine`. A `schedule` such as `{ frequency: "weekly",
dayOfWeek: "monday", time: "09:00", timezone }` maps to the routine's
schedule trigger through the existing routine-offer cadence helpers.
`schedule: null` turns the schedule off. `fileUnder` files the routine
under a responsibility.
- Add `server/src/services/routine-tools.ts`. It calls the routine
routes with the run token. Fields and schedule go in one `PATCH
/routines/:id` (one transaction and revision, guarded by
`baseRevisionId`); filing follows, and if it fails after the routine
changed the tool reports what was saved. Each part reports its own undo:
the routine revision, or the Dashboard history for filing.
- `PATCH /routines/:id` takes `schedule` (`{ cronExpression, timezone?
}` or `null`) and replaces the schedule under the routine row lock, so
racing changes leave one schedule. Without a zone it keeps the current
schedule's, else uses the person's saved time zone, else answers 422.
- `GET /companies/:companyId/routines` filters `q`, `status`,
`assigneeAgentId`, `responsibleUserId`, `responsibilityId` and
`unfiled=true` in SQL.
- In `routes/routines.ts`, an agent may manage routines assigned to
itself or routines its person is responsible for. On a routine the agent
does not run, taking it from another agent (or handing it on), turning
it on, changing its schedule (also through the trigger routes), starting
a run, or restoring a revision requires that person's `tasks:assign`, as
for a person. The person must have directed the run (see #22261).
`routine.updated` activity records `onBehalfOfUserId`.
- The routine and responsibility routes share one rule,
`agentPersonInCompany` in `routes/agent-person-authz.ts`.
- The catalog keeps each live action's `requiredClaims` (`list_routines`
is `routines:read`).
- The routine tools stay visible when Responsibilities is off. Only
`responsibilityId`, `unfiled` and `fileUnder` need it.
- Update `search_api` tool pointers, the routines reference, the skill
section, the chat directive, the operation-groups spec and the pinned
counts.

## Verification

- Server: `routine-tools.test.ts` (new), `routines-routes.test.ts` (new:
an agent changes its person's routine, hands it off only with
`tasks:assign`, and is refused for another person's routine), the
`responsibilit*` tests, `paperclip-runner-tool-authority` and
`runner-api`: all pass. The first test in `routines-routes.test.ts`
(Fireflies) times out at 15 s in my sandbox on a cold import, with or
without this change. It passes with `--testTimeout=60000`.
- Server `node scripts/typecheck-layers.mjs`: passed.
- Runner: catalog, semantic-tool, eval, scenario and permission-policy
tests (316) pass. All generator checks pass.

## Risks

- Medium-low. Agents get write access to their person's routines. The
route still checks the company, the routine revision guard and
`tasks:assign` for a hand-off. The person can restore any earlier
routine revision.
- `list_routines` changes from a scenario-only mock to a live tool, so
the reconciled catalog counts change.

## 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
- [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-19 09:30:03 -06:00
DottaandClaude Opus 5.5 c0aa7751f8 feat(responsibilities): let agents change areas and responsibilities for their person, with undo (#22261)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - People keep their areas and responsibilities in Paperclip
(experimental, `enableResponsibilities`). #22253 lets agents read them.
> - Agents can still only propose. They cannot rename or archive an
area, change an active responsibility, let one go, or move work between
responsibilities in one step.
> - A person who says "file my weekly routines under Sales" must then do
it by hand.
> - The maintainer chose this rule: an agent may make each change that
its person could make, the person can undo it from the Dashboard
history, and a permanent delete still needs the person's yes on a card.
> - This pull request adds eight change tools and the server rules
behind them.
> - The benefit is that an agent maps work to responsibilities for the
person, and the person keeps control through undo and the delete card.

## Linked Issues or Issue Description

Refs #22253 (phase 1; this pull request is stacked on it).

**Subsystem affected**

Server (responsibility and area routes, Dashboard versions, native
runner tool authority), shared validators and Dashboard types, the
native runner tool catalog, the `paperclip` skill, and the Dashboard
history UI.

**Problem or motivation**

An agent that works for a person can only propose areas and
responsibilities. It cannot change active ones, archive or delete them,
or move filed work in one step. Unfiling needs link IDs. There is no way
for the person to undo an agent's change.

**Proposed solution**

When an agent acts for the person its run works for (`onBehalfOfUserId`)
and that person directed the run (the run's own task is one they made,
such as their chat, or their own message woke it; parent tasks do not
count), apply that person's own rights: their own responsibilities, or
anyone's for a company owner or admin; areas for any active member. Save
each such change as a version of the person's Dashboard, so the existing
history and Undo line show it under the agent's name. Make a permanent
delete wait for an accepted confirmation card that the agent posted. Add
`file` and `unfile` routes that take items by kind and ID, with an
optional move.

**Alternatives considered**

One card for every change, or propose-only. The maintainer chose "act
for me, with undo". A separate undo journal would need a new table and a
new UI; Dashboard versions already have both. A new version cause needs
a check-constraint migration; this change uses `change_set` with no
`interactionId` instead.

## What Changed

- Add tools `create_area`, `update_area`, `delete_area`,
`create_responsibility`, `update_responsibility`,
`delete_responsibility`, `file_under_responsibility` and
`remove_from_responsibility`. They are standard-mode only and hidden
while Responsibilities is off.
- Add the writer rule for agents in `routes/agent-person-authz.ts`
(`agentPersonInCompany`, `agentActsForResponsibilityOwner`), used by
`routes/responsibilities.ts` and `routes/responsibility-areas.ts`. The
person must have directed the run: a person can name anyone as a task's
responsible person, and a run can also work for a routine's person or
the company default, so those runs do not borrow that person's rights.
An agent with no such person keeps the old propose-only rules.
- The response names only the version of the responsibility's owner (for
area changes, the acting person's), and `X-Paperclip-Dashboard-Owner`
says whose history holds it; tools return `dashboardOwnerUserId`. A
change Undo cannot reverse (the name, description, order or un-archiving
of an area other people's proposed or active responsibilities share)
saves no version and is not reported as undoable.
- `/file` without `moveFrom` follows the `/links` rule, so
`create_responsibility` with `fileItems` works for a proposal.
- A title-only create is allowed for an acting agent. It is active by
default and records the agent in `proposedByAgentId`.
- Add `responsibility-agent-changes.ts`. In one transaction that holds
each affected owner's Dashboard lock, it saves the dashboard before the
change (when a person changed it by hand), runs the change on services
bound to that transaction, and saves the result as a `change_set`
version by that agent. The response names the version in
`X-Paperclip-Dashboard-Version`. The tools say Undo only when a version
was saved.
- Dashboard snapshots now also hold each responsibility's filed items,
description, "run by" agent, evidence, health override and note, and
each area's description (optional fields). Restore puts them back. Older
versions still restore as before. A matching older version is upgraded
in place, so the first change after it compares and undoes in full.
- Create and update accept `areaTitle`. The server finds or makes that
area in the same transaction, so a refused change leaves no area. Agent
creates reuse a live responsibility with the same title under a lock, so
retries and parallel calls make no copies.
- Add `POST /api/responsibilities/:id/file` (`items`, optional
`moveFrom`: an ID or `all`) and `POST /api/responsibilities/:id/unfile`
(`items`), each in one transaction.
- Agent deletes need `confirmationId`: an accepted
`request_confirmation` card that this agent posted, with target key
`responsibility-delete:<id>` or `responsibility-area-delete:<id>`.
Someone who may manage the owner must accept it, on the card or by a
verified chat reply. The tools post the card (named after the item),
return `awaiting_confirmation`, and delete on the next call after
acceptance.
- `DELETE /api/responsibility-areas/:id` accepts
`moveResponsibilitiesTo`. Area changes and deletes save versions for
everyone whose Dashboard shows the area.
- Agent activity details now include `onBehalfOfUserId`. The Dashboard
history shows "<agent>, for you" for these versions.
`ResponsibilityDashboardVersionSummary` now has `interactionId`.
- Update the OpenAPI registry and metadata, the `search_api` tool
pointers, the skill, the API reference, the chat directive, the
operation-groups spec, and the pinned counts and SDK source pins.

## Verification

- Server: `vitest run` of the `responsibilit*` tests,
`responsibility-tools.test.ts`, `openapi-routes`, `runner-api*`,
`paperclip-runner-tool-authority` and `task-markdown` all pass. New
tests cover these cases: acting-agent create, update and undo; file,
move and undo; the rule for a person who may not manage the owner;
delete only after an accepted card, including a verified chat reply;
area delete with move and a version for the other owner; undo of a
health override, an area description and an un-archived empty area;
upgrade of an older version; an area by title that a refused change
rolls back; parallel creates.
- UI: `DashboardEditModule.test.tsx` and
`responsibility-dashboard.test.ts` passed. `pnpm --filter
@paperclipai/ui typecheck` passed.
- Server `node scripts/typecheck-layers.mjs` passed.
- Runner: catalog, semantic-tool, eval, protocol-action and
permission-policy tests (284) passed. All generator checks pass.
- I did not run the browser e2e suite locally.

## Risks

- Medium. Agents that work for a person can now change and archive that
person's responsibilities and areas without a card. Every change is a
Dashboard version that the person can restore, and a delete still needs
the card.
- Undo restores titles, sentences, areas, order, status, filed items,
description and the "run by" agent. It does not restore a bar or metric
change; those stay in the metric history.
- A restore of a version from before this change does not touch filed
items, which matches the earlier behavior.
- Undo of a rename or archive of an area that other people also use
keeps its name, as the existing restore rule does for shared areas.
- Manual edits do not take the Dashboard lock. A person's edit that
commits while an agent's change is open can appear in that agent's
version.
- Changes to proposed or let-go responsibilities are not on a Dashboard,
so they cannot be undone there. The tools say so.

## 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
- [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-19 09:29:11 -06:00
DottaandClaude Opus 5.5 ffcd49f6aa feat(responsibilities): let agents read a person's areas and responsibilities (#22253)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - People keep their areas and responsibilities in Paperclip
(experimental, `enableResponsibilities`). Agents chat with them about
this work.
> - Agents have no dedicated tool to read a person's responsibilities.
The only path is the generic `search_api` and `call_api` fallback.
> - That path needs the person's user ID, and nothing in a chat tells
the agent that responsibilities exist. When the feature is off, every
route returns a 404 that looks like "nothing there".
> - So a chief-of-staff agent asked the person "what are your
responsibilities, or where are they written down?" when Paperclip
already had them.
> - This pull request adds three read tools, makes the owner default to
the person the run works for, and tells agents in chats how to use the
tools or that the feature is off.
> - The benefit is that an agent reads and maps a person's
responsibilities itself. This is phase 1 of 4. Later pull requests add
the change tools for areas, responsibilities, routines and skills.

## Linked Issues or Issue Description

**Subsystem affected**

Server (responsibility routes, native runner tool authority, chat
prompt), native runner tool catalog, and the `paperclip` skill.

**Problem or motivation**

An agent in a chat cannot find a person's responsibilities. It has no
dedicated tool. The list route requires `ownerUserId` from an agent, and
the chat does not give the agent that ID. The chat prompt does not
mention responsibilities. When the experiment is off, the 404 does not
tell the agent that the feature is off. The agent then asks the person
to list their responsibilities again.

**Proposed solution**

Add three optional native tools: `list_responsibilities`,
`get_responsibility` and `find_responsibilities_for`. They call the
existing routes with the run's agent token, so all route checks and the
activity log stay the same. The owner defaults to the person the run
works for. The routes return a `responsibilities_disabled` code while
the feature is off. The tools are hidden while the feature is off, and
the chat prompt then says that the feature is off.

**Alternatives considered**

Better `search_api` guidance alone still needs the user ID and many
calls. A new read service in the tool authority would copy the route
permission rules. The tools use the routes instead.

## What Changed

- Add `list_responsibilities` (areas with their responsibilities,
responsibilities with no area, totals, and company work filed under no
responsibility), `get_responsibility` (one responsibility with its filed
items, link IDs, skills and latest status report), and
`find_responsibilities_for` (where a project, task or routine is filed;
a task can be a `PAP-12` identifier).
- Add `server/src/services/responsibility-tools.ts`. It calls the routes
over HTTP with the run token and returns compact results with page
links.
- When an agent sends no `ownerUserId`, the responsibility list, create,
summary, automation and dashboard routes use the person the run works
for (`onBehalfOfUserId`). A run that works for no person still gets a
422 with a clear message.
- The nine "not enabled" checks now throw one shared error. The 404 and
its message do not change. The body now also has `code:
"responsibilities_disabled"` and a remediation line. One
`RESPONSIBILITIES_OFF_GUIDANCE` text is the remediation, the tool error
and the chat prompt note.
- `list_responsibilities` with `areaId` counts only that area. Archived
areas are listed only on request. When only proposals are hidden, the
tool says so.
- `services/paperclip-api-loopback.ts` holds the tools' authenticated
API call; the project tools use it too.
- Show the tools only while the instance has Responsibilities on. A
hidden tool that is called by name returns "Areas and responsibilities
are turned off".
- In standing chats, add an "Areas and responsibilities" prompt block:
use the tools before you ask the person, or say that the feature is off.
- `search_api` results for these routes now name the dedicated tools.
- Add an "Areas and responsibilities" section to
`skills/paperclip/SKILL.md` and to `references/api-reference.md`. Add
one line to the chief-of-staff persona.
- Register the tools in the runner catalogs. Regenerate the semantic
contracts, the action catalog, protocol coverage, the operation-groups
spec and the capability inventory. Update the pinned counts.

## Verification

- `pnpm --filter @paperclipai/paperclip-runner exec vitest run
src/catalog src/semantic-tools src/tools src/eval/workflow-evals.test.ts
src/protocol-actions src/evals/native-execution.test.ts
src/drivers/acpx/permission-policy.test.ts`: 276 passed.
- All runner generator checks pass: protocol manifest, capability
contract, capability inventory, protocol coverage, semantic contracts,
semantic action catalog, operation groups, replay goldens, workflow
traceability.
- Server: `vitest run` of `responsibilit*` route tests,
`responsibility-tools.test.ts` (new), `task-markdown.test.ts`,
`task-context*`, `paperclip-runner-tool-authority.test.ts`,
`runner-api.test.ts`, onboarding first-task tests and
`user-facing-wording-guidance.test.ts`: 20 files, 2620 tests passed.
- `node scripts/typecheck-layers.mjs` for the server: passed.
- New tests cover these items: the owner default for an agent and the
422 without a person, the `responsibilities_disabled` code on every
route, the tool projections, an identifier lookup, the "turned off"
mapping, the tool visibility switch, and the chat prompt block.

## Risks

- Low risk. The routes keep their permission checks. Agents can still
only read and propose in this phase.
- An agent that sends no `ownerUserId` now gets the responsible person's
list instead of a 422. Agents that name an owner see no change.
- The chat prompt gets one more short block in standing chats.
- The flag is pinned when a turn opens. If an admin changes it during a
turn, the tool list changes on the next turn. The routes always check
the current setting.

## 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
- [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-19 08:52:42 -06:00
DottaandClaude Opus 5.5 53fedd653b fix(connections): split GitHub Copilot into its own connector (#22238)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The Connectors catalog lets people give agents tools and AI
accounts.
> - GitHub showed repository access and GitHub Copilot authentication on
one card.
> - The card had an extra "Connect Copilot" button. Saved Copilot
accounts showed in the GitHub account list.
> - These are two different products. People must find each one by its
own name.
> - This pull request makes GitHub Copilot a separate connector. GitHub
keeps repository and MCP access only.
> - The benefit is a clear catalog. Each card opens its own setup, and
saved accounts show on the correct card.

## Linked Issues or Issue Description

**What existing behavior does this improve?**

Discovery and setup of the GitHub and GitHub Copilot connectors.

**Current behavior**

The GitHub card says "Connect GitHub repository access or authenticate
GitHub Copilot agents." It shows a "Connect Copilot" button next to its
own Connect button. Saved Copilot accounts show in the GitHub account
list. Agent connection search returns Copilot as a method of GitHub. The
Copilot setup link that search gives to agents opens the GitHub tool
setup.

**Proposed behavior**

GitHub and GitHub Copilot are two cards. GitHub says "Give agents access
to GitHub repositories, issues, and pull requests." GitHub Copilot has
its own logo and opens Copilot token setup. Saved Copilot accounts,
including accounts saved before this change, show on the GitHub Copilot
card.

**Reason and benefit**

People do not have to know that Copilot is behind the GitHub card. The
catalog names the two products. The Copilot runtime keeps the same
provider identity, token storage, grants, and model discovery.

**Additional context**

This follows the same pattern as the GitHub Code Review Bot split in
#14750. Copilot setup was added in #15705.

## What Changed

- Add a `github-copilot` app definition with the existing
`copilot-token` method. Remove that method from `github`. Restore the
GitHub description and the `developer` category.
- Add the GitHub Octicons Copilot mark (MIT license, from
`primer/octicons`) as light and dark brand assets.
- Map the `github` AI provider to the `github-copilot` catalog entry in
`aiConnectionCatalogSlug`. New Copilot accounts save under a "GitHub
Copilot" application.
- Remove the "Connect Copilot" button from the GitHub card.
- Show saved AI accounts on the card for their provider. This includes
Copilot accounts that were saved under the GitHub application. The
connection page and its reconnect link use the same rule.
- Redirect old `/apps/connect?source=github&method=copilot-token` links
to `source=github-copilot`. Keep the other query values.
- Keep the "My GitHub account" identity wording on the Copilot access
step.
- In connection search and connection requests, file AI accounts under
their catalog entry. Accept the `github` provider for the
`github-copilot` service. Copilot authentication recovery cards now open
GitHub Copilot setup, not GitHub tool setup.
- Keep older Copilot accounts and requests working. An older account
saved under the GitHub application reconnects through GitHub Copilot,
and an older Copilot draft resumes through GitHub Copilot. A recovery
request saved with the `github` service name can complete. A Copilot
request declined before this change stays declined in its continuation.
Adoption accepts the `github` provider binding for a `github-copilot`
request.
- Move the rule that finds an AI account's catalog entry
(`aiConnectionSourceSlug`) into `@paperclipai/shared`, so the UI and
server use one copy.
- Use the Copilot logo for Copilot in the AI account picker and account
details.
- Update the GitHub Copilot connection doc and the GitHub connections
Storybook story. The GitHub and GitHub Copilot setup stories open
**Change** before checking "Connect GitHub as", because that heading
sits in the collapsed access section.

## Verification

- New and updated tests fail on `master` and pass with this change:
  - `pnpm exec vitest run packages/shared/src/app-definitions.test.ts`
- `pnpm exec vitest run ui/src/pages/apps/Browse.test.tsx
ui/src/pages/apps/AppsConnect.test.tsx
ui/src/pages/apps/AppDetail.test.tsx
ui/src/pages/apps/app-connect-policy.test.ts
ui/src/pages/apps/Connections.test.tsx`
- `pnpm exec vitest run
server/src/__tests__/connection-intents-service.test.ts
server/src/__tests__/ai-connections.test.ts`
- `pnpm exec vitest run
ui/src/features/connections/ConnectionSetupFlow.oauth.test.ts`
- Older-account tests cover reconnect, draft resume, completion of a
request saved with `github`, a request declined before the split, and
Copilot adoption. Each test fails without its fix.
- The play functions of all 8 stories in
`github-connections.stories.tsx` pass when rendered with
`composeStories` in jsdom.
- Brand checks: `node scripts/check-app-brand-assets.mjs`,
`ui/src/lib/app-brand-assets.test.ts`, and
`ui/src/pages/apps/AppLogo.brand-assets.test.tsx`.
- Typecheck: `@paperclipai/shared`, `@paperclipai/ui`, and
`@paperclipai/server`.
- Manual check in `pnpm dev:once` with a local company:
1. Open Connectors and search for "GitHub". Two cards show: "GitHub" and
"GitHub Copilot". GitHub has no "Connect Copilot" button.
2. Seed one GitHub tool account and one Copilot account under the GitHub
application, as older installs have them. The GitHub tool account shows
on GitHub. The Copilot account shows on GitHub Copilot.
3. Click Connect on GitHub Copilot. The "Connect GitHub Copilot" page
opens with the Copilot logo and the token field.
4. Open `/apps/connect?source=github&method=copilot-token`. The page
redirects to `source=github-copilot`.
  5. Open GitHub setup. It offers repository access only.
  6. Check the catalog in light and dark themes.

## Risks

- Low risk. There is no database migration. Existing Copilot accounts
keep their application and stored source. The UI and connection search
group them by their AI provider.
- New Copilot accounts save under a new "GitHub Copilot" application and
record `github-copilot` as their source. Code that finds GitHub
repository identities by `sourceTemplateKey === "github"` no longer sees
new Copilot accounts. These are AI accounts, so this is the intended
separation.
- A pending Copilot recovery card from before this change keeps the
`github` service slug. The server still resolves it to GitHub Copilot,
and the card can complete.
- Search for "github" now returns two results: GitHub and GitHub
Copilot.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`) through Claude Code, with tool use
(shell, file edits, test runs, and a headless browser for the manual
check).

## Checklist

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

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 08:51:36 -06:00
DottaandClaude Opus 5.5 70a4351343 fix(restart-chaos): grade double executors on local runner identities only (#22307)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The restart-chaos harness grades release swaps. One rule,
`MS_double_executor`, flags a run that records a second runner identity
before the first one is shown stopped.
> - The server records stop evidence (`native.local_process_stopped`)
only for local processes. It never records it for a sandbox
(`targetKind: "remote"`) process.
> - So when a sandbox run relaunches its runner inside the same run (a
session retry after a reconnect), the grader counts each new sandbox PID
as a second executor. Sandbox PIDs are also in a different PID space
from the server.
> - In a 197-task wave, run `c5b1f8ae` (a Daytona run that retried its
session after a reconnect) was reported as 2 double executors. The
runner journal shows the first turn was stopped with
`providerExitConfirmed: true` before the relaunch, so nothing ran twice.
> - This pull request makes the rule grade only local identities, as
`SCENARIOS.md` already describes it ("a second local runner identity").
> - The benefit is that the duplicate count in release-swap results
shows only real duplicates.

## Linked Issues or Issue Description

**What happened?**
The release-swap grade reported "2 double executor(s)" for one Daytona
run whose session retried in the same run. The previous provider process
had confirmed exit. No two processes ran together.

**Expected behavior**
`MS_double_executor` charges only local runner identities. A sandbox
relaunch is not a double executor.

**Steps to reproduce**
1. Run a restart-chaos wave on Daytona.
2. Have one run retry its native session in the same run (a reconnect).
3. Read `release-swap-summary.md`. The run appears under double
executors once per relaunch.

**Paperclip version or commit**
`master` at 1c67687998.

## What Changed

- `tests/restart-chaos/multi-server.ts`: reads `payload.targetKind` for
runner identity events and skips `remote` identities in
`MS_double_executor`.
- `tests/restart-chaos/multi-server.test.ts`: adds a red/green test with
three sandbox relaunches of one run.
- `tests/restart-chaos/SCENARIOS.md`: states that sandbox identities are
not graded, and why.

## Verification

- Red: without the filter, the new test fails (2 violations for 3 remote
identities).
- Green: `npx vitest run --config tests/restart-chaos/vitest.config.ts
tests/restart-chaos/multi-server.test.ts` passes (16 tests).
- `tsc -p tests/restart-chaos/tsconfig.json` shows no errors in the
changed files.

## Risks

- Low risk. Harness only; no product code.
- A real double executor inside a sandbox is not caught by this rule. It
was never reliably caught before: no remote stop evidence exists, so
every remote relaunch was flagged. Sandbox ownership stays graded by the
Runner checkpoint owner checks.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, via Claude Code with
tool use (shell, file edit). 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-19 03:50:33 -06:00
Nicky Leach 1c67687998 feat(runner): start a released Runner again as the next run (#22288) 2026-11-18 23:17:30 -08:00
170e1b0c07 feat(runner): pin Codex 0.170.0 and Agent SDK 0.3.328 so Fable 5.2 and GPT-6.2 run (#22278)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Paperclip Runner runs Claude and Codex agents from one shared
provider pack. The pack pins an exact Claude Agent SDK (which bundles
Claude Code) and an exact Codex CLI.
> - #22222 added Claude Fable 5.2 (minimum Claude Code 2.1.321) and
GPT-6.2 Sol and Astra (minimum Codex 0.169.1). The pack still bundles
Claude Code 2.1.286 and Codex 0.160.0.
> - Because of this, Paperclip Runner stops these models with a named
version error, and native remote Codex accepts only `>=0.149.0
<0.161.0`.
> - This pull request moves the provider pack to Agent SDK 0.3.328
(Claude Code 2.1.328) and Codex 0.170.0. It moves every constant that
depends on these pins, and the remote Codex window to `<0.171.0`.
> - The benefit is that Fable 5.2 and GPT-6.2 run on Paperclip Runner
after a sandbox image with this pack is promoted.

## Linked Issues or Issue Description

Refs #22222 (adds the models and the version floors; this pull request
makes them runnable on Paperclip Runner).
Refs #18488 (moves only the Codex pin to 0.166.0 and the window to
`<0.167.0`; it is not updated since November 1 and has conflicts with
`master`).
Refs #18486 (GPT-6.1 Terra needs Codex 0.165.0; Codex 0.170.0 satisfies
it).

**Overlap with #18488.** #18488 changes the same Codex pin locations.
This pull request uses a newer pin (0.170.0) and also moves the Claude
runtime. If this pull request merges first, #18488 has no remaining
change. I did not change the #18488 branch.

## What Changed

- Claude runtime: `@anthropic-ai/claude-agent-sdk` 0.3.286 → 0.3.328
(Claude Code 2.1.286 → 2.1.328). This changes the root `pnpm.overrides`,
`pnpm-workspace.yaml`, the ACPX `claude` profile, and the qualified
Claude runtime in `installation-integrity.ts`, with new executable
digests for Linux x64, Linux ARM64, macOS ARM64, and macOS x64.
- Codex runtime: `@openai/codex` 0.160.0 → 0.170.0. This changes the
runner dependency, the `codex-acp@1.6.2>@openai/codex` override, the
`codex-acp` patch dependency line, the ACPX `codex` profile, and the
qualified Linux x64 runtime with its new executable digest.
- The ACP bridges do not change: `claude-agent-acp` 0.73.0 and the
patched `codex-acp` 1.6.2. Their `commandDigest` values and profile
versions do not change.
- Generated declarations: `generated-profiles.ts` and
`generated_acpx_profiles.rs` are regenerated with
`generate:acpx-profiles`.
- Remote native Codex window: `REMOTE_CODEX_MAXIMUM_VERSION_EXCLUSIVE`
0.161.0 → 0.171.0. The minimum stays at 0.149.0. Images with Codex
0.149.0 through 0.170.x are accepted.
- Codex company observability: the qualified-version check moves to
`codex-cli 0.170.0`. The `otel` configuration keys that Paperclip writes
(`exporter`, `trace_exporter`, `metrics_exporter`) are present in the
0.170.0 configuration schema. The `OtelExporterKind`,
`OtelHttpProtocol`, and `OtelTlsConfig` definitions are identical to
0.160.0.
- Daytona runner image probes (`Dockerfile`, `Dockerfile.release`)
expect `codex-cli 0.170.0` and `2.1.328 (Claude Code)`. The remote npm
install spec in `server/src/adapters/registry.ts` is
`@openai/codex@0.170.0`.
- Tests: fixtures and assertions that mirror the pins use the new
versions. The window tests accept 0.161.0 through 0.170.99 and reject
0.171.0. The ACPX gate tests now show that Fable 5.2 and GPT-6.2 are
admitted. A new test mocks an older bundled runtime and keeps the named
version-gap errors covered. The fallback test shows that GPT-6.2 stays
on 0.170.0 and still falls back on 0.160.0.
- Opt-in qualification scripts
(`scripts/tests/native-cleanup-paginated-codex.mjs`,
`native-provider-startup-codex.mjs`) require Codex 0.170.0.
- Documentation: `docker/daytona-runner/README.md`,
`doc/architecture/paperclip-runner-compatibility.md`,
`doc/agent-observability.md`, `docs/deploy/environment-variables.md`,
and the deferred item in `doc/adapter-model-audit-2026-11-18.md`.
- `pnpm-lock.yaml` is not part of this pull request. The refresh bot
regenerates it on `master`, as for the previous pin refreshes (#14942,
#14993).

## Verification

Sources, checked on 2026-11-19:

- npm registry: `@openai/codex@0.170.0` (published 2026-11-18T03:45Z)
and `@anthropic-ai/claude-agent-sdk@0.3.328` (published
2026-11-18T23:13Z, `claudeCodeVersion` 2.1.328). Both are the `latest`
tags.
- [Codex releases](https://github.com/openai/codex/releases) 0.161.0
through 0.170.0. The notes record no app-server protocol break. 0.169.0
keeps project configuration disabled for `codex exec` in untrusted
directories; Paperclip's CLI path already uses `--skip-git-repo-check`,
and the native path uses `app-server`.
- [Claude Code
changelog](https://github.com/anthropics/claude-code/blob/main/CHANGELOG.md)
2.1.287 through 2.1.328. See "Risks" for the headless changes that I
reviewed.

Digests and package shape:

- I downloaded each platform archive with `npm pack`, which verifies
registry integrity, and computed the SHA-256 of the executable. As a
method check, the same command on the 0.3.286 Linux x64 archive gives
the digest that is on `master` (`fe503f65…`). The Codex 0.160.0 archive
also gives the `master` digest (`12eb3e81…`).
- The extracted executables report `codex-cli 0.170.0` and `2.1.328
(Claude Code)`.
- The Codex 0.170.0 Linux x64 archive no longer contains
`codex-resources/zsh/bin/zsh`. Paperclip does not reference that path.
- The Agent SDK 0.3.328 `optionalDependencies` have the same platform
set as 0.3.286. The Codex 0.170.0 `optionalDependencies` use the same
`npm:@openai/codex@<version>-<platform>` aliases.
- Bridge link check: I installed
`@agentclientprotocol/claude-agent-acp@0.73.0` with an override to Agent
SDK 0.3.328 and imported its entry module. Node linked all of the named
SDK imports, and the import completed.

Real Codex qualification (no model turn, no credentials):

- `PAPERCLIP_TEST_CODEX_BINARY=<installed 0.170.0 Linux x64 binary> node
--import ./server/node_modules/tsx/dist/loader.mjs
scripts/tests/native-cleanup-paginated-codex.mjs` passed: `green: true`,
with the expected red control and paginated `thread/resume` through the
real 0.170.0 `app-server`. The installed binary digest matches the
pinned digest.

Focused suites (Linux x64, Node 25.9.0, local `pnpm install
--no-frozen-lockfile`):

- `cd packages/paperclip-runner && pnpm run typecheck:typescript`
passed, including `check:acpx-profiles`.
- `npx tsc --noEmit` passed in `packages/adapters/codex-local` and
`packages/adapters/claude-local`.
- `packages/adapters/codex-local`: 625 passed.
`packages/adapters/claude-local`: 419 passed, 1 skipped.
- `node --test`: `acpx-codex-package-contract` 9 passed,
`controlled-evals/controller` 77 passed, `scripts/acpx-patch-packaging`
26 passed, `scripts/__tests__/grok-public-install-sandbox` 27 passed.
- `server`: `acpx-qualification`, `codex-runtime-compatibility`, and
`codex-model-fallback` 110 passed. `native-session-executor` 1541
passed, 1 failed. The failure (`compares export process compatibility …
db.transaction is not a function`) also fails on unchanged `master` on
this host.
- `packages/paperclip-runner` vitest (`installation-integrity`,
`qualified-profiles`, `codex-security-config`, `native-execution`,
`native-backend-factory`): 283 passed, 25 failed. All 25 failures are in
`installation-integrity.test.ts` with "ACPX provider lifetime guardian
failed to start". The same 25 tests fail on unchanged `master` on this
host (master fails 30 here).

Rust (toolchain 1.97.1 from `rust-toolchain.toml`, Linux x64):

- `cargo test -p paperclip-runner-core --lib`: 658 passed, 2 failed, 4
ignored. `warm_run_attachment_reuses_the_provider_ingress_listener` also
fails on unchanged `master` on this host.
`reaping_stops_a_dead_runners_provider_and_its_escaped_tool_job` is
flaky here: on this branch it passed 2 of 3 reruns.
- `cargo test -p paperclip-runner-core --test acpx_warm_attachment
--test native_provider_backend`: 7 and 45 passed.
- The new and changed saved-session tests pass:
`a_session_saved_by_the_previous_agent_runtime_is_refused_by_name`,
`unrestorable_saved_sessions_keep_strict_bindings_and_name_their_class`,
and `a_settled_session_saved_by_the_previous_acpx_release_continues`.
`rustfmt --check` passes.
- `server`: `native-session-resume.test.ts` and
`acpx-qualification.test.ts` 110 passed, 2 skipped. Both new resume
cases run and pass.

Not run here:

- `native-provider-startup-codex.mjs`, because it needs a compiled
`paperclip-runnerd`. The trusted CI runner workflow covers startup and
session-resume probes.
- The Docker image build and any live model turn. A live Fable 5.2 and
GPT-6.2 test follows the staging image rollout.

## Saved sessions from the previous release

This change keeps the ACPX bridge command digests and profile versions.
It changes `agentRuntimeVersion` in the `claude` and `codex` ACPX
profiles. That field is part of the saved session identity. The previous
release saved sessions with Agent SDK 0.3.286 or Codex 0.160.0. This
build refuses those saved sessions. It does not migrate them.

- **Next run (the usual case):** the saved provider descriptor names the
old runtime. `rebindNativeSessionCheckpoint` does not match it, so the
next run starts a fresh provider session in the same workspace with the
complete handoff prompt. No run fails. The earlier provider conversation
does not carry over.
- **A run in flight at the deploy (settled or mid-turn):** the runner
restore refuses the saved descriptor with the permanent class
`provider_state_incompatible`. The server reports it as
`native_provider_state_incompatible` and stops automatic retries. The
runner opens no provider and keeps the saved state bytes and the
workspace. The next run on the task starts a fresh provider session.
- **Native Codex (`codex_app_server`) and OpenCode** sessions do not
record this field, so their resume decision does not change. After a new
image is promoted, native Codex resumes a saved thread with Codex
0.170.0 instead of 0.160.0. This pull request does not test that
cross-version thread resume.

New tests:
- `acpx_provider_backend.rs`:
`a_session_saved_by_the_previous_agent_runtime_is_refused_by_name`
covers settled Claude and Codex sessions and a Claude turn interrupted
mid-run by the deploy.
`unrestorable_saved_sessions_keep_strict_bindings_and_name_their_class`
has a new `agent_runtime_release` case. Each case checks the named
class, that no provider session opens, and that the saved bytes do not
change.
- `native-session-resume.test.ts`: "a session saved by the previous
Claude or Codex ACPX runtime" checks that a same-release session
resumes, and that a session saved with Agent SDK 0.3.286 or Codex
0.160.0 starts fresh in the same workspace.

## Risks

- Medium. Every Paperclip Runner Claude and Codex run uses the new
executables. The digests, generated profiles, image probes, and window
must agree. They agree locally, and CI runs the Rust and runner suites
again.
- Claude Code 2.1.287 through 2.1.328 change some headless defaults. I
checked each one against Paperclip:
- 2.1.302: `-p` and Agent SDK sessions with no permission mode start in
`default` mode on third-party providers. Paperclip always sets a mode
(`bypassPermissions` or `default`), so this does not apply.
- 2.1.299: MCP allow rules now match only the whole server name.
Paperclip already writes `mcp__<server>__*` and exact
`mcp__paperclip__<tool>` rules.
- 2.1.302: fork subagents are on by default in `-p` and the Agent SDK,
as in the terminal. This pull request keeps the upstream default and
does not set `CLAUDE_CODE_FORK_SUBAGENT=0`. Reviewers can ask to keep
them off.
- 2.1.299 and later: stdio MCP connections negotiate MCP protocol
2026-07-28 first and fall back to the older protocol for servers that do
not answer.
- Agent SDK 0.3.328 is less than one day old. If a regression appears,
revert this pull request to return to 0.3.286 and Codex 0.160.0.
- Sandbox images built before this change still carry Codex 0.160.0 and
Claude Code 2.1.286. They stay accepted. On those images, Fable 5.2 and
GPT-6.2 keep the existing named errors and fallbacks until a new image
is promoted.
- Until the refresh bot updates `pnpm-lock.yaml` on `master`, a local
`--frozen-lockfile` install fails, as with the previous pin refreshes.

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

## Model Used

- Anthropic Claude, model ID `claude-opus-5-5`, through Claude Code with
tool use (shell, file edit, `gh`) and code execution. The context window
and reasoning mode are not reported in this session.
- The registry archives, digests, release notes, configuration schemas,
and changelog were read directly. No model output was used as a source
for those facts.

## 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
- [ ] 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-18 20:45:18 -08:00
DottaandClaude Opus 5.5 067f7a0815 feat(telemetry): send product lifecycle events and agent run failure cause (#22250)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - First-party telemetry tells the team which product steps people
finish
> - Telemetry did not record when a model is connected, when a task is
created, completed, or blocked, when a plan is created or approved, or
when an artifact is created
> - Telemetry also did not tell why an agent run failed, so failures
could not be grouped by cause
> - This pull request syncs the new telemetry contract and sends these
events from the server once per real change
> - The benefit is a product funnel and a failure breakdown that use
only enums, booleans, and counts

## Linked Issues or Issue Description

**Subsystem affected**
Server telemetry (`packages/shared/src/telemetry`,
`server/src/services/product-telemetry.ts`) and the emit sites in the
issue, document, work product, interaction, and AI connection services.

**Problem or motivation**
The team cannot measure the main product path. There is no event for a
new model connection, a new task, a completed task, a blocked task, a
new plan, an approved plan, or a new artifact. `agent.task_run` tells
that a run failed, but not why. The signup funnel also must know when
the onboarding wizard created the first task.

**Proposed solution**
Register the events in the telemetry backend. Sync the generated
contract here. Add typed helpers. Send each event once, after the
transaction that makes the change commits. Use fixed enums for every
kind, reason, and cause.

**Alternatives considered**
A post-commit action queue on the issue service only. The native status
path and many other callers use an external transaction without that
queue, so most agent completions would not send an event. A generic
after-commit hook on the database client covers every caller.

**Roadmap alignment**
This is telemetry for existing features. It adds no new product feature.

**Additional context**
This change depends on paperclipai/telemetry-backend#150, which is
merged. Deploy that backend change before this change ships. Until then,
the collector rejects the new event names.

## What Changed

- Sync `generated/paperclip-telemetry.ts` from the backend branch as a
direct copy. Regenerate `posthog-direct/enum-fallbacks.generated.ts`
with `scripts/generate-posthog-direct-fixtures.mjs`. The loader golden
file did not change.
- Add `afterTransactionCommit()` to `@paperclipai/db`. It runs a
callback after the outermost transaction commits. It drops the callback
on rollback. Outside a transaction it runs the callback at once. A
callback that throws never fails the committed work.
- Add helpers `trackModelConnected`, `trackTaskCreated`,
`trackTaskCompleted`, `trackTaskBlocked`, `trackPlanCreated`,
`trackPlanApproved`, and `trackArtifactCreated`. Add `failureCause` to
`trackAgentTaskRun`. Assign the new events to `operational_enum_count`
retention.
- Add `server/src/services/product-telemetry.ts`. It sends each event
after commit inside `withTelemetryCompany()`, so Cloud direct delivery
gets `company_id` for background writes.
- Emit sites:
- `model.connected`: `aiConnectionService.save`, for a new connection
only. A reconnect sends nothing. `first_for_company` is true when the
company had no earlier model connection.
- `task.created`: `issueService.create`, after the insert. A
deduplicated create, a company import, and a chat conversation send
nothing. `created_by_kind` is `routine` for routine runs, `onboarding`
for the onboarding wizard's first task, and otherwise `user`, `agent`,
or `system`.
- `task.completed` and `task.blocked`: `issueService.update`, when the
status changes to `done` or `blocked`. The same status again sends
nothing.
- `plan.created`: `documentService.upsertIssueDocument`, for the first
revision of the `plan` document.
- `plan.approved`: the accept path of a `request_confirmation` that
targets the task's `plan` document.
- `artifact.created`: `workProductService.createForIssue` (`direct`),
the promotion route (`promotion`), and a run file deliverable
(`run_deliverable`).
- `agent.task_run.failure_cause`: `emitAgentTaskRun`, for `failed`,
`timed_out`, and `interrupted` runs only.
- `blocked_reason` mapping: unfinished blocking tasks give
`waiting_on_task`. Otherwise an unblock owner of a person or the board
gives `waiting_for_person`, and an agent owner gives
`waiting_for_agent`. A system write with neither gives `needs_recovery`.
A person or agent write with neither gives `unspecified`.
- `failure_cause` mapping (stored `errorCode`, with
`resultJson.providerFailure.category` for generic provider and adapter
codes):
- `missing_access`: auth and permission codes (`acpx_auth_required`,
`provider_auth_failed`, `user_secret_missing`, `github_access_denied`,
`github_repo_not_accessible`, `permission_denied`,
`project_access_denied`, `configuration_incomplete`,
`connection_unavailable`, `signing_secret_unconfigured`), and provider
category `authentication` or `permission`.
- `provider_limit`: `provider_quota`, `native_provider_usage_limit`,
`native_provider_overloaded`, `github_rate_limited`,
`ai_connection_busy`, and provider category `rate_limit`,
`quota_exhausted`, or `overloaded`.
- `provider_error`: `native_provider_model_rejected`,
`provider_transport_failed`, `codex_transient_upstream`,
`provider_failed`, `provider_tool_definition_invalid`, and the other
provider categories.
- `waiting_for_person`: `execution_reconciliation_required`, every code
in `EXECUTION_RECONCILIATION_CAUSES`, `issue_waiting_for_response`, and
`issue_continuation_waiting_on_review`.
- `task_changed`: the task was reassigned, paused, closed, blocked, or
stopped by a person (`operator_interrupted`, `cancelled`, `interrupted`,
`issue_*` lifecycle codes, `agent_paused`, `queued_comment_discarded`).
- `platform_error`: process, server, workspace, sandbox, runner, and
storage codes (`process_lost`, `server_shutdown_interrupted`,
`setup_failed`, `workspace_*`, `environment_provider_unavailable`,
`controller_lease_lost`, and others).
- `agent_error`: `adapter_failed` without a provider failure,
`invalid_output`, `invalid_response`, `tool_error`, `acpx_turn_failed`,
`test_run_failed`, `prompt_injection_blocked`,
`tool_execution_outcome_unknown`, `timeout`.
  - `unknown`: any other code, or no code.
- On Cloud direct delivery, every new emit site names the responsible
person with `withTelemetryActor()` and `resolveTelemetryPerson()`, as
`agent.task_run` does: the task creator, else the task's responsible
user, else the run owner. `task.created` uses the creating user, else
the agent's on-behalf user. `model.connected` uses the user who owns the
connection. A live request still wins. The self-hosted collector
envelope does not change.
- `failure_cause` builds on the run failure code sets in
`continuation-cause.ts`. A test fails when a code in those sets has no
telemetry code. The provider failure category decides only for
`adapter_failed`, `provider_failed`, or no code.
- Work product providers outside `paperclip`, `github`, `vercel`, and
`s3` are sent as `custom`.
- The dispatch workspace check and execution recovery write `blocked`
directly. They call the same after-commit helper, with the task's real
blockers and unblock owner. The blocker read runs in a savepoint in the
issue dependency layer, so a failed read never aborts the block write.
- Update the telemetry README with the emit rules, the after-commit
rule, and the `failure_cause` source.
- Refresh `tests/runner-e2e/source-sdk-public-inputs.json`, because its
check reported a change.

## Privacy Review

Privacy review requested. Every new dimension is a fixed enum, a
boolean, or a count. No dimension carries a title, a body, a plan step,
a connection or account name, an email, a URL, a repository name, a
prompt, an error message, or an endpoint address. `failure_cause` is a
code that the server picks. The run's error text is never sent. The
tests check that a provider message and a connection name do not reach
the event.

## Verification

- `pnpm vitest run packages/shared/src/telemetry/`: 7 files pass,
including the new `product-events.test.ts` (helper payloads, omitted
optional values, collector envelope with only registered dimensions,
retention class).
- `packages/db/src/after-transaction-commit.test.ts`: 4 pass (after
commit, rollback drop, savepoint, outside a transaction).
- `server/src/__tests__/product-telemetry.test.ts`: 14 pass. They check
that each event fires once with the right kind and company scope, that a
rollback sends nothing, that a repeated status sends nothing, that a
later plan revision sends nothing, and that a reconnect sends nothing.
- `server/src/__tests__/agent-task-run-telemetry.test.ts`: 35 pass,
including the `failure_cause` mapping table and the emit path.
- `server/src/__tests__/issue-thread-interactions-service.test.ts -t
Plan`: `plan.approved` fires for a plan confirmation and not for an
unrelated confirmation.
- `server/src/__tests__/posthog-direct-telemetry.test.ts`: the Cloud
direct path sends `company_id`, `user_id`, and `attributed_via` for
background lifecycle events, an event with no person stays on the
workspace, and `failure_cause` passes through. A self-hosted test checks
that a person scope leaves the collector events unchanged.
- Existing telemetry tests (connector, interaction, run finalizer,
heartbeat, AI connection): 299 pass.
- `pnpm --filter @paperclipai/shared typecheck`, `pnpm --filter
@paperclipai/db typecheck`, and `pnpm --filter @paperclipai/server
typecheck`: pass.
- `pnpm verify` returned exit 2 (global CI input changed). Required CI
supplies the broad coverage.

## Risks

- Merge order: merge and deploy paperclipai/telemetry-backend#150 first.
If this change ships first, the collector quarantines the new events.
The product behavior does not change.
- `afterTransactionCommit` uses the existing open-transaction marker in
the database client. A callback that a savepoint registers runs when the
outer transaction commits, even if that savepoint rolled back.
- `task.blocked` adds one small indexed read inside the update
transaction, only when a task enters `blocked`.
- `failure_cause` adds one small read for a failed run when the caller
did not pass the error code. It runs off the run's critical path, as
before.
- Low risk otherwise. No schema migration. No change to existing event
dimensions.

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

## Model Used

- Anthropic Claude Opus 5.5 (`claude-opus-5-5`), through Claude Code,
with tool use (shell, Git, tests).

## Checklist

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

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 19:32:27 -06:00
DottaandClaude Opus 5.5 92dbf39e6f feat(analytics): attribute agent work and onboarding steps to a person on Cloud (#22260)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Paperclip Cloud sends product events straight to PostHog: server
events from `server/src/services/posthog-direct/` and browser events
from `ui/src/lib/analytics/`
> - A person-level funnel goes from sign-up to the first finished task
> - Agent-driven events (`agent.task_run`, `agent.task_completed`,
`agent.first_heartbeat`) used `workspace:<stackId>` as the distinct id,
so the funnel broke at those steps
> - The in-workspace onboarding wizard sent no step events, so we could
not see where people stop before their first agent
> - This pull request attributes agent work to the responsible person on
the Cloud direct path, and adds consent-gated onboarding step events in
the browser
> - The benefit is one PostHog person per customer across sign-up,
onboarding, agent runs, and task completion. Self-hosted output does not
change.

## Linked Issues or Issue Description

**Subsystem affected**
Cloud product analytics: Cloud direct PostHog delivery (server) and
browser product analytics (UI onboarding wizard).

**Problem or motivation**
A PostHog funnel from sign-up to the first finished task cannot follow
one person. Agent-driven events run in the background, with no signed-in
request, so they use the workspace id as the distinct id. The onboarding
wizard also sends no events, so we cannot see which step people leave.

**Proposed solution**
Give background emit sites a narrow scope that names the person
responsible for the work. Use the task creator first, then the task's
responsible user, then the run owner. Keep the signed-in request user
first. Add `attributed_via` to every Cloud direct event. Add four
browser events to the onboarding wizard. Send them through the existing
analytics module, so the consent rules stay the same.

**Alternatives considered**
A lookup in the transport at send time. We did not use it: it adds
database reads to the telemetry path and loses the emit site's context.
A new contract event for onboarding steps. We did not use it: the server
does not see the wizard steps, and the UI must never send
`PAPERCLIP_EVENTS` names.

**Additional context**
Self-hosted installs keep the collector path. The collector envelope
stays byte-identical (a test checks it).

## What Changed

- `server/src/telemetry-company-scope.ts`: add `withTelemetryActor({
companyId, person }, fn)`, `scopedTelemetryPerson()`, and
`resolveTelemetryPerson()`. The resolver picks the task creator, then
the task's responsible user, then the run owner. It ignores
`local-board`. `withTelemetryCompany` now calls `withTelemetryActor`.
- `server/src/services/posthog-direct/request-context.ts`: a signed-in
request user wins (`attributed_via: request`). Without one, the scoped
person is used.
- `server/src/services/posthog-direct/event-shape.ts`: every Cloud
direct event (including `cloud.workspace_started`) has `attributed_via`
(`request`, `task_creator`, `task_assigner`, `run_owner`, or `none`). An
event with a person keeps today's person-event shape (no
`$process_person_profile: false`).
- `server/src/services/agent-task-run-telemetry.ts`: `agent.task_run`
reads the task creator and responsible user in the existing agent query
(one left join, no new query), and the run's `responsibleUserId`.
- `server/src/routes/issues.ts`: `agent.task_completed` uses the issue
row that the route already has, and the agent actor's `onBehalfOfUserId`
as the run owner.
- `server/src/services/heartbeat/agent-status.ts`:
`agent.first_heartbeat` uses the agent's `createdByUserId` (already
loaded) as the run owner.
- `ui/src/lib/analytics/product-analytics.ts`: add
`captureProductAnalyticsEvent()`. It captures only with a browser
analytics config and granted consent. Events from before posthog-js
loads wait in a queue (at most 50) and keep their time. Withdrawn
consent or a change of signed-in person drops the queue.
- `ui/src/lib/analytics/onboarding-analytics.ts` and
`ui/src/components/OnboardingWizard.tsx`: capture `onboarding_opened`,
`onboarding_step_viewed`, `onboarding_step_completed` (with `step` and,
for `connect_model` and `launch`, `outcome`), and
`onboarding_dismissed`. `step` is `create_agent`, `connect_model`,
`review`, or `launch`. No event has free text.
- Docs: `packages/shared/src/telemetry/README.md` (Cloud Direct
Delivery) and `doc/cloud-browser-analytics.md` (new "Onboarding events"
section).

## Verification

- `server/src/__tests__/posthog-direct-telemetry.test.ts`: attribution
matrix (creator, assigner, run owner, none stays on
`workspace:<stackId>` with `$process_person_profile: false`), the
request user wins over the scope, and the self-hosted collector envelope
is byte-identical with a person scope.
- `server/src/__tests__/agent-task-run-telemetry.test.ts` (embedded
Postgres): `agent.task_run` scope for creator, assigner, run owner, and
nobody; another company's task is never read.
- `server/src/__tests__/issue-telemetry-routes.test.ts`:
`agent.task_completed` scope for creator and assigner.
- `server/src/__tests__/heartbeat-process-recovery.test.ts`:
`agent.first_heartbeat` scope is the agent owner.
- `ui/src/components/OnboardingWizard.test.tsx`: a launch for the old
company that settles after a switch to another company does not end the
new analytics session.
- `ui/src/lib/analytics/onboarding-analytics.test.tsx`: each transition
fires once, held events drop on a person change, a stale opening step is
not a view, dismissal fires once, nothing is captured when analytics is
off or consent is `denied` or `ask`, and queued events keep their time.
- `ui/src/lib/analytics/product-analytics-events.test.ts` still passes
(the UI never captures a `PAPERCLIP_EVENTS` name).
- Local Cloud-mode run: an isolated instance (own Postgres, trusted
Cloud tenant headers, `PAPERCLIP_POSTHOG_HOST` set to a local capture
server, never real PostHog). A stub stood in for posthog-js and sent
through the `/_ph` proxy.
- A user created a task and assigned it to the agent. `agent.task_run`
arrived with `distinct_id: paperclip-id:local-user-1`, `attributed_via:
task_creator`, the raw `task_id`, and no `$process_person_profile`. (The
run itself failed locally because the Cloud runner is not available. The
event still shows the attribution.)
- `agent.first_heartbeat` arrived with the same person and
`attributed_via: run_owner`. `server.started` kept
`workspace:stack-local` with `attributed_via: none`.
- Headless Chromium walked the wizard: `onboarding_opened`
(create_agent), `onboarding_step_viewed` (create_agent),
`onboarding_step_completed` (create_agent), `onboarding_step_viewed`
(connect_model), `onboarding_step_completed` (connect_model, `api_key`),
`onboarding_step_viewed` (review), `onboarding_step_completed` (review),
`onboarding_step_completed` (launch, `succeeded`). Each fired once, with
the signed-in user as the distinct id. Events from before posthog-js
loaded arrived with their original time.
- A second walk left the onboarding page on the connect step and sent
one `onboarding_dismissed` (connect_model).

## Risks

- Low risk for self-hosted: the collector path never reads the new
scope, and a test checks the envelope bytes.
- Cloud: agent events move from the workspace person to a real person.
Insights that count `workspace:` distinct ids for these events will
change. `attributed_via` lets a query filter or split them.
- `task_assigner` uses the task's responsible user. Paperclip does not
store who assigned a task, so this is the person who owns or delegated
the task.
- Privacy: the new data is Cloud-only and uses ids that Cloud events
already carry. No new free text, email, or name goes on an event.
**Privacy review requested** for the Cloud attribution change (per
`rules/data-paths.mdc`). The generated contract does not change:
`attributed_via` is a Cloud-only property, like `stack_id` and
`user_id`.

> 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, used through Claude
Code with tool use (shell, file edits, headless browser).

## Checklist

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

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 18:44:45 -06:00
DottaandClaude Opus 5.5 c600d69242 Let plugin connectors declare their tool timeout (#22249)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Plugins can serve connector tools from their worker (`transport:
"plugin"`, added in #22004, #22019 and #22201).
> - The tool gateway runs these tools with a fixed 10 s default timeout.
> - Some plugin tools call backends that take 12–20 s. These calls fail
every time with "Tool execution timed out", even though the plugin's own
HTTP client waits much longer.
> - The plugin connector design said that the connector, not a fixed
gateway constant, sets the timeout.
> - This pull request lets a plugin method or a single static tool
declare `timeoutMs`, and gives plugin-served tools a 30 s default.
> - The benefit is that a plugin connector can serve slow tools like
other connectors can, within the same 60 s gateway ceiling.

## Linked Issues or Issue Description

Refs #22004, #22019, #22201. Refs #20746.

**Relationship to #20746.** This PR builds alongside #20746. It does not
supersede it. #20746 changes the default for legacy top-level plugin
tools (provider `paperclip_plugin`) to 60 s. This PR changes only
plugin-served connector tools (provider `paperclip_plugin_connection`,
`transport: "plugin"`). The two PRs touch different branches of the
gateway and can merge in either order. This PR does not pin the legacy
default in its tests, so #20746 does not break them.

**Current behavior**
A plugin connector tool always times out after 10 s, unless the caller
sends `timeoutMs`. Agents and runners do not send it. The worker RPC
also stops at 30 s.

**Proposed behavior**
A plugin can declare `timeoutMs` (1000–60000 ms) on a `transport:
"plugin"` method or on one static tool. The gateway uses that value. If
nothing is declared, the gateway waits 30 s.

**Reason and benefit**
Plugin tools whose backends take longer than 10 s can now work. Plugin
authors control the value in the manifest, and the gateway keeps its 60
s ceiling.

**Breaking changes**
None. Existing manifests stay valid. Only plugin-served tools get the
new 30 s default.

## What Changed

- `packages/shared`: `timeoutMs` is a new optional field on
`ConnectionMethodDef` and on `PluginConnectorToolDef`. The validator
accepts integers from 1000 to 60000 only. It rejects `timeoutMs` on
methods that do not use `transport: "plugin"`. New exported constants:
`PLUGIN_CONNECTOR_TOOL_TIMEOUT_MIN_MS`,
`PLUGIN_CONNECTOR_TOOL_TIMEOUT_MAX_MS`, and
`PLUGIN_CONNECTOR_TOOL_DEFAULT_TIMEOUT_MS` (30000).
- `server/src/services/plugin-connector-runtime.ts`:
`pluginConnectionToolTimeoutMs()` resolves the timeout in this order:
the tool's value, then the method's value, then 30 s. The worker
`executeTool` RPC now gets the gateway timeout plus 1 s. Thus the
gateway's `tool_timeout` error is what callers see, and the 30 s RPC
default no longer cuts off a longer declared timeout.
- `server/src/services/tool-gateway.ts`: `executePluginConnectionTool`
now applies the timeout itself, after it loads the connection. All three
plugin paths use it: session, assigned-tool and direct calls
(`executeTool`), test calls (`executeTestCall`), and approved action
execution. If a caller sends `timeoutMs`, that value wins, as before. It
is still clamped to 60 s. Approved actions keep their fixed 60 s budget.
- Other transports do not change. Remote MCP, local stdio, built-in and
legacy plugin tools keep their timeouts. (#20746 separately proposes a
60 s default for legacy plugin tools.)
- Docs: `doc/plugins/PLUGIN_SPEC.md` §11A and the plugin SDK README
describe the field, its range, and the default. The SDK manifest type
gets the field from `@paperclipai/shared`.

### Why 30 s

30 s is the same as the plugin worker manager's default RPC timeout. So,
before this change, the worker already allowed 30 s, and only the
gateway's 10 s limit stopped the call. With 30 s, the common 12–20 s
backend case works without a declaration. It is also well under the 60 s
ceiling. Tools that need more time can declare up to 60 s.

## Verification

- New `server/src/__tests__/plugin-connector-tool-timeout.test.ts` runs
the real gateway invocation path against an embedded Postgres and a fake
worker. Fake timers make the 12 s backend free in wall-clock time:
- With method `timeoutMs: 30000`, a 12 s tool succeeds through
`executeTool` and through `executeTestCall`. The worker RPC timeout is
31000.
- With tool `timeoutMs: 5000`, a 12 s tool fails at 5 s with `504
tool_timeout`.
- With no declaration, a 12 s tool succeeds (it failed at the old 10 s),
and a 45 s tool times out at 30 s.
- Manifest values above 60000, below 1000, or not integers are rejected.
A caller `timeoutMs: 120000` is clamped to 60 s.
- A legacy plugin tool (`paperclip_plugin`, a different provider path)
never reaches the connector runtime, and a caller deadline still
applies. This test does not pin the legacy default, because #20746
changes it.
- Remote MCP, local stdio and REST timeouts do not change in this PR.
Their existing timeout tests in `tool-gateway.test.ts` and
`google-workspace-rest-transport.test.ts` still apply.
- Red/green: with the source change reverted, 4 of these 5 tests fail.
The legacy-tool test passes both ways, as expected.
- `packages/shared/src/plugin-apps.test.ts`: validation cases for the
range, non-integer values, and non-plugin methods.
- Commands run:
- `pnpm --filter @paperclipai/shared typecheck && pnpm --filter
@paperclipai/server typecheck && pnpm --filter @paperclipai/plugin-sdk
typecheck`
- `cd server && npx vitest run
src/__tests__/plugin-connector-tool-timeout.test.ts
src/__tests__/plugin-connectors-plugin-transport.test.ts
src/__tests__/plugin-connector-agent-grant.test.ts` (20 passed)
- `cd packages/shared && npx vitest run src/plugin-apps.test.ts
src/app-definitions.test.ts` (76 passed)
  - `pnpm check:module-boundaries`
- Full suite not run locally. CI supplies it.

## Risks

- Low risk. Plugin-served tools now wait up to 30 s instead of 10 s by
default. An agent turn can wait longer for a slow or stuck plugin tool,
but never longer than the existing 60 s ceiling.
- The connection row lookup now runs before the timeout timer starts.
This is one indexed query.
- Dynamic tool lists (`kind: "dynamic"`) use the method's `timeoutMs`.
Per-tool values apply to static tools only.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), 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-18 18:24:03 -06:00
Devin FoleyandPaperclip d4b7ae5532 fix(tasks): require merged PR deliverables before native completion (#22244)
Keep native tasks with declared pull request deliverables active until
GitHub verifies every deliverable is merged. Preserve delivery guidance
in follow-up contracts and recheck the current outputs under task locks.

Use bounded incomplete-work feedback during reassessment, including for
saved non-Done reports. Serialize work-product restoration and identity
changes with completion. Preserve configured reviews and conversations.

Add regression coverage and repair the CI fixtures exposed during
qualification. All CI checks pass on afee630120. Greptile is 5/5 with no
unresolved review threads.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-11-18 16:20:17 -08:00