Commit Graph
3311 Commits
Author SHA1 Message Date
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
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
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>
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 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
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
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
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>
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
2026-11-25 10:27:26 -06:00
DottaandPaperclip c5107f12fe feat(runner): flip Google Antigravity ACPX profile to qualified (#22939)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Paperclip Runner executes native ACPX providers using
release-verified profiles, capability declarations, and provider packs
> - Google Antigravity is wired across Runner, server routes, UI
pickers, and remote provider packs, but its ACPX profile remained
`qualificationStatus: "pending"` behind operator candidate grants
> - The owner waived the paid-key `runner-e2e-paid` gate on 2026-11-25
so Google Antigravity can ship to staging and be tested there live
> - This pull request flips the Google Antigravity ACPX profile from
`pending` to `qualified` (profile revision 2), updates its capability
declaration while keeping `recovery: "unverified"`, enables ordinary
server/UI/pack admission without candidate grants, and updates tests and
qualification docs honestly
> - The benefit is that Google Antigravity enters the default
`linux-x64` remote provider pack and ordinary board setup/execution
flows on staging, while candidate-era v1 saved sessions are cleanly
rejected and unverified recovery/paid-key evidence remains honestly
labeled

## Linked Issues or Issue Description

Refs #22923
Refs #22935 (merge after #22935
`fix/per-turn-harness-on-warm-environment`)

**What existing behavior does this improve?**
Google Antigravity native ACPX profile qualification, remote
provider-pack assembly, and Paperclip Runner agent setup/admission
across `packages/paperclip-runner`, `packages/adapter-utils`,
`packages/adapters/codex-local`, `server`, `ui`, and `tests/runner-e2e`.

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

**Current behavior**
`packages/paperclip-runner/acpx-profiles.json` declares `antigravity` at
`agentProfileVersion: 1` with `qualificationStatus: "pending"`.
`PAPERCLIP_RUNNER_ACPX_PROFILES` marks `antigravity.qualified = false`,
remote `linux-x64` provider packs exclude Antigravity unless built with
`--candidate-providers=antigravity`, and server/Runner admission
requires a short-lived operator candidate grant.

**Proposed behavior**
Remove `qualificationStatus: "pending"` from `antigravity` and bump
`agentProfileVersion` from `1` to `2` so candidate-era v1 saved state is
refused permanently as `provider_state_incompatible`. Flip
`PAPERCLIP_RUNNER_ACPX_PROFILES.antigravity.qualified` to `true`, mark
`ACPX_CAPABILITY_PROFILES.antigravity` as `qualified` with `models:
"explicit-provider-verified"` while keeping `recovery: "unverified"`,
require an explicit provider model in config builders and server
validation, and admit qualified Antigravity through the ordinary ACPX
path without candidate grants.

**Reason and benefit**
Unblocks staging deployment and live testing of Google Antigravity under
the 2026-11-25 owner waiver of `runner-e2e-paid`, including default
`linux-x64` provider pack inclusion (local `darwin-arm64` continues to
use `paperclipai runtime setup antigravity`).

**Breaking changes**
Any candidate-era v1 Google Antigravity saved session state is
intentionally refused as `provider_state_incompatible` due to the
`agentProfileVersion` bump (`1` -> `2`).

## What Changed

- **Runner profile & generated contracts**:
- `packages/paperclip-runner/acpx-profiles.json`: removed
`qualificationStatus: "pending"` on `antigravity` and bumped
`agentProfileVersion` from `1` to `2`.
- Regenerated
`packages/paperclip-runner/src/drivers/acpx/generated-profiles.ts` and
`packages/paperclip-runner/runner/crates/runner-core/src/generated_acpx_profiles.rs`
(`qualification_pending: false`).
- `packages/paperclip-runner/src/drivers/acpx/capability-profiles.ts`:
set `antigravity.qualification` to `"qualified"` and `models` to
`"explicit-provider-verified"` when released; kept `recovery:
"unverified"` (never claiming `session-load` without live proof).
- **Adapter utils & config builder**:
- `packages/adapter-utils/src/paperclip-runner-permissions.ts`: flipped
`PAPERCLIP_RUNNER_ACPX_PROFILES.antigravity.qualified` to `true`.
- `packages/adapters/codex-local/src/ui/build-config.ts`: added
`"antigravity"` to the explicit-provider-model validation check.
- **Server admission & routes**:
- `server/src/services/native-runtime/provider-profile.ts`: added
`antigravity: null` to `DEFAULT_ACPX_RUNNER_MODELS`, included
`antigravity` in explicit-model-required and qualified ACPX checks.
- `server/src/services/native-runtime/acpx-qualification.ts`:
short-circuited `resolveAntigravityCandidateAdmission` to return
`undefined` once `qualificationStatus !== "pending"`.
- `server/src/routes/agents.ts`: allowed qualified `antigravity` without
`experimental.enableNativeRunner` (matching Copilot and UI rules),
preserved empty model on provisional setup draft transitions, and
allowed `setupOnly` draft creation before model selection.
- **Tests**:
- Updated Runner TS/Rust tests (`profile-compatibility.test.ts`,
`candidate-provider-pack.test.mjs`, `release-provider-pack.test.mjs`,
`antigravity-provider-pack-smoke.test.mjs`,
`candidate-admission*.test.ts`, `antigravity-models.test.ts`,
`acpx-runtime-sidecar.test.ts`, `runner-core` Rust unit/integration
tests).
- Updated `@paperclipai/adapter-utils`,
`@paperclipai/adapter-codex-local`, `@paperclipai/server`,
`@paperclipai/ui`, and `tests/runner-e2e` (`catalog.test.ts`,
`controller-rolling-deployment.test.ts`) tests for qualified Antigravity
behavior.
- **Documentation & maps**:
- `doc/plans/2026-11-22-antigravity-qualification.md`,
`doc/plans/2026-11-25-antigravity-cloud-rollout.md`, and
`packages/paperclip-runner/README.md`: recorded the 2026-11-25 owner
waiver of `runner-e2e-paid` for staging verification while keeping all
`NOT RUN` paid-key rows honestly marked `NOT RUN` / deferred.
- Minimal in-place accuracy updates in
`maps/feature-map/instance-operations.md` and
`maps/agent-access-map/instance-operations.md` (`node
scripts/check-maps.mjs` passing).

## Verification

- `pnpm --filter @paperclipai/paperclip-runner build` (TS + Rust release
binary + `check:acpx-profiles`, `generate-antigravity-models --check`,
`check:protocol-types`,
capability/attestation/traceability/replay-golden checks) — passed.
- `pnpm --filter @paperclipai/paperclip-runner test:typescript:prep`
(468 tests) and focused Runner Vitest suites
(`acpx-runtime-sidecar.test.ts` 127/127, `antigravity-models.test.ts`
22/22, `candidate-admission*.test.ts`, `profile-compatibility.test.ts`,
`runnerd-codex-transport-antigravity-release.test.ts`, pack script
tests) — passed.
- Rust tests in `packages/paperclip-runner/runner`: `cargo fmt --all --
--check`, `paperclip_process_table` (3/3), `paperclip_runner_core --lib`
(670/670, skipping macOS-incompatible `task_memory::tests::monitor_*`),
`paperclip-runnerd` bin tests (11/11), and `acpx_provider_resolutions`
(12/12) — passed.
- `packages/adapter-utils` (`paperclip-runner-permissions.test.ts`
50/50) and `packages/adapters/codex-local` (`build-config.test.ts`
64/64) — passed.
- `scripts/__tests__/prepare-runner-release-image.test.mjs`, `node
scripts/check-maps.mjs`, and `node
tests/runner-e2e/source-sdk-public-inputs.mjs <HEAD> --check` — passed.
- Server suites: `adapter-routes.test.ts` (36/36), `registry.test.ts`
(67/67), `agent-adapter-validation-routes.test.ts` (`Antigravity|YAML`),
`antigravity-connection-probe.test.ts`,
`antigravity-save-refusal.test.ts`, `antigravity-release.test.ts`
(10/10), `acpx-qualification.test.ts` (39/39),
`antigravity-candidate-admission.test.ts`,
`remote-provider-pack.test.ts` (60/60),
`native-session-executor.test.ts` (`Antigravity|provider pack`),
`plugin-runner-credentials.test.ts`,
`plugin-runner-credential-names.test.ts`,
`antigravity-plugin-task-credential-writeback.test.ts` — passed.
- CLI (`runtime.test.ts`, `runtime-setup.test.ts` 15/15), UI (6
Antigravity/setup suites 58/58 + `AgentConfigForm.render.test.tsx`), and
`tests/runner-e2e` (`catalog.test.ts`,
`controller-rolling-deployment.test.ts`,
`antigravity-qualification.test.ts`, `eval-gateway-drain.test.ts`, and
690+ unit files) — passed.
- Typechecks: `@paperclipai/adapter-utils`,
`@paperclipai/adapter-codex-local`, `@paperclipai/paperclip-runner`,
`@paperclipai/server` (all 7 layers), `@paperclipai/ui`, and `pnpm
test:e2e:runner:typecheck` — all passed.
- **Not run locally**: Live paid-key `runner-e2e` suites
(`antigravity-qualification`, `antigravity-model-lineup`,
`antigravity-agent-journey`) were waived by the owner on 2026-11-25 to
enable staging testing and remain marked `NOT RUN` / deferred in the
qualification docs. Rust `task_memory::tests::monitor_*` cgroup tests
require Linux CI.

## Risks

- **Merge sequencing**: Merge after #22935
(`fix/per-turn-harness-on-warm-environment`) so warm environments keep
Antigravity on its per-turn lifecycle.
- **Deferred live qualification**: Paid-key `antigravity-qualification`
cells have not run in CI;
`ACPX_CAPABILITY_PROFILES.antigravity.recovery` remains `"unverified"`
until live multi-turn and restart continuity are verified on staging.
- **Profile version reset**: Bumping `agentProfileVersion` from `1` to
`2` intentionally rejects any candidate-era v1 saved sessions as
`provider_state_incompatible`; new runs start a clean replacement
conversation in the same workspace.
- **Remote provider pack targets**: Remote provider packs intentionally
target `linux-x64` (Core Docker images and Linux sandboxes); local
`darwin-arm64` hosts continue to provision via `paperclipai runtime
setup antigravity`.

> 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 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>
2026-11-25 09:02:06 -06:00
DottaandClaude Opus 5.5 1bea1eeaed fix(ai-connections): delete the saved Google Antigravity sign-in on disconnect (#22931)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - AI connections let a company sign in to a model provider, and Google
Antigravity uses a Google account sign-in with a long-lived refresh
token
> - When a user disconnected that account, or removed its connection,
Paperclip marked the grant revoked but kept the saved sign-in in its
database
> - The obvious fix, revoking the token at Google, is unsafe here: the
sign-in uses the OAuth client of Google's own Antigravity runtime, and
Google revocation removes the grant for that whole client
> - A revoke would sign the person out of their own Antigravity app or
CLI and out of every other Paperclip connection for that Google account
> - This pull request deletes Paperclip's saved sign-in on disconnect
and removal, does not call Google, and says plainly that the sign-in
stays valid at Google until the person removes it there
> - The benefit is that "disconnect" does what the person expects in
Paperclip, never breaks their other tools, and never leaves a usable
token behind in Paperclip

## Linked Issues or Issue Description

No issue exists. This follows the feature request template.

**Subsystem affected**

AI connections: Google Antigravity subscription sign-in, its disconnect
and connection removal paths, the connection removal transaction, and
the disconnect messages in the UI and activity log.

**Problem or motivation**

Disconnecting a Google Antigravity subscription account marked the
connection grant revoked in Paperclip only. The saved sign-in (an
encrypted company secret that holds the refresh token) was not deleted.
Connection removal kept it too, because removal only deletes secrets in
the app-owned key namespace. Separately, connection removal revoked the
grants and then released usage-limit holds in two separate writes, so a
failure between them left the grants revoked while held work kept
waiting.

**Proposed solution**

On disconnect or removal, delete Paperclip's saved sign-in and record
the result in plain words. Do not call Google's token revocation. Keep a
saved sign-in that another grant or target still uses. If the delete
fails, keep the reference and let the next disconnect retry. Never
delete a sign-in that a reconnect saved in the meantime. Commit the
grant revocation and the hold release in one transaction, as the
single-grant revoke already does.

**Alternatives considered**

Revoking the refresh token at `https://oauth2.googleapis.com/revoke`
(the first revision of this pull request). The saved credential always
uses client
`1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com`
(`sanitizeAntigravityCredential` rejects any other), which belongs to
Google's own Antigravity runtime that Paperclip runs for sign-in.
Google's OAuth guide for installed apps ("Token revocation") says
revocation "removes all OAuth 2.0 scopes previously granted to a
project" and invalidates tokens for all clients registered under that
project. So a revoke would sign the person out of every Antigravity
sign-in for that account, not only Paperclip's. Paperclip has no client
of its own for this sign-in, so it cannot revoke only its own access.

**Roadmap alignment**

This is work item 5 of the merged plan
`doc/plans/2026-11-25-antigravity-cloud-rollout.md` (gap G10). This pull
request updates G10, item 5 and the security table there to record the
decision.

## What Changed

- `server/src/services/antigravity-access-removal.ts`: for a Google
Antigravity subscription connection, deletes the grant's own saved
sign-in (the private `ai-<grant>` or `ai_<grant>` slot only). It keeps a
sign-in that a live grant or connection elsewhere, a secret binding or
user-secret declaration on another target, or another consumer (agent
profile, routine trigger, secret proposal) still uses. On connection
removal, other grants of the same connection do not count. The delete
passes the saved version, and the grant must still be revoked, so a
reconnect that saved a new version is never deleted. A failed delete
keeps the grant's reference so the next disconnect retries, and the
retry finds a sign-in that is already marked deleted and finishes the
purge. It also clears the quota-recovery file for that grant.
- New `server/src/services/connection-secret-consumers.ts`: one
`findSecretConsumers` check for "is this secret used elsewhere?".
Connection removal (`classifyConnectionSecrets`), managed Google removal
(`secretsHeldElsewhere`) and this change use it. Removal keeps its rule
that any grant or connection counts; the two Google paths count only
live ones. Managed Google removal now also respects bindings,
declarations and other consumers, which only keeps more secrets.
- `packages/shared`: new `AiSignInRemoval` result (`savedSignIn: deleted
| kept_shared | not_deleted`, `providerSignIn: still_valid`) on the
grant revocation result and the connection removal summary.
- `grants.ts`, `removal.ts`, `routes/tool-access.ts`: return and log the
result. Removal does not clear a grant reference whose delete failed,
and its final reference clear only touches revoked grants, so a
reconnect that lands during removal keeps its sign-in.
- `removal.ts`: the grant revocation and the usage-limit hold release
now commit in one transaction.
- `ai-connections.ts`: a personal reconnect reuses the grant's existing
secret definition only if the owner created it, it is live, and it is a
Paperclip-managed local definition. Otherwise the reconnect is refused
in plain words and no token is written.
- UI: the AI account disconnect shows a toast, and connection removal
and the audit feed show the result in plain words, for example
"Paperclip deleted its saved Google sign-in. The sign-in stays valid at
Google until you remove it in your Google account's third-party
connections. Removing it there also signs this Google account out of
Antigravity everywhere." A failed delete says "Paperclip couldn't delete
its saved Google sign-in. Disconnect again to retry."
- Docs: `doc/connections/AI-CONNECTIONS.md` and the rollout plan.
- The first revision's direct Google call and its retry branch in the
Google revocation queue are removed. `google-pending-revocation.ts` is
unchanged from `master`.
- `tests/runner-e2e/source-sdk-public-inputs.json`: refreshed pins for
the changed shared export.

## Verification

- `npx vitest run src/__tests__/antigravity-disconnect-sign-in.test.ts`
(server, embedded Postgres, network calls fail the test): 17 cases.
Disconnect through the route deletes the sign-in, makes no network call,
logs the result with no token, and the owner can reconnect. Connection
removal deletes it, also when a second grant of the same connection
references it. It is kept when a grant on another live connection, a
binding on another target, a declaration on another target, or a routine
trigger uses it. A failed delete (forced by a database trigger) is
reported, keeps the reference, and the next disconnect deletes it, for
disconnect and removal, and also when the failure comes after the
sign-in was marked deleted. A reconnect during the delete, or during
connection removal, keeps its sign-in. A personal reconnect is refused
when the slot was created by someone else, deleted, or moved to another
provider, and no token is written. A hold-release failure during removal
leaves every grant active and the sign-in saved.
- Red/green: with `master`'s `grants.ts`, `removal.ts`,
`ai-connections.ts` and `routes/tool-access.ts`, the disconnect and
removal cases fail. Each guard was also removed on its own, and its case
failed: the saved-version check, the revoked-only final clear, the
half-deleted retry, the same-connection exclusion, and the definition
ownership check.
- `ui`: `npx vitest run
src/features/connections/googleAccessRemoval.test.ts` (13 pass, 5 new).
- Connection removal and managed Google tests pass:
`tool-connection-removal`, `tool-access-service`,
`google-managed-connection-removal`, `google-pending-revocation`,
`ai-connections`, and the browser-use, client-credentials, generic MCP,
Braintrust, 1Password and remote MCP connection suites.
- Server typecheck passes. UI `tsc` shows no errors in changed files.
`pnpm verify` selects about 1,900 test files for this change (removal is
widely imported), so required CI supplies that broad coverage.

## Risks

- The Google sign-in stays valid at Google after a disconnect. The UI
and activity log say so and link to the Google account page. This is
deliberate; see Alternatives considered.
- A reconnect still keeps older versions of a rotated shared secret, as
before this change.
- Company deletion does not change here.
- No schema change and no migration.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude
Code with tool use (shell, file edits, test runs, web reading of
Google's OAuth documentation).

## 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 08:52:03 -06:00
917fe1ba29 fix(runner): keep per-turn-only harnesses per-turn on warm environments (#22935)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The Paperclip Runner runs each agent in an environment: the host, a
sandbox provider, or a plugin task environment
> - An environment can set `runnerLifecycleMode: "warm"` (and
`reuseLease: true` for sandboxes). Then the run keeps its task or
sandbox lease alive and reuses it between runs
> - Some harnesses are qualified only for per-turn sessions: Google
Antigravity, Dot, Muse, Grok Bot, and Cursor Cloud
> - The native session policy already keeps these harnesses per-turn.
The environment view did not: on a warm plugin environment it leased a
warm task, and on a warm sandbox environment it could lease or retain a
reusable sandbox (`reuseLease: true`)
> - The run-time Antigravity defense refuses a warm lifecycle
(`antigravity_warm_unsupported`). An agent on a warm environment saved
without error, but its run lifecycle disagreed with what the harness
supports
> - This pull request makes the environment view use the same
per-turn-only declaration as the session policy, clears `reuseLease` on
reusable sandboxes for per-turn-only harnesses, and enforces per-turn
even over a persisted warm admission
> - The benefit is that an agent with a per-turn-only harness saves and
runs per-turn on every environment, with no failed runs and no manual
fix

## Linked Issues or Issue Description

**What happened?**
A plugin environment with `runnerLifecycleMode: "warm"` (for example a
managed Daytona or Unikraft task environment) or a sandbox environment
with `runnerLifecycleMode: "warm"` / `reuseLease: true` overrode the
agent's own lifecycle. For a Google Antigravity agent (or Dot, Grok Bot,
Muse, Cursor Cloud), the run could lease a warm task or reusable sandbox
kept between runs. The native session policy is qualified only per-turn,
and Antigravity's run-time check refuses warm. The save-time check did
not see the environment lifecycle, so the agent saved without error.

**Expected behavior**
A harness that supports only per-turn sessions runs per-turn on every
environment, including when the environment asks for `warm` or
`reuseLease: true`, and even if a pre-fix persisted warm admission
exists. The user never saves a configuration that fails at run start.

**Steps to reproduce**
1. Create a plugin environment with `runnerLifecycleMode: "warm"`, or a
sandbox environment with `runnerLifecycleMode: "warm"` and `reuseLease:
true`.
2. Save a Google Antigravity agent with a Google API key on that
environment. The save succeeds.
3. Resolve the run environment for that agent
(`resolveRunnerEnvironmentForRun`). On master the plugin task lifecycle
is `warm` and a reusable sandbox retains `reuseLease: true`.

**Deployment mode**
Both local (`local_trusted`) and hosted/cloud (`authenticated`)
Paperclip Runner deployments using plugin task or remote sandbox
environments.

## What Changed

- `requiresPerTurnNativeSession` in
`server/src/services/native-runtime/native-warm-capability.ts` is now
the single declaration of per-turn-only harnesses: Google Antigravity
(`acpx_runtime` / `antigravity`), plus `openai_dot_mcp`, `grok_bot_mcp`,
`muse_external`, and `cursor_cloud_api`, with an updated doc comment
covering all five harnesses and both rationales.
- Added `requiresPerTurnNativeSessionForConfig` in
`native-warm-capability.ts` so the environment lifecycle view resolves
per-turn-only harnesses through the same module, including when full
provider-profile validation refuses a config (such as a pending
Antigravity rollout without a company grant or an incomplete/invalid
external bot config).
- The native session policy
(`server/src/services/heartbeat/native-lifecycle.ts`) uses
`requiresPerTurnNativeSession` instead of duplicating the backend list.
- The run environment view (`resolveRunnerEnvironmentForRun`,
`resolveWarmRunnerIdleTimeoutMsForRun`, and
`runnerLifecycleDefaultNeedsLeaseProbe`) now enforces per-turn-only
harnesses ahead of `admittedLifecycleMode`, environment settings, and
agent settings (matching `resolveHeartbeatNativeLifecyclePolicy`), and
explicitly sets `reuseLease: false` on run-scoped sandbox views when the
shared sandbox config has `reuseLease: true`.
- Other harnesses continue to honor environment warm settings and
admitted warm recovery.

## Verification

- `server/src/services/runner-environment-lifecycle.test.ts`: covers all
five per-turn-only harnesses (Google Antigravity, Dot, Grok Bot, Muse,
Cursor Cloud) and refused external bot configs across warm plugin
environments, warm sandboxes with `reuseLease: true`, and persisted
`admittedLifecycleMode: "warm"`, plus unaffected harnesses keeping
warm/admitted recovery.
- `server/src/__tests__/antigravity-save-refusal.test.ts`: verifies
saving a Google Antigravity agent with a Google API key on a warm plugin
task environment resolves per-turn across the run environment, session
policy, and run-time credential check.
- `server/src/services/heartbeat/native-lifecycle.test.ts`: passes
without changes.
- `pnpm --filter @paperclipai/server typecheck` (all layers including
`test-tree-0`) and targeted Vitest suites pass locally; full suite
verified by CI.

## Risks

- Low risk. The change affects only the five per-turn-only harnesses.
Their sessions already ran per-turn, so only plugin task and sandbox
lease retention change from warm/reusable to per-turn/ephemeral.
- A per-turn-only harness no longer keeps a warm task or reusable
sandbox between runs on a warm environment, including if an older run
had a persisted warm admission. That retention was never qualified for
these harnesses.
- In the session policy, a saved warm policy for Dot, Muse, Grok Bot, or
Cursor Cloud is now ignored; their configuration validators never
allowed warm.

> 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

- Initial implementation: Claude Opus 5.5 (`claude-opus-5-5`) in Claude
Code.
- Review fixes & CI verification: Antigravity 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: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-25 08:44:08 -06:00
DottaandPaperclip e04efb9734 feat(antigravity): allow plugin Runner-task and remote Google sign-in targets once released (#22940)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The native Runner executes Google Antigravity on local hosts, Core
managed sandboxes, and plugin Runner-task environments such as Paperclip
Computer.
> - Before this change, Paperclip refused Google sign-in on all remote
targets even after release, returned an unavailable error when testing
Antigravity on plugin Runner-task environments, and did not wire remote
refresh-token write-back on Core sandboxes or released Antigravity
profile resolution.
> - Paperclip Cloud needs Google Antigravity to run with both Gemini API
keys and Google sign-in on both plugin Runner-task environments and Core
managed sandboxes once the profile flips from pending to qualified.
> - This pull request lifts the released-state remote sign-in refusal,
wires plugin Runner-task probing and released profile resolution for
Antigravity, adds Core sandbox remote sign-in write-back and checkpoint
exclusion, and keeps pending-release candidate grants restricted to
API-key non-plugin targets.
> - The benefit is that flipping the Antigravity profile from pending to
qualified immediately enables picker selection, agent creation/save,
Test probing, and execution with either Gemini API keys or Google
sign-in on both plugin Runner-task environments and Core sandboxes.

## Linked Issues or Issue Description

- Refs #22923 (Item 6 of
`doc/plans/2026-11-25-antigravity-cloud-rollout.md`, gaps G6 and G7)
- Pairs with #22933 (Item 2: Antigravity sign-in task credential and
plugin write-back) and #22935 (Item 3: keep per-turn-only harnesses
per-turn on warm environments)
- Refs #22930 (Item 1: Gemini API key task credential for plugin
Runners)

## What Changed

- **Remote Google sign-in policy & credential preparation
(`antigravity-connection-policy.ts`,
`antigravity-runner-credentials.ts`)**:
- Allow both Gemini API key and Google sign-in on remote targets in
`antigravityConnectionRefusal` once `releasePending` is `false`, while
keeping `lifecycleMode: "warm"` refused and keeping pending-release
candidate grants API-key-only on non-plugin remote targets.
- Strip all `GOOGLE_*` and non-selected `GEMINI_*` variables (plus
`PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET`) in
`prepareAntigravityRunnerCredentials`, enforce
`antigravityConnectionRefusal` using `antigravityReleasePending()`, and
pass pure sanitized sign-in JSON on remote runs (without local `/swarm`
metadata).
- **Core sandbox remote sign-in write-back & checkpoint safety
(`native-credential-store.ts`, `native-session-executor.ts`,
`antigravity-runner-credentials.ts`)**:
- Extend `createNativeCredentialStore` to support `provider:
"antigravity"` (`acp_token.json` and `auth-refresh.json`) over local and
remote command runners.
- Add optional `runtimeStore` support to `antigravityCredentialTurn` and
wire it in `native-session-executor.ts` for Core remote sandboxes so
rotated Google refresh tokens copy back after process retirement and
remote credential files are scrubbed.
- Exclude
`antigravity-home/antigravity-acp/{acp_token.json,auth-refresh.json,auth-refresh.json.tmp,logs}`
from remote ACPX session checkpoints.
- Enforce `antigravityConnectionRefusal` in `preparePluginTaskOwner` and
reject pending `pluginTask` execution in
`assertAntigravityExecutionAdmissible` (defense in depth).
- **Plugin Runner-task probing, released profile resolution & agent
save/setup (`provider-profile.ts`, `plugin-runner-probe.ts`,
`antigravity-connection-probe.ts`, `agent-environment-test.ts`,
`agents.ts`, `NewAgentSetup.tsx`)**:
- Add `antigravity` to `DEFAULT_ACPX_RUNNER_MODELS` and the qualified
ACPX agent allowlist in `provider-profile.ts`, requiring an explicit
non-placeholder model ID and checking `antigravityReleasePending()`.
- Wire `testAntigravityConnection` to delegate plugin Runner-task
targets to `probePluginRunnerEnvironment` instead of returning `"Google
Antigravity is unavailable in this hosting environment."`, and update
`probePluginRunnerEnvironment` to run `admissionOnly: true` for
Antigravity with either Gemini API key or Google sign-in once released,
returning `antigravity_metadata_verified`.
- Allow Core sandbox/SSH `probeAntigravityExecutionTarget` for Google
sign-in once released, preserve `antigravity_remote_runtime_ready` warn
status in `agent-environment-test.ts` and `NewAgentSetup.tsx`.
- Allow released Antigravity creation without `enableNativeRunner`,
allow released remote sign-in account model discovery on the tenant
host, and refuse pending plugin targets even when a `linux-x64`
candidate grant exists.
- Note on existing >1,000-line files: edits to
`server/src/routes/agents.ts` and
`server/src/services/native-runtime/native-session-executor.ts` are
minimal wiring at existing Antigravity call sites (+12 and +26 net
lines).
- **Tests**:
- Updated `antigravity-runner-credentials.test.ts`,
`native-credential-store.test.ts`, `antigravity-save-refusal.test.ts`,
`antigravity-connection-probe.test.ts`, `antigravity-release.test.ts`,
`adapter-routes.test.ts`, `agent-runner-selection.test.ts`,
`agent-environment-test-status.test.ts`,
`native-session-executor.test.ts`, and
`ui/src/lib/cloud-harness-policy.test.ts`.
- Added
`server/src/services/native-runtime/plugin-runner-probe-antigravity.test.ts`.

## Verification

- Local Vitest (all passed against a released-profile fixture as well as
the real pending profile):
- `pnpm --filter @paperclipai/server exec vitest run
src/services/native-runtime/antigravity-runner-credentials.test.ts
src/services/native-runtime/native-credential-store.test.ts
src/services/native-runtime/antigravity-release.test.ts
src/services/native-runtime/plugin-runner-probe-antigravity.test.ts
src/services/native-runtime/plugin-runner-probe-runner-mismatch.test.ts
src/services/native-runtime/plugin-runner-credentials.test.ts
src/__tests__/antigravity-connection-probe.test.ts
src/__tests__/antigravity-save-refusal.test.ts
src/__tests__/antigravity-managed-subscription.test.ts
src/__tests__/antigravity-plugin-task-credential-writeback.test.ts
src/services/agent-runner-selection.test.ts
src/services/agent-environment-test-status.test.ts` (12 files, 425 tests
passed)
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/adapter-routes.test.ts --hookTimeout=60000` (36 passed)
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/agent-test-environment-routes.test.ts --hookTimeout=60000
-t "passes the selected Antigravity"` (1 passed)
- `pnpm --filter @paperclipai/server exec vitest run
src/services/native-runtime/native-session-executor.test.ts -t "projects
the selected Antigravity subscription"` (2 passed)
- `pnpm --filter @paperclipai/ui exec vitest run
src/lib/cloud-harness-policy.test.ts` (36 passed)
- Typechecks:
  - `pnpm --filter @paperclipai/server exec tsc --noEmit` (passed)
  - `pnpm --filter @paperclipai/ui typecheck` (passed)
- Not run live: the real Antigravity profile remains `pending` until
Item 8; live staging verification on Paperclip Computer and Core managed
sandboxes is covered by Item 12.

## Risks

- Low risk while the Antigravity profile remains `pending`: all new
remote sign-in and plugin Runner-task paths stay gated behind
`!antigravityReleasePending()`, and pending-release candidate behavior
remains unchanged (and tighter on plugin environments).
- Once Item 8 flips the profile to qualified, released Antigravity
agents on Core sandboxes and plugin Runner-task environments will use
the paths tested here; live acceptance on staging is gated by Items
9–12.

> 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 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>
2026-11-25 08:36:37 -06:00
DottaandClaude Opus 5.5 aa85bcb518 feat(plugins): carry a Google sign-in to plugin Runners for Google Antigravity (#22933)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Plugin environments (for example, an agent computer) run agents as
plugin Runner tasks. Core sends each task one typed credential, and gets
refreshed sign-ins back through the task's `credentials` snapshot.
> - #22930 let a Google Antigravity task carry a Gemini API key. A
Google subscription sign-in was still refused with "Google sign-in is
not supported."
> - The Cloud rollout plan (#22923) needs both routes. This is gaps G3
and G4 and work item 2: deliver the sign-in, and save a rotated refresh
token safely, as Codex does.
> - This pull request sends the saved, sanitized sign-in as the
`antigravity` `provider-env` credential under
`PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET`. It saves a refreshed
token from the snapshot only after the generation, epoch and Google
account checks.
> - The benefit is that a plugin (for example, the Cloud agent computer)
can run an Antigravity task with a person's Google sign-in, and token
refreshes are not lost or saved to the wrong account. The picker, Test
and save refusals for plugin targets (item 6) and the qualification flip
(item 8) stay out of scope.

## Linked Issues or Issue Description

Refs #22923
Refs #22930

**What problem does this solve?**
A plugin Runner task cannot use a Google sign-in for Google Antigravity.
Core refuses it at run start. There is also no path to save a refresh
token that the Runner rotated on the plugin's computer.

**Proposed solution**
Add the sign-in variable as a second `antigravity` key set in
`provider-env`. Core reads the sign-in from the run's private managed
home, runs it through `sanitizeAntigravityCredential`, and sends that
exact output. Core saves the write-back binding (grant, secret, session
epoch, and a SHA-256 of the starting sign-in) on the lease. When the
task stops, Core reads the snapshot and saves a new token only if all
checks pass.

**Alternatives considered**
A new credential type for the sign-in. `provider-env` already has the
exact-set check, the credential binding contract and the cross-check
against the Runner's allowlists. The Cloud plan already describes the
Launcher row as "`GEMINI_API_KEY` or the sign-in key".

## What Changed

- `packages/plugins/sdk/src/environment-tasks.ts`: the `antigravity` key
sets are now `GEMINI_API_KEY` or
`PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET`. A mix of both stays
rejected.
- `server/src/services/native-runtime/plugin-runner-credentials.ts`:
with no Gemini API key, Core reads `antigravity-acp/acp_token.json` from
the selected managed home and sends the sanitizer's complete output
(client ID, client secret, refresh token, token URI, `scopes`, and
`project_id` when present). It never sends an access token or the
account email. The task needs write-back authority. A sign-in supplied
through the environment is refused. An unreadable or invalid saved
sign-in fails with "The selected Google Antigravity account is
unavailable. Reconnect the Google account, then retry." No error
contains credential text.
- `server/src/services/ai-connection-runtime.ts`: a Google subscription
run now returns a write-back binding with `google.credentialSha256` of
the starting sign-in.
- `server/src/services/managed-ai-credential-writeback.ts`: new
`syncManagedAntigravityCredential`. It requires an active grant, the
same secret reference and session epoch, a Google subscription
connection, and a saved sign-in that still hashes to the starting
generation. It verifies a changed token with the existing account check
(`prepareAntigravityCredentialWriteback`) in a private temporary home,
then rechecks all of the above under the account lock before it rotates
the secret. It writes `ai_connection.credential_refreshed` on save. For
a different account, or a connection with no saved account, it saves
nothing, writes `ai_connection.credential_refresh_refused` with a plain
reason, and settles as `account_refused`.
- `server/src/services/plugin-task-credential-writeback.ts`: a handoff
with a Google binding takes the snapshot's `provider-env` `antigravity`
sign-in and uses the Google write-back. Codex is unchanged.
- `server/src/services/native-runtime/native-session-executor.ts`: a
sign-in credential needs a Google write-back binding, and a Codex
credential needs a non-Google one.
-
`server/src/services/native-runtime/antigravity-runner-credentials.ts`:
the account mismatch is a typed error. The message is unchanged.
- Docs: `doc/plugins/PLUGIN_ENVIRONMENT_TASKS.md` and
`doc/plugins/PLUGIN_RUNNER_EXECUTION.md` describe the sign-in
credential, where the Runner stages it, and the snapshot that the plugin
must return.
- `tests/runner-e2e/source-sdk-public-inputs.json`: refreshed for the
changed SDK source.

## Verification

- Red first: with the source changes removed, 22 of the new and updated
tests failed (the refusal, no write-back binding, no Google write-back).
- Green after the change:
- `cd server && npx vitest run
src/__tests__/antigravity-plugin-task-credential-writeback.test.ts` (11
passed, embedded PostgreSQL): delivery of the exact sanitized sign-in;
same-account rotation saved and logged; a second rotation during the
account check saved; a different account refused and recorded in plain
words; unchanged token with no Google call; reconnect (new generation
and epoch) and a revoked grant discard the write-back without an export;
a Google outage keeps the handoff pending and the next cleanup saves it;
Codex, API-key and invalid snapshots refused. No token, client secret or
access token in lease metadata, activity rows or errors.
- `cd server && npx vitest run
src/services/native-runtime/plugin-runner-credentials.test.ts
src/__tests__/plugin-runner-credential-names.test.ts` (39 passed). The
names test checks that the Runner forwards the sign-in variable to the
sidecar and keeps it out of the provider process.
- `cd packages/plugins/sdk && npx vitest run
tests/environment-task-release-resume.test.ts
tests/environment-tasks.test.ts` (104 passed)
  - `cd server && pnpm typecheck` (clean)
  - `pnpm verify` (see the CI run for broad coverage)
- No live run, no Google login and no real token was used. All Google
calls are fixtures.

## Risks

- Low for current users. Plugin targets still refuse Antigravity in the
picker, Test and save (item 6), so no existing agent reaches this path
until item 6 merges.
- The lease now stores a SHA-256 of the starting sign-in. It is a
one-way digest of a high-entropy token, and it is the same kind of
generation value that Core already derives for the local route.
- If Google rotates the token during the account check and the database
save then fails, the cleanup retries from the plugin's snapshot. Google
does not normally rotate these refresh tokens, so this matches the local
route's exposure without its recovery journal.
- The Launcher must return the Runner's `auth-refresh.json` (or
`acp_token.json` before lease close) in the snapshot. A Launcher that
returns the starting sign-in only records `unchanged`, so no token is
lost on the Core side, but a rotation on the computer would not be
saved.

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

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, in Claude Code with
tool use (shell, file edits, test runs). Standard context window,
extended reasoning.

## Checklist

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

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 07:43:49 -06:00
DottaandPaperclip 57bd302c81 feat(antigravity): add hosted Google loopback-relay sign-in (#22932)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Google Antigravity supports Google account sign-in through Paperclip
Runner's pinned, isolated `agy_acp_server.par` process.
> - On `authenticated + public` deployments (including hosted Cloud
instances), `supportsLocalAiLogin` returns `false`, and the user's
browser cannot directly reach the server's `127.0.0.1:<ephemeral_port>`
loopback callback listener.
> - Because `client_secret` lives only inside `agy_acp_server.par` and
uses PKCE with a one-shot `127.0.0.1` listener, hosted deployments need
an authenticated relay path instead of an anonymous callback route or
extracted secret.
> - This pull request adds an authenticated loopback-relay flow across
Runner, server policy/routes/redaction, and the UI so users on hosted
deployments can sign in with Google, copy the `127.0.0.1` redirect URL
from their address bar, and paste it to complete authentication.
> - The benefit is that Google Antigravity subscription sign-in works on
hosted public deployments while keeping Claude, OpenAI, and Grok
server-host login disabled and preventing SSRF, secret leakage, or
cross-tenant access.

## Linked Issues or Issue Description

Refs #22923

**Subsystem affected**
Cross-cutting (packages/paperclip-runner, packages/shared, server/, ui/)

**Problem or motivation**
Google Antigravity sign-in launches Paperclip's pinned, isolated
`agy_acp_server.par` closure, which opens a one-shot
`127.0.0.1:<ephemeral_port>` OAuth callback listener. On hosted
`authenticated + public` deployments, server-host login routes are
blocked and the user's browser cannot connect to the server's loopback
interface, so users cannot sign in with a Google account on Cloud or
remote instances.

**Proposed solution**
Add an authenticated loopback-relay flow:
1. Runner exposes a single-use `submitRedirect(rawRedirectUrl)` handler
on `AntigravityBrowserLoginState` that validates the pasted URL (length,
printable ASCII, `http://127.0.0.1:<expectedPort>/`, no
credentials/hash, no duplicate `state`/`code`, no `error` param,
`timingSafeEqual` state check, bounded 5-attempt bad-paste cap, SHA-256
reused-code tracking) and issues an SSRF-proof reconstructed `GET` to
`expectedRedirect.origin` with `redirect: "manual"`.
2. Server adds `supportsHostedGoogleAiLogin` (exposed on `/api/health`
as `hostedGoogleAiLoginSupported`), permits Google through the
authenticated `/api/companies/:companyId/ai-connections/local/*` routes
while keeping `anthropic`/`openai`/`xai` blocked on public deployments,
accepts up to 4096-character redirect URLs on `/code` while preserving
Claude's 512-byte limit, runs the loopback relay outside DB
transactions, falls back cleanly when a stack has no active `local`
environment row, and redacts `browserCode`/`redirectUrl` and marks
`/code` secret-sensitive.
3. UI enables Google sign-in for `antigravity_runtime` on non-local
environments when `hostedGoogleAiLoginSupported` is true, renders the
external Google sign-in link plus plain-language `127.0.0.1` copy/paste
instructions with analytics masking/no-capture markers, and triggers an
immediate status check after submission.

**Alternatives considered**
- Adding an anonymous public OAuth callback route on the server:
rejected because it widens the unauthenticated attack surface and cannot
change the loopback `redirect_uri` bound inside `agy_acp_server.par`.
- Extracting Google OAuth `client_secret` out of `agy_acp_server.par`:
rejected by policy; secrets remain owned solely inside the pinned
closure.

## What Changed

- `packages/paperclip-runner/src/drivers/acpx/antigravity-auth.ts` &
`packages/paperclip-runner/src/index.ts` &
`server/src/vendor/paperclip-runner/index.ts`: add single-use
`submitRedirect` on `AntigravityBrowserLoginState` with strict
validation, `timingSafeEqual` state verification, 5-attempt cap, bounded
SHA-256 reused-code set, and SSRF-proof loopback relay.
- `packages/shared/src/ai-connections.ts`: add
`LOCAL_AI_LOGIN_CODE_MAX_LENGTH` (4096), `localAiLoginCodeSchema`, and
`submitLocalAiLoginCodeSchema` while preserving Claude's 512-byte
`BROWSER_CODE_MAX_LENGTH` and `browserCodeSchema`.
- `server/src/services/local-ai-login-policy.ts` &
`server/src/routes/health.ts`: add `supportsHostedGoogleAiLogin` and
expose `hostedGoogleAiLoginSupported` on `/api/health`.
- `server/src/services/local-ai-browser-login.ts`,
`server/src/services/local-ai-login.ts`,
`server/src/routes/ai-connections.ts`: permit hosted Google sign-in on
authenticated public deployments while keeping Claude/OpenAI/Grok
blocked; enforce `Cache-Control: no-store`, owner/company/active/expiry
checks, and Claude's 512-byte cap; run Google `submitRedirect` outside
any DB transaction; fall back cleanly to an active environment or
savepoint-wrapped `ensureLocalEnvironment` when no active `local`
environment row exists.
- `server/src/middleware/redact-sensitive.ts`,
`server/src/middleware/http-log-redaction.ts`,
`server/src/middleware/http-log-policy.ts`: redact
`browserCode`/`redirectUrl`/`redirect_url` unconditionally and classify
`/api/companies/:companyId/ai-connections/local/attempts/:sessionId/code`
as secret-sensitive (`local_ai_login_code`).
- `ui/src/api/health.ts`,
`ui/src/components/ai-connections/useLocalAiLogin.ts`,
`ui/src/components/AdapterLoginChrome.tsx`,
`ui/src/components/new-agent/AgentProviderConnection.tsx`,
`ui/src/components/ai-connections/AiConnectionCredentialStep.tsx`,
`ui/src/components/OnboardingWizard.tsx`: enable hosted Google sign-in
for `antigravity_runtime` on hosted/non-local environments, render the
hosted `127.0.0.1` redirect paste flow with `ANALYTICS_MASK_CLASS` and
`ANALYTICS_NO_CAPTURE_CLASS`, preserve retryable paste errors inline,
and trigger immediate status re-check on submit.
- `tests/runner-e2e/source-sdk-public-inputs.json`: refreshed for the
updated `packages/shared/src/ai-connections.ts` schema.
- Unit, integration, and UI tests across `antigravity-auth.test.ts`,
`local-ai-login-policy.test.ts`, `health.test.ts`,
`health-dev-server-token.test.ts`, `redact-sensitive.test.ts`,
`http-log-policy.test.ts`, `antigravity-local-ai-login.test.ts`,
`ai-connections.test.ts`, `AdapterLoginChrome.test.tsx`,
`useLocalAiLogin.test.tsx`, and `AgentProviderConnection.test.tsx`.

## Verification

- `pnpm --filter @paperclipai/shared build && pnpm --filter
@paperclipai/shared typecheck && pnpm --filter
@paperclipai/paperclip-runner typecheck && pnpm --filter
@paperclipai/server typecheck && pnpm --filter @paperclipai/ui
typecheck` — passed.
- `pnpm --filter @paperclipai/shared exec vitest run
src/validators/claude-setup-token-session.test.ts` — 15/15 passed.
- `pnpm --filter @paperclipai/paperclip-runner exec vitest run
src/drivers/acpx/antigravity-auth.test.ts
src/drivers/acpx/antigravity-auth-stream-order.test.ts` — 33/33 passed
(including real `127.0.0.1` loopback HTTP relay with fake ACP peer,
bad-paste cap, reused-code rejection, single-use, and non-200 failure).
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/local-ai-login-policy.test.ts src/__tests__/health.test.ts
src/__tests__/health-dev-server-token.test.ts
src/__tests__/redact-sensitive.test.ts
src/__tests__/http-log-policy.test.ts
src/__tests__/antigravity-local-ai-login.test.ts` — all passed.
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/ai-connections.test.ts` — 167/167 passed against embedded
PostgreSQL (including hosted Google end-to-end route test, redaction of
activity and HTTP logs, and continued blocking of Anthropic/OpenAI/xAI
on hosted public deployments).
- `pnpm --filter @paperclipai/ui exec vitest run
src/components/AdapterLoginChrome.test.tsx
src/components/ai-connections/useLocalAiLogin.test.tsx
src/components/new-agent/AgentProviderConnection.test.tsx` — 30/30
passed.
- `pnpm verify --explain` returned exit 2
(`tests/runner-e2e/source-sdk-public-inputs.json` broad input); required
CI supplies full-repo coverage.
- Note: live end-to-end sign-in against real `agy_acp_server.par` and
Google OAuth on a live Cloud stack was not run in this unit/integration
environment and remains a live-staging verification step.

## Risks

- Low-to-moderate risk. All hosted Google sign-in endpoints stay
authenticated, company-scoped, owner-bound, and `Cache-Control:
no-store`; `localAiLoginSupported` remains `false` on `authenticated +
public` deployments so Claude, OpenAI, and Grok server-host login stay
blocked.
- Loopback relay runs strictly against the validated
`127.0.0.1:<ephemeral_port>` origin printed by `agy_acp_server.par` with
`redirect: "manual"` and a 5-second timeout, outside any database
transaction.
- No database migrations are required.

## 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>
2026-11-25 07:36:36 -06:00
DottaandClaude Opus 5.5 07d444a717 feat(plugins): carry a Gemini API key to plugin Runners for Google Antigravity (#22930)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Plugin environments (for example, an agent computer) run agents as
plugin Runner tasks. Core sends each task one typed credential.
> - The typed `provider-env` credential carries API keys for Grok,
Copilot and OpenCode. It has no entry for Google Antigravity.
> - So an Antigravity agent cannot get its Gemini API key on a plugin
Runner task. This is gap G3 and work item 1 in the Antigravity Cloud
rollout plan (#22923).
> - This pull request adds `antigravity` to `provider-env`, with the
single variable set `GEMINI_API_KEY`. It follows the Copilot pattern
from #22359.
> - The benefit is that a plugin (for example, the Paperclip Cloud agent
computer) can now accept a Gemini API key for an Antigravity task.
Google sign-in, the plugin-target refusal and the qualification flip
stay out of scope.

## Linked Issues or Issue Description

Refs #22923
Refs #22359

**What problem does this solve?**
A plugin Runner task cannot carry a Gemini API key. `provider-env`
accepts only `grok`, `copilot` and `opencode`, and Core throws "Plugin
Runner does not support the selected credential provider" for
Antigravity.

**Proposed solution**
Add `antigravity: [["GEMINI_API_KEY"]]` to the published key sets and to
the `provider-env` provider enum. Core transfers only that key. Core
refuses a Google sign-in or a missing key with a plain message.

**Alternatives considered**
A new credential type only for Gemini. The generic `provider-env` type
already has the exact-set check, the binding contract and the
cross-check against the Runner's allowlists, so a new type adds no
value.

## What Changed

- `packages/plugins/sdk/src/environment-tasks.ts`:
`ENVIRONMENT_TASK_PROVIDER_CREDENTIAL_KEY_SETS` has `antigravity:
[["GEMINI_API_KEY"]]`. The `provider-env` provider enum accepts
`antigravity`. Mixed, partial and extra variable sets stay rejected.
- `server/src/services/native-runtime/plugin-runner-credentials.ts`: for
provider `antigravity`, Core sends only `GEMINI_API_KEY`. Core refuses a
Google sign-in document (`PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET`)
or a missing or blank key with "Plugin Runner supports Google
Antigravity only with a Gemini API key. Google sign-in is not
supported." No key value is in any error message.
- Tests: SDK schema cases (accept the key; reject a sign-in document, a
key mixed with a sign-in document, `GOOGLE_API_KEY`, extra routing
variables, empty values, and the key under another provider). Core
transfer and refusal cases. Dispatch only for the matching `antigravity`
harness, with no key in persisted lease metadata or in a worker error. A
Runner check that the Antigravity process gets the key and no `GOOGLE_*`
or other `GEMINI_*` variable.
- Docs: `doc/plugins/PLUGIN_ENVIRONMENT_TASKS.md` and
`doc/plugins/PLUGIN_RUNNER_EXECUTION.md` list the new set, the binding
requirement and the sign-in refusal.
- `tests/runner-e2e/source-sdk-public-inputs.json`: refreshed for the
changed SDK source.

## Verification

- Red first: the new tests failed before the change (the schema rejected
`antigravity`, and Core threw "does not support the selected credential
provider").
- Green after the change:
  - `cd packages/plugins/sdk && npx vitest run tests/` (322 passed)
- `cd server && npx vitest run
src/__tests__/plugin-runner-credential-names.test.ts
src/services/native-runtime/plugin-runner-credentials.test.ts
src/__tests__/environment-task-runtime.test.ts` (94 passed)
- `cd packages/plugins/sdk && npx tsc --noEmit -p .` and `cd server &&
npx tsc --noEmit -p .` (clean)
- `node tests/runner-e2e/source-sdk-public-inputs.mjs <HEAD> --check`
(no change)
- `pnpm verify` asks for broad CI coverage (exit 2) because an SDK test
file changed. Required CI supplies that coverage.
- No live run. Antigravity on a plugin target stays refused by Core
until a later change lifts that refusal, so this change is not reachable
in a run yet.

## Risks

- Low risk. The change adds one enum value and one key set. Existing
providers keep the same behavior.
- Plugins that validate with an older SDK reject an `antigravity`
credential. This is the expected fail-closed result.
- The key reaches the Runner only through the typed credential. The
Runner still requires a matching `PAPERCLIP_ACPX_CREDENTIAL_BINDING` and
still removes other `GOOGLE_*` and `GEMINI_*` variables.

## Model Used

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

## Checklist

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

> - Paperclip is the open source app people use to manage AI agents for
work
> - Review agents answer GitHub pull request threads, and each request's
comment must end in a real reply or an honest final notice
> - After #22672, #22710, #22798 and #22807, new review-bot comments on
staging settle: 0 of 85 comments since the deploy are stuck
> - Two older "Working on this…" comments (PRs #22649 and #22676) still
did not settle. Before those fixes, their requests spent all
acknowledgement retries and were left `failed`, a state no recovery path
reads again
> - Separately, the chat-channels split (#22838) was built from an older
copy of the monolith and dropped the regression tests those fixes added
> - This pull request adds a one-time recovery migration for exhausted
requests and restores the lost regression tests
> - The benefit is that the last stuck comments settle, and the settle
rules stay covered by tests that run on every PR

## Linked Issues or Issue Description

Refs #22672, #22710, #22798, #22807, #22838

**Describe the bug**
Two GitHub request comments from 2026-11-23 still read "Working on
this…" on staging after the settle fixes deployed. Before #22798, an
unsettled reply made each acknowledgement attempt fail with "GitHub
reply is still being resolved", so these requests spent all 8 retries
and stayed `failed` with `retryable: false`. Neither the acknowledgement
sweep (retryable only) nor the terminal sweep (processed only) reads
them again.

**Steps to reproduce**
1. A request's acknowledgement fails 8 times and is left `failed`,
`retryable: false`, with its comment still "Working on this…".
2. Deploy the settle fixes. Nothing reads the request again.

**Expected behavior**
Such a request settles with the current decision once.

## What Changed

- Migration `0509_recover_exhausted_github_responses.sql`: one UPDATE
that returns failed, non-final `github_response_comment` rows that
already hold a posted comment to `processed` (code
`recovered_after_exhausted_retries`, wait key and retry time cleared),
so the terminal sweep settles them. Marked `online_compatible`.
- Restored regression tests dropped by the split, in
`server/src/__tests__/chat-channels/github-review-workflow.integration.test.ts`:
published review kept in the main comment (ended / paused), older status
settles against a newer placeholder, back-to-back runs settle, waited
thread links a later response (including a different-PR guard),
inline-only review link, waited thread settles when the task finishes,
refused reply settles.
- New tests: a failed run whose automatic retry finished the task
(inline and issue threads), and the exhausted-retries recovery.

## Verification

- `github-review-workflow.integration.test.ts` restored + new tests: 11
passed locally. The recovery test shows the comment stuck before the
migration and settled after it.
- Test tree typecheck (`src/__tests__/tsconfig.json`) is clean.
- After deploy: the two remaining placeholders on #22649 and #22676
should settle within a sweep pass; I will check them on staging.

## Risks

- The migration updates only failed, non-final GitHub request rows that
have a posted comment; on staging that is a handful of rows. Each is
read once by the terminal sweep and then settles or waits under the
current rules.
- Restored tests add a few seconds to the GitHub review workflow suite.

## Model Used

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

## Checklist

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

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 05:42:24 -06:00
Dotta 4aaa77e6fc perf(ci): split 6 single-file Vitest stragglers across runner, chat, server, and serialized lanes (#22916)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Profiling live 8-core PR runs (`45592683902`, `45578886514`,
`45591289735`, `45587659461`) showed that every single top Vitest
critical-path straggler across all 4 Vitest lanes was caused by
**single-file tail pinning**—one massive file running solo while 4–6 CPU
cores sat idle—rather than insufficient shard counts:
> - `Verify Paperclip Runner (vitest package 1/6)` (`245s` job):
`runnerd-codex-transport.test.ts` = `190.9s` solo
> - `Verify Paperclip Runner (vitest package 2/6)` (`236s` job):
`runnerd-codex-transport-deadlines.test.ts` = `181.3s` solo
> - `Verify Paperclip Runner (vitest package 3/6)` (`185s` job):
`runnerd-codex-transport-settlement.test.ts` = `123.6s` solo
> - `General tests (chat 1/2)` (`229s` job):
`github-review-workflow.integration.test.ts` = `179.2s` solo
> - `General tests (server 1/20)` (`209s` job):
`connection-management.integration.test.ts` = `160.1s` solo
> - `Verify serialized server suites (1/9)` (`190s` job):
`issue-queued-comments-routes.test.ts` = `132.8s` solo
> - Instead of bloating shard counts, this pull request splits those 6
single-file tails into 20 focused sibling suites (`<925 LOC` per new
file) with shared non-test harness helpers so existing 8-core workers
execute them in parallel, keeps all 6 original anchor filenames intact
so every existing `maps/` and contract reference remains valid, and
refreshes all 4 Vitest LPT duration manifests from live 8-core
measurements.
> - Every single original test case is preserved (`694/694` live pass
across the 20 split suites, zero deleted assertions) while shaving
`60–105s` off every Vitest lane's critical-path tail.

## Linked Issues or Issue Description

Refs #22804

**What existing behavior does this improve?**
Parallel wall-clock execution time of the slowest shards across `Verify
Paperclip Runner (vitest package)`, `General tests (chat)`, `General
tests (server)`, and `Verify serialized server suites`.

**Subsystem affected**
packages/paperclip-runner/, server/, and scripts/ — Vitest integration
test layout, sequencer priorities, and LPT shard duration manifests

**Current behavior**
Six oversized test files (`123s–191s` solo each) pin the tail of the
slowest shard in every Vitest lane while peer workers on the 8-core
runner sit idle.

**Proposed behavior**
Split those 6 single-file stragglers into 20 parallelizable sibling
suites (retaining all 6 original anchor filenames and extracting shared
non-test harnesses) and refresh
`packages/paperclip-runner/scripts/vitest-lane-durations.json`,
`scripts/chat-shard-durations.json`,
`scripts/general-server-shard-durations.json`, and
`scripts/serialized-shard-durations.json` plus
`packages/paperclip-runner/scripts/vitest-sequencer.mjs`.

## What Changed

- **Split all 6 single-file stragglers (31 files changed: 11 modified,
20 new; every new file `<925 LOC`, 100% of test cases preserved):**
1.
`packages/paperclip-runner/test/runnerd-codex-transport-deadlines.test.ts`
(`181.3s` CI) → 3 files (`anchor` + `-lease-expiry` + `-cold-admission`,
9/9 tests)
2.
`packages/paperclip-runner/test/runnerd-codex-transport-settlement.test.ts`
(`123.6s` CI) → 2 files (`anchor` + `-settlement-revocation`, 19/19
tests) + 3 non-test support harnesses
(`runnerd-settlement-assertions.ts`, `runnerd-settlement-harness.ts`,
`runnerd-settlement-fixture.ts`)
3. `packages/paperclip-runner/test/runnerd-codex-transport.test.ts`
(`190.9s` CI) → 4 files (`anchor` + `-backlog-proxy` + `-held-calls` +
`-provider-turns`, 337/337 tests)
4.
`server/src/__tests__/chat-channels/github-review-workflow.integration.test.ts`
(`179.2s` CI) → 4 files (`anchor` + `-finding-threads` +
`-response-maintenance` + `-publications`, 89/89 tests) +
`github-review-harness.ts`
5. `server/src/__tests__/connection-management.integration.test.ts`
(`160.1s` CI) → 4 files (`anchor` + `-providers` + `-delegated-policy` +
`-gateways`, 92/92 tests) + `helpers/connection-management-harness.ts`
6. `server/src/__tests__/issue-queued-comments-routes.test.ts` (`132.8s`
CI) → 3 `*routes*` files (`anchor` + `-steering-routes` +
`-dispatch-routes`, 148/148 tests, all matching `routeTestPattern` in
the `serialized` lane) + `helpers/issue-queued-comments-harness.ts`
- **Updated sequencer & LPT duration manifests:**
- Updated `packages/paperclip-runner/scripts/vitest-sequencer.mjs` and
refreshed
`packages/paperclip-runner/scripts/vitest-lane-durations.json`,
`scripts/chat-shard-durations.json`,
`scripts/general-server-shard-durations.json`, and
`scripts/serialized-shard-durations.json` from live 8-core PR run
`45592683902` with exact `coverage` reconciliation.

## Verification

- Live execution of all 20 split suites: **20/20 files, 694/694 tests
PASS** (`deadlines` 9/9 in `81.1s` parallel, `settlement` 19/19 in
`105.4s` parallel, `transport` 337/337 in `109.2s` parallel,
`github-review` 89/89 under shared PG, `connection-management` 92/92
under shared PG, `issue-queued-comments` 148/148 under shared PG)
- `node scripts/check-test-budget.mjs --base origin/master` — **PASS**
(105 nightly suites, 11 test files checked, 0 violations)
- `node scripts/check-maps.mjs` — **PASS** (35 areas, 192 capability IDs
aligned)
- `pnpm --filter @paperclipai/paperclip-runner exec tsc --noEmit` —
**PASS** (0 errors)
- `pnpm --filter @paperclipai/paperclip-runner exec vitest run
scripts/vitest-sequencer.test.mjs` — **5/5 PASS**
- `node --test` across `native-completion-source-contract`,
`run-vitest-stable-shard`, `run-vitest-stable-pr-mode`,
`runner-vitest-package-lanes`, `test-selection-pr-timings`,
`test-selection-timings`, `e2e-shard`, `check-test-budget`, and
`ci-plan` — **121/121 PASS**

## Risks

- Low risk: all 6 original anchor filenames remain intact, zero
`.github/**` or `CODEOWNERS` files are touched, zero cross-test-file
imports were introduced (shared setup lives in non-test harness
modules), and full CI will execute all 20 split suites live before
merge.

## Model Used

- Gemini 4 Neon (High) via Antigravity agent swarm (`vitest-runner`,
`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 05:28:53 -06:00
DottaandClaude Opus 5.5 371ece9375 fix(tool-access): do not store provider-removed actions in the connection profile (#22908)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Connected apps give agents actions. A person reviews and turns on
each action on the Permissions page.
> - #22877 lets the review save when it contains an action that the
provider no longer lists (status `removed`, or `disabled` with
`quarantineReason: mcp_tool_removed`).
> - But the save still wrote that action to the connection profile as an
`include` entry.
> - When the provider lists the action again, the catalog refresh sets
the row back to `active`. The stored `include` then turns the action on
for agents with no new review.
> - The Permissions page does not send removed ids now, but a stale page
or a direct API call can still send them.
> - This pull request keeps provider-removed actions out of the profile
entries and the Ask first policies when the review is saved.
> - The benefit is that an action that comes back from the provider is
not offered to agents until a person turns it on again.

## Linked Issues or Issue Description

Refs #22877

**What happened?**
`finishGalleryAppConnection` accepted a provider-removed action in
`enabledCatalogEntryIds` or `askFirstCatalogEntryIds` and stored it as
an `include` profile entry (or an Ask first policy). When the provider
listed the action again, the refresh set the row to `active` and agents
got the action with no new review.

**What did you expect to happen?**
The save accepts the removed action, but does not store it. When the
provider lists the action again, the action is `active` in the catalog
but it is off for agents until a person turns it on.

**Steps to reproduce**
1. Connect Google Workspace and save a review.
2. Make Google stop listing `gmail__list_threads`. Refresh the catalog.
The row becomes `disabled` with `mcp_tool_removed`.
3. Save the review again with that row id in `enabledCatalogEntryIds`.
4. Make Google list the action again. Refresh the catalog.
5. Before this fix, the agent tool list contains `gmail__list_threads`.

## What Changed

- `server/src/services/tool-access.ts`: `finishGalleryAppConnection`
filters the enabled rows and the Ask first rows with
`isCatalogEntryOffered` before it builds the profile entries and the Ask
first policies. The validation is the same. A blocked action still gives
"Disabled actions cannot be enabled".
- `server/src/services/tool-access.ts`: when `preserveExistingAccess` is
true (OAuth completion and task setup use it), the save no longer copies
back a prior `include` entry whose catalog row is provider-removed. A
prior `exclude` entry is kept, so a saved exclusion still blocks the
action if it comes back.
- `server/src/__tests__/google-workspace-mcp-transport.test.ts`: the
test "saves the review when Google no longer offers actions that were
on…" now makes Google list the two removed actions again. It also saves
one removed action as Ask first and checks that no enabled
`require_approval` policy is made for it. It checks that the rows are
`active` and that the agent tool list does not contain them.
- New test "does not keep a removed action on when a save keeps the
existing access": a save with `preserveExistingAccess: true` does not
keep the old `include` for a removed action, and keeps an `exclude` for
a removed action.

What happens to a removed action that the provider lists again: the
refresh sets the row to `active` with no profile entry. The action is
off. A person must turn it on again on the Permissions page. It is not
held as `quarantined`, because the definition was already reviewed; only
the on/off choice is reset to off.

This applies to every connection kind that saves through
`finishGalleryAppConnection`. Remote MCP aggregators (Zapier, Arcade,
Composio, Executor) also stop storing a removed action when a review is
saved. This is the safe result for them too: an aggregator can list a
different tool under a reused name, so a returning action must not turn
on by itself. Their existing tests (`remote-mcp-connectors.test.ts`,
`tool-access-service.test.ts`) pass with no change.

Scope: this PR changes what a save stores. It does not change the
catalog refresh or a reconnect that keeps the profile unchanged
(`mcpPreserveAccess`). An `include` that was saved before the provider
removed the action, with no later save, stays in the profile as before.
A follow-up can decide if a refresh should drop it.

## Verification

- Red: with only the test change, the new assertion fails: `expected [
'docs__read_doc', …(8) ] to not include 'gmail__list_threads'`.
- Red: without the preserve-path filter, the preserve test fails
(`gmail__list_threads` is offered again). With the filter but without
the `include` check, the exclusion assertion fails (`expected [] to
deeply equal [ 'exclude' ]`). Without the Ask first filter, the policy
assertion fails.
- Green: with the fix, `google-workspace-mcp-transport.test.ts` and
`tool-access-service.test.ts` pass (547 tests).
- `remote-mcp-connectors.test.ts`,
`tool-profile-review-service.test.ts`, `app-permission-save.test.ts`,
`tool-connection-removal.test.ts`, `tool-gateway.test.ts` pass.
- `pnpm --filter @paperclipai/server typecheck` and `pnpm verify` run
locally. CI covers the full suite.

## Risks

- Low risk. A person who saved a removed action as on must turn it on
again if the provider lists it again. This is the intended result.
- A prior Ask first policy for a removed action can stay on the preserve
path (`disableStale` is false there). It only restricts an action. It
cannot turn an action on.
- No schema change. No migration.

## Model Used

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

## Checklist

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

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 05:25:51 -06:00
Dotta 9bb4789c57 fix(heartbeat): park deferred issue monitors and preserve updated_at (#22851)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The heartbeat scheduler claims due issue monitors and dispatches
wakes when their scheduled check time arrives
> - When admission defers a scheduled monitor behind an unsettled
execution-reconciliation hold or another temporary block, the scheduler
wrote `issues.updated_at` on every claim and release and immediately
reset `monitor_wake_requested_at` to `null`
> - That left the past `monitor_next_check_at` eligible on every
subsequent tick, flooding old held tasks to the top of the issues list,
generating recurring database writes, and emitting a new
`issue.monitor_deferred` activity row every five minutes forever
> - This pull request stops updating `issues.updated_at` on sterile
monitor claims and deferred releases, parks monitors held behind an
unchanged effective recovery hold until that hold resolves or changes
(with event-driven wake on resolution), and applies capped exponential
backoff to non-hold deferrals without consuming `monitor_attempt_count`
> - The benefit is zero idle polling, zero `updated_at` churn, and zero
unbounded `activity_log` spam on held tasks while legitimate monitors
still fire immediately once reconciliation clears and still respect
`timeoutAt` deadlines

## Linked Issues or Issue Description

Fixes #20174
Refs #20114
Refs #18973
Refs #18979

Related open PRs:
- `#20175` and `#20296` remove `updated_at` writes during
claims/releases and retain the five-minute stale claim, but deferred
monitors still re-fire and emit a new `issue.monitor_deferred` activity
row every five minutes indefinitely.
- `#21714` adds backoff by mutating `monitor_next_check_at` and
incrementing `monitor_attempt_count`, but still bumps
`issues.updated_at` on claims and releases, spends attempt budget on
rejected admissions, and loops every 30 minutes on
`monitor_recovery_deferred` when default `recoveryPolicy: "wake_owner"`
hits an active `execution_reconciliation_required` hold.

## What Changed

- Added `server/src/services/heartbeat/issue-monitor-deferral.ts`
(keeping `server/src/services/heartbeat/scheduling.ts` lean and
cohesive) with:
- Server-internal deferral state stored under
`execution_state.monitorDeferral`, bound to `monitor_next_check_at` so
any schedule replacement auto-invalidates prior deferral state without
any database migration or `packages/shared` contract change.
- Shared `parkableRecoveryHoldCondition()` (`status in ('active',
'escalated')` OR `executionBlockerPredicate()`), parking monitors behind
both open holds and still-effective resolved holds (such as
`automaticRecovery.replay = 'blocked'` and unreconciled native exports).
- `resolveScheduledMonitorDeferralUpdate(...)` encapsulating
recovery-hold lookup, deferral state construction, and patch assembly
outside `scheduling.ts`.
- Capped exponential backoff (`30s` -> `60m`, clamped to `timeoutAt`)
with scaled diagnostic quiet windows for non-hold deferrals.
- Updated `server/src/services/heartbeat/scheduling.ts`:
- Removed `updatedAt` updates from monitor claims
(`triggerIssueMonitor`, `tickDueIssueMonitors`) and deferred releases
(`releaseIssueMonitorWithDiagnostic`), so only actual monitor dispatch
or clear advances task activity.
- Parked scheduled deferrals (including `wake_owner` recovery deferrals)
on unchanged effective `issue_recovery_actions` holds with a
microsecond-exact UTC `updated_at` fence, yielding `nextIssueMonitorAt()
=== null` while the hold stays unchanged.
- Preserved `timeoutAt` deadlines for `escalate_to_board` and
`create_recovery_issue` policies even while a recovery hold is active.
- Stripped `monitorDeferral` atomically on monitor trigger or clear
without consuming `monitor_attempt_count` on rejected admissions or
starving ready monitors behind tied deferred rows.
- Updated `server/src/services/heartbeat/run-preparation.ts` and
`server/src/services/heartbeat/queue.ts` to pass optional
`executionBlocker.recoveryActionId ?? null` to `onExecutionDeferred`.
- Updated `server/src/services/issue-recovery-actions.ts`
(`resolveActiveForIssue`, `upsertSourceScoped`) and
`server/src/routes/issues.ts` (direct workspace-repair resolution) to
notify `DELIVERY_QUEUES.issueMonitors` when mutating or resolving a hold
on an issue with a scheduled monitor.
- Updated `server/src/services/issue-execution-policy.ts` to preserve
`monitorDeferral` across unrelated `execution_state` rewrites for the
same schedule and drop it when a monitor is replaced or cleared.
- Added red-green behavioral regressions and unit tests in
`server/src/__tests__/issue-monitor-deferral-parking.test.ts` (keeping
`issue-monitor-scheduler.test.ts` at 817 lines),
`server/src/services/heartbeat/scheduling.test.ts`, and
`server/src/services/heartbeat/issue-monitor-deferral.test.ts`.

## Verification

- **Red -> Green proof**:
- Before production edits, all 5 new behavioral regressions failed on
unfixed `master`: parking regressions failed on `issues.updated_at`
bumping during deferred claims and `nextIssueMonitorAt()` staying
immediately due instead of parking, and `scheduling.test.ts` regressions
failed on `issues.updated_at` bumping and re-selecting 49 deferred tied
rows.
  - After production edits and review fixes (commit `db0cdf8cbf`):
    - `npx tsc --noEmit -p server/tsconfig.json`: passed (0 errors)
- `pnpm --filter @paperclipai/server exec vitest run
src/services/heartbeat/issue-monitor-deferral.test.ts`: **4/4 passed**
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/issue-monitor-deferral-parking.test.ts`: **4/4 passed**
(covers `provider_failure_meaning_unverified`,
`legacy_execution_requires_reconciliation`, resolved
`automaticRecovery.replay = 'blocked'` no-replay holds,
`DELIVERY_QUEUES.issueMonitors` wake on resolution, and `timeoutAt` for
`escalate_to_board` vs `wake_owner`)
- `pnpm --filter @paperclipai/server exec vitest run
src/services/heartbeat/scheduling.test.ts`: **58/58 passed** (includes
exponential backoff, replacement invalidation, 50-deferred + 1-ready
non-starvation, and all 18 deadline lifecycle tests)
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/issue-execution-policy.test.ts
src/__tests__/issue-monitor-scheduler.test.ts
src/services/native-runtime/native-failed-run-owner-release.test.ts
src/__tests__/scheduled-work-postgres.test.ts`: **134/134 passed**
- `pnpm verify --explain`: selects broad transitive server suites;
required CI covers the full suite.

## Risks

- Low risk; no schema migration and no `packages/shared` public contract
changes.
- `monitorDeferral` lives inside `issues.execution_state` as
server-internal state stripped by `parseIssueExecutionState` on public
reads and bound to `monitor_next_check_at` so raw or API schedule
replacements invalidate it immediately.
- Non-hold scheduled deferrals now wait at least 30 seconds (growing
exponentially to 60 minutes, clamped to `timeoutAt`) before retrying
instead of re-selecting immediately on the next tick. Manual board
checks (`triggerIssueMonitor`) bypass scheduled backoff and run on
demand.
- A monitor parked on an effective `issue_recovery_actions` hold wakes
immediately when that hold clears or its `updated_at` advances, and
recovery-action mutations emit `DELIVERY_QUEUES.issueMonitors` so
deadline workers wake without polling. `readIdleIssueSchedule` remains
intentionally conservative about open holds.

> 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-2.5-pro` / Antigravity agent runtime with
reasoning, tool use, and local code execution)

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [ ] I have updated relevant documentation to reflect my changes (no
user-facing docs cover internal scheduler deferral bookkeeping)
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green (in progress on PR head
`db0cdf8cbf`)
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
(in progress on PR head `db0cdf8cbf`)
- [x] I will address all Greptile and reviewer comments before
requesting merge
2026-11-25 04:37:02 -06:00
Dotta cd02a8e0e4 fix(workspaces): release superseded ended writers and resolve expired reusable leases on writer holds (#22847)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Remote task workspaces enforce a single writer run at a time
(`writerRunId`) and intentionally keep a dirty ended writer held until
its unsaved files are saved, proved unchanged, or explicitly abandoned
> - Two edge cases left remote workspaces permanently stuck behind an
ended writer with `"The workspace still has an unfinished writer or save
operation."` (`setup_failed`, HTTP 409)
> - First, `readRemoteWorkspaceWriterHold` checked
`hasRemoteTerminationReceipt` directly on an unused reservation (`dirty:
false`) without resolving an expired `reuse_by_environment` lease
through `resolveRemoteTerminationLease`
> - Second, when a dirty ended writer already had a recorded
continuation or successor run and that successor also ended before
taking over the workspace (for example `controller_lease_lost`), no
recovery pass could revisit the already-superseded writer, leaving the
task wedged forever
> - This pull request resolves expired reusable leases in
`readRemoteWorkspaceWriterHold` and adds
`releaseSupersededRemoteWorkspaceWriter` to safely abandon a superseded
ended writer's stale dirty epoch once its successor has ended, while
keeping every unsaved-files and board-owned export hold fenced
> - The benefit is that wedged tasks recover cleanly without losing
unverified files or bypassing intentional board-owned save holds

## Linked Issues or Issue Description

Refs #21221
Refs #22103

**What happened?**
Remote task workspaces could remain permanently blocked behind an ended
writer run, causing every subsequent run to fail setup with `409` /
`setup_failed`: `"The workspace still has an unfinished writer or save
operation."`:
1. On an unused reservation (`dirty: false`), if the ended writer ran on
a `reuse_by_environment` lease that later expired via reusable-lease
handoff and whose successor tip lease was destroyed,
`readRemoteWorkspaceWriterHold` ignored `resolveRemoteTerminationLease`
and treated the workspace as held forever.
2. When a dirty ended writer was already superseded by a recorded
successor run (`nativeRunFinalizations.failureDetail.successorRunId`,
resolved `explicitUserContinuation`, or resolved
`executionReconciliation` with `continuationRunId`), and that successor
ended (for example `controller_lease_lost`) before taking over or
rebinding the workspace, neither `workspace-recovery-fallback`,
`fresh-continuation-fallback`,
`settlePreparationOnlyRemoteWorkspaceEpoch`, nor
`released-writer-escalation` could ever release the old writer's epoch.

Note: a dirty ended writer with an uncommitted accepted result and an
open board-owned export recovery hold (for example
`native_workspace_sync_out_retry_exhausted` on `sandbox_disk_full`) is
intentionally kept fenced; that hold is preserved here.

**Expected behavior**
- An unused reservation (`dirty: false`) whose expired
`reuse_by_environment` lease resolves to a destroyed tip via
`resolveRemoteTerminationLease` is reported as `{ kind: "free" }`.
- A dirty ended writer whose durable successor has already ended (with
no uncommitted accepted result, open/active recovery hold, unsettled
no-replay hold, running save, or live controller/finalizer lease) has
its stale epoch safely abandoned via
`abandonUnverifiedRemoteWorkspaceEpoch` during workspace reservation or
stranded-writer escalation settlement, so the next run restores the last
committed snapshot into a new directory without overwriting or applying
unverified files.
- Board-owned unsaved-files export holds and live
successors/leases/saves remain strictly fenced.

**Steps to reproduce**
1. Bind a task to a remote execution workspace whose ended writer run
has `dirty: true` and a recorded `location`, plus a durable successor
run recorded on `nativeRunFinalizations.failureDetail.successorRunId`,
resolved `explicitUserContinuation`, or resolved
`executionReconciliation.continuationRunId`.
2. End the successor run (for example `failed` with
`controller_lease_lost`) before it reserves or rebinds a workspace.
3. Call `reserveRemoteWorkspace` for a new run on that workspace (or run
`continueTasksAfterWorkspaceWriterReleased` when the task is stranded
behind a `setup_failed` writer-pending escalation). Before this change,
reservation throws `"The workspace still has an unfinished writer or
save operation."` and the task stays blocked forever.
4. Separately, give a clean (`dirty: false`) ended writer an expired
`reuse_by_environment` lease whose successor tip lease carries a
`destroyed` termination receipt; before this change,
`readRemoteWorkspaceWriterHold` returns `{ kind: "held" }` instead of `{
kind: "free" }`.

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

**Deployment mode**
Self-hosted server / cloud sandbox remote workspaces.

## What Changed

- `server/src/services/remote-workspace-writer-hold.ts`:
- Resolve `environmentLeases` rows through
`resolveRemoteTerminationLease(tx, lease)` in
`readRemoteWorkspaceWriterHold` before checking
`hasRemoteTerminationReceipt` for `unusedReservation`, matching the
repo's other remote termination checks.
- Add `releaseSupersededRemoteWorkspaceWriter`, which checks fail-closed
guards (terminal ended writer, `FOR UPDATE SKIP LOCKED`, no live
controller/finalizer lease, no running snapshot operation on the epoch,
no uncommitted accepted result, identifiable writer issue, no
open/escalated recovery action, no active `systemRecovery`, no unsettled
`automaticRecovery.replay === "blocked"` hold, no unsettled
`restore_unsafe_archive` hold, durable `successorRunId` present, and
every non-caller successor run is terminal and not live) and abandons
the stale epoch via `abandonUnverifiedRemoteWorkspaceEpoch`.
- `server/src/services/remote-workspaces.ts`:
- In `reserveRemoteWorkspace`, attempt
`releaseSupersededRemoteWorkspaceWriter` right after
`releaseUnchangedRemoteWorkspaceWriter` when an ended dirty writer still
holds the workspace.
- `server/src/services/recovery/released-writer-escalation.ts`:
- Lock the bound `executionWorkspaces` row in `continueOne` and attempt
`releaseSupersededRemoteWorkspaceWriter` before
`readRemoteWorkspaceWriterHold`, so tasks already stranded behind a
superseded ended writer's hold unblock and continue once.
- `server/src/__tests__/released-writer-escalation.test.ts`:
- Add red-first behavioral regressions for expired reusable lease
resolution (destroyed vs stopped vs active tip), superseded dirty
writers across all three supersession paths (`coordinator`,
`explicit_continuation`, `reconciliation`) and both `failed` and
`succeeded` writers, stranded-task recovery, and 12 negative safety
guards (including board-owned uncommitted accepted result export holds,
live successors, open recovery actions, active system recovery,
unsettled no-replay holds, unsafe archive holds, running snapshot saves,
and live controller/finalizer leases).

## Verification

- **Red (before production edits)**:
- 5/5 targeted behavioral regressions failed (`destroyed-tip` returned
`held` instead of `free`; `coordinator`, `explicit_continuation`, and
`reconciliation` superseded dirty writers threw `"The workspace still
has an unfinished writer or save operation."`; stranded task stayed
`blocked`), while all safety negative tests passed.
- **Green (at `8159b9a39c`, rebased on `master` after `#22831`)**:
  - `npx tsc --noEmit -p server/tsconfig.json`: passed.
- `node scripts/check-test-budget.mjs --base origin/master`: passed
(`105 nightly suites validated, 1 test file(s) checked`).
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/released-writer-escalation.test.ts`: **25/25 passed**.
- Prior pre-rebase targeted matrix across sibling suites
(`abandoned-workspace-files-hold`, `issue-blocker-stall-wakeups`,
`native-cancelled-workspace-preservation`,
`heartbeat-remote-workspace-busy`, `legacy-workspace-rehome`,
`workspace-recovery-stop-proof`, `superseded-workspace-export-recovery`,
`remote-workspace-save-concurrency`): **185/185 passed**; required CI
covers the full suite, build, and E2E on `8159b9a39c`.

## Risks

- **Low risk, fail-closed design**:
`releaseSupersededRemoteWorkspaceWriter` never touches an unsuperseded
writer, an uncommitted accepted result (board-owned save holds stay
fenced), an open/active recovery hold, an unsettled no-replay hold, a
running save, or a live successor/controller/finalizer lease.
- When abandonment runs, it uses `abandonUnverifiedRemoteWorkspaceEpoch`
to advance the epoch, retain the old root in
`remoteWorkspaceAbandonedEpochs` (never overwritten or applied), and
force the next run to restore the last committed snapshot into a new
directory.
- Row locking follows the existing lock order (`issues` ->
`issueRecoveryActions` -> `executionWorkspaces` -> `heartbeatRuns FOR
UPDATE SKIP LOCKED`), avoiding lock inversions and deadlocks.
- No schema change, no migration, and no Runner protocol change.
- Note on file length: `server/src/services/remote-workspaces.ts` was
already over 1,000 lines; this PR adds only 6 lines there (import +
fallback call) and keeps all new logic in
`server/src/services/remote-workspace-writer-hold.ts` (242 lines).

## Model Used

- Google Gemini (Antigravity agentic coding environment) with tool use
(shell, file read/edit, code search, Vitest execution) and extended
reasoning.

## Checklist

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

> - Paperclip is the open source app people use to manage AI agents for
work
> - Connections give agents actions in other apps, and the Permissions
page controls which actions agents can use
> - A managed Google Workspace connection moved from Paperclip's REST
tools to Google's MCP servers (#22815)
> - Google's MCP servers do not list two Gmail actions, so the catalog
refresh marked them as removed (`disabled`, `mcp_tool_removed`)
> - The Permissions page still sent these two actions as enabled, and
the server refused every save that contained them, except on remote MCP
aggregators
> - An admin could not release the 34 held actions, so the connection
stayed unusable
> - This pull request makes the server accept a removed action for every
connection kind, and makes the UI stop sending disabled or removed
actions
> - The benefit is that an admin can always save the review after a
provider removes actions, and a disabled action still cannot be turned
on

## Linked Issues or Issue Description

Refs #22815

**What happened?**

On a managed Google Workspace connection that runs on Google's MCP
servers, the Permissions page showed "Review 34 new actions". After
"Turn all on" and "Save choices", the save failed with the message
"Couldn't save that — Disabled actions cannot be enabled". The held
actions stayed held.

**What did you expect to happen?**

The save releases the reviewed actions. Actions that Google no longer
offers stay off and do not block the save.

**Steps to reproduce**

1. Connect Google Workspace with the managed method while the transport
is Paperclip REST. Keep all actions on.
2. Move the connection to Google's MCP servers (#22815). The refresh
holds the actions for review, and Google's listing does not include
`gmail__list_threads` and `gmail__search_messages`.
3. Open the connection's Permissions page. Select "Review 34 new
actions", then "Turn all on", then "Save choices".
4. See the error "Disabled actions cannot be enabled".

**Cause**

- `useConnectionPermissionSave.ts` sent `enabledCatalogEntryIds:
[...next.enabled]`. This set came from the saved profile and still
contained the two removed actions.
- `finishGalleryAppConnection` in `server/src/services/tool-access.ts`
refused an enabled row with `status === "disabled"`. It accepted a
removed row (`quarantineReason === "mcp_tool_removed"`) only for remote
MCP aggregators (`isRemoteMcpConnectorMethod`). The catalog refresh
writes `mcp_tool_removed` also for Google Workspace and plugin
connections, so these connections did not get the same exception.

## What Changed

- Server: `finishGalleryAppConnection` accepts a row that the provider's
listing removed (`mcp_tool_removed`) for every connection kind. Only the
catalog refresh writes this marker, and only when the provider's listing
no longer has the action. This is the same behavior that remote MCP
aggregators already had. Any other disabled row is still refused with
"Disabled actions cannot be enabled". A removed row is not active, so
the gateway does not offer it to agents.
- Shared: `@paperclipai/shared` has three named predicates in
`tool-catalog-availability.ts`. `isCatalogEntryOffered` is true for
active and held actions. `isCatalogEntryRemovedByProvider` is true for
`removed` rows and for `disabled` rows with `mcp_tool_removed`.
`isCatalogEntryBlocked` is true for every other disabled row. The server
and the UI use these predicates, so the rule is in one place.
- Server: the review coverage check ignores a reviewed id that the
provider removed after the page loaded. Before this change, that save
failed with "Action review decisions must cover every currently
quarantined action exactly once".
- Server: a save no longer sets a `removed` row back to active.
- UI: a new `withoutUnavailableActions` helper drops catalog entries
that are not offered (`isCatalogEntryOffered` is false) from an enabled
list.
- UI: the Permissions page save (`finishAppPermissions` in
`useConnectionPermissionSave.ts`) sends only available actions as
enabled or Ask first. The page already showed and counted only active
and held actions, so the removed actions do not show, count, or toggle.
The page has no existing pattern for removed actions, so this change
adds no new text.
- UI: the setup flow (`ConnectionSetupFlow.tsx`, which also serves
task-hosted setup) and the pasted-config flow (`PasteConfigTab.tsx`)
also drop disabled actions before they finish a connection. Before this
change, a provider-blocked action (for example a Gmail write action on a
read-only method) could make the first save fail the same way.
`RemoteMcpProductionSetup.tsx` already sends only active actions.
`QuarantinedActionsReview` in `SetupPanel.tsx` selects only from held
actions.

## Verification

- Red, then green:
`server/src/__tests__/google-workspace-mcp-transport.test.ts` → "saves
the review when Google no longer offers actions that were on, and still
refuses a disabled action". The test saves a managed Google Workspace
connection on REST, moves it to Google's MCP servers while Google does
not list `list_threads` and `search_messages`, then saves the review
with the removed actions in the enabled list. Before the fix it failed
with "Disabled actions cannot be enabled". After the fix it passes. The
same test makes sure that a disabled action without the removal marker
is still refused, and that agents are not offered the removed actions.
- Red, then green:
`ui/src/pages/apps/app-detail/action-permissions.test.ts` →
"finishAppPermissions never asks to turn on an action Google no longer
offers or a disabled action". Without the filter, the test fails.
- `packages/shared/src/tool-catalog-availability.test.ts` covers the
three predicates.
- The transport test also sends the removed ids in
`reviewedCatalogEntryIds`. Without the coverage fix it fails with
"Action review decisions must cover every currently quarantined action
exactly once". It also makes sure that the removed rows stay disabled
after the save.
- Local runs: `google-workspace-mcp-transport.test.ts` and
`tool-access-service.test.ts` (542 passed). UI tests in `app-detail`,
`features/connections` and `pages/tools` (143 passed).
- `pnpm verify` selected the full server suite (1520 files) because
`tool-access.ts` is a shared service. On this machine, under load from
other sessions, 31 of 33876 tests failed. The run output did not keep
the names of the failed tests. The touched test files pass when run
alone, and the CI server shards run the full suite on the final head.
- `tsc --noEmit` for `server` and for `ui/src`.

## Risks

- Low risk. The security rule stays: a disabled action that the provider
did not remove cannot be turned on.
- Behavior change: Google Workspace and plugin connections now accept a
removed action in the enabled list, as remote MCP aggregators already
did. The UI no longer sends removed actions, so after a save from the
page a removed action stays off if the provider lists it again.

## Model Used

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

## Checklist

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

> - Paperclip is the open source app people use to manage AI agents for
work
> - A task on a reusable cloud sandbox resumes the same sandbox on its
next run, and the run restores the last saved workspace there before the
agent starts
> - On staging, one run filled its sandbox disk. Its save failed, and
the task correctly continued from the last save
> - The next two runs resumed the same full sandbox. Each restore failed
with a full disk, and Paperclip treated that as a permanent refusal, so
the task went to Blocked with no automatic retry
> - The full disk belonged to the sandbox, not to the saved workspace. A
new sandbox would have restored the save
> - This pull request takes a reused sandbox out of reuse when a restore
finds its disk full, and lets the bounded setup retry restore on a new
sandbox
> - The benefit is that the task recovers by itself, and nobody has to
free space in a sandbox or press Retry

## Linked Issues or Issue Description

**What happened?**
On hosted staging (2026-11-24), a Paperclip Runner task went to Blocked
after a full sandbox disk:
- 21:53Z: the run's agent filled a new Daytona sandbox during a 6-minute
turn. The final workspace save failed with
`native_workspace_sync_out_retry_exhausted` ("Saving the workspace
stopped because the sandbox disk is full"). Its finalization sibling
ended with `execution_reconciliation_required`.
- 22:17Z and 22:26Z: two runs failed during setup with
`remote_workspace_restore_failed` (step `sandbox_restore`, operation
`upload`, reason `sandbox_disk_full`). Both recorded
`remoteWorkspaceRestore.retryable: false`, so no retry was scheduled and
a recovery action went to the board.

Forensics from `/api/heartbeat-runs/:id/events` and the environment
leases: all three runs used the same provider sandbox (three lease rows,
one `providerLeaseId`, policy `reuse_by_environment`). The two restores
resumed the sandbox that the first run had filled.

**Expected behavior**
A restore that fails only because a resumed sandbox is full continues on
a new sandbox automatically.

**Steps to reproduce**
1. Run a task on a reusable sandbox environment until the sandbox disk
is full and the save fails.
2. Wake the task again. Lease selection resumes the same sandbox.
3. The restore upload fails with ENOSPC. The run fails with `retryable:
false`, and every later wake picks the same sandbox again.

**Paperclip version or commit**
Staging Core on `f7fd3f43fe` (current `master` has the same code path).

**Deployment mode**
Hosted staging (cloud), Daytona sandbox provider plugin, reusable leases
on.

**Agent adapter(s) involved**
`paperclip_runner` (setup runs before dispatch in legacy mode).

**Root cause**
`prepareRemoteWorkspace` in `server/src/services/remote-workspaces.ts`
treats every restore failure that names a `reason=` as a permanent
refusal. For `reason=sandbox_disk_full` on a resumed sandbox, the reason
belongs to the sandbox. Lease selection kept choosing that sandbox, so
every attempt failed the same way.

Refs #22835 (the earlier stale snapshot qualification failure on the
same agent, a different cause).

## What Changed

- Add `server/src/services/full-reusable-sandbox.ts`:
- `isRestoreSandboxDiskFullRefusal` matches a restore refusal with
`reason=sandbox_disk_full` at any stage.
- `retireFullReusableSandbox` applies only to this run's own active
`reuse_by_environment` lease whose sandbox has an earlier lease row, so
it was resumed. It removes the `reusableSandboxLease` scope and records
`reusableSandboxLeaseSuperseded` (reason `sandbox_disk_full`) with one
compare-and-swap. This is the same pattern that
`native-retired-backup-source.ts` uses.
- `remote-workspaces.ts`: when the sandbox leaves reuse, the restore
failure is no longer a refusal. It is retryable only when the existing
re-check of writer, epoch, clean state and saved version passes.
`run-completion.ts` then schedules the existing bounded retry.
- The retry's acquisition sees the full sandbox as obsolete. The
existing obsolete-lease cleanup destroys it and keeps every protection
(pending export, parked abandoned files). Then it creates a new sandbox.
- A full disk on a sandbox created for the run keeps the current
behavior. A new sandbox has the same disk.
- `doc/task-recovery.md`: document the rule.

## Verification

- Red on `master`: the new `full reused sandbox disk` case in
`server/src/services/remote-workspaces.integration.test.ts` failed with
`retryable: false`, the same result as on staging.
- Green with the fix: the restore is retryable, the lease loses its
reuse scope and gets the marker, and the final restore succeeds. The
existing `full sandbox disk` case (a sandbox created for the run) still
returns `retryable: false` and does not change the lease.
- New `full sandbox disk` case in
`server/src/__tests__/environment-runtime.test.ts`: after the sandbox
leaves reuse, the next acquisition makes no resume call, destroys the
full sandbox (`lease_fingerprint_mismatch`, `expired`), and creates a
new sandbox.
- `pnpm exec vitest run
src/services/remote-workspaces.integration.test.ts
src/__tests__/environment-runtime.test.ts
src/services/native-runtime/native-retired-backup-source.integration.test.ts`:
3 files, 370 tests pass
- `tsc -p server/tsconfig.json --noEmit`: passes
- Review round: the disk-full check moved into
`remote-workspace-transport.ts` with unit cases for the helper, upload
and extract stages. One shared `supersedeReusableSandboxLease` writes
the marker for both callers. A failed lease write keeps the restore
refusal. The integration case now also restores on a new sandbox in a
retry run. 378 tests pass across the four affected files, and `tsc`
passes.
- After deploy: confirm on staging that a disk-full restore on a resumed
sandbox retries on a new sandbox, and that the affected task leaves
Blocked.

## Risks

- A run that hits this path spends one failed setup attempt (about 15
seconds) before the retry gets a new sandbox.
- The full sandbox is destroyed through the existing obsolete-lease
cleanup. That path already skips a sandbox with a pending export or
parked abandoned files. Files from an abandoned epoch were already given
up before this restore.
- The rule needs an earlier lease row on the same sandbox. A sandbox
created for the run is not affected.
- Not covered here: the first loss, where the agent fills a new sandbox
and the final save needs free space for its archive. That needs separate
work.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use
(shell, browser forensics on staging through Claude in Chrome).

## 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 04:26:49 -06:00
DottaandClaude Opus 5.5 5347c01de5 fix(antigravity): give the follow-up after a swarm its result, and say each thing once in the thread (#22893)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - A task thread shows an agent's runs, and each new run starts from
the task's saved context
> - A second hands-on check of Google Antigravity `/swarm` runs (after
#22886) still found gaps
> - The first ordinary follow-up after a swarm was slow: it spent
minutes searching the instance's run logs to learn what the swarm did
> - The thread also showed each file twice, lost the "Swarm" note after
a reload, and read "Swarm Swarm started…"
> - This pull request gives the next run the swarm's result in its
opening context and removes the prompt's pointer to run records, and it
fixes the four thread problems
> - The benefit is a faster follow-up after a swarm and a thread that
says each thing once

## Linked Issues or Issue Description

Refs #22886

**What happened?**
1. After a finished `/swarm`, the ordinary follow-up "append three to
v1.txt" took 4 min 6 s (an earlier one took 5.5 min). The agent read the
server's raw run log of the swarm run with about 20 shell commands,
searched the instance folder, and listed processes. Other follow-ups
took 41 s and 105 s.
2. Each file showed twice: the run's file card, and a second card under
the final reply (from the reply's "Download: v1.txt" link). This also
happened on the ordinary follow-up.
3. The "Swarm" note on the user's message showed while live, but not
after a page reload.
4. Swarm activity rows read "Swarm Swarm started in the task folder…",
with the word twice.

**Expected behavior**
1. The follow-up starts with what the swarm did, so it has no reason to
search for it.
2. Each file shows once per run, as the run's file card.
3. The "Swarm" note shows after a reload.
4. A swarm row reads its sentence once.

**Steps to reproduce**
1. Send `/swarm Create v1.txt containing "one" and v2.txt containing
"two", one helper per file, then verify both.` to a Google Antigravity
agent.
2. When it finishes, look at the files and the activity rows, then
reload the page.
3. Send the ordinary follow-up `append three to v1.txt` and time it.
4. Put another task in Plan mode and send `/swarm do something`.

## What Changed

- Follow-up context (cause of item 1). A swarm runs in the Antigravity
CLI, and an ordinary turn runs on the registry route. The ordinary route
cannot reopen the swarm's conversation, so the Runner refuses the saved
session and the server starts a fresh one. That fresh session gets the
same wake prompt as any other turn. Before this change, its only record
of the swarm was the task continuation summary, and that summary listed
no files ("No file or route paths were detected"; the path detector only
knows repository folders such as `server/`). It also gave three run ids
and said "Detailed shell/tool commands remain in the run log and
transcript." The agent followed that line: its first searches matched
the swarm's run id, and an earlier follow-up searched for
`transcript*.jsonl` files. An ordinary follow-up after an ordinary turn
gets the same prompt, but it resumes its own conversation, so it already
knows what it did.
- `issue-continuation-summary.ts` (shared by every harness): a new
"Files Delivered" section lists, by name, the files the run handed in as
deliverables (applied or duplicate receipts), newest first, and keeps
earlier runs' names. These names are kept apart from "Files / Routes
Touched", because a deliverable's name is not always its path. The run's
own checks are listed, read through the shared accepted-result reader.
The summary contains no run ids, adapter names or log locations. The
"Commands Run" section is removed: it held only the run id and the log
pointer. The summary reaches the next turn through the existing
mechanism (the wake prompt's "Issue continuation summary" and the
continuation evidence).
- Server: `GET /issues/:id/recent-comments` and both chat bootstrap
routes now add the swarm marker with the same shared rule
(`withAntigravitySwarmMarkers`) as the comment list, the single comment
and the POST response. A cold task page reads this recent window, so the
marker was missing after a reload.
- UI: a reply does not show a second card for a file that its own run
already shows as a file card. The reply text and its links do not
change. A later run's reply that links the same file still shows the
file.
- UI: a swarm progress row shows its sentence without the "Swarm" label.
A failed or stopped row keeps its label and marker. Live and settled
rows use the same rule.

Not changed, by investigation:
- "Check passed cat v1.txt one\nthree" and "verifier check on swarm
board #6": the model wrote both strings in its `paperclip_finish` call.
The Runner's first record of the result already holds the literal
backslash and the board number, so this is model text, not Paperclip's
presentation.
- The inline "Download: v1.txt" links in the reply are the model's own
words, so they stay.
- No read-confinement policy is added. The agent finds the instance
folder from its working directory, not from the prompt.
- A refused send still shows its reason twice (inline under the composer
and as a toast). Each attempt to remove the toast missed a send path,
which could leave a refusal with no visible reason. A repeated reason is
better than a missing one, so this PR does not change the toast.

## Verification

- Red/green `server/src/__tests__/issue-continuation-summary.test.ts`: a
swarm's accepted result (from a live run, with ids replaced) is built
into the summary and rendered into the follow-up's wake prompt. The
prompt contains the hand-in summary, `v1.txt` and `v2.txt` under "Files
Delivered" (one with a different content reference and a duplicate
receipt), and the verifier check. A later run lists its own delivered
file first. A full path list still takes the latest run's path first. It
contains no run id, "run log", "transcript", attachment path, digest or
adapter name. A later run keeps the files listed. This failed before the
change.
- Red/green `server/src/__tests__/issue-chat-bootstrap-routes.test.ts`
(embedded Postgres): for an ordinary task and a conversation, a recorded
`/swarm` request carries `nativeCommand: "swarm"` on `GET /comments`,
`GET /comments/:id`, `GET /recent-comments`, `GET
/issues/:ref/chat-bootstrap` and the batch chat bootstrap. It failed on
`recent-comments` before the change.
- Red/green `ui/src/components/TaskChatThread.test.tsx`: a reply that
links its run's file shows no second card; a later run's reply still
shows it. It failed before the change.
- Red/green `ui/src/components/task-chat/antigravity-thread.test.tsx`:
the live swarm fixture's rows read "Swarm started in the task folder…"
(no doubled word), and live rows equal settled rows.
- Focused suites: UI `TaskChatThread.test.tsx` and
`src/components/task-chat` (925 tests), server bootstrap routes (19
tests) and continuation summary (7 tests) pass. UI and server typechecks
pass.
- Not proved without a live run: that the next follow-up after a swarm
is faster. The tests prove the opening input; the agent's behavior with
that input needs a live Antigravity run.

## Risks

- The continuation summary wording changes for every harness that runs
on a task (every adapter whose finished run refreshes the summary, not
only Antigravity): no run ids, no adapter name, no "Commands Run"
section, and a new "Files Delivered" section when the run registered
deliverables. Nothing in the code parses those lines. Older saved
summaries keep their text until the next run refreshes them.
- One extra indexed activity-log query for each recent-comments or
chat-bootstrap read (the same query the comment list already runs). The
bootstrap budget test still passes.
- The second-card rule matches only a file whose card belongs to the
same run as the reply.

## 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 02:50:44 -06:00
DottaandClaude Opus 5.5 3fbf872d9e fix(antigravity): make the task thread read in plain language (#22886)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - A task thread shows what an agent did during a run, as a list of
activity rows under its reply
> - Google Antigravity runs (ordinary and `/swarm`) send no tool
identity, so each row was named after the CLI's display title
> - Users saw rows like "Ran a command · failed Run
mcp_paperclip_paperclip_finish", "Ran File runtime paperclip runner acpx
…", lowercased sentences, and a sha256 dump
> - Each attached file also showed twice, nothing marked a message as a
swarm request, and a refused send only showed a short toast
> - This pull request gives Antigravity tool calls the identity other
harnesses send, and makes the thread read the same live and after the
run
> - The benefit is a task thread that reads in plain language for
Antigravity, with fixes that also help other harnesses

## Linked Issues or Issue Description

**What happened?**
In a live Antigravity `/swarm` run, the task thread showed raw tool
names and internal paths. Examples: "Run mcp_paperclip_paperclip_finish
· failed", "Ran File runtime paperclip runner acpx 5230… antigravity
home … SKILL md", "Ran Swarm started in the task folder with gemini 3 8
flash low …" (lowercased, punctuation removed), "Registered title:
u1.txt, sha256: 7692…". The live list and the finished list used
different words. The CLI's first reads of u1.txt failed ("must be an
absolute path") and were read again successfully, but the thread showed
"failed". Each file showed twice: a file card, and an agent message
"Prepared u1.txt for this response." with a second card. The user's
bubble did not show that the message was a swarm request. When the
server refused a send (for example `/swarm` in Plan mode), only a short
toast explained it.

**Expected behavior**
Rows say what the agent did in plain words, the same while live and
after the run. No raw tool names, internal paths, hashes or key/value
dumps. The refused-then-accepted completion call is hidden as for every
other harness. A failure that a later call recovered reads as "retried".
Each file shows once. A swarm request has a small "Swarm" marker. A
refused send keeps an inline, dismissible error under the composer.

**Steps to reproduce**
1. Assign a task to a Google Antigravity agent with the experimental
swarm setting on.
2. Send `/swarm Create u1.txt containing "one" and u2.txt containing
"two", one helper per file, then verify both.`
3. Expand the activity list while the run is live, and again after it
finishes.
4. Put another task in Plan mode and send `/swarm do something`.

## What Changed

- Runner (Antigravity-owned): new `antigravity-tool-identity.ts` names
each call. Paperclip bridge tools become
`mcp__paperclip__<canonicalRunnerToolName(tool)>` (from the CLI's
`mcp_paperclip_<tool>`, an ordinary run's `paperclip_<tool>` title, or
ACP `_meta.mcp`). Native CLI tools keep their own names (`run_command`,
`view_file`, …) with the command as the subject. Reads of the CLI's own
built-in files (its private Antigravity home) are dropped. Swarm
progress lines get one neutral identity (`swarm_update`) whose subject
is the plain sentence. Swarm file locations are task-relative.
- Runner: a narrow activity-adapter hook (`createToolEventProjection`)
applies this in both places that pump an ACPX turn (in-process driver
and sidecar). The sidecar now keeps a provider-supplied tool detail
instead of overwriting it.
- UI: live rows use the call's subject, drop raw technical names
(Paperclip's own tools need no source label), and use the same "verb +
subject" form as settled rows, so both lists read the same.
- UI: a bridge call recorded under its own id (providers that pass no
tool-use id) joins the provider's row for the same Paperclip tool, in
the live log and in stored events. `register_deliverable` reads
"Attached u1.txt"; content digests never show in an input summary.
- UI: a failed call whose later call of the same tool on the same target
succeeded shows as "· retried" (token-only, same muted style).
Unrecovered failures stay "· failed".
- UI: generated "Prepared <file> for this response." receipts are hidden
for any file that already shows as the run's file card (before, only
images).
- Server + shared + UI: `IssueComment.nativeCommand` ("swarm") is
derived read-only from the server's own activity record on comment list,
get and the POST response. The user's bubble shows a small "Swarm" note.
The `/swarm` eligibility rule (`isAntigravityAgent`,
`antigravitySwarmAvailable`) now lives in `packages/shared`; the
composer shows a light hint when the text starts with `/swarm` and the
assignee can run a swarm.
- UI: the composer keeps the server's message as an inline, dismissible
error after any 4xx refusal, until dismissed or the next send. The
optimistic "Working" row behaviour is unchanged.

Not changed, by design: after a reload, a settled run's activity is
deferred behind "More run output" for every native harness (cold-load
speed), so Antigravity already matches the others.

## Verification

- Red/green runner test `antigravity-tool-identity.test.ts` with a
fixture rebuilt from a live swarm run's updates (ids, paths and hashes
replaced): names, subjects, dropped internal reads, hidden finish
identity, ordinary-run titles and `_meta.mcp`.
- Red/green UI test `antigravity-thread.test.tsx` renders the real run's
stored events (settled) and the same events through the live run-log
parser. It asserts the exact rows, "retried" reads, one "Attached" row
per file, no finish rows, no raw names/paths/hashes, and live ==
settled. It fails on master (raw "Ran Swarm update …", "Read · failed",
"Registered title: …, sha256: …").
- Red/green `TaskChatThread.test.tsx`: a prepared text file shows once;
a refused send shows the server message inline until dismissed and the
Working row clears; only a server-marked comment shows "Swarm".
- `TaskChatComposer.test.tsx`: the `/swarm` hint shows only for an
Antigravity assignee with the setting on.
- Server `antigravity-swarm-request-path.test.ts` (embedded Postgres):
only the user's recorded request is marked; text, metadata, another
user's or an agent's comment are not.
- Local: paperclip-runner acpx/sidecar/provider-events suites, UI
task-chat/transcript/adapters/thread/hooks suites (1630 tests), server
swarm suite, and shared/server/ui/runner typechecks pass. `pnpm verify`
exited 2 (broad input), so CI supplies the broad coverage.

Before (live swarm run, done state):

```
Ran This swarm runs on the google account of this agent s google connection
Ran File runtime paperclip runner acpx 523076a3 3689 4b28 9910 c101bc6b64d8 97d9fb76f6aa11b6 a…
Ran File u1 txt · failed  u1.txt
Ran a command · failed
Registered title: u1.txt, sha256: 7692c3ad3540bb803c020b3aee66cd8887123234ea0c6e7143c0…
```

After (same events, settled and live):

```
Swarm  This swarm runs on the Google account of this agent's Google connection.
Swarm  Started helper writer1: Create a file named u1.txt in the current workspace directory containing exactly "one"
Read · retried  u1.txt
Read  u1.txt
$ shasum -a 256 u1.txt u2.txt; wc -c u1.txt u2.txt
Attached  u1.txt
Swarm  Files changed in the task folder: u1.txt, u2.txt
```

## Risks

- Live tool rows for all harnesses no longer show a raw technical name
("Paperclip · search_tasks", "Bash") next to the activity. Rows with a
concrete subject now read like settled rows ("Read README.md", "$ npm
test"). This is a deliberate wording change.
- `register_deliverable` reads "Attached <file>" for all harnesses.
- Generated file receipts are hidden for any file with its own card, not
only images. Human text and agent progress with attachments stay visible
(the same marker and link checks as for images).
- Bridge-call pairing is display only and matches only a Paperclip tool
of the same name that is in flight. Claude already shares one id and is
unchanged.
- One extra indexed activity-log query per comment list or get. No
schema 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`) 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 01:45:06 -06:00
DottaandClaude Opus 5.5 f1dd9288d1 fix(google-workspace): show agents Paperclip's refusal text and a stable Google error code (#22881)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Agents call Google Workspace through Google's MCP servers. Paperclip
checks the arguments before it sends a call (#22815, #22706)
> - The Paperclip Runner wrapper for assigned tools sends the agent only
a stable code. It does not send the provider's free text (#22723)
> - Paperclip's own refusals had no code. Google's errors had no code.
So the agent saw only `assigned_tool_error: The connected tool reported
an error.`
> - The agent did not know which argument to remove, or that it must
delete one occurrence. It retried blindly and stopped
> - This pull request gives each Paperclip refusal a stable code and
sends its Paperclip-written text. It gives each Google error a stable
code from Google's status. It records the code on the failed call event
> - The benefit is that the agent can fix its call, and an admin can see
why a call failed

## Linked Issues or Issue Description

Refs #22815
Refs #22723
Refs #22842

**What happened?**
On the staging tester (build 1b4ebec), a Workspace Tester agent on
OpenCode + DeepSeek on the native runtime ran a QA task. Three Calendar
calls returned only `assigned_tool_error: The connected tool reported an
error.`:
1. `list_calendars` with an extra argument `bogus: 1`. Paperclip refused
it before dispatch (`dispatched: false`).
2. `delete_event` with a recurring series ID. Paperclip refused it
before dispatch (`dispatched: false`).
3. `respond_to_event` "accepted" on an event that the user organises.
Google returned an error. The agent retried blindly and stopped. The
failed call event had an empty `errorCode` and `errorMessage`.

**What did you expect to happen?**
1. The agent sees `unknown_argument:` and the refusal text that names
the unknown argument and lists the accepted arguments.
2. The agent sees `recurring_series_delete_refused:` and the text that
tells it to pass one occurrence.
3. The agent sees a stable code from Google's structured error, for
example `google_permission_denied`. The failed call event records this
code.

**Steps to reproduce**
1. Connect Google Workspace on Google's MCP servers and give an agent on
the Paperclip Runner access.
2. Call Calendar `list_calendars` with `{ "bogus": 1 }`.
3. Call Calendar `delete_event` with the ID of a recurring series.
4. Call Calendar `respond_to_event` on an event that Google refuses.
5. Each call returns only `assigned_tool_error: The connected tool
reported an error.`

## What Changed

- `argument-guards.ts`: each refusal now returns `{ code, message }`.
The codes are `unknown_argument`, `invalid_arguments`,
`invalid_file_id`, `request_kind_refused`,
`recurring_series_delete_refused` and `delete_target_unverified`.
- `tool-gateway.ts`: a Google MCP preflight refusal returns
`errorDetails` with the code and the Paperclip text (`paperclipRefusal`)
beside the result. Only Paperclip code sets this field, so a provider
result cannot forge it. A Google MCP error result gets `errorDetails`
from the new `googleWorkspaceMcpErrorDetails`. The three tool error
throw sites use these details first.
- `google-workspace-rest-dispatch.ts`: `googleWorkspaceMcpErrorDetails`
finds Google's HTTP status (`error.code`, a status name such as
`PERMISSION_DENIED` mapped to its canonical HTTP status, or `HTTP 403`
in the text). It gives the status and Google's error body to the REST
tools' `googleError`, so there is one Google classification. The code is
`google_<kind>`, for example `google_permission_denied`,
`google_invalid_argument`, `google_not_found`, `google_unavailable`, or
`google_unauthenticated` / `google_insufficient_scope`. Otherwise the
code is `google_error`. `google_rate_limited` is retryable.
`google_unavailable` is retryable only for a read action: a write can
already be applied when Google reports a server error. Google's text
never becomes a code.
- `assigned-mcp-tools.ts`: `toolReportedError` sends `paperclipRefusal`
text after the code, bounded to 2,000 characters. Without it, the
message stays `<code>: The connected tool reported an error.` (#22723
rule).
- Every failed call event writer (`tool_call_events`, `call_failed`:
agent call, approved action, connection test, plugin tool) now records
`errorCode` (the tool code, else the reason code) and `errorMessage`
through one helper. The 30-day Google Technical Information sweep from
#22842 already clears `tool_call_events.error_message` for Google
connections. The invocation row is unchanged (`errorCode: tool_error`,
`errorMessage`: the text).
- README of the Google Workspace tools: the codes and what the agent
sees.

Why Google's text stays out: #22723 sends only a stable code because
provider text is untrusted. It can carry prompt injection or internal
details. This reasoning applies to Google's text, so this change keeps
it. In a test, an injection-style Google error message was blocked by
the result screen, which shows that this text is a real risk.
Paperclip's refusal text is trusted: Paperclip wrote it. It echoes only
the argument names that the agent sent and the argument names from the
tool's schema, which the agent already has.

## Verification

- Red/green: the first three new tests in
`server/src/__tests__/google-workspace-mcp-transport.test.ts` ("what an
agent on the Paperclip Runner sees when a call fails") use the fake
Google MCP server and the native-runtime assigned tool path
(`buildPaperclipRuntimeMcpServers` + `createAssignedMcpTools`). With the
gateway and wrapper changes reverted, all three fail. With the changes,
all three pass:
- `list_calendars { bogus: 1 }` → `unknown_argument: Invalid arguments
for list_calendars: unknown argument "bogus". Accepted arguments:
pageSize, pageToken. Nothing was sent to Google.` Event `errorCode:
unknown_argument`, `dispatched: false`, nothing sent to Google.
- `delete_event` on a series → `recurring_series_delete_refused: This ID
is a whole recurring series. … Pass one occurrence's ID (from
list_events). Nothing was deleted.` Event `errorCode:
recurring_series_delete_refused`, `dispatched: false`.
- `respond_to_event` with a Google 403 `PERMISSION_DENIED` →
`google_permission_denied: The connected tool reported an error.` with
no Google text. Event `errorCode: google_permission_denied`,
`errorMessage`: Google's text.
- A fourth test approves an Ask first `respond_to_event` that Google
refuses. The failed call event has `errorCode: google_permission_denied`
and Google's text.
- Unit tests: guard codes (`argument-guards.test.ts`),
`googleWorkspaceMcpErrorDetails` classification, 5xx retry for reads
only, and its free-text refusal
(`google-workspace-rest-dispatch.test.ts`), refusal text only from the
gateway detail and bounded (`assigned-mcp-tools.test.ts`).
- Focused run: `npx vitest run` on the tool gateway, tool gateway
service, content deletion, Google connection removal, Google Workspace
tools, dispatch, assigned tools and MCP transport tests: 63 files, 1,925
tests passed.
- `pnpm exec tsc --noEmit -p server/tsconfig.json`: passed.
- `pnpm verify`: exit 2 (the README is a broad input). Required CI
covers the rest.

## Risks

- Low. The change touches only connected tool errors. Approval,
revocation and gateway failures are unchanged.
- A failed call event now records `errorMessage` for every connection,
not only Google. The invocation row and the audit event already hold
this text. For Google connections, the 30-day sweep clears it.
- `errorCode` on the call event holds a short code such as
`google_permission_denied`, not Google text. The sweep does not clear
it, as on the invocation row.
- The ACPX runner feedback (Rust) keeps only the leading code from a
failed tool result. Harnesses on that path now see the stable code (for
example `unknown_argument`) but not the refusal text. OpenCode on the
native runtime sees the full text. A runner change is out of scope.
- A JSON-RPC protocol error from Google (not a tool error result) keeps
its current path (`remote_mcp_error`).

## Model Used

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

## Checklist

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

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 23:46:35 -06:00
DottaandClaude Opus 5.5 06c184a92b test(heartbeat): let a slow wait attempt finish instead of failing at its deadline (#22880)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Master deploys to staging only after the "Cloud readiness" workflow
passes
> - One test in the deferred receipt suite failed on a loaded 8-core CI
runner, so the Docker image build was cancelled and every merge was held
> - The test does not find a product defect. Its wait helper rejects at
its deadline while an attempt that would pass is still running
> - This pull request makes the deadline stop further retries, but lets
the attempt in flight decide the result
> - The benefit is that master deploys again, and the suite fails only
when the expected state is really absent

## Linked Issues or Issue Description

**What happened?**
The "Cloud readiness" run for master failed two times in "General tests
(server (1/10))". The failing test was
`deferred-execution-receipt-work.test.ts > dispatches task Retry past a
repeatedly invalidated backlog into real process output`. The error was
"Expectation did not complete before its deadline", with no assertion
error. The same test also failed on master before #22865 (an earlier
readiness run on 2026-11-25 01:12Z), so #22865 did not cause it.

**What did you expect?**
The test passes when the Retry run starts and succeeds, also on a slow
runner.

**Steps to reproduce**
Make `drainActiveRunExecutions` about 1 s slower, as on the loaded
runner (see Verification). The test then fails every time with the same
message.

**Root cause**
`waitForReal` set a wall-clock deadline and rejected when it fired, also
while an attempt was still awaiting. Each attempt calls
`drainActiveRunExecutions`, which waits for the real child process and
its run writes. On the CI runner this test takes 21 to 27 s (2 s alone
on a fast machine), so one drain can take longer than a deadline. The
tightest deadline is the 1 s default in `finish()`. A deadline that
fires during the first attempt rejects with no `lastError`, which is the
exact CI message. The failed runs stopped at 20.9 s, 21.9 s and 23.0 s,
and that is where `finish()` runs in a 26 to 27 s passing run.

## What Changed

- `server/src/__tests__/deferred-execution-receipt-work.test.ts`: in
`waitForReal`, the deadline marks the wait as expired. If no attempt is
running, it rejects as before. If an attempt is running, that attempt
decides: a pass resolves, a failure rejects with its real assertion
error. No deadline, assertion or test step changed.

## Verification

- Red: a local experiment (not committed) made
`drainActiveRunExecutions` 1.1 s slower in this test. Before the fix: 3
of 3 runs failed with "Expectation did not complete before its deadline"
at the helper deadline line. After the fix: 5 of 5 runs passed (14.5 to
14.9 s).
- Under CPU throttling (`taskpolicy -b` with busy loops), one attempt's
drain took 19.6 s and failed the 15 s wait before the fix. This shows
the same slow-attempt failure at the other deadlines.
- Without the experiment: the full test file passes, and the test passes
alone (about 2 s).
- The readiness shard command `pnpm test:run:general -- --group
general-server-without-chat-or-native-runner --shard-index 0
--shard-count 10` with 7 workers passed this test locally. Results are
in the PR comments.
- CI supplies the 8-core runner coverage.

## Risks

- Low risk. The change is test-only. A wait now can last one attempt
longer than its deadline. The 90 s test timeout still bounds an attempt
that never returns.

## Model Used

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

## Checklist

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

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 23:16:26 -06:00
DottaandClaude Opus 5.5 aeafc6a190 fix(google-workspace): adopt Google's definitions over any shipped REST definition after the switch back (#22874)
## 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
save each action's definition, and a catalog refresh holds a changed
definition for review
> - #22815 moved Gmail, Drive, Docs, Sheets, Slides and Calendar from
Paperclip's REST tools back to Google's MCP servers
> - It said that the first refresh after the switch replaces saved REST
definitions with no hold, but it recognised only the current REST
schemas
> - Rows saved by the first REST launch (#22634) carry older schemas, so
the refresh held 34 of 36 actions on a staging test instance and agents
lost all Google actions
> - This pull request recognises every shipped REST schema, so the
switch back holds none of these actions
> - The benefit is that the switch back keeps agents working with no
admin review, and a Google definition that Paperclip never shipped is
still held

## Linked Issues or Issue Description

Refs #22815

**What happened?**

On a staging test instance (build 1b4ebec), a Google Workspace
connection ran on the REST tools since Nov 23. After the deploy, the
first catalog refresh set 34 of 36 Google actions to `quarantined` with
`pending_review`. Agents lost every Google action until an admin reviews
them. `gmail__list_threads` and `gmail__search_messages` became
`disabled` with `mcp_tool_removed`, which is expected.

Root cause: `formerPaperclipDefinedTool` compared the saved schema hash
with the hash of the REST definition in the current build only. #22706
changed all 36 REST input schemas (it adds `additionalProperties:
false`, and it changes `list_threads` and `search_threads`). A row that
a refresh saved on a #22634 build, and that no refresh updated after
#22706, has a #22634 hash. I computed the hashes from the code at
b865dd1 (#22634), 6a07420 (#22706) and master: all 36 hashes differ
between #22634 and #22706, and master equals #22706. So every saved row
failed the match, and the refresh held it.

**What did you expect to happen?**

The refresh saves Google's definitions with no hold. It keeps Off, Ask
first and the review fields of each action.

**Steps to reproduce**

1. Connect Google Workspace on Google's MCP servers.
2. Switch the six services to `paperclip_rest` and refresh the catalog.
3. Make the saved rows carry the #22634 input schemas (a refresh on a
#22634 build does this).
4. Switch back to `google_mcp` and refresh the catalog.
5. See that every action is `quarantined` with `pending_review`.

## What Changed

- `server/src/google-workspace-rest-tools/shipped-schema-hashes.ts`
lists the input schema hash of each REST tool for each shipped revision
(#22634 and #22706).
- `shippedPaperclipSchemaHashes` replaces `formerPaperclipDefinedTool`.
A refresh does not hold an action when its saved schema hash is in that
list.
- No automatic repair for actions that are already held. The hold
replaced the saved definition with Google's, so the row does not show
its earlier definition. I tried a release from call history
(`tool_invocations.catalog_schema_hash` after the last successful
refresh before the hold). Review showed that a refresh can save rows and
stop before it writes its success audit (for example, at a restart).
Then a call from before that refresh can wrongly prove a later Google
change. No other record proves the earlier definition, so there is no
safe automatic signal. These actions stay held, and a person reviews
them. A test shows this.
- `fixtures/input-schemas-22634.json` keeps the #22634 schemas for the
tests.
- The folder README and `doc/memory/google-connector-memory.md` describe
the change.

## Verification

- `pnpm exec vitest run
src/__tests__/google-workspace-mcp-transport.test.ts` (in `server/`): 25
tests pass with the boundary test.
- Red before the fix: "adopts Google's definitions with no hold when the
rows carry the #22634 REST definitions" failed with 10 of 10 actions
held.
- The tests run the real catalog refresh against a fake Google that
serves REST and MCP. They follow the history: MCP rows, then REST rows
(#22634 and #22706), with review fields, Off and Ask first, then the
switch back.
- "holds for review a Google definition that Paperclip never shipped": a
saved hash that Paperclip never shipped is held at the switch, and a
later change in Google's schema is held.
- "keeps an action that a switch before this fix held for review held":
a later refresh does not release an action that an earlier switch held.
- `src/services/google-workspace-rest-dispatch.test.ts`: the list
contains the current hash of every REST tool, and the hash of every
#22634 schema in the fixture.
- `pnpm verify` exited 2 (the README is a broad input). I ran the 21
test files that use the catalog refresh or the REST dispatch. All pass
except `email-channels.integration.test.ts`, which fails in this
worktree because a bundled skill file is not on disk. That file does not
touch this change. Required CI covers the rest.

## Risks

- Connections that a switch already held (the staging test instance)
keep those actions held. An admin must review them.
- A future change to a REST schema must add its hash to the list. A test
fails when it is missing.
- No migration. No change for connections that are not Google Workspace.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, 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-24 22:40:57 -06:00
Devin FoleyandPaperclip 1b4ebec820 test: load remaining route modules during setup (#22872)
## Thinking Path

> - Paperclip exposes company portability and routine APIs.
> - Route fixtures install mocks before loading those APIs.
> - Their first test currently pays the cold module-load cost inside its
test timer.
> - Exact-source verification can time out before that first request is
checked.
> - This PR moves module loading into the existing setup hooks.
> - Each company app keeps a fresh module instance, and routine mocks
still reset for every test.

## Linked Issues or Issue Description

Refs #22870.

**What happened?**

The first company-portability and routine-route tests time out at 15
seconds during cold module loading. Both cases failed again in
[exact-source
verification](https://github.com/paperclipai/paperclip/actions/runs/45534861756/job/138942393280).
The attachment fixture fixed in #22870 passed that run.

**Expected behavior**

Load each route graph after its mocks are installed, in setup. Keep the
existing request assertions, test limits, and per-app state isolation.

**Steps to reproduce**

Run the first case from each original fixture in a cold process with a
three-second test budget. Both time out. With the setup change, all 101
tests across the company-portability, routine, and attachment fixtures
pass at that same limit.

## What Changed

- Share the company route loader across both app factories and
`beforeAll`. Keep the existing unique import query for each app, so its
import-job map stays separate.
- Load routine modules at the end of `beforeEach`, after module reset,
mock registration, and default mock values. Keep the sequential imports
and the per-test reset.
- Reuse each loader in its app factory. Keep the existing test limits
and assertions.

## Verification

- Node 25.6.1 red/green: both original first cases time out with
`--testTimeout=3000`.
- `pnpm exec vitest run
server/src/__tests__/company-portability-routes.test.ts
server/src/__tests__/routines-routes.test.ts
server/src/__tests__/issue-attachment-routes.test.ts --testTimeout=3000
--maxWorkers=1 --no-file-parallelism`: all 101 tests passed.
- `pnpm exec tsc --noEmit -p server/tsconfig.json` passed.
- `pnpm verify --base origin/master --explain` retained 1,921 of 2,276
test files conservatively and requires broad CI coverage. The focused
checks above passed; required CI supplies the final-head coverage. No
full local suite pass is claimed.
- Added-line secret and PII scan passed.
- Greptile scored `a22ce8a1358d479e08beb49622278428fe2d3dd4` 5/5 with no
unresolved findings. All current-head CI checks passed. GitHub reports
the branch clean and mergeable.

## Risks

The fixture must load modules after installing its mocks. Routine
imports still follow each test's reset. Company imports still use a new
query key per app, preserving independent job maps and cross-user tests.
Setup remains bounded by the existing hook timeout. The helpers stay in
these large test files because they own the fixture mocks and app state.

## Model Used

OpenAI Codex, `gpt-6.1-sol`, xhigh reasoning, with tool use and code
execution.

## Checklist

- [x] Thinking path and issue description included
- [x] Model specified
- [x] Red/green reproduction and all 101 related route tests pass
- [x] Server typecheck passes
- [x] Scope is two test fixtures; no run artifacts or secrets in the
diff
- [x] All required CI gates are green on the current head
- [x] Greptile is 5/5 with no unresolved findings

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-24 19:13:48 -08:00
Devin FoleyandPaperclip 04b0a7c0bc test: load attachment route modules during setup (#22870)
## Thinking Path

> - Paperclip lets teams manage work with AI agents.
> - Issues can contain file attachments.
> - The attachment route tests load a large route module and its
dependencies.
> - The first upload test pays that cold load inside its test timer.
> - Source verification repeatedly times out before that test reaches
its upload assertions.
> - This PR loads the mocked route modules in suite setup.
> - The upload tests keep their existing assertions and timeout.

## Linked Issues or Issue Description

**What happened?**

The first attachment-route test can use its 15-second budget loading the
route module. The same zip-upload case timed out in three exact-source
verification attempts, while the other tests in its file passed. This
holds release publication. See [the latest
failure](https://github.com/paperclipai/paperclip/actions/runs/45527647916/job/138928612528).

**Expected behavior**

Load the shared route modules after installing the suite's mocks, during
setup. Give each upload assertion its normal test budget.

**Steps to reproduce**

Run the zip-upload case from a cold process with a three-second test
budget:

```sh
pnpm exec vitest run server/src/__tests__/issue-attachment-routes.test.ts -t 'accepts zip uploads for issue attachments' --testTimeout=3000 --maxWorkers=1 --no-file-parallelism
```

The original fixture times out. With this change, the whole file passes
under the same three-second test budget.

## What Changed

- Share the route imports through `loadRouteModules`.
- Load them in `beforeAll` after `registerRouteMocks`. Use the existing
30-second setup limit.
- Keep the existing upload assertions and test timeouts.

## Verification

- Red/green on Node 25.6.1: the original zip-upload test times out at
three seconds; the changed file passes all 32 tests at that same limit.
- `node scripts/agent-preflight.mjs --skip-rust-debug` and `pnpm exec
tsc --noEmit -p server/tsconfig.json` passed on Node 25.6.1. The
preflight refreshed the Runner build after newer master changes.
- The conservative local `pnpm verify --base origin/master` sweep
selected 1,920 files. Its initial Node 22 run was stopped after the
engine warning; no full local-sweep pass is claimed. Focused
verification uses the supported Node version; required CI must supply
broad coverage on the final head.
- Added-line secret and PII scan passed.
- All current-head CI checks passed on
`2de7b70bd7977b0b88df450a86e8d1a37d25f2d7`. Greptile scored that head
5/5 with no unresolved findings. GitHub reports the branch clean and
mergeable.

## Risks

This changes one test fixture. Module loading now uses the existing
setup hook budget. The hook still runs after module reset and mock
registration. CI must confirm that module mocking and the full server
suite remain correct. Revert this fixture change if setup order
regresses.

## Model Used

OpenAI Codex, `gpt-6.1-sol`, xhigh reasoning, with tool use and code
execution.

## Checklist

- [x] Thinking path and issue description included
- [x] Model specified
- [x] Red/green reproduction and all attachment tests pass
- [x] Server typecheck passes
- [x] Scope is one test fixture; no run artifacts or secrets in the diff
- [x] All required CI gates are green on the current head
- [x] Greptile is 5/5 with no unresolved findings

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-24 18:42:22 -08:00
627d59c5aa fix(inbox): group repeated provider failures and clear recovered tasks (#22846)
## Thinking Path

> - Paperclip helps people manage work that agents do.
> - The inbox tells a person which tasks need a decision.
> - A provider usage limit can stop several attempts on one task or
affect several tasks.
> - Separate failure cards made it hard to tell which tasks still needed
attention.
> - This change groups failures using the account, reset time, or retry
links that Paperclip can verify.
> - A person can now see which task to retry, which tasks are waiting,
and which ones recovered.

## Linked Issues or Issue Description

**What existing behavior does this improve?**

It improves the Coordinator inbox when a provider limits usage.

**Current behavior**

Repeated run failures can fill the inbox. Resolved failures can still
appear beside open decisions.

**Proposed behavior**

Show personal actions in Needs you, automatic retries and snoozes in
Waiting, and past events in History. Keep an archived retry chain hidden
during automatic attempts. Return it to Needs you when a person must
act.

**Additional context**

Related work includes #18020 on completed tasks, #9704 on archive
behavior, and #21570 on usage limits in chat.

## What Changed

- Group verified account and reset windows. When that evidence is
missing, count linked attempts per task and show the tasks in a
collapsible group.
- Separate the reported reset time from each task’s retry schedule. Keep
unresolved ownership recoveries visible after task closure. Use
persisted native retry requests to preserve the original archive and
increment the attempt count.
- Keep personal archive in the card menu. Put decision receipts and run
logs in History.
- Align inbox filters, tabs, and history. Share empty-state artwork and
placement across Inbox, Goals, Routines, and Secrets.
- Index run-history pages and resumed-work lookups, and rate-limit
history requests per company and viewer. Add synthetic fixtures for both
grouping paths and a manual walkthrough.

## Verification

- The author and a human tester completed the synthetic retry-chain
walkthrough. Chromium also verified archive, repeat failure, exhaustion,
and recovery.
- The 64 focused server tests and the UI and server typechecks passed
before rebasing. See `doc/testing/coordinator-inbox-test-drive.md` to
repeat the manual checks.
- The shared SDK input check and all 64 focused server tests passed
after rebasing. The OpenAPI suite (59 tests), API catalog suite (2,309
tests), and both demo seed paths passed locally after the CI fixes.
- The affected inbox and native-runtime suites passed locally after
merging the upstream conformance test fix in #22854. The browser
access-denial scenarios passed three runs each for 403 and 404.
- The migration checks and 79 focused tests passed, including an
index-plan regression with 5,000 unrelated runs. The migration and query
plan were reverified after renumbering. [Full CI on
`cf52b80161`](https://github.com/paperclipai/paperclip/actions/runs/45529834793)
passed after rerunning a timed-out server shard.

## Risks

The attention feed reads retry ancestry. Long chains can increase query
cost. Task and company checks bound the traversal, and cycle detection
stops repeated visits. Providers that omit the reset time leave the card
with an unknown reset. Migration 0508 adds two indexes concurrently.
Each run-history page returns at most 100 records.

## Model Used

OpenAI Codex, GPT-6 family, with repository editing, local test
execution, and browser verification.

## Checklist

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

---------

Co-authored-by: Scott Tong <scott@scotts-mbp-m5-max.local>
Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-24 18:33:27 -08:00
Nicky Leach 0c3ed144cb Label opt-in traces with the public instance hostname (#22856) 2026-11-24 18:08:46 -08:00
DottaandClaude Opus 5.5 12944919c6 feat(google): keep Google Technical Information at most 30 days and keep Google data out of training exports (#22842)
Adds a durable, sleep-aware 30-day sweep for Google Technical Information, keeps Google results out of decision training and shared feedback traces, and deletes the remaining copies of a cleaned run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 19:57:23 -06:00