Commit Graph
8656 Commits
Author SHA1 Message Date
DottaandPaperclip e18fe61c8f perf(runner-image): parallelize pack archiving and use cloud-release-32 on master amd64 (#22992)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The Runner image workflow (`.github/workflows/runner-image.yml`)
builds `ghcr.io/paperclipai/paperclip-runner` for `amd64` and `arm64`
whenever Runner inputs change
> - Profiling recent builds showed `Build and check (amd64)` taking ~12
minutes versus ~4m 38s on `arm64`, driven by 4-core CPU saturation
during `create-provider-pack-archive.mjs` (which compressed every large
provider-pack binary serially on a single core) and during OCI tar/gzip
export on `ubuntu-latest`
> - Because `docker.yml` waits for the Runner image whenever Runner
inputs change, slow `amd64` Runner builds sit directly on the release
critical path
> - This pull request parallelizes zstd layer archive creation in
`scripts/create-provider-pack-archive.mjs` with bounded concurrency
while preserving byte-for-byte deterministic output, and routes
canonical `master` `amd64` runs of `.github/workflows/runner-image.yml`
to the larger GitHub-hosted runner (`cloud-release-32`)
> - The benefit is cutting `amd64` Runner image build time substantially
on `master` (and speeding up provider-pack archiving on every PR and
architecture) without weakening the PR/fork security boundary or
changing output bytes

## Linked Issues or Issue Description

**What existing behavior does this improve?**
`scripts/create-provider-pack-archive.mjs` layer compression throughput
and `.github/workflows/runner-image.yml` `amd64` runner sizing on
canonical `master` pushes.

**Subsystem affected**
Cross-cutting (multiple of the above)

**Current behavior**
`createProviderPackLayers` compresses `overlay.tar.zst` and each large
provider-pack file (`0.tar.zst..N.tar.zst`) sequentially on one CPU
core. In `.github/workflows/runner-image.yml`, canonical `master`
`amd64` builds run on 4-core `ubuntu-latest` (~12 minutes total vs ~4m
38s on `arm64`).

**Proposed behavior**
`createProviderPackLayers` compresses `overlay.tar.zst` and the indexed
large-file archives through a bounded worker pool
(`min(availableParallelism(), 8)`), preserving exact file ordering,
archive numbering, and byte-for-byte deterministic zstd frames. In
`.github/workflows/runner-image.yml`, canonical `master` `amd64` pushes
(`paperclipai/paperclip`, `push` to `refs/heads/master`) use
`vars.CORE_PUBLICATION_RUNNER || 'cloud-release-32'`, while all PRs,
forks, schedules, and `arm64` jobs stay on standard GitHub-hosted
runners.

**Reason and benefit**
Eliminates single-core archiving bottlenecks across all environments and
removes the 4-core `amd64` CPU bottleneck on `master` Runner image
publications.

**Breaking changes**
None.

## What Changed

- Updated `scripts/create-provider-pack-archive.mjs` to compress
`overlay.tar.zst` and large-file archives via a bounded worker pool
while preserving exact archive indices, receipt ordering, and
byte-for-byte deterministic output.
- Added `scripts/__tests__/create-provider-pack-archive.test.mjs`
verifying serial (`concurrency: 1`) and parallel (`concurrency: 4`) runs
produce identical receipts and archive bytes.
- Updated `.github/workflows/runner-image.yml` to route canonical
`master` `amd64` pushes to `vars.CORE_PUBLICATION_RUNNER ||
'cloud-release-32'` while keeping PRs, forks, schedules, and `arm64` on
`matrix.runner`.
- Added a workflow guard in
`server/src/__tests__/runner-image-workflow.test.ts` verifying only
canonical `master` `amd64` pushes use the larger GitHub-hosted runner
and never touch self-hosted AWS release fleets.

## Verification

- `node --test scripts/__tests__/create-provider-pack-archive.test.mjs`
(passed)
- Vitest: `server/src/__tests__/runner-image-identity.test.ts` (42/42
passed)
- Vitest: `server/src/__tests__/runner-image-workflow.test.ts` (18/18
passed)
- PR CI also executes the live `Runner image` workflow end-to-end
because both `scripts/create-provider-pack-archive.mjs` and
`.github/workflows/runner-image.yml` are in its PR path filter.

## Risks

- Low risk. Archive bytes and receipt structure are verified identical
between serial and parallel runs. PRs, forks, and schedules remain on
`ubuntu-latest` / `ubuntu-24.04-arm`, and `cloud-release-32` is the same
GitHub-hosted larger runner already used on `master` by `docker.yml` and
`cloud-migrator-artifacts.yml`.

## Model Used

- Gemini 3 Pro (Antigravity agent with tool use, shell execution, and
local test 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
- [ ] 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-25 16:03:05 -06:00
Dotta 168253f74d fix(telemetry): send agent.task_completed when a native run closes a task (#22963)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Paperclip sends product telemetry, and the `agent.task_completed`
event counts each task that an agent finishes
> - Only the REST issue update route (`server/src/routes/issues.ts`)
sent `agent.task_completed` when an agent moved a task to `done`
> - Native runs close tasks through `commitNativeStatusDecision` in
`server/src/services/native-runtime/status-decision-committer.ts`, which
bypasses the REST route and therefore sent `agent.task_run` without ever
sending `agent.task_completed`
> - Deployments where agents close tasks through native runs
consequently under-report completed tasks
> - This pull request supersedes #21206 (rebased onto current `master`),
sending `agent.task_completed` once after a committed native transition
into `done` without blocking finalization, with full company/person
telemetry scope and underlying Paperclip runner harness `adapter_type`
resolution
> - The benefit is accurate, deduplicated `agent.task_completed`
telemetry across both API and native completion paths

## Linked Issues or Issue Description

Refs #21206

**What happened?**
A native run closes a task through `commitNativeStatusDecision` in
`server/src/services/native-runtime/status-decision-committer.ts`. The
task moves to `done` and the run sends `agent.task_run`, but no
`agent.task_completed` event is sent because the only sender is
`server/src/routes/issues.ts` and native completion does not go through
that route.

**Expected behavior**
Paperclip sends one `agent.task_completed` event each time an agent
moves a task into `done`, on both the REST issue route and native status
commits. The event carries the same dimensions, runner harness
`adapter_type`, company scope, and person attribution as the issue
route. Replayed commits and tasks that were already `done` send nothing.

**Steps to reproduce**
1. Seed a native run ready to commit a `done` status decision on an
`in_progress` task.
2. Call `commitNativeStatusDecision` (or `finalizeNativeRun`) with a
`done` decision.
3. Observe that the task moves to `done`, while
`trackAgentTaskCompleted` is called 0 times.

**Paperclip version or commit**
`master` at `2d065677959b585065ff3fec8718156a4cf6f41d`.

## What Changed

- `server/src/services/agent-task-run-telemetry.ts`: add
`emitAgentTaskCompleted`. It loads the agent within the task's
`companyId`, resolves the underlying runner harness with
`telemetryAdapterType(agent)`, resolves person attribution with
`resolveTelemetryPerson`, wraps `trackAgentTaskCompleted` in
`withTelemetryActor({ companyId, person }, ...)`, and never throws.
- `server/src/services/native-runtime/status-decision-committer.ts`:
select `originRun.responsibleUserId` alongside `originRun.agentId`,
capture the completion payload only when the committed transaction
transitions `issue.status` from non-`done` to `done` with an origin
agent, and invoke `void emitAgentTaskCompleted(input.db, completedTask)`
after commit when `!committed.replayed` so slow lookups cannot block run
finalization.
-
`server/src/services/native-runtime/native-task-completed-telemetry.test.ts`:
add embedded-Postgres regression tests covering single emission (with
company scope, person attribution, and underlying runner harness
`adapter_type`), no duplicate on replay, non-blocking commit while
telemetry is pending, and no emission when the task was already `done`.
- `server/src/__tests__/agent-task-run-telemetry.test.ts`: add unit/DB
coverage for `emitAgentTaskCompleted` (company/person scope, runner
harness `adapterType`, cross-company agent isolation, and error
swallowing).
-
`server/src/services/native-runtime/native-run-finalizer-telemetry.test.ts`:
add an end-to-end `finalizeNativeRun` integration test verifying a real
native run completion emits `agent.task_completed` once through the real
`trackAgentTaskCompleted` path and emits no duplicates on replay or
reconciliation.

Note: this PR supersedes #21206 (whose fork branch had merge conflicts
with pruned test suites and predated `withTelemetryActor` /
`telemetryAdapterType` on `master`, and whose fork repository did not
allow maintainer pushes from this account).

## Verification

- **RED (before fix on `2d065677959b585065ff3fec8718156a4cf6f41d`):**
`pnpm --dir server exec vitest run
src/services/native-runtime/native-task-completed-telemetry.test.ts`
Result: 1 failed | 1 passed — `sends agent.task_completed once with
company, person, and harness adapter_type when the runner closes a task`
failed with `AssertionError: expected "vi.fn()" to be called 1 times,
but got 0 times`.
- **GREEN (after fix):**
`pnpm --dir server exec vitest run
src/services/native-runtime/native-task-completed-telemetry.test.ts
src/__tests__/agent-task-run-telemetry.test.ts
src/services/native-runtime/native-run-finalizer-telemetry.test.ts
src/__tests__/heartbeat-status-preserving-telemetry.test.ts
src/__tests__/issue-telemetry-routes.test.ts`
Result: **5/5 files, 106/106 tests passed**
(`native-task-completed-telemetry.test.ts` 3/3,
`agent-task-run-telemetry.test.ts` 55/55,
`native-run-finalizer-telemetry.test.ts` 42/42 including end-to-end
`finalizeNativeRun`, `issue-telemetry-routes.test.ts` 5/5,
`heartbeat-status-preserving-telemetry.test.ts` 1/1).
- **Typecheck:** `pnpm --filter @paperclipai/server typecheck` —
**PASS** (0 errors across all layers).
- **Test budget:** `node scripts/check-test-budget.mjs --files
server/src/services/native-runtime/native-task-completed-telemetry.test.ts
server/src/__tests__/agent-task-run-telemetry.test.ts
server/src/services/native-runtime/native-run-finalizer-telemetry.test.ts`
— **PASS** (110 nightly suites validated, 3 test files checked).
- **Broader suite:** `pnpm verify --base
2d06567795 --explain` conservatively
selected 1948/2302 files; PR CI supplies the full sharded server,
runner, typecheck, and build verification.
- **Runtime dependency assumption
(`rules/runtime-dependency-boundaries.mdc`):**
`commitNativeStatusDecision` fires `void emitAgentTaskCompleted(...)`
after transaction commit without awaiting it;
`native-task-completed-telemetry.test.ts` verifies with a
never-resolving promise that run finalization returns immediately even
if the telemetry lookup hangs.

## Risks

- Low risk. Emission runs after transaction commit as fire-and-forget
and catches all errors, so a rolled-back commit sends nothing and a
telemetry fault cannot fail or delay a status commit.
- Deployments where native runs close tasks will see
`agent.task_completed` counts rise to reflect actual completions, which
is the intended fix.

## Model Used

- Google Antigravity (`antigravity`, tool use and code execution),
building on and rebasing #21206 onto `master`.

## 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
2026-11-25 16:02:12 -06:00
Dotta 702368ffaf feat(github): graduate GitHub review bots out of experimental (#22996)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - GitHub Code Review Bot connects an agent to a dedicated GitHub App
so it reviews pull requests and responds to GitHub mentions
> - The feature was gated behind the default-off
`enableGitHubReviewBots` experimental instance setting, hiding the
catalog card, setup routes, identity links, and channel creation
> - People had to find and flip an instance-level experimental switch
before they could connect a GitHub review agent
> - This pull request graduates GitHub review bots to a normal always-on
feature, keeping `enableGitHubReviewBots` only as a deprecated
compatibility key that always resolves to `true`
> - The benefit is that every Paperclip instance exposes GitHub Code
Review Bot setup, discovery, and management by default without requiring
feature flags

## Linked Issues or Issue Description

**What existing behavior does this improve?**
GitHub Code Review Bot discovery, catalog visibility, setup/management
routes, identity-link endpoints, and Agent Channels visibility
(`enableGitHubReviewBots`).

**Subsystem affected**
Cross-cutting (`packages/shared`, `server/`, `ui/`, Storybook, E2E
specs, docs).

**Current behavior**
GitHub Code Review Bot is hidden from Connectors, `connections_search`,
chat-endpoint creation, identity-link confirmation, and UI
setup/settings routes until an instance admin turns on **Settings →
Experimental → GitHub review bots** (`enableGitHubReviewBots`).

**Proposed behavior**
GitHub Code Review Bot is always available as a standard feature on
every instance (self-hosted and Cloud), matching AgentMail and graduated
features such as Assistant connections (`enablePublicMcp`) and the AWS
connector (`enableAwsConnector`). `enableGitHubReviewBots` stays in
schemas and the feature catalog only as a deprecated compatibility key
that always normalizes to `true`, ignores stored or Cloud-managed
`false` values, and does not reject legacy `false` patches. Experimental
chat providers (Slack, Discord, Microsoft Teams, Telegram, iMessage
Photon, Speko) remain gated by `enableChatConnectors`.

**Reason and benefit**
Users can connect and manage GitHub review agents directly from
Connectors without an admin enabling an experimental flag first, and
Cloud stacks no longer require managed feature-flag overrides to expose
GitHub review bots.

**Breaking changes**
No schema migration or breaking API change. Existing rows, API patches,
and Cloud managed configs that still carry `enableGitHubReviewBots`
continue to parse cleanly, while the effective value is always `true`.
Instances that previously kept `enableGitHubReviewBots` off now display
GitHub Code Review Bot in Connectors and allow authorized managers
(`tools:manage_connections`) to create GitHub review bot endpoints.

## What Changed

- `packages/shared`: marked `enableGitHubReviewBots` as a deprecated
compatibility key in types, Zod defaults (`true`), and
`INSTANCE_FEATURE_CATALOG` (`cloudDefault: true`, `selfHostedDefault:
true`); updated `channelMethodEnabled` in `connector-availability.ts` so
`github` is always enabled alongside `agentmail`.
- `server` instance settings and Cloud staging:
`normalizeExperimentalSettings` always returns `enableGitHubReviewBots:
true`; `applyManagedExperimentalOverlay` and `updateExperimental` ignore
retired `enableGitHubReviewBots` entries so Cloud managed configs cannot
turn it off and legacy `false` patches are not rejected; removed
`enableGitHubReviewBots` from `CLOUD_STAGING_EXPERIMENTAL_KEYS`.
- `server` chat channels, discovery, and OpenAPI: allowed `github` in
`assertChatProviderEnabledForCreate`, `assertIdentityProviderEnabled`,
`assertIdentityLinkAccess`, and `connection-intents` discovery without
experimental flags while keeping `enableChatConnectors` enforcement for
experimental chat providers; updated the OpenAPI endpoint description.
- `ui` and Storybook: removed the **GitHub review bots** Experimental
settings toggle card; simplified `useChatConnectorsEnabled` and
`chatProviderVisible` so `github` and `github-code-review-bot` are
always visible; bypassed experimental loading wait for `provider=github`
in `ChatConnectorsExperimentalGate`; made the classic Agent Detail
Channels tab and `AgentChannelsPanel` empty-state copy always reflect
available agent identities; updated `canEnterAppsConnect`, `Browse`,
`ConnectionSetupFlow`, and `github-connections.stories.tsx`.
- Tests, E2E, runner-e2e, docs, and maps: updated unit, integration,
managed-overlay, runner-e2e, and Playwright E2E specs; refreshed
`tests/runner-e2e/source-sdk-public-inputs.json`; updated
`doc/connections/GITHUB.md`, `doc/connections/GITHUB-REVIEW-BOT.md`, and
`maps/feature-map/chat-channels.md`.

## Verification

- `pnpm --filter @paperclipai/shared build && pnpm --filter
@paperclipai/shared typecheck && pnpm --filter @paperclipai/server
typecheck && pnpm --filter @paperclipai/ui typecheck` — passed.
- `node scripts/check-maps.mjs && node scripts/storybook-catalog.mjs` —
passed.
- `pnpm vitest run packages/shared/src/validators/instance.test.ts
packages/shared/src/connector-availability.test.ts
packages/shared/src/feature-catalog.test.ts
server/src/__tests__/instance-settings-service.test.ts
server/src/__tests__/instance-settings-managed-overlay.test.ts
server/src/__tests__/instance-settings-cloud-defaults.test.ts
server/src/routes/chat-channels.identity.test.ts
server/src/__tests__/connection-intents-service.test.ts
server/src/__tests__/chat-channels/slack-ingress-and-threads.integration.test.ts
server/src/__tests__/chat-channels/github-setup-and-access.integration.test.ts`
— all passed.
- `pnpm vitest run ui/src/pages/apps/app-connect-policy.test.ts
ui/src/components/chat/ExternallyConnectedTaskBanner.test.tsx
ui/src/features/connections/ConnectionSetupFlow.slack-oauth.test.tsx` —
3 files, 62 tests passed.
- `pnpm --dir tests/runner-e2e vitest run github-review-journey.test.ts`
— 56 tests passed.
- `pnpm verify --explain` — confirmed
`tests/runner-e2e/source-sdk-public-inputs.json` is current; exited 2
for broad CI coverage (handled by required GitHub CI gates on this PR).

## Risks

- Behavioral shift: instances that had `enableGitHubReviewBots` off now
show GitHub Code Review Bot in Connectors and allow authorized users
with `tools:manage_connections` to configure GitHub review bots.
Existing permission boundaries (`tools:manage_connections`, company
scoping, GitHub App OAuth/installation consent) are unchanged.
- `useIssueChatBinding` now queries `/api/issues/:issueId/chat-binding`
for normal tasks even when `enableChatConnectors` is off so GitHub-bound
task banners remain visible; experimental chat bindings remain filtered
out by `chatProviderVisible` while `enableChatConnectors` is off.
- No database migration is required; stored `enableGitHubReviewBots`
JSON values become inert.

> 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

- Google Gemini (high reasoning) in Antigravity, with tool use (shell,
file edits, 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
- [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
2026-11-25 16:01:38 -06:00
Dotta 1a1d436cc5 docs: add GitHub Review Bots setup and architecture guide (#22995)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The GitHub Code Review Bot connector lets any Paperclip agent review
pull requests through a dedicated GitHub App
> - Operators had no public user guide under
`docs/guides/board-operator/`, and the internal connector doc still
instructed users to toggle an experimental flag
> - Users need accurate GA setup steps, clear separation between
triggers and GitHub Rulesets merge checks, and honest self-hosted
sandbox guidance
> - This pull request adds the public GitHub Review Bots operator guide,
registers it in `docs/docs.json`, and updates
`doc/connections/GITHUB-REVIEW-BOT.md` to match GA availability
> - The benefit is that Cloud and self-hosted operators can connect,
configure, and troubleshoot GitHub Review Bots from verified
documentation

## Linked Issues or Issue Description

**Issue type**
Missing documentation

**Where is the issue?**
`docs/guides/board-operator/github-review-bots.md`, `docs/docs.json`,
and `doc/connections/GITHUB-REVIEW-BOT.md`

**What's wrong?**
The public docs site does not include a board operator guide for GitHub
Review Bots, and `doc/connections/GITHUB-REVIEW-BOT.md` still tells
operators to enable a default-off experimental flag before setup.

**Suggested fix**
Publish the GitHub Review Bots setup and architecture guide under
`docs/guides/board-operator/github-review-bots.md`, register it in
`docs/docs.json`, and update `doc/connections/GITHUB-REVIEW-BOT.md` to
reflect GA setup.

## What Changed

- Added `docs/guides/board-operator/github-review-bots.md` covering
Quickstart, the three independent choices (App installation, Paperclip
triggers, opt-in GitHub Rulesets), structured 0–5 assessments and
commit-bound `Paperclip Review` check runs, linked members and sponsored
external contributors, low-trust presets vs. self-hosted runtime
sandboxing, localhost Cloud connector ingress vs. direct HTTPS, bot
avatar branding, and troubleshooting.
- Registered `guides/board-operator/github-review-bots` in
`docs/docs.json` under the Board Operator group.
- Updated `doc/connections/GITHUB-REVIEW-BOT.md` to remove the outdated
experimental-flag toggle instruction from the setup section.

## Verification

- Validated `docs/docs.json` JSON parsing and verified
`docs/guides/board-operator/github-review-bots.md` exists and is
registered.
- Verified `git diff --check` passes cleanly with no trailing whitespace
or formatting issues.
- Docs-only change; no server, UI, or database code modified.

## Risks

- Low risk. Documentation-only change with no runtime or schema impact.

## Model Used

Gemini 3.1 Pro / Gemini 4 Neon (High)
2026-11-25 15:50:20 -06:00
DottaandClaude Opus 5.5 73369c5d46 feat(connections): AWS connector out of experimental; role ARN comes back from the agent (#22994)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The AWS connector lets agents work in an AWS account through AWS's
hosted MCP server, with a per-connection role and short-lived
credentials (#22083, #22195, #22233, #22626)
> - It has been behind the `enableAwsConnector` experimental setting. It
is now proven on paperclip.staging: a connection was set up end to end,
and the daily QA routine's agent uses it to read private test evidence
from S3
> - On the role step, the person still had to paste the role ARN back,
even when their own agent created the role and reported the ARN in its
live checklist
> - This pull request takes the connector out of experimental and has
the page pick up the role ARN from the agent, keeping the field for
people who set the role up by hand
> - The benefit is AWS available to everyone, with a setup that is
"paste a prompt, press Test connection"

## Linked Issues or Issue Description

Refs #22233 (role setup), #22626 (live agent checklist).

**Subsystem affected**
Connections (AWS app definition, role setup UI), instance experimental
settings.

**Problem or motivation**
- The AWS connector works, but is hidden unless an operator turns on an
experimental flag.
- The setup page always showed a Role ARN field, and the person had to
copy the ARN from the agent's summary into it.

**Proposed solution**
- Remove `experimentalFeatureKey` from the AWS app definition.
`enableAwsConnector` becomes a compatibility key: stored and
Cloud-managed values are ignored, and old clients' writes are accepted
(same pattern as `enableMcpAggregators` and `enablePublicMcp`).
- Move the Role ARN field into "Or do it by hand". When the agent
finishes, take the ARN from its finish summary, accepting only an IAM
role ARN for this connection's own role name
(`paperclip-<connectionId>`), so a summary cannot point the connection
at another role. "Test connection" then works with nothing to paste. The
by-hand section opens on its own when a test fails or the agent finished
without a usable ARN.

**Alternatives considered**
- Letting the agent save the ARN through the checklist API: more surface
on a token-only route. Reading it from the finish summary needs no new
API, and the test still proves the role trusts only this connection.
- Removing the field entirely: people who use CloudFormation or IAM by
hand still need it.

## What Changed

- `packages/shared/src/app-definitions/aws.json`,
`scripts/app-definition-overrides/aws.json`: no
`experimentalFeatureKey`.
- `packages/shared/src/feature-catalog.ts`, `validators/instance.ts`:
`enableAwsConnector` is "(compatibility)", default on.
- `server/src/services/instance-settings.ts`: always on; Cloud-managed
values skipped; old clients' writes accepted.
- `ui/src/pages/InstanceExperimentalSettings.tsx`: the AWS toggle is
removed.
- `ui/src/features/connections/aws-role-arn.ts` (new): the role ARN rule
and `roleArnFromAgentSummary`.
- `ui/src/features/connections/AwsRoleSetup.tsx`: Role ARN under "Or do
it by hand", auto-filled from the agent's summary, with copy updated
("hands back the role when it finishes", "the Role ARN field below").
- `doc/connections/AWS.md`: no longer described as experimental.

## Verification

- Server: `aws-mcp-connector.test.ts` (connects even with a stored
`enableAwsConnector: false`),
`instance-settings-managed-overlay.test.ts` (stays on with stored and
Cloud-managed false; an old client's false write is accepted),
`instance-settings-service.test.ts`: 68 passed. The 4 new flag tests
fail against master's source (red/green).
- Shared: `app-definitions.test.ts` 43 passed;
`scripts/app-definition-overrides.test.mjs` 3 passed.
- UI: `aws-role-arn.test.ts` 3 passed (this connection's ARN from a
summary, including role paths and a trailing period; another role, a
longer name, a short account and no ARN are rejected). UI typecheck
clean.
- Storybook (headless Playwright, current branch): the default view has
no Role ARN field; "agent done" shows "Your agent's role is ready. Test
the connection to finish." with Test connection enabled; "test failed"
opens "Or do it by hand" with the field at its end. No page errors.
- Live: the connector was set up end to end on paperclip.staging (Test
connection passed) and is in daily use by the QA routine. To re-check
after deploy without the flag.

## Risks

- Every instance now shows the AWS connector. It was already proven on
staging; access is per connection and read-only connections are capped
by AWS's `ReadOnlyAccess`.
- The ARN auto-fill trusts only an ARN naming this connection's own
role, and Test connection still verifies AWS accepts it, so a wrong or
foreign ARN cannot be saved silently.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use
(shell, file edits, Storybook with headless Playwright, the live staging
instance).

## 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-25 15:44:59 -06:00
Dotta 8e8c1b9f4d fix(sandbox): scope staged provider-pack assets per provider and default Daytona disk to 20 GiB (#22981)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Native agents run inside remote Daytona sandboxes that require a
verified Runner provider pack
> - When a sandbox stages the provider pack into its workspace,
Paperclip copies, transfers, and verifies every
`provider-assets/<provider>` closure (~1.6 GB across pi, cursor,
copilot, kimi, and antigravity) even when the run only uses Claude,
Codex, OpenCode, or one provider
> - New image-backed Daytona sandbox environments also default to a 10
GiB disk, which leaves too little headroom for repository installs and
tests
> - This pull request stages and verifies only the
`provider-assets/<provider>` tree needed by the active run and raises
the Daytona plugin default disk size from 10 GiB to 20 GiB
> - The benefit is significantly more free workspace disk space, smaller
pack transfers, and safer default disk sizing without changing the
provider-pack archive format or breaking multi-provider workspace reuse

## Linked Issues or Issue Description

- Fixes: #19367
- Refs #19484
- Related: #19500 (ENOSPC fail-fast and full-sandbox recovery already
merged in #22068, #22239, #22383, #22466, and #22837), #22241
(deduplicated repeated bytes in staged packs)

## What Changed

- `server/src/services/native-runtime/provider-pack-compatibility.ts`:
add `requiredProviderAssetNames`, `isProviderAssetPathIncluded`, and
`providerAssetExcludeArgs` helpers that resolve the required
`provider-assets/<provider>` subset for a `PackProvider` (returning
unfiltered behavior when `provider` is omitted).
- `server/src/services/native-runtime/provider-pack-layers.ts`: filter
large layer entries by required provider assets before running the
remote reuse script and transferring missing layers, preserve
cross-provider image-twin reuse so core files can still reuse identical
bytes from excluded provider paths in the base image, and pass
`--exclude` flags to GNU `tar` for `overlay.tar.zst`.
- `server/src/services/native-runtime/provider-pack-archive.ts` and
`provider-pack-upload.ts`: forward `provider` and `manifest` into v1 and
v2 archive staging and exclude unused `provider-assets/*` during
extraction.
-
`server/src/services/native-runtime/remote-provider-pack-verification.ts`:
scope candidate asset tree digest checks to the active provider when
`provider` is passed and include `requiredAssets` in the verification
seal key so a pack verified for one provider cannot satisfy a seal check
for a different provider.
- `server/src/services/native-runtime/native-session-executor.ts` and
`server/src/services/kimi-connection-probe.ts`: pass the active
`PackProvider` to `prepareRemoteProviderPackOnTarget` and
`verifyRemoteProviderPackIdentity`.
- `packages/plugins/sandbox-providers/daytona/src/manifest.ts` and
`package.json`: raise the default `disk` allocation from `10` to `20`
GiB and bump the plugin version from `0.1.10` to `0.1.11` so
bundled-plugin boot reconciliation refreshes persisted manifests.
- Added unit and end-to-end tests in
`packages/plugins/sandbox-providers/daytona/src/plugin.test.ts`,
`server/src/services/native-runtime/provider-pack-archive.test.ts`,
`server/src/services/native-runtime/remote-provider-pack-verification.test.ts`,
and updated `server/src/__tests__/kimi-connection-probe.test.ts`.

## Verification

- **RED (before production edits):**
- `cd packages/plugins/sandbox-providers/daytona && npx vitest run
--config vitest.config.ts -t "bumps the plugin version|pre-fills
sizing|validates and passes the default 20 GiB"` — 3 failed (`0.1.10 !==
0.1.11`, `10 !== 20`).
- `cd server && npx vitest run
src/services/native-runtime/provider-pack-archive.test.ts -t "omits all
provider-assets|stages only the selected provider"` — 2 failed (unused
`provider-assets` staged on disk).
- `cd server && npx vitest run
src/services/native-runtime/remote-provider-pack-verification.test.ts -t
"verifies only the selected provider"` — 1 failed (`candidate_digest`
rejected Claude when `provider-assets/` was absent).
- **GREEN (after fix):**
  - `cd server && npx tsc --noEmit -p tsconfig.json` — passed.
- `cd server && npx vitest run
src/services/native-runtime/provider-pack-archive.test.ts` — **56/56
passed**, including an end-to-end upload+verify test proving unfiltered
staging writes >= 6 MiB of provider assets, Claude staging omits all 6
MiB (< 256 KiB total) and verifies cleanly, and switching the same
workspace to Cursor rejects the Claude seal (`candidate_digest`) and
re-stages only Cursor (2 MiB, excluding Kimi and Pi).
- `cd server && npx vitest run
src/services/native-runtime/remote-provider-pack-verification.test.ts
src/services/native-runtime/remote-provider-pack.test.ts
src/services/native-runtime/retained-provider-pack-source.test.ts
src/__tests__/kimi-connection-probe.test.ts` — all passed
(`remote-provider-pack-verification.test.ts` 34/34,
`remote-provider-pack.test.ts` 60/60, `kimi-connection-probe.test.ts`
39/39, `retained-provider-pack-source.test.ts` all passed).
- `cd packages/plugins/sandbox-providers/daytona && pnpm typecheck &&
npx vitest run --config vitest.config.ts` — typecheck passed; all 15
offline test files passed (641 passed, 8 live tests skipped;
`archive-stream-window.test.ts` timed out once during parallel CPU
contention and passed in 6.17s when re-run).
- `node scripts/check-test-budget.mjs --files
server/src/services/native-runtime/provider-pack-archive.test.ts
server/src/services/native-runtime/remote-provider-pack-verification.test.ts
server/src/__tests__/kimi-connection-probe.test.ts` — passed (110
nightly suites validated, 3 test files checked).
- `pnpm verify --base 2d06567795
--explain` exited 2 because
`packages/plugins/sandbox-providers/daytona/package.json` is a global CI
input; focused suites and package typechecks ran locally and sharded PR
CI supplies broad coverage.
- **Not run locally:** Live Daytona sandbox provisioning (requires
`DAYTONA_API_KEY`). Managed Cloud snapshot disk sizing is updated
separately in the Cloud repository.

## Risks

- Low risk. Archive schema v1 and v2 remain unchanged, so existing
Docker images and retained OCI release packs work without rebuilding.
- If a reusable workspace previously staged a pack for one provider (for
example Claude) and a later run on the same workspace uses a provider
with native assets (for example Cursor), the provider-scoped
verification seal misses, `verifyStaged` fails with `candidate_digest`,
and `prepareRemoteProviderPackOnTarget` cleanly re-stages with the
needed provider assets.
- Raising the Daytona plugin default `disk` to 20 GiB only affects new
image-backed environments created with the form default; existing saved
environments and snapshot-backed environments keep their existing
configuration.

> 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

- Google Gemini (Antigravity agent) with shell, file editing, and local
test 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
- [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
2026-11-25 15:33:44 -06:00
87fadcb108 feat(annotations): one-tap reactions on artifact comments (#22989)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - People review agent artifacts (plans, documents, routine
descriptions, and case documents) with inline annotation comments
> - Today a person must type a full reply to say "done", "checked",
"looks good", or "I have a question"
> - This slows down quick review feedback, and a question inside a reply
does not automatically bring the assignee back
> - This pull request adds four one-tap reactions to each annotation
comment: Done, Check, Thumbs up, and Question
> - A person's first Question reaction on an open task saves a durable
wake receipt and wakes the task's assignee in a dedicated follow-up run
to reply in that comment's thread (respecting chat ownership and wake
rate limits)
> - The benefit is fast review feedback without extra typing, while
agents can read and set the same reactions through the API

## Linked Issues or Issue Description

Refs #21637 (supersedes on current `master` with renumbered Drizzle
migration, OpenAPI/experimental route contracts, durable wake receipts,
chat ownership and rate-limit hardening, and current UI test suite)
Refs #9336 (agent wake notifications for document annotation threads)
Refs #9674 (agents cannot read inline document review comments)

**What problem does this solve?**
A reviewer cannot quickly acknowledge or question an annotation comment
on an artifact. A short answer requires a typed reply, and nothing tells
the agent that a person has a question about a comment.

**Proposed solution**
Add four fixed reactions per annotation comment: `done`, `check`,
`thumbs_up`, and `question`. One tap adds a reaction and a second tap
removes it. Each person or agent can add each reaction once per comment.
A person's first `question` reaction on an open task commits a durable
wake receipt in the same transaction and wakes the assignee once in a
dedicated follow-up turn, with the comment included in the wake context.

**Alternatives considered**
Free-form emoji reactions. Fixed named reactions keep the API contract
stable for agents and avoid storing arbitrary emoji strings on the
server.

## What Changed

- `packages/db`: Added `document_annotation_comment_reactions` table
(`company_id`, `comment_id`, `reaction`, `actor_type`, `actor_id`,
`created_at`, `removed_at`) with check constraints, cascade delete on
comment deletion, and unique `(comment_id, reaction, actor_type,
actor_id)` index. Generated online-compatible migration
`0510_clear_speedball.sql`, refreshed Drizzle snapshot
`0510_snapshot.json`, and pruned `0505_snapshot.json`.
- `packages/shared`: Added `DOCUMENT_ANNOTATION_COMMENT_REACTIONS`,
`DocumentAnnotationCommentReactionName`,
`DocumentAnnotationCommentReactionActor`,
`DocumentAnnotationCommentReactionSummary`, optional `reactions` on
`DocumentAnnotationComment`, and
`documentAnnotationCommentReactionSchema`.
- `server`: Added `setCommentReaction` in `document-annotations.ts`
using soft-delete (`removed_at`) and upsert revival (`(xmax = 0)` for
`firstAdd`), and attached reaction summaries (`count`, `actors`,
`reactedByMe`) to thread/comment reads.
- `server` routes & contracts: Added `PUT` and `DELETE
.../annotations/:threadId/comments/:commentId/reactions/:reaction` for
issues, routines, and cases, registered them in `openapi.ts`,
`experimental-api-metadata.ts`, and `experimental-api-paths.ts`, and
logged activity (`*.document_annotation_comment_reaction_added` /
`_removed`) only when a row changes.
- `server` durable wake, chat ownership, rate limits &
`packages/adapter-utils`:
- A person's first `question` reaction on an open assigned issue inserts
a recoverable `deferred_issue_execution` receipt in
`agent_wakeup_requests` in the same DB transaction
(`annotation-question-reaction:<id>`), passes `executionWaitRequestId`
to `heartbeat.wakeup` (`reason: "issue_commented"`, `allowRunCoalescing:
false`), resumes via `resumeDeferredExecutionReceipts` if immediate wake
fails, and defers behind busy turns without duplicating receipts.
- Recognized human annotation question reactions
(`isHumanAnnotationQuestionWake`) as an independent wake cause for idle
waiting agent chats while strictly enforcing chat ownership
(`!conversationAgentId || conversationUserId === actorId`) across
service, route, wake preflight, locked admission, and recovery queries.
- Bounded distinct-comment question wakes under `issues ... FOR UPDATE`
to at most 1 pending/in-flight wake per `(companyId, issueId, agentId)`
and at most 3 original question receipts (`idempotency_key LIKE
'annotation-question-reaction:%'`) per `(companyId, issueId, user)` in a
rolling 10-minute window.
- `renderPaperclipWakePrompt` instructs the agent to answer the question
in the annotation thread.
- `ui`: Added four one-tap reaction buttons (`✅`, `✔️`, `👍`, `❓`) under
each non-optimistic annotation comment in `DocumentAnnotationPanel` /
`DocumentAnnotationPopover`, with counts, `aria-pressed`, hover tooltips
naming actors, optimistic updates, client-scoped write serialization
across panel/popover remounts (`WeakMap<QueryClient, Map<string,
TargetReactionState>>`), live-update refetch overlay preservation,
deferred invalidation while writes are pending, and updated Storybook
fixture.
- `docs/api` & `tests/runner-e2e`: Documented the reaction endpoints and
wake bounds in `docs/api/issues.md` and `docs/api/routines.md`, and
refreshed `tests/runner-e2e/source-sdk-public-inputs.json`.

## Verification

- `pnpm --filter @paperclipai/db run check:migrations` and
`migration-compatibility.ts`: `0510_clear_speedball.sql` classified
`online_compatible`.
- `pnpm --filter @paperclipai/db exec vitest run
src/migration-snapshot-drift.test.ts
src/migration-compatibility.test.ts`: passed (117/117).
- `pnpm --filter @paperclipai/adapter-utils exec vitest run
src/server-utils.test.ts -t "question reaction"`: passed.
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/document-annotations-service.test.ts` (20/20, embedded
Postgres — covering durable wake recovery, idle waiting-chat wake,
busy-turn deferral, non-owner chat wake denial, and rolling-window +
pending-backlog wake bounds across full queue admission),
`src/__tests__/document-annotation-routes.test.ts` (20/20),
`src/__tests__/routine-document-annotation-routes.test.ts`,
`src/modules/wake-queue/application/issue-wake-admission.test.ts`
(15/15), and `src/modules/wake-queue/domain/policy.test.ts`: all passed.
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/openapi-routes.test.ts`: passed (59/59).
- `pnpm --filter @paperclipai/ui exec vitest run
src/hooks/useDocumentAnnotationMutations.test.tsx`: passed (9/9,
covering optimistic updates, serialized writes across remounts,
live-update refetch preservation, deferred invalidation across comments,
and rendered `ThreadCard` DOM buttons/toggles).
- Package typechecks (`@paperclipai/shared`, `@paperclipai/db`,
`@paperclipai/adapter-utils`, `@paperclipai/server` all 7 layers,
`@paperclipai/ui` + Storybook catalog): all passed.
- `pnpm check:token-gates`, `node scripts/check-module-boundaries.mjs`,
and `node scripts/check-test-budget.mjs`: all passed.
- `node tests/runner-e2e/source-sdk-public-inputs.mjs $(git rev-parse
HEAD) --check`: in sync (`inputs: 579, changed: false`).
- Full-stack Playwright verification against a throwaway local server +
embedded PostgreSQL: created a task, `plan` document, and annotation
thread; verified invalid reaction returns `400`; clicked `thumbs_up` and
`question` in the real document viewer; reloaded to prove PostgreSQL
persistence; toggled `thumbs_up` off and reloaded to verify removal
persisted.
- PR CI on `4d892c8067`: 83/83 executed checks passing (including `ci /
verify`, `ci / e2e` + all 16 E2E shards, all General/Serialized server
shards, `Build`, `Typecheck + Release Registry`, `Verify Paperclip
Runner`, `Superagent Security Scan`, and `Greptile Review` 5/5 with 0
unresolved threads).

## Risks

- Low risk. Migration `0510_clear_speedball.sql` only creates a new
table and its indexes (`online_compatible`), so running releases are
unaffected.
- `reactions` is optional on `DocumentAnnotationComment`, preserving
backward compatibility for existing clients.
- Question wakes are bounded by soft-delete revival (`firstAdd`), chat
ownership enforcement, single pending/in-flight wake per `(companyId,
issueId, agentId)`, and at most 3 original question wakes per
`(companyId, issueId, user)` per 10-minute window.

> 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

- Google Gemini (`gemini-3-pro` / Antigravity agentic coding environment
with shell execution, file editing, embedded PostgreSQL, and Playwright
verification), rebasing and extending prior work originally authored
with Claude Opus 5.5 in #21637.

## 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: lucktastic <13757243+lucktastic@users.noreply.github.com>
Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-25 15:33:38 -06:00
DottaandPaperclip 0f52d90993 fix(github): detect writes outside GitHub App installations and stop advising Refresh access (#22978)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Agents use managed GitHub App connections through the tool gateway
to open issues, post comments, and perform approved writes on GitHub
repositories.
> - A GitHub App user-to-server token can write only to repositories
inside accounts where the Paperclip GitHub App is installed; even on a
public third-party repository, GitHub rejects writes with `403 Resource
not accessible by integration`.
> - Previously, Paperclip did not check the App's installed accounts
before posting an approval card, mapped every `403 Resource not
accessible by integration` to `github_access_denied`, and told both the
user ("Manage GitHub access") and the agent ("select Refresh access") to
repair access through a flow that cannot reach third-party
organizations.
> - This wastes human approvals on doomed writes and sends operators
into a dead-end permission refresh loop.
> - This pull request adds a pre-check before posting approval cards for
managed GitHub App writes outside installed accounts, distinguishes
`github_repo_outside_app_installations` and
`github_app_installation_suspended` from `github_access_denied` across
server classification, MCP routes, and continuation delivery, and
renders accurate UI guidance without a misleading "Manage GitHub access"
link for external repositories.
> - The benefit is that unreachable external-org writes fail immediately
with actionable alternatives (post directly on GitHub, use a PAT
connection, or have an org admin install the App and refresh access),
suspended installations get explicit unsuspend guidance, and missing
repository grants on installed organizations keep the existing "Manage
GitHub access" and "Refresh access" repair flow.

## Linked Issues or Issue Description

No public issue exists. Refs #19315, #19655, #20141.

**What happened?**
When an agent requested an approval-gated GitHub write targeting a
public repository owned by an external organization where the Paperclip
GitHub App was not installed, Paperclip posted a normal approval card.
After the user approved it, GitHub returned `403 Resource not accessible
by integration`, and both the failed approval card and agent
continuation instructions advised clicking "Manage GitHub access" and
"Refresh access", which cannot grant write access to a third-party
organization.

**Expected behavior**
Paperclip should check managed GitHub App write targets against the
grant's installed accounts before posting an approval card, fail
unreachable external-organization writes cleanly without wasting an
approval, preserve suspended installations separately with unsuspend
guidance, keep incomplete webhook-invalidated snapshots on
`github_access_denied` until refreshed, and present accurate
alternatives in both the UI card and agent continuation instructions.

**Steps to reproduce**
1. Connect GitHub via the managed GitHub App installed on one
organization (for example `acme`), with an approval policy on GitHub
writes.
2. Ask an agent to run `create_issue` or `add_issue_comment` targeting a
repository in an external organization where the App is not installed
(for example `external-org/public-repo`).
3. Previously, Paperclip posted an approval card, executed it upon
approval, received `403 Resource not accessible by integration`, and
showed "GitHub access needed" / "Manage GitHub access" plus "Refresh
access" instructions.

**Paperclip version or commit**
`2d065677959b` (`master`, merged cleanly with `331e1a9fd3`)

**Deployment mode**
Local / Paperclip Cloud managed GitHub App connection

## What Changed

- `server/src/services/tool-access/github-access-discovery.ts`,
`packages/db/src/schema/tool_access.ts`,
`packages/shared/src/types/tool-access.ts`,
`packages/shared/src/validators/tool-access.ts`: Preserved suspended
installation owner logins separately in optional
`suspendedInstallationOwnerLogins` so active `installationOwnerLogins`
stays unchanged while suspended orgs are distinguishable from
uninstalled orgs. Added `github_repo_outside_app_installations` to
`ToolAccessReasonCode` and updated
`tests/runner-e2e/source-sdk-public-inputs.json`.
- `server/src/services/tool-access/github-access-errors.ts`: Added
`github_repo_outside_app_installations`,
`github_app_installation_suspended`, `isGitHubAccessErrorCode`,
`extractGitHubTarget` (`owner`+`repo`, `repository: "owner/repo"`,
`organization`/`org`, `fork_repository` destination-only handling, and
GitHub API URL fallback), `suspendedManagedGitHubOwner`,
`findUnreachableManagedGitHubTarget`,
`githubOutsideAppInstallationsInstructions`,
`githubSuspendedInstallationInstructions`, and
`githubAccessErrorInstructions`. Webhook-invalidated/incomplete
snapshots (`bindingSync` set or `installationIds` ahead of
`installationOwnerLogins` with `repositories` cleared) skip pre-check
blocking and stay on `github_access_denied` on runtime `403` until
access is refreshed.
- `server/src/services/tool-access-policy.ts` and
`server/src/services/tool-gateway.ts`: Reused the already-resolved
remote tool context from `resolveGovernedToolCall` (avoiding redundant
connection/grant lookups for non-GitHub providers), routed unreachable
approval-requiring managed GitHub writes through the canonical policy
denial path with `{ claimIdempotencyKey: false }` (inserting
`idempotencyKey: null` atomically in the single `INSERT` so retries
after installing the App are never falsely replayed), and propagated
`github_repo_outside_app_installations` /
`github_app_installation_suspended` (HTTP 403) without echoing raw
provider text into trusted instructions.
- `server/src/routes/tool-gateway.ts`,
`server/src/services/tool-action-delivery.ts`,
`server/src/services/continuation-cause.ts`,
`server/src/services/agent-task-run-telemetry.ts`: Treated all GitHub
access error codes as MCP `tools/call` `isError: true` results, routed
continuation wakes through `githubAccessErrorInstructions`, and
registered `github_repo_outside_app_installations` and
`github_app_installation_suspended` as person-owned `missing_access`
failure codes.
- `ui/src/components/IssueThreadInteractionCard.tsx` and
`ui/storybook/stories/questions-and-approvals/connection-reviews.stories.tsx`:
Added dedicated alert states for `github_repo_outside_app_installations`
("Repository outside GitHub App access", omitting dead-end "Manage
GitHub access") and `github_app_installation_suspended` ("GitHub App
installation suspended", with unsuspend guidance and "Manage GitHub
access"), using existing design tokens only, while keeping "GitHub
access needed" for `github_access_denied`.
- `doc/connections/GITHUB.md`: Documented pre-check, suspended
installation, incomplete webhook snapshot, and error classification
behavior.
- Added unit, UI component, and embedded-Postgres integration tests in
`server/src/services/tool-access/github-access-errors.test.ts`,
`server/src/__tests__/github-grant-metadata.test.ts`,
`server/src/__tests__/tool-gateway.test.ts`,
`server/src/__tests__/tool-gateway-action-approvals.test.ts`, and
`ui/src/components/IssueThreadInteractionCard.test.tsx`.

## Verification

- `pnpm vitest run
server/src/services/tool-access/github-access-errors.test.ts
server/src/services/tool-access/github-default-owner.test.ts
server/src/__tests__/github-grant-metadata.test.ts
ui/src/components/IssueThreadInteractionCard.test.tsx`: 4 files, 140/140
passed.
- `pnpm vitest run server/src/__tests__/tool-gateway.test.ts -t
"GitHub"`: 13/13 passed (covers pre-check blocking with atomic
`idempotencyKey: null`, installed-org missing-repo
`github_access_denied`, direct + MCP HTTP route `isError: true`,
approved-card runtime 403 URL classification, post-install retry,
suspended installation `github_app_installation_suspended`, and
webhook-invalidated `bindingSync` snapshot pass-through).
- `pnpm vitest run
server/src/__tests__/tool-gateway-action-approvals.test.ts -t "tells the
agent how to recover from"`: 9/9 passed (including
`github_repo_outside_app_installations` and
`github_app_installation_suspended` continuation wakes).
- `pnpm --filter @paperclipai/shared typecheck && pnpm --filter
@paperclipai/db typecheck && pnpm --filter @paperclipai/server typecheck
&& pnpm --filter @paperclipai/ui typecheck`: passed (0 errors across all
7 server layers, shared, db migration safety/compatibility, and UI +
Storybook catalog).
- `pnpm check:token-gates`: all 4 gates clean.
- `node tests/runner-e2e/source-sdk-public-inputs.mjs
6714ad6b68 --check`: passed (`changed:
false`, 578 inputs).
- `node scripts/check-test-budget.mjs --files
server/src/services/tool-access/github-access-errors.test.ts
server/src/__tests__/github-grant-metadata.test.ts
server/src/__tests__/tool-gateway.test.ts
server/src/__tests__/tool-gateway-action-approvals.test.ts
ui/src/components/IssueThreadInteractionCard.test.tsx`: PASS (`113
nightly suites validated, 5 test file(s) checked`).
- PR CI on `6714ad6b68`: 81/81 executed checks passed (`0 failing, 0
pending, 0 cancelled, 6 skipped`), including `ci / verify`, `ci / e2e` +
all 16 E2E shards, all General tests, all 9 Serialized server shards,
all Verify Paperclip Runner lanes, `Build`, `Typecheck + Release
Registry`, `Superagent Security Scan`, `Socket Security`, `Contributor
trust`, `commitperclip`, `Snyk`, and `Greptile Review` (5/5, 0
unresolved threads).
- Not tested against a live GitHub App installation.

## Risks

- Low risk. No SQL database migration is required
(`suspendedInstallationOwnerLogins` is an optional property inside the
existing `connection_grants.provider_tenant` JSONB column, and
`errorCode` is already an open string field).
- Pre-check blocking only activates for approval-requiring non-read
writes on managed GitHub connections that have a complete, populated
grant snapshot (`login` and non-empty `installationOwnerLogins`, without
`bindingSync` invalidation). PAT connections, legacy/empty/incomplete
snapshots, installed organizations, suspended installations, the user's
own personal account, read tools, and upstream `fork_repository` source
repos retain their existing behavior.
- Pre-check denials insert `idempotencyKey: null` atomically so retrying
the same write after an org admin installs the App and access is
refreshed never hits a stale denial replay.

## Model Used

- Google Gemini (Antigravity agent) with tool use and local code/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
- [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-25 15:33:31 -06:00
Dotta 38e3a71669 fix(connections): use Slack MCP user OAuth flow and surface OAuth errors in setup UI (#22976)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Apps and Connections let operators connect external providers
through remote MCP servers and OAuth.
> - Slack's curated `mcp-oauth` method pins Slack's bot install
endpoints (`oauth/v2/authorize` and `oauth.v2.access`) while sending
user-only scopes (`search:read.public`, `search:read.private`, etc.) in
`scope`, so Slack rejects sign-in with `"Invalid permissions
requested"`.
> - In addition, when OAuth fails or returns an error for a
customer-owned OAuth app like Slack, `ConnectionSetupFlow`'s `KeyStep`
drops `oauthError` completely, hiding the failure banner, and
`OAuthClientFields` hides the method's `guidanceMd` prerequisites.
> - This pull request switches Slack's `mcp-oauth` method to Slack's
documented MCP user OAuth endpoints (`oauth/v2_user/authorize` and
`oauth.v2.user.access`), propagates allowlisted RFC OAuth
`providerError` codes without reflecting untrusted provider prose,
displays OAuth errors and popup fallback links on `KeyStep`, and renders
setup prerequisites (`guidanceMd`) beside customer OAuth fields.
> - The benefit is that customer-owned Slack MCP sign-in succeeds
(including when resuming pre-fix drafts) and any OAuth error or Slack
MCP prerequisite is clearly shown to the user.

## Linked Issues or Issue Description

Fixes: #13935
Refs #17258
Refs #14037

Builds on #17258 (`fix/slack-mcp-user-oauth-flow`) and adds the missing
customer-OAuth error surface and setup guidance in
`ConnectionSetupFlow`.

## What Changed

- Updated `packages/shared/src/app-definitions/slack.json` and
`scripts/ingest-app-definitions.mjs` so Slack's `mcp-oauth` method uses
`https://slack.com/oauth/v2_user/authorize` and
`https://slack.com/api/oauth.v2.user.access`, and added Slack MCP
prerequisites (`User Token Scopes`, callback URL, and `Model Context
Protocol`) to `guidanceMd`.
- Updated `server/src/routes/tool-access.ts` to propagate allowlisted
RFC `providerError` codes (`normalizeOAuthProviderError`, excluding
`unrecognized`) via `provider_error` on OAuth recovery redirects and
connection-intent postMessages, while continuing to never read or
reflect untrusted `error_description` or `error_uri`.
- Updated `ui/src/features/connections/ConnectionSetupFlow.tsx` and
`ui/src/lib/oauthWindowOutcome.ts` so:
- `KeyStep` renders `oauthError` (not only `connectMutation.error`) and
the `"Open sign-in in a new tab"` fallback link when popups are blocked.
- `oauthCallbackErrorMessage` and `oauthFailureMessage` map allowlisted
`providerError` values (such as `invalid_scope`, `invalid_redirect_uri`,
`invalid_client`) and Paperclip failure codes (including
`slack_mcp_access_disabled`) to actionable Paperclip-authored copy.
- Opener popup polling reads same-origin failure `code` and
`provider_error` details from the returned callback URL.
- `OAuthClientFields` renders `method.guidanceMd` for required
customer-owned OAuth apps whose client secret is optional.
- Updated `tests/runner-e2e/source-sdk-public-inputs.json` for the
changed `@paperclipai/shared` sources.
- Updated Slack OAuth test fixtures in
`server/src/__tests__/tool-access-service.test.ts` and
`server/src/services/tool-access/oauth/client-settings.test.ts`, and
added regressions in `packages/shared/src/app-definitions.test.ts`,
`server/src/__tests__/tool-access-service.test.ts`,
`ui/src/features/connections/ConnectionSetupFlow.oauth.test.ts`, and
`ui/src/features/connections/ConnectionSetupFlow.slack-oauth.test.tsx`.

## Verification

- Shared, UI, and OAuth client-settings unit + DOM tests (95/95 passed):
- `pnpm exec vitest run packages/shared/src/app-definitions.test.ts
ui/src/features/connections/ConnectionSetupFlow.oauth.test.ts
ui/src/features/connections/ConnectionSetupFlow.slack-oauth.test.tsx
ui/src/features/connections/ConnectionSetupFlow.architecture.test.ts
server/src/services/tool-access/oauth/client-settings.test.ts`
- Embedded-Postgres server OAuth start + legacy-draft upgrade + callback
error redirect + redaction tests:
- `pnpm exec vitest run server/src/__tests__/tool-access-service.test.ts
-t "uses Slack user OAuth endpoints even for legacy drafts|starts OAuth
from|refreshes|personal|slack"` (33 passed)
- `pnpm exec vitest run
server/src/__tests__/generic-mcp-connection.test.ts -t "returns browser
denials|denied and cancelled callbacks|redacts"` (9 passed)
- Typechecks & guardrails:
- `pnpm --filter @paperclipai/shared typecheck && pnpm --filter
@paperclipai/server typecheck && pnpm --filter @paperclipai/ui
typecheck` (all passed)
- `node scripts/check-test-budget.mjs --files
packages/shared/src/app-definitions.test.ts
server/src/__tests__/tool-access-service.test.ts
server/src/services/tool-access/oauth/client-settings.test.ts
ui/src/features/connections/ConnectionSetupFlow.oauth.test.ts
ui/src/features/connections/ConnectionSetupFlow.slack-oauth.test.tsx`
(PASS)
- `pnpm verify --base 2d06567795
--explain` (exit 2 due to `scripts/ingest-app-definitions.mjs` being a
global CI input; `tests/runner-e2e/source-sdk-public-inputs.json`
verified in sync; sharded PR CI supplies broad repo coverage).

## Risks

- Low risk. The endpoint change applies only to Slack's `mcp-oauth` tool
method; Slack chat-channel setup and Slack search OAuth retain their
existing bot/user flows.
- Resuming a pre-fix Slack MCP draft automatically re-resolves the
updated `v2_user` endpoints from the catalog definition during
`startOAuth` and overwrites the stored bot URLs.
- Only allowlisted RFC OAuth error codes (`normalizeOAuthProviderError`)
are forwarded in `provider_error`; untrusted provider
`error_description` and `error_uri` values are never read or echoed.

## Model Used

- Claude Opus 4.6 by Anthropic (in Antigravity with tool use, shell
execution, and file editing). Used for root-cause analysis, test-driven
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
2026-11-25 15:33:26 -06:00
f9ee58c214 feat(ui): filter the Tasks list by when tasks were updated (#22965)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The Tasks page lists tasks and provides a Filters panel for status,
assignee, project, and other fields
> - The panel has no time filter, so users cannot limit the list to
tasks updated in a recent time window or date range
> - Users need a quick way to find recent work (such as the last 3 days)
or inspect a custom date range across both desktop and mobile views
> - This pull request supersedes #21822 on current `master` and adds an
"Updated" section to all Tasks filter panels (Any time, Last 24 hours,
Last 3 days, Last 7 days, Last 30 days, and Custom range), keeps the
filter in the URL, aligns "Last updated" display and sort with the
filter timestamp, and adds an optional `updatedBefore` server list bound
> - The benefit is that users can filter tasks by update time window and
share filtered links cleanly across all Tasks views

## Linked Issues or Issue Description

Refs #21822 (rebased onto current `master` with merge conflicts and
post-pruning test updates resolved).

**What existing behavior does this improve?**
The Tasks list filters (`CoordinatorTasks`, Classic `IssuesList`, and
`LegacyIssuesList`) and the company issue list API (`GET
/api/companies/:companyId/issues`). The Filters panel had status,
responsible, project, creator, and label filters, but no time filter.

**Subsystem affected**
UI (Tasks list filters, sorting, and URL sync) and Server (`GET
/api/companies/:companyId/issues`).

**Current behavior**
Users cannot limit the Tasks list to tasks updated within a recent time
window or custom date range. They must scan rows manually to find recent
activity.

**Proposed behavior**
Add an "Updated" section to the Tasks filter panels with options: Any
time (default), Last 24 hours, Last 3 days, Last 7 days, Last 30 days,
and Custom range (start and end local calendar day). Filter on the same
timestamp shown on each row (`lastActivityAt ?? lastExternalCommentAt ??
updatedAt`), count it as 1 active filter, reset it on Clear, persist it
in the page URL (`updated`, `updatedFrom`, `updatedTo`), and send an
optional `updatedBefore` upper bound to the server for custom ranges.

**Reason and benefit**
Users can narrow large task lists to recent work or a specific date
window in one click, including on phones, and share filtered URLs that
open with the same filter applied.

**Breaking changes**
None. The filter defaults to Any time, and `updatedBefore` is an
optional query parameter.

## What Changed

- `server/src/routes/issues.ts`, `server/src/services/issues.ts`,
`docs/api/issues.md`: add the optional `updatedBefore` query parameter
(`issues.updatedAt < updatedBefore`) with `400` validation matching
`updatedSince`, apply both `updatedSince` and `updatedBefore` in
`blockedInboxIssueConditions` so `attention=blocked` enforces the same
bounds, and document both parameters.
- `ui/src/api/issues.ts`: add optional `updatedBefore` to
`IssueListFilters` and `issueListSearchParams`.
- `ui/src/lib/issue-filters.ts`,
`ui/src/hooks/useIssueUpdatedFilterNow.ts`: add `updatedWithin`,
`updatedFrom`, and `updatedTo` to `IssueFilterState`, plus
`issueUpdatedWithinOptions`, `issueUpdatedWithinPatch`,
`issueUpdatedTime`, `issueUpdatedTimeRange`,
`nextIssueUpdatedFilterExpiryMs`, `issueUpdatedServerBefore`,
`readIssueUpdatedParams`, and `writeIssueUpdatedParams`. Reject
impossible calendar dates (such as `2026-02-31`), swap reversed custom
ranges, count Updated as 1 active filter, filter in `applyIssueFilters`
on the row time, and schedule a single deadline timer when a relative
window (`24h`/`3d`/`7d`/`30d`) is active so tasks age out automatically
across task and inbox lists.
- `ui/src/components/IssueUpdatedRangeInputs.tsx`,
`ui/src/components/IssueFilterPanel.tsx`,
`ui/src/components/IssueFiltersPopover.tsx`: add the "Updated" section
and native date inputs (`text-base md:text-xs` to prevent mobile Safari
focus zoom) across refreshed, streamlined, and legacy filter panels.
- `ui/src/components/IssueColumns.tsx`,
`ui/src/components/TaskList.tsx`, `ui/src/lib/issue-sort.ts`,
`DESIGN.md`: align `TaskList` "Last updated" display and sort with
`issueUpdatedTime`, compute each task's sort key once before sorting
(`O(N)` context reads), and update `DESIGN.md` to document the shared
timestamp rule.
- `ui/src/components/IssuesList.tsx`,
`ui/src/components/LegacyIssuesList.tsx`, `ui/src/pages/Issues.tsx`,
`ui/src/pages/CoordinatorTasks.tsx`: sync `updated`, `updatedFrom`, and
`updatedTo` with the page URL, queue multiple URL filter writes in the
same event so Clear resets filters together, pass `updatedBefore` for
custom ranges while preserving `archiveQueryScope` as the final
`issuesQuery.queryKey` segment for `placeholderData`, and forward
`updatedBefore` to `CoordinatorTasks` and `Issues` `searchFilters`.
- `server/src/__tests__/issue-list-updatedsince-filter-routes.test.ts`,
`ui/src/lib/issue-filters.test.ts`, `ui/src/lib/issue-sort.test.ts`,
`ui/src/lib/inbox.test.ts`,
`ui/src/components/IssueFiltersPopover.updated.test.tsx`: add
embedded-Postgres route tests for `updatedBefore` (strict bound,
combined range, `400` validation), unit tests for time windows/custom
ranges/local time zone/invalid dates/URL params/sort key caching, and
component tests across `legacy`, `streamlined`, and `refreshed` panels.

## Verification

- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/issue-list-updatedsince-filter-routes.test.ts`: **1 file,
6/6 tests pass** (embedded Postgres, including `attention=blocked` with
`updatedBefore` and `updatedSince`).
- `pnpm --filter @paperclipai/server typecheck`: **pass** (0 errors
across all server layers).
- `pnpm --filter @paperclipai/ui exec vitest run
src/lib/issue-filters.test.ts src/lib/issue-sort.test.ts
src/lib/inbox.test.ts
src/components/IssueFiltersPopover.updated.test.tsx
src/pages/Issues.test.tsx`: **5 files, 94/94 tests pass** (including
fake-timer relative window expiration and a 500-task bounded
timestamp-read render-cost test).
- `pnpm --filter @paperclipai/ui typecheck`: **pass** (0 errors,
Storybook catalog clean).
- `node scripts/check-token-gates.mjs`: **pass** (all 4 token gates
clean).
- `node scripts/check-test-budget.mjs --files
server/src/__tests__/issue-list-updatedsince-filter-routes.test.ts
ui/src/lib/issue-filters.test.ts ui/src/lib/issue-sort.test.ts
ui/src/lib/inbox.test.ts
ui/src/components/IssueFiltersPopover.updated.test.tsx`: **pass** (110
nightly suites validated, 5 test files checked).
- `pnpm verify --base 2d06567795
--explain`: exited `2` because `DESIGN.md` is a global CI input; focused
server and UI verification ran locally and full PR CI supplies repo-wide
coverage.

## Risks

- Low risk. The Updated filter is off by default (`Any time`), and
`updatedBefore` is optional.
- `IssueFiltersPopover` is shared by Inbox and agent work panels; those
views use `applyIssueFilters`, so the Updated section works consistently
there as well.
- The refreshed `TaskList` "Last updated" column now displays and sorts
by latest activity (`lastActivityAt ?? lastExternalCommentAt ??
updatedAt`), matching the Classic row and the Updated filter.
- Relative windows filter loaded pages in the browser (like other Tasks
filters); because the server sorts by update time descending, recent
tasks load first.

> 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

- Google Gemini (`gemini-3-pro` / Antigravity agentic coding environment
with tool use, shell execution, and embedded Postgres testing), building
on original work from #21822 authored with Anthropic Claude Opus 5.5
(`claude-opus-5-5`).

## 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: lucktastic <13757243+lucktastic@users.noreply.github.com>
Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-25 15:33:20 -06:00
fa6086facb fix(chat): let agents message each other in a person's chats (#22961)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Agent Chat gives each person one standing chat with each agent.
> - Agents work for the same person, so one agent often must tell
another agent something in that person's chats.
> - The shared comment boundary refused every agent message in a chat
unless the chat's own agent wrote it, and `resume`/`reopen` flags turned
chat posts into 409 conflicts.
> - So one agent could not pass a person's decision to another agent in
that person's chat. The person had to relay it by hand.
> - This pull request rebases #21232 onto current `master` and lets an
agent post in another agent's chat while it acts for the chat's person,
preserving source-task privacy, credential binding, and company
boundaries.
> - The benefit is that agents can talk with each other in the person's
chats, the chat's agent wakes and answers there, and the person sees the
exchange where it happens.

## Linked Issues or Issue Description

**Subsystem affected**

Server (comment-write boundary, comment route, chat directive,
fresh-session handoff), UI (chat transcript adapter), and documentation.

**Problem or motivation**

A person asked one agent to pass a decision to another agent. The first
agent posted the decision in the person's chat with the second agent.
Paperclip refused the post with `"Only this conversation's agent can
post agent messages"`, or returned HTTP 409 when `resume` or `reopen`
was set. The person then had to carry the message by hand.

**Proposed solution**

Rebase and supersede #21232 (whose fork branch is conflicting with
`master` and could not be pushed directly due to fork repository
permissions). Let another agent post in a chat through the ordinary
comment route when it posts from its own running, unrevoked, task-bound
run in the same company, while both the run's responsible person and the
authenticated credential's responsible person match the chat's person,
and the source task passes the company-visible privacy check. Keep every
other guard. Wake the chat's agent through the normal comment wake. Tell
the chat's agent that another agent's message is colleague input, not
the person's authority.

**Alternatives considered**

A destination parameter on `send_chat_message` would add a second
delivery path and new routing authority. The ordinary comment route
already carries attribution, comment permissions, per-run cross-task
limits, and the comment wake, so this change reuses it.

**Roadmap alignment**

This extends the shipped Agent Chat capability in `ROADMAP.md`.
Supersedes #21232 (rebased cleanly onto current `master` with expanded
isolation and handoff tests). Refs #18374, which added the comment
boundary for proactive chat messages. Refs #14143, which asks for
broader group discussions between agents and people; this change does
not add group chats.

## What Changed

- `server/src/services/issues.ts` (+20 net lines; edits remain in the
existing >1,000-line owning `addComment` write boundary rather than
splitting a shared transaction guard): allow a peer agent to post in
another agent's chat only from its own running, unrevoked, task-bound
run in the same company, when both `run.responsibleUserId` and
`actor.onBehalfOfUserId` (when set) match `current.conversationUserId`,
and when the source task passes `canActorReadIssuePrivacy(dbOrTx, {
type: "none" }, source)`. Keep proactive chat delivery and the session
fence restricted to the chat's own agent.
- `server/src/routes/issues.ts` (+0 net lines; edits remain in the
existing >1,000-line owning comment route): ignore `reopen` and `resume`
flags on conversations (`!isConversation(issue)`) because ordinary
comment wakes always reach the chat's agent.
- `server/src/services/agent-conversations.ts`: update
`AGENT_CHAT_DIRECTIVE` to state that another agent's comment is
colleague input (never the person's approval, decision, or instruction
authority) and document how to find and write to another agent's chat
for the same person.
- `server/src/services/native-runtime/native-session-handoff.ts`: label
comments authored by another agent as `other_agent` in fresh-session
history so a fresh session distinguishes them from the chat agent's own
`agent` replies.
- `ui/src/components/task-chat/transcript-adapter.ts` (+5 net lines;
edits remain in the existing >1,000-line owning transcript adapter): add
`sameTurnAgent` so `coalesceSettledTurns` and `attachSettledTurns` match
settled turns to agent bubbles by `agent.id` when both IDs are known,
falling back to display name.
- Tests:
- `server/src/__tests__/agent-chat-peer-messages.test.ts`: real
embedded-Postgres + Express route/service suite covering task-search
chat discovery, comment delivery + wake admission with `resume: true`,
run/agent/status/cancellation/proactive/credential checks, restricted
source tasks (private task, private project, private ancestor, unscoped
run), session fence + both `canReceiveCommentsFromAgents` and
`canCommentOnOtherTasks` permissions, cross-company isolation +
credential `onBehalfOfUserId` mismatch through the HTTP route, and
`buildNativeSessionHandoff` `other_agent` labeling.
- `server/src/__tests__/agent-conversations.test.ts`: verifies the new
peer-chat directive text.
- `server/src/__tests__/agent-chat-messages.test.ts`: updates the
expected denial message for an agent acting for a different person.
- `server/src/services/native-runtime/native-session-handoff.test.ts`:
preserves the fast unit suite on `master` and verifies
`renderNativeSessionHandoff` retains `author: "other_agent"` and
`authorAgentId`.
- `ui/src/components/task-chat/transcript-adapter.test.ts`: covers
ID-based turn coalescing and attachment when runs carry no display name.
- Docs and maps: updated `doc/PRODUCT.md`,
`doc/plans/2026-09-10-agent-chat.md`,
`docs/guides/agent-developer/comments-and-communication.md`, and
`maps/agent-access-map/agent-chat.md`.

## Verification

RED before fix on base `2d065677959b585065ff3fec8718156a4cf6f41d`:
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/agent-chat-peer-messages.test.ts`: **3 failed | 2 passed
(5)**:
- `delivers the message to the chat's agent as the sending agent's
message` failed with HTTP `409` (`"Issue is not resumable through
comment follow-up intent"`).
- `requires the sending agent's own running run, acting for the chat's
person` failed with `"Only this conversation's agent can post agent
messages"`.
- `refuses content from a restricted or missing source task` failed with
`"Only this conversation's agent can post agent messages"`.

GREEN after rebase and fix on head
`64ee873ad760ab0b53e2eaa161c5e83e7b1e9ad9`:
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/agent-chat-peer-messages.test.ts`: **7 passed (7)** (real
embedded Postgres + real Express `issueRoutes` + real `issueService` +
real `agentWakeupRequests` + real `buildNativeSessionHandoff`).
- `pnpm --filter @paperclipai/server exec vitest run
--no-file-parallelism src/__tests__/agent-chat-peer-messages.test.ts
src/__tests__/agent-conversations.test.ts`:
`agent-conversations.test.ts` **73 passed (73)**.
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/agent-chat-messages.test.ts
src/services/native-runtime/native-session-handoff.test.ts`: both files
**passed** (`native-session-handoff.test.ts`: **4 passed (4)**;
`agent-chat-messages.test.ts`: all tests passed).
- `pnpm --filter @paperclipai/ui exec vitest run
src/components/task-chat/transcript-adapter.test.ts`: **119 passed
(119)**.
- `pnpm --filter @paperclipai/server typecheck`: **passed**.
- `pnpm --filter @paperclipai/ui typecheck`: **passed**.
- `node scripts/check-maps.mjs`: **passed** (35 areas, 192 capability
IDs; references and contract fields valid).
- `node scripts/check-test-budget.mjs --files
server/src/__tests__/agent-chat-peer-messages.test.ts
server/src/__tests__/agent-chat-messages.test.ts
server/src/__tests__/agent-conversations.test.ts
server/src/services/native-runtime/native-session-handoff.test.ts
ui/src/components/task-chat/transcript-adapter.test.ts`: **PASS** (110
nightly suites validated, 5 test files checked).
- `pnpm verify --base 2d06567795
--explain`: exited `2` (global CI input
`maps/agent-access-map/agent-chat.md` changed; broad verification
delegated to required PR CI).

Not run locally:
- Full repository `pnpm test:run` and Playwright browser E2E suites
(covered by PR CI).
- Live provider-backed two-agent run (the embedded-Postgres integration
test exercises the real HTTP route, comment boundary, privacy guards,
wake admission, and fresh-session handoff up to provider dispatch).

## Risks

- Behavior change: other agents can now post in a person's chat with an
agent, waking that chat's agent. Existing controls remain enforced:
`canCommentOnOtherTasks`, `canReceiveCommentsFromAgents`, per-run
cross-task write limits, run cancellation, credential/run
responsible-user match, source-task privacy, and company boundaries.
- Prompt injection: another agent's text reaches a chat turn. Owner-only
paths still require the person's own message/outbox, fresh-session
history labels peer comments `other_agent`, and the chat directive
states peer comments never carry the person's approval or instruction
authority.
- Delivery & loops: peer chat messages use ordinary best-effort comment
wakes (not the durable human outbox). Budgets, cross-task write limits,
and directive guidance bound back-and-forth chatter.
- No schema, migration, or API contract change.

## Model Used

- Rebase, conflict resolution, additional boundary/handoff tests, and
verification: Google Gemini via Google Antigravity with tool use, shell
execution, and extended reasoning.
- Original implementation and design from #21232: Claude Opus 5.5
(`claude-opus-5-5`, Anthropic, via Claude Code).

## Checklist

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

---------

Co-authored-by: marshall <13757243+lucktastic@users.noreply.github.com>
Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-25 15:33:14 -06:00
Dotta 5e6bfe698d fix(heartbeat): guarantee queued interrupt receipt coalescing on admission (#22984)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - When an agent is busy on a chat or task, a person's follow-up
message parks as a `deferred_issue_execution` wake and can be sent
immediately via Interrupt (`queued-comment-interrupt:<queueId>`)
> - At claim time, `explicitOperatorRunIdentity` requires that
`<queueId>` was atomically coalesced into the replacement run (`status =
'coalesced'`, `runId = run.id`), or it rejects the claim with `403
Queued-message interrupt authority is unavailable`
> - Three admission paths still allowed a replacement wake or run to be
written without coalescing `<queueId>`: `/new` conversation resets
bypassed `readBlocker` but not `readCommentCandidates`,
`admitFreshIssueRun` inserted the primary wake and queued run even when
`readCommentCandidates` returned `[]` under an execution blocker, and
resuming an interrupt behind an active conversation run fell through to
`admitBusy` and inserted a duplicate deferred wake carrying
`queued-comment-interrupt:<queueId>`
> - This pull request aligns execution-blocker checks between admission
and candidate adoption, aborts fresh admission before creating a wake or
run when a required resumed receipt cannot be adopted, and stops
already-deferred interrupt/retry receipts from duplicating behind an
active execution run
> - The benefit is that queued messages sent while an agent is busy
coalesce cleanly with valid operator interrupt authority, while
legitimate execution blockers continue to hold non-reset work safely

## Linked Issues or Issue Description

Refs #14865, #20698

**What happened**

Even after #14857 and #20698 (card-answer interrupts), queued chat
interrupts can still leave their interrupt receipt uncoalesced (`status
= 'deferred_issue_execution'`, `runId = null`) while creating a
replacement wake/run carrying `idempotencyKey =
queued-comment-interrupt:<queueId>`:

1. A verified `/new` chat interrupt passes `readBlocker` (which forwards
`conversationResetCommentId`), but `readCommentCandidates` called
`getExecutionBlocker(tx, companyId, issueId)` without
`conversationResetCommentId`, returned `candidates: []`, and still
inserted a queued run whose claim immediately failed with `403
Queued-message interrupt authority is unavailable`.
2. If any execution blocker (including a concurrent `READ COMMITTED`
lease/recovery hold or multiple pre-boundary `restoreHold` rows) made
`readCommentCandidates` return `[]`, `admitFreshIssueRun` still inserted
both the primary wake request and a doomed queued run without coalescing
`queuedCommentInterruptId`.
3. When `resumeQueuedCommentInterrupt` entered `enqueueWakeup` while
`activeExecutionRun` held the issue on a conversation
(`allowRunCoalescing: false`), it fell through to `admitBusy` and
inserted a second `deferred_issue_execution` wake with `idempotencyKey =
queued-comment-interrupt:<queueId>`; once promoted after the active run
finished, that duplicate run failed claim with `403 Queued-message
interrupt authority is unavailable`.

**Expected behavior**

A queued interrupt run is only created when its interrupt receipt is
atomically coalesced into that run in the same transaction; otherwise
admission defers cleanly without inserting a duplicate wake or doomed
run. Legitimate execution blockers continue to hold non-reset messages.

## What Changed

- `server/src/modules/wake-queue/application/recovery-admission.ts` &
`server/src/services/heartbeat/queue.ts`: expose
`conversationResetCommentId` from `prepareRecovery` and pass it into
`admitFresh`, so `readCommentCandidates` applies the same verified
`/new` reset policy as `readBlocker`.
- `server/src/modules/wake-queue/adapters/postgres.ts`: forward optional
`conversationResetCommentId` to `getExecutionBlocker` in
`readCommentCandidates` (preserving the 3-argument call when absent),
and add `FreshIssueAdmissionRollbackError` handling in
`withIssueAdmission`.
- `server/src/modules/wake-queue/application/fresh-issue-run.ts` &
`server/src/modules/wake-queue/index.ts`: read comment candidates before
inserting the primary wake receipt for non-promoted fresh runs; if a
required resumed receipt (`queuedCommentInterruptId`,
`queuedCommentRequestId`, or `boardRetryReceiptId`) is not adopted,
return `undefined` without creating a wake or run (and roll back the
transaction if `explicitContinuationRunId` already wrote recovery
state).
- `server/src/services/heartbeat/queue.ts`: return `{ kind: "deferred"
}` immediately under `if (activeExecutionRun)` when resuming an
already-deferred `queuedCommentInterruptId`, `queuedCommentRequestId`,
or `taskRetryRequestId`, preventing `admitBusy` from folding it into
another run or inserting a duplicate deferred wake.
- `server/src/services/explicit-native-continuation.ts`: include
`restoreHoldPredicate()` in the conversation-boundary recovery action
query so multiple pre-boundary restore holds are resolved together
rather than leaving a residual hold for `readCommentCandidates`.
- `server/src/__tests__/heartbeat-queued-run-claim-isolation.test.ts` &
`server/src/modules/wake-queue/adapters/postgres.test.ts`: add
embedded-Postgres regression tests covering queued `/new` interrupts
under an active ownership hold, interrupt resumes racing an active chat
run (no duplicate `queued-comment-interrupt:` wakes and clean delivery
once the run ends), `admitFresh` aborting before creating a doomed run
when a blocker hides a required interrupt receipt, and confirming
non-reset ordinary chat messages still remain held behind an active
ownership blocker until released.

## Verification

- **RED (before production edits on
`2d065677959b585065ff3fec8718156a4cf6f41d`):**
- `cd server && npx vitest run
src/__tests__/heartbeat-queued-run-claim-isolation.test.ts`: failed on
queued `/new` interrupt (`receipt.status` stayed
`"deferred_issue_execution"` instead of `"coalesced"`) and on
active-chat interrupt race (`duplicateInterruptWakes` contained a newly
inserted duplicate wake instead of `[]`).
- `cd server && npx vitest run
src/modules/wake-queue/adapters/postgres.test.ts -t "checks execution
holds only when the scoped saved receipt exists"`: failed with
`AssertionError: expected { status: "queued", ... } to be undefined`
because `admitFresh` inserted a queued run despite
`readCommentCandidates` returning `[]`.
- **GREEN (after fix):**
- `pnpm --filter @paperclipai/server typecheck`: PASS (0 errors across
all 7 layers).
  - `node scripts/check-module-boundaries.mjs`: PASS.
- `node scripts/check-test-budget.mjs --files
server/src/__tests__/heartbeat-queued-run-claim-isolation.test.ts
server/src/modules/wake-queue/adapters/postgres.test.ts`: PASS (`110
nightly suites validated, 2 test file(s) checked`).
- `cd server && npx vitest run --no-file-parallelism
src/__tests__/heartbeat-queued-run-claim-isolation.test.ts
src/modules/wake-queue/application/recovery-admission.test.ts
src/modules/wake-queue/adapters/postgres.test.ts`: **3/3 files, 148/148
passed**.
- `cd server && npx vitest run src/__tests__/run-identity.test.ts
src/__tests__/heartbeat-responsible-user-invariant.test.ts`: **all
passed**.
- `cd server && npx vitest run --no-file-parallelism
src/__tests__/issue-queued-comments-dispatch-routes.test.ts
src/services/heartbeat/queue.test.ts`: **158/158 test assertions
passed** (`issue-queued-comments-dispatch-routes.test.ts` 40/40 passed;
`queue.test.ts` 118/118 tests passed, with only its `afterAll`
embedded-Postgres shutdown hitting the 30s default hook timeout on a
loaded host).
- `pnpm verify --base 2d06567795
--explain`: selects 1,947/2,301 Vitest files (shared hub `queue.ts`);
focused suites passed locally and PR CI supplies full sharded coverage.

## Risks

- Low risk. Legitimate execution blockers (including active ownership
holds and unresolved reconciliation holds on non-reset messages) are
preserved and explicitly covered by a new regression test.
- Moving `readCommentCandidates` before `saveReceipt` only applies to
non-promoted fresh runs; promoted durable chat wakes keep their existing
promote-before-read order so they cannot be re-adopted as secondary
candidates.
- No database migrations or schema changes.

## Model Used

- Google Gemini (Antigravity agent with tool use and local code/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
- [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
2026-11-25 15:32:47 -06:00
DottaandPaperclip 1299d1d776 fix(google-workspace): keep approved tools active when only Paperclip's display title changed (#22980)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Agents use Google Workspace through a connection whose catalog rows
store each action's definition, and a catalog refresh holds a changed
definition for review
> - #22630 replaced each launch Google Workspace action's discovered
title with Paperclip's own readable display label (for example, `Gmail:
Read a message`), and #22874 exempted transitions from Paperclip's
shipped REST schemas back to Google's MCP servers
> - Catalog publication still hashes `descriptor.title` into
`versionHash`, so refreshing a Google Workspace MCP connection whose
rows were saved before #22630 (with a `null` title or Google's raw
title, including after the 30-day technical-information strip) or after
a local display-title copy edit quarantines every approved Gmail and
Workspace action even though Google changed nothing
> - This pull request recognizes Paperclip-authored display titles for
the six REST-defined Google Workspace services and skips quarantine when
`schemaHash` is unchanged and `versionHash` matches the exact discovered
description, input schema, annotations, and risk level under the
previously saved or raw upstream title
> - The benefit is that catalog refreshes keep approved Gmail and Google
Workspace tools working without false review holds, while upstream
description, schema, annotation, risk-level, and non-Paperclip title
mutations still quarantine for review

## Linked Issues or Issue Description

Refs #22630
Refs #22874

**What happened?**

Refreshing a managed Google Workspace connection (`POST
/api/tool-connections/:id/catalog/refresh` or the automatic 15-minute
`listCatalog` refresh) puts previously approved Gmail and Workspace read
actions into `quarantined` (`pending_review`) when the saved catalog
rows carry a `null` title, Google's raw title (pre-#22630 MCP
connections, including rows stripped by the 30-day Google Technical
Information sweep), or an earlier Paperclip display title. Because
`discovery.ts` substitutes Paperclip's local display title
(`googleWorkspaceCatalogToolTitle`) before `publication.ts` computes
`descriptorHash`, `existing.versionHash !== hash` fires even when
Google's upstream definition did not change at all.

**Expected behavior**

Catalog refresh keeps already-approved Google Workspace actions `active`
(preserving `reviewedAt`, `reviewedByUserId`, Off, and Ask first
settings) when only Paperclip's own display title changed, while still
quarantining any upstream change to `description`, `inputSchema`,
`annotations`, `riskLevel`, or any title change on tools whose title is
provider-controlled. Already-quarantined rows stay held for human
review.

**Steps to reproduce**

1. Connect Google Workspace on Google's MCP servers with Gmail
permissions enabled and approve all read actions.
2. Have saved catalog rows from before #22630 (where `title` is `null`
or Google's raw title such as `"Get Message"` and `versionHash` was
computed with that title), or from an earlier Paperclip display title.
3. Run `refreshCatalog` against Google's MCP server returning the exact
same `description`, `inputSchema`, `annotations`, and `riskLevel`.
4. Observe that all 9 Gmail actions move to `status: "quarantined"`
(`quarantineReason: "pending_review"`) and disappear from agent
sessions.

**Paperclip version or commit**

`2d065677959b585065ff3fec8718156a4cf6f41d`

## What Changed

- `server/src/services/google-workspace-rest-dispatch.ts`: added
`googleWorkspacePaperclipToolTitle(toolName)` returning Paperclip's
static display title only for the six REST-defined Google Workspace
services (`gmail`, `drive`, `docs`, `sheets`, `slides`, `calendar`), and
reused it in `googleWorkspaceCatalogToolTitle`.
- `server/src/services/connectors/paperclip-defined-tools.ts`: exposed
`paperclipAuthoredToolTitle(connection, toolName)` on the narrow
connector contract so `publication.ts` stays connector-agnostic.
- `server/src/services/tool-access/catalog/descriptors.ts` &
`discovery.ts`: carried the raw upstream title as an in-memory-only
`upstreamTitle` field on `McpToolDescriptor` when Google Workspace
discovery replaces `title` with Paperclip's local display title (needed
when the 30-day Google Technical Information sweep has cleared
`existing.title` to `null`).
- `server/src/services/tool-access/catalog/publication.ts`: skipped
quarantine when `existing.schemaHash === schemaHash`,
`paperclipAuthoredToolTitle` equals `descriptor.title` (non-null), and
`descriptorHash` with `existing.title ?? null` or
`descriptor.upstreamTitle ?? null` matches `existing.versionHash`.
Already-quarantined rows remain quarantined, and any change to
`description`, `inputSchema`, `annotations`, `riskLevel`, or
non-Paperclip titles still quarantines.
- `server/src/__tests__/google-workspace-mcp-transport.test.ts`,
`server/src/services/google-workspace-rest-dispatch.test.ts`, and
`server/src/__tests__/connector-tool-policy.test.ts`: added
embedded-Postgres and unit regression tests covering all four
Paperclip-title-only refresh cases, plus security negative tests
confirming description/annotation/schema mutations on Gmail and upstream
title mutations on non-Paperclip connectors still quarantine.

## Verification

- Red before fix (on base `2d065677959b585065ff3fec8718156a4cf6f41d`):
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/google-workspace-mcp-transport.test.ts -t "keeps approved
Gmail read tools active on refresh when only Paperclip|still quarantines
approved Gmail read tools when Google mutates"` -> `4 failed | 1 passed`
(`AssertionError: expected 9 to be +0` quarantined on all 4 title-only
cases).
- Green after fix:
- `pnpm --filter @paperclipai/server exec vitest run
src/services/google-workspace-rest-dispatch.test.ts
src/__tests__/google-workspace-mcp-transport.test.ts
src/__tests__/connector-tool-policy.test.ts` -> **3 files, 77 passed
(77)** (including 34/34 embedded-Postgres Google Workspace MCP transport
tests, 21/21 REST dispatch tests, and 22/22 connector policy tests).
- `pnpm --filter @paperclipai/server exec vitest run
src/google-workspace-rest-tools/boundary.test.ts` -> **1 file, 2 passed
(2)**.
- `pnpm --filter @paperclipai/server typecheck` -> **PASS** (all 7
server typecheck layers).
- `node scripts/check-test-budget.mjs --files
server/src/services/google-workspace-rest-dispatch.test.ts
server/src/__tests__/google-workspace-mcp-transport.test.ts
server/src/__tests__/connector-tool-policy.test.ts` -> **PASS** (`110
nightly suites validated, 3 test file(s) checked`).
- `pnpm verify --base 2d06567795
--explain` selected 1947/2301 test files (>50); focused affected suites
and server typecheck ran locally while sharded PR CI supplies broad
coverage.

## Risks

- Low risk. No schema migration, no API contract change, and no
relaxation of security boundaries.
- Only tools whose displayed title is unconditionally replaced by
Paperclip's static `googleWorkspacePaperclipToolTitle` (the 36 launch
Google Workspace tools) can match `paperclipTitleOnlyChange`, and only
when SHA-256 proves `name`, `description`, `inputSchema`, `annotations`,
and `riskLevel` are all identical to the saved row.
- Already-quarantined rows (including pre-#22874 switch holds) remain
held for human review, matching #22874's safety invariant.

## Model Used

- Google Gemini (Antigravity agentic coding assistant) with tool use,
shell execution, and embedded-Postgres integration testing.

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

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-25 15:32:39 -06:00
Dotta 227c2f794f fix(runner): align request_human_input title and prompt limits with server (#22977)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Agents ask humans for answers or approvals with the runner's
`request_human_input` tool, which creates an interaction card on the
active task
> - The runner tool schema advertised `title` up to 300 characters and
`prompt` up to 10,000 characters
> - The server's `createIssueThreadInteractionSchema` enforces `title`
at most 240 characters and `summary` / `payload.prompt` at most 1,000
characters across all five interaction kinds
> - An agent that sends a 241–300 character title or a 1,001–10,000
character prompt passes the runner tool schema but fails server
validation, causing wasted retries
> - Open PR #20134 addressed the mismatch on an older base, but
conflicted with `master` and left `native-execution-seeded.json` and
`protocol/manifest.json` stale
> - This pull request defines shared constants inside
`packages/paperclip-runner`, aligns both runner tool catalogs to 240 /
1,000, regenerates every derived catalog and manifest file, and adds
cross-package parity tests for all five interaction kinds
> - The benefit is that agents receive the exact server limits in the
tool schema before calling `request_human_input`, preventing avoidable
validation failures and retries

## Linked Issues or Issue Description

Supersedes #20134 (rebased cleanly onto `master`, resolves catalog
conflicts, regenerates `native-execution-seeded.json` and
`protocol/manifest.json`, and tests all five interaction kinds).
Refs #19405

**What happened?**
An agent called `request_human_input` with a `prompt` longer than 1,000
characters (or a `title` longer than 240 characters). The call passed
the runner's advertised schema (`title` max 300, `prompt` max 10,000),
but failed server validation in `createIssueThreadInteractionSchema`
(`title <= 240`, `summary <= 1000`, `payload.prompt <= 1000`).

**What did you expect to happen?**
The runner's `request_human_input` schema should advertise the exact
character limits that the server accepts (`title` max 240, `prompt` max
1,000), so invalid inputs fail at the tool schema boundary instead of
failing server validation.

**Steps to reproduce**
1. Inspect
`capabilitySemanticToolDescriptor("request_human_input").inputSchema`
and `paperclipSemanticAction("request_human_input").inputSchema`.
2. Build an interaction input at the advertised `title.maxLength` and
`prompt.maxLength` and validate it with
`createIssueThreadInteractionSchema.safeParse(...)`.
3. Before this fix, all five interaction kinds fail server validation
with `too_big` (`maximum: 240` on `title`, `maximum: 1000` on `summary`
and `payload.prompt`).

## What Changed

- Exported `REQUEST_HUMAN_INPUT_TITLE_MAX_LENGTH = 240` and
`REQUEST_HUMAN_INPUT_PROMPT_MAX_LENGTH = 1000` from
`packages/paperclip-runner/src/protocol-actions/request-human-input.ts`
and updated its live descriptor to use them.
- Reused those constants in
`packages/paperclip-runner/src/catalog/semantic-action-catalog.ts` so
both runner catalogs share one source of truth.
- Regenerated
`packages/paperclip-runner/generated/semantic-action-catalog.json`,
`packages/paperclip-runner/generated/capability/semantic-tool-contracts.json`,
`packages/paperclip-runner/protocol/fixtures/evals/native-execution-seeded.json`,
and `packages/paperclip-runner/protocol/manifest.json`.
- Added a runner catalog parity test in
`packages/paperclip-runner/src/catalog/semantic-action-catalog.test.ts`
and a cross-package contract test in
`server/src/__tests__/request-human-input-bounds.test.ts` covering all
five interaction kinds (`ask_user_questions`, `request_confirmation`,
`request_checkbox_confirmation`, `request_item_verdicts`,
`suggest_tasks`) at `max` and `max + 1`.

## Verification

- `pnpm exec vitest run
server/src/__tests__/request-human-input-bounds.test.ts` (failed 5/6
before the fix with `too_big` 240/1000; passed 6/6 after the fix)
- `pnpm --filter @paperclipai/paperclip-runner exec vitest run
src/catalog/semantic-action-catalog.test.ts
src/catalog/protocol-action-contracts.test.ts
src/protocol-actions/core-contracts.test.ts
src/contracts/tool-input-variants.test.ts
src/evals/native-execution.test.ts
src/semantic-tools/semantic-tools.test.ts` (passed)
- `pnpm --filter @paperclipai/paperclip-runner run build` and `pnpm
--filter @paperclipai/paperclip-runner run check:static` (passed;
confirmed generated contracts, seeded catalog digest, and protocol
manifest match)
- `pnpm --filter @paperclipai/server typecheck` and `pnpm --filter
@paperclipai/paperclip-runner run typecheck:typescript` (passed)
- `pnpm exec vitest run
server/src/services/native-runtime/paperclip-runner-tool-authority.test.ts
-t "advertised (choice|text|mixed) question|checkbox interactions"` (4/4
embedded-Postgres tests passed)
- `cargo test --manifest-path
packages/paperclip-runner/runner/Cargo.toml --locked -p
paperclip-runner-core acpx_tool_failure_feedback` and `cargo test
--manifest-path packages/paperclip-runner/runner/Cargo.toml --locked -p
paperclip-runner-core --test acpx_provider_resolutions` (7 unit + 12
integration tests passed, confirming field-level Zod validation feedback
reaches the agent cleanly)
- `node scripts/check-test-budget.mjs --files
server/src/__tests__/request-human-input-bounds.test.ts` (passed)

## Risks

- Low risk. Narrowing the runner schema matches the trimmed character
limits that the server already enforces (`title` <= 240, `prompt` <=
1,000); raw inputs padded with extra leading or trailing whitespace that
exceed those raw lengths are conservatively rejected at the tool schema
boundary.
- Agents that need longer body text in a question card should put it in
`payload.questionSet.description` (up to 100,000 characters) or
`detailsMarkdown` on confirmation/checkbox/item-verdict payloads (up to
20,000 characters).

## Model Used

- Claude Opus 4.6 (`claude-opus-4-6`), Anthropic, with extended
thinking, tool use, and code execution in an agent harness.

## Checklist

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

> - Paperclip is the open source app people use to manage AI agents for
work.
> - OpenAI Dot connects to Paperclip through a dedicated agent OAuth
grant and a signed MCP Events subscription
(`paperclip.dot.mailbox_updated`).
> - Three compounding bugs broke paired Dot connections: (1) event
subscriptions expire after 24 hours with no renewal instructions and an
unclear "required" UI state that pushed operators to re-pair; (2) the
`/mcp/runner` 401 challenge and omitted-scope OAuth defaults requested
only `paperclip:agent` without `offline_access`, so clients received no
refresh token and broke after 15 minutes while the pairing preview still
promised ongoing access; and (3) expired or unpaired Dot runs failed as
generic `adapter_failed`, triggering an endless 15-minute automatic
recovery retry loop.
> - Operators should not have to re-pair a Dot every day, lose OAuth
access after 15 minutes, or watch failed runs loop every 15 minutes on a
missing or expired connection.
> - This pull request adds 24-hour subscription renewal instructions and
expired-subscription status/guidance, includes `offline_access` in the
Dot OAuth 401 challenge and default scopes with an accurate pairing
preview, and classifies missing or expired Dot connections as
non-retryable `configuration_incomplete` with clear operator
instructions.
> - The benefit is durable Dot OAuth and event-subscription renewal
without needless re-pairing, honest pairing previews, and clean
blocked-task guidance instead of infinite retry loops.

## Linked Issues or Issue Description

**What happened?**

1. `paperclip.dot.mailbox_updated` event subscriptions expire after 24
hours (`lifetime` in `server/src/services/public-mcp/events.ts`), but
neither the Dot setup prompt nor pairing `eventInstructions` told Dot to
resubscribe before `refreshBefore`. After 24 hours, new runs failed with
`"Dot must be paired with a verified event subscription and a completed
event test."` and `DotRunnerConnection` displayed `"Event subscription:
required"`, pushing operators to re-pair needlessly.
2. The `/mcp/runner` 401 `WWW-Authenticate` challenge
(`server/src/routes/public-mcp.ts`) and omitted-scope OAuth defaults
(`server/src/services/public-mcp/oauth.ts`) requested only
`paperclip:agent` instead of `paperclip:agent offline_access`. Clients
following the challenge or omitting `scope` received no refresh token
and failed after 15 minutes even though the pairing preview promised
`"Ongoing until revoked"`.
3. When a Dot binding was unpaired or its event subscription expired,
runs failed with generic `adapter_failed` (before `nativeExecutionInput`
was persisted), so automatic recovery (`issue_recovery_action_restored`
/ `issue_continuation_needed`) kept retrying every 15 minutes
indefinitely.

**Expected behavior**

1. Dot receives explicit instructions to renew
`paperclip.dot.mailbox_updated` before `refreshBefore` and on expiry;
when expired, Paperclip names the expiry and shows `"Event subscription:
expired"` with resubscribe guidance (no new pairing needed).
2. Dot OAuth challenges and default scopes include `offline_access` so
paired clients receive rotating refresh tokens; an explicit agent-only
request without `offline_access` displays an accurate 15-minute
non-renewable access preview.
3. Missing or expired Dot connections fail as non-retryable
`configuration_incomplete` with dedicated operator recovery notices,
moving the task to `blocked` and stopping automatic recovery loops.

**Steps to reproduce**

1. Pair an OpenAI Dot agent and omit `scope` (or follow the
`/mcp/runner` 401 `WWW-Authenticate` challenge); inspect the issued
OAuth tokens (no `refresh_token`) and the pairing preview for an
explicit `paperclip:agent` request.
2. Expire the agent's `mcp_event_subscriptions` row past 24 hours or
revoke the binding, then assign a task to the Dot agent.
3. Observe the run failing as `adapter_failed` and automatic recovery
repeatedly queuing continuation runs every 15 minutes.

**Paperclip version or commit**

Base commit `2d065677959b585065ff3fec8718156a4cf6f41d` on `master`.

## What Changed

- **24-hour event subscription renewal & expired UX**:
- Updated `pair()` `eventInstructions` in
`server/src/modules/external-agents/dot.ts` and `buildDotSetupPrompt` in
`ui/src/lib/dot-setup-prompt.ts` to instruct Dot to renew
`paperclip.dot.mailbox_updated` before `refreshBefore` and whenever
Paperclip reports expiry.
- Added `subscriptionExpired` to `bindingForAgent()`, surfaced an
explicit expired-subscription error in `snapshot()` and the Dot
environment check (`server/src/routes/agents.ts`), added
`subscriptionExpired` to the OpenAPI schema
(`server/src/routes/openapi.ts`), and updated
`ui/src/components/DotRunnerConnection.tsx` to display `"Event
subscription: expired"` with resubscribe guidance without re-pairing.
- **OAuth `offline_access` challenge, default scopes, and honest
preview**:
- Updated the `/mcp/runner` 401 `WWW-Authenticate` challenge
(`server/src/routes/public-mcp.ts`) and Dot `defaultScope` for both
`authorize` and `deviceAuthorize`
(`server/src/services/public-mcp/oauth.ts`) to use
`DOT_RUNNER_MCP_SCOPES` (`paperclip:agent offline_access`).
- Updated `describeDotPairing()`
(`server/src/services/public-mcp/oauth.ts`) to show a 15-minute
non-renewable duration when a client explicitly requests
`paperclip:agent` without `offline_access`.
- **Non-retryable recovery on expired or unpaired Dot**:
- Tagged unavailable Dot binding errors in
`server/src/modules/external-agents/dot.ts` with typed
`DotBindingUnavailableReason` (`dot_subscription_expired` /
`dot_pairing_required`) on `McpOAuthError`, mapped them to
`ConfigurationIncompleteFailure` in
`server/src/services/heartbeat/runtime-selection.ts`, and mapped
`paperclip_runner_dot_config_invalid` / `paperclip_runner_dot_disabled`
to `ConfigurationIncompleteFailure` in
`server/src/services/heartbeat/run-completion.ts`.
- Added `dot_subscription_expired` and `dot_pairing_required` notices in
`server/src/services/recovery/stranded-notice.ts`, added
`configuration_incomplete` to `NON_RETRYABLE_CONTINUATION_ERROR_CODES`,
and extended `CONFIGURATION_INCOMPLETE_ERROR_RE` in
`server/src/services/recovery/service.ts` so pre-existing legacy
`adapter_failed` Dot runs also stop looping immediately.
- Note on file size: `runtime-selection.ts`, `run-completion.ts`,
`recovery/service.ts`, `agents.ts`, and `openapi.ts` already exceeded
1,000 lines on `master`; this PR adds only narrow, owning-module changes
(2 to 31 lines each) without introducing new modules.
- **Tests**:
- Extended `server/src/__tests__/dot-runner.test.ts` with
embedded-Postgres tests covering 24h subscription expiry + resubscribe
recovery without re-pairing, OAuth 401 `offline_access` challenge +
omitted-scope refresh token rotation, and full heartbeat +
`assignedWorkSweep` + recovery classification proof that expired and
unpaired Dot runs fail as non-retryable `configuration_incomplete`
without looping.
- Extended `server/src/__tests__/dot-oauth-onboarding.test.ts` for
omitted-scope device authorization (`offlineAccess: true`) and honest
15-minute pairing preview on explicit agent-only scope.
- Added focused UI regression tests in
`ui/src/components/DotRunnerConnection.test.tsx`.

## Verification

- `pnpm exec vitest run server/src/__tests__/dot-runner.test.ts
server/src/__tests__/dot-oauth-onboarding.test.ts
server/src/__tests__/grok-bot-routine.test.ts
server/src/services/public-mcp/discovery.test.ts`: **4 files, 124 passed
(124)** (`dot-runner`: 59, `dot-oauth-onboarding`: 18,
`grok-bot-routine`: 45, `discovery`: 2).
- `pnpm exec vitest run server/src/__tests__/public-mcp.test.ts
server/src/services/antigravity-swarm.test.ts
server/src/__tests__/disposition-repair.test.ts`: **3 files, 90 passed
(90)**.
- `pnpm --filter @paperclipai/ui exec vitest run
src/components/DotRunnerConnection.test.tsx`: **1 file, 2 passed (2)**.
- `pnpm --filter @paperclipai/ui typecheck` && `pnpm --filter
@paperclipai/server typecheck` (all 7 layers): **PASS**.
- `pnpm check:token-gates`: **All 4 gates CLEAN, cliplab character in
sync**.
- `node scripts/check-test-budget.mjs --files
server/src/__tests__/dot-runner.test.ts
server/src/__tests__/dot-oauth-onboarding.test.ts
ui/src/components/DotRunnerConnection.test.tsx`: **PASS (110 nightly
suites validated, 3 test file(s) checked)**.
- `pnpm verify --base 2d06567795
--explain` selected 2,224/2,927 files because shared server modules
(`oauth.ts`, `run-completion.ts`, `recovery/service.ts`) are modified;
focused affected suites and full UI/server typechecks ran locally, and
sharded PR CI covers the full repository suite.

## Risks

- **Low risk.** No database migrations, no changes to existing OAuth
grants, no changes to the 24-hour subscription security lifetime, and no
changes to Personal MCP, Muse, or Grok Bot scopes or admission gates.
- Existing Dot grants created without `offline_access` retain their
original scopes and will need one reconnect after deploy to obtain
refresh tokens.
- Real ChatGPT/OpenAI Dot client renewal beyond 15 minutes and automatic
idle wake reliability remain subject to OpenAI's external client
behavior (unrelated to Paperclip's webhook delivery path).

## Model Used

- **Provider & Model:** Claude (Anthropic) via Antigravity agent runtime
(exact model snapshot ID and context window size are not exposed in this
environment).
- **Capabilities Used:** Codebase inspection, reasoning,
TypeScript/React editing, shell execution, embedded-Postgres and Vitest
verification, and GitHub CLI PR creation.

## 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
2026-11-25 15:32:27 -06:00
DottaandPaperclip 71d7f86293 fix(runtime): prevent pre-start plugin workspace, checkpoint, and taskless wake failures (#22973)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Paperclip Runner agents run tasks inside local, sandbox, and plugin
task environments.
> - Four pre-start failure modes still prevent valid runs from starting
or create doomed failing runs before the agent launches.
> - A Core-storage project running on a workspace-storage plugin
environment can reserve an empty `adapter_managed` workspace on fresh
retries or `project_primary` runs and retry in an hourly loop.
> - A task reassigned to or reviewed by another agent on the same plugin
environment fails with `plugin_workspace_owner_mismatch` because the
retained `adapter_managed` workspace still names the previous agent.
> - A follow-up wake whose prior plugin task stopped without retained
session state fails with `checkpoint_status_unconfirmed`, and sanitized
plugin task worker errors drop safe closed-enum operation and RPC codes.
> - Non-timer taskless wakes (such as manual Run Heartbeat) still
enqueue doomed Runner runs that immediately fail with an
ineligible-work-mode message.
> - This pull request fixes all four pre-start paths while preserving
cross-environment, local-workspace, credential-redaction, and stop-proof
invariants.

## Linked Issues or Issue Description

Refs #19921, #22849, #19878.

**What happened?**

Four pre-start failure modes affected Paperclip Runner tasks before the
agent started:

1. When a task in a Core-storage project (no `storageProviderPluginId`)
ran on a workspace-storage plugin environment with `project_primary` or
a fresh continuation retry, `prepareHeartbeatWorkspace` called
`reserveFreshPluginTaskWorkspace` before checking project storage
compatibility, creating an empty `adapter_managed` workspace and looping
on retries.
2. When a task with a retained `adapter_managed` plugin workspace was
reassigned to another agent or reviewed by another agent on the same
plugin environment, `prepareHeartbeatWorkspace` threw
`WorkspaceValidationFailure` (`plugin_workspace_owner_mismatch`).
3. When `executeEnvironmentTask` sanitized worker failures, it discarded
safe closed-enum operation and RPC error codes, and when a follow-up run
inspected a committed, provably stopped prior plugin task whose provider
session state was gone (`executionStopped: true, sessionStateAvailable:
false`), `recoverPluginRunnerCheckpoint` failed the run with
`checkpoint_status_unconfirmed` instead of retiring the settled root
into a fresh session.
4. When a user or caller triggered a non-timer taskless wake (for
example `POST /api/agents/:id/heartbeat/invoke` or `/wakeup` without a
task) on a `paperclip_runner` agent, `heartbeat.wakeup` still created a
run that immediately failed with `"Paperclip Runner requires a standard,
planning, ask, or skill test task."`

**Expected behavior**

1. Core-storage project sources running on a workspace-storage plugin
environment fail early with `configuration_incomplete`
(`project_storage_environment_incompatible`) across all workspace
strategies and fresh retries without reserving an empty workspace.
2. Reassigned assignees and reviewers on the same plugin environment
provision their own agent-owned `adapter_managed` workspace (rebinding
`issues.executionWorkspaceId` only for the assignee, leaving the
assignee's workspace intact during reviews, and keeping
cross-environment and local-workspace ownership guards fail-closed).
3. Sanitized plugin task errors carry closed-enum `pluginTaskError`
(`operation`, `errorCode`, `rpcErrorCode`) into `resultJson` without
leaking worker text or credentials, and a committed, provably stopped
prior plugin task with `executionStopped: true` and
`sessionStateAvailable: false` retires cleanly into `continuity-breaks`
so the new run starts fresh.
4. Non-timer taskless wakes for `paperclip_runner` agents are skipped
cleanly with a `heartbeat.task_required` receipt and `reason:
"task_required"` wakeup response instead of creating a failing run, and
`resolveNativeRuntimeMode` distinguishes missing-task
(`paperclip_runner_task_required`) from wrong work mode
(`paperclip_runner_issue_ineligible`).

**Steps to reproduce**

1. Run `prepareHeartbeatWorkspace` with a Core-storage project workspace
on an active workspace-storage plugin environment during a fresh retry
or `project_primary` run.
2. Run `prepareHeartbeatWorkspace` as Agent A on a plugin environment,
then reassign or review the task as Agent B on the same plugin
environment.
3. Trigger a follow-up replacement run when the prior committed plugin
task is stopped (`executionStopped: true`) with `sessionStateAvailable:
false`, or throw a `JsonRpcCallError` timeout from a plugin task worker.
4. Call `heartbeat.wakeup` with `source: "on_demand"` and no task scope
on a `paperclip_runner` agent.

**Paperclip version or commit**

Reproduced on `origin/master` at
`2d065677959b585065ff3fec8718156a4cf6f41d`.

**Deployment mode**

Self-hosted / Cloud server. Verified locally on macOS arm64 with
embedded PostgreSQL.

## What Changed

- `server/src/services/heartbeat/workspace-preparation.ts`:
- Check `projectStorageForEnvironment` for Core-storage project sources
on workspace-storage plugin environments immediately after
`preparePluginWorkspace` and before `reserveFreshPluginTaskWorkspace`,
covering `fresh` retries and `project_primary` as well as
`git_worktree`.
- Detach a foreign agent's `adapter_managed` plugin workspace when a
different `paperclip_runner` agent runs on the same plugin environment
(not during native restart recovery) so the new agent provisions its own
agent-owned workspace cleanly; rebind `issues.executionWorkspaceId` and
idle the previous workspace only when `wasIssueAssignee` is true, and
leave the assignee's workspace untouched during reviews.
- `server/src/services/environment-task-runtime.ts` and
`server/src/services/heartbeat/run-completion.ts`:
- Attach closed-enum `pluginTaskError` (`operation`, optional
`errorCode`, optional `rpcErrorCode`) on sanitized worker errors without
forwarding raw worker text or `cause`, and persist it to
`resultJson.pluginTaskError` on failed runs.
- Attach closed-enum `pluginTaskCheckpointStatus` (`executionStopped`,
`sessionStateAvailable`) to `checkpoint_status_unconfirmed` refusals
while preserving the exact error message.
- `server/src/services/native-runtime/native-session-executor.ts`:
- When a replacement/created run hits `checkpoint_status_unconfirmed`
with explicit `executionStopped: true` and `sessionStateAvailable:
false` on a non-quarantined settled journal, pass
`pluginCheckpointUnavailableConfirmed` into
`retireFinishedPerTurnRunnerdOwner` /
`inspectFinishedPerTurnRunnerdOwner`, verify `remoteExecutionHasStopped`
plus all existing committed-owner and controller-stop proofs, and
archive the prior root into `continuity-breaks` for a fresh session.
Keep unconfirmed stops fail-closed.
- `server/src/services/heartbeat-policy.ts`,
`server/src/services/heartbeat/queue.ts`, `server/src/routes/agents.ts`,
and `server/src/services/native-runtime/runtime-mode.ts`:
- Add `supportsUnscopedHeartbeat`, skip non-timer taskless wakes for
`paperclip_runner` agents with a `heartbeat.task_required` skipped
wakeup receipt, return `reason: "task_required"` in
`buildSkippedWakeupResponse`, and separate
`paperclip_runner_task_required` from
`paperclip_runner_issue_ineligible`.
- `doc/project-environment-compatibility.md`:
- Update the Core-storage-on-plugin-environment note to reflect early
refusal across all workspace strategies and fresh retries.
- Tests added across `workspace-preparation.test.ts`,
`environment-task-runtime.test.ts`,
`environment-task-authority.integration.test.ts`,
`run-completion.test.ts`, `native-session-executor.test.ts`,
`heartbeat-stale-queue-invalidation.test.ts`, `runtime-mode.test.ts`,
and `agent-live-run-routes.test.ts`.
- Note on file length: edits touch existing >1,000-line
lifecycle/executor modules (`workspace-preparation.ts`,
`native-session-executor.ts`, `queue.ts`, `run-completion.ts`,
`agents.ts`) with minimal, scoped additions directly at each invariant
boundary to avoid churn.

## Verification

- **RED (on base `2d065677959b585065ff3fec8718156a4cf6f41d` before
production edits):**
- Ran the 8 new focused tests across `workspace-preparation.test.ts`,
`environment-task-runtime.test.ts`, `run-completion.test.ts`,
`native-session-executor.test.ts`,
`heartbeat-stale-queue-invalidation.test.ts`, and
`runtime-mode.test.ts`: **8 failed | 1 control passed**, confirming
every bug reproduced before edits.
- **GREEN (on head `9c860ca51c4e9742a6594e12ae160895aab8dbdf`):**
- `pnpm --filter @paperclipai/server typecheck` (all 7 layers):
**PASS**.
- Unit suites (`environment-task-runtime.test.ts`,
`runtime-mode.test.ts`, `provider-fresh-workspace.test.ts`,
`native-exact-resume-failure.test.ts`): **4/4 files passed** (`100%`).
- `native-session-executor.test.ts` (focused plugin checkpoint +
unconfirmed checkpoint tests) and `agent-live-run-routes.test.ts`
(focused wakeup/invoke/task_required tests): **PASS**.
- Real embedded-Postgres integration suites
(`environment-task-authority.integration.test.ts` 11/11,
`ephemeral-server-data.test.ts` 6/6, `workspace-preparation.test.ts`
18/18 focused plugin/storage/reassignment/fresh-retry tests,
`heartbeat-stale-queue-invalidation.test.ts` + `run-completion.test.ts`
8/8 focused tests): **PASS**.
- `node scripts/check-test-budget.mjs --files <all 8 modified test
files>`: **PASS** (`110 nightly suites validated, 8 test file(s)
checked`).
- Broad repo-wide verification is supplied by sharded GitHub Actions CI.

## Risks

- Low risk. Cross-environment mismatches, local-workspace reuse on
plugin environments, and native restart recovery ownership checks remain
fail-closed (`plugin_workspace_owner_mismatch`).
- Only committed, provably stopped (`remoteExecutionHasStopped` +
controller-stop proof + settled journal) prior plugin tasks with
explicit provider `executionStopped: true, sessionStateAvailable: false`
retire into `continuity-breaks`; unconfirmed stops still fail closed.
- Sanitized plugin task errors only expose closed-enum operation,
errorCode, and RPC code names; raw worker messages and credentials
remain redacted.
- No database migrations or schema changes are required.

## Model Used

- Google Gemini (Antigravity agentic coding assistant) with tool use,
shell execution, and local embedded-PostgreSQL test verification. Exact
deployment model ID and context window are not exposed to the 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: Paperclip <noreply@paperclip.ing>
2026-11-25 15:32:20 -06:00
DottaandPaperclip cc5136ca02 fix(workspaces): run projectless isolated tasks and chats without a repo (#22972)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Execution workspace isolation controls how each task and
conversation gets a working directory
> - When isolated workspaces are enabled (including with
`enableIsolatedWorkspacesByDefault`), a task or conversation without a
project or repository can resolve to `isolated_workspace` without an
explicit `workspaceStrategy`
> - Wakeup preflight synthesized the default `git_worktree` strategy and
blocked projectless tasks with `workspace_worktree_requires_project`,
while `shouldUseIsolatedTaskDirectory` only allowed `low_trust_review` +
`sandbox` and failed standard local, sandbox, and plugin runs with
`git_worktree_base_not_git_checkout` or
`plugin_workspace_strategy_unsupported`
> - This pull request admits repository-free isolated tasks and
conversations into private isolated task directories across local,
sandbox, and plugin environments while preserving explicit Git worktree
validation, SSH preflight blocking, cross-task archived-workspace
protection, and low-trust sandbox containment
> - The benefit is that projectless tasks, projectless agent chats, and
repository-free project tasks run cleanly with persistent isolated
directories across turns, without weakening Git worktree isolation for
repository-backed projects

## Linked Issues or Issue Description

Fixes: #20962

Refs #20963, #19860, #14766, #13636

Relationship to #20963: #20963 enables private task directories for
standard local repository-free tasks and guards
`hasSelectedExecutionWorkspace`. This pull request builds on that
direction by also:
- Allowing repository-free isolated tasks without an explicit
`workspaceStrategy` to pass wakeup preflight in
`server/src/services/heartbeat/queue.ts` via the canonical
`shouldUseIsolatedTaskDirectory` predicate with resolved trust preset
and environment driver (otherwise projectless tasks and chats with
`mode: "isolated_workspace"` are blocked with
`workspace_worktree_requires_project` before environment selection runs,
while SSH, explicit `git_worktree`, and cross-task/shared archived
bindings remain blocked pre-dispatch).
- Supporting standard `sandbox` (Paperclip Cloud) and `plugin`
environments in `shouldUseIsolatedTaskDirectory` (including multi-turn
ordinary plugin task directory reuse via `isBoundPluginTaskDirectory`),
not only `local` / `null`.
- Scoping `!hasSelectedExecutionWorkspace` strictly to `trustPreset ===
"standard"` so `low_trust_review` sandbox containment remains unchanged.
- Preserving `nativeChatWorkspaceScope` isolation (zero referenced
project roots) in `workspace-preparation.ts` when an external chat also
uses a private task directory.

## What Changed

- `server/src/services/isolated-task-directory.ts`: Extract
`hasExplicitWorkspaceStrategy`, add a `standard`-scoped
`hasSelectedExecutionWorkspace` guard, and allow
`shouldUseIsolatedTaskDirectory` for `standard` trust on `local`,
`sandbox`, `plugin`, and `null` drivers while keeping `low_trust_review`
sandbox containment unchanged and keeping `ssh`, `denied`, selected
standard workspaces, and explicit strategies excluded.
- `server/src/services/provider-fresh-workspace.ts`: Add
`isBoundPluginTaskDirectory` recognizing both fresh plugin attempt
directories and ordinary task-owned plugin directories
(`/workspaces/<issueId>` with matching `runnerTaskWorkspaceOwner`,
`projectWorkspaceId === null`, and no `runnerTaskFreshWorkspace`) so
multi-turn repository-free plugin tasks reuse their bound workspace
without hitting `plugin_workspace_strategy_unsupported`.
- `server/src/services/heartbeat/queue.ts`: Call the canonical
`shouldUseIsolatedTaskDirectory` during wakeup preflight with resolved
`trustPreset` (`resolveCoreTrustPreset`) and effective
`environmentDriver` (honoring `executionWorkspaceSettings.environmentId`
for `low_trust_review`, `executionMode === "kubernetes"`, and
`enableManagedSandboxOnly`, and allowing verified exclusively task-owned
archived/cleanup_failed task directories matching
`readTaskDirectoryRetention` or `issue_terminal` cleanup while blocking
cross-task/shared archived bindings) to resolve
`effectivePreflightStrategy` to `"project_primary"` instead of adding a
bypass flag on `isUnrunnableWorktreeCombo`.
- `server/src/services/heartbeat/environment-selection.ts`: Use
`isBoundPluginTaskDirectory` for bound plugin task directory reuse and
pass `hasSelectedExecutionWorkspace` into
`shouldUseIsolatedTaskDirectory` so existing or tampered standard
workspace bindings still go through binding validation.
- `server/src/services/heartbeat/workspace-preparation.ts`: Force
`project_primary` strategy for host and plugin preparation when
`useIsolatedTaskDirectory` is active (outside `remoteAuthority`), and
keep projectless `nativeChatWorkspaceScope` runs on the external-chat
directory branch so referenced projects are not attached.
- `doc/experimental/issue-worktree-support.md`: Document private
isolated task directory behavior for repository-free isolated tasks and
conversations.
- Tests: Extend `isolated-task-directory.test.ts`,
`provider-fresh-workspace.test.ts`, `workspace-preparation.test.ts`, and
`heartbeat-workspace-source-trust.test.ts` with unit and
embedded-Postgres E2E coverage across local, sandbox, plugin, and SSH
environments (projectless tasks, projectless chats, repo-free projects,
2-turn local/sandbox/plugin workspace reuse, git-backed project
`git_worktree` regression, explicit projectless `git_worktree` block,
SSH pre-dispatch block, low-trust projectless sandbox on SSH-default
agent, cross-task archived workspace blocking, and exclusively
task-owned archived directory reopening).

## Verification

- `pnpm exec vitest run
server/src/services/isolated-task-directory.test.ts
server/src/services/provider-fresh-workspace.test.ts
server/src/__tests__/execution-workspace-policy.test.ts` — 3 files, 101
passed (101).
- `pnpm exec vitest run
server/src/services/heartbeat/workspace-preparation.test.ts -t "prepares
a repository-free local task directory|reuses a bound ordinary
repository-free plugin task directory|names incompatible Core project
storage"` — 3 passed (including 2-turn ordinary plugin task directory
reuse + explicit `git_worktree` rejection).
- `pnpm exec vitest run
server/src/__tests__/heartbeat-workspace-source-trust.test.ts -t "in a
company with no repository|still uses git_worktree"` — 9 passed with
embedded Postgres (projectless tasks, projectless chats, repo-free
projects on local and sandbox, git-backed project `git_worktree`,
explicit projectless `git_worktree` block, SSH pre-dispatch block,
low-trust projectless sandbox on SSH-default agent, cross-task archived
workspace pre-dispatch block, and own archived isolated task directory
reopening).
- `pnpm exec vitest run
server/src/__tests__/heartbeat-workspace-branch-containment.test.ts -t
"blocks projectless isolated git-worktree issues before dispatch"` — 1
passed.
- `pnpm --filter @paperclipai/server typecheck` — passed (0 errors
across all 7 layers).
- `node scripts/check-test-budget.mjs --files
server/src/services/isolated-task-directory.test.ts
server/src/services/provider-fresh-workspace.test.ts
server/src/services/heartbeat/workspace-preparation.test.ts
server/src/__tests__/heartbeat-workspace-source-trust.test.ts` — PASS
(110 nightly suites validated, 4 test files checked).
- `git diff --check` — clean; no secrets, artifacts, or internal IDs.
- Sharded PR CI on `eb2b11ee9b`: **66/66** executed checks `SUCCESS` (0
failing, 0 pending, 7 skipped, 2 non-blocking neutral Paperclip Review),
including `ci / verify`, `ci / e2e` + all 16 E2E shards, all 20 General
server shards + chat + workspaces-b, all 9 Serialized server shards, all
Verify Paperclip Runner lanes, `Build`, `Typecheck + Release Registry`,
`policy`, `Superagent Security Scan`, `Socket Security`, `Contributor
trust`, `commitperclip`, `Snyk`, and `Greptile Review` (5/5).

## Risks

- Repository-free tasks and conversations with `mode:
"isolated_workspace"` and no explicit `workspaceStrategy` now run in
private task directories under
`<instanceRoot>/isolated-workspaces/<companyId>/<issueId>` (or
`/workspaces/<issueId>` on plugin environments / remote empty workspaces
under `remoteAuthority`) instead of failing preflight or Git checkout
validation.
- Explicit `workspaceStrategy` requirements (including `git_worktree`,
`existingBranch`, and `provisionCommand`), SSH pre-dispatch blocking,
cross-task archived workspace blocking, low-trust sandbox confinement,
tampered-binding checks (`hasSelectedExecutionWorkspace`), and
`git_worktree` isolation for git-backed projects remain unchanged.
- No database migrations, schema changes, or API contract changes.

## Model Used

- Claude Opus 4.6 (`claude-opus-4-6`) in Antigravity with tool use,
shell execution, and extended thinking.

## Checklist

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

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Task execution recovery prevents failed, timed-out, or interrupted
runs from leaving tasks permanently blocked.
> - Three concrete recovery gaps still leave tasks stuck:
`hermes_gateway` is omitted from `CONVERSATION_ADAPTER_TYPES` (so
timed-out/cancelled runs stick in
`legacy_execution_requires_reconciliation`), terminal `hermes_gateway`
429/529 failures omit `errorFamily` (so bounded transient retry never
fires), and automatic continuation after a non-retryable workspace
`binding_mismatch` chooses `writer_ended` (reusing the broken workspace
in a loop) while stranded notices omit the saved failure reason.
> - Users cannot unblock `hermes_gateway` tasks via Retry or board
comments, transient provider rate limits park tasks indefinitely, and
`binding_mismatch` tasks exhaust the hourly retry cap with only a
generic chat notice.
> - This pull request adds `hermes_gateway` to conversation continuation
and explicit continuation admission (delegating terminal stop proof to
the Hermes adapter), classifies terminal `hermes_gateway`
429/529/5xx/quota/gateway-shutdown failures with `errorFamily` and
`retryNotBefore`, switches automatic continuation to
`fresh_isolated_workspace` on non-retryable `binding_mismatch`, and
surfaces the Core-owned failure reason in stranded no-running-execution
notices.
> - The benefit is that stuck `hermes_gateway` holds clear cleanly when
stopped, transient upstream errors retry automatically, and
`binding_mismatch` continuations start in a fresh isolated workspace
with clear user-facing diagnostics.

## Linked Issues or Issue Description

- Fixes: #17196
- Fixes: #17526
- Refs #21289 (extends non-retryable `binding_mismatch` fresh-workspace
handling from manual board Retry to automatic continuation fallback and
stranded recovery notices)
- Related open PRs checked during dedup search (no overlap): #22756,
#22810, #22738

## What Changed

- **`hermes_gateway` conversation continuation and hold clearing
(#17196)**:
- Add `"hermes_gateway"` to `CONVERSATION_ADAPTER_TYPES` in
`server/src/services/conversation-continuation.ts` so failed,
interrupted, and acknowledged-cancelled `hermes_gateway` runs receive
`conversationContinuation` policy and matching holds retire cleanly.
- Export `hasHermesGatewayTerminalStopProof` from
`@paperclipai/hermes-paperclip-adapter/gateway/server`
(`packages/adapters/hermes/src/gateway/server/terminal-failure.ts`) and
consume its boolean result in
`server/src/services/explicit-native-continuation.ts` so pre-existing
`legacy_execution_requires_reconciliation` holds for remote
`hermes_gateway` runs clear `process_identity_missing` only when the
Hermes adapter confirms a terminal gateway response or pre-fetch
configuration error, while unconfirmed `hermes_gateway` timeouts fail
closed.
- **`hermes_gateway` terminal transient/quota classification (#17526)**:
- Extract terminal error classification into
`packages/adapters/hermes/src/gateway/server/terminal-failure.ts` and
wire it in `packages/adapters/hermes/src/gateway/server/execute.ts`
(`extractErrorMessage`, `classifyTerminalFailure`,
`mapFinalResultForTest`) to classify terminal provider
429/529/5xx/rate-limit/overload errors (including camelCase
`statusCode`/`httpStatus`, `HTTP/x.y` status lines, and `Bad
Gateway`/`Gateway Timeout` phrases) as `errorFamily:
"transient_upstream"`, structured/message quota errors (including
`insufficient_quota`) as `errorFamily: "provider_quota"`, and forward
range-checked `retryNotBefore` from `retry_not_before` / `retry_after`.
- Map unexpected `hermes_gateway` shutdown/restart interruptions
(`status: "cancelled"` with shutdown/restart wording) to retryable
failed outcomes (`errorCode: "hermes_gateway_run_failed"`, `signal:
null`, `errorFamily: "transient_upstream"`, `resultJson: { status:
"interrupted", gateway_status: "cancelled" }`) while keeping deliberate
cancels as `cancelled`, keeping HTTP 400/403 errors (even with
rate-limit/overloaded text) non-transient, and never forging
`connectionFailure` from remote text.
- **Automatic continuation `binding_mismatch` isolation and saved
failure cause**:
- Export `readWorkspaceProviderFailure` and
`workspaceProviderFailureMessage` in
`server/src/services/workspace-provider-failure.ts` using only
Core-owned closed messages (no raw provider text).
- Update `server/src/services/fresh-continuation-fallback.ts` to choose
`isolation: "fresh_isolated_workspace"` instead of `"writer_ended"`
strictly when `run.resultJson.workspaceProviderFailure?.retryable ===
false && workspaceProviderFailure.reason === "binding_mismatch"`,
clearing `issues.executionWorkspaceId` and tagging
`freshContinuationIsolation` while preserving `"writer_ended"` for
retryable and non-binding errors (e.g. `storage_pending`,
`credential_unavailable`).
- Update `buildNoRunningExecutionNoticeSeed` and
`buildImmediateExecutionPathRecoveryNoticeSeed` in
`server/src/services/recovery/stranded-notice.ts` to accept typed
`WorkspaceProviderFailureSummary | PluginWorkspaceOperationFailureReason
| null` (resolving once and dropping unknown strings) and pass
`readWorkspaceProviderFailure(latestRun?.resultJson)` from
`server/src/services/recovery/service.ts` (minimal argument additions at
existing escalation call sites).
- **Regression and embedded-Postgres E2E tests**:
- Added tests to existing test suites
(`packages/adapters/hermes/src/gateway/server/execute.test.ts`,
`server/src/services/conversation-continuation.test.ts`,
`server/src/services/fresh-continuation-fallback.test.ts`,
`server/src/__tests__/workspace-provider-failure.test.ts`,
`server/src/__tests__/heartbeat-retry-scheduling.test.ts`,
`server/src/services/heartbeat/run-completion.test.ts`) without adding
new test files.

## Verification

- **Hermes adapter unit tests**: `pnpm --filter
@paperclipai/hermes-paperclip-adapter exec vitest run
src/gateway/server/execute.test.ts` — 122/122 passed.
- **Hermes adapter typecheck**: `pnpm --filter
@paperclipai/hermes-paperclip-adapter typecheck` — passed.
- **Server typecheck**: `pnpm --filter @paperclipai/server typecheck` —
passed (all 7 project layers).
- **Module boundaries**: `node scripts/check-module-boundaries.mjs` —
passed.
- **Server recovery, retry scheduling, `completeRun`, and
embedded-Postgres E2E suites**:
- `pnpm --filter @paperclipai/server exec vitest run --hookTimeout=60000
src/services/conversation-continuation.test.ts
src/__tests__/workspace-provider-failure.test.ts` — 11/11 passed.
- `pnpm --filter @paperclipai/server exec vitest run --hookTimeout=60000
src/services/fresh-continuation-fallback.test.ts -t
"binding_mismatch|workspaceProviderFailure"` — 3/3 passed.
- `pnpm --filter @paperclipai/server exec vitest run --hookTimeout=60000
src/services/heartbeat/run-completion.test.ts -t "hermes_gateway
shutdown"` — 1/1 passed.
- `pnpm --filter @paperclipai/server exec vitest run --hookTimeout=60000
src/__tests__/heartbeat-retry-scheduling.test.ts -t "hermes_gateway
429"` — 1/1 passed.
- **Test budget check**: `node scripts/check-test-budget.mjs --files
server/src/services/conversation-continuation.test.ts
server/src/services/fresh-continuation-fallback.test.ts
server/src/__tests__/workspace-provider-failure.test.ts
server/src/__tests__/heartbeat-retry-scheduling.test.ts
server/src/services/heartbeat/run-completion.test.ts` — passed.

## Risks

- Low risk; no database schema migrations or breaking API changes.
- `hermes_gateway` holds without a confirmed terminal gateway response
(such as unconfirmed client-side timeouts) intentionally fail closed
with `process_identity_missing` to prevent overlapping remote execution.
- Only `binding_mismatch` workspace provider failures trigger
`fresh_isolated_workspace` on automatic continuation; retryable and
non-binding non-retryable failures keep `writer_ended` so usable task
workspaces are not discarded.
- Stranded recovery notices render only Core-owned closed failure
messages and drop unrecognized values, preventing raw provider error
strings from reaching issue threads.

## Model Used

- Google Gemini (Antigravity agent with tool use and code execution)

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
2026-11-25 15:32:05 -06:00
Dotta 263c6f6c04 fix(tool-access): enforce connection installs across non-plugin transports (#22967)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Agents call external tools (remote MCP, OAuth REST apps, local
stdio, plugins) through Paperclip's tool-access policy, Effective Access
view, and tool gateway
> - Non-plugin connections installed only for Agent A could still be
called by Agent B because `tool-access-policy.ts` only checked
`tool_connection_installs` for `plugin` connections,
`governedByConnectionProfile` only checked the calling agent's own bound
profiles (allowing Agent B's default unscoped `tools:use` grant to
match), Effective Access did not filter by connection installs, and
reconnect/uninstall paths could drop agent scoping
> - This is a cross-agent security boundary bypass where an agent can
access another agent's private connection or mailbox
> - This pull request extracts one shared `connection-access-boundary`
helper and enforces connection install boundaries consistently across
policy decisions, Effective Access (`allowedTools` and profile summary
counts), install removal (`putConnectionInstalls`), generic approval
policies, and gallery reconnect/catalog sync while preserving legacy
shared connections and explicit policy/targeted-grant overrides
> - The benefit is airtight per-agent connection isolation across all
transports with policy/test, Effective Access, and the live tool gateway
in full agreement

## Linked Issues or Issue Description

- Fixes: #17166

## What Changed

- **`server/src/services/tool-access/connection-access-boundary.ts`**:
Extracted a single shared batched helper
(`readConnectionAccessBoundaries`, `connectionRequiresInstall`,
`hasAgentAccessConfiguredMarker`, `agentAccessConfiguredSql`,
`defaultConnectionProfileBindingTargets`) so policy evaluation,
Effective Access projection, and default binding helpers share one query
and predicate.
- **`server/src/services/tool-access-policy.ts`**:
- Keeps the pre-policy install gate for `plugin` connections unchanged.
- Enforces the shared connection install boundary for non-plugin
governed connections (any connection with `tool_connection_installs`
rows, `agentAccessConfigured` / `mcpAgentAccessConfigured` marker, or
unbound managed profiles): denies uninstalled agents with
`deny_connection_not_installed` before profile/trust allows and blocks
generic `require_approval` policies when `blockedByConnectionInstall` is
true (so pending approvals cannot execute after uninstall and cannot
fall through to lower-priority allow policies), while preserving
explicit `block`/`allow` policies and tool-targeted `tools:use` grants
(`scope: { connectionId }`, `{ allow: [...] }`, etc.) required by
delegated policy contracts.
- Rejects default unscoped `tools:use` (`scope: null`) whenever the
connection is governed by installs or managed connection profiles, and
suppresses `app_gallery_finish` / `connection_intent` approval and trust
rules for uninstalled agents.
- Preserves legacy company-wide / unscoped connections that have no
install rows, no `agentAccessConfigured` marker, and no unbound managed
profiles.
- **`server/src/services/tool-access/profiles/resolution.ts`**: Uses
`readConnectionAccessBoundaries` to filter Effective Access
`allowedTools` and passes `eligibleCatalog` to `buildProfileDetails` so
`profile.summary.allowedToolCount` agrees with `allowedTools` and `POST
/companies/:companyId/tools/policy/test`.
- **`server/src/services/tool-access/connections/installs.ts` &
`server/src/services/tool-access.ts`**:
- Persists `agentAccessConfigured: true` on all governed tool
connections when installs are saved via `putConnectionInstalls` or
`finishGalleryAppConnection` (alongside `mcpAgentAccessConfigured: true`
for `mcp_remote`), so removing the final install via
`putConnectionInstalls({ installs: [] })` closes access across
`mcp_remote`, `rest_api`, and `local_stdio`.
- Preserves `agentAccessConfigured` / `mcpAgentAccessConfigured` on
`connectGalleryApp` reconnect when the retained connection is not
`archived` (while allowing revival of an archived connection to restore
fresh defaults).
- **`server/src/services/tool-access/catalog/default-access.ts` &
`server/src/services/tool-access/oauth/catalog-completion.ts`**: Uses
`defaultConnectionProfileBindingTargets` and
`hasAgentAccessConfiguredMarker` so reconnecting or syncing catalog
tools preserves existing agent-scoped installs and zero-agent
restrictions without widening access to the whole company.
- **Tests (`server/src/__tests__/tool-access-policy-service.test.ts`,
`heartbeat-runtime-mcp-servers.test.ts`,
`tool-access-policy-index.test.ts`)**: Added RED-before-fix regression
tests and embedded-Postgres route/gateway E2E coverage across
`mcp_remote`, `rest_api`, and `local_stdio`, newly created Agent C,
stripped-marker zero-agent removal via `putConnectionInstalls({
installs: [] })`, generic `require_approval` + explicit
allow/targeted-grant precedence, reconnect preservation, Effective
Access profile summary counts, and legacy shared connections.

## Verification

- Verified RED-before-fix on base `2d06567795`: `pnpm --filter
@paperclipai/server exec vitest run
src/__tests__/tool-access-policy-service.test.ts -t "denies uninstalled
agents|aligns policy/test route"` failed 4/4 with uninstalled agents
receiving `allow_explicit_grant`.
- Verified GREEN-after-fix on `484ecb416a`:
  - `pnpm --filter @paperclipai/server typecheck` (PASS, all 7 layers)
- `node scripts/check-test-budget.mjs --files
server/src/__tests__/tool-access-policy-service.test.ts` (PASS)
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/tool-access-policy-service.test.ts
src/__tests__/connection-management-delegated-policy.integration.test.ts
src/__tests__/plugin-connector-install-gate.test.ts` (3 files, 100/100
tests PASS)
- Full Paperclip CI (`66/66` executed checks PASS) + Greptile **5/5**
(`0` unresolved review threads)

## Risks

- Low risk: legacy unscoped/company-wide connections with no
`tool_connection_installs` rows, no `agentAccessConfigured` /
`mcpAgentAccessConfigured` marker, and no unbound managed connection
profiles continue to evaluate unchanged.
- Explicit `block`/`allow` policies and tool-targeted `tools:use` grants
continue to take precedence over the non-plugin install gate (matching
`connection-management-delegated-policy.integration.test.ts`), while
default unscoped `tools:use` (`scope: null`), generic
`require_approval`, and profile/trust allows can no longer bypass
connection install boundaries.

## Model Used

- Google Gemini (Antigravity agentic workflow with tool use, code
execution, and embedded-Postgres 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
2026-11-25 15:32:01 -06:00
0774cb90cd feat(ui): open Needs You on All assignees and keep its filters between visits (#22964)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The Coordinator Inbox (Needs You, `/decisions`) shows the decisions
and problems that wait for a person
> - Its toolbar has agent, project, and assignee filters, plus a
grouping control
> - Today the page always opens on "Assigned to you", so a board member
who reviews work for the whole company must select "All assignees" again
on every visit
> - The page also forgets the agent, project, and grouping choices after
a reload or on a new visit
> - This pull request opens the page on "All assignees" for a person who
can see everyone's cards, and saves the toolbar choices in local storage
per company and person
> - The benefit is that Inbox opens on the company-wide queue by default
for board members and keeps each person's filters across visits with no
repeated clicks

## Linked Issues or Issue Description

Supersedes #21255 (rebased onto current `master` after InboxFilter
dropdown menus and Waiting/History Inbox folders landed). Related: Refs
#20959, Refs #22675, Refs #22846.

**What existing behavior does this improve?**
The Coordinator Inbox / Needs You page (`/decisions`) and the filters in
its toolbar.

**Current behavior**
- The page always opens on "Assigned to you". To see everyone's cards, a
board member must select "All assignees" on every visit.
- The agent, project, and grouping choices stay in memory only. A reload
or return visit resets them.

**Proposed behavior**
- A person who can see everyone's cards (a board member) opens Needs You
on "All assignees". A viewer still opens on "Assigned to you".
- The page saves the assignee, agent, project, and grouping choices for
each company and person in local storage, and restores them on reload or
return visits.
- A link that names a view (for example `?view=company`) still opens
that view without overwriting the saved choice.
- Switching to Waiting or visiting `?folder=waiting` directly loads the
Waiting feed immediately without waiting for board access and keeps
Waiting filters isolated from Needs You's saved filters.

**Reason and benefit**
Operators who review work across the whole company open Inbox many times
each day. Opening on "All assignees" by default and keeping filter
choices eliminates repeated clicks on every visit.

**Breaking changes**
None for the API or stored server data. The initial default view on
Needs You changes from "Assigned to you" to "All assignees" for board
members. See Risks.

## What Changed

- `ui/src/lib/coordinator-attention.ts`: Add
`openingCoordinatorAssignee`, `coordinatorAssigneeNeedsEveryone`,
`needsYouToolbarStorageKey`, `loadNeedsYouToolbar`,
`saveNeedsYouToolbar`, `DEFAULT_NEEDS_YOU_TOOLBAR`, and toolbar types.
Unreadable local storage fields fall back to their defaults one field at
a time.
- `ui/src/hooks/useAttentionViews.ts`: Add `useAttentionEveryoneAccess`
returning `{ everyone, settled }`, with `useAttentionEveryoneView`
delegating to it.
- `ui/src/components/InboxFilter.tsx`: Add optional `disabled` prop and
forward it to the trigger button so the assignee filter stays disabled
while board access is settling.
- `ui/src/components/coordinator/CoordinatorNeedsYou.tsx`:
- Open Needs You on the saved assignee when no `view` query parameter is
present, defaulting to "All assignees" for board members and "Assigned
to you" for viewers.
- Always write the selected assignee's view to the URL (including
`?view=mine`), and clear the `view` param on "Back to Needs You" from
Archived so the saved assignee applies again.
- Persist agent, project, assignee, and grouping changes by merging only
the changed field onto stored preferences. A `?decisionId=` link clears
filters only for that visit without erasing stored filters, and clears a
kept agent even before the agent list loads.
- Apply a kept agent filter only when the loaded agent list includes
that agent, and keep a saved project visible in the project menu even
when it has no open cards (preserving `inboxProjectOptions` for folded
provider-limit obligations).
- Delay the initial feed request until board access settles when the
opening view requires Everyone access, avoiding a flash of "Assigned to
you". Direct `?folder=waiting` visits bypass that wait and keep
Waiting's agent/project filters isolated from Needs You's saved filters.
- Read `viewCounts` from the active feed instead of calling
`useAttentionBadge` a second time.
- `ui/src/components/coordinator/CoordinatorNeedsYou.toolbar.test.tsx`
and `ui/src/lib/coordinator-attention.test.ts`: Add unit and jsdom
integration regression tests covering default opening views, sticky
filters, viewer fallback, board-access loading gate, missing/failed
agent list, empty saved project, decision links, Archived return, and
Waiting folder isolation.
- `tests/e2e/coordinator-inbox-views.spec.ts`: Update the local-board
desktop Inbox check to assert "All assignees" on open, verify assignee
and grouping persistence across navigation and reload, and confirm
wrapped toolbar alignment at 1024x720.
- `doc/PRODUCT.md`: Document the new default opening view and
per-person/per-company saved toolbar choices.

## Verification

- RED before fix (on base `2d065677959b585065ff3fec8718156a4cf6f41d`):
`cd ui && npx vitest run
src/components/coordinator/CoordinatorNeedsYou.toolbar.test.tsx` failed
(`11 failed | 1 passed (12)`), proving Needs You opened on `me` instead
of `all` and did not persist filters.
- GREEN after fix: `cd ui && npx vitest run
src/components/coordinator/CoordinatorNeedsYou.toolbar.test.tsx
src/lib/coordinator-attention.test.ts
src/hooks/useAttentionViews.test.tsx src/lib/attention-views.test.ts
src/lib/attention-obligations.test.ts
src/components/coordinator/InboxProviderLimit.test.tsx` -> **6 passed
(6), 49 passed (49)**.
- `pnpm --filter @paperclipai/ui typecheck` -> **PASS**.
- `pnpm check:token-gates` -> **All 4 gates CLEAN**.
- `node scripts/check-test-budget.mjs --files
ui/src/components/coordinator/CoordinatorNeedsYou.toolbar.test.tsx
ui/src/lib/coordinator-attention.test.ts` -> **PASS**.
- `pnpm verify --base 2d065677959b585065ff3fec8718156a4cf6f41d` -> exit
2 (broad input `tests/e2e/coordinator-inbox-views.spec.ts`); PR CI
supplies full coverage.
- Playwright E2E (`PAPERCLIP_E2E_PORT=3255 npx playwright test --config
tests/e2e/playwright.config.ts
tests/e2e/coordinator-inbox-views.spec.ts`) against freshly built
production UI in `local_trusted` mode -> **2 passed (desktop +
mobile)**, proving Needs You opens on "All assignees", persists assignee
and grouping across navigation and reload, and preserves 1024x720
wrapped toolbar alignment.

## Risks

- Behavioral shift: a board member's Needs You page now opens on "All
assignees" instead of "Assigned to you". The sidebar badge still counts
personal ("For you") items.
- Toolbar preferences are stored in browser local storage
(`paperclip:needs-you-toolbar:v1:<companyId>:<userId>`), so a different
browser or device starts from the default.
- While board access is still loading on an Everyone-requiring opening
view, the feed waits for board access before fetching and the assignee
menu stays disabled; if board access fails to load, the page falls back
safely to "Assigned to you".
- The classic (non-Coordinator) Decisions page is unchanged.

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

## Model Used

- Rebase, conflict resolution, InboxFilter/Waiting-folder integration,
E2E expansion, and verification: Gemini 3.1 Pro by Google DeepMind (in
Antigravity, with tool use, shell execution, Vitest, and Playwright).
- Original implementation in #21255: Claude Opus 5.5 (`claude-opus-5-5`)
by Anthropic.

## 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: lucktastic <13757243+lucktastic@users.noreply.github.com>
Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-25 15:31:54 -06:00
f237785766 fix(native): save and wake the unblock owner a blocked report names (#22962)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - An agent reports a blocked task with `paperclip_block` and names the
unblock owner in `blocker.owner` (`kind` and `name`).
> - The server dropped an agent owner's name, so current-track blocks
saved `owner: "board"` and task-wide blocks fell back to the reporting
agent or its self-blocker retry path.
> - The named agent never became the unblock owner and never received a
wake, so work waiting on another agent stopped until a person reassigned
the task by hand.
> - PR #21265 fixed agent resolution and wake dispatch, but it
conflicted with newer master changes (named human owners in #22438 and
self-blocker continuations in #22140), carried a stale runner-check
failure from before #21726, and left a Greptile P1 where
external-chat-bound tasks failed finalization with
`chat_binding_agent_locked`.
> - This pull request rebases #21265 cleanly onto master, preserves
#22438 human-owner routing and #22140 self-blocker continuations,
enforces the full assignment/authorization/chat-lock/invokability
eligibility contract (including `tasks:assign` with run `keyScope` and
external `authorizingUserId`), and falls back safely to board ownership
if eligibility changes race before commit.
> - The benefit is that a blocked task moves to the named agent owner
and wakes that owner without manual reassignment, while chat-bound,
unauthorized, and conversation tasks never fail finalization with
`chat_binding_agent_locked` or bypass assignment policy.

## Linked Issues or Issue Description

Refs #21265 (supersedes with clean rebase onto master, Greptile P1
`chat_binding_agent_locked` fix, `tasks:assign` authorization
enforcement, and compatibility with #22438 and #22140).
Related: #20969, #22140, #22438.

**What happened?**
When an agent reports `blocked` with `blocker.owner: { kind: "agent",
name: "Review Lead" }`, the server drops the owner name. Current-track
blocks save `unblockDescriptor.owner` as `"board"`, and task-wide blocks
treat the report as the reporting agent's own blocker (triggering
self-continuation or board handoff). The named agent is never saved as
the unblock owner and never receives a wake.

**What did you expect?**
The server resolves a named agent owner against non-terminated company
agents (exact ID, trimmed NFC case-folded full name, URL key, or
initials), saves that agent in `unblockDescriptor`, hands the task to
it, and wakes it so its run starts. A person owner keeps #22438
company-member routing (or `"board"` when unresolved). A self-owned
blocker keeps #22140 fresh-session continuation. Unknown, ambiguous,
unavailable, unassignable, unauthorized, interaction-denied, or
chat-locked agent handoffs fail at report time with a clear message so
the agent can correct the report.

**Steps to reproduce**
1. Create two agents in one company: a worker and a reviewer (for
example `"Eligible status corpus delegate"`).
2. Assign a task to the worker and report `blocked` with `blocker.owner:
{ kind: "agent", name: "ESCD" }` (initials) or the full name for
`current_track` or `task_wide` scope.
3. Finalize the run and inspect `issue.unblockDescriptor.owner`,
`issue.assigneeAgentId`, and `agent_wakeup_requests`. On `master`,
`current_track` saves `"board"` and `task_wide` schedules a self-retry
for the worker instead of waking the named agent.

## What Changed

- Add leaf `server/src/services/native-runtime/blocker-owner.ts` (zero
service imports) and `blocker-owner.test.ts`:
- `matchBlockerOwnerAgent` resolves an agent by exact ID, trimmed NFC
case-folded full name (supports non-ASCII names such as `王明`), URL key,
then initials without falling through an ambiguous tier.
- `resolveNativeBlockerOwner` queries non-terminated company agents
(supporting `lockSources` shared row locks).
- Add `server/src/services/native-runtime/blocker-owner-handoff.ts`:
- Centralizes `evaluateBlockerAgentHandoff` and `hasExternalChatBinding`
for report-time validation, run finalization, and under-lock commit
rechecks: conversation/external-chat lock (`chatConversations`), agent
invokability, assignability, interaction policy, and
`authorizationService(db).decide({ action: "tasks:assign", ... })` with
run `keyScope` (`nativeRunKeyScope`) and external `authorizingUserId`.
- Add `server/src/modules/external-agents/run-authorizer.ts` (exported
via `modules/external-agents/index.ts`):
- Owns external-agent execution-input payload parsing and pinned
authorizer lookup (`resolveExternalRunAuthorizingUser`), returning a
normalized `{ status: "none" | "authorized" | "unavailable" }` contract
to keep provider-specific parsing inside `modules/external-agents`.
- Update `server/src/services/native-runtime/evidence-classifier.ts`:
- Carry `ownerAgentId` on `NativeEvidenceAssessment["blocker"]` while
preserving `ownerUserId` from `nativeBlockerUserId` (#22438).
- Mark unresolved agent names `boardOwned: true` so they never silently
fall back to the reporting agent.
- Update `server/src/services/native-runtime/status-arbiter.ts` (995
lines):
- Preserve named agent owners via `resolveBlockerHandoff` across
`current_track`, `task_wide`, and `durable_dependency_blocker_bound`
(carrying `handoffAgentId` while preserving `effects: []` until
dependencies resolve).
- Skip #22140 self-blocker recovery (`agentBlockerRecoverable`) and
queued-request self-supersession when the blocker names a *different*
agent.
- Honor `blockerHandoffLocked` by falling back cleanly to `"board"`
without queueing an unwakeable agent wake; strip `handoffAgentId` in
`supersedeHandedOffDecision`.
- Update
`server/src/services/native-runtime/native-completion-feedback.ts`,
`native-run-finalizer.ts`, `status-decision-committer.ts`, and
`server/src/services/chat-control-recovery-stop.ts`:
- Reject invalid, unauthorized, or chat-locked agent handoffs at report
time; resolve and verify eligibility under lock at commit time with safe
fallback to `"board"`; dispatch the named owner wake on handoff.
- Add unit and embedded-Postgres integration tests in
`blocker-owner.test.ts`, `evidence-classifier.test.ts`,
`status-arbiter.test.ts`, and `native-status-arbiter-corpus.test.ts`
(covering initials/full-name `current_track` and `task_wide` handoff +
wake dispatch, human owner preservation,
unknown/chat-locked/dependency-gated/policy-denied/`skill_test`
`keyScope` cases).

## Verification

- **RED-before-fix on base `2d06567795`:**
- `cd server && npx vitest run
src/services/native-runtime/evidence-classifier.test.ts
src/services/native-runtime/status-arbiter.test.ts` → 4 failed | 34
passed (38).
- **Local checks on final implementation:**
  - `node scripts/check-module-boundaries.mjs` → PASS
- `node scripts/check-test-budget.mjs --base
2d065677959b585065ff3fec8718156a4cf6f41d` → PASS (`110 nightly suites
validated, 4 test file(s) checked`)
- `pnpm --filter @paperclipai/server typecheck` → PASS across all 7
layers
- `cd server && npx vitest run
src/services/native-runtime/blocker-owner.test.ts
src/services/native-runtime/evidence-classifier.test.ts
src/services/native-runtime/status-arbiter.test.ts` → 49/49 passed
- `cd server && npx vitest run --hookTimeout=120000
src/__tests__/native-status-arbiter-corpus.test.ts -t "saves the unblock
owner|rejects a blocker owner agent name|rejects handing off an
external-chat-bound task|hands off a dependency-gated blocker"` → 6/6
passed (plus full 291/291 corpus/blocker/chat suite & 39/39
`github-retry-and-recovery.integration.test.ts`)
- **CI on head `aafddae13b`:**
- **70/70** executed checks `SUCCESS` (0 failing, 0 pending, 6 skipped,
2 non-blocking neutral Paperclip Review), including `ci / verify`, `ci /
e2e` + all 16 E2E shards, all 20 General server shards + chat +
workspaces, all 9 Serialized server shards, Verify Paperclip Runner,
Runner support (1–4/4), Build, Typecheck + Release Registry, policy,
`Superagent Security Scan`, `Socket Security`, `Contributor trust`,
`commitperclip`, `Snyk`, and `Greptile Review`.
- **Greptile:** **5/5** (`The PR appears safe to merge, with the
previous module-ownership finding addressed and no new actionable issues
found.`), 0 unresolved Greptile threads.

## Risks

- Low risk: existing `owner: "board"`, `owner: "agent"` (self-owned
blockers with #22140 continuation), and `owner: { kind: "user", ... }`
(#22438 named human owners) paths keep their existing semantics when no
distinct agent is named.
- If a task becomes chat-bound, unassignable, or unauthorized between
report validation and run finalization, finalization degrades safely to
`owner: "board"` instead of failing the commit.
- No database migrations or schema changes are required.

## Model Used

Gemini 3.1 Pro (Antigravity)

## Checklist

- [x] I have tested my changes locally
- [x] I have checked for any regressions
- [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: lucktastic <13757243+lucktastic@users.noreply.github.com>
Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-25 15:31:46 -06:00
Dotta bff0f6dab5 fix(redaction): preserve SigV4 presigned upload URLs in tool results (#22959)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Tool results flow through `validateToolContent`,
`redactSensitiveText`, and `redactCommandText` before reaching the agent
> - `COMMAND_ENV_SECRET_ASSIGNMENT_RE` matched `X-Amz-Credential` and
`X-Amz-Security-Token` inside AWS SigV4 presigned URLs and consumed the
rest of the URL, wiping `X-Amz-Signature`
> - Agents received truncated upload URLs and could not execute signed
S3/R2 `PUT` uploads returned by MCP tools
> - This pull request extracts a focused SigV4 helper that temporarily
sets aside validated `X-Amz-Credential` and `X-Amz-Security-Token`
parameters inside complete HTTPS SigV4 presigned queries before command
redaction, while keeping request-identity hashing and approval
encryption sensitive for those URLs
> - The benefit is that agents receive usable short-lived presigned
upload links while percent-encoded or malformed secrets, other secret
parameters, secret-named assignments, incomplete queries, placeholder
collisions, and retried write idempotency keys remain safe

## Linked Issues or Issue Description

- Refs #14014

## What Changed

- Extracted `packages/adapter-utils/src/sigv4-presigned-url.ts` to
detect complete HTTPS SigV4 presigned queries
(`X-Amz-Algorithm=AWS4-HMAC-SHA256`, valid SigV4 `X-Amz-Credential`
scope, `X-Amz-Date`, numeric `X-Amz-Expires`, `X-Amz-SignedHeaders`, and
64-hex `X-Amz-Signature`), including single- and double-escaped `\u0026`
query separators and trailing markdown/prose delimiters.
- Validated raw and iteratively percent-decoded `X-Amz-Credential` and
`X-Amz-Security-Token` values against canonical decoded shapes and
shared standalone secret token patterns (`sk-`, `gh*_`, `github_pat_`,
Stripe `sk_`/`rk_` keys, JWTs), failing closed on malformed/deeply
nested percent-encoding and private-use placeholder collisions.
- Updated `packages/adapter-utils/src/command-redaction.ts` to delegate
SigV4 parameter protection to `protectSigV4PresignedUrlParameters` and
keep `collectDiagnosticEnvironmentSecrets` treating SigV4 presigned URLs
as private.
- Updated `server/src/services/tool-content-guards.ts`
(`containsSensitiveToolArguments`) to keep SigV4 presigned URLs
classified as sensitive for `toolRequestIdentityHash` (preserving HMAC
`side_effect:v2` idempotency keys across deploys) and
`signToolArguments` (keeping v2 A256GCM encryption at rest).
- Added unit and end-to-end tests in
`packages/adapter-utils/src/command-redaction.test.ts` and
`server/src/__tests__/tool-content-guards.test.ts` covering complete
SigV4 URLs, percent-encoded/double-encoded/malformed smuggled secrets,
sibling secret redaction, model-classifier parity, and HMAC
identity/approval encryption stability.

## Verification

- `pnpm vitest run packages/adapter-utils/src/command-redaction.test.ts
server/src/__tests__/tool-content-guards.test.ts
server/src/__tests__/redaction.test.ts
server/src/__tests__/remote-mcp-redaction.test.ts` — passed (`4` files,
`143` tests).
- `pnpm --filter @paperclipai/adapter-utils typecheck && pnpm --filter
@paperclipai/adapter-utils build && pnpm --filter @paperclipai/server
typecheck` — passed (all 7 server typecheck layers).
- `pnpm verify` — exited with code `2` because graph worker
`@paperclipai/server` hit `SIGKILL` under local memory pressure;
required CI covers the broad suite.
- Verified end-to-end via `validateToolContent`
(`server/src/services/tool-content-guards.ts`) with a realistic MCP
presigned upload response: complete S3 SigV4 URLs arrive intact while
sibling `apiKey`/`Authorization: Bearer` secrets and percent-encoded
smuggled secrets are redacted, and `toolRequestIdentityHash` /
`signToolArguments` remain HMAC-keyed and v2-encrypted.

## Risks

- Complete HTTPS SigV4 presigned URLs remain visible in tool results,
audit summaries, and transcripts until their short expiry window
(`X-Amz-Expires`). Incomplete SigV4 queries, non-SigV4 parameters,
secret-named assignments/CLI flags/JSON keys, percent-encoded/malformed
smuggled tokens, and placeholder collisions fail closed.

## Model Used

- Antigravity AI coding assistant (Google DeepMind agentic runtime,
extended reasoning with local tool execution and 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
2026-11-25 15:31:40 -06:00
7b446b4504 fix(recovery): report an unrunnable recovery continuation once instead of every sweep (#21288)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Execution recovery delivers a recorded continuation to the task's
agent through a sweep that runs about every 15 seconds.
> - The sweep keeps a continuation `pending` until a wake for it is
admitted. A skipped wake leaves it pending, and the next pass tries
again.
> - The workspace preflight refuses a wake for an isolated git-worktree
task that has no project and no reusable workspace
(`workspace_worktree_requires_project`). Each refusal blocks the task
again, writes an activity row and posts a system comment.
> - Thus one refused continuation produced a new "blocked before
dispatch" comment about every 15 seconds, without end. A person's chat
collected hundreds of them in a few hours.
> - This pull request closes the continuation that the preflight
refuses, in the same transaction as the refusal.
> - The benefit is that the task is reported once and then waits for a
person, instead of a tight retry loop that floods its thread.

## Linked Issues or Issue Description

Refs #21250 (merged; fixes one way to reach this state: admission
refused a fresh isolated continuation of a projectless task. This PR
bounds the loop for any continuation that the preflight refuses.)

**What happened?**
A conversation task had `executionWorkspaceSettings.mode =
isolated_workspace`, no project, and a bound adapter-managed workspace.
A run failed at bootstrap. The fresh-continuation fallback could not
prove that the old writer had stopped, so it chose
`fresh_isolated_workspace`, cleared the task's `executionWorkspaceId`,
and recorded a continuation with `continuationDelivery: "pending"`. The
recovery wake sets `forceFreshSession`, so the preflight found no prior
session workspace. With no project and no binding, the preflight refused
the wake as `workspace_worktree_requires_project`. The continuation
stayed `pending`, so `deliverReconciledExecutions` woke it again on
every pass. Each pass posted the same system comment and activity row
(about every 15 s, for hours).

**Expected behavior**
A continuation that cannot start is reported once. The task stays
blocked with one clear comment until a person changes its workspace
settings. The sweep does not retry it in a tight loop.

**Steps to reproduce**
1. Enable isolated workspaces. Give a task `mode: isolated_workspace`,
`git_worktree` strategy, no project and no execution workspace.
2. Record a resolved recovery action for it with `continuationDelivery:
"pending"` and a valid `executionReconciliation`.
3. Run `deliverReconciledExecutions` three times.
4. See three "blocked before dispatch" comments and three
`issue.workspace_preflight_blocked` rows. The continuation stays
`pending`.

## What Changed

- `server/src/services/heartbeat/queue.ts`: when the workspace preflight
refuses a validated execution-reconciliation wake
(`reconciledRecoveryActionId`), it now sets the action's
`continuationDelivery` to `invalidated` with
`continuationInvalidatedReason: "workspace_worktree_requires_project"`,
and settles its coalesced holds in the same transaction as the block,
the comment, and the activity row. The sweep only reads `pending`
continuations, so it stops. (`queue.ts` already exceeded 1,000 lines;
this adds 10 lines inside the existing preflight refusal transaction
rather than splitting the transactional refusal path.)
- `server/src/__tests__/issue-recovery-actions.test.ts`: new regression
`"reports a reconciled continuation with an unrunnable workspace once
instead of retrying every sweep"` verifying across 3
`deliverReconciledExecutions` sweeps that only 1 comment, 1
`issue.workspace_preflight_blocked` activity row, and 1 skipped wakeup
request are recorded, the task is blocked, the primary continuation is
`invalidated` with `workspace_worktree_requires_project`, and a
coalesced sibling hold is also settled to `invalidated`.

## Verification

- Red, on unfixed `origin/master` (`2d06567795`): `cd server && npx
vitest run src/__tests__/issue-recovery-actions.test.ts -t "unrunnable
workspace once"` failed with `AssertionError: expected [ …(3) ] to have
a length of 1 but got 3` (three sweeps, three duplicate comments).
- Green, on rebased head (`7b2c4cdbda`):
- `cd server && npx vitest run
src/__tests__/issue-recovery-actions.test.ts -t "unrunnable workspace
once"`: 1 passed (120 skipped).
- `cd server && npx vitest run
src/__tests__/issue-recovery-actions.test.ts
src/__tests__/completed-turn-cleanup-hold-settle.test.ts`: 2 files, 131
passed (121 + 10).
  - `pnpm --filter @paperclipai/server typecheck`: passed.
- `node scripts/check-test-budget.mjs --files
server/src/__tests__/issue-recovery-actions.test.ts`: passed (110
nightly suites validated, 1 test file checked).
- `pnpm verify --explain` selected 1,944/2,301 Vitest files because
`queue.ts` is a shared server hub; focused recovery suites passed
locally and PR CI supplies full typecheck, build, and sharded suite
coverage.

## Risks

- Low risk. The change only runs on the preflight's refusal path, and
only for a validated execution-reconciliation wake.
- After this change, the refused continuation does not run by itself
when a person later fixes the workspace settings. The person's next
message or Retry starts the task through normal admission. This is the
same contract as the existing `in_review` invalidation.
- No migration. No schema change. No new query on the normal admission
path.

## Model Used

- Original PR: Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used
through Claude Code with tool use.
- Rebase onto `master`, conflict resolution, strengthened regression
test, and verification: Claude Opus 4.6 (`claude-opus-4-6`), Anthropic,
used through Antigravity with tool use (shell, file edits, git/gh).

## 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: lucktastic <13757243+lucktastic@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 15:31:34 -06:00
marshallandDotta 68e92bcd5d fix(composio): return the sign-in link when adding a second account (#19408)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - A Composio gateway lets one person connect several accounts of the
same app, for example 3 Gmail accounts, through the Connectors "Add
account" action
> - `POST /api/tool-connections/{id}/composio/apps/{toolkit}/accounts`
with `{"action":"add"}` must return a hosted sign-in link for the new
account
> - When the app already has an active account, the call always fails
with "Composio did not return a sign-in link. Check the app in
Composio."
> - The add reply lists the app's existing accounts beside the new link.
The shared setup parser sees an active account, returns `connected`, and
drops the link
> - This pull request reads the new link directly for an add, after the
same provider-error check
> - The benefit is that people can add a second or third account to a
Composio app from Paperclip

## Linked Issues or Issue Description

**What happened?**
On a managed instance, a Composio gateway had Gmail and Google Calendar
connected for one Google account. "Add account" for a second account
returned HTTP 422 with "Composio did not return a sign-in link. Check
the app in Composio." The setup `start` action returns only
`{"status":"connected"}` for an app that has an account, so no Paperclip
path gave a link for another account.

**Expected behavior**
"Add account" returns a `connect.composio.dev/link/...` sign-in link for
a new account, also when the app already has an active account.

**Steps to reproduce**
1. Connect a Composio gateway and connect one Gmail account.
2. Call `POST /api/tool-connections/{id}/composio/apps/gmail/accounts`
with `{"action":"add"}`, or use "Add account" on the Connectors page.
3. The response is 422 "Composio did not return a sign-in link".

**Root cause**
`manageComposioAppAccount` used `composioAppSetupResult` for the add
reply. That function returns `{ status: "connected" }` as soon as any
entry for the toolkit has status `ACTIVE`, before it looks for a link.
The existing test fixture returned only `{ redirect_url }` for an add,
so it did not include the existing accounts that the live gateway
returns.

Related: #19380 (Connectors page CPU fix). That PR fixes the page that
holds the "Add account" button. This PR fixes the API call behind the
button.

## What Changed

- `server/src/services/composio-app-setup.ts`: add
`composioAddAccountLink(response)`. It runs the same provider-error
check as the other parsers, then returns the first trusted
`connect.composio.dev/link/` URL from the reply.
- `server/src/services/tool-access/catalog/aggregator-accounts.ts`: for
`action: "add"`, use `composioAddAccountLink` and return `{ status:
"authorization_required", authorizationUrl }`. Rename and remove do not
change.
- `server/src/__tests__/composio-add-account-link.test.ts`: new tests
for a reply with an active account plus a new link, a reply without a
trusted link, and a provider failure.

## Verification

- `cd server && npx vitest run
src/__tests__/composio-add-account-link.test.ts
src/__tests__/composio-app-setup.test.ts
src/__tests__/aggregator-app-discovery.test.ts`: all pass.
- Red before the fix: I changed the add reply in the `direct Composio
setup` fixture so it lists the toolkit's accounts beside the link, as
the live gateway does. On the unchanged service, "adds another account
without a task or an agent grant, even when an account is already
active" failed with `Error: Composio did not return a sign-in link.
Check the app in Composio.` With the fix, it passed. That fixture change
is not in this PR, to keep the diff small. The new unit test covers the
same reply shape.
- I did not get a live link from Composio with this change, because it
is not deployed. Before the fix, the live API call returned the 422
above.
- I could not run a full server `tsc` in my sandbox (out of memory). CI
runs it.

## Risks

- Low. Only the `add` action changes. It still rejects provider errors
first, and it accepts only trusted Composio hosted links
(`extractRemoteMcpPending`).
- An add reply that has no link still returns the same 422 as before.

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

## Model Used

- Anthropic Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with
tool use (shell, file editing, 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
- [x] I will address all Greptile and reviewer comments before
requesting merge

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

Co-authored-by: Dotta <bippadotta@protonmail.com>
2026-11-25 15:31:27 -06:00
d99721398d fix(tool-access): keep a personal OAuth URL draft that needs its user's sign-in (#20167)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Agents and people can connect a custom remote MCP server ("Connect
your own MCP server") through `POST
/api/companies/{companyId}/tools/apps/connect`
> - A draft that declares OAuth for one user (`authMode: "oauth"`,
`grantKind: "user"`) has no user grant until the OAuth callback
> - Its first health check stops at `user_authorization_required` before
any request reaches the server
> - The connect flow handles only `oauth_challenge` as "needs sign-in",
so it deletes the draft and returns a 422 with a `setupUrl` to the
deleted row
> - The person who opens that link finds a connection that does not
exist
> - This pull request keeps the draft and starts sign-in, and it removes
links to a deleted draft from the error
> - The benefit is that an agent can start a per-user OAuth connection
for its user, and the link it gets back opens a draft the user can sign
in to

## Linked Issues or Issue Description

**What happened?**
An agent called `POST /api/companies/{companyId}/tools/apps/connect` for
a per-user OAuth remote MCP server. The call returned 422
`user_authorization_required`. The body held a `draft` connection id and
a `setupUrl` / `reconnectUrl` of `/apps/<id>/permissions`. A later `GET
/api/tool-connections/<id>` returned 404, and the connection was not in
the company's connection list. The connect flow had deleted the draft
after it built the error.

Also: for a custom server draft with no `sourceTemplateKey`, the agent
sign-in hand-off from `start-authorization` is
`/<prefix>/apps/connect?resume=<id>` with no `source`. The connect route
sends a link without `source` to the Apps list, so the user does not see
the sign-in.

**Expected behavior**
The draft stays, sign-in starts, and the returned link opens a page
where the user can click **Connect as me**. If setup deletes its draft,
the error carries no link to that draft and says what to do next.

**Steps to reproduce**
1. As an agent with a responsible user, call `POST
/api/companies/{companyId}/tools/apps/connect` for a custom remote MCP
URL with `authMode: "oauth"` and `grantKind: "user"`.
2. See the 422 `user_authorization_required` with a `setupUrl`.
3. Call `GET /api/tool-connections/<connectionId>`. It returns 404.

**Paperclip version or commit**
Rebased onto `master` at `2d06567795`.

## What Changed

- `server/src/services/tool-access.ts`: on a fresh personal OAuth draft,
treat `user_authorization_required` from the first health check like
`oauth_challenge`. Keep the draft and start sign-in.
- `server/src/services/tool-access.ts`: when setup deletes its draft,
remove `setupUrl` / `reconnectUrl` for that draft from the 422. Add
`connectionRemoved: true` and a `nextStep` message.
- `server/src/services/tool-access/oauth/authorization-start.ts`: for a
draft with no app source, send the agent's hand-off to
`/<prefix>/apps/<id>/permissions`, not to `/apps/connect?resume=<id>`.
- `server/src/__tests__/generic-mcp-connection.test.ts`: 3 regression
tests covering draft preservation, stripped dead links on removed
drafts, and agent custom-server hand-off URLs.
-
`server/src/__tests__/connection-management-delegated-policy.integration.test.ts`:
update the custom-server hand-off assertion to expect
`/<prefix>/apps/<id>/permissions` (while asserting curated
`google-workspace` apps still hand off to
`/apps/connect?resume=<id>&source=google-workspace`), and add a
full-stack HTTP E2E integration test verifying an agent-started personal
OAuth draft stays alive (`200` on GET, `firstSignInPending: true`,
`canConnectAsCurrentUser: true`) until the addressed user signs in
through `start-authorization` and `/api/tools/oauth/callback`.

## Verification

- Red-before-fix on `master` (`2d06567795`): all 3 new regression tests
in `generic-mcp-connection.test.ts` fail (`422
user_authorization_required` instead of `201`, missing
`connectionRemoved: true` with dead `setupUrl`/`reconnectUrl` still
present).
- Green-after-fix locally:
  - `pnpm --filter @paperclipai/server typecheck`: passed (0 errors)
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/generic-mcp-connection.test.ts
src/__tests__/tool-access-cancelled-first-sign-in.integration.test.ts`:
121/121 passed
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/connection-management-delegated-policy.integration.test.ts
src/__tests__/tool-access-oauth-protocol.integration.test.ts`: 41/41
passed (including full-stack HTTP agent-to-human E2E sign-in test)
- `pnpm verify --base 2d06567795 --explain` selects 1947/2301 Vitest
files because `server/src/services/tool-access.ts` is broadly imported;
focused suites and typecheck passed locally and required CI supplies
broad sharded coverage.

## Risks

- Low risk. The new path applies only to a draft created in the same
connect call, with `authMode: "oauth"` and `grantKind: "user"`. Other
health-check errors still delete the draft as before.
- The 422 body for a deleted draft no longer has `setupUrl` /
`reconnectUrl`. A client that read those fields got a link to a deleted
row, so no working flow depends on them.
- Compatible with #22714 (`firstSignInPending`): an awaiting personal
draft is marked `firstSignInPending: true` in the Apps list while
remaining reachable via `GET /api/tool-connections/:id` and
`start-authorization` until the user signs in, after which
`firstSignInPending` clears and the connection becomes `active`.
- Not in scope: after a user signs in on a personal draft with no
installs, the defaults give access to all agents. That is a
sharing-default design question, not part of this fix.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), via Claude Code with tool use and
code execution (original PR commit).
- Rebase, delegated-policy test alignment, full-stack E2E integration
test, and local verification: Antigravity agent with shell, edit, and
test 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
- [ ] I have updated relevant documentation to reflect my changes (no
docs change needed)
- [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>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Dotta <bippadotta@protonmail.com>
2026-11-25 15:31:22 -06:00
9ee562fd27 fix(ui): fit the right side panel to its layout row so it is never clipped (#19864)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The web UI shows a resizable left sidebar, a center column, and a
resizable right side panel
> - On the chat page (and other layouts with a secondary sidebar), the
right side panel can go past the right edge of the window
> - Then the right part of the panel is cut off, and the close control
is not visible
> - Resizing the left sidebar or the panel does not bring it back
> - This pull request makes the panel fit the space that its layout row
actually has
> - The benefit is that the panel always stays inside the window, at all
sidebar and panel widths

## Linked Issues or Issue Description

No public issue exists. I searched open PRs and issues for overflow,
clipped, and right-panel problems and found no match.

**What happened?**
On the chat page, the right side panel went past the right edge of the
window (or crushed the center thread under the 280px conversation list).
At a 1280px window, with the left sidebar at 420px and a saved panel
width of 624px, the right panel overflowed the available space in its
layout row and clipped its right edge and close control. Dragging the
panel or the sidebar did not fix it.

**Expected behavior**
With any sidebar and panel width, the panel stays inside the window with
its close control visible, and the center column keeps a usable width.

**Steps to reproduce**
1. Open the chat page for an agent and open the right side panel.
2. Drag the left sidebar to its maximum width (420px).
3. Drag the right panel to its maximum width.
4. Look at the right edge of the window or shrink the viewport to 900px:
the panel overflows/clips.

**Paperclip version or commit**
Rebased onto `master` at `2d06567795`.

## What Changed

- Cause: `PropertiesPanel` clamped its width to `window.innerWidth -
656`, assuming a fixed 236px left sidebar and no secondary sidebar in
the row. The left sidebar can be up to 420px wide, and Agent Chat adds a
280px conversation list in the same row.
- `ui/src/components/PropertiesPanel.tsx`:
- `measureFittedPaneMax` measures the real space available for the
panel: `row.getBoundingClientRect().right -
main.getBoundingClientRect().left`. It preserves a 420px minimum center
column down to the 260px panel minimum, and when total remaining space
is below 260px, fits to that remaining space so the panel and its close
control never clip past the row's right edge.
- Displays `min(saved width, fitted width)` without overwriting the
saved width in `localStorage`, so when space returns the panel grows
back to the saved width.
- Observes both the layout row and `#main-content` with `ResizeObserver`
(plus window `resize`), so changes to the window, primary sidebar, or
collapsible secondary rails (such as Agent Chat's collapsible
conversation list) apply immediately.
- Uses the fitted display width for drag start, drag clamping, and
maximize restore glides, and keeps `widthRef` in sync during
`pointermove` so fast `pointerup` persists the clamped drag width.
- Falls back to window-based clamping when no `#main-content` exists in
the row (for example, in isolated stories).
  - Leaves the classic fixed 320px panel unchanged.
- `ui/src/components/PropertiesPanel.test.tsx`: focused regression suite
covering layout-row fitting, narrow `<260px` desktop clamping,
`#main-content` resize re-measurement when the row width is unchanged,
drag start/clamping/persistence, and fallback without `#main-content`.

## Verification

- RED before fix (on `2d06567795`): `pnpm --filter @paperclipai/ui exec
vitest run src/components/PropertiesPanel.test.tsx` -> 3 failed / 1
passed (`Expected "260px", Received "624px"` and `Expected "372px",
Received "624px"`).
- GREEN after fix (`66adf42c82`):
- `pnpm --filter @paperclipai/ui exec vitest run
src/components/PropertiesPanel.test.tsx` -> 4/4 passed.
  - `pnpm --filter @paperclipai/ui typecheck` -> passed.
  - `pnpm check:token-gates` -> all 4 gates clean.
- `node scripts/check-test-budget.mjs --files
ui/src/components/PropertiesPanel.test.tsx` -> PASS.
- Affected UI suite (217 files, 3,870 tests): 211 passed on initial
parallel run and the 6 CPU-contention timed-out suites passed 6/6
(103/103 tests) on focused rerun.
- Real-browser Chromium check against the built production UI
(`server/ui-dist`) with left sidebar at 420px and saved panel width
624px:
- Agent Chat 1280×800: `mainWidth=320`, `asideWidth=260`,
`asideRight=1280`, `closeRight=1272`, `scrollWidth=1280`, saved width
still `"624"`.
- Agent Chat 900×800: `asideWidth=200`, `asideRight=900`,
`closeRight=892`, `scrollWidth=900`.
- Agent Chat 1440×900: `mainWidth=420`, `asideWidth=320`,
`asideRight=1440`, `closeRight=1432`, `scrollWidth=1440`.
- Task Detail 1280×800: `mainWidth=420`, `asideWidth=440`,
`asideRight=1280`, `closeRight=1272`, `scrollWidth=1280`.
- Task Detail 900×800: `mainWidth=220`, `asideWidth=260`,
`asideRight=900`, `closeRight=892`, `scrollWidth=900`.

## Risks

- Low risk. The production change is confined to `PropertiesPanel.tsx`.
When the row has space, the panel width matches prior behavior.
- When space is constrained, the panel narrows to fit the layout row
rather than overflowing past the right edge of the window.
- Layout measurement relies on `#main-content` rendered by `Layout`;
when absent, the existing window-based clamp applies.

## Model Used

- Original PR: Claude Opus 5.5 (`claude-opus-5-5`).
- Rebase, `#main-content` ResizeObserver & drag-ref refinement, and
verification: Antigravity (Google DeepMind) with shell, Vitest, and
Playwright Chromium 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
- [ ] 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: Dotta <bippadotta@protonmail.com>
Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-25 15:31:15 -06:00
1916b4f18e fix(native): never post an earlier conversation turn's reply after a later turn started (#21803)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - People talk to agents in agent chats. Each message starts a native
run, a "turn", for the chat's agent
> - When a turn ends with a committed reply but no posted comment,
committed-reply recovery posts that reply later
> - Recovery treats an unposted turn as the current turn when the task
holds no execution run. A later turn holds that run only while it runs
> - So when a later turn fails at setup, or finishes, an earlier turn's
reply qualifies again. Recovery then posts it as a new message, days
late
> - This pull request makes recovery skip a turn when a later turn of
the same agent on the task has started
> - The benefit is that a person never sees an old reply as a new
message

## Linked Issues or Issue Description

No public issue exists. Bug description:

**What happened?**

On a hosted instance, old agent replies appeared in agent chats as new
comments, 2 to 8 days after their runs ended. In each case, a new run of
the same agent on the same task had just started or failed at setup.
Each posted comment had the old run as `createdByRunId`, and its
`presentationDecision` had `commentAction: create` and the reason code
`committed_task_response_recovered`. Some of the old replies had been
shown before by another run. Others had never been shown.

Cause: `recoverCommittedNativeChatResponseInScope` in
`native-run-finalizer.ts` and the pending-presentation query in
`native-response-presentation-query.ts` accept an unposted conversation
turn as current when `issues.executionRunId` is null or the run itself.
A later turn releases `executionRunId` when it fails at setup or
finishes. After that, every earlier unposted turn of the same
conversation generation passes the check again.

**Expected behavior**

Recovery posts a turn's reply only while that turn is still the latest
started turn of the conversation. An earlier turn's reply is never
posted after a later turn started.

**Steps to reproduce**

1. Commit a native conversation turn with a final reply and no posted
comment.
2. Insert a later run of the same agent for the same task. Give it
status `failed` (setup failure), `running`, or `succeeded`.
3. Set the task's `executionRunId` to null.
4. Call `recoverCommittedNativeChatResponse`. Before this change, it
returns `true` and posts the earlier reply.

**Paperclip version or commit**

Reproduced in tests on `master` at `cec8c2b3f4`.

Related: #18465 and #20204 added committed-reply recovery. This PR keeps
their behavior for the current turn.

## What Changed

- `native-run-finalizer.ts`: new `laterConversationTurnStarted`.
Committed-reply recovery treats a conversation turn as current only when
no later run of the same agent on the task has started. Three later runs
do not count: a `queued` wake that has not started, a discarded queued
message (`cancelled` with no `startedAt`), and a context compaction run
(it keeps the same session). One shared condition,
`laterConversationTurn`, is used by recovery and by the
pending-presentation query. The query compares the stored `createdAt`
values in SQL, because a JavaScript `Date` drops microseconds.
- `native-response-presentation-query.ts`: the pending-presentation
candidates query has the same `NOT EXISTS` condition. It uses the
existing `heartbeat_runs_company_ctx_issue_created_idx` index.
- `agent-chat-response-recovery.test.ts`: new tests for a later turn
that failed at setup, is running, or finished, with `yielded`, `done`,
and held (pending approval) turns. New tests show that the reply still
posts when the only later run is a queued wake, a discarded queued
message, or a context compaction run.

## Verification

- Red before the fix, green after: `never posts an earlier turn's reply
after a later turn of the conversation started (...)` in
`server/src/services/native-runtime/agent-chat-response-recovery.test.ts`.
  - Without the source change: 5 failed, 65 passed (70).
  - With the source change: 70 passed (70).
- Red before the review fix, green after: `still posts the reply when
the only later run is a discarded queued message` and `... is a context
compaction run`. On the first commit: 2 failed. Now: the file has 72
passed (72).
- `pnpm verify` returned exit 2 (an opaque setup dependency), so CI
supplies broad coverage.
- Focused related suites (`committed-chat-response-authority`,
`idle-native-finalization`, `chat-monitor-continuation`,
`presentation-ownership-read`, `native-blocked-reply-recovery`,
`native-response-publication-retry`, `paperclip-control-plane-port`,
`native-workspace-queued-wake-recovery`,
`native-run-finalizer-telemetry`): 340 passed (10 files, with the
recovery test file). After that run, a type-only change moved the shared
alias; the recovery test file passed again on the final revision (72
passed).
- `pnpm --filter @paperclipai/server typecheck`: passed on the first
commit. On the final revision, the local run was stopped by the shared
memory limit of this machine. CI typecheck covers the final revision.
- Not run locally: `chat-channels.integration.test.ts` (did not finish
in 25 minutes on this machine). CI runs it.
- Not run: a live chat on a hosted instance.

## Risks

- Low risk. The change only removes cases where recovery posts a reply.
The current turn still recovers its reply.
- A turn whose reply did not post before a later turn started now never
posts that reply by recovery. The later turn answers the conversation
instead.
- No migration and no API change.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use and code
execution in a Claude Code agent 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
- [ ] 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: lucktastic <13757243+lucktastic@users.noreply.github.com>
Co-authored-by: Paperclip <noreply@paperclip.ing>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: commitperclip[bot] <284812584+commitperclip[bot]@users.noreply.github.com>
2026-11-25 15:31:09 -06:00
DottaandPaperclip 320d7fe76d perf(docker): consume attested Runner image in merge-queue builds and promote on master (#22993)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The repository includes `.github/workflows/docker-merge-group.yml`
and `scripts/merge-group-image.mjs` to pre-build production images in
the GitHub merge queue so `.github/workflows/docker.yml` can promote
verified bytes on `master` instead of rebuilding from scratch
> - Currently, `docker.yml` skips merge-queue promotion whenever
`needs.runner_image.outputs.mode == 'published'`, and
`docker-merge-group.yml` builds the Runner inline on 4-core
`ubuntu-latest` while waiting up to 15 minutes during promotion lookup
> - With `RUNNER_IMAGE_CONSUME_ENABLED=true`, that meant enabling the
merge queue would never promote pre-built images on normal commits
> - This pull request wires read-only attested Runner image consumption
into `docker-merge-group.yml`, records and verifies `runnerInputsDigest`
in `scripts/merge-group-image.mjs`, routes canonical `amd64` merge-group
builds to `cloud-release-32`, parallelizes disk cleanup, caps promotion
wait to 3 minutes, and allows `docker.yml` to promote verified
merge-queue images when `runner_image` resolves to `published`
> - The benefit is enabling fast pre-merge image promotion for
merge-queue commits without weakening attestation, Runner-digest
matching, or credential isolation

## Linked Issues or Issue Description

**What existing behavior does this improve?**
Pre-merge Docker image building and promotion across
`.github/workflows/docker-merge-group.yml`,
`scripts/merge-group-image.mjs`, and `.github/workflows/docker.yml`.

**Subsystem affected**
Cross-cutting (multiple of the above)

**Current behavior**
`docker-merge-group.yml` builds the Runner inline on `ubuntu-latest`
with serial disk cleanup, and `docker.yml` disables merge-queue
promotion whenever `needs.runner_image.outputs.mode == 'published'`.
`scripts/merge-group-image.mjs` also waits up to 15 minutes for an
in-flight merge-group run.

**Proposed behavior**
`docker-merge-group.yml` resolves an already-published Runner image
(non-blocking lookup, read-only permissions, `gh attestation verify`),
runs `amd64` on `vars.CORE_PUBLICATION_RUNNER || 'cloud-release-32'`,
skips unnecessary disk cleanup / runs cleanup in parallel, and records
`runnerInputsDigest` in `record.json`. `docker.yml` attempts merge-queue
promotion regardless of whether `runner_image` resolved `published` or
`inline`, passing `RUNNER_INPUTS_DIGEST` to `merge-group-image.mjs
verify` so promotion only succeeds when the merge-group image used the
exact same Runner inputs digest. Promotion wait is capped at 3 minutes
so `docker.yml` falls back quickly to building from source if a
merge-group build is still running.

**Reason and benefit**
Makes merge-queue pre-built image promotion work with published Runner
images so queued commits can promote verified bytes to GHCR instead of
rebuilding after merge.

**Breaking changes**
None.

## What Changed

- Added a read-only `runner_image` resolution and attestation
verification job to `.github/workflows/docker-merge-group.yml`
(non-blocking lookup, `persist-credentials: false`, SHA-pinned actions,
no secrets or registry writes).
- Routed canonical `amd64` merge-group builds in
`docker-merge-group.yml` to `vars.CORE_PUBLICATION_RUNNER ||
'cloud-release-32'`, skipped lockfile refresh when using a published
Runner, parallelized `Free runner disk` with a `>= 50 GiB` skip, and
passed `build-contexts`, `build-args`, and `labels` into `Build image
archive`.
- Updated `scripts/merge-group-image.mjs` to record and verify
`runnerInputsDigest`, include `scripts/runner-image-resolve.mjs` in
`pipelineFiles`, and cap `findWaitMs` at 3 minutes.
- Updated `.github/workflows/docker.yml` to output `inputs_digest` from
`runner_image`, run `Find the merge-queue build of this commit` even
when `mode == 'published'`, and verify `--runner-inputs-digest` before
promoting.
- Updated `scripts/merge-group-image.test.mjs`,
`server/src/__tests__/docker-build-stamp.test.ts`, and
`server/src/__tests__/docker-runner-workflows.test.ts`.

## Verification

- `node --test scripts/merge-group-image.test.mjs
scripts/__tests__/docker-cache-export-policy.test.mjs
scripts/__tests__/release-verify-workflow.test.mjs
scripts/macos-runner-runtime-workflow.test.mjs` (all passed)
- Vitest: `server/src/__tests__/docker-build-stamp.test.ts` (18/18
passed), `server/src/__tests__/docker-runner-workflows.test.ts` (11/11
passed)

## Risks

- Low risk. Promotion remains strictly fail-closed: `docker.yml` runs
`$BEFORE:scripts/merge-group-image.mjs`, refuses promotion on any
pipeline file change, verifies commit SHA, tree SHA, architecture,
archive blob digests, and exact `runnerInputsDigest`, and falls back to
building from source on any mismatch or timeout.

## Model Used

- Gemini 3 Pro (Antigravity agent with tool use, shell execution, and
local test 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
- [ ] 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-25 15:22:50 -06:00
DottaandPaperclip 64bef50be0 feat(cloud): add Cloud starter inference proxy, migration modal, and PostHog A/B telemetry (#22966)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Hosted Cloud onboarding currently requires new users to connect a
model provider subscription or API key before their first agent can run
> - That upfront credential step creates drop-off before a new user sees
their first agent do real work
> - We need an opt-in, managed Cloud capability that runs the first
agent right away through a server-side proxy, keeps the raw provider key
out of sandboxes and browsers, prompts the user to connect their own
provider when starter inference runs out, and measures treatment vs.
control in PostHog
> - This pull request adds the default-off `enableCloudTrialInference`
managed feature, the server-side OpenRouter reverse proxy with ephemeral
per-run tokens, the blocking model-connection and agent-migration modal
with Storybook stories, and Cloud-only PostHog A/B cohort and funnel
telemetry
> - The benefit is zero-friction first-agent onboarding on Cloud stacks
enrolled in the experiment, with automatic migration to the user's own
model provider and clean A/B observability

## Linked Issues or Issue Description

**Subsystem affected**

Cross-cutting (`packages/shared`, `packages/paperclip-runner`,
`server/`, `ui/`)

**Problem or motivation**

New Cloud users must connect an AI subscription or API key before they
can run their first agent. We want to A/B test letting eligible Cloud
workspaces start their first agent right away with managed starter
inference (OpenCode / GPT-6 Luna in Paperclip Runner) without exposing
any raw upstream API key to the sandbox, database, or browser, and then
guide the user to connect their own model provider when starter
inference runs out.

**Proposed solution**

Add an experimental managed feature flag (`enableCloudTrialInference`,
off by default on both Cloud and self-hosted) that:

- Routes starter-inference runs through a server-side OpenRouter reverse
proxy (`/api/internal/cloud-inference/v1/*`) authenticated with
ephemeral per-run bearer tokens so the raw OpenRouter key never leaves
server memory.
- Enforces the configured starter model, detects upstream HTTP 402
exhaustion, invalidates active run tokens, reports exhaustion back to
the Cloud control plane, and broadcasts `cloud_trial.status.updated`
over live events.
- Displays a blocking modal (`CloudTrialExhaustedModal`) when starter
inference runs out while agents still depend on it, lets the user
connect their own model provider, automatically migrates trial agents to
that provider's default harness and model, clears incompatible provider
sessions, and resumes paused work.
- Stamps the `cloud-trial-inference` (`treatment` / `control`) cohort
onto Cloud-only server and browser PostHog telemetry and records
Cloud-only funnel events (`$feature_flag_called`, `cloud_trial.started`,
`cloud_trial.key_issued`, `cloud_trial.exhausted`,
`cloud_trial.modal_shown`, `cloud_trial.migrated`,
`cloud_trial.migration_failed`) without affecting self-hosted telemetry.

**Alternatives considered**

- Passing a capped OpenRouter API key directly into the agent sandbox
environment: rejected because a sandboxed agent or user could read and
reuse the raw key outside Paperclip.
- Showing starter dollar amounts or a usage progress bar in the UI:
rejected in favor of a simple prompt asking the user to connect a model
provider to continue.

**Roadmap alignment**

Supports hosted onboarding activation experiments while staying strictly
gated behind a default-off managed feature flag (`cloudDefault: false`,
`selfHostedDefault: false`) so self-hosted installs and unflagged Cloud
stacks see zero behavior change.

**Additional context**

Paired with the private Cloud control plane key-management service PR
that provisions per-stack capped OpenRouter child keys and enforces
single-trial caps across accounts.

## What Changed

- **Shared contracts & feature flag (`packages/shared`)**:
- Added `enableCloudTrialInference` (`tier: "managed"`, `cloudDefault:
false`, `selfHostedDefault: false`) to `feature-catalog.ts`,
`types/instance.ts`, and `validators/instance.ts`.
- Added `packages/shared/src/cloud-inference.ts` with trial status
types, migration schemas, provider-to-harness migration defaults, and
telemetry event validation.
- Added `cloud_trial.status.updated` to `LIVE_EVENT_TYPES`,
`cloudTrialInference` to `agentRuntimeConfigSchema`, and optional
`cloudTrialInferenceEnabled` to `browserAnalyticsConfigSchema`.
- **Paperclip Runner (`packages/paperclip-runner`)**:
- Updated OpenCode server driver (`opencode-server-driver.ts`) and
`configured-environment.ts` to accept `PAPERCLIP_OPENROUTER_PROXY_URL`
and `PAPERCLIP_OPENROUTER_PROXY_TOKEN`.
- Updated `provider-failure.ts` to classify HTTP 402 as quota exhaustion
and redact `sk-or-` key material.
- **Server proxy, migration, and onboarding (`server/`)**:
- Added `server/src/services/cloud-trial-inference.ts` and
`server/src/routes/cloud-inference.ts` for server-memory key custody,
ephemeral per-run proxy tokens, model guard, HTTP 402 exhaustion
handling, agent migration, blocked-run resume, and company-scoped
status/migrate/telemetry routes.
- Wired proxy mounting in `server/src/app.ts`, runtime env & cleanup in
`heartbeat.ts` / `execution-configuration.ts`, `cloud_trial_exhausted`
error code in `run-completion.ts`, and starter-agent seeding in
`onboarding-seed.ts`.
- **PostHog A/B telemetry (`server/`, `ui/`)**:
- Resolved `cloudTrialInferenceEnabled` from `PAPERCLIP_MANAGED_CONFIG`
in `cloud-posthog-config.ts` and `cloud-posthog-browser.ts`.
- Stamped `cloud_trial_inference_enabled` and
`$feature/cloud-trial-inference` on `workspace` groups,
`cloud.workspace_started`, direct server PostHog events, and browser
PostHog super-properties plus `$set_once.cloud_trial_inference_cohort`.
- Added Cloud-only direct PostHog helpers (`trackCloudPostHogEvent`,
`trackCloudTrialExposure`) in `server/src/telemetry.ts` and wired
exposure + lifecycle funnel events (no-op on self-hosted).
- **UI & Storybook (`ui/`)**:
- Added `ui/src/api/cloud-inference.ts`, `CloudTrialExhaustedModal.tsx`,
`CloudTrialGate.tsx`, and optional `hideCancel` / `hideProviderHeading`
props on `AiProviderSetup.tsx`.
- Wired `CloudTrialGate` into `Layout.tsx` / `Layout.production.tsx`,
live-event invalidation into `LiveUpdatesProvider.tsx`, starter
onboarding card into `OnboardingWizard.tsx`, and the experimental card
into `InstanceExperimentalSettings.tsx`.
- Added Storybook stories in
`ui/storybook/stories/onboarding/cloud-trial-exhausted-modal.stories.tsx`
covering single agent, multiple agents, migrating, migration succeeded,
and migration error states.

## Verification

- `pnpm --filter @paperclipai/shared build`: passed.
- `pnpm --filter @paperclipai/paperclip-runner build`: passed
(TypeScript, protocol manifest, Cargo release build, replay golden
parity).
- `pnpm --filter @paperclipai/ui typecheck` & `node
scripts/storybook-catalog.mjs --check`: passed (372 files, 3484
stories).
- `pnpm --filter @paperclipai/server exec tsc --noEmit`: passed.
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/cloud-trial-inference.test.ts
src/__tests__/cloud-posthog-config.test.ts
src/__tests__/cloud-posthog-browser.test.ts
src/__tests__/posthog-direct-event-shape.test.ts
src/__tests__/posthog-direct-telemetry.test.ts
src/__tests__/auth-routes.test.ts`: 6 files, 144/144 passed.
- `pnpm --filter @paperclipai/ui exec vitest run
src/lib/analytics/product-analytics.test.ts
src/lib/analytics/product-analytics-events.test.ts`: 2 files, 14/14
passed.
- Verified Storybook stories interactively in the embedded browser
(`ExhaustedSingleAgent`, `ExhaustedMultipleAgents`,
`MigrationSucceeded`) with passing `play()` interactions and zero
console errors, plus live end-to-end onboarding → exhaustion → blocking
modal → provider connect → agent migration flow against a mock
OpenRouter server.

## Risks

- **Default-off isolation**: `enableCloudTrialInference` defaults to
`false` everywhere, and Cloud stacks hide `instance.experimental.*`
controls by default, so existing self-hosted and unflagged Cloud stacks
have zero behavior change.
- **Key custody boundary**: Raw OpenRouter keys stay strictly in server
process memory; sandboxes only receive short-lived per-run proxy tokens
invalidated on run exit or exhaustion.
- **PostHog direct contract**: Existing self-hosted collector envelopes
remain unchanged; `posthog-direct-event-shape.test.ts` and
`product-analytics-events.test.ts` verify event shape and ownership
invariants.
- **CI coverage**: Broad workspace suites and E2E lanes were not run
locally and will run on PR CI.

## Model Used

- Google Gemini (Antigravity agentic assistant) with code editing,
terminal execution, browser verification, and test 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
- [ ] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-25 14:44:42 -06:00
DottaandPaperclip 9cfc80b340 perf(docker): skip redundant registry cache export and link deps layer (#22986)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The Docker publishing workflow (`.github/workflows/docker.yml`)
builds and pushes multi-arch production images from `Dockerfile` on
every `master` push and release tag
> - Profiling recent `master` builds showed two large overheads on every
normal commit: `exporting cache to registry` (`cache-to: ...,mode=max`)
took ~2m 42s *after* the image push had already finished, and `COPY
--chown=node:node --from=deps /app/node_modules /app/node_modules` took
~55s without `--link`
> - On ordinary application commits (server, UI, docs, tests), all
cross-commit cacheable layers (`base`, `tailscale-client`,
`runner-lockfile`, `deps`, and the weekly CLI-tools + entrypoint layers)
are already warm in `:buildcache-<arch>`; re-exporting the ~4 GB
per-commit `build` stage wastes ~2.5–3 minutes on every build
> - This pull request adds a fail-open cache-export policy
(`scripts/docker-cache-export-policy.mjs`), adds `--link` to the `deps`
`node_modules` copy in `Dockerfile`, and parallelizes `Free runner disk`
(with a `>= 50 GiB` skip) in `docker.yml`
> - The benefit is saving ~3.5 minutes on every normal `master` Docker
image build while preserving full `mode=max` cache refreshes whenever
any cacheable input changes, the weekly CLI-tools epoch rolls over, or
cache freshness cannot be verified

## Linked Issues or Issue Description

**What existing behavior does this improve?**
BuildKit cache export, `deps` layer linking, and runner disk cleanup in
`.github/workflows/docker.yml` and `Dockerfile`.

**Subsystem affected**
Cross-cutting (multiple of the above)

**Current behavior**
Every `docker.yml` build runs `cache-to:
type=registry,ref=...:buildcache-<arch>,mode=max`, which uploads the
per-commit `build` stage (~4 GB) for ~2m 42s after the production image
is already pushed. In `Dockerfile`, `COPY --chown=node:node --from=deps
/app/node_modules /app/node_modules` copies ~2.9 GB without `--link`
(~55s). On hosted runners, `Free runner disk` deletes nine tool
directories serially.

**Proposed behavior**
Before `Build and push by digest`,
`scripts/docker-cache-export-policy.mjs` checks whether this build is a
`master` push using a published Runner image whose `:buildcache-<arch>`
ref exists and whose cacheable inputs and weekly `CLI_TOOLS_CACHE_EPOCH`
have not changed since the most recent published `sha-<commit>` master
ancestor (within the last 10 commits). When unchanged, `cache_to` is
left empty (skipping the post-push cache export while keeping
`cache-from` active). Whenever any check fails or is inconclusive, it
fails open to `mode=max`. `Dockerfile` uses `COPY --link
--chown=node:node --from=deps /app/node_modules /app/node_modules`, and
`Free runner disk` skips when `/` already has `>= 50 GiB` free or
deletes directories in parallel.

**Reason and benefit**
Cuts ~3.5 minutes from the critical path of normal `master` image builds
without weakening cache freshness on lockfile, Dockerfile, patch,
entrypoint, inline-Runner, tag, manual, or weekly tool-epoch builds.

**Breaking changes**
None.

## What Changed

- Added `scripts/docker-cache-export-policy.mjs` with fail-open BuildKit
cache-export policy logic (checking event/ref, published Runner mode,
clean lockfile, remote cache existence, most recent published master
ancestor in the last 10 commits, cacheable path diff, and UTC ISO week
epoch).
- Wired `Compute BuildKit cache export policy` into
`.github/workflows/docker.yml` before `Build and push by digest`,
passing workflow values through `env:` and keeping `cache-from`
unconditional.
- Added `--link` to `COPY --link --chown=node:node --from=deps
/app/node_modules /app/node_modules` in `Dockerfile`.
- Parallelized `Free runner disk` in `.github/workflows/docker.yml` and
added a `>= 50 GiB` free-space fast-path skip.
- Added `scripts/__tests__/docker-cache-export-policy.test.mjs` (unit
tests for path matching, ISO week boundaries, every fail-open branch, a
Dockerfile audit asserting every pre-app context `COPY` is covered, and
workflow wiring checks).
- Updated `server/src/__tests__/docker-image-layer-reuse.test.ts` and
`scripts/__tests__/release-verify-workflow.test.mjs` to match the linked
copy and cache export policy wiring.

## Verification

- `node --test scripts/__tests__/docker-cache-export-policy.test.mjs
scripts/__tests__/release-verify-workflow.test.mjs
.github/scripts/tests/docker-pid1-prewarm.test.mjs
.github/scripts/tests/docker-canary-promotion.test.mjs
.github/scripts/tests/post-merge-runner-routing.test.mjs
.github/scripts/tests/cloud-readiness.test.mjs
scripts/docker-deps-postinstall.test.mjs
scripts/merge-group-image.test.mjs` (all passed)
- Vitest contract tests:
`server/src/__tests__/docker-build-stamp.test.ts` (18/18 passed),
`server/src/__tests__/docker-image-layer-reuse.test.ts` (2/2 passed),
`server/src/__tests__/runner-image-identity.test.ts` (passed)

## Risks

- Low risk. The cache-export policy is strictly fail-open: any
non-master push, inline Runner build, refreshed lockfile, missing remote
cache, missing ancestor in the last 10 commits, git/registry lookup
error, week rollover, or change to any pre-app Dockerfile input exports
`mode=max` as before. A Dockerfile contract test prevents new pre-app
`COPY` inputs from drifting out of `CACHEABLE_INPUT_EXACT_PATHS`.

## Model Used

- Gemini 3 Pro (Antigravity agent with tool use, shell execution, and
local test 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
- [ ] 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-25 14:35:18 -06:00
DottaandClaude Opus 5.5 304854ee99 fix(antigravity): resolve the hosted runtime in one place and report sign-in failures plainly (#22990)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Google Antigravity agents can sign in with a Google subscription. On
hosted public deployments the server starts the pinned Antigravity
runtime and relays the pasted loopback redirect (#22932).
> - The server looked for that runtime only in the server package's
vendored assets and the OS-account cache. The Docker image keeps the
verified closure in the build-owned provider pack
(`PAPERCLIP_RUNNER_REMOTE_PROVIDER_PACK_PATH`).
> - So every hosted attempt failed before the runtime started, and the
page showed "Google sign-in did not complete. Start sign-in again." with
no sign-in link. Every failure reason became that one message, and
nothing was logged.
> - #22983 added the pack lookup as an option that each caller had to
pass. That leaves several search paths that can drift: installation
verification still used none.
> - This pull request moves the pack lookup into the one canonical
resolver, gives sign-in failures a typed reason with one plain-language
message each, and logs a secret-free reason code.
> - The benefit is that sign-in, model discovery and installation
verification always find the same verified runtime, and a server without
the runtime says why.

## Linked Issues or Issue Description

Refs #22932, Refs #22983

**Describe the bug**
On a hosted authenticated public deployment, the user chooses Google
Antigravity and then "Google Subscription". The page immediately shows
"Google sign-in did not complete. Start sign-in again." `POST
.../ai-connections/local/attempts` returns 201, and every `POST
.../ai-connections/local/check` returns `sign_in_required` with the same
message and no `authorizationUrl`.

**Steps to reproduce**
1. Run the standard image as an authenticated public deployment. Do not
create an Antigravity runtime cache in the server account.
2. Create an agent with Google Antigravity and choose Google
Subscription.
3. See the error before any sign-in step runs.

**Expected behavior**
The server starts the pinned runtime from the image's provider pack and
shows the Google sign-in link. If the server has no runtime, the message
says so in plain language and does not tell the user to start again.

**Root cause**
`antigravityNativeDistributionSpec()` resolved
`<server>/dist/vendor/paperclip-runner/provider-assets/antigravity/<target>`
and then `$HOME/.paperclip/runtimes/antigravity/<target>/<closure>`. The
image ships the closure at
`$PAPERCLIP_RUNNER_REMOTE_PROVIDER_PACK_PATH/provider-assets/antigravity/linux-x64`.
`startAntigravityBrowserLogin` caught every failure with a bare `catch`
and showed the generic message. The #22932 tests mocked both the runtime
resolution and the installation check.

## What Changed

- Runner: `antigravityNativeDistributionSpec` is the one resolver for
every caller. The search order is: the runner package's own assets
(runnerd binds Runner children to the selected pack with
`PAPERCLIP_ACPX_PROVIDER_PACKAGE_ROOT`), then the deployment provider
pack from `PAPERCLIP_RUNNER_REMOTE_PROVIDER_PACK_PATH`, then the
OS-account cache. The pack root must be a normalized absolute path. The
pack goes through the manifest and link checks of
`resolveRunnerProviderAssetsRoot` from #22983. The pinned closure digest
check is unchanged.
- Runner: the `providerPackageRoot` option on
`startAntigravityBrowserLogin`, `discoverAntigravityModels` and
`antigravityNativeDistributionSpec` is removed. The server no longer
reads the pack path.
- Runner: sign-in failures have a typed reason (`runtime_unavailable`,
`start_failed`, `login_incomplete`, `aborted`). One table maps each
reason to its message. A missing runtime reports "This server does not
have the current Google Antigravity runtime, so Google sign-in cannot
start. Use a Google API key instead, or update Paperclip on this
server."
- Runner: model discovery throws `AntigravityRuntimeUnavailableError`
when the runtime is missing. The server shows a plain-language message
for it instead of "Could not load models for this Google account".
- Server: sign-in failures, except cancelled attempts, are logged with a
secret-free code such as `ANTIGRAVITY_SIGN_IN_RUNTIME_UNAVAILABLE`. A
missing runtime during model discovery is logged as
`ANTIGRAVITY_RUNTIME_UNAVAILABLE`.

## Verification

- Red on master, green on this branch:
- `antigravity-installation.test.ts`: pack resolution, precedence, cache
fallback, link and path refusal, and one test that binds sign-in, model
discovery and `verifyAntigravityInstallation` to the same pack with no
vendored assets.
- `antigravity-auth.test.ts`: one test for each failure reason and its
message.
- `antigravity-models.test.ts`: a missing runtime gives
`AntigravityRuntimeUnavailableError` without a launch.
- `pnpm --filter @paperclipai/paperclip-runner exec vitest run` on the
antigravity auth, stream-order, installation, models and
provider-assets-root suites: 76 of 76 pass.
- `server/src/__tests__/local-ai-browser-login-google.test.ts`,
`antigravity-connection-models.test.ts` and
`antigravity-local-ai-login.test.ts`: 33 of 33 pass.
- The runner `tsc --noEmit` and the server `tsc --noEmit` pass.
- `node tests/runner-e2e/source-sdk-public-inputs.mjs <HEAD> --check`
reports no registry change.
- `pnpm verify` returned exit 2 (runner test files are outside the
resolved test graphs). Required CI supplies the broad coverage.
- Not run: a live Google sign-in against the real closure in a hosted
image. That needs a deploy and a real Google account.

## Risks

- Low risk. The pack is used only when the packaged assets are absent
and the pack contains the target. A modified pack still fails the pinned
closure check.
- A pack root that is relative or contains `..` now fails as "runtime
unavailable" instead of being ignored silently.
- Error text changes only for failures before the runtime initializes.

> 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-25 14:30:43 -06:00
DottaandPaperclip cb39f99a39 perf(ci): parallelize Runner image checks and shrink smoke build context (#22987)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The Runner image workflow (`.github/workflows/runner-image.yml`)
builds and verifies `ghcr.io/paperclipai/paperclip-runner` for `amd64`
and `arm64` whenever Runner inputs change
> - Profiling a recent `master` run showed `Build and check (amd64)`
taking 12m 30s versus 5m 03s on `arm64`, with ~2m 25s spent serially
deleting directories in `Free runner disk`, 36s serially unpacking
`full` and `slim`, 35s serially verifying layout/pack integrity for
`full` and `slim`, and extra BuildKit transfer time streaming the entire
~1.5 GB `slim` directory to `Dockerfile.smoke` even though it only reads
`/paperclip-runnerd`
> - Because `docker.yml` waits for the published Runner image when
Runner inputs change, slow `amd64` Runner image steps sit directly on
the release critical path
> - This pull request parallelizes `Free runner disk` (with a `>= 50
GiB` skip), parallelizes `full`/`slim` unpacking and layout checks, and
stages a minimal single-file `smoke-context` containing only
`/paperclip-runnerd` for the smoke matrix build
> - The benefit is saving ~2.5 minutes on `Build and check (amd64)`
without changing any built image bytes, security boundaries, or
verification checks

## Linked Issues or Issue Description

**What existing behavior does this improve?**
Non-build overhead in the `build` job (`Build and check (amd64/arm64)`)
of `.github/workflows/runner-image.yml`.

**Subsystem affected**
Cross-cutting (multiple of the above)

**Current behavior**
In `.github/workflows/runner-image.yml`, `Free runner disk` deletes nine
large tool directories sequentially (~2m 25s on `ubuntu-latest`),
`Unpack both images` and `Check the layout contract and pack integrity`
process `full` and `slim` sequentially (~71s combined), and `Run the
daemon on every consumer base image` passes the entire ~1.5 GB
`$RUNNER_TEMP/runner-image/slim` directory as `--build-context
runner-artifacts=...` even though `Dockerfile.smoke` only copies
`/paperclip-runnerd`.

**Proposed behavior**
`Free runner disk` skips cleanup when `/` already has `>= 50 GiB`
available and otherwise runs cleanup operations concurrently. `Unpack
both images` and `Check the layout contract and pack integrity` run
`full` and `slim` concurrently while collecting exit statuses from both
processes so any failure still fails the step. `Run the daemon on every
consumer base image` copies only `/paperclip-runnerd` into
`$RUNNER_TEMP/runner-image/smoke-context` and passes that minimal
directory as `--build-context runner-artifacts=...`.

**Reason and benefit**
Cuts ~2.5 minutes off `Build and check (amd64)` while keeping every
security invariant, artifact layout check, pack integrity check, and
five-base-image daemon smoke check identical.

**Breaking changes**
None.

## What Changed

- Parallelized `Free runner disk` in
`.github/workflows/runner-image.yml` and added a `>= 50 GiB` free-space
fast-path skip.
- Parallelized `full` and `slim` inside `Unpack both images` and `Check
the layout contract and pack integrity`, preserving strict failure
propagation across both background PIDs.
- Staged a minimal single-file `$RUNNER_TEMP/runner-image/smoke-context`
containing only `/paperclip-runnerd` for `Run the daemon on every
consumer base image` instead of streaming the full ~1.5 GB `slim` tree
to BuildKit.
- Extended `server/src/__tests__/runner-image-workflow.test.ts` to pin
the minimal smoke context staging alongside the existing
`Dockerfile.smoke` copy assertion.

## Verification

- Vitest workflow security and contract suite:
`server/src/__tests__/runner-image-workflow.test.ts` (16/16 passed)
- Workflow run on this PR exercises `Runner image` (`Build and check
(amd64)` and `(arm64)`) end-to-end because
`.github/workflows/runner-image.yml` is in the PR path filter.

## Risks

- Low risk. `full` and `slim` unpack into disjoint directories and
`runner-image-layout.mjs check` creates isolated temporary directories
via `mkdtempSync`. `Dockerfile.smoke` is already pinned by
`runner-image-workflow.test.ts` to only `COPY --from=runner-artifacts
/paperclip-runnerd /usr/local/bin/paperclip-runnerd`. No job
permissions, credentials, actions, or published image bytes change.

## Model Used

- Gemini 3 Pro (Antigravity agent with tool use, shell execution, and
local test 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
- [ ] 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-25 14:21:48 -06:00
DottaandPaperclip 362bdc1117 fix(antigravity): resolve hosted login and model discovery from configured provider pack (#22983)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Paperclip supports Google Antigravity through Paperclip Runner,
including server-hosted Google sign-in and account-bound model
discovery.
> - In Docker and hosted deployments, the server ships Antigravity's
verified Linux runtime closure inside the build-owned provider pack at
`PAPERCLIP_RUNNER_REMOTE_PROVIDER_PACK_PATH`, not under
`server/dist/vendor/paperclip-runner/`.
> - Because `startAntigravityBrowserLogin` and
`discoverAntigravityModels` only checked `import.meta.url` and
`PAPERCLIP_ACPX_PROVIDER_PACKAGE_ROOT`, hosted Google sign-in and
subscription model discovery failed immediately on container
deployments.
> - This pull request adds an explicit `providerPackageRoot` option to
the Runner asset-root and Antigravity helpers and forwards the
normalized `PAPERCLIP_RUNNER_REMOTE_PROVIDER_PACK_PATH` from the server
without mutating `process.env`.
> - The benefit is that hosted Google Antigravity sign-in and model
discovery resolve the verified build-owned closure cleanly on Docker and
Cloud deployments while keeping all manifest, symlink, and
closure-integrity checks intact.

## Linked Issues or Issue Description

Refs #22932

**What happened?**
On a Docker/hosted server where `hostedGoogleAiLoginSupported` is `true`
and
`PAPERCLIP_RUNNER_REMOTE_PROVIDER_PACK_PATH=/opt/paperclip-runner/provider-pack`,
starting Google Subscription sign-in returned `HTTP 201` on `POST
/ai-connections/local/attempts` and then immediately failed on
`/ai-connections/local/check` with `Google sign-in did not complete.
Start sign-in again.` and no OAuth URL. `discoverAntigravityModels` hit
the same missing asset lookup in container deployments.

**Expected behavior**
Hosted Google Antigravity sign-in and account-bound model discovery
resolve the verified `provider-assets/antigravity/linux-x64` closure
from the server's configured
`PAPERCLIP_RUNNER_REMOTE_PROVIDER_PACK_PATH` provider pack, return the
PKCE loopback authorization URL for hosted redirect relay, and load the
account's model catalog.

**Steps to reproduce**
1. Run the Paperclip Docker image (`node server/dist-runtime/index.mjs`)
with
`PAPERCLIP_RUNNER_REMOTE_PROVIDER_PACK_PATH=/opt/paperclip-runner/provider-pack`.
2. Open the Google Antigravity and Gemini connector and start a `Google
Subscription` sign-in attempt.
3. Observe `/ai-connections/local/check` immediately returning `Google
sign-in did not complete. Start sign-in again.` without an authorization
URL.

**Paperclip version or commit**
`1fca3a6d8c5a2be455f1240e96ff8d12387ad688` (on `master`)

**Deployment mode**
Docker

## What Changed

- Added an optional `RunnerProviderAssetsRootOptions` (`{
providerPackageRoot?, providerPackageManifest? }`) parameter to
`resolveRunnerProviderAssetsRoot` in
`packages/paperclip-runner/src/drivers/acpx/provider-assets-root.ts` so
callers can pass an explicit package root without mutating
`process.env`, reusing the same manifest, symlink, containment, and
TOCTOU verification checks and failing closed on invalid roots.
- Threaded optional `{ providerPackageRoot }` through
`antigravityNativeDistributionSpec`, `startAntigravityBrowserLogin`, and
`discoverAntigravityModels`.
- Updated `server/src/services/local-ai-browser-login.ts` and
`server/src/services/antigravity-connection-models.ts` to normalize
`PAPERCLIP_RUNNER_REMOTE_PROVIDER_PACK_PATH` (stripping trailing slashes
and rejecting non-normalized or relative paths) and pass `{
providerPackageRoot }` when configured.
- Added unit tests covering explicit `providerPackageRoot` resolution
for bundled server paths, fail-closed validation on invalid roots, and
server forwarding in `provider-assets-root.test.ts`,
`antigravity-connection-models.test.ts`, and
`local-ai-browser-login-google.test.ts`.

## Verification

- `pnpm --filter @paperclipai/paperclip-runner build:typescript` —
passed.
- `pnpm --filter @paperclipai/server typecheck` — passed.
- `pnpm --filter @paperclipai/paperclip-runner exec vitest run
src/drivers/acpx/provider-assets-root.test.ts
src/drivers/acpx/antigravity-auth.test.ts
src/drivers/acpx/antigravity-models.test.ts` — passed (52/52 tests
across 3 files).
- `pnpm exec vitest run
server/src/__tests__/antigravity-connection-models.test.ts
server/src/services/local-ai-browser-login-google.test.ts
server/src/__tests__/antigravity-local-ai-login.test.ts` — passed (31/31
tests across 3 files).
- `node --test
packages/paperclip-runner/scripts/contracts/contract-fingerprints.test.mjs`
— passed (11/11 tests).

## Risks

- Low risk. When `PAPERCLIP_RUNNER_REMOTE_PROVIDER_PACK_PATH` is unset
(ordinary local development), all call sites keep their existing
single-argument behavior. When set, the path must be normalized and
absolute and still passes `resolveRunnerProviderAssetsRoot`'s full
`package.json` and symlink-containment checks plus
`verifyNativeAcpxInstallation`'s pinned SHA-256 closure verification. No
contract fingerprints or database schemas change.

## Model Used

- Google Gemini (Antigravity agent with tool use and code execution)

## Checklist

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

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Pull request CI runs Vitest suites across five lanes: Runner native
server, general chat, general server, serialized server, and Runner
package tests.
> - Even after pre-baked AMIs and 8-vCPU runners, single-shard `vitest
native server`, 2-shard `general-chat`, and several oversized
single-file Vitest specs still exceed the 85s per-shard ceiling and
dominate pull request wall-clock time.
> - Splitting those oversized test files and expanding AWS sharding
where needed lowers the slowest Vitest shard under the sub-3-minute pull
request budget while preserving every test case and keeping
`ubuntu-latest` fallback fan-out compact.
> - This pull request shards `vitest native server` (`1 -> 2` on AWS,
`1` on hosted runners) and `general-chat` (`2 -> 3` on AWS, `1` on
hosted runners), splits the remaining `>85s` single-file Vitest tails
across all five lanes into focused `<1,000 LOC` sibling test files with
shared harnesses, and refreshes the four Vitest timing manifests.
> - The benefit is faster pull request feedback with lower tail variance
across every Vitest lane and zero deleted tests.

## Linked Issues or Issue Description

Refs #22916

**What existing behavior does this improve?**
Pull request Vitest shard wall-clock time across `vitest native server`,
`general-chat`, `general server`, `serialized server`, and `Runner
vitest package`.

**Current behavior**
Single-shard `vitest native server`, 2-shard `general-chat`, and several
monolithic test files still run above 85s on 8-vCPU AWS PR runners,
holding back pull request CI completion.

**Proposed behavior**
Expand AWS sharding for `vitest native server` (`1 -> 2` with
`release_crate: true` on both, `1` compacted shard on `ubuntu-latest`)
and `general-chat` (`2 -> 3` on AWS, `1` on `ubuntu-latest`), split the
remaining oversized single-file Vitest suites into focused sibling files
under 1,000 LOC with shared test harnesses, and refresh the four Vitest
shard duration manifests so LPT packing balances the split files
immediately.

**Reason and benefit**
Cuts Vitest critical-path wall clock under 95s per shard while
preserving 100% of test coverage, lane ownership boundaries, and compact
33-job `ubuntu-latest` fallback fan-out.

**Breaking changes**
None. Pure test-file refactoring and shard matrix configuration.

## What Changed

- Expanded AWS sharding in `.github/ci-task-matrix.json`,
`.github/workflows/pr-trusted.yml`, and `scripts/run-vitest-stable.mjs`:
- `Verify Paperclip Runner (vitest native server)`: `1 -> 2` shards on
AWS (`release_crate: true` on both), `1` shard on `ubuntu-latest` via
`HOSTED_SHARD_COUNTS["ci:runner-vitest"] = 1` and
`nativeServerLanePattern`.
- `General tests (chat)`: `2 -> 3` shards on AWS, `1` shard on
`ubuntu-latest`.
- Split the remaining `>85s` single-file Vitest tails across all five
lanes into focused `<1,000 LOC` sibling test files with shared harnesses
(zero deleted tests, zero cross-test-file imports, anchor filenames and
lane ownership preserved):
- Runner package lane (`packages/paperclip-runner`): split oversized
daemon/provider integration files.
- Native server lane: split `native-ingress-bootstrap-retry` while
keeping `native-ingress-bootstrap-retry-opencode` strictly in
`native-runner`.
- Chat lane: split oversized Telegram/GitHub/connection-management
integration tests.
- General server lane: split `tool-gateway-service.test.ts` and
`attention-service` tests using shared harnesses.
- Serialized server lane: split `heartbeat-dependency-scheduling` /
`native-wakes` and `agent-adapter-validation` tests, keeping serialized
ownership intact.
- Refreshed all four Vitest shard duration manifests
(`packages/paperclip-runner/scripts/vitest-lane-durations.json`,
`scripts/chat-shard-durations.json`,
`scripts/general-server-shard-durations.json`,
`scripts/serialized-shard-durations.json`) and updated CI contract
tests.

## Verification

- Ran all CI contract suites after rebasing onto `origin/master`:
- `node --test .github/scripts/tests/ci-plan.test.mjs
scripts/ci/runner-release-crate-cache.test.mjs
scripts/ci/run-vitest-stable-shard.test.mjs
scripts/ci/run-vitest-stable-pr-mode.test.mjs
scripts/ci/runner-vitest-package-lanes.test.mjs
scripts/ci/test-selection-pr-timings.test.mjs
scripts/ci/e2e-shard.test.mjs scripts/ci/check-test-budget.test.mjs`
  - `node scripts/check-test-budget.mjs`
  - `node scripts/check-maps.mjs`
- Verified every new test file is under 1,000 LOC, zero cross-test-file
imports exist, zero files are missing from the four timing manifests,
and `ubuntu-latest` remains strictly at 33 jobs.

## Risks

- Low risk: pure test-file refactoring and shard matrix expansion with
zero production code changes.
- Reverted cleanly by a single `git revert` if any shard balance or
manifest adjustment is needed.

## Model Used

- Google Gemini (Antigravity / Gemini 4 Neon (High), tool use and code
execution 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
2026-11-25 13:52:16 -06:00
Dotta 7563842165 perf(ci): cut E2E ceiling under 95s via 16 AWS shards, 8-core speedup, top serial splits, and parallel UI build (#22960)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Live 8-core PR runs (`45668834558`, `45667106472`) showed
`e2e_shards` was the #1 critical-path bottleneck on normal PRs
(`152–171s` test step) due to four compounding causes:
> 1. `scripts/e2e-shard.mjs` still used the 4-vCPU
`EFFECTIVE_PARALLEL_SPEEDUP = 1.85` even on 8-vCPU runners running 4
Playwright workers (`~3.35x` measured speedup), under-allocating serial
shards (`5` serial shards running `96–124s` while parallel shards sat
idle after `55–78s`).
> 2. `scripts/e2e-shard-durations.json` had stale weights
(`chat-adapters-ui-providers.spec.ts` `86.8s` vs `117–165s` actual;
`acp-stop-continuation.spec.ts` `69.3s` vs `88–102s` actual).
> 3. Three serial (`1-worker`) specs pinned the floor at `75–91s`:
`agent-configuration.spec.ts` (`91.4s`), `agent-chat-sessions.spec.ts`
(`79.9s`), and `onboarding.spec.ts` (`75.3s`).
> 4. `playwright.config.ts` ran `vite build ui` (`~5.4s`) serially
before starting embedded Postgres + 512 migrations (`~21s`) even though
database bootstrap does not read `server/ui-dist`.
> - This pull request overlaps the unminified Vite UI build with
Postgres bootstrap inside `start-e2e-server.ts`, splits the top 3 serial
specs into 6 balanced specs (keeping all 3 anchor filenames and 100% of
20 tests intact), makes `e2e-shard.mjs` CPU-aware (`3.2x` on 8-vCPU /
`1.85x` on 4-vCPU), refreshes all 58 specs in
`e2e-shard-durations.json`, and scales AWS `e2e_shards` `12 -> 16` while
keeping `ubuntu-latest` hosted at `4` — bringing simulated E2E test
execution to `~90–96s` (`-60 to -75s`).

## Linked Issues or Issue Description

Refs #22804

**What existing behavior does this improve?**
E2E shard wall-clock ceiling on 8-core PR runners (`tests/e2e/`,
`scripts/e2e-shard.mjs`, `scripts/e2e-shard-durations.json`,
`.github/ci-task-matrix.json`, `.github/workflows/pr-trusted.yml`).

**Subsystem affected**
tests/e2e/ and CI — Playwright server bootstrap, serial spec sharding,
and E2E shard matrix

**Current behavior**
E2E shards take `152–171s` on 8-core runners because `vite build ui`
runs serially before Postgres boot, 3 serial specs run `75–91s` each,
`e2e-shard.mjs` assumes 4-vCPU `1.85x` parallel speedup, and AWS runs 12
shards.

**Proposed behavior**
Overlap unminified Vite UI build with embedded Postgres boot in
`tests/e2e/start-e2e-server.ts`, split the top 3 serial specs into 6
balanced specs (preserving anchor paths and all tests), use CPU-aware
parallel speedup (`3.2x` on 8-vCPU / `1.85x` on 4-vCPU) with refreshed
58-spec durations, and run 16 AWS E2E shards (`8 serial + 8 parallel`,
`59.7–76.5s` Playwright) while keeping `ubuntu-latest` hosted at `4`.

## What Changed

- **Overlapped UI build with Postgres bootstrap
(`tests/e2e/playwright.config.ts`, `tests/e2e/start-e2e-server.ts`):**
- Launches `start-e2e-server.ts` directly with `PAPERCLIP_E2E_BUILD_UI`
(`0` when `PAPERCLIP_E2E_SKIP_UI_BUILD=1`), overlapping `vite build ui
--outDir ../server/ui-dist --emptyOutDir --minify false` concurrently
inside `Promise.all([dbPromise, import("../../server/src/index.js"),
uiReady])` with `stopUiBuild()` and `dbPromise` cleanup on
signals/failure, plus `maintenance_work_mem = 128MB` / `work_mem = 32MB`
on disposable PG.
- **Split top 3 serial E2E specs (100% of 20 tests preserved, all 3
anchor filenames & `maps/` links intact, all 3 new siblings registered
in BOTH `playwright.config.ts` and `scripts/e2e-shard.mjs`
`SERIAL_SPECS`):**
- `agent-configuration.spec.ts` (3 tests) +
`agent-configuration-revisions.spec.ts` (5 tests) +
`agent-configuration.shared.ts`
- `agent-chat-sessions.spec.ts` (3 tests) +
`agent-chat-sessions-navigation.spec.ts` (3 tests)
- `onboarding.spec.ts` (3 tests) + `onboarding-resume.spec.ts` (3 tests)
- **CPU-aware speedup, refreshed 58-spec manifest, & 16 AWS E2E shards
(`scripts/e2e-shard.mjs`, `scripts/e2e-shard-durations.json`,
`.github/ci-task-matrix.json`, `.github/workflows/pr-trusted.yml`,
`.github/scripts/tests/ci-plan.test.mjs`,
`scripts/__tests__/e2e-shard.test.mjs`):**
- Exported `EFFECTIVE_PARALLEL_SPEEDUP_4W = 3.2` and
`resolveEffectiveParallelSpeedup(cpus)` matching `playwright.config.ts`
worker scaling.
- Refreshed all 58/58 spec weights from live 8-core runs `45668834558` &
`45667106472`.
- Scaled AWS `e2e_shards` `12 -> 16` while keeping `ubuntu-latest`
hosted at `4`.

## Verification

- `node --test scripts/__tests__/e2e-shard.test.mjs
.github/scripts/tests/ci-plan.test.mjs
scripts/check-test-budget.test.mjs
scripts/__tests__/merge-queue-checks-workflow.test.mjs` — **45/45 PASS**
- `npx playwright test --config tests/e2e/playwright.config.ts --list`
on all 6 split specs — **20 tests in 6 files**
- `tsc --strict --noEmit` across all 9 edited `tests/e2e/*.ts` files —
**0 errors**
- `node scripts/check-test-budget.mjs --base origin/master` and `node
scripts/check-maps.mjs` — **PASS**
- `ruby -ryaml -e 'YAML.load_file(".github/workflows/pr-trusted.yml")'`
— **YAML OK**

## Risks

- Low risk: all 3 original serial spec anchor filenames remain intact,
`PAPERCLIP_E2E_SKIP_UI_BUILD=1` is preserved, signal/failure handlers
clean up both the Vite child and embedded PG, `ubuntu-latest` stays at 4
hosted shards, and full CI runs all E2E shards live before merge.

## Model Used

- Gemini 4 Neon (High) via Antigravity agent swarm (`e2e-opt`,
`verifier`, `ci-pipeline`).

## 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
2026-11-25 13:40:52 -06:00
Dotta 1c36d24d0c perf(ci): parallelize Runner Rust checks, Runner build, and typecheck lane (#22957)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Live 8-core PR runs (`45667106472`, `45665466678`, `45668834558`)
showed two critical-path stragglers on Rust- and TypeScript-heavy PRs:
> 1. `Verify Paperclip Runner (rust)` (`206s` step): ran a redundant
`cargo check --workspace` (`8.1s`) before `cargo test --release`,
executed all 44 compiled Rust test binaries **sequentially** (`119.2s`
vs `~50s` parallel!), and then re-invoked `cargo test --release` twice
more for `check:conformance-parity` and `check:replay-parity` (`~8s`).
> 2. `Typecheck + Release Registry` (`100s–147s` step): ran `CLI
guidance safety` (`2.9s`) and `typecheck @paperclipai/paperclip-runner`
(`5.6s`) serially before `prepare:runner-vendor`, ran
`packages/paperclip-runner` `build` (`17.1s` hit / `51.0s` miss)
serially across 12 steps, and scheduled lighter `7–10s` test projects
ahead of the 4 `17–25s` server test layers.
> - This pull request parallelizes `check:runner`
(`run-check-runner.mjs`), `packages/paperclip-runner` `build`
(`run-build.mjs`), and `scripts/ci-typecheck-lane.mjs` cleanly across 8
cores with full process-group signal cleanup (`stopActiveChildren`),
exact `CARGO_BIN_EXE_*` / `CARGO_MANIFEST_DIR` fidelity, fail-closed
parity assertions, exact `record-build-inputs --begin/--finish`
bracketing, and 100% check parity.

## Linked Issues or Issue Description

Refs #22804

**What existing behavior does this improve?**
Execution wall-clock of `Verify Paperclip Runner (rust)`, `Typecheck +
Release Registry`, and `Build` on 8-core runners.

**Subsystem affected**
packages/paperclip-runner/ and scripts/ — Rust test orchestration,
Runner package build, and monorepo typecheck DAG

**Current behavior**
`check:runner` runs `cargo check`, 44 Rust test binaries sequentially,
and 2 redundant parity re-runs; `packages/paperclip-runner` `build`
executes 12 build/check steps serially; `ci-typecheck-lane.mjs` blocks
`prepare:runner-vendor` behind serial `prepare` steps and under-utilizes
8-core / 32 GiB runners.

**Proposed behavior**
Execute `check:runner` with overlapped `acpx-profiles` / `cargo fmt
--check` / `cargo test --release --no-run` followed by LPT-ordered
concurrent execution of all 44 test binaries + `--doc` + fail-closed
parity verification; parallelize `packages/paperclip-runner` `build`
into race-free pre-dist / build / staging / post-dist phases;
parallelize `CLI guidance safety` and `typecheck
@paperclipai/paperclip-runner` in `ci-typecheck-lane.mjs`, LPT-order
post-declaration tasks, and tune 8-core / >=24 GiB concurrency
(`laneConcurrency: 8`, `serverDeclCheckers: 6`).

## What Changed

- **`packages/paperclip-runner/scripts/run-check-runner.mjs` &
`run-check-runner.test.mjs`:**
- Overlaps `check:acpx-profiles` and `cargo fmt --all -- --check` with
`cargo test --release --locked --workspace --no-run
--message-format=json-render-diagnostics`.
- Parses all 44 compiled test binaries with exact `CARGO_BIN_EXE_*` and
per-crate `CARGO_MANIFEST_DIR`, executes them concurrently in LPT order
(`codex_provider` first, `acpx_sidecar_stopped_time` isolated in its own
detached process group with `--test-threads=1`, plus `cargo test
--release --workspace --doc`).
- Verifies both `runs_the_mock_core_path_with_stable_output` and
`replay_fixture_parity` passed in the workspace run (failing closed if
missing or ignored), eliminating 2 redundant `cargo test`
re-invocations.
- **`packages/paperclip-runner/scripts/run-build.mjs` &
`run-build.test.mjs`:**
- Preserves exact `record-build-inputs.mjs --begin` / `--finish`
bracketing from the same parent PID, overlaps `eval-kernel + tsc`,
`cargo build --release` (honoring
`PAPERCLIP_RELEASE_RUNNER_ARTIFACTS_DIR`), and all 9 pure source-only
pre-dist checks, stages disjoint `dist/` outputs in parallel, and runs
all 5 `dist/`-importing checks (`check:runner-workflow-traceability`,
`check:protocol-coverage`, `check:semantic-contracts`,
`check:replay-goldens`, `check:semantic-action-catalog`) in parallel
post-dist.
- **`scripts/ci-typecheck-lane.mjs`,
`scripts/__tests__/ci-typecheck-lane.test.mjs`, &
`.github/scripts/tests/ci-plan.test.mjs`:**
- Moved `CLI guidance safety` and `typecheck
@paperclipai/paperclip-runner` (`needs: [PREPARE_RUNNER_VENDOR]` when
`runServer`) out of serial `prepare` into `tasks`.
- Ordered post-declaration tasks LPT (`tests/runner-e2e` -> 4 `server
layer test-*` -> smaller projects) and tuned 8+ core / >=24 GiB runners
to `laneConcurrency: 8`, `serverDeclCheckers: 6`.
- **`packages/paperclip-runner/scripts/run-check-static.mjs`,
`run-prep-tests.mjs`, & `package.json`:**
- Shared `stopActiveChildren` / process-group runner helpers across
`run-check-static.mjs`, `run-check-runner.mjs`, and `run-build.mjs`;
wired `run-build.test.mjs` and `run-check-runner.test.mjs` into
`PREP_TEST_FILES`.

## Verification

- `node --test .github/scripts/tests/*.test.mjs
scripts/__tests__/ci-typecheck-lane.test.mjs
scripts/check-test-budget.test.mjs
scripts/__tests__/runner-release-crate-cache.test.mjs` — **855/855
PASS**
- `node --test scripts/run-check-runner.test.mjs
scripts/run-build.test.mjs scripts/run-check-static.test.mjs
scripts/build-inputs.test.mjs scripts/stage-runner-binary.test.mjs` (in
`packages/paperclip-runner`) — **32/32 PASS**
- `node scripts/check-test-budget.mjs --base origin/master` and `node
scripts/check-maps.mjs` — **PASS**
- Live Linux Cargo/Runner and monorepo Typecheck/Build execution
verified end-to-end by PR CI.

## Risks

- Low risk: all 9 pre-dist checks were verified pure source read-only
while all 5 `dist/`-importing checks run strictly after `tsc` and asset
staging; Rust parity checks fail closed if either test is absent or
ignored; process-group cancellation ensures zero orphaned test
processes.

## Model Used

- Gemini 4 Neon (High) via Antigravity agent swarm (`server-prune`,
`verifier`, `ci-pipeline`).

## 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-25 13:40:47 -06:00
TonioandClaude Fable 5.2 a336e295f6 feat(ui): turn Connectors into a Plugins marketplace (#22869)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Agents reach outside tools through connectors, which people add on
the Connectors page
> - That page is one long list. Each row mixes the catalog entry with
its accounts, so it is hard to scan and hard to tell what is installed
> - Some connectors also bring skills, but the page does not show them
> - This pull request renames the page to Plugins and changes the browse
view into a marketplace of small cards grouped by category. Each card
opens a plugin page that holds the accounts, the skills and the tool
permissions
> - The benefit is a catalog that people can scan fast, with one place
per connector for its accounts and its skills. Connector behavior does
not change

## Linked Issues or Issue Description

**Subsystem affected**

UI: the Connectors (Apps catalog) pages under `ui/src/pages/apps/` and
the navigation labels that point to them.

**Problem or motivation**

The Connectors browse page is a vertical list of large rows. A row shows
the catalog entry and every account under it. People must expand rows to
see what is connected. The page does not show which skills come with a
connector.

**Proposed solution**

- Rename the page from Connectors to Plugins in the navigation, the
breadcrumbs, and the page titles. A single app is still called a
connector.
- Remove the Browse / Review rail. The page header carries the title, a
Review shortcut, and an Add menu for a custom MCP server, a pasted
config, or an assistant connection.
- Show the catalog as a marketplace under one "All" tab: "Most used" and
"New and noteworthy" for first-party connectors, then one block per
category. Composio and Arcade connectors sit in the same blocks. A block
shows at most nine plugins, its total, and a "See all" link to a
category page at `/apps/category/:categoryId`.
- Use a compact card: logo, name, description, and one corner control.
The control is a plus to connect, a check when connected, or a warning
when an account needs attention.
- Open a plugin page at `/apps/plugin/:pluginKey` from each card. The
page has Connect in its header and groups Accounts, Connector, Skills,
Tool permissions, and Information as blocks. Tool permissions shows a
connected account's actions as Reads and Writes, each with a group
policy and per-action policies.
- Start sign-in straight from the card for a one-click connector: one
OAuth method that Paperclip can start itself, with nothing to fill in
and no warning to read. The success screen states who can use the
connection and links to where that changes.
- Search reads plugin titles only.
- Keep the account list on the Installed filter.

**Related pull requests**

A search of open and closed pull requests for the Connectors browse
page, a plugins or connectors marketplace, connector categories, and
one-click sign-in found no duplicate. #22863 compresses connector logo
files and does not overlap with these pages.

**Alternatives considered**

- An experimental setting that keeps the old page. The product owner
chose to replace the page for everyone.
- A new backend link between connectors and catalog skills. This pull
request stays in the front end. The pairing for GitHub is a constant in
`PluginSkills.tsx`.
- Real categories for Composio apps. Its public catalog file has names
only, so those apps are sorted by keywords in the name and the rest go
to "Other". Arcade's catalog states a category, which is now carried
through `AggregatorAppCatalogEntry.category`.

## What Changed

- `Browse.tsx`: keeps all data loading, connect logic, and dialogs. The
render now has five views: marketplace, category page, flat results
grid, Installed list, and plugin page. The default source is `all`; the
`paperclip` source is removed.
- `PluginMarketplace.tsx` (new): `PluginTile`, `PluginShelf` (count and
"See all"), `PluginCategories`, and the category labels.
- `PluginsHeader.tsx` (new): page title, Review shortcut with the
pending count, and the Add menu.
- `PluginPageSections.tsx` (new): plugin page header, Connector row, and
Information facts read from the app definition.
- `PluginPermissions.tsx` (new): Reads and Writes blocks for a connected
account. Saves go through `useConnectionPermissionSave` and restate
agent access exactly as the per-connection page does. The four helpers
it shares with that page moved from `AppDetail.tsx` to
`app-detail/saved-permissions.ts` with no behavior change.
- `PluginSkills.tsx` (new): lists built-in connector skills, skills that
a connected server publishes, and paired catalog skills. "Add skill"
calls the existing catalog install endpoint.
- `plugin-categories.ts` (new): maps Arcade categories onto the Plugins
categories and guesses a category from the name for apps that state
none.
- `features/connections/one-click-oauth.ts` (new): the one-click rule
and the hand-over of the sign-in window from the card's click to the
connect flow. A browser only opens that window during a click, so the
card opens it and `ConnectionSetupFlow` takes it over. If the window is
blocked, or the page is reloaded, the ordinary confirmation screen
shows.
- `ConnectionSetupFlow.tsx`: takes the handed-over window, starts
sign-in when the app qualifies, and adds a "Change" link beside the
stated default on the success screen.
- `apps-rail.ts` (new), `AppsSidebar*.tsx`, `Layout*.tsx`: the
marketplace pages have no second rail. Chat setup and detail keep
theirs, and the developer pages keep one while a developer tab is on.
- `ConnectorCard`: new `variant="page"` that renders the accounts as one
block with "Add account" at the bottom.
- `ConnectorsToolbar.tsx`: source filters first, a wider "Search
plugins" field on the right.
- `App.tsx`, `Layout.tsx`, `Layout.production.tsx`: new
`apps/plugin/:pluginKey` and `apps/category/:categoryId` routes and
reserved subpaths.
- Navigation and breadcrumb labels: "Connectors" becomes "Plugins" in 19
files, and the instance plugin system becomes "System plugins".
- `packages/shared/src/aggregator-app-catalog.ts`: optional `category`
on a catalog entry, set from Arcade's catalog.
- `ui/storybook/prototypes/ConnectorCatalogNavigation.tsx`: keeps its
own five-source list so the older prototype still builds.
- Tests: label renames in the specs and stories that named Connectors or
"Search connectors". Seven specs now reach the custom-server setup
through the Add menu. New specs: `one-click-connect`, `plugins-browse`.
`apps-prosumer-mcp-flow` also covers the plugin page permissions and the
success-screen link.

Kept on purpose, so current flows and specs continue to work: the
`Connector list` list label, `data-app-slug` and `data-connected` on
each card, and the `<Verb> <App name>` button names.

## Verification

- `cd ui && pnpm typecheck`: pass.
- `pnpm run check:token-gates`: pass.
- `cd ui && npx vitest run`: 564 files, 7,059 tests pass, 1 skipped.
- `cd packages/shared && npx vitest run
src/aggregator-app-catalog.test.ts`: 9 tests pass.
- `PAPERCLIP_RUNNER_BINARY=/usr/bin/true npx playwright test --config
tests/e2e/playwright.config.ts` for the 15 spec files under
`tests/e2e/*.spec.ts` that touch the Plugins pages, plus
`one-click-connect` and `plugins-browse`: all pass (3 skipped by their
own conditions).
- Storybook: built this branch and master and ran the interaction tests
of the 253 stories in the files that mount the browse page. Master
passes 230; this branch passes the same 230. The 23 that fail do so on
master too.
- Manual: opened Plugins, a category page, a plugin page, the Installed
filter, and Review on a local instance.
- Not run locally: `execution-recovery/recovery.spec.ts`,
`in-feed-native/connections.spec.ts`, the runner e2e tests, and the
repo-wide typecheck (it needs the Rust toolchain). A real provider
sign-in was not completed; the one-click test stops at the point the
flow starts. `pnpm verify` exits 2 and names CI as the source of broad
coverage.

## Risks

- The page changes for every user. People who know the old list must
learn the new layout. The Installed filter keeps the old account list.
- The instance plugin system is renamed "System plugins" in the settings
navigation, breadcrumbs, and its management page, so the two areas no
longer share a name. URLs and lower-case mentions of "plugin" inside
sentences are unchanged.
- One-click connect skips the screen that states the access default
("Connects for everyone in your organization, available to all agents")
and offers Change. The default is applied without being shown first; the
success screen states it and links to the permissions page.
- Most Composio apps (about 1,100 of 1,583) land in "Other", and the
keyword guess is sometimes wrong. Correct categories need category data
in the catalog file.
- The plugin page can now save action permissions. It uses the same save
path and access derivation as the per-connection page and waits for all
four reads before it enables the controls. The account picker for
several accounts and the read-only view have no test.
- The Smoke Lab developer page has no link from the browse page; it is
reachable by URL.
- e2e specs that this pull request did not run locally can fail on
selectors. CI must confirm them.
- "New and noteworthy" is a fixed list in code. The catalog has no date
to sort by.
- Skill pairing is a front-end constant. Nothing records that a skill
came from a connector, so removing a connector does not remove the
skill.
- The per-connection permissions page is not restyled in this pull
request.

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

## Model Used

- Claude Fable 5.2 (`claude-fable-5-2`) through Claude Code, with tool
use, code execution, and subagents for read-only code search.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [ ] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [ ] 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 Fable 5.2 <noreply@anthropic.com>
canary/v2026.1125.0-canary.862000
2026-11-25 19:16:24 +00:00
Dotta 3773d0f40f perf(ci): skip prebaked pnpm setup, move rollups to ubuntu-slim, and narrow dep cache inputs (#22958)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Live 8-core runs on `paperclip-public-ci-fleetd:29`
(`ami-09dfb1e62707f576c`, runs `45665466678` & `45668834558`) revealed
three zero-hot-instance sources of wasted PR wall-clock time:
> 1. `pnpm/action-setup@v6` still spent `4.1–5.0s` on all 68 jobs
switching its bundled `v11.19.0` to `v9.15.4` even though the pre-baked
AMI already has `pnpm@9.15.4` installed at
`$HOME/setup-pnpm/node_modules/.bin/pnpm`.
> 2. `ci / verify` and `ci / e2e` rollups booted fresh 8-core AWS EC2
VMs (`18–23s` cold queue after all tests already finished!) just to run
a 1-second inline Node `assert` check with zero repo checkout and zero
secrets.
> 3. `scripts/ci-dependency-cache.mjs` hashed blanket `scripts/**`,
`server/scripts/**`, and `packages/paperclip-runner/scripts/**`, causing
every merge touching any CI script or shard duration manifest to
invalidate the ~944 MB `ci-dependencies-v1` cache for all 70 jobs
(`35–40s` cold restore vs `10s` hit) until `release-verify.yml` rebuilt
it 15–20 minutes later.
> - This pull request eliminates all three bottlenecks with zero
hot/standby instances and zero security-boundary changes
(`ci-routing.yml`, `pr.yml`, `CODEOWNERS`, and read-only PR caches
untouched).

## Linked Issues or Issue Description

Refs #22804

**What existing behavior does this improve?**
PR job startup latency, rollup tail latency, and `ci-dependencies-v1`
cache hit rate across `.github/workflows/pr-trusted.yml`,
`.github/actions/setup-ci-dependencies/action.yml`, and
`scripts/ci-dependency-cache.mjs`.

**Subsystem affected**
CI — PR workflow bootstrap, rollup jobs, and materialized dependency
cache key inputs

**Current behavior**
All 11 `Setup pnpm` steps run `pnpm/action-setup@v6` unconditionally
(`4–5s` each); `ci / verify` and `ci / e2e` boot full AWS EC2 runners
(`18–23s` queue) after tests complete; `ci-dependency-cache.mjs` hashes
blanket `scripts/**` globs so unrelated CI script edits bust
`node_modules` caching across all 70 PR jobs.

**Proposed behavior**
Dynamically compare `$HOME/setup-pnpm/node_modules/.bin/pnpm --version`
against `package.json`'s `packageManager` before all 11 `Setup pnpm`
steps (skipping `pnpm/action-setup` on pre-baked runners while
preserving identical `PNPM_HOME` and failing closed on version bumps);
run `ci / verify` and `ci / e2e` rollups on `ubuntu-slim`; narrow
`ci-dependency-cache.mjs` script inputs to the exact 8-file
`DEPENDENCY_SCRIPT_INPUTS` closure enforced by a static relative-import
test plus `--prefer-offline` on cold-install fallback.

## What Changed

- **Skip redundant `pnpm/action-setup` on pre-baked AMIs
(`.github/workflows/pr-trusted.yml`):**
- Added inline `Check preinstalled pnpm` (`id: pnpm_preinstalled`)
before all 11 `Setup pnpm` steps: parses `package.json`'s
`packageManager` (`^pnpm@([^+\s]+)(?:\+.*)?$`) dynamically, compares
against `$HOME/setup-pnpm/node_modules/.bin/pnpm --version`, exports
identical `PNPM_HOME` + `$GITHUB_PATH` on match, and fails closed to
`pnpm/action-setup@v6` on version bump or `ubuntu-latest`.
- **Move `ci / verify` & `ci / e2e` rollups to `ubuntu-slim`
(`.github/workflows/pr-trusted.yml`):**
- Switched both zero-checkout rollup jobs from
`needs.gate.outputs.runner` to `ubuntu-slim` (~2–4s container start
instead of `18–23s` EC2 VM boot).
- **Narrow dependency cache script inputs
(`scripts/ci-dependency-cache.mjs`,
`.github/actions/setup-ci-dependencies/action.yml`):**
- Replaced blanket `scripts/**`, `server/scripts/**`, and
`packages/paperclip-runner/scripts/**` hashes with exported
`DEPENDENCY_SCRIPT_INPUTS` (the exact 8 scripts invoked during
dependency materialization/postinstall), kept
`scripts/ensure-plugin-build-deps.mjs` on `buildKey` only, and added
`--prefer-offline` on cold-install fallback.
- **Tests (`.github/scripts/tests/ci-dependency-cache.test.mjs`,
`.github/scripts/tests/ci-plan.test.mjs`):**
- Added automated static relative-import closure verification for
`DEPENDENCY_SCRIPT_INPUTS`, `ubuntu-slim` rollup checks, and execution
tests of the extracted `Check preinstalled pnpm` snippet across
matching, `+sha512`, bumped, missing `packageManager`, and missing
binary cases.

## Verification

- `ruby -ryaml -e 'YAML.load_file(".github/workflows/pr-trusted.yml");
YAML.load_file(".github/actions/setup-ci-dependencies/action.yml")'` —
**YAML OK**
- `node --test .github/scripts/tests/*.test.mjs
scripts/ci/test-selection-workflow.test.mjs
scripts/__tests__/{ci-typecheck-lane,e2e-shard,run-vitest-stable-shard,run-vitest-stable-pr-mode,merge-queue-checks-workflow,runner-release-crate-cache,runner-debug-crate-cache,public-install-closure}.test.mjs
scripts/check-test-budget.test.mjs
scripts/docker-image-metadata.test.mjs` — **942/942 PASS**
- Live PR CI proves `ubuntu-slim` rollup execution, pre-baked `Check
preinstalled pnpm` skip (`hit=true`), and `ci-dependencies-v1` restore
parity end-to-end.

## Risks

- Low risk: `Check preinstalled pnpm` dynamically reads `package.json`'s
`packageManager` and fails closed on mismatch or version bump;
`ci-dependency-cache.test.mjs` statically enforces that no relative
import from `DEPENDENCY_SCRIPT_INPUTS` can escape the cache key; `ci /
verify` and `ci / e2e` check out no code and use no secrets.

## Model Used

- Gemini 4 Neon (High) via Antigravity agent swarm (`typecheck-opt`,
`verifier`, `ci-pipeline`).

## 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
2026-11-25 12:39:05 -06:00
Dotta 1fca3a6d8c fix(github): silence anonymous sandbox launchers and auto-request GitHub connection on unconfigured git auth failures (#22954)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Sandboxed runs wrap `git` and `gh` with broker launchers so agents
do not inherit ambient host credentials, and task feeds use
`connection_intent` cards to let users connect services inline.
> - When a workspace has no GitHub connection configured, anonymous
sandbox launchers logged `Paperclip: GitHub capability_missing;
continuing without managed credentials.` on every `git` or `gh` call,
and failed local `gh --version`/`--help` commands.
> - In addition, when an agent tried to clone a private GitHub
repository, push to GitHub, or run `gh` without a GitHub connection
configured, the task feed did not prompt the user with a GitHub
connection card.
> - Both issues hurt first-run clarity: noisy `capability_missing`
warnings look like broken infrastructure, while unconfigured git auth
failures leave users without an inline path to connect GitHub.
> - This pull request marks intentional anonymous sandbox launchers
silent, treats local `gh` version/help commands as local, and
automatically attaches a `github` `connection_intent` card in the task
feed when a run hits an unambiguous unconfigured GitHub auth failure.
> - The benefit is clean anonymous git/gh execution and a one-click
inline GitHub setup card when a task needs private GitHub access.

## Linked Issues or Issue Description

**What happened?**
In sandboxes without a GitHub connection configured, running `git` (such
as `git --version` or public clones) logged `Paperclip: GitHub
capability_missing; continuing without managed credentials.` and `gh
--version` / `gh --help` attempted broker resolution. When an agent
tried an authenticated GitHub operation (such as cloning a private
repository, pushing, or running `gh`), the run failed or reported the
auth error without showing a GitHub connection card in the task feed.

**Expected behavior**
Anonymous unconfigured sandbox launchers should run public/local `git`
and local `gh` commands silently without emitting `capability_missing`
warnings, while keeping `capability_missing` diagnostics for genuinely
missing or failed-bridge broker configs. When an agent hits an
unconfigured GitHub authentication failure during a task run or
workspace clone, Paperclip should attach a `github` connection card in
the task feed and mark run liveness as blocked waiting for the user.

**Steps to reproduce**
1. Run an agent in a sandbox with no GitHub connection configured.
2. Execute `git --version`, `gh --version`, and `git clone
https://github.com/<org>/<private-repo>.git`.
3. Observe `Paperclip: GitHub capability_missing; continuing without
managed credentials.` on stdout/stderr and no GitHub connection card in
the task feed after the private clone fails.

**Paperclip version or commit**
`a0d5f275af` (`master`)

**Deployment mode**
Other (sandboxed Paperclip Runner and local server)

## What Changed

- Added explicit `anonymous` mode to GitHub broker launchers
(`packages/adapter-utils/src/github-launcher.ts`,
`packages/adapter-utils/src/execution-target.ts`,
`server/src/services/heartbeat-github-launchers.ts`) and supported
`"anonymous": true` in `broker.json` so intentionally unconfigured
sandboxes stay quiet while missing/broken broker bridges still emit
`capability_missing`.
- Treated local `gh` commands (`--version`, `--help`, `-h`, `version`,
`help`) as local in the `gh` launcher without contacting the credential
broker.
- Added `server/src/services/git-auth-connection-detection.ts` to detect
unambiguous `github.com` auth failures in failed command execution
events (`tool.execution.completed` and `item.completed`) and structured
workspace clone failures while ignoring `exitCode === 0`, assistant
prose, non-GitHub remotes, transient 5xx errors, and local non-auth git
errors.
- Added controller-only
`connectionIntentService(db).requestForRunGitHubAuthFailure(runId,
resultJsonOverride?)` in `server/src/services/connection-intents.ts`
(with `completed_git_auth` run-context mode) to create a `github`
`connection_intent` card in the task feed when GitHub is not already
configured/usable, skipping `host` auth mode, closed tasks, non-latest
runs, existing pending cards, and declined continuations.
- Wired `requestForRunGitHubAuthFailure` into
`classifyAndPersistRunLiveness`
(`server/src/services/heartbeat/run-lifecycle.ts`) and added
`githubConnectionRequested` support to `classifyRunLiveness`
(`server/src/services/run-liveness.ts`) to classify the run as `blocked`
(`Waiting for GitHub connection`).
- Added unit and embedded-Postgres integration tests in
`packages/adapter-utils/src/github-launcher.test.ts`,
`server/src/services/heartbeat-github-launchers.test.ts`, and
`server/src/__tests__/github-connection-auto-request.test.ts`.

## Verification

- `pnpm vitest run packages/adapter-utils/src/github-launcher.test.ts`
(41/41 passed)
- `pnpm vitest run
packages/adapter-utils/src/github-launcher-environment.test.ts
--testTimeout=15000` (40 passed, 1 skipped)
- `pnpm vitest run
server/src/services/heartbeat-github-launchers.test.ts
server/src/services/native-runtime/native-github-access.test.ts`
(passed)
- `pnpm vitest run
server/src/__tests__/github-connection-auto-request.test.ts
server/src/__tests__/connection-intents-service.test.ts
server/src/__tests__/ai-auth-failure.test.ts
server/src/services/heartbeat/run-comment-selection.test.ts` (86/86
passed)
- `pnpm vitest run server/src/__tests__/run-liveness.test.ts` (21/21
passed)
- `pnpm vitest run
server/src/__tests__/heartbeat-process-recovery.test.ts -t
"clone|connection|GitHub"` (6/6 passed)
- `pnpm --filter @paperclipai/adapter-utils typecheck && pnpm --filter
@paperclipai/server typecheck` (0 errors)

## Risks

- Low risk. No database migrations or UI schema changes are required;
the auto-created card reuses the existing `connection_intent`
interaction kind (`serviceSlug: "github"`).
- False-positive card creation is guarded by strict `github.com` host
matching, non-zero command exit requirements, `githubAuthenticationMode
!== "host"`, active-identity checks (`usableConnectionForAgent` and
`resolveManagedGitHubIdentitySelection`), idempotent pending-card
checks, and decline respect.

## Model Used

- Google Gemini (Antigravity agent) with tool use and local code/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
- [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
canary/v2026.1125.0-canary.861800
2026-11-25 12:11:21 -06:00
DottaandPaperclip 2538dce415 Split heartbeat-process-recovery.test.ts into 4 balanced serialized suites (#22955)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Release and master verification run serialized server integration
suites across sharded CI jobs (`release-verify.yml`)
> - `server/src/__tests__/heartbeat-process-recovery.test.ts` (17,926
lines, 466 expanded tests) takes ~6m 28s in a single file, so Vitest
cannot shard it across runners even with 9 serialized shards (#22946)
> - Because one file sets a hard floor on the serialized verification
lane, release readiness stays slower than necessary after every merge
> - This pull request moves the shared suite body into
`server/src/__tests__/heartbeat-process-recovery.helper.ts` with four
disjoint `part` slices and adds four thin test entrypoints
(`heartbeat-process-recovery-part-{1..4}.test.ts`)
> - The benefit is balanced shard distribution across serialized
runners, cutting the single-file serialized ceiling by ~4.5 minutes
while keeping all 466 test cases intact

## Linked Issues or Issue Description

Refs #22946

**Area**
CI / Test Infrastructure

**Current Behavior**
`server/src/__tests__/heartbeat-process-recovery.test.ts` runs as a
single 17,926-line Vitest file (~344s recorded, ~388s in recent release
runs), bounding `Serialized tests` even across 9 shards.

**Proposed Improvement**
Partition the suite into four thin entrypoint files
(`heartbeat-process-recovery-part-{1..4}.test.ts`) backed by a shared
`heartbeat-process-recovery.helper.ts`, with measured proportional shard
weights in `scripts/serialized-shard-durations.json` and
`scripts/ci/nightly-only-suites.json`.

**Motivation / Use Case**
Shorten master and release verification wall-clock latency without
dropping or weakening any recovery test coverage.

## What Changed

- Renamed `server/src/__tests__/heartbeat-process-recovery.test.ts` to
`server/src/__tests__/heartbeat-process-recovery.helper.ts` exporting
`registerHeartbeatProcessRecoverySuite(part: 1 | 2 | 3 | 4)`, hoisting
`withTempPaperclipHome` to shared scope, making `beforeAll`'s
`authUsers` seed `.onConflictDoNothing()` for shared
`PAPERCLIP_TEST_DATABASE_URL` safety, routing dynamic `run-dispatch`
imports through `../modules/run-dispatch/index.js`, and updating the two
stack-trace file-name assertions to `.helper.ts`.
- Added four 3-line entrypoints:
`server/src/__tests__/heartbeat-process-recovery-part-{1,2,3,4}.test.ts`.
- Updated `scripts/run-vitest-stable.mjs`,
`scripts/serialized-shard-durations.json`, and
`scripts/ci/nightly-only-suites.json` with the four part paths and
measured proportional shard weights (`88511`, `102168`, `72141`, `81197`
ms; sum `344017` ms).
- Updated `.github/workflows/runner-chaos-evals.yml` (with
`--no-file-parallelism` to preserve serial execution in that job),
`maps/feature-map/recovery.md`,
`packages/paperclip-runner/spec/evals/stress-workflow-traceability.json`,
and `scripts/ci/test-selection.integration.test.mjs`.

## Verification

- Executed all four split suites locally via Vitest against embedded
Postgres — **466/466 tests passed** (0 failed, 0 skipped):
- `heartbeat-process-recovery-part-1.test.ts`: 116/116 passed (199.67s
under 4-way local contention)
- `heartbeat-process-recovery-part-2.test.ts`: 103/103 passed (230.48s)
  - `heartbeat-process-recovery-part-3.test.ts`: 87/87 passed (162.74s)
- `heartbeat-process-recovery-part-4.test.ts`: 160/160 passed (183.17s)
- Verified brace-depth exhaustiveness across
`heartbeat-process-recovery.helper.ts`: 0 top-level
`it`/`it.each`/`describe` blocks outside `if (part === N)` guards.
- `node scripts/check-module-boundaries.mjs` — passed.
- `node scripts/check-maps.mjs` — passed.
- `node scripts/check-test-budget.mjs --base origin/master` — passed.
- `node --test scripts/check-test-budget.test.mjs
scripts/__tests__/run-vitest-stable-shard.test.mjs
scripts/__tests__/run-vitest-stable-pr-mode.test.mjs
scripts/ci/test-selection.integration.test.mjs` — passed.

## Risks

- Low risk: test-only partition; zero production runtime files changed.
- Adding a future test to `heartbeat-process-recovery.helper.ts` outside
an `if (part === N)` guard would not register in any part; documented
the placement rule directly on `registerHeartbeatProcessRecoverySuite`.

## Model Used

- Google Gemini (Antigravity agent with tool use and code execution)

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-25 12:08:54 -06:00
Dotta 2d06567795 Run release-verify check:api-authority in its own parallel lane (#22951)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Post-merge release verification in
`.github/workflows/release-verify.yml` runs `verify_paperclip_runner`
matrix lanes in parallel to prove exact-source readiness.
> - Today, the `rust` lane runs `check:runner` (236s) and
`check:api-authority` (92s) serially on one runner, stretching the lane
to ~6m 39s–7m 34s even though `check:api-authority` is independent and
reads the same shared `release-runner-v2` Rust dependency cache.
> - Meanwhile, PR verification (`pr-trusted.yml`) already separates
`check:api-authority` from the Rust test lane.
> - This pull request moves `check:api-authority` into its own
`api-authority` lane in `.github/workflows/release-verify.yml` and
updates `.github/scripts/tests/release-runner-cache.test.mjs` to cover
the new lane.
> - The benefit is cutting ~1m 30s off the `Verify Paperclip Runner
(rust)` critical path on every post-merge `cloud-readiness.yml` and
release verification run.

## Linked Issues or Issue Description

**What existing behavior does this improve?**
Wall-clock duration of `Verify Paperclip Runner (rust)` in
`.github/workflows/release-verify.yml`.

**Subsystem affected**
Cross-cutting (multiple of the above)

**Current behavior**
The `rust` matrix entry executes `checks: check:runner
check:api-authority` serially in one job (~328s in the check step,
~399s–454s total job duration).

**Proposed behavior**
Run `check:runner` in the `rust` lane (which remains the sole Rust cache
writer) and run `check:api-authority` concurrently in a dedicated
`api-authority` lane that restores the same `release-runner-v2` Rust
cache.

**Reason and benefit**
Removes ~92s of serial wall-clock time from `Verify Paperclip Runner
(rust)` with identical check coverage (`check:all-without-vitest` stays
exact and complete).

**Breaking changes**
None. All checks in `check:all-without-vitest` remain required before
verification passes.

## What Changed

- Split `checks: check:runner check:api-authority` in
`.github/workflows/release-verify.yml` into `lane: rust` (`checks:
check:runner`) and `lane: api-authority` (`checks:
check:api-authority`).
- Updated `.github/scripts/tests/release-runner-cache.test.mjs` to
verify `api-authority` restores the shared Rust cache without writing it
and preserves complete `check:all-without-vitest` coverage.

## Verification

- `node --test .github/scripts/tests/release-runner-cache.test.mjs
scripts/__tests__/release-verify-workflow.test.mjs
.github/scripts/tests/cloud-readiness.test.mjs` (80/80 passed).

## Risks

- Low risk. No production code, schema, or test assertions change;
`rust` remains the sole cache writer (`save-if: matrix.lane == 'rust'`),
and `release-verify-workflow.test.mjs` enforces exact
`check:all-without-vitest` coverage.

## Model Used

- Google Gemini 3.1 Pro (thinking mode, 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
2026-11-25 11:23:04 -06:00
DottaandPaperclip 1f56bfb690 Expand release-verify serialized server tests from 5 to 9 shards (#22946)
## Thinking Path
> Release verification in `.github/workflows/release-verify.yml` runs
`serialized_tests` on 5 shards while PR verification runs the same suite
on 9 shards. Expanding `serialized_tests` to 9 shards matches PR CI
shard balance and shortens the non-oversized serialized shards on
post-merge verification.

## Summary
- Expand the `serialized_tests` matrix in
`.github/workflows/release-verify.yml` from 5 shards (`shard_index`
`0..4`, `shard_count: 5`) to 9 shards (`shard_index` `0..8`,
`shard_count: 9`), matching PR verification.
- Tighten the workflow unit test in
`scripts/__tests__/release-verify-workflow.test.mjs` so it scopes its
check specifically to the `serialized_tests` job block and asserts every
`(shard_index, shard_count, shard_label)` entry from `0..8`.

## Verification
- `node --test scripts/__tests__/release-verify-workflow.test.mjs
.github/scripts/tests/cloud-readiness.test.mjs` (76/76 passed).

## Model Used
Gemini 3.1 Pro

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-25 11:22:59 -06:00
DottaandPaperclip 3b3c6e4f5f ci: pre-warm base image layers during docker build for PID 1 probe (#22945)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Master Docker image publication in `.github/workflows/docker.yml`
verifies that PID 1 reaps orphaned processes on the exact pushed digest
(`docker run --pull always "$IMAGE_NAME@$IMAGE_DIGEST"`)
> - Because `Build and push by digest` runs inside BuildKit
(`docker-container` driver) on a fresh runner, the local Docker daemon
starts empty and the PID 1 probe spends ~2m 50s–3m 06s downloading and
extracting unchanged base layers before running the 8-second probe
> - Pre-warming the local Docker daemon in the background from the
newest already-published ancestor master image while Buildx builds and
pushes hides ~2+ minutes of layer download and extraction behind the 4–5
minute build
> - This pull request adds `scripts/docker-pid1-prewarm.sh`
(`start`/`stop`) and wires it into `build-and-push` on AWS master pushes
without changing BuildKit, image digests, or the `--pull always`
verification check
> - The benefit is cutting ~2+ minutes off master image publication on
both `amd64` and `arm64` legs while preserving every provenance and PID
1 safety check

## Linked Issues or Issue Description

**What existing behavior does this improve?**
The `Verify PID 1 reaps orphaned processes` step in
`.github/workflows/docker.yml` (`build-and-push`).

**Subsystem affected**
Cross-cutting (multiple of the above)

**Current behavior**
After `Build and push by digest` pushes the new digest from BuildKit to
GHCR, `Verify PID 1 reaps orphaned processes` runs `docker run --rm -i
--pull always "$IMAGE_NAME@$IMAGE_DIGEST"` on an empty local Docker
daemon, spending ~2m 50s–3m 06s downloading and extracting unchanged
base layers before running the 8-second orphan-reaping script.

**Proposed behavior**
On canonical AWS master pushes (when not promoting a merge-queue image),
`docker.yml` starts a non-blocking background `docker pull` of the
newest published ancestor master image (checking `HEAD~1`..`HEAD~10`
with `docker manifest inspect`) right before `Build and push by digest`.
Before `docker run --pull always` (and in an `if: always()` cleanup
step), `scripts/docker-pid1-prewarm.sh stop` waits briefly or stops the
background `docker pull` process cleanly.

**Reason and benefit**
Hides ~2+ minutes of base-layer download and extraction behind `Build
and push by digest` on both `amd64` and `arm64`, speeding up master
Docker image publication while still verifying the exact pushed digest
from GHCR.

**Breaking changes**
None. BuildKit inputs, image digests, and the `--pull always
"$IMAGE_NAME@$IMAGE_DIGEST"` probe are unchanged.

## What Changed

- Added `scripts/docker-pid1-prewarm.sh` with `start` (finds newest
published `HEAD~1`..`HEAD~10` `:sha-<commit>` image via `docker manifest
inspect` and starts a detached background `docker pull --quiet
--platform "$PLATFORM"`) and `stop [wait_seconds]` (verifies the
recorded PID is still a `docker pull` process via `ps -o args=`, waits
up to `wait_seconds`, stops it if still running, and removes the
pidfile).
- Wired `Pre-warm base layers for PID 1 probe` (`timeout-minutes: 1`,
`continue-on-error: true`, gated on `CORE_RELEASE_AWS_ENABLED == 'true'`
canonical master pushes with `steps.promote.outputs.digest == ''`),
`stop 15` before the PID 1 probe, and `stop 0` in an `if: always()`
cleanup step in `.github/workflows/docker.yml`.
- Added `.github/scripts/tests/docker-pid1-prewarm.test.mjs` testing
workflow gating/ordering and executing `scripts/docker-pid1-prewarm.sh`
with fake `git`/`docker` binaries across ancestor discovery, clean skip,
non-docker PID protection, and active-process termination.

## Verification

- `node --test .github/scripts/tests/docker-pid1-prewarm.test.mjs
scripts/merge-group-image.test.mjs
.github/scripts/tests/cloud-readiness.test.mjs
.github/scripts/tests/docker-canary-promotion.test.mjs
.github/scripts/tests/post-merge-runner-routing.test.mjs
scripts/docker-image-metadata.test.mjs` — all tests passed (14/14 in
`docker-pid1-prewarm` + `merge-group-image`; 361/361 across the full
docker/readiness workflow suite).

## Risks

- Low risk: pre-warm is gated to the spacious AWS release fleet
(`CORE_RELEASE_AWS_ENABLED == 'true'`), bounded to 1 minute with
`continue-on-error: true`, verifies process command arguments before
signaling any PID, and never modifies BuildKit or weakens `docker run
--pull always "$IMAGE_NAME@$IMAGE_DIGEST"`.

## Model Used

- Google Gemini (Antigravity agent, high reasoning, 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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-25 11:22:52 -06:00
Nicky LeachandClaude Opus 5.5 9f570837cb perf(runner): commit each provider batch with one durable save (#22829)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - `paperclip-runnerd` delivers provider output to the controller
through a durable outbox in `runner-state.json`
> - Each save rewrites the whole state, then syncs the file and its
directory
> - runnerd saved once for every provider event in a poll, so a burst of
k events paid k saves before any of them could leave
> - #20217 made the provider state save once per poll. runnerd's own
outbox still saved once per event
> - This pull request commits each polled batch with one save
> - The benefit is fewer syncs and full-state rewrites whenever events
arrive together, on every disk, with no change to what recovery can
replay

## Linked Issues or Issue Description

Refs #20217 (the same change for the provider state file)
Related: #17514 (closed; the same per-event rewrite on the controller
side)

**What existing behavior does this improve?**

runnerd's commit of provider events into its durable outbox.

**Subsystem affected**

Paperclip Runner
(`packages/paperclip-runner/runner/crates/runner-core/src/durable`).

**Current behavior**

`commit_executor_events` saves the full durable state once for each new
event in a poll. A poll that returns k events costs k saves before the
provider can release them. Each save writes the full state and calls
`fsync` twice.

**Proposed behavior**

runnerd adds a polled batch (up to 128 events) to the outbox in memory.
Then it saves once, and then it acknowledges the batch to the provider.
A poll that returns k events costs one save.

**Reason and benefit**

Every save is a full rewrite and two syncs, so the save count sets the
cost of durable delivery. On a local macOS APFS disk, one save takes
about 10 ms. With 8 events per round, the cost drops from about 10.7 ms
to about 2.4 ms per event. The change helps on any storage. It does not
change what recovery can replay.

**Breaking changes**

None. The state file format does not change. Older and newer Runners
read the same file.

## What Changed

- `commit_executor_events` (group commit):
- It adds each polled batch to the outbox and saves once. Only then does
it acknowledge the batch to the provider.
- The batch stays at 128 events, below the 256-receipt window. A crash
between the save and the provider acknowledgement still replays every
retained event exactly.
- If an event is rejected (oversized, or over capacity), runnerd still
saves and acknowledges the events before it. The provider keeps the
rejected event and everything after it, as before.
- If the save fails, runnerd acknowledges nothing. The provider keeps
the whole batch.
- Cumulative ACK persistence does not change. runnerd saves when an ACK
empties the outbox, and after every 16 advances.
- `DurableStateStore` counts saves in test builds only.
- `DURABLE_TRANSPORT.md` describes the batch commit.

An earlier revision of this pull request also let an outbox-emptying ACK
wait for the next save. It was removed. Recovery treats an empty outbox
on disk as fully delivered. `runnerd-acpx-source-reconciliation.test.ts`
showed that a Runner stopped shortly after a completed run then started
its provider once more on recovery.

## Verification

- `cargo test -p paperclip-runner-core --lib durable::`: 136 pass,
including 2 new tests in `src/durable/tests/batched_saves.rs`:
- `provider_batch_commits_with_one_durable_save`: batches of 8 and 48
events each need one save. The reloaded file holds every event.
- `a_streamed_round_saves_its_batch_once_and_its_emptying_ack_once`: 10
rounds of 1 or 8 events need 20 saves either way. The reloaded file has
an empty outbox.
- Existing tests that cover the accepted prefix, a failed save,
backpressure, and receipts pass unchanged:
  - `event_batch_acknowledges_only_bounded_durable_prefixes`
  - `event_batch_never_acknowledges_a_failed_durable_save`
-
`disconnected_ingestion_keeps_durable_prefix_and_resumes_after_backpressure_ack`
  - `receipt_survives_outbox_ack_and_prevents_duplicate_delivery`
- `cargo test -p paperclip-runner-core --test durable_recovery --test
acpx_park_preparation --test acpx_park_readiness --test
acpx_provider_suspend --test acpx_warm_attachment`: all pass.
- With a freshly built runnerd: `vitest run
src/live/runnerd-acpx-source-reconciliation.test.ts` (17 pass) and
`vitest run src/live/runnerd-codex-transport.test.ts -t "replaces an
owned v1 runner with fresh v2 authorization"` (pass).
- `cargo fmt --all -- --check`: clean.
- Local measurement: a release build on macOS APFS, 200 events of
`item.delta`, not committed.

| Events per round | Saves before | Saves after | Time before | Time
after |
| --- | --- | --- | --- | --- |
| 1 | 400 | 400 | 3.9 s | 3.8 s |
| 8 | 225 | 50 | 2.1 s | 0.49 s |

## Risks

- Low risk. The file holds the same data after each batch as before.
Only the number of intermediate saves changes.
- A failed save inside a batch leaves the in-memory state ahead of the
file, as a failed per-event save did before. The error stops the loop,
as before.
- The provider state file (ACPX, Codex and others) keeps its own save
policy. This change touches only runnerd's state file.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, through Claude Code
with tool use (shell, file editing, 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
- [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-25 09:17:12 -08:00
Nicky LeachandClaude Opus 5.5 0175300a48 perf(runner): save ACPX provider state once per poll instead of once per output (#22840)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - ACPX chat turns (Claude, Codex, and the other ACP agents) run
through runnerd. runnerd reads the ACPX sidecar output in order and
keeps the run's provider state in a durable file
> - For each sidecar output that it read, runnerd rewrote the full
provider state file. Each save did a JSON rewrite, a file `fsync`, a
rename, and a directory `fsync`
> - runnerd reads the sidecar again only after the controller
acknowledges the events that it sent. Streamed text collects in the
sidecar pipe during that round trip, so one poll usually reads several
outputs
> - #20217 made the Codex provider save once per poll. ACPX still saved
once per output
> - This pull request makes the ACPX executor save the outputs of one
poll once, before anything that depends on them leaves the executor
> - The benefit is fewer full state rewrites and `fsync` pairs during a
streamed turn, on any disk. In a replay of a real Claude stream, runnerd
made 49% fewer ACPX state saves

## Linked Issues or Issue Description

Refs #20217 (the same change for the Codex provider)
Related: #22829 (the same change for runnerd's own state file)
Related: #16817 (a broader change. It also merges text deltas into fewer
events, changes the sidecar contract, and records expired tool results.
This pull request changes only when the ACPX executor saves, and does
not change the event stream or the contract.)

**What existing behavior does this improve?**

The number of durable ACPX provider state saves during a streamed turn.

**Subsystem affected**

Runner (`paperclip-runner-core`, ACPX provider backend).

**Current behavior**

`poll_provider_events` calls `save_state` after each sidecar output that
returns events. One ACP update, for example one streamed text chunk,
becomes one sidecar output. Each save rewrites the full
`acpx-provider-state.json` file and does two `fsync` calls.

**Proposed behavior**

The executor keeps the effects of ordinary outputs in memory and saves
them once at the end of the poll. Outputs that drive an effect outside
the stream save at once, as before.

**Reason and benefit**

The save count during a streamed turn no longer grows with the number of
chunks in a poll. This removes disk writes and `fsync` calls on every
platform.

**Breaking changes**

None. The state file format does not change.

## What Changed

- The ACPX executor marks state as unsaved after an ordinary sidecar
output. It saves once when the poll ends, also when the poll stops with
an error. A poll returns events only after that save, so no event,
command result, or reply to the sidecar leaves before the state that it
depends on is on disk.
- Each unsaved output still applies the state transition that a save
applies (`leave_finished_provider_turn_wait`). The order of the events
does not change.
- These outputs still save at once: a turn terminal, a tool call, a lost
provider turn, and a provider transport failure. The goal read at a
terminal keeps its own save.
- The session holds a tool rejection that it sends to the sidecar inside
`poll_output` (the "too many tool calls in flight" case). The executor
saves the outputs read before the rejection, then sends it.
- The event acknowledgement (`acknowledge_events`) still saves at once.
Recovery reads an empty queue on disk as fully delivered, so that save
must not wait.
- The transport-failure handling moves into one helper,
`fail_polled_provider`. The poll loop and the held-rejection path both
use it.
- `runner/DURABLE_TRANSPORT.md` now describes when the ACPX executor
saves.

## Verification

Measurement (macOS, APFS, debug runnerd). I recorded the arrival times
of one real Claude ACP turn from `claude-agent-acp` (323 updates in 15.4
s, median gap 33 ms). A temporary build of the fake sidecar replayed
that timing in `runnerd-acpx-source-reconciliation.test.ts` ("claude"
case, two turns). That test runs a real runnerd against the in-process
controller. Temporary counters in the backend recorded the outputs per
poll and each state save. These counters are not in this pull request.

| | Polls with output | Outputs per poll (mean) | ACPX state saves |
Time in saves |
| --- | --- | --- | --- | --- |
| Before | 84 | 7.7 | 749 | 8.1 s |
| After | 182 | 3.6 | 379 | 4.3 s |

- One save took about 10 ms (median) in both runs.
- Before the change, 642 of 650 outputs came in polls with more than one
output.
- After the change, the remaining saves are about one per poll plus one
per acknowledgement. Polls come more often because each cycle spends
less time in saves.

Tests:

- New lib tests in `src/tests/acpx_poll_state_saves.rs`:
- 48 outputs in one poll need one state write. The file on disk then
equals the state in memory.
- Polled outputs survive a restart once: a new executor retains exactly
the unacknowledged suffix, with no duplicate event ids.
  - An output that ends the turn, or calls a tool, is saved at once.
- The sidecar receives a held tool rejection only after the outputs read
before it are on disk.
- With the old per-output save restored, the tests fail with 48, 26, and
21 writes. Without the hold, the rejection test fails.
- `cargo test -p paperclip-runner-core --lib acpx` (122 passed) and
`--lib durable` (162 passed).
- `cargo test -p paperclip-runner-core --test acpx_park_preparation
--test acpx_park_readiness --test acpx_warm_attachment --test
durable_recovery` (47, 8, 7, 4 passed).
- `cargo test -p paperclip-runner-core --test acpx_provider_session
--test acpx_provider_turns --test acpx_quiet_turn_continuation --test
acpx_provider_resolutions` (13, 31, 14, 12 passed).
- With a freshly built runnerd: `vitest run
src/live/runnerd-acpx-source-reconciliation.test.ts` (17 passed).
- `cargo fmt --check` is clean. `cargo clippy` shows no new warnings in
the changed files.
- I did not run `pnpm verify` or the full Rust suite locally. CI
supplies that coverage.

## Risks

- Crash window: if runnerd stops before the end-of-poll save, it loses
the unsaved outputs of that poll. Nothing derived from them has left the
executor, so recovery is the same as a stop before runnerd read them.
Turn terminals, tool calls, lost provider turns, and failures keep their
immediate save.
- The executor adds no save to `retained_events`, `execute`,
`host_park_ready`, or `prepare_for_park`. Unsaved state does not outlive
one poll call. If the end-of-poll save fails, the existing persistence
latch blocks all later work.
- A held tool rejection reaches the sidecar after one more state save.
Its order relative to other sidecar requests does not change.
- Low risk overall. The state file format and the acknowledgement path
do not change.

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

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, through Claude Code
with tool use (shell, file edits, local builds and tests).

## Checklist

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

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

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 09:16:32 -08:00
DottaandClaude Opus 5.5 a0d5f275af test(e2e): grade the question journey's saved reference by its complete token (#22949)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The daily QA staging smoke runs the `question-answer-resume` product
journey against a real agent
> - The board answers the agent's reference question with the text `Use
<marker>.`
> - The grader required the literal text `Use <marker>.` in the saved
note
> - Agents read `Use X.` as an instruction. Some save `Use X.`, others
save only `X`. Both notes are correct
> - This pull request grades the saved note by the complete marker
token, not by the answer's instruction wording
> - The benefit is that the smoke case no longer fails at random on a
correct note

## Linked Issues or Issue Description

**Describe the bug**
The QA staging smoke case `question-answer-resume` failed with
`journey_operation_failed`. The failed checks were
`question-resume.complete-evidence` and `question-document-reloaded`.

**Steps to reproduce**
1. Run the QA staging smoke journeys (full run on 2026-11-25).
2. The agent asks for a reference. The board answers `Use
AMBERjourney179560441987913f9fa70.`
3. The agent saves `Welcome to the club meetup this afternoon — we're
glad you're here; reference: AMBERjourney179560441987913f9fa70.`
4. The grader fails the note because it does not contain the word `Use`.

**Expected behavior**
A note that contains the complete submitted reference and the selected
time passes. A second campaign on the same day passed only because that
agent kept `Use` in the note.

**Additional context**
The private record also showed 4 `Invalid JSON body` responses. They
come from one failed `POST /api/issues/{id}/interactions` call that the
agent made itself, before it retried with a valid body and got 201. That
call is not the cause of the failure. The journey and the server route
are correct.

## What Changed

- Add `includesSubmittedReference` in
`tests/runner-e2e/question-resume-scoring.ts`. It matches the complete
marker token with no extra letters or digits on either side.
- Use it in `question-resume.complete-evidence` and in
`question-document-reloaded`.
- `waitForClarificationDocument` waits for the complete marker
(`submittedReferencePattern`), not for `Use <marker>.`. Before, a
correct note without `Use` timed out in the browser readback.
- Change the old unit test that rejected a note with only the marker. It
now accepts that note. New cases reject a shortened marker, an extended
marker, and a prefixed marker.

## Verification

- Red: the new cases failed on the old grader (3 failed, 144 passed).
The new readback case timed out on the old wait (1 failed, 3 passed).
- Green: `pnpm exec vitest run --config
tests/runner-e2e/vitest.config.ts` on the question-resume,
clarification, and question-documentation tests: 6 files, 170 tests
pass.
- `pnpm test:e2e:runner:typecheck` passes.
- After merge: a single-case `qa-staging-smoke.yml` run for
`question-answer-resume` on the new harness pin.

## Risks

Low risk. Test code only. The grader still requires the full marker. The
marker is a unique nonce, so a truncated or changed reference still
fails.

## 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>
canary/v2026.1125.0-canary.861100
2026-11-25 11:09:02 -06:00
DottaandClaude Opus 5.5 0609da79fb fix(skills): let a blocked failed run stop pinning its skill versions (#22950)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Company skills have saved versions. Runs pin the exact versions that
they use, and the skill cache keeps those files while a run can still
need them.
> - The same check also blocks skill deletion: "an active or recovering
run may still need it".
> - The check treats every native run whose finalization is not
`committed` as live. A run that ended in `terminal_failure` with
`recovery_state = 'blocked'` is a recorded dead end. Retry and fresh
continuation start new runs that select skills again.
> - So one failed run blocks deletion of its skills, and the eviction of
their cached files, for ever.
> - This pull request lets a blocked failed run release its pins. A
same-run resume, a scheduled attempt, or a lease holder still keeps
them.
> - The benefit is that people (and automated clean-up) can delete a
skill after a run that used it failed.

## Linked Issues or Issue Description

No public issue exists. Bug description:

**What happened?**
A skill that a failed native run used cannot be deleted. `DELETE
/api/companies/:companyId/skills/:skillId` returns 422 "Cannot delete
skill ... while an active or recovering run may still need it." On a
long-lived QA instance, 11 test skills from Nov 5 to Nov 15 are still
refused today. Each one belongs to a run with status `failed`, native
phase `terminal_failure`, released environment leases, and no active
recovery action.

**Expected behavior**
After a failed run is settled and nothing will resume it in place, the
run must not keep its skill versions. Deletion must succeed.

**Steps to reproduce**
1. Run an agent with a company skill. Let the native run fail so that
its finalization is `terminal_failure` with `recovery_state = 'blocked'`
(for example `native_continuation_requires_reconciliation`).
2. Let its environment lease release and its recovery action resolve.
3. Delete the skill. The server refuses with 422 for ever.

**Paperclip version or commit**
master at 5a683696eb.

## What Changed

- `skillRunNeedsFilesSql`
(`server/src/services/skill-version-cache.ts`): a finalization in
`terminal_failure` with `recovery_state = 'blocked'`, no `lease_owner`,
no `next_attempt_at`, and no active or escalated `resume_native_run`
recovery action for that run no longer counts as a run that needs skill
files. All other finalization states keep their current behavior. This
applies through an opt-in flag that only `protectedVersions` uses, so it
covers skill deletion and version-cache eviction. Runtime asset
preservation and retention share the predicate but keep their current,
broader retention.
- The recovery-action lookup is scoped to the run's issue, so it uses
the partial unique index of active actions per issue.
- Tests: a new red/green test covers the blocked failed run and each
case that must still protect its pins (active resume, scheduled attempt,
lease holder). The legacy-pin test fixture now records an active
same-run resume, so those tests still exercise legacy pin parsing on a
run that is truly recoverable.

## Verification

- Red: the new test fails on master with the same 422 that the QA
instance returns.
- Green: `npx vitest run src/__tests__/skill-version-cache.test.ts`
passes 45/45, including the existing test that a `terminal_failure`
without a blocked recovery state keeps its pins.
- `runtime-skill-preservation.test.ts` and
`ephemeral-server-runtime-skill-startup.test.ts` pass unchanged (66/66
across the three files).
- `npx tsc --noEmit -p server` passes.
- After deployment: the QA smoke clean-up for the `saved-skill-use` case
must delete the old leftover skills.

## Risks

- Low risk. The change only releases pins for runs that the server
already recorded as blocked and with no resume scheduled. If a new
same-run resume path appears later without a `resume_native_run` action,
`next_attempt_at`, or a lease owner, it would not find these files. Such
a resume already reports a clear "saved skill could not be prepared"
error instead of running with wrong files.
- No schema or migration change.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Claude Code with tool use (shell,
browser read of the QA instance API).

## 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-25 11:05:40 -06:00
DottaandClaude Opus 5.5 1fa6d71171 fix(connections): clear run answer copies and show reconnect state when Google access ends (#22937)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Agents use Google Workspace through a connection, and Paperclip
saves what they read in runs and tool-call records
> - Google's Workspace AI Tools Addendum says Paperclip must keep no
user data from a connection after access ends. #22836 and #22842 delete
this content when access ends.
> - A live test found two gaps. The run record still holds the run's
final answer and its evidence (a Drive link, text from a Drive file).
And after a person removes Paperclip at their Google Account, the
connection still shows as healthy and agents still get its tools.
> - This pull request clears the answer and evidence copies in the run
record, and puts the connection in the existing "sign in again" state
when no grant on it is active.
> - The benefit is that no Google data stays in run records after
deletion, and people and agents see that the connection must be signed
in again.

## Linked Issues or Issue Description

Refs #22836

**What happened?**

1. After `tool_connection.content_deleted`, `GET
/api/heartbeat-runs/:id` still returned Google data. The data was in
`resultJson.nativeResult.evidence[].ref`, `verification[].detail` and
`commandOrCheck`, `completionClaim.criteria[].evidenceRefs[]`, and in
`runnerProfileJson.sessionCheckpoint` (`semanticResult` and
`terminalTurns[].fingerprint`, a 1.3 to 1.9 KB copy of the result).
2. After a person removed Paperclip at their Google Account, the next
Google call failed with `oauth_reauthorization_required` and the
deletion started with reason `provider_access_ended`. But the connection
status stayed `active` with healthy status, and agents were still
offered its 34 tools.

**What did you expect to happen?**

1. The deletion clears the run's answer and evidence copies the same way
it clears the transcript. The run keeps its status, ids, counts and
hashes, so the run page still shows.
2. The connection shows that it needs a new sign-in, and agents do not
get its tools until someone reconnects.

**Steps to reproduce**

1. Connect Google Workspace and let an agent run that reads a Drive file
and reports a link as evidence.
2. Remove the connection (or remove Paperclip at the Google Account and
let the next Google call fail).
3. Wait for `tool_connection.content_deleted`.
4. Open `GET /api/heartbeat-runs/:id` for that run. See the Drive link
in `resultJson.nativeResult` and in
`runnerProfileJson.sessionCheckpoint`.
5. For case 2, open the connection. See status `active` and health `ok`.
List the agent's tools. See the Google tools.

## What Changed

- `content-cleaning.ts`: add `withoutRunAnswers`. In every
`paperclip.run_result.v1` object in `result_json` (`nativeResult`,
`acceptedResult`, `semanticResult.result`), each free-text string
becomes the fixed text "Removed because the connection data was
deleted.", so the result still passes `validatePrpStructuredRunResult`.
Structural fields stay (schema, disposition, status, scope, reason
codes, Paperclip ids, booleans and numbers). Agent-chosen
`idempotencyKey` values become `sha256:` hashes.
- `content-cleaning.ts`: add `withoutCheckpointAnswers`. It cleans the
persisted checkpoint (`PersistedNativeSession`): `semanticResult` and
`governedWait.result` the same way, `governedWait.sourceEvent.payload`
free text, and each `terminalTurns[]` fingerprint becomes its `sha256:`
hash. The recovery hash is updated when it matched.
- Each store gets its own mark: `result_json.answerCopiesDeletedAt` and
`sessionCheckpoint.contentDeletedAt`. A run in scope whose result or
checkpoint lacks its mark is cleaned again. This fixes runs cleaned by
an older build and a checkpoint rewritten later.
- `paperclip-control-plane-port.ts`: a checkpoint written for a run
whose result has `contentDeletedAt` is cleaned before it is saved
(`checkpointProfileForRun`).
- `withoutResultText` no longer blanks fields inside a run result;
`withoutRunAnswers` owns those.
- `withoutFreeText` moves from `run-copies.ts` to `content-cleaning.ts`;
`native_run_results` gets the same treatment.
- The task text stays: `contextSnapshot.paperclipIssue.description` and
`runnerProfileJson.nativeExecutionInput.task` are the user's text, not
Google data.
- `grant-refresh.ts`: when a refresh marks a grant
`needs_reauthorization` and no grant on the connection is still active,
the connection gets the needs-attention state: health `error`, last
error `oauth_reauthorization_required`, message "Access to this app
ended. Reconnect to continue." The check and the write run under a row
lock on the connection, so a reconnect that finishes at the same time is
not overwritten. This applies to the Paperclip Cloud broker path and to
the direct token path for personal grants. Status and the enabled flag
do not change, so the app list shows "Needs attention" (not "Paused"),
and a reconnect keeps the chosen tools.
- `tool-gateway.ts`: agents are not offered a connection's tools (tool
list, tool search, and the prompt guidance for usable connections) while
the connection has a `needs_reauthorization` grant and no active grant.
An action that a person already approved still finds its tool and waits
for the new sign-in, as before.
- Plain copy: "OAuth authorization expired/has expired" becomes "Access
to this app ended. Reconnect to continue." in `connection-refresh.ts`,
`grant-refresh.ts`, `catalog/failures.ts` and `oauth/client.ts`.
- UI (`Connections.tsx`, `Browse.tsx`): the removal message and dialog
count a connection as "available to agents" only when agents are offered
its tools: it is on, it is not waiting for a new sign-in, and it is
healthy, personal or a plugin. New helper
`isConnectionAvailableToAgents` in `connection-identity.ts`.
- Docs: the inventory and access-end notes in
`doc/memory/google-connector-memory.md`, and the help page
`docs/guides/board-operator/deleting-connection-data.md`.

## Verification

- Red/green:
`server/src/__tests__/tool-connection-content-deletion.test.ts`,
"removes the run's final answer and evidence from its result and session
checkpoint, and keeps the task text". It failed before the fix (the
Drive link and quoted text stayed in `nativeResult`) and passes after.
It also checks that a run cleaned by an older build is cleaned again,
that the task text stays, that `hasAcceptedSemanticResult` is still
true, and that the recovery hash matches the new checkpoint.
- Red/green:
`server/src/__tests__/google-managed-connection-removal.test.ts`, "shows
a user/organization connection needs signing in again and stops offering
its tools after Google access ends". Before the fix, health stayed `ok`.
After the fix, health is `error`, the agent's tool list for the
connection is empty, and after a reconnect health is `ok` and the tool
comes back.
- The deletion test checks that the fixture result is valid and that the
cleaned `nativeResult` and checkpoint `semanticResult` still pass
`validatePrpStructuredRunResult`. It rewrites a dirty checkpoint on a
cleaned run and checks that the next deletion cleans it, and checks
`checkpointProfileForRun`. It uses the persisted checkpoint shape
(`semanticResult` is the run result, plus `governedWait`). A second
phase stores a legacy run (no `answerCopiesDeletedAt` mark) whose only
remaining text is `nativeResult.evidence[].ref` and the checkpoint
copies, with hashed fingerprints and blank summaries. The new selection
rule cleans it.
- `tool-access-oauth-protocol.integration.test.ts` still passes: an
approved action waits for sign-in and runs after reconnect. Its fixture
now also restores the health fields when it restores the connection by
hand.
- `ui/src/pages/apps/connection-identity.test.ts`: the new helper does
not count a connection that needs attention.
- Agents in the needs-attention state: the provider-ended test lists the
agent's tools before (1), after Google access ends (0) and after
reconnect (1). So agents are not offered the actions of a connection in
that state.
- On the final code: deletion, removal and OAuth protocol files 77/77;
`paperclip-control-plane-port.test.ts` 108/108; deletion and
reauthorization cases in `tool-access-service.test.ts` 9/9; UI helper
test 12/12. Server and UI typecheck pass.
- `tsc --noEmit` for `server`: pass.
- `pnpm verify`: see the comment below for the result.

## Risks

- Medium-low. The tool gateway now hides a connection's tools from
discovery when it has a `needs_reauthorization` grant and no active
grant. Before, a personal (`per_user`) connection in that state still
listed its tools, and each call failed. Execution of an already approved
action is not changed. Connections with no grants, or with one active
grant, do not change.
- Health `error` is set for any provider whose last active grant needs a
new sign-in, not only Google. This is the same state a direct token
refresh already uses.
- No schema change and no migration.
- Not covered: the encrypted controller checkpoint rows
(`native_runner_checkpoints`). The harness backup expiration removes
them. This is recorded in the memory doc.

## 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>
canary/v2026.1125.0-canary.860900
2026-11-25 10:31:28 -06:00
Dotta 8fabcfff30 Split oversized native-runtime integration tests for file-parallel CI (#22948)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The native-runtime integration test lane
(`general-server-native-runner`) runs real-process Vitest suites with
file parallelism enabled.
> - Three oversized files (`plugin-runner-eviction.integration.test.ts`
at 307s, `plugin-runner-release-resume.integration.test.ts` at 200s, and
`native-runner-restart-diskless.integration.test.ts` at 191s) exceed the
180s per-file budget and bound the entire lane wall-clock time because
shards cannot split a single file.
> - Each file runs parameterized test matrices serially inside one
Vitest worker while other workers sit idle.
> - This pull request moves each suite body into a shared helper under
`server/src/__tests__/helpers/` and splits the parameterized cases
across focused `.integration.test.ts` entrypoints, updating the suite
list, nightly manifest, duration manifest, and shard tests.
> - The benefit is cutting `Verify Paperclip Runner (vitest native
server)` wall-clock time from ~461s down to ~157s while keeping
identical test cases and assertions.

## Linked Issues or Issue Description

**What existing behavior does this improve?**
Execution time of the `general-server-native-runner` Vitest lane in PR
and release verification workflows.

**Subsystem affected**
server/ — REST API & orchestration services

**Current behavior**
Three parameterized integration test files exceed the 180s
`PAPERCLIP_CI_OVERSIZED_TEST_FILE_SECONDS` budget
(`plugin-runner-eviction.integration.test.ts` takes 307s,
`plugin-runner-release-resume.integration.test.ts` takes 200s, and
`native-runner-restart-diskless.integration.test.ts` takes 191s).
Because Vitest parallelizes across files, the slowest single file bounds
the entire lane to ~461s total job time.

**Proposed behavior**
Extract each suite body into `server/src/__tests__/helpers/` and run
disjoint slices of the exact same parameterized cases across focused
`.integration.test.ts` files so Vitest fork workers execute them
concurrently.

**Reason and benefit**
Cuts the `Verify Paperclip Runner (server-integration)` / `vitest native
server` CI lane by roughly 5 minutes (461s -> 157s measured in CI) with
zero change to test logic, timeouts, or assertions.

**Breaking changes**
None. All existing test cases remain covered in the same
`general-server-native-runner` group.

## What Changed

- Extracted `server/src/__tests__/helpers/plugin-runner-eviction.ts` and
split its 42 cases across 4 entrypoints by `(codex | claude) x (retired
| abrupt)`:
-
`server/src/services/native-runtime/plugin-runner-eviction-codex-retired.integration.test.ts`
(11 cases)
-
`server/src/services/native-runtime/plugin-runner-eviction-codex-abrupt.integration.test.ts`
(10 cases)
-
`server/src/services/native-runtime/plugin-runner-eviction-claude-retired.integration.test.ts`
(11 cases)
-
`server/src/services/native-runtime/plugin-runner-eviction-claude-abrupt.integration.test.ts`
(10 cases)
- Extracted
`server/src/__tests__/helpers/plugin-runner-release-resume.ts` and split
its 19 cases across 2 entrypoints:
-
`server/src/services/native-runtime/plugin-runner-release-resume-cached.integration.test.ts`
(8 cases)
-
`server/src/services/native-runtime/plugin-runner-release-resume-adopted.integration.test.ts`
(11 cases)
- Extracted
`server/src/__tests__/helpers/native-runner-restart-diskless.ts` and
split its 2 cases across 2 entrypoints with isolated embedded Postgres
comments:
-
`server/src/services/native-runtime/native-runner-restart-diskless-direct.integration.test.ts`
(`preparedTask: false`)
-
`server/src/services/native-runtime/native-runner-restart-diskless-prepared-task.integration.test.ts`
(`preparedTask: true`)
- Updated `scripts/run-vitest-stable.mjs`,
`scripts/ci/nightly-only-suites.json`,
`scripts/general-server-shard-durations.json`, and
`scripts/__tests__/run-vitest-stable-shard.test.mjs` to register the
split files and remove the three replaced paths.

## Verification

- `node --test scripts/check-test-budget.test.mjs
scripts/__tests__/run-vitest-stable-shard.test.mjs
scripts/__tests__/run-vitest-stable-pr-mode.test.mjs` (53/53 passed)
- `node scripts/check-test-budget.mjs --base origin/master` (passed)
- `ci / Verify Paperclip Runner (vitest native server)` passed in 157s
on this PR (down from 461s on master).

## Risks

- Low risk. Each entrypoint runs a disjoint, exhaustive slice of the
original parameterized matrix against the same helper implementation,
with no production code changes and no schema migrations.

## Model Used

- Google Gemini 3.1 Pro (thinking mode, 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
canary/v2026.1125.0-canary.860800
2026-11-25 10:27:26 -06:00
DottaandClaude Opus 5.5 4285366e79 test(antigravity): prove positive run-start cases reach the coordinator claim with a strict DB fake (#22947)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Agents can run on the Google Antigravity harness, and run start has
a release gate for it
> - #22943 added run-start tests for that gate
> - Two positive cases only checked that the error was not the gate
error, so an unrelated early failure also passed
> - The fixture database returned itself for every method and an empty
result for every query, so the tests accepted any database access
> - This pull request makes each positive case prove that the run
reached the step after admission, and makes the fake database strict
> - The benefit is that a regression before the coordinator claim, or an
unexpected database call, now fails the tests

## Linked Issues or Issue Description

Refs #22943

**What happened?**
Two positive run-start cases in `antigravity-run-start.test.ts` passed
when the run failed for any reason other than the gate. The fixture
database in `antigravity.test-fixture.ts` silently accepted any call.

**What did you expect to happen?**
Each positive case proves that the run got past admission to a known
later step. The fake database rejects calls that the tests do not use.

**Steps to reproduce**
Add a temporary `throw` in `executePaperclipNativeSessionAttempt` just
before the coordinator claim. The old tests still pass (6 of 6).

## What Changed

- The granted Core sandbox case and the released plugin Runner-task case
now require the exact `native_finalization_coordinator_missing` error.
This error comes from the coordinator claim, which is after admission.
- Both cases also check the exact database reads: the coordinator lookup
and its locked re-read. The plugin case also checks the plugin lease
lookup before them.
- The older-profile case now checks that it is refused before any
database read.
- `emptyDb()` is now a typed fake. It supports only `select`, `from`,
`innerJoin`, `where`, `limit`, `for("update")`, `then`, and
`transaction`. It records each table read and throws a clear error for
any other method or lock mode.

## Verification

- `cd server && npx vitest run
src/services/native-runtime/antigravity-run-start.test.ts
src/services/native-runtime/antigravity-release.test.ts`: 16 of 16 pass.
- Red/green: with a temporary `throw` just before the coordinator claim,
the new tests fail in the two positive cases ("got
'fixture_break_before_coordinator_claim'"). The old tests pass with the
same break (6 of 6). The temporary change is not part of this PR.
- `cd server && npx tsc --noEmit -p .`: clean.

## Risks

- Low risk. This is a test-only change. No product code changes.
- If run start adds or reorders database reads, these tests fail and
need an update. That is intended.

## Model Used

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

## 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-25 09:48:56 -06:00