Commit Graph
8588 Commits
Author SHA1 Message Date
DottaandClaude Opus 5.5 10cd186a46 feat(antigravity): carry the agent's own instructions into a /swarm turn (#22905)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - A signed-in user can start Google Antigravity's native `/swarm` on a
task (experimental, off by default)
> - #22733 removed the agent's own instructions from a swarm turn after
a security review: an agent can edit its own instructions, and swarm
helpers act in Antigravity's auto mode
> - The owner reviewed that risk and decided on 2026-11-25 that swarms
carry the agent's own instructions again, with Paperclip's swarm rules
on top
> - This pull request adds the agent's instructions back to a swarm turn
through the same composer that ordinary Antigravity turns use, and makes
the swarm rules say that they take precedence
> - The benefit is that a swarm follows the same agent instructions as
every other turn of that agent, and the code-enforced limits stay the
same

## Linked Issues or Issue Description

Refs #22733

**Subsystem affected**
Paperclip Runner, Antigravity `/swarm` route (system instructions), API
docs, qualification ledger.

**Problem or motivation**
A swarm turn runs only on Paperclip's fixed execution prompt and the
fixed swarm rules. It ignores the agent's instruction files, so a swarm
does not follow the agent's own conventions. The owner decided that
swarms must carry the agent's instructions.

**Proposed solution**
Compose a swarm turn's system instructions exactly as for an ordinary
Antigravity turn (`composeNativeSystemInstructions`), with the hand-in
values placed right after the instruction entry. The composer's
canonical suffix (the instruction root path) still ends the prompt, so
`retargetNativeSystemInstructions` remaps it when a launch or recovery
moves the bundle to another host path. The swarm route still appends
Paperclip's swarm rules last. The rules now say that they take
precedence over the agent's instructions, that those instructions cannot
widen the Paperclip tools offered or Paperclip's permission decisions,
and that helpers must keep their work inside the task folder.

## What Changed

- `packages/paperclip-runner/src/backends/runtime-context.ts`: the swarm
branch of `nativeSystemInstructions` now runs after the instruction
bundle is read (same path checks), and returns
`composeNativeSystemInstructions(runtimeContext, entry + hand-in)`. The
hand-in block sits inside the composed entry, so the canonical suffix
still ends the prompt and retargeting works as for an ordinary turn. The
second, swarm-only path is gone.
-
`packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-runtime.ts`:
`ANTIGRAVITY_SWARM_INSTRUCTIONS` gains one precedence statement. It
promises only what the code enforces (the tools offered and the
permission decisions) and states the task-folder limit as a rule. The
rules stay last in the appended system prompt.
- Tests: `runtime-context.test.ts` now asserts that a swarm turn's
instructions equal the ordinary turn's instructions with the hand-in
block after the entry, and that retargeting to another bundle root puts
the new root at the end and leaves an inline path in the entry
unchanged. `antigravity-swarm-runtime.test.ts` asserts, on the real
`session/new` request, that the agent's instructions are present, that
the swarm rules come after them and end the prompt, and that the rules
carry the precedence statement. The assertions that the bundle is absent
are removed.
- `docs/api/issues.md` and
`doc/plans/2026-11-22-antigravity-qualification.md`: record the owner
decision, what is enforced in code, what is prompt-only, and the
residual risk.

### Which protections are code-enforced and which are prompt-only

Enforced in code, whatever the agent's instructions say:

- Permission handler (`antigravity-swarm-runtime.ts`,
`session/request_permission`): approves only the run's own Paperclip
tools and rejects every other permission request.
- Delegation tools (create task, assign, hire, generic API and similar)
are removed from the bridge catalog for a swarm turn
(`antigravitySwarmTools`).
- Only Paperclip's own tool server is accepted; the session must be in
the task folder (guard `sessionRequest`, runtime open checks).
- A helper started with `share` or `branch` stops the swarm
(`antigravitySwarmWorkspaceEscape`).
- A visible change outside the task folder in a reported tool call stops
the swarm (`antigravityOutsideChange`). This is a best-effort detector,
not a boundary.
- A changed model, thinking level or auto mode fails the run (guard
`assertStable`). Plan mode, a restored session and extra tool servers
are refused.

Not enforced by Paperclip: helper shell commands. Helper tool calls do
not reach the client, so they can write wherever Antigravity's own
sandbox allows (the task folder and temp directories). This is unchanged
by this pull request.

Prompt-only: the precedence statement itself, handing in once, naming
files by task-folder path, and not mentioning the rules.

Residual risk, accepted by the owner: an agent that can edit its own
instructions can influence what its swarm helpers do inside the task
folder.

## Verification

- Red: with only the test changes, `npx vitest run
src/backends/runtime-context.test.ts
src/drivers/acpx/antigravity-swarm-runtime.test.ts` (in
`packages/paperclip-runner`) failed 2 tests: the swarm instructions
lacked the agent's text, and the `session/new` system prompt did not
contain it.
- Green: with the change, `npx vitest run src/backends src/drivers/acpx
src/live/runner-provider-launch.test.ts
src/cli/acpx-runtime-sidecar.test.ts` passed (one timing-sensitive
launcher test failed once under load and passed on re-run).
- Retarget red/green: with the hand-in appended after the canonical
suffix, the swarm composition test fails; with it inside the entry, it
passes.
- `pnpm typecheck` in `packages/paperclip-runner`: passed.
- `node tests/runner-e2e/source-sdk-public-inputs.mjs <HEAD> --check`:
unchanged.
- `pnpm verify` exited 2 (docs are a global CI input), so required CI
supplies broad coverage.
- No live swarm run.

## Risks

- Security: agent-editable instructions now reach a swarm whose helpers
act in auto mode. The owner reviewed and accepted this. The
code-enforced limits above are unchanged.
- Behavior: a swarm now fails like an ordinary turn when the agent's
instruction entry is missing or outside its bundle.
- The system prompt is larger by the size of the agent's instructions.

## Model Used

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

## Checklist

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

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 04:52:11 -06:00
DottaandPaperclip 1ad5dd9dce fix(runner): preserve admitted remote provider pack across reattach and relaunch (#22850)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Native Paperclip Runner executes remote OpenCode and ACPX sessions
in sandbox environments backed by immutable image provider packs and
durable session state
> - When a remote run reattaches, relaunches a settled runner, or
resumes a warm runner after a controller restart or deploy on an
ephemeral server, `prepareRemoteRunnerAssets` rejected the sandbox's
immutable image pack with `exact_identity` and then probed a
non-existent workspace-staged `provider-pack` path, failing with
`exitCode=127` (`No such file or directory`)
> - This happened for two reasons: the reattach/warm-recovery branch
skipped the `artifactStorage && providerArtifacts` fast path used during
cold startup, and when local `provider-pack-authority.json` was absent
(`ENOENT`), the controller fell back to its newer bundled manifest
instead of re-pinning against the durable verified admission receipt in
PostgreSQL
> - When an immutable image pack genuinely failed compatibility and no
workspace-staged pack existed, swallowing the rejection also masked the
real `exact_identity` or interface failure behind `exitCode=127`
> - This pull request aligns reattach and warm-recovery provider-pack
preparation with durable artifact storage and verified DB admission
receipts while keeping all integrity and confinement checks fail-closed
> - The benefit is reliable mid-run reattach, settled-runner relaunch,
and warm-session recovery across deploys without sacrificing
pack-identity verification

## Linked Issues or Issue Description

**What happened?**

During remote `reattach_remote_runner` or `remoteWarmRecovery` (for
example after a hard controller restart or deploy on an ephemeral
server), `prepareRemoteRunnerAssets` failed with
`runner_remote_provider_artifact_incompatible: provider pack
verification failed (exitCode=127;
.../.paperclip-runtime/paperclip-runner/provider-pack/node_modules/node/bin/node:
No such file or directory)` right after `provider_pack.compatibility`
logged `installation_unprotected` on `workspace` and `exact_identity` on
`image`.

**Expected behavior**

A reattach, settled-runner relaunch, or warm recovery on a reused
sandbox must preserve the admitted provider pack:
1. When an OpenCode session already has durable
`nativeProviderArtifacts`, reattach/relaunch must restore that admitted
artifact bundle using any immutable image pack's `node` executable as
bootstrap instead of demanding an exact-identity match on
`/opt/paperclip-runner/provider-pack`.
2. When ephemeral local `provider-pack-authority.json` is absent
(`ENOENT`) after a controller restart or deploy, the controller must
re-pin an OS-protected immutable image pack whose self-sealed manifest
cryptographically matches the verified `nativeProviderPackAdmission`
receipt stored in PostgreSQL for that exact `(companyId, agentId, runId,
sessionId, runnerInstanceId, environmentLeaseId)`.
3. When no valid receipt matches (or the installed pack genuinely
mismatches), reattach must fail closed with a permanent
`runner_remote_provider_artifact_incompatible` error that preserves the
real `failureCheck` (such as `exact_identity`) instead of masking it
behind `exitCode=127` on a missing workspace path.

**Steps to reproduce**

1. Start a remote native OpenCode or ACPX session in a sandbox whose
immutable `/opt/paperclip-runner/provider-pack` was built from an
earlier revision than the replacement controller's bundled manifest (so
no workspace-staged `.paperclip-runtime/paperclip-runner/provider-pack`
exists).
2. Restart or deploy the controller onto a fresh ephemeral filesystem
(so local `provider-pack-authority.json` is absent) while durable
`nativeProviderArtifacts` or a verified `nativeProviderPackAdmission`
receipt exists in PostgreSQL.
3. Reattach or relaunch the settled remote runner
(`reattach_remote_runner`) or recover the warm runner
(`remoteWarmRecovery`). On unfixed `master`, `prepareRemoteRunnerAssets`
rejects `/opt/paperclip-runner/provider-pack` with `exact_identity` and
fails with `exitCode=127` on the missing workspace path.

**Paperclip version or commit**

Reproduced on `origin/master` (`fb900bf0fe`).

## What Changed

- **`server/src/services/native-runtime/remote-provider-pack.ts`**:
- Added `verifiedProviderPackAdmissionReceipt()` to strictly validate a
PostgreSQL `nativeProviderPackAdmission` receipt and its `verified`
admission state against exact `(companyId, agentId, runId, sessionId,
runnerInstanceId, environmentLeaseId)` and digest/revision formats.
- Added `isMissingProviderPackBinaryError()` to identify only
`exitCode=127` `pack_verifier_failed` errors from a missing staged
`node` binary without matching exit-code-3 verification failures or
transient unavailability errors.
-
**`server/src/services/native-runtime/remote-provider-pack-verification.ts`**:
- Extended `verifyRemoteProviderPack` / `compatibleInstallation` with an
optional `admittedReceipt` (honored only when `requireExactIdentity` is
true). It continues to enforce `immutable === true`, root match, schema,
self-sealed `manifest_digest`, target, `pins.opencode`, all artifact
paths/SHA-256 formats, and ACPX agent profile presence while requiring
exact cryptographic match to `providerPackDigest`,
`opencodeProxySha256`, and `sourceRevision`.
- **`server/src/services/native-runtime/native-session-executor.ts`**
*(kept minimal by placing pure validation helpers in
`remote-provider-pack.ts` and `remote-provider-pack-verification.ts`,
since `native-session-executor.ts` already exceeds 1,000 lines)*:
- Added the `if (artifactStorage && providerArtifacts)` fast path to the
`reattach_remote_runner || remoteWarmRecovery` branch of
`prepareRemoteRunnerAssets` (matching cold preparation) and recovered
session `providerArtifacts` via `recordedSessionProviderArtifacts` when
relaunching a settled runner (`!adoptedProcess`).
- Tracked when `selectProviderPackAuthority` fell back to
`resolveCurrentProviderPackManifest()` on local `ENOENT`, loaded the
verified DB admission receipt in `useInstalledProviderPack()`
(supporting both same-run `providerPackAdmissionSource` and prior-run
`remoteWarmRecovery` receipts), and re-bound in-memory
`providerPackAuthority` to the verified manifest while preserving
`runnerArtifact`.
- Surfaced immutable-pack incompatibility rejections when
workspace-staged pack verification fails with `exitCode=127`, while
preserving valid workspace-staged packs and real verification errors
from tampered workspace packs.
- Hardened the `bootstrap` immutable-pack lookup in
`prepareRemoteRunner` to require a valid `nodeCommand.path`.
- **Tests (`native-session-executor.test.ts`,
`remote-provider-pack.test.ts`,
`remote-provider-pack-verification.test.ts`)**:
- Added red-green behavioral regressions (with sandbox path confinement)
covering durable `providerArtifacts` settled-runner relaunch with a
different image pack, mid-run deploy DB receipt recovery for both
OpenCode and ACPX (`claude`), `remoteWarmRecovery` prior-run DB receipt
recovery, and negative fail-closed integrity checks (`exact_identity`
mismatch, `pending`/`unknown`/`wrong-lease`/`missing` receipts,
unprotected `immutable: false` packs, valid and tampered
workspace-staged packs).

## Verification

- **Red -> Green proof**:
- Before production edits, `pnpm --filter @paperclipai/server exec
vitest run src/services/native-runtime/native-session-executor.test.ts
-t "remote provider pack reattach and relaunch after deploy or restart"`
failed 8/9 cases with verbatim
`runner_remote_provider_artifact_incompatible: provider pack
verification failed (exitCode=127; timedOut=false; signal=none; env:
'/workspace/.paperclip-runtime/paperclip-runner/provider-pack/node_modules/node/bin/node':
No such file or directory)`.
  - After the fix (commit `e2e7138024`):
    - `npx tsc --noEmit -p server/tsconfig.json`: passed (0 errors).
- `pnpm --filter @paperclipai/server exec vitest run
src/services/native-runtime/native-session-executor.test.ts -t "remote
provider pack reattach and relaunch after deploy or restart|uses the
bundled Linux image authority|relaunches|reattach"`: **112/112 passed**.
- `pnpm --filter @paperclipai/server exec vitest run
src/services/native-runtime/remote-provider-pack.test.ts
src/services/native-runtime/remote-provider-pack-verification.test.ts
src/services/native-runtime/remote-provider-pack-authority.test.ts
src/services/native-runtime/native-artifact-preparation.test.ts
src/services/native-runtime/native-provider-pack-admission.test.ts
src/services/native-runtime/provider-pack-selection-harness.test.ts`:
**190/190 passed**.
- `pnpm verify --explain`: selects `2375/2735` Vitest files due to
transitive imports of `native-session-executor.ts`; required CI covers
the full repository matrix.
- **Verification environment & limits**:
- Verified locally with unit/behavioral Vitest suites simulating sandbox
confinement and immutable/writable pack inventories on macOS
(`fb900bf0fe` + `e2e7138024`). Live Daytona sandbox reattach after a
staging deploy is not exercised locally and awaits post-merge
deployment.

## Risks

- **Previous-release & upgrade safety**: State saved by prior releases
carries forward cleanly — runs with local
`provider-pack-authority.json`, durable `nativeProviderArtifacts`, or a
verified PostgreSQL `nativeProviderPackAdmission` receipt re-pin to
their exact admitted pack across mid-run deploys. Runs with none of
those receipts remain at the current-release exact-identity gate and
fail closed with permanent
`runner_remote_provider_artifact_incompatible` (`failureCheck:
"exact_identity"`), leaving saved session/checkpoint/workspace state
intact.
- **Security boundary**: `admittedReceipt` is only consulted when
`requireExactIdentity` is true and local authority fell back on
`ENOENT`, and only for OS-protected (`immutable: true`) installations
whose self-sealed manifest digest matches the DB receipt's SHA-256
digest and exact run/session/runner/lease binding. Unprotected
(`immutable: false`), unverified (`pending`/`unknown`), or mismatched
packs continue to fail closed.
- **Overall risk**: Low to medium — scoped strictly to remote
provider-pack verification on `reattach_remote_runner` and
`remoteWarmRecovery`; cold launch and local execution paths are
unchanged.

## Model Used

- Gemini 4 Neon (`gemini-4-neon-high`), via Antigravity agent with tool
use (file inspection/editing, git worktree isolation, Vitest and
TypeScript execution).

## Checklist

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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-25 04:44:10 -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
canary/v2026.1125.0-canary.858600
2026-11-25 04:37:02 -06:00
Dotta 6b070dc749 fix(workspaces): name incompatible Core project storage on plugin environments (#22849)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - A repository project belongs to one storage owner: Core / local
storage or an installed workspace-storage plugin.
> - A task keeps its selected workspace source when it moves to another
project, so the source project's storage owner still governs
compatibility.
> - Merged #22398 already reports `configuration_incomplete`
(`project_storage_environment_incompatible`) when a plugin-storage
project runs on a Core environment on a volume-free server.
> - In the opposite direction — a Core-storage project source paired
with an active workspace-storage plugin environment — workspace
preparation fell through to `workspace_validation_failed`
(`plugin_workspace_strategy_unsupported`), claiming the plugin
environment does not support Core Git worktree preparation.
> - That message hid the true storage mismatch, skipped the owner-action
"Workspace storage unavailable" notice, and sent pre-dispatch Sentry
noise.
> - This pull request checks `projectStorageForEnvironment` inside that
refusal path and reports the same `configuration_incomplete` /
`project_storage_environment_incompatible` outcome when the plugin
environment owns separate workspace storage.
> - Generic task-only plugin environments, disabled storage plugins, and
project-less tasks keep `plugin_workspace_strategy_unsupported`.

## Linked Issues or Issue Description

Related: #22398 (names incompatible plugin project storage when a
volume-free server refuses a Core environment), #17552 (a moved task
keeps its selected workspace source). Verified non-overlapping with open
#21625, which only touches local non-Git task directories where
`!pluginTaskWorkspace`.

**What happened?**

A task had an isolated workspace source belonging to a Core-storage
project (for example after moving the task into a plugin-storage project
while retaining its original source). The assigned Paperclip Runner
agent ran in an active workspace-storage plugin environment. Because the
source project used Core / local storage rather than the plugin's
storage, `preparePluginWorkspace` returned `null` and workspace
preparation refused the run with `workspace_validation_failed`
(`plugin_workspace_strategy_unsupported`): `"The selected plugin
environment does not support Core Git worktree preparation."` That
message falsely blamed the plugin environment for not supporting Git
worktrees, did not show the "Workspace storage unavailable" owner-action
notice, and was not filtered as a known pre-dispatch configuration
mismatch by run-failure reporting.

**Expected behavior**

The refusal names the actual storage mismatch (`Core / local` storage vs
the selected plugin environment), fails with `configuration_incomplete`
(`reason: "project_storage_environment_incompatible"`), triggers the
existing `"Workspace storage unavailable"` task notice with the owner
action, and avoids pre-dispatch Sentry noise. Generic task-only plugin
environments, disabled storage plugins, and project-less tasks still
fail closed with `workspace_validation_failed`
(`plugin_workspace_strategy_unsupported`).

**Steps to reproduce**

1. Install and enable a workspace-storage plugin that also registers a
task-capable environment driver (`supportsTasks: true`).
2. Create a Core-storage project with a Git workspace and a
plugin-storage project owned by that plugin.
3. Create an isolated task (`mode: "isolated_workspace"`) backed by the
Core-storage project workspace, then move the task to the plugin-storage
project (retaining its selected workspace source) and assign it to a
Paperclip Runner agent using the plugin environment.
4. Prepare the workspace for a run. Before this fix,
`prepareHeartbeatWorkspace` rejects with `WorkspaceValidationFailure`
(`workspace_validation_failed`, `reason:
"plugin_workspace_strategy_unsupported"`).

**Paperclip version or commit**

Reproduced against `origin/master` at
`fb900bf0fe4361e6b6a43814da952c87957a3299`.

**Deployment mode**

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

## What Changed

- `server/src/services/heartbeat/workspace-preparation.ts`: inside the
existing `pluginTaskWorkspace && !pluginPrepared &&
latestWorkspaceStrategyType === "git_worktree"` refusal branch, check
`projectStorageForEnvironment(selectedEnvironmentForConfig, await
listProjectWorkspaceProviders(db, agent.companyId))` when a resolved
Core-storage project workspace source is present
(`!projectExecutionWorkspacePolicy?.storageProviderPluginId &&
resolvedWorkspace.projectId && resolvedWorkspace.workspaceId`). When the
selected plugin environment belongs to an active workspace-storage
plugin, throw `ConfigurationIncompleteFailure` with `reason:
PROJECT_STORAGE_ENVIRONMENT_INCOMPATIBLE`, naming `Core / local` storage
and the selected environment, with `projectId:
resolvedWorkspace.projectId`, `storageProviderPluginId: null`,
`environmentId`, stable fingerprint
`project_storage_environment:core:${environmentId}`, and `actionUrl`.
(This adds 26 lines to `workspace-preparation.ts`, which is already
above 1,000 lines, directly inside the owning refusal guard so no new
indirection is introduced.)
- `server/src/services/heartbeat/workspace-preparation.test.ts`: add a
behavioral regression simulating a moved task retaining a Core-storage
source on an active storage-plugin environment, plus negative safety
assertions confirming disabled storage plugins and project-less tasks
retain `workspace_validation_failed` /
`plugin_workspace_strategy_unsupported` with zero lease acquisition or
workspace creation.
- `doc/project-environment-compatibility.md`: document the symmetric
Core-storage-project vs workspace-storage-plugin-environment refusal
contract.

## Verification

- **Red (before production edit)**:
- `pnpm --filter @paperclipai/server exec vitest run
src/services/heartbeat/workspace-preparation.test.ts -t "names
incompatible Core project storage|rejects Core Git worktree
preparation"`
- `names incompatible Core project storage when a storage-plugin
environment refuses a Core Git worktree` failed with
`WorkspaceValidationFailure` (`code: "workspace_validation_failed"`,
`resultJson: { reason: "plugin_workspace_strategy_unsupported" }`);
existing `rejects Core Git worktree preparation for a plugin-owned
workspace` passed.
- **Green (at `218312be90a5a116d0f4cc7643bdb671a3e76df3`)**:
  - `pnpm --filter @paperclipai/server typecheck` — passed.
- `pnpm --filter @paperclipai/server exec vitest run
src/services/heartbeat/workspace-preparation.test.ts -t "names
incompatible Core project storage|rejects Core Git worktree
preparation|names an incompatible project storage environment"` — 3/3
passed.
- `pnpm --filter @paperclipai/server exec vitest run
src/services/heartbeat/workspace-preparation.test.ts` — 155/155 passed.
- Companion suites (`src/__tests__/project-environments.test.ts` 16/16,
`src/services/__tests__/run-failure-report.test.ts`,
`src/services/recovery/stranded-notice.test.ts`) — all passed (511/511
total tests across the 4 files; an earlier combined run hit an embedded
Postgres `afterAll` shutdown timeout under parallel host load, so
`workspace-preparation.test.ts` was re-run standalone cleanly to exit
0).
- `pnpm verify --explain` exited 2 because
`doc/project-environment-compatibility.md` is a global CI input;
required GitHub Actions CI supplies the broad suite coverage.
- Live deployment/recovery is outside this PR's scope; local
verification covers the real workspace-preparation, database, and
plugin-storage compatibility boundary.

## Risks

- Low risk. The new classification runs strictly inside the existing
`pluginTaskWorkspace && !pluginPrepared && latestWorkspaceStrategyType
=== "git_worktree"` refusal guard, so no run that previously succeeded
can fail now.
- One extra `listProjectWorkspaceProviders` read occurs only on that
refusal path.
- Existing `stranded-notice.ts`, `recovery/service.ts`, and
`run-failure-report.ts` already handle `configuration_incomplete` /
`project_storage_environment_incompatible`.
- A task that moves projects still retains its selected workspace
source; the owner still resolves the mismatch by choosing a compatible
agent environment or selecting a workspace source from a compatible
project.

## Model Used

- Google Gemini (Antigravity agentic coding assistant) with tool use,
shell execution, and local 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
- [ ] 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:36:24 -06:00
Dotta 0e12237d16 fix(workspaces): classify Git storage guard failures during clone and archive (#22848)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Remote cloud sandboxes can wrap `git` in a storage guard that exits
with code 75 (`paperclip_git_storage_limit:`) when free space, free
inodes, or per-command disk growth hits its budget, or when the guard
itself is misconfigured
> - Previously, Paperclip's remote workspace archive capture and
repository preparation did not recognize `paperclip_git_storage_limit:`
output, so both reported opaque Git exit 75 failures
> - During archive capture, an unclassified exit 75 prevented fallback
to read-only controller-side capture and caused finalization to burn
retries instead of recognizing sandbox disk exhaustion immediately;
during workspace clone, it reported generic `setup_failed` and left
partial `.preparing-*` directories behind
> - This pull request classifies Git storage-guard space/budget refusals
as sandbox disk full across capture and preparation, cleans up failed
`.preparing-*` staging directories, and labels misconfigured/unavailable
guard failures distinctly so they are never misreported as a full disk
> - The benefit is that low-disk saves can recover through read-only
capture or stop retrying immediately, clone storage refusals classify
accurately, and unavailable guard errors remain clearly distinguishable

## Linked Issues or Issue Description

**What happened?**
When a sandbox Git storage guard stops a Git command with exit code 75
and `paperclip_git_storage_limit:` on stderr:
- Workspace archive capture (`remote-workspace-snapshot-archive.ts` /
`remote-workspace-transport.ts`) drops the storage-limit message and
reports `remote_workspace_capture_failed: stage=archive exit=75
program=git helper_exit=1`. Because this does not match
`REMOTE_WORKSPACE_SANDBOX_DISK_FULL`, `captureRemoteWorkspaceArchive`
skips its read-only controller-side fallback and finalization wastes 3
retries into `native_workspace_sync_out_retry_exhausted`.
- Workspace preparation (`prepareRemoteWorkspaceDirectory` /
`prepareRemoteRepository`) reports `remote_workspace_prepare_failed:
stage=clone exit=75 program=git`, which
`isRemoteWorkspaceSandboxDiskFullError` does not recognize (so setup
records generic `setup_failed`), and `PREPARE` does not remove its
partial `.preparing-*` staging directory on failure.

**Expected behavior**
- Git storage-guard low-space or storage-budget refusals classify as
`REMOTE_WORKSPACE_SANDBOX_DISK_FULL` during capture (triggering
`captureReadOnlyWorkspaceArchive` fallback and single-attempt
storage-exhaustion recognition) and as `disk=full git=storage_limit`
during prepare/repository (matched by
`isRemoteWorkspaceSandboxDiskFullError`), with `.preparing-*` cleanup on
failure.
- Unavailable or misconfigured Git storage-guard errors stay distinct
(`reason=git_storage_guard_unavailable` during capture,
`git=storage_guard_unavailable` during prepare/repository) and are never
misclassified as sandbox disk full.

**Steps to reproduce**
1. Configure a `git` wrapper on `PATH` that writes
`paperclip_git_storage_limit: The sandbox has too little free disk space
or too few free inodes; Git did not start.` (or `stopped at its storage
budget`) to stderr and exits 75.
2. Run `prepareRemoteWorkspaceDirectory`, `prepareRemoteRepository`, or
`captureRemoteWorkspaceArchive` against a Git workspace.
3. Observe opaque `stage=clone exit=75 program=git` or `stage=archive
exit=75 program=git helper_exit=1` with no read-only fallback,
`isRemoteWorkspaceSandboxDiskFullError` returning `false`, and leftover
`.preparing-*` directories on failed clones.

**Paperclip version or commit**
`master` (`ba63f4f8b2`).

**Deployment mode**
Hosted / remote sandbox execution (`paperclip_runner`).

Refs #22837 (companion handling for full reused sandboxes on
`remote_workspace_restore_failed`; this PR keeps
`remote_workspace_restore_failed` untouched and composes cleanly with
it).

## What Changed

- `server/src/services/remote-workspace-snapshot-archive.ts`:
- Recognize `paperclip_git_storage_limit:` low-space and storage-budget
refusals as `remote_workspace_sandbox_disk_full` inside
`remoteWorkspaceCaptureFailureMessage`.
- In `remoteWorkspaceFailureDetail`, emit the closed field
`reason=git_storage_guard_unavailable` when Git fails with any other
`paperclip_git_storage_limit:` message (such as misconfigured or
unreadable capacity), never copying raw stderr text and never
misclassifying it as disk full.
- `server/src/services/remote-workspace-transport.ts`:
- Extend `DISK_FULL_CHECK` to recognize `paperclip_git_storage_limit:`
space/budget refusals (not unavailable/misconfigured guard errors).
- Extend `SETUP_FAILURE_CHECK` to emit `git=storage_limit` (with
`disk=full`) or `git=storage_guard_unavailable` (without `disk=full`)
within the existing closed `SANDBOX_SETUP_CAUSE` grammar.
- Extend `isRemoteWorkspaceSandboxDiskFullError` to match
`RemoteWorkspaceOperationError` carrying
`remote_workspace_(?:prepare|repository)_failed: ... disk=full`, while
leaving host-side `ENOSPC` and `remote_workspace_restore_failed`
unaffected.
- Remove unpublished `.preparing-*` staging directories in `PREPARE`'s
`finally` block so failed or aborted clones do not leak partial data on
the sandbox disk.
- `server/src/services/remote-workspace-transport.test.ts`:
- Add real-subprocess red-green regressions for serialized `archive.cjs`
helper classification, read-only capture fallback, clone/repository
storage-limit classification and `.preparing-*` cleanup, and negative
cases proving unavailable/misconfigured guard errors stay distinct and
do not trigger read-only fallback or
`isRemoteWorkspaceSandboxDiskFullError`.

## Verification

- **Red (before production edits)**: 9/9 new real-subprocess tests
failed with the exact unfixed diagnostics (`stage=clone exit=75
program=git`, `stage=archive exit=75 program=git helper_exit=1`).
- **Green (commit `3de3c3181d`, rebased onto `ba63f4f8b2`)**:
- `pnpm --filter @paperclipai/server exec tsc -p tsconfig.json
--noEmit`: passes.
- `pnpm --filter @paperclipai/server exec vitest run
src/services/remote-workspace-transport.test.ts -t "Git storage guard"`:
9/9 pass.
- Affected suites verified locally:
`remote-workspace-transport.test.ts`,
`native-workspace-finalizer-failure.test.ts`,
`remote-workspace-readonly-capture-cause.test.ts`, and
`run-completion.test.ts -t "sandbox disk"` all pass.
- Full PR CI runs on this commit to provide broad coverage across the
workspace.
- **Limitations**: Verified locally via real serialized `archive.cjs`
and Node/Git subprocesses; live cloud sandbox verification requires
deployment after merge alongside the companion sandbox-image guard
update.

## Risks

- Low risk: all new diagnostic values use closed literal tokens within
existing `SANDBOX_CAPTURE_CAUSE` and `SANDBOX_SETUP_CAUSE` grammars, so
raw stderr/paths never cross into error records.
- `isRemoteWorkspaceSandboxDiskFullError` only matches
`RemoteWorkspaceOperationError` for `prepare`/`repository` with
`disk=full`, preserving existing `RemoteWorkspaceRestoreError` handling
(#22837) and keeping host-side `ENOSPC` distinct.
- `PREPARE` only removes its own newly created `.preparing-*` directory
when publish (`fs.rename`) has not completed, matching
`prepareRemoteRepository`.

## Model Used

- Google Gemini 4 Neon (High) (`gemini-4-neon-high`) in Antigravity with
tool use (shell, file edit, test execution).

## Checklist

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

> - Paperclip is the open source app people use to manage AI agents for
work.
> - After a native run on a remote sandbox, Paperclip copies the
workspace back to durable storage during finalization.
> - The archive capture guard refuses to save a workspace that still has
an unfinished Git operation (such as an unresolved merge or rebase) with
`remote_workspace_archive_git_operation_in_progress`.
> - Finalization treated that refusal as transient and retried three
times, then saved-work recovery treated it as a transient provider error
and retried across its 30-minute window.
> - Nothing finishes or aborts a Git operation in an idle or stopped
sandbox between automatic retries, so every retry fails the same way
while delaying user action.
> - This pull request stops both finalization and saved-work recovery on
the first unfinished Git operation refusal, keeps the accepted result
and retained sandbox intact, and hands the task to the board with a
clear Retry path.
> - The benefit is that tasks stop immediately with an accurate
explanation instead of burning futile retries, and Retry saves the files
and applies the accepted result without another provider turn once the
Git operation is resolved.

## Linked Issues or Issue Description

Refs #20678 (stop retrying copy-back on a full sandbox disk), Refs
#20758 (stop re-saving a retained sandbox whose disk is still full),
Refs #20819 (apply a saved accepted result on Retry instead of a new
turn)

**What happened?**
When an agent finishes a native turn and leaves an unresolved Git
operation (such as a conflicted merge or rebase) in the remote sandbox,
workspace archive capture fails with
`remote_workspace_archive_git_operation_in_progress: finish or abort the
Git operation before saving the workspace`. Finalization retried
copy-back 3 times before ending with
`native_workspace_sync_out_retry_exhausted` ("Saving the workspace
failed after 3 attempts"), and saved-work recovery then classified the
refusal as `export_interrupted` / `retry_transient` (`provider_error`)
and retried across its 30-minute window.

**Expected behavior**
Paperclip recognizes
`remote_workspace_archive_git_operation_in_progress` on the first
failure in both finalization and saved-work recovery. It stops automatic
retries immediately, keeps the accepted result linked and the retained
sandbox intact, names the unfinished Git operation clearly, and exposes
the task's Retry action so the user can save the files and apply the
accepted result without another agent turn once the Git operation is
finished or aborted.

**Steps to reproduce**
1. Run a native task on a remote sandbox and leave a conflicted `git
merge` open before the turn finishes with an accepted result.
2. Observe copy-back fail with
`remote_workspace_archive_git_operation_in_progress: finish or abort the
Git operation before saving the workspace`.
3. Before this change, finalization stays in `retryable_failure` for 3
attempts, and saved-work recovery schedules automatic transient retries
with cause `provider_error`.

## What Changed

- `server/src/services/native-runtime/native-workspace-failure.ts`:
export `REMOTE_WORKSPACE_GIT_OPERATION_IN_PROGRESS_CODE`,
`isWorkspaceGitOperationInProgress()`, and a unified
`workspaceSaveRestCause()` helper (`"sandbox_disk_full" |
"git_operation_in_progress" | null`) used by both finalization and
saved-work recovery as the single source of truth.
- `server/src/services/native-runtime/native-run-finalizer.ts`: use
`workspaceSaveRestCause(failureCause)` to exhaust workspace copy-back on
Attempt 1 for both `sandbox_disk_full` and `git_operation_in_progress`
(keeping `failureCode = native_workspace_sync_out_retry_exhausted`,
accepted result linked, retained sandbox lease preserved, and no new
wakeups), and emit truthful run error and recovery `nextAction` text
without "after 3 attempts" or "Finalization retry budget exhausted."
(net file size change: +1 line).
- `server/src/services/workspace-recovery.ts` &
`server/src/services/system-recovery-state.ts`: use
`workspaceSaveRestCause(error)` so retained saved-work recovery stops on
Attempt 1 for `git_operation_in_progress` with `export_interrupted`,
`retryClass: "user_action_required"`, and cause `{ label:
"git_operation_in_progress", code: null, status: null }`, keeping
unsaved files protected and showing plain-language
`exhaustedSystemRecoveryAction` guidance.
- `ui/src/components/WorkspaceExportRecovery.tsx`: treat
`git_operation_in_progress` alongside `sandbox_disk_full` as a
user-action save rest so the panel surfaces clear status copy and leaves
the task's Retry control available.
- Added red-to-green regression tests across
`server/src/services/native-runtime/native-workspace-failure.test.ts`
(including producer-to-detector redaction round-trip through
`remoteWorkspaceCaptureFailureMessage` and
`remoteWorkspaceFailureCause`),
`server/src/services/native-runtime/native-run-finalizer-telemetry.test.ts`,
`server/src/services/workspace-recovery-warm-handoff.test.ts`, and
`ui/src/components/WorkspaceExportRecovery.control.test.tsx`.

## Verification

- **Red before production edits**:
- Finalizer (`recordNativeFinalizationFailure`), saved-work recovery
(`recoverRetainedWorkspace`), `exhaustedSystemRecoveryAction`, and
`WorkspaceExportRecovery` regressions all failed against unfixed
production code (finalizer stayed `retryable_failure`, recovery stayed
`scheduled`/`retry_transient`/`provider_error`, UI rendered `Recover
saved files` button instead of handing off to task Retry).
- **Green at `6b18fd8b63`** (rebased cleanly onto `origin/master`
`ba63f4f8b2`):
  - `npx tsc --noEmit -p server/tsconfig.json`: pass.
  - `pnpm --filter @paperclipai/ui typecheck`: pass.
- `cd server && npx vitest run
src/services/native-runtime/native-workspace-failure.test.ts
src/services/native-runtime/native-run-finalizer-telemetry.test.ts
src/services/workspace-recovery-warm-handoff.test.ts`: 89/89 pass
(covers producer->detector redaction round-trip, Attempt-1 stop for
git-op-in-progress and disk-full, preserved accepted result, transient
`remote_workspace_archive_changed` & `ECONNRESET` still retrying,
permanent errors still permanent, Retry-while-open resting immediately,
and Retry-after-resolved saving and applying the accepted result without
a new turn).
- `cd ui && npx vitest run
src/components/WorkspaceExportRecovery.control.test.tsx`: 51/51 pass.
- Required GitHub CI supplies the full repo-wide suite on `6b18fd8b63`.
- Environment: local macOS worktree with embedded Postgres fixture for
server integration tests and jsdom for UI tests; live Daytona sandbox
acceptance was not run locally.

## Risks

- Low risk. The terminal finalization code
(`native_workspace_sync_out_retry_exhausted`) and recovery schema
(`export_interrupted` / `user_action_required` with closed-label cause
`git_operation_in_progress`) reuse existing persisted contracts and DB
indexes without any migration.
- Upgrade safety: a run persisted in `retryable_failure` by an earlier
release with `remote_workspace_archive_git_operation_in_progress` stops
on its next attempt; an earlier release reading the new
`git_operation_in_progress` cause passes schema validation and displays
its generic Retry copy.
- Does not modify `remote-workspace-snapshot-archive.ts` or relax any
Git archive safety guard. Unsaved files remain protected in the retained
sandbox and never trigger the `source_unavailable` fallback.

## Model Used

- Gemini 4 Neon (High) (`gemini-4-neon-high`), Google, via Antigravity
with tool use (shell, file edits, test execution).

## Checklist

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

> - Paperclip is the open source app people use to manage AI agents for
work.
> - When a user comments on a finished task, Paperclip starts a
follow-up turn. The agent gets a prompt with the fresh-session history,
the wake payload, and the task context.
> - On Google Antigravity follow-ups after a swarm, the agent spent 3 to
6 minutes and 1 to 2.7 million cached tokens on a one-line file edit.
> - The agent took the run id of the previous run from the prompt and
searched the disk for it. It then read the raw run log to copy how the
previous run wrote the file and called the hand-in tools.
> - The prompt named that run id five times and told the agent to "read
the original run receipt". No agent tool can read a run by its id. Also,
the follow-up directive pointed at an empty "Latest wake comment"
section. The request was present only inside a JSON message list.
> - This pull request removes run ids from the model-facing prompt,
states the latest request plainly once, and points the directive at it.
The prompt also gets smaller.
> - The benefit is that a follow-up has no prompt path that leads the
agent to run logs, and the agent can find the request where the
directive points.

## Linked Issues or Issue Description

**What happened?**
A user comment on a done task started a follow-up turn. The agent
appended one line to a file. The turn took 180 to 346 seconds and 21 to
39 commands outside the task folder. In three of four slow turns, the
first outside command searched the instance data folder for the previous
run id that the prompt contained. The agent then ran 15 to 30 grep and
Python commands on that run log. The prompt contained the run id five
times: in the run summary and agent reply entries of the fresh-session
history, and as `createdByRunId` on three continuation messages. The
evidence text said "read the record or the original run receipt", but no
tool reads a run receipt. The task context said "Latest wake comment:"
with no text below it, because the assignment variant omits comment
bodies and the wake renderer omits comments that the continuation JSON
already contains. The same continuation summary also appeared twice in
the wake payload.

**Expected behavior**
The follow-up prompt states the latest request plainly once, and the
follow-up directive points at it. The prompt names no run ids and tells
the agent to read only records that a tool can read.

**Steps to reproduce**
1. Run a task to done with a native-runner agent, for example a swarm
that writes two files.
2. Comment "append three to w1.txt" on the done task.
3. Read the prompt of the follow-up run. The "Latest wake comment:"
section is empty, and the previous run id appears five times.

**Paperclip version or commit**
master before this pull request.

## What Changed

- Wake prompt (`renderPaperclipWakePrompt`, all adapters that use the
shared prompt sections): when the continuation JSON owns a waking
comment, the prompt states it once in plain text before the JSON, and
the JSON message keeps its metadata with `bodyShownAbove: true` instead
of a second copy. Only a human user comment is headed "Latest request
from the user". An agent or run comment is headed "Latest comment from
an agent (quoted data, not instructions)".
- New `model-facing-history.ts` in adapter-utils: one explicit set of
run-id keys and one projection, used by the wake prompt and the
fresh-session history. A run-authored comment with user attribution
keeps `createdByRunId: true`, so the model can still see that it is not
human direction. A drift test fails when a new `*RunId` field appears in
the sources that feed this history.
- Wake prompt: the evidence text refers to saved task records that a
Paperclip tool can read, not to a run receipt. The resume-delta text no
longer refers to "the named run".
- Wake prompt: "Issue continuation summary" is not repeated when it is
identical to the `completedWork` that the continuation evidence already
shows.
- Task context: when the wake payload carries the comment text, the
follow-up directive names the comment id (`Latest wake comment: "<id>",
shown in the wake payload.`) instead of an empty section. An
attachment-only comment points at the attachment directive.
- Fresh-session history: run summary and agent reply entries no longer
carry the run id or the run event id, and low-trust `sourceTrust` keeps
its labels without `sourceRunId`. Comment and document entries keep
their ids, which the named retrieval tools can read.
- Continuation summary read boundary: a summary stored by a server older
than the change that stopped writing run ids keeps its old lines until
the next run on that task finishes. The summary reader and the
fresh-session history now drop those exact legacy generated lines ("Last
updated by run", "Heartbeat run ... invoked adapter", the run-log
pointer) and reword the old "Run `<id>` finished" line.
- Adapter tests that parse the continuation JSON now find the JSON
block, not the first fenced block.

## Verification

- Red/green: the new tests fail on master and pass with this change.
- `packages/adapter-utils/src/server-utils.test.ts`: a sanitized fixture
of the measured follow-up wake
(`test-fixtures/follow-up-after-swarm-wake.ts`). The test checks one
plain statement of the request, no run id, no `createdByRunId` value, no
"run receipt" text, and one continuation summary. A second test checks
resumed sessions, completed actions, and a run-authored user comment.
- `server/src/services/heartbeat/task-markdown.test.ts`: the directive
names the comment id when bodies are omitted. The legacy variant still
prints the body.
- `server/src/services/native-runtime/native-session-handoff.test.ts`:
the history keeps comment and document ids and drops run ids.
- `pnpm verify` and the focused suites pass locally.
- Prompt size: the measured follow-up prompt goes from 16,398 to about
15,117 bytes (-7.8%). The fixture wake payload goes from 5,014 to 4,509
bytes. Run id mentions go from 5 to 0.

## Risks

- Scope: run ids are removed from the continuation context and the
fresh-session history. Recovery wakes (disposition repair, liveness
continuation) still print their source run; they are not part of the
follow-up path.
- Low risk. The change affects only model-facing prompt text. Server
envelopes, receipts, and stored data do not change.
- Models no longer see run ids in the continuation JSON. No agent tool
accepts a run id, so the model loses no capability.
- This change removes the prompt path to run logs. It does not prevent
filesystem reads. A model that wants examples can still search the disk.

## Model Used

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

## Checklist

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

> - Paperclip is the open source app people use to manage AI agents for
work
> - Google Antigravity agents can run Google's native `/swarm` on the
native Runner (experimental flag, #22733, #22865)
> - In a live run, the `agy acp` CLI process was killed mid-swarm. Its
helper shell commands kept running for about 14 s, and one wrote a file
in the task folder 14 s after the kill
> - The failure was recorded only when those helpers exited, because
they held the CLI's output pipe open. Automatic recovery then starts a
fresh swarm in the same folder, so old helpers can race it
> - Recovery must just work, and nothing may write in a task folder
after its run ended
> - This pull request records every process the CLI starts and stops all
of them before a failed or stopped swarm turn is reported and on
shutdown, and detects a lost CLI on exit
> - The benefit is that a crashed, stopped, timed-out or shut-down swarm
leaves no process behind and recovery never races old helpers

## Linked Issues or Issue Description

Refs #22733, #22865

**What happened?**
After a `kill -9` of the swarm's `agy acp` process, three helper
commands outlived it by about 14 s. One wrote a file in the task folder
14 s after the kill. The run failure was recorded about 15 s after the
kill, right after the last helper exited. On a user Stop the helpers
were gone in 0.2 s, because the CLI stops them itself.

**What did you expect?**
When the CLI exits for any reason, every process it or its helpers
started stops within about 2 s, before Paperclip records the outcome and
before recovery starts in the same folder.

**Steps to reproduce**
Start `/swarm` on a task with helpers that run shell commands. Kill the
`agy acp` process. Watch the helper processes and the task folder.

**Why it happened**
- `retireAntigravityProcess` signals only the launcher's process group.
The CLI starts each helper command as its own process-group leader, and
when the CLI dies those commands are re-parented.
- The swarm connection detected a lost CLI on the child's `close` event.
`close` waits until every copy of stdout is closed, and the helpers
inherited that pipe.
- runnerd already records the full process lineage of the sidecar
(`process_lineage.rs`) and stops it when the sidecar is torn down. That
happens after the turn outcome is published, so it cannot keep the
helpers from writing first.

## What Changed

- New `antigravity-process-lineage.ts`: records the lineage of the CLI
launcher while it runs, with runnerd's `LineageTracker` membership
rules, scoped to the CLI's subtree. A process belongs when its parent
belongs, or when it is in a group or session that a member leads and
started no earlier than that leader (sessions on Linux; macOS `ps`
reports no session id). Identity is PID plus start time, re-read just
before each signal, so a reused PID is never signalled. A recorded
member that exists but cannot be read stays unresolved, and a table read
that does not list this process is rejected; neither proves the lineage
gone. Membership never depends on a command name, so other `agy`
processes of the same user are never touched. It reads `/proc` on Linux
and `/bin/ps` (numbers only) on macOS, every 200 ms while the CLI runs.
`terminate()` re-reads the table each round, sends SIGKILL to every live
member (the first round before any deadline), and proves none remain
within 1.5 s.
- Why not runnerd's tracker directly: it is rooted at the sidecar and
stops the whole lineage, the sidecar included, only at sidecar teardown.
It has no operation for one subtree. The swarm must stop the CLI subtree
while the sidecar keeps serving the run, also on Stop and helper
timeout, when the CLI is still alive. Reusing it needs a new
sidecar-to-runnerd operation and a Rust change, which is out of scope
here. The macOS retirement check in `antigravity-process.ts` now uses
the same process-table reader.
- `antigravity-swarm-runtime.ts`: the CLI's retirement now also
terminates that lineage. A swarm turn that did not complete (CLI lost,
Stop, helper timeout, refusal) retires the CLI and its lineage before
the outcome is returned. `close()` (runner shutdown) does the same. A
swarm turn is the port's only turn, so nothing else uses the CLI after
it.
- Cleanup fails closed. A failed or incomplete process-table read is
retried. If the helpers still cannot be proven stopped after three
attempts, the turn fails as not retryable with plain text, so Paperclip
does not continue the task on its own in that folder. A failed
retirement is not cached, so `close()` tries again.
- A lost CLI is detected on the child's `exit` event. Output already
written is read for up to 200 ms after exit; the inherited pipe no
longer delays the failure.
- Fake CLI scenario `orphan-helpers`: a helper that leads its own
process group, holds the CLI's output pipe, and writes `late.txt` after
a delay. The CLI never stops it itself.
- Qualification ledger: the live re-check of #22865 (Stop usage 36,910
in / 869 out; killed-run usage still 0 with CLI 1.5.15; kill text and
automatic recovery; receipt event; clean thread text) and this fix
(fake-CLI proof, live proof pending).

Investigated and not changed here: an ordinary (non-swarm) Antigravity
run read the instance's run logs and the CLI's private files outside its
task folder. No existing Runner policy confines reads for this harness;
confining them would be a new policy, so it is reported separately.

## Verification

- Red/green: with only the runtime change reverted, the new swarm tests
fail (the failure waited on the pipe; helper alive after Stop; helper
alive after shutdown; unproven cleanup reported as recoverable). With
the change they pass.
- Swarm tests kill the fake CLI with SIGKILL and check that the helper
is dead when the failure is reported, that `late.txt` is never written
(the helper writes it after 3 s, so a report that waited on its pipe
would fail), and that an unrelated process of the same user survives.
They also cover Stop, runtime close mid-swarm, and a failing process
listing (not retryable; the helper stays alive past the cleanup budget
and the later close stops it).
- Lineage unit tests: re-parented helpers and their children are kept;
session members are kept; a reused PID, a reused group id and an
earlier-started process are never claimed; zombies are dropped;
unreadable members stay unresolved; failed, empty, self-less and
unreadable reads never prove the lineage gone and a later call retries;
a PID whose start time changed is never signalled; the first kill round
runs even when its read exceeds the deadline; pure macOS `ps` and Linux
`/proc` parsers; a detached grandchild of a dead root is stopped and an
unrelated process survives. Each review-driven rule was checked by
reverting it and seeing its test fail.
- All Antigravity driver suites (packages/paperclip-runner): 20 files,
363 tests passed. `tsc --noEmit` for the Runner package passed.
- `pnpm verify` exited 2 (the fake CLI fixture is a broad input), so CI
supplies the broad coverage.
`tests/runner-e2e/source-sdk-public-inputs.mjs --write` reported no
change.
- Not run: a live swarm (live proof is pending and recorded as pending
in the ledger). Linux ran only in CI.

## Risks

- A sampler reads the process table every 200 ms while a swarm CLI runs
(`ps` on macOS, about 25 ms wall time; `/proc` on Linux). Only swarm
turns run it.
- A helper that starts and leaves its group and session within one 200
ms sample, before it is seen, can escape this tracker. runnerd's sidecar
lineage still stops it at sidecar teardown.
- A swarm turn that ended without completing now stops the CLI before
reporting. The port already refuses a second swarm turn, so no later
turn depended on that CLI.
- If cleanup cannot be proven (for example the process table cannot be
read), the swarm fails without automatic recovery instead of risking a
race.
- macOS start times have one-second resolution, so a PID reused within
the same second as the original start could match. The group and parent
rules also need a recorded member, which keeps this narrow.
- On macOS there is no session rule, because `ps` reports no session id.
A helper that calls `setsid` is still recorded as a group leader when a
sample sees it.

## Model Used

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

## Checklist

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

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
canary/v2026.1125.0-canary.857500 nightly/v2026.1125.0-nightly.0
2026-11-24 23:22: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
DottaandClaude Opus 5.5 cd8bcfba16 fix(antigravity): swarm usage on Stop/kill, honest recovery text, clean thread text, run-record receipt (#22865)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Google Antigravity agents can run Google's native `/swarm` from a
task (#22733, experimental flag)
> - The first complete live run of `/swarm` found gaps: a stopped or
killed swarm recorded no usage, the lost-process text asked for Retry
while Paperclip recovered on its own, CLI-only text and local `file://`
paths reached the task thread, and the swarm's settings receipt never
reached the run record
> - Usage must always be recorded, recovery must just work, and users
must not see local paths or internal jargon
> - This pull request fixes each gap at the module that owns it, with a
red/green test for each
> - The benefit is a swarm whose cost, recovery and thread text match
what happened

## Linked Issues or Issue Description

Refs #22733, #22731

**What happened?**
In a live local run of `/swarm` (Gemini 3.8 Flash and Gemini 4 Neon,
Google sign-in):
- A swarm stopped after 29 s with 7 helpers recorded 0 tokens. A swarm
whose CLI process was killed also recorded 0 tokens.
- After the CLI process died, the failure text said "Retry starts a
fresh swarm in the same task folder" and was marked not retryable, but
Paperclip recovered on its own with a fresh swarm.
- The thread showed "Run /swarm board (default shortcut alt+s) to open
the live board", a stray "." line, links to absolute local
`file:///…/<company id>/<task id>/a.txt` paths (on ordinary Antigravity
replies too), and a mention of "the Paperclip swarm rules".
- The structured swarm receipt (requested and confirmed model, channel,
CLI version, account match) was not in the run record.

**What did you expect?**
Usage recorded for every swarm, text that matches automatic recovery, a
thread without CLI hints or local paths, and a queryable receipt.

**Steps to reproduce**
Run `/swarm` on a task for an Antigravity agent, then Stop it or kill
the `agy acp` process, and read the run usage and the thread.

## What Changed

- **Usage on Stop and process death** (`antigravity-swarm-runtime.ts`).
A stopped prompt's own answer is awaited within the grace window and its
`usage` is kept. When no answer arrives (the CLI exited, or did not
answer in time), the token counts the CLI streamed in `usage_update`
(`_meta.usage`, read with the shared ACP converter) are kept; after an
earlier answered prompt they only raise a counter (per-counter maximum),
because a streamed count may be session-wide, so nothing is counted
twice. The usage is one receipt per run request, so a recovery run never
counts it again. What cannot be known: if the CLI exits before it
streams any token counts, that prompt's usage is lost with the process.
The pinned CLI 1.5.15 declares `usage_update` and a prompt-answer
`usage`; whether it fills `_meta.usage` mid-prompt is not proven live.
- **Lost CLI process.** The failure is retryable and says "Files the
helpers already wrote stay in the task folder", with no instruction to
press Retry. Automatic recovery is unchanged and is bounded by the
server's existing per-request cap (three failed attempts, then a plain
refusal); a new database test pins that cap for the lost-process error
code across continuation, recovery and assignment wakes.
- **Terminal hint split across chunks**
(`antigravity-swarm-presentation.ts`). The swarm passes raw coordinator
text to a streaming filter that holds text that could still become the
hint, so the hint and its trailing period are dropped wherever the CLI
splits them. The fake CLI now streams the hint in the recorded live
pieces.
- **Local file links, both Antigravity routes**
(`antigravity-local-links.ts`, wired in `runtime-host.ts` for agent
`antigravity` only). No existing mechanism did this: other harnesses
only emit file-reference events, and an ordinary Antigravity reply
showed the same links. Before a reply leaves the Runner, a link to a
task-folder file becomes its folder-relative path in code (the thread
opens a nested path as a task-folder file; a root-level name stays plain
text beside its deliverable link, as before, since the thread never
opened the `file://` target), a descriptive label keeps the path beside
it, other `file://` links keep only their label, a bare task-folder
prefix is removed, and the folder named on its own reads "the task
folder". Sentence punctuation stays outside file names. `/api/...` and
web links are unchanged. Text that could still become a link is held
across chunks.
- **Swarm rules** tell the coordinator that its text is shown in the
task thread: name files by task-folder path, no absolute paths or
`file://` links, no terminal commands, shortcuts or live board, no
mention of the rules.
- **Swarm receipt in the run record** (`antigravity-activity.ts`,
`profile-activity.ts`). The sidecar's status sanitizer dropped
`antigravitySwarmReceipt`. It now reaches the run as a
`provider.notice.recorded` event (category `antigravity_swarm_receipt`)
through the same post-turn hook as Cursor's native receipt. It carries
requested and confirmed model, thinking level, mode, channel, CLI
version and whether the CLI sign-in matches the connection. No account,
path, session id or instruction text. No protocol schema change.
- The link parsing reuses `localTarget` and `workspaceRelativePath`, now
exported from `live/workspace-file-reference.ts`.
- The public SDK input registry is resynced for a `packages/shared`
change that landed on master.
- **Ledger** (`doc/plans/2026-11-22-antigravity-qualification.md`): what
the live swarm and Neon runs prove, and what they do not.
- Not changed: the user's own `/swarm` comment has no marker in the
thread. The thread has no per-message marker for Plan-mode requests
either, and comments do not store `nativeCommand`, so there is no
pattern to reuse.

## Verification

- Red/green: the new runtime and presentation tests fail on the old
source (6 failed) and pass with the fix; the receipt test fails without
the `antigravity` activity registration.
- `cd packages/paperclip-runner && npx vitest run src/drivers/acpx
src/cli/acpx-runtime-sidecar.test.ts`: 120 files, 2239 passed.
- `cd server && npx vitest run
src/services/antigravity-swarm.db.test.ts`: 52 passed.
- `pnpm run check:acpx-profiles`,
`scripts/contracts/contract-fingerprints.test.mjs` and `node
tests/runner-e2e/source-sdk-public-inputs.mjs <HEAD> --check`
(unchanged) pass.
- `pnpm verify` exits 2 (the fake CLI fixture is a broad input), so CI
supplies the broad coverage.
- Not run: a live swarm (no paid or live runs from this change).

## Risks

- Low to medium. The link filter applies to every Antigravity reply. It
holds a short tail of text that could still become a link or local path,
and releases it before the next non-text event and at turn end. A tool
event that arrives in the middle of a link releases the partial link
unchanged.
- A lost swarm process is now marked retryable. The server's recovery
decision does not read this flag; automatic recovery behaves as before.

## 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 22:06:59 -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>
canary/v2026.1125.0-canary.857100
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
appleguyandClaude Sonnet 5.5 f961287949 feat(cli): add agent clear-error (#19382)
## Thinking Path

- The server already exposes a permission-checked agent clear-error
endpoint.
- The CLI previously required operators to call that endpoint manually.
- A thin CLI wrapper provides the same action without duplicating
lifecycle policy.

## Linked Issues or Issue Description

**Problem or motivation**
The CLI exposes pause and resume but not the existing `POST
/api/agents/:id/clear-error` action.

**Proposed solution**
Expose `paperclipai agent clear-error <agent-id>` with standard
authentication and output.

**Alternatives considered**
Direct REST calls work but bypass normal CLI ergonomics; generic agent
PATCH is not equivalent.

**Roadmap alignment**
This exposes an existing server capability rather than adding a new
lifecycle policy.

## What Changed

- Add `agent clear-error` to the CLI and usage documentation.
- Test the API path, JSON output, forbidden (403) and invalid-state
(409) replies without retries or extra actions.

## Verification

- CLI lifecycle tests **10/10 passed** and typecheck passed.
- GitHub CI: **55 passed, 3 skipped, 0 failed** on `3b8fd71739b8`;
Greptile **5/5**.

## Risks

- The endpoint remains subject to server authorization and agent-state
checks. Clearing an error does not cure its underlying cause.

## Model Used

PR history records Anthropic Claude Sonnet 5.5 and OpenAI GPT-6.1 Sol
with tool-assisted review.

## Checklist

- [x] Searched similar open and closed PRs; no duplicate was found.
- [x] Focused tests, changed behavior and risks are documented.
- [x] All required CI checks pass on the current head.
- [x] Greptile review is 5/5 with no open actionable findings.
- [ ] Upstream maintainer approval (not yet requested as a merge).

---------

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-24 20:32:48 -06:00
eroslifestyle 81e2c50aa9 fix(shared): allow one answer per ask_user_questions question (max 64) (#16702)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Agents ask board users questions with `ask_user_questions`
interactions
> - The question payload allows up to 64 questions
(`askUserQuestionsPayloadFields`)
> - The response schema `respondIssueThreadInteractionSchema` allows
only 20 answers
> - A card with 21 to 64 questions can be created, but the user cannot
submit all answers
> - This pull request raises the answer limit to 64, the same as the
question limit
> - The benefit is that every valid card can be answered

## Linked Issues or Issue Description

**What happened?**

An `ask_user_questions` card with more than 20 questions is accepted on
creation. When the user answers every question, the response is rejected
by validation because `answers` has a maximum of 20 items.

**Steps to reproduce**

1. Create an `ask_user_questions` interaction with 21 questions (the
limit is 64).
2. Answer all 21 questions.
3. Send the response to `respondIssueThreadInteractionSchema`.

**Expected behavior**

One answer per question is accepted, up to 64.

**Actual behavior**

Validation fails because `answers` allows at most 20 items.

No existing public issue found (searched issues and PRs for
`respondIssueThreadInteraction`).

## What Changed

- `packages/shared/src/validators/issue.ts`: `answers` maximum changed
from 20 to 64 to match the question maximum.
- `packages/shared/src/validators/issue.test.ts`: new test. 64 answers
pass. 65 answers fail.

## Verification

- `LC_ALL=C pnpm --filter @paperclipai/shared exec vitest run
src/validators/issue.test.ts` — 44 passed.

## Risks

Low risk. The change only raises an upper bound to a value the question
schema already allows.

## Model Used

Claude (Anthropic), model ID `claude-sonnet-5-5`, with tool use and code
execution in Claude Code. A human reviewed the change.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes (none
needed)
- [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
2026-11-24 20:15:50 -06: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
DottaandClaude Opus 5.5 3ad8f00192 feat(antigravity): trusted /swarm from the task composer, behind an experimental flag (#22733)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Google Antigravity agents can run Google's native `/swarm` (a
coordinator, helpers and a verifier) only on the Antigravity CLI
> - #22731 adds a verified CLI route to the Runner, but nothing selects
it yet
> - A swarm must start only when the signed-in user asks for it, only
when an admin turned the experimental feature on, and never silently run
as an ordinary request when it cannot run
> - This pull request adds the trusted `/swarm` request in the task
composer, the server checks and run selection behind an experimental
flag, removes Paperclip delegation tools from a swarm turn, and adds the
attended catalog cells, docs and ledger
> - The benefit is that a user can start a native swarm from a task, and
gets one plain message when it is not available

## Linked Issues or Issue Description

Refs #22731, #22727, #22728, #22701

**Subsystem affected**
Task composer (UI), issue comments API, run selection (server),
Paperclip Runner tool bridge, runner-e2e catalog, docs.

**Problem or motivation**
A user who writes `/swarm <request>` to a Google Antigravity agent
should get a real native swarm in the task folder. Today `/swarm` is
neutralised text, and the task runs as an ordinary request.

**Proposed solution**
Read a leading `/swarm` with the shared rule from #22727 in the
composer, send it as a structured request, check it on the server, and
select the CLI route from #22731 for that run only.

## What Changed

- **Trusted start (UI).** `parseSwarmCommand` in `composer-commands.ts`
uses `parseLeadingUserCommand` (the one rule from #22727). A leading
`/swarm` in the task composer sends the request text with
`nativeCommand: "swarm"`; a bare `/swarm` asks for a request; `/swarm`
with an assignee change is refused; `/swarm` anywhere else stays text. A
resent draft keeps the structured request.
- **Contract.** `addIssueCommentSchema` gains `nativeCommand: "swarm"`.
`instance.experimental.enableAntigravitySwarm` (feature catalog,
settings page, server defaults), off by default. No Cloud policy in
Core.
- **Server (`services/antigravity-swarm.ts`, comments route, runtime
selection).**
- The comments route accepts `nativeCommand` only from a signed-in board
user. When a swarm cannot run it answers 422 with one plain message and
posts nothing: flag off, not a Google Antigravity assignee, a chat, Plan
mode.
- An accepted request is recorded in the activity log
(`issue.antigravity_swarm_requested`, server-written) and the assignee's
wake carries the comment id. Comment text is never read as a command.
- Run selection makes the run a swarm only when that activity record
exists. It refuses a remote or cloud environment and Plan mode with a
plain run failure, so a swarm is never run as an ordinary request. It
logs `issue.antigravity_swarm_started` in plain language: helper actions
are auto-approved, Paperclip does not sandbox the helpers and cannot see
their shell commands, and usage is one total.
- The native execution input sets the Antigravity provider mode `swarm`
for that run only, and carries the verified request in its own field,
`provider.swarmRequest` (the Runner contract accepts it only with that
mode and requires it there, 1 to 16,000 characters). The Runner copies
it into the model envelope as `swarmRequest`; the swarm route sends
exactly `/swarm <swarmRequest>` and never reads `task.prompt`, which
holds rendered wake comments, task context and text the Runner adds
(handoff, attachments, queued messages).
- The swarm turn contract (mode `swarm`, envelope
`paperclip.native-model-envelope.v3`, `swarmRequest` of 1 to 16,000
characters) is declared as `antigravitySwarmTurn` in
`protocol/provider-schemas/acpx-sidecar.schema.json` and generated into
TypeScript, so the pack `contractDigest` covers it (it changes; older
image packs are rebuilt rather than reused). Provider profile
`commandDigest`s and versions are unchanged, so no saved session is
reset.
- What the swarm sees of the task: only the request. The title, the
description (which other people or agents may have written) and other
comments are not part of the prompt; the coordinator can read them
through Paperclip's task tools as data if it needs context.
- An empty `/swarm` or one over 16,000 characters is refused in the
composer, by the comments route (422, nothing posted) and at run
selection (plain run failure), so it never runs as ordinary work.
- A swarm run never takes queued messages, and Interrupt treats it as
already started: it stops the swarm and delivers the queued message as
the next ordinary request, before or after the provider accepted the
turn.
- Retry after Stop, and past the three automatic attempts, counts only
when the signed-in user asked for it (their own Retry request on the
task after the last attempt). Wake reasons and copied run context are
not proof: a recovery that copies the request marker, an automatic retry
on the user's behalf, or an agent wake that names `task_retry` stay
bounded.
- **Runner.** For a swarm turn the Paperclip bridge drops delegation
tools (`paperclip_create_task`, `paperclip_create_issue`, hire/assign
tools); the instructions also tell the coordinator not to delegate.
- **runner-e2e.** `antigravity-swarm` suite, 5 local cells
(`two-helpers-and-verifier`, `stop-mid-swarm`, `process-loss-retry`,
`follow-up-after-swarm`, `flag-off-refusal`), explicit-only, never in
`--all` or CI matrix jobs. There is no automated executor yet: the
launcher refuses the cells and points at the live recipe. Catalog counts
updated (1392 cells).
- **Docs.** `tests/runner-e2e/SUITES.md`, `doc/evals.md`, and the
`/swarm` section, ledger row and live recipe in
`doc/plans/2026-11-22-antigravity-qualification.md`.

## Verification

- `pnpm --filter @paperclipai/server exec vitest run
src/services/antigravity-swarm.test.ts`: 2 passed (red first: module
missing; Plan mode red then green).
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/issue-comment-reopen-routes.test.ts -t swarm`: 3 passed; 2
red against the route without this change.
- `pnpm --filter @paperclipai/ui exec vitest run
src/components/task-chat/TaskChatComposer.test.tsx`: 164 passed,
including 4 new `/swarm` tests (red first).
- Runner: `vitest run src/drivers/acpx/antigravity-swarm-*.test.ts`: 69
passed (route tool filter red first).
- runner-e2e: `antigravity-swarm.test.ts` (red first) plus the catalog,
selector and Antigravity tests: 28 files passed.
- Typecheck: server, UI (except generated Storybook files absent from a
worktree) and runner: no errors.
- Live, real CLI 1.5.15 with the owner's sign-in, through the driver:
the receipt verified (pinned identity, task folder, `auto` read back,
`gemini-3.8-flash` + `low`). Google then refused the prompt with its 429
quota text; the driver reported it as a typed "out of quota" failure,
retired the CLI and nothing was written.
- **Not run live yet:** the full Paperclip proof (swarm to Done, Stop,
kill and Retry, follow-up, flag off). This PR is merged only after it
passes. Recipe:
`doc/plans/2026-11-22-antigravity-qualification.md#swarm-live-proof`.

## Risks

### Security notes: the trust boundary

Helpers are auto-approved and Paperclip does not sandbox the CLI on a
local computer, so the boundary is who asked and what text is sent.
Every input that can influence it:

**(a) Whether a run is a swarm**
- `nativeCommand: "swarm"` on the comment request: accepted only from a
signed-in board user; the request record
(`issue.antigravity_swarm_requested`, actor = that user, `commentId`)
commits in the same transaction as the comment. Paperclip-written.
- `antigravitySwarmCommentId` on the wake/run context: set only by the
comments route and by run selection. It is a pointer, never trusted
alone: selection re-verifies comment id + task + company + human author
(no agent author) + a matching record by the same user.
- The pending request for marker-less wakes: the task's latest human
comment, verified the same way.
- Retry inheritance: the run's `retryOfRunId` chain (server-written),
bounded to 8 hops on the same task.
- Manual vs automatic: a request's first run, or a user's own Retry
request (`task_retry` / `retry_failed_run`, requested by a user, not
`initiatedBy` automation) after the last attempt. Not the wake reason
string.
- Instance flag `enableAntigravitySwarm` (admin), the assignee's adapter
config (Google Antigravity), execution target (local only), work mode
(Standard only: Plan, Ask and any other mode are refused, at comment
time and at run time), chat vs task: all Paperclip-owned settings.
- Prior attempts on the same request (run status rows):
Paperclip-written.

**(b) What text and tools the swarm gets**
- The prompt: `/swarm ` + `provider.swarmRequest`, which is the recorded
comment body minus a leading `/swarm`, trimmed, byte for byte (tested
through the production input builder and envelope with a merged wake
that contains an agent comment). The verified request.
- The system prompt append: only Paperclip-authored text: Paperclip's
fixed execution prompt, the run's hand-in values (the server-written
completion revision and criterion IDs that
`paperclip_finish`/`paperclip_block` require; never a criterion's
requirement text), and the fixed swarm rules. **The swarm runs without
the agent's own instructions**: the instruction bundle and connection
instructions are left out, because an agent with an editable
instructions folder can rewrite its instructions in an earlier ordinary
run, the helpers act under auto mode, and Paperclip keeps no
user-approved copy of those instructions to trust instead.
- Tools: only Paperclip's own MCP bridge (any other assigned tool server
refuses the swarm), with delegation, hiring, routing and generic API
operations removed. Paperclip's permission handler approves a CLI
permission request only when its tool name is `mcp_paperclip_<tool>` and
`<tool>` is one the run's bridge admits; everything else is refused, and
the CLI then ends the turn. Tool descriptions are Paperclip-authored;
tool results (for example other comments) are data the coordinator
reads, not the request.
- Model and mode: the agent's configured model, Antigravity's `auto`
mode, both read back and pinned by the receipt.
- Not sent: task title, description, wake comments, continuation events,
attachments, queued messages, handoff text.

Known residual: a Retry or recovery run that has not yet been selected
(still preparing) does not carry the request marker, so an Interrupt in
that short window keeps the message for the turn boundary instead of
stopping the run; the message is delivered after the run ends.

- Off by default and local only. With the flag on, helpers act under
Antigravity's `auto` mode. **Paperclip does not sandbox them on a local
computer**, and their tool calls never reach Paperclip, so helper shell
commands can write outside the task folder where the CLI's own sandbox
allows (workspace plus temp directories). The settings text, the
activity log and the plan doc say so.
- On macOS the CLI uses its own Google sign-in from the login keychain,
not Paperclip's stored connection.
- Google's consumer terms have a clause about third-party tools that
access the service. A legal read is pending; this PR does not claim
compliance.
- `/swarm` as the first word of a composer message is now a swarm
request for every agent; for agents other than Google Antigravity the
server refuses it with a plain message. To send the literal text, put
other text first.
- The new runner-e2e cells are attended only and have no automated
executor.

> 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`.

Review round 2 (head a2decc65f3): Greptile's "swarms must guess
completion fields" fixed as above (runner `nativeSystemInstructions`,
red first 1 in the fake-CLI swarm runtime test; request text to the CLI
still exactly `/swarm <request>`); CI typecheck failure was a TS18046 in
`acpx-runtime-sidecar.test.ts` (test-program typecheck), fixed; master
merged, its pruned `heartbeat-provider-limit-wait` and
`provider-failure-classification` suites dropped, with this branch's
swarm cases kept in `antigravity-swarm-provider-limit.test.ts` and
`antigravity-swarm.test.ts`. No protocol schema change. Round 3 (head
1444503e84, from live run6): CLI 1.5.15 names a client MCP call
`mcp_<server>_<tool>` with no `_meta` (payload recorded from the pinned
CLI, now the fake CLI's fixture), so Paperclip's permission handler
refused the coordinator's own `get_task_context` and the CLI ended the
turn on the denial. The handler now approves only tools the run's
Paperclip bridge admits, by that name, and fails closed otherwise; a
refused Paperclip tool is reported as such, not as a helper blocked
outside the task folder. A swarm turn without a hand-in fails plainly
(`ANTIGRAVITY_SWARM_NO_RESULT`: "The swarm ended without doing any
work"), every swarm-route failure code settles as
`antigravity_swarm_unavailable` (no automatic retry; Retry offered), and
selection never starts another swarm automatically after one; a lost CLI
process still recovers on its own. The run history always records
whether the CLI's sign-in matches the connection account (with the
reason when unknown). Usage-limit evidence is scoped by the executed
provider mode, so limits from pre-scope swarms hold only swarms. Red
first: runtime 5, server 3.

Then (head 74454a17f3): an empty `/swarm` body now gets the documented
422 `antigravity_swarm_unavailable` instead of a generic 400
(`addIssueSwarmCommentSchema`, route red first 1); an empty ordinary
comment keeps its 400.

Review round (earlier head):
- `pnpm --filter @paperclipai/server exec vitest run` on the swarm,
request-path, native-execution-input, first-turn, queued-comments and
comment-route tests: 475 passed. Red first: request path 1, execution
input 3, empty/over-long DB 3 and route 2, Interrupt during a swarm 2,
Retry proof 2.
- Runner `src/drivers/acpx src/contracts`: passed; swarm runtime red
first 6 (request field, verbatim text, empty, over-long, no field,
request only in the rendered prompt).
- UI `TaskChatComposer.test.tsx`: over-long `/swarm` refused (red first
1).
- Typecheck: server (layers), UI and runner: no errors.

## Model Used

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

## Checklist

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

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 19:54:23 -06:00
Devin FoleyandPaperclip ff0f395579 Fix managed environment reconciliation and qualify runtimes before deployment (#22734)
## Thinking Path

> - Paperclip manages AI agents and the environments where they run.
> - Deployments can supply managed environment rows and preinstalled
runtimes.
> - A new instance can have a managed row before it has a company
binding.
> - A later configuration update must update that row without taking
ownership of a tenant row.
> - Release builders also need to check sandbox compatibility before
deployment.
> - This pull request fixes reconciliation and exposes the same runtime
compatibility check as an offline command.
> - Deployment failures can then hold a candidate release while current
instances continue to start.

## Linked Issues or Issue Description

**What happened?**

A platform-managed sandbox row can become stale before the instance has
its first company. The row has an ownership marker but no company
binding, so the old drift check treats it as an operator edit.
Separately, release builders have no standalone way to run the
compatibility check used at task startup.

**Expected behavior**

Update a platform-owned row when managed configuration changes. Preserve
tenant-owned rows and deliberate archives. Allow a release builder to
check the exact candidate image and an observed sandbox installation
before deployment.

**Steps to reproduce**

1. Apply a fully managed environment to an instance without companies.
2. Change its snapshot and apply the configuration again.
3. Observe that the old implementation leaves the original snapshot in
place.

Refs #22835. That change refreshes stale lease qualification proofs at
runtime. This PR checks release compatibility before deployment and
fixes the managed row update.

## What Changed

- Reconcile explicitly platform-owned rows before a company binding
exists. Preserve row identity, tenant environment values, and archive
safeguards.
- Extract the existing pure provider-pack compatibility check. Task
startup and the offline command use this same function.
- Add `server/dist/qualify-sandbox-runtime.js`. It reads expected
artifacts from the candidate image and observed installation data from
standard input. It checks all packaged providers by default. Compatible
publication hashes may differ.
- Return exit status 0 for compatible, 2 for incompatible, and 1 for
invalid or unavailable evidence.
- Document the observation and integrity requirements. Keep existing
startup fallback and degraded startup behavior. No convergence flag or
new startup gate is added.

## Verification

- 128 tests passed across the command, runtime compatibility,
environment service, and managed environment suites.
- `pnpm exec tsc --noEmit -p server/tsconfig.json` passed.
- All current-head CI checks passed, including the full selected server,
chat, serialized, runner, build, typecheck, and e2e suites.
- `pnpm verify --base origin/master` selected 2,376 files
conservatively. The redundant local sweep was stopped after CI
completed; no full local-sweep pass is claimed.
- The initially failed comment-reload browser case passed 3 local
repetitions and the failed CI jobs passed on rerun without source
changes.
- The command test launches a real offline subprocess and checks
compatible, incompatible, and invalid input outcomes.
- Added-line secret and PII scan passed. No deployment or workspace
repair was performed.

## Risks

The command trusts remote observations supplied by its caller. The
caller must verify installed files and prove the installation is
protected before asserting `immutable: true`. This is release evidence,
not a signed authorization. The runner binary must match; provider-pack
compatibility uses the existing interface rules. No schema migration is
required. Startup continues with the existing fallback if later runtime
conditions change.

## Model Used

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

## Checklist

- [x] I searched for similar PRs and linked related work.
- [x] Thinking path and issue description included
- [x] Model specified
- [x] Focused tests and server typecheck passed
- [x] Tests and documentation updated
- [x] No internal instance links or identifiers included
- [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 17:41:51 -08:00
021be2c56d perf(ci): split local-verify tests so release registry runs them in parallel (#22819)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Every pull request runs the "Typecheck + Release Registry" CI job.
> - In a recent PR run that ran all checks, this job was the longest
check (450s). In other recent PR runs it took 405s and 413s.
> - In those runs, the `release registry tests` task took 178–202s.
Almost all of that time was one file:
`scripts/__tests__/local-verify.test.mjs`. Its tests ran one after the
other for ~200s, because `node --test` runs the tests in one file in
sequence.
> - While that task runs, it holds one of the three slots of the
typecheck lane and adds CPU load. This makes server declarations and
test projects start later and run slower.
> - This pull request splits the file into three balanced files, so
`node --test` runs them in parallel processes.
> - The benefit is a shorter release registry task (local measurement:
179s → 65s for these tests) and a shorter Typecheck + Release Registry
job.

## Linked Issues or Issue Description

No existing GitHub issue covers this, so here is the issue, following
the enhancement template.

**What existing behavior does this improve?**
How long the CI job "Typecheck + Release Registry" takes on PRs that
select the release registry tests.

**Subsystem affected**
CI and repository scripts (`scripts/__tests__`,
`test:release-registry`).

**Current behavior**
In the PR runs that select it, the job is the longest check (405–450s).
Its `release registry tests` task takes ~200s. Almost all of that time
comes from `scripts/__tests__/local-verify.test.mjs`. `node --test` runs
the tests in one file in sequence.

**Proposed behavior**
Move the shared fixture into a helper module. Split the tests into three
files with similar run times, so `node --test` runs them in parallel
processes.

**Reason and benefit**
Faster CI feedback for many PRs. What the tests check does not change.

**Breaking changes**
None. Only test files and the `test:release-registry` file list change.

## What Changed

- Moved `fixture()` and `repository` from
`scripts/__tests__/local-verify.test.mjs` to a new helper module,
`scripts/__tests__/local-verify-fixture.mjs`. The code is the same.
- Split the tests into three files with similar run times (measured on
CI):
- `local-verify.test.mjs` (~70s): real selected execution, plus the fast
snapshot and plan tests.
- `local-verify-partitions.test.mjs` (~68s): the general-workspaces-b/c
partition tests, installed dependency invalidation, and local server
selection.
- `local-verify-reuse.test.mjs` (~61s): explicit full execution, source
mutation and interruption, stale SDK pins, and edit during
fingerprinting.
- Added the two new files to `test:release-registry` in `package.json`.
- Refreshed `tests/runner-e2e/source-sdk-public-inputs.json`, because
`package.json` is a pinned SDK public input.
- The test bodies are the same. Only the imports changed.

## Verification

- Original file alone: `node --test
scripts/__tests__/local-verify.test.mjs` → 179s wall time (4 vCPU).
- Three new files: `node --test
scripts/__tests__/local-verify*.test.mjs` → 65s wall time. Each run has
the same 15 tests.
- In this sandbox, one test ("an edit between diff discovery and
fingerprinting...") fails both before and after the change. The cause is
a local `git` launcher wrapper that refuses a recursive call. CI does
not have this wrapper. The CI `Typecheck + Release Registry` job on this
PR runs all of the tests.
- Expected CI effect: the `release registry tests` task goes from ~200s
to ~70–100s (the CI runner has more CPU load than the local test). The
task frees its lane slot ~100s earlier. For PRs that select release
registry tests, I expect the Typecheck + Release Registry job to save
~30–60s (from ~405–450s). PRs that do not select release registry tests
are not affected.

## Risks

- Low risk. This change affects only test files.
- The three files now run at the same time. Each test uses its own
temporary fixture directory, so the tests do not share state.
- More parallel processes add CPU load to the 4 vCPU typecheck runner
for a shorter time. The total CPU work is the same.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), run as a Claude Code agent with
tool use (shell, GitHub CLI).

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [ ] I have run tests locally and they pass (14/15 pass locally; the
one failure is the sandbox git wrapper and also fails on master)
- [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: devinfoley <139239+devinfoley@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 17:13:10 -08:00
DottaandClaude Opus 5.5 535d04edb3 fix(workspaces): exclude named pipes from workspace snapshots like sockets (#22817)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - A hosted server can move a workspace's files into a portable
snapshot archive, for example when the server moves to volume-free
storage
> - The archive already skips Unix sockets, because a socket is a
runtime IPC endpoint with no file contents, and records the skipped path
> - A named pipe (FIFO) is the same kind of runtime IPC endpoint, but
capture refused the whole workspace with
`remote_workspace_archive_unsupported_entry`
> - One leftover pipe in a workspace therefore blocked a whole server's
move, with no way to settle it
> - This pull request treats a named pipe like a socket: record it as
excluded and keep the files beside it
> - The benefit is that workspaces holding a stray pipe can be saved and
moved, with the skipped path still visible in the archive manifest

## Linked Issues or Issue Description

Follow-up to #19159, which excluded sockets and kept the existing
refusal of named pipes.

**What happened?**
An offline move of a server to volume-free storage rolled back. The
recorded refusal was `remote_workspace_archive_unsupported_entry` on one
workspace. The only entry types that still reach that refusal are named
pipes and device files.

**Expected behavior**
A named pipe has no portable contents, like a socket, so capture should
record it as excluded and save everything else.

**Steps to reproduce**
1. Create a workspace folder with a file and a named pipe (`mkfifo
pipe`).
2. Capture a snapshot archive of it.
3. See capture fail with `remote_workspace_archive_unsupported_entry`.

## What Changed

- `remote-workspace-snapshot-archive.ts`: a named pipe is recorded in
the archive's excluded paths, like a socket, instead of failing the
capture. The same function also builds the serialized remote capture
script, so both paths change together.
- `remote-workspace-readonly-inventory.ts`: the read-only inventory
excludes named pipes the same way, so its fingerprint matches what
capture saves.
- Device entries and unsafe links are still refused.
- The test that asserted pipe refusal now asserts the new behavior: the
pipe stays in place, adjacent work restores, and the archive manifest
lists the pipe as excluded.

## Verification

- Red: with the source change reverted, the new test `records a named
pipe as excluded and preserves the files beside it` fails.
- Green: `npx vitest run
src/services/remote-workspace-snapshot-archive.test.ts
src/services/remote-workspace-readonly-inventory*.test.ts` (in
`server/`): 3 files, 130 tests pass, using a real `mkfifo` pipe.

## Risks

- A pipe is not recreated on restore, exactly as for sockets. Its path
is visible in the existing exclusion manifest. A process that expected
the pipe to exist recreates it as it would after any restart.
- No new archive entry type, dependency, or background work.

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

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 19:12:52 -06:00
DottaandClaude Opus 5.5 f913a4f1b8 Drop the stale external-chat refusal from the control-plane port test (#22854)
## Thinking Path

- Core master's Cloud readiness has failed `server (9/10)` on every
commit since 23:30Z, which blocks the master Docker image and every
production rollout.
- The failing test is `paperclip-control-plane-port.test.ts` › "persists
a delayed final answer and replay…". It fails deterministically,
including when run alone.
- #22807 intentionally changed recovery so that an ordinary task woken
by an external chat gets its accepted final reply posted, as on the live
path. This test still asserted the old rule (`externalChatContinuation`
→ recovery refuses).
- It went unnoticed because the suite ran only nightly until #22831
moved it into regular CI.

## What Changed

- Removed the stale `externalChatContinuation` refusal step. #22807's
`agent-chat-response-recovery.test.ts` cases already cover external-chat
recovery (`done` and `needs_review`).
- The test still checks that recovery refuses while the issue comment is
skipped, and that the presentation worker posts the final reply exactly
once.

## Verification

- `paperclip-control-plane-port.test.ts`: 1 failed / 108 before, all
pass after.
- Together with `agent-chat-response-recovery.test.ts`: 181 passed.
- Reproduced the CI failure locally first with `pnpm test:run:general --
--group general-server-without-chat-or-native-runner --shard-index 8
--shard-count 10` (same assertion).

## Risks

- Test-only. No product change.

## Checklist

- [x] I have searched GitHub for duplicate or related PRs and linked
them above (related: #22807, #22831; companion master fix #22852)

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code.

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

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 18:41:25 -06:00
DottaandClaude Opus 5.5 8c04793a4a feat(google): delete content read from Google when access ends (#22836)
Every way a Google connection ends now starts the durable connection content deletion on its own, and Paperclip never resumes a cleaned harness session.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 18:32:11 -06:00
Dotta ba63f4f8b2 perf(test): split chat-channels monolith into 16 suites and shrink PR chat shards 5 -> 2 (#22838)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - `server/src/__tests__/chat-channels.integration.test.ts` had grown
into an 86,498-LOC single-file monolith (~1,815s total CPU across 5
serialized line-sharded PR runners) that forced special-case line
sharding in `scripts/run-vitest-stable.mjs`, prevented `general-chat`
from participating in file-level test selection, and pinned 5 PR CI
shards even for single-provider chat edits.
> - This pull request splits the monolith into 16 provider- and
domain-scoped integration suites plus 4 `<1,000`-LOC shared harness
helpers (`harness.ts`, `providers.ts`, `github-harness.ts`,
`retry-fixtures.ts`), optimizes redundant setup/polling overhead
(`-41.8%` net LOC, `-70.9%` CPU-min: `1,815.3s -> 528.4s` with every
original assertion and matrix case preserved), switches `general-chat`
to file-level duration-balanced LPT sharding (`265.1s / 263.3s` across 2
shards), wires `general-chat` into `test-selection` and `local-verify`,
and shrinks the PR matrix from 5 chat shards to 2 (`general_tests`: `30
-> 27`).
> - Every provider (GitHub, Discord, Slack, Teams, Telegram) and shared
core behavior retains full assertion coverage while ordinary chat edits
now select only affected provider suites instead of all 5 shards.

## Linked Issues or Issue Description

Refs #22804

**What existing behavior does this improve?**
Test execution time, maintainability, and incremental test selection for
`server/src/__tests__/chat-channels/**`,
`scripts/run-vitest-stable.mjs`, and `.github/workflows/pr-trusted.yml`.

**Subsystem affected**
server/ — chat-channels integration tests & CI test runner/matrix

**Current behavior**
`server/src/__tests__/chat-channels.integration.test.ts` is an
86,498-LOC monolith requiring custom source-line sharding across 5 PR CI
jobs (`chat (1/5)`..`chat (5/5)`) and bypassed by file-level test
selection.

**Proposed behavior**
Replace the monolith with 16 focused provider/domain suites + 4 shared
harness modules, use standard file-level duration-balanced LPT sharding
with `scripts/chat-shard-durations.json`, include `general-chat` in
incremental test selection (`select-tests.mjs`,
`test-selection-plan.mjs`, `local-verify/plan.mjs`), and run
`general-chat` on 2 PR shards (`chat (1/2)`, `chat (2/2)`).

## What Changed

- **Split & optimized `chat-channels.integration.test.ts` (`86,498 LOC`
→ 16 provider/domain suites + 4 `<1,000`-LOC harness modules, `-37,314`
net LOC / `-70.9%` CPU-min):**
- Shared harnesses: `harness.ts` (957 LOC), `providers.ts` (857 LOC),
`github-harness.ts` (817 LOC), `retry-fixtures.ts` (905 LOC).
- 16 integration suites covering Board/Core (1), Discord (2), GitHub
(4), Slack (4), Teams (2), and Telegram (3), totaling `528.4s` CPU (down
from `1,815.3s`), preserving all 20 stopped-workspace-cleanup and 28
response-maintenance GitHub matrix cases.
- **File-level LPT sharding & test selection for `general-chat`:**
- Updated `scripts/run-vitest-stable.mjs` (947 LOC),
`scripts/chat-shard-durations.json`,
`scripts/ci/refresh-chat-shard-durations.mjs`,
`scripts/ci/select-tests.mjs`, `scripts/ci/test-selection-manifest.mjs`,
`scripts/ci/test-selection-plan.mjs`, `scripts/local-verify/plan.mjs`,
and `scripts/general-server-shard-durations.json`.
- Updated `maps/agent-access-map/chat-channels.md`,
`maps/feature-map/{chat-channels,connection-setup,recovery}.md`,
`server/scripts/benchmark-response-presentation.mjs` (including
`../../services/native-runtime/...` relative baseline import), and
`server/scripts/test-slack-sync-protocol.mjs`.
- **Shrank PR `general-chat` matrix from 5 shards to 2 (`general_tests`:
`30 -> 27`):**
- Updated `.github/ci-task-matrix.json`,
`.github/workflows/pr-trusted.yml` fallback matrix, and
`.github/scripts/tests/ci-plan.test.mjs` (`30 -> 27`).
  - Kept `release-verify.yml` at 3 chat shards (LPT-balanced).

## Verification

- `node --test .github/scripts/tests/ci-plan.test.mjs
scripts/__tests__/run-vitest-stable-shard.test.mjs
scripts/__tests__/run-vitest-stable-pr-mode.test.mjs
scripts/__tests__/local-verify.test.mjs
scripts/__tests__/release-verify-workflow.test.mjs
scripts/ci/test-selection*.test.mjs` — **197/197 PASS**
- `node scripts/check-maps.mjs` — **PASS** (35 areas, 192 capability IDs
aligned)
- `node scripts/check-test-budget.mjs --base origin/master` — **PASS**
(105 nightly suites validated, 17 test files checked)
- `node server/scripts/typecheck-layers.mjs` — **0 errors** across all 7
layers
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/chat-channels/github-review-workflow.integration.test.ts`
— **89/89 PASS** (`171.27s`)
- Live shard execution (`node scripts/run-vitest-stable.mjs --mode
general --group general-chat --shard-index 0 --shard-count 2`) — **8/8
files, 455/455 tests PASS in 104.0s**

## Risks

- Low risk: all 16 split suites preserve full PostgreSQL-backed
integration assertions across every chat provider, `general-chat` file
sharding gracefully handles arbitrary shard counts (including
`release-verify.yml`'s 3 shards and over-sharded empty shards), and full
CI validates all chat suites live before merge.

## Model Used

- Google Gemini (Antigravity agent swarm) with extended reasoning, tool
use, and local test execution (`ui-prune-2`, `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-24 17:47:05 -06:00
commitperclip[bot] 0733a01c8d fix: Restore icon and appearance when rolling back an agent config revision (#19244)
> [!NOTE]
> Opened by Prospector's automated issue-fix pipeline. A maintainer
reviews and decides; nothing here merges on its own.

## Thinking Path

- Issue #19081 reports a defect in paperclipai/paperclip.
- Root cause, as the fixing agent read it: configPatchFromSnapshot built
the rollback patch without icon or appearance, so a rollback kept the
agent's newer values and recorded that mixed state as the new revision.
- This pull request: Restore icon and appearance when rolling back an
agent config revision

## What Changed

- `server/src/lib/agent-records.ts`: configPatchFromSnapshot now adds
icon (string or null) and appearance (only if
agentAppearanceSchema.safeParse succeeds). It leaves each field out when
the snapshot value is missing or invalid, so older revisions don't clear
the agent's current values.

## Verification

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

## Risks

- Written by an automated pipeline, not a person: review it as you would
an outside contribution.
- Risk tier of the touched paths: 2.

## Model Used

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

## Linked Issues

Fixes #19081

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

## Checklist

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

<!-- prospector:issue-fix v1 issue=19081 base=6452e964a363
report=e4e8f7064467f854 -->

Co-authored-by: commitperclip[bot] <284812584+commitperclip[bot]@users.noreply.github.com>
2026-11-24 15:40:01 -08:00
commitperclip[bot] 5ea18a811a fix: Match originKindPrefix as a literal prefix by escaping LIKE wildcards (#19197)
> [!NOTE]
> Opened by Prospector's automated issue-fix pipeline. A maintainer
reviews and decides; nothing here merges on its own.

## Thinking Path

- Issue #19120 reports a defect in paperclipai/paperclip.
- Root cause, as the fixing agent read it: All three originKindPrefix
predicates in server/src/services/issues.ts (the issue list, the issue
count and blockedInboxIssueConditions) put the raw value into a LIKE
pattern, so '%', '_' and '\' acted as pattern syntax instead of literal
characters. The route casts req.query to string without checking it, so
a repeated query parameter reaches the service as an array, and escaping
has to convert t
- This pull request: Match originKindPrefix as a literal prefix by
escaping LIKE wildcards

## What Changed

- `server/src/services/issues.ts`: Adds originKindPrefixCondition, which
applies escapeLikePattern, and uses it at all three predicates so the
rule is defined once. String(prefix) keeps the existing comma-joined
result for repeated query parameters; without it those requests no
longer return 200, and all three repeated-parameter route tests fail.

## Verification

- Reproducing test(s), added in this PR:
`server/src/__tests__/issues-origin-kind-prefix.test.ts`
- They fail on the base commit and pass with the fix, each twice in a
fresh sandbox.
- The repository's compile command passes with the fix applied.
- 9 existing test file(s) near the change passed.
- The full test suite passes except for the 14 file(s) that already fail
on the base commit.

## Risks

- Written by an automated pipeline, not a person: review it as you would
an outside contribution.
- Risk tier of the touched paths: 2.
- The scope reviewer found it also changes, beyond the report: Missing,
undefined, null, empty-string, false, zero, or NaN prefixes passed at
runtime
- The scope reviewer found it also changes, beyond the report: Ordinary
nonempty prefixes, whitespace, repeated parameters without pattern
characters, and stringifiable malformed values without pattern
characters

## Model Used

- opus (Anthropic Claude, via Claude Code), writing and checking the
change in an isolated sandbox.
- opus (Anthropic Claude, via Claude Code), reviewing it independently.

## Linked Issues

Fixes #19120

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

## Checklist

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

<!-- prospector:issue-fix v1 issue=19120 base=a19416601759
report=771e573dddc44281 -->

---------

Co-authored-by: commitperclip[bot] <284812584+commitperclip[bot]@users.noreply.github.com>
2026-11-24 15:31:45 -08:00
Dotta 4553c2396b refactor(test): prune 483 redundant nightly soak test suites (keep 105 canonical) (#22831)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Over recent sprints, `scripts/ci/nightly-only-suites.json`
accumulated 588 real-clock soak, recovery, lease, and maintenance test
files totaling ~326k LOC and ~307 CPU-minutes on `master`,
`release-verify`, and `full-ci` runs.
> - Most of those files are overlapping single-PR regression soaks whose
failure modes are already covered by canonical suites, driving up
maintenance cost, typecheck load, and post-merge verification runtime
without adding distinct coverage.
> - Following `.agents/skills/test-audit/SKILL.md`, this pull request
prunes 483 redundant/overlapping soak files (`-158,485` net LOC, ~180
CPU-min saved) while retaining 105 canonical, high-signal nightly suites
covering every distinct failure mode and 100% of suites referenced by CI
workflows, benchmarks, Slack eval manifests, lifecycle inventories, or
tsconfigs.
> - All timing manifests and feature/agent-access maps are updated
cleanly to remove stale references.
> - The benefit is a ~59% reduction in nightly soak CPU time and ~158.5k
fewer lines of duplicate test code to compile, typecheck, and maintain
while preserving full invariant and canonical soak coverage.

## Linked Issues or Issue Description

Refs #22804

**What existing behavior does this improve?**
Test suite maintainability, typecheck scope, and
nightly/post-merge/full-CI runtime across
`scripts/ci/nightly-only-suites.json` and `server/src/`.

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

**Current behavior**
`scripts/ci/nightly-only-suites.json` contains 588 standalone soak test
files (~307 CPU-min total), with hundreds of overlapping one-PR
recovery, lease, and idle-maintenance soak suites duplicating canonical
coverage.

**Proposed behavior**
Retain 105 canonical high-signal nightly suites covering every distinct
failure mode and every hard-referenced suite, delete 483 redundant soak
files, and keep `nightly-only-suites.json`,
`general-server-shard-durations.json`, and `maps/` 100% synchronized.

## What Changed

- **Pruned 483 redundant nightly soak files (`-158,916 / +431` LOC =
`-158,485` net LOC, ~59% of nightly soak CPU):**
- Retained **105 canonical high-signal nightly suites** covering every
distinct failure mode and 100% of hard-referenced suites
(`scripts/run-vitest-stable.mjs`, `runner-chaos-evals.yml`,
`ci-work-benchmark.yml`, `tests/lifecycle-baseline/inventory.mjs`,
`stress-workflow-traceability.json`,
`packages/plugins/examples/slack/evals/cases.json`, and
`tsconfig*.json`), including the 6 focused suites restored after review
(`idle-database-backup-sync`, `isolated-remote-workspace-source-lock`,
`agent-chat-response-recovery`, `chat-slack-receipts`,
`heartbeat-slack-invitation`, `ephemeral-migration-service`).
- **Updated manifests and maps:**
- `scripts/ci/nightly-only-suites.json`: 588 → 105 suites (0 missing, 0
duplicates, 0 protected invariants demoted).
- `scripts/general-server-shard-durations.json`: 2,138 → 1,655 entries
(`coverage: { measured: 1573, withSetup: 1573, inventory: 1655 }`,
pruned all 483 deleted paths).
- Updated all affected `maps/{agent-access-map,feature-map}/*.md` files
with zero dangling references.

## Verification

- `node scripts/check-test-budget.mjs --base origin/master` — **PASS**
(105 nightly suites validated, 0 invariant violations)
- `node scripts/check-maps.mjs` — **PASS** (35 areas, 192 capability IDs
aligned)
- `node packages/plugins/examples/slack/evals/run-regressions.mjs
--list` — **PASS**
- `node --test scripts/__tests__/run-vitest-stable-shard.test.mjs
scripts/__tests__/run-vitest-stable-pr-mode.test.mjs
scripts/check-test-budget.test.mjs
scripts/ci/test-selection-pr-timings.test.mjs
scripts/ci/test-selection-timings.test.mjs
tests/lifecycle-baseline/report.test.mjs
.github/scripts/tests/ci-plan.test.mjs` — **102/102 PASS**
- Repo-wide scan confirmed 0 test-to-test imports and 0 dangling
references in `scripts/`, `.github/`, `maps/`, `tsconfig*.json`,
`packages/plugins/examples/slack/evals/cases.json`, or
`tests/lifecycle-baseline/inventory.mjs`.

## Risks

- Low risk: every deleted file was already nightly-only (not running on
ordinary PRs) and every distinct failure mode plus every core
control-plane invariant remains covered by PR suites and the 105
retained canonical nightly suites.

## Model Used

- Google Gemini (Antigravity agent swarm) with extended reasoning, tool
use, and local test execution (`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
- [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-24 17:30:47 -06:00
DottaandClaude Opus 5.5 fb900bf0fe fix(runner): re-qualify a stale sandbox snapshot proof instead of blocking runs (#22835)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Paperclip Runner on a Daytona sandbox pins the snapshot that a saved
qualification proof measured.
> - The proof goes stale when the snapshot, the config or a captured
image changes. It also goes stale when a qualification probe stops
before it finishes.
> - Lease admission then failed every run with
`sandbox_snapshot_qualification_required`. Only a person who selected
Run test could clear it.
> - Recovery must work without a person. A config change or a deploy
must not leave runs that need a click.
> - This pull request makes lease admission run the same qualification
probe by itself, then pin the newly qualified snapshot.
> - The benefit is that runs continue after an image change. A run still
never starts on an unpinned snapshot name.

## Linked Issues or Issue Description

**What happened?**
On a hosted staging instance, every Paperclip Runner run on the managed
"Paperclip Sandbox" environment failed at setup for about 40 minutes.
The error was `sandbox_snapshot_qualification_required: The snapshot
qualification is missing or stale. Open the agent's Harness / Runtime
page and select Run test`. Three agents were blocked. The run was not
retried. The failures stopped only after a person selected Run test.

**Expected behavior**
A stale saved proof is re-checked automatically. The run continues on
the qualified snapshot. No person needs to select Run test.

**Steps to reproduce**
1. Use a Daytona snapshot environment that has a saved v2 snapshot
proof.
2. Change the snapshot, or interrupt a qualification probe, so that the
proof is stale or invalidated.
3. Make sure the managed-image bypass does not apply. For example, a
managed row whose provider is not in the live managed config
`environments` section.
4. Start a Paperclip Runner run. Before this fix, admission throws
`sandbox_snapshot_qualification_required` and does not try again.

Root cause: The managed row's saved proof was from 2026-10-28, when a
person last selected Run test. The fleet snapshot changed several times
after that, so the proof was stale. That had no effect while
`usesManagedCloudSandboxImage` returned true. When that check returned
false, the stale proof became a hard stop. The check needs the live
managed config to list the provider, with no active captured image. The
existing `unowned-marker` test shows that this stops the run. I could
not read the server environment to confirm which input changed at that
time. This fix therefore covers the whole class: a stale proof is
re-qualified, whatever made it stale.

Refs #18066, Refs #17445

## What Changed

- `acquireRunLease` no longer fails when a saved snapshot proof is stale
or invalidated. It runs the same probe as the agent's Run test
(`probeEnvironment` with `acquireSandboxRuntimeLease`). It then reads
the recorded proof again and pins the qualified snapshot ID.
- Only one re-qualification runs for each environment and company at a
time in a server process. The in-flight probes are shared by all runtime
instances. Admission reads the saved proof again before it probes, so a
run that comes after a successful re-check does not probe again.
- A failed re-check answers later runs for the same saved config for two
minutes. A queue of runs behind a broken snapshot starts one probe
sandbox, not one for each run. A config change starts a new probe at
once.
- If the re-check cannot prove the snapshot, the run still fails before
it gets a run lease. The run error uses only controlled text. Raw
provider error text, which can contain credentials, stays out of the run
error. The message does not tell a person to fix the sandbox.
- Tests: a new regression test reproduces the staging case. It also
starts a second run through a different runtime while the probe is held
open, and checks that only one probe lease starts. A second new test
checks that a provider error with a token does not reach the run error,
and that two runs one after the other start only one probe after a
failure. The `unowned-marker` and `changed-base`/`changed-runtime` cases
now check that the only provider lease is the qualification probe
(`resolveSnapshotIdentity: true`). No run lease uses an unpinned name.

## Verification

- Red/green: the new test `re-qualifies a stale snapshot proof by itself
instead of blocking the run until someone selects Run test` fails on
master with the exact staging error. It passes with this fix.
- `npx vitest run src/__tests__/environment-runtime.test.ts
src/__tests__/environment-probe.test.ts
src/__tests__/agent-runner-qualification-routes.test.ts
src/services/agent-runner-selection.test.ts`: 505 passed on the first
commit. `environment-runtime.test.ts`: 217 passed on the final head, two
runs in a row.
- The single-probe and failure-reuse tests fail when the shared map or
the failure reuse is removed.
- `tsc --noEmit -p server/tsconfig.json` passes.
- After deploy, I will check staging: Paperclip Runner runs on the
managed sandbox reach a lease without anyone selecting Run test.

## Risks

- When a proof is stale, the first run after the change waits for one
extra probe sandbox (boot, `uname`, release) before its own lease. This
happens once for each environment and company until the snapshot changes
again. Runs with a valid proof, and runs on the managed-image bypass, do
not change.
- A probe that fails still stops the run with
`sandbox_snapshot_qualification_required`. The pinning guarantee does
not change.
- For two minutes after a failed re-check, runs for that environment
fail without a new probe. After that, the next run checks again.
- Server replicas do not share in-flight probes. Each replica can start
at most one probe, and the first success records the proof for all of
them.

## Model Used

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

## 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 17:19:32 -06:00
Dotta d02774f404 perf(ci): gate PR Canary Dry Run strictly to release-packaging scripts or full-ci (#22830)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Pull request CI runs `Canary Dry Run` (`//#ci:canary`) to validate
npm release staging and packaging before merge.
> - Even on 8-core Spot runners, `Canary Dry Run` takes 5.5–7.7 minutes
and still triggers on any PR that edits `package.json`,
`pnpm-lock.yaml`, `README.md`, `turbo.json`, `scripts/**`, or
`.github/**` because `ci-plan.mjs` forces every task on any
`globalDependencies` change.
> - Post-merge `release.yml` and `release-verify.yml` already verify
canary packaging on every `master` push, so running a 6-minute canary
dry run on ordinary app, docs, or dependency PRs makes it the single
slowest lane on PRs.
> - This pull request narrows `//#ci:canary` inputs in `turbo.json` to
release-packaging scripts and updates `.github/scripts/ci-plan.mjs` so
`ci:canary` runs on PRs only when those release-packaging files change,
when explicit full CI is requested (`full-ci` label /
`CI_INCREMENTAL_MODE=full`), or when the diff is missing, invalid, or
unclassified.
> - The benefit is removing 5.5–7.7 minutes of unnecessary canary
packaging from ordinary PRs while keeping full release verification for
packaging edits, `full-ci` runs, and post-merge releases.

## Linked Issues or Issue Description

Refs #22804

**What existing behavior does this improve?**
Pull request CI task selection for `Canary Dry Run` (`canary_dry_run` /
`//#ci:canary`) in `turbo.json` and `.github/scripts/ci-plan.mjs`.

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

**Current behavior**
Any PR touching `package.json`, `packages/*/package.json`,
`pnpm-lock.yaml`, `README.md`, `turbo.json`, `scripts/**`, or
`.github/**` triggers `Canary Dry Run` (5.5–7.7 minutes) even when no
release-packaging scripts changed.

**Proposed behavior**
Run `canary_dry_run` on PRs only when release-packaging scripts
(`scripts/release*`, `scripts/build-npm.sh`,
`scripts/stage-bundled-packages.mjs`,
`scripts/pack-staged-packages.mjs`) change, when explicit full CI is
requested (`full-ci` label / `profile-ci` / `CI_INCREMENTAL_MODE=full`),
or when the diff is missing, invalid, or unclassified.

## What Changed

- **`turbo.json`:** Narrowed `//#ci:canary` inputs strictly to
`scripts/release*`, `scripts/build-npm.sh`,
`scripts/stage-bundled-packages.mjs`, and
`scripts/pack-staged-packages.mjs`.
- **`.github/scripts/ci-plan.mjs`:** Kept `ci:canary` gated on its
explicit release-packaging inputs when only `globalDependencies`
changed, while still failing closed on explicit `full-ci` /
`CI_INCREMENTAL_MODE=full` / missing / invalid / unclassified diffs. All
other CI lanes continue to force full execution on `globalDependencies`
changes.
- **`.github/scripts/tests/ci-plan.test.mjs`:** Updated and added unit
tests covering release-packaging owners, skipped ordinary/global inputs
(`package.json`, `packages/shared/**`, `pnpm-lock.yaml`, `README.md`,
non-release scripts), and forced `full-ci` / `mode=full` / uncertain
diffs.

## Verification

- `node --test .github/scripts/tests/*.test.mjs
scripts/__tests__/merge-queue-checks-workflow.test.mjs
scripts/__tests__/runner-release-crate-cache.test.mjs
scripts/__tests__/e2e-shard.test.mjs
scripts/ci/test-selection-workflow.test.mjs` — **849/849 PASS**
- Confirmed zero changes to `.github/workflows/pr-trusted.yml`,
`.github/workflows/ci-routing.yml`, `.github/workflows/pr.yml`,
`CODEOWNERS`, or `.github/workflows/merge-queue-checks.yml`; `verify`
aggregate remains 100% synchronized with `plan.jobs.canary_dry_run.run`.

## Risks

- Low risk: ordinary PRs still run `Build` (including `pnpm --filter
@paperclipai/server build:runtime`), `Typecheck + Release Registry`, and
all affected server/UI/Runner/E2E suites; release-packaging edits and
`full-ci` PRs still run `Canary Dry Run`; post-merge `release.yml` and
`release-verify.yml` continue to test canary packaging on `master`.

## Model Used

- Google Gemini (Antigravity agent swarm) with extended reasoning, tool
use, and local test execution (`ci-pipeline`, `verifier`).

## 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-24 17:07:41 -06:00
Dotta 1a57a2abec refactor(ui): prune 36 thin mocked jsdom UI tests and consolidate replay masking checks (#22834)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The `@paperclipai/ui` Vitest suite includes 182 component/page test
files, many of which boot full jsdom and React module graphs with 6–19
mocks solely to verify wiring that Playwright E2E specs already exercise
end-to-end.
> - Auth, security, permission, privacy, error-boundary, pure-logic
`ui/src/lib` / `ui/src/hooks` / `ui/src/api` suites, and complex
interactive client logic must stay intact.
> - This pull request removes 36 thin
mocked/E2E-duplicated/synthetic-perf jsdom component/page test files
(-17,367 LOC), consolidates 7 tiny single-purpose session-replay privacy
tests into `ui/src/lib/analytics/replay-masking.test.tsx` with 100% of
assertions preserved, converts 2 pure-logic suites from `jsdom` to
`node`, and updates affected feature/agent-access map references plus
`.github/workflows/ci-incremental-qualification.yml`.
> - The benefit is cutting full `@paperclipai/ui` suite execution to
~36s locally (~42s fewer raw test seconds and 42 fewer jsdom boots)
while preserving 100% of auth, permission, privacy, and pure-logic
coverage.

## Linked Issues or Issue Description

Refs #22804

**What existing behavior does this improve?**
UI Vitest runtime, signal-to-noise ratio, and jsdom boot overhead in
`ui/src/`.

**Subsystem affected**
ui/ — React + Vite board UI

**Current behavior**
36 thin mocked/E2E-duplicated/synthetic-perf jsdom component/page tests
and 7 tiny single-purpose session-replay privacy files pay full
jsdom+React boot overhead on every UI PR despite duplicate Playwright
E2E and pure-logic coverage.

**Proposed behavior**
Remove the 36 thin mocked/E2E-duplicated jsdom suites, consolidate the 7
session-replay privacy suites into
`ui/src/lib/analytics/replay-masking.test.tsx`, convert 2 pure-logic
suites to `node`, and keep all maps and incremental qualification checks
aligned.

## What Changed

- **Deleted 36 thin mocked / E2E-duplicated / synthetic-perf jsdom
suites (`-17,367 LOC`):**
- Mocked chat-adapter setup & banner wiring (4 files), heavily mocked
`Inbox.test.tsx` shell (1 file, 19 mocks; pure logic in
`ui/src/lib/inbox.test.ts` and browser E2E retained), synthetic jsdom
microbenchmarks & mocked app/browse/connector wiring (9 files), mocked
AI-connection & agent-config wiring (6 files), and thin
presentational/mocked component wiring (16 files).
- **Consolidated 7 tiny session-replay privacy tests into
`ui/src/lib/analytics/replay-masking.test.tsx` (498 LOC, 100% of
assertions preserved):** `AccountQuotaPanels`, `WebhookFields`,
`AiConnectionPicker`, `AiConnectionAccountControls`,
`AiConnectionIdentity`, `AiConnectionPoolRunDetails`, and
`AgentSetupPrompt`.
- **Converted 2 pure-logic suites from `jsdom` to `node` (0 assertions
lost):** `ui/src/pages/Secrets.test.ts` and
`ui/src/pages/tools/ProfilesTab.test.ts`.
- **Retained 100% of high-signal UI coverage:** all 276 `ui/src/lib`, 56
`ui/src/hooks`, 19 `ui/src/context`, 26 `ui/src/api`, 14
`ui/src/adapters`, 6 `ui/src/plugins`, all 94 pure-logic `node`
component/page tests, and all
auth/security/permission/privacy/error-boundary/complex-interactive
suites.
- **Updated references:** updated the 7 affected `maps/` files to
reference current canonical suites and updated
`.github/workflows/ci-incremental-qualification.yml`
(`ui/src/pages/Inbox.tsx → Inbox.test.tsx` to `ui/src/pages/Auth.tsx →
Auth.test.tsx`).

## Verification

- `pnpm exec vitest run --project @paperclipai/ui` — **557/557 files,
6,916 passed | 1 skipped (`36.14s`)**
- `pnpm --filter @paperclipai/ui typecheck` — **PASS (0 errors)**
- `node scripts/storybook-catalog.mjs` — **PASS (371 files, 3,480
stories)**
- `node scripts/check-maps.mjs` — **PASS (35 areas, 192 capability
IDs)**
- `node scripts/check-query-error-rendering.mjs` — **PASS (0 findings)**
- `node scripts/check-test-budget.mjs --base origin/master` — **PASS
(588 nightly suites validated)**
- Verified `.github/workflows/ci-incremental-qualification.yml`
`qualify_test_selection` check locally (`Auth.tsx → Auth.test.tsx`) —
**PASS**

## Risks

- Low risk: zero production UI code changed; all auth, permission,
privacy, replay-masking, error-boundary, pure-logic, and Playwright E2E
behavioral checks remain intact.

## Model Used

- Google Gemini (Antigravity agent swarm) with extended reasoning, tool
use, and local test execution (`e2e-opt`, `verifier`, `ci-pipeline`).

## Checklist

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

> - Paperclip is the open source app people use to manage AI agents for
work
> - Operators control what agents spend with budgets, and the public
docs explain how budgets work
> - Pull request #22784 updated the budget docs to match the code on
`master`
> - The review of #22784 found three claims that were stated too broadly
> - #22784 merged before the corrections reached its branch, so `master`
still has the three claims
> - An operator who reads them can expect the wrong behavior from a
budget
> - This pull request applies the three corrections. It changes docs
only
> - The benefit is that the budget docs on `master` match the review and
the code

## Linked Issues or Issue Description

Refs #22784
Refs #8856

**Issue type**

Incorrect content.

**Where is the issue?**

- `docs/guides/board-operator/costs-and-budgets.md`
- `docs/api/costs.md`
- `docs/guides/board-operator/creating-a-company.md`
- `docs/guides/board-operator/managing-agents.md`
- `docs/start/core-concepts.md`
- `docs/guides/agent-developer/cost-reporting.md`

**What's wrong?**

Three claims from #22784 are too broad:

1. The docs say that a budget does not stop an agent that runs on a
subscription. Subscription usage adds no billed spend, but a hard stop
in the agent's scope still refuses its runs, and the reserve per run
applies to every run.
2. One guide says that both thresholds are settings. Only the warning
percentage is a setting. The hard stop is on or off and always uses 100%
of the budget.
3. The docs say that the unpriced-usage setting blocks all usage with no
price. It does not cover every entry under "run costs unavailable".

**Suggested fix**

Apply the corrections from the review threads of #22784.

## What Changed

- Subscription claim: the docs now say that subscription usage adds $0
and never moves a budget toward its limit. They also say that a hard
stop on a shared budget and the reserve per run still apply to
subscription agents. Corrected in the main guide, the API page, and four
related guides.
- Thresholds: `creating-a-company.md` now says that you can change the
warning percentage and turn the hard stop on or off, and that the hard
stop always uses 100% of the budget.
- Unpriced usage: the guide now says that the setting covers usage from
a complete receipt that has no price. It lists the entries that do not
trigger `block`.

## Verification

I read the code on `origin/master`. I did not run the product.

- A hard stop refuses work in its scope without reading the billing
type: `server/src/services/budgets.ts:825`
- The reserve check does not read the billing type:
`server/src/services/budget-reservations.ts:160`
- The hard stop compares spend with the full amount:
`server/src/services/budgets.ts:258`
- The exclusions from the unpriced-usage block:
`server/src/services/budget-exposure.ts:144`
- I checked every internal link and anchor in the changed files with a
script. All resolve.
- `git diff --check` reports no whitespace errors.

## Risks

Low risk. The change is docs only. It is the same commit that the review
threads of #22784 refer to, applied on top of `master`.

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

## Model Used

- Claude Fable 5.2 (Anthropic), model ID `claude-fable-5-2`, in Claude
Code. Extended thinking and tool use (file read, search, shell, `gh`).
The model read the code, wrote the docs, and wrote this description.

## Checklist

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

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

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-24 14:45:34 -08:00
Dotta de4b60fc54 refactor(test): prune 28 completed migration, prose-grep, and Storybook fixture tests (#22832)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Over recent sprints, the test suite accumulated completed one-time
SQL migration backfill tests, brittle static prose-matching guidance
tests, and non-production Storybook fixture/prototype/feasibility-probe
tests that add compile and CI maintenance cost without testing live
behavioral invariants.
> - Core database migration guards, active runtime migration services,
security/safety static guards, and active adapter suites must stay
intact.
> - This pull request deletes 28 audited low-value test files (-1,894
LOC), preserves the one genuine schema validation assertion from
`chat-communication-guidance.test.ts` inside
`packages/shared/src/validators/chat-channels.test.ts`, prunes the 5
deleted server test keys from
`scripts/general-server-shard-durations.json`, and refreshes
`tests/runner-e2e/source-sdk-public-inputs.json`.
> - The benefit is cleaner, higher-signal test coverage with zero lost
invariants and synchronized SDK public source pins.

## Linked Issues or Issue Description

Refs #22804

**What existing behavior does this improve?**
Test suite signal-to-noise ratio and maintenance overhead across
`packages/db`, `packages/shared`, `packages/skills-catalog`, `server`,
`ui/storybook`, `scripts`, and `tests/speko-voice-proof`.

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

**Current behavior**
28 test files test already-shipped one-time migrations/dead backfills,
static markdown/copy wording, non-production Storybook
fixtures/prototypes, or a superseded voice feasibility probe.

**Proposed behavior**
Remove the 28 low-value test files while preserving all core migration
integrity suites, active runtime migration services, security static
guards, live adapter suites, and the genuine `updateChatEndpointSchema`
assertion.

## What Changed

- **Completed one-time migrations & dead backfills (3 files deleted, 444
LOC):**
- Deleted
`packages/db/src/better-auth-account-issuer-migration.test.ts`,
`packages/db/src/chat-telegram-draft-ids-migration.test.ts`, and
`server/src/__tests__/tool-oauth-legacy-backfill.test.ts` (zero
production callers outside barrel re-export).
- Retained all core DB migration guards (`check-migration-safety`,
`migration-compatibility`, `migration-snapshot-drift`,
`check-pr-migration-order`) and active runtime migration/legacy-recovery
services.
- **Brittle static prose/wording grep tests (9 files deleted, 317
LOC):**
- Deleted `packages/shared/src/connection-intent-guidance.test.ts`,
`packages/shared/src/telemetry/readme-contract.test.ts`,
`packages/skills-catalog/src/release-content-cases-contract.test.ts`,
`server/src/__tests__/secret-entry-guidance.test.ts`,
`server/src/__tests__/primary-agent-guidance.test.ts`,
`server/src/services/chat-communication-guidance.test.ts`,
`server/src/services/onboarding-greeting.test.ts`,
`ui/src/lib/agent-onboarding-prompt.test.ts`, and
`ui/src/lib/grok-bot-setup-prompt.test.ts`.
- Moved the one genuine schema validation assertion
(`updateChatEndpointSchema` `communicationInstructions`) into
`packages/shared/src/validators/chat-channels.test.ts`.
- Retained `cli-invocation-safety.test.ts` and all real
security/auth/prompt-injection guards.
- **Non-production Storybook fixture / prototype / feasibility-probe
tests (16 files deleted, 1,182 LOC):**
- Deleted 10 Storybook fixture/prototype/mock-API tests, 2 unreferenced
Storybook audit script tests, and 4 superseded
`tests/speko-voice-proof/*.test.mjs` feasibility probe tests.
- **Manifest & SDK pin hygiene:**
- Pruned the 5 deleted server test keys and reconciled coverage counts
in `scripts/general-server-shard-durations.json`.
- Synced `tests/runner-e2e/source-sdk-public-inputs.json` via `node
tests/runner-e2e/source-sdk-public-inputs.mjs <HEAD> --write` (0 files
deleted under `tests/runner-e2e/`).

## Verification

- `node scripts/check-maps.mjs` — **PASS** (35 areas, 192 capabilities
aligned)
- `node scripts/check-test-budget.mjs --base origin/master` — **PASS**
(588 nightly suites validated)
- `pnpm exec vitest run` on retained suites (`chat-channels`,
`telemetry`, `skills-catalog`, `check-migration-safety`,
`migration-compatibility`, `migration-snapshot-drift`, `runner-api`) —
**15/15 files, 2,532/2,532 PASS**
- `node tests/runner-e2e/source-sdk-public-inputs.mjs $(git rev-parse
HEAD) --check` and `vitest run --config
tests/runner-e2e/vitest.config.ts
tests/runner-e2e/source-sdk-public-inputs.test.mjs` — **PASS (13/13)**
- `node --test scripts/typecheck-test-programs.test.mjs
scripts/__tests__/ci-typecheck-lane.test.mjs
scripts/__tests__/run-vitest-stable-shard.test.mjs
scripts/storybook-catalog.test.mjs` — **103/103 PASS**
- Typecheck (`@paperclipai/shared`, `@paperclipai/db` incl.
`check:migrations`, `@paperclipai/skills-catalog`, `node
scripts/ci-typecheck-lane.mjs --typecheck-ui`) — **PASS (0 errors)**

## Risks

- Low risk: zero production code changed, zero core DB migration or
auth/security guards removed, and zero dangling references across
`maps/`, `scripts/`, `.github/`, or `tsconfig*.json`.

## Model Used

- Google Gemini (Antigravity agent swarm) with extended reasoning, tool
use, and local test execution (`typecheck-opt`, `verifier`,
`ci-pipeline`).

## Checklist

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

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Product journeys observe native tasks until their useful result is
complete.
> - A native session can time out while the server schedules an
exact-session retry.
> - The run status is temporarily failed while its retry remains
scheduled.
> - The observer currently grades that temporary state as a final
failure.
> - This pull request keeps observing a bound scheduled retry within the
original deadline.
> - The benefit is a grade based on the completed task, with terminal
failures and work limits preserved.

## Linked Issues or Issue Description

**What happened?**
A build-and-revise task prepared its ZIP, then hit a five-minute native
session timeout. The API reported agent-owned exact-session recovery on
the same run with one of three attempts used and a retry scheduled
before the campaign deadline. The journey raised `agent_run_failed`
before that retry could occur.

**Expected behavior**
Observe a proven scheduled retry on the same run within the original
deadline. Require a later successful run and the existing independent
artifact checks. A pending retry cannot pass the journey.

**Steps to reproduce**
Run the new agent-recovery regression against the previous observer. A
realistic failed native run with a scheduled retry fails immediately.
The corrected observer sees the same run succeed and still fails
terminal, exhausted, foreign and late recovery states.

**Paperclip version or commit**
Reproduced from 28aa32e7d7. Affected
source files were unchanged on current master before publication. The
documentation incorporates current master changes.

**Deployment mode**
Credential-free task-observer calibration on Linux. The observed hosted
failure supplied the original diagnosis. No full-stack staging recovery
pass is claimed.

## What Changed

- Pass the original campaign deadline to agent task validation.
- Reuse the existing native recovery predicate after company, task,
agent, environment and model checks.
- Accept older API projections that omit a successor when no successor
exists. Continue to reject an actual successor.
- Require succeeded or explicitly checked cancelled runs for settlement.
Never settle a failed recovery snapshot.
- Add controlled success, deadline and negative recovery tests. Preserve
the original budgets and run limits.

## Verification

- Red: three new recovery checks failed against the previous observer:
premature terminal grading, premature settlement and the wrong deadline
failure.
- Green: 194 tests pass across agent-recovery, agent-evidence and
onboarding-first-task.
- Local test-project typecheck could not complete: the host killed the
compiler with SIGKILL. `pnpm verify --explain` could not select checks
because the managed Git storage guard rejects `git ls-files`. Neither
attempt is a pass.
- Review follow-up at `b2957a3112df1cbcce80bba441cc0415bed1f86c`: the
shared task read now waits for pending recovery before it reaches any
consumer. This covers Plan revision, Plan approval, protected-action
decisions, replies and artifact reads. Four journey regression checks
fail before this gate and pass after it. All 202 focused recovery,
agent-evidence, onboarding and Plan checks pass. Fresh CI and review on
this head are pending. No new paid test, protected pin update or staging
deployment was made.

## Risks

- Waiting requires an explicit native retry projection, a matching
cause, agent ownership, remaining attempts and a retry time inside the
existing deadline. Other failures still stop immediately.
- Older projections omit the optional successor field. The compatibility
change accepts only null or absent values.
- No provider timeout or runtime recovery policy changes. A full
authorized staging run must still prove acceptance.

## Model Used

OpenAI GPT-6 through Codex, with reasoning, source editing, shell tools
and Chromium. The runtime does not expose a more specific model
revision.

## 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>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 16:34:32 -06:00
Michael NguyenandClaude Fable 5.2 455462812a docs: describe budgets as they work today (#22784)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Operators control what agents spend with budgets, and the public
docs explain how budgets work
> - The budget docs were last changed in March 2026. The budget system
was rebuilt after that
> - The docs still describe a fixed 80% alert and a 100% auto-pause on
company and agent budgets only
> - The docs do not say that budgets count billed dollars only.
Subscription usage is recorded at zero cents, so a budget never stops an
agent that runs on a subscription
> - An operator who reads the docs today can believe that a budget
protects a subscription. It does not
> - This pull request updates the cost and budget docs to match the code
on `master`. It changes docs only
> - The benefit is that operators and agent developers get a correct
description of what a budget does and does not do

## Linked Issues or Issue Description

Refs #8856

Related open pull requests. None of them changes these docs: #22745,
#13379, #11511, #17356.

**Issue type**

Outdated content.

**Where is the issue?**

- `docs/guides/board-operator/costs-and-budgets.md`
- `docs/api/costs.md`
- The budget lines in `docs/guides/board-operator/managing-agents.md`,
`docs/guides/board-operator/dashboard.md`,
`docs/guides/board-operator/creating-a-company.md`,
`docs/start/core-concepts.md`, and
`docs/guides/agent-developer/cost-reporting.md`

**What's wrong?**

The docs describe the budget system as it was in March 2026. Seven
points are wrong or missing. Each point is listed under Verification
with the code that supports the new text.

**Suggested fix**

Update the docs to describe the behavior of the code on `master`. Do not
change product code.

## What Changed

- `costs-and-budgets.md`: added a warning at the top. A budget counts
billed dollars only, and it does not stop an agent that runs on a
subscription.
- `costs-and-budgets.md`: added the three budget scopes (company, agent,
project) and their windows.
- `costs-and-budgets.md`: added the budget settings and their defaults
(`warnPercent`, `notifyEnabled`, `hardStopEnabled`, `reservationCents`,
`unpricedUsagePolicy`).
- `costs-and-budgets.md`: rewrote the enforcement section. It now
describes the warning, the hard stop, the budget incident, the two ways
to resolve it, and the monthly reset.
- `costs-and-budgets.md`: added where to set a budget in the UI and with
the API. It says that the older `budgetMonthlyCents` fields still work.
- `costs-and-budgets.md`: added sections for the reserve per run, usage
with no reliable price, the Subscriptions card, and provider quota
windows.
- `docs/api/costs.md`: added the budget overview, budget policy, and
incident routes, the report period parameters, and the subscription and
quota routes. Added the required `occurredAt` field to the cost event
example.
- The five related guides: corrected the lines that repeated the old
claims. Each one now links to the main guide.

## Verification

I read the code on `origin/master` at commit `0731cd3afc`. I did not run
the product. Each point below has the file and line that supports the
new text.

1. **Budgets exist for a company, an agent, and a project. A project
budget uses a lifetime window.** Corrected.
   - Scopes: `packages/shared/src/constants.ts:1050`
- The service uses `lifetime` for a project when no window is given:
`server/src/services/budgets.ts:862`
- The project page sends `lifetime`:
`ui/src/pages/ProjectDetail.tsx:658`
- The request validator fills in `calendar_month_utc` when the field is
absent: `packages/shared/src/validators/budget.ts:14`. The docs
therefore tell API callers to send `"windowKind": "lifetime"` for a
project.
2. **Budgets count dollars only. Subscription usage is recorded at zero
cents.** Corrected, and stated at the top of the guide.
- The only metric is `billed_cents`:
`packages/shared/src/constants.ts:1053`
- `subscription_included` is billed at 0:
`server/src/services/heartbeat/run-state.ts:522`
- Budget exposure counts it as 0:
`server/src/services/budget-exposure.ts:33`
- Claude Code and Codex report subscription billing when no API key is
set: `packages/adapters/claude-local/src/server/execute.ts:176`,
`packages/adapters/codex-local/src/server/execute.ts:204`
3. **The warning threshold and the hard stop are settings.** Corrected.
- Defaults `warnPercent` 80 and `hardStopEnabled` true:
`server/src/services/budgets.ts:912`
- `warnPercent` accepts 1 to 99:
`packages/shared/src/validators/budget.ts:17`
- The UI shows `warnPercent` but has no control to change it:
`ui/src/components/BudgetPolicyCard.tsx:108`
4. **At the hard stop, new work is refused, running work is told to
stop, and an incident opens.** Corrected.
- Incident, pause, and cancellation:
`server/src/services/budgets.ts:770`
   - New work is refused: `server/src/services/budgets.ts:825`
- Raise the budget or keep the scope paused:
`server/src/services/budgets.ts:1045`
- **A new month does resume a paused scope.** The budget worker
reconciles held monthly scopes at the end of the UTC month:
`server/src/services/budgets.ts:1329` and
`server/src/services/budget-enforcement-worker.ts:44`. With no spend in
the new window, the service closes the incident and removes the budget
pause: `server/src/services/budgets.ts:716`. This also applies after
"Keep paused". A manual pause stays. A lifetime budget does not reset.
5. **The "focus on critical tasks" text at 80% is skill guidance.**
Corrected.
   - The text is in the skill: `skills/paperclip/SKILL.md:681`
- At the soft threshold the server opens an incident and writes an
activity entry. It sends nothing to the agent:
`server/src/services/budgets.ts:750`
6. **Where to set a budget.** Corrected.
- Routes: `server/src/routes/costs.ts:347` (overview), `:355`
(policies), `:367` (resolve incident), `:399` (company), `:418` (agent)
- UI: `ui/src/pages/audit/audit-navigation.ts:11`,
`ui/src/pages/Costs.tsx:745`, `ui/src/pages/ProjectDetail.tsx:876`,
`ui/src/pages/AgentDetail.production.tsx:186`
- **The old fields still work.** `PATCH /companies/:id` with
`budgetMonthlyCents`: `server/src/services/companies.ts:430`. `PATCH
/agents/:id` with `budgetMonthlyCents`:
`server/src/services/agent-configuration.ts:196`. On an agent the change
needs a board user: `server/src/routes/agents.ts:5637`.
7. **Reserve per run, unpriced-usage policy, Subscriptions, and quota
windows.** Added.
- Reserve per run: `ui/src/components/BudgetPolicyCard.tsx:61`,
`server/src/services/budget-reservations.ts:160`
   - Unpriced-usage policy: `server/src/services/budgets.ts:244`
- Subscriptions: `server/src/routes/costs.ts:114`,
`ui/src/components/SubscriptionCostCard.tsx:113`
- Quota windows: `server/src/routes/costs.ts:332`,
`packages/shared/src/types/quota.ts:2`

Could not confirm:

- I took the UI paths from the code and from
`maps/feature-map/budgets-costs.md`. I did not check them on a running
instance.
- I found no UI control that creates the first company budget. The
Budgets page edits a company budget that exists. The docs say to create
it with the API. A maintainer who knows the UI should confirm this
sentence.
- I did not find an adapter that reports `subscription_overage`. The
docs say only that such usage counts for its reported cost.

Checks:

- `pnpm verify` exits with code 2. It reports a global CI input change
(`docs/api/costs.md`), so required CI supplies the broad coverage. I did
not run the full local suite.
- I checked every internal link and anchor in the seven changed files
with a script. All resolve.
- `git diff --check` reports no whitespace errors.
- No test reads the changed files.

## Risks

Low risk. The change is docs only.

- A wrong sentence in these docs can mislead an operator about spend.
The two sentences that most need a maintainer's review are the monthly
resume (point 4) and the company budget in the UI (see "Could not
confirm").
- `docs/guides/board-operator/delegation.md` still says that a CEO above
80% of its budget focuses on critical tasks. That is the skill guidance
from point 5. I did not change that file.

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

## Model Used

- Claude Fable 5.2 (Anthropic), model ID `claude-fable-5-2`, in Claude
Code. Extended thinking and tool use (file read, search, shell, `gh`).
The model read the code, wrote the docs, and wrote this description.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [ ] I have run tests locally and they pass — *docs only. No test reads
these files. `pnpm verify` asks for required CI*
- [ ] I have added or updated tests where applicable — *not applicable.
Docs only*
- [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 — *pending on this PR*
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups —
*pending on this PR*
- [x] I will address all Greptile and reviewer comments before
requesting merge

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

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-24 14:25:24 -08:00
DottaandPaperclip 3128be7cda fix(e2e): preserve exact spacing around handoff mentions (#22825)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Product journeys check that a person can hire and delegate through
chat.
> - The journey selects real agent and project mentions in the composer.
> - Each selection inserts a trailing space for the next typed word.
> - The helper then types the complete next source slice, including its
own whitespace.
> - This pull request removes the inserted space through normal keyboard
editing before continuing.
> - The benefit is one exact saved message with the existing strict
identity and count checks.

## Linked Issues or Issue Description

**What happened?**
The hiring journey saves two spaces after its agent mention and an
unwanted space before the comma after its project mention. Its exact
saved-body assertion fails after the delegated task completes. The
retained historical observation lacks the original message comparison.
This PR reproduces the spacing defect directly in the production
composer; it does not claim those missing historical inputs were
recovered.

**Expected behavior**
Normal mention selection must preserve the exact requested body,
including whitespace and punctuation, and save it exactly once.

**Steps to reproduce**
Run the production composer browser spec with the quoted checklist
reference. Before the repair, the saved message has an extra space after
each selected mention. After the repair, the body matches exactly.

**Paperclip version or commit**
Reproduced from source at 28aa32e7d7. The
affected source files were unchanged on current master before
publication.

**Deployment mode**
Local Linux Chromium control with the real production and streamlined
composers. No model or staging credentials. Related merged #22821
repairs a separate routine journey.

## What Changed

- Check the collapsed caret before removing exactly one editor-added
space. Refuse to send if the caret does not match.
- Preserve exact agent/project mention identities and the single-message
assertion.
- Retain private byte counts, SHA-256 body hashes, IDs and comparison
results before grading. Do not retain raw bodies.
- Extend the real composer test with the quoted checklist reference.
Keep wrong-agent, duplicate and missing-project rejection.

## Verification

- Red: the production composer browser check failed with extra spaces
around both mention chips.
- Green: all 6 composer browser checks pass with the corrected helper.
- All 75 focused hiring flow and evidence tests pass. A changed-body
control proves the failure receipt survives grading.
- Local test-project typecheck could not complete: the host killed the
compiler with SIGKILL. `pnpm verify --explain` could not select checks
because the managed Git storage guard rejects `git ls-files`. Neither
attempt is a pass.
- Final head `99338b2a3f0717489f09cd949353ed2d12248e3e`: [selected
CI](https://github.com/paperclipai/paperclip/actions/runs/45491682386)
passes, including Typecheck + Release Registry, four support shards, six
Runner package shards, static checks and aggregate verify. Build and
unrelated suites are skipped by the test-only path policy. Greptile is
5/5 on this head. There are no review threads. No new paid test,
protected pin update or staging deployment was made.

## Risks

- The browser helper depends on the shipped mention insertion caret
contract. A missing trailing space stops the send instead of deleting a
mention.
- The historical cause remains an inference from an independently
reproduced defect. A future full run must establish staging acceptance.

## Model Used

OpenAI GPT-6 through Codex, with reasoning, source editing, shell tools
and Chromium. The runtime does not expose a more specific model
revision.

## 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-24 16:05:37 -06:00
Zurva Aziz 96eb00e98f fix(routines): prefer X-Hub-Signature-256 on app_webhook triggers (#18581)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Routines can start from public webhook triggers
> - The `app_webhook` signing mode reads a signature from
`X-Hub-Signature` or `X-Hub-Signature-256`
> - Some senders, such as GitHub, can send both headers on one delivery
> - The code reads `X-Hub-Signature` first, and `verifyAppWebhook`
accepts only `sha256=` values
> - So a SHA-1 value in `X-Hub-Signature` causes a 401, even when the
SHA-256 signature is valid
> - This pull request reads `X-Hub-Signature-256` first
> - The benefit is that senders that send both headers can use
`app_webhook` triggers

## Linked Issues or Issue Description

Fixes #18565

Related, not duplicates: #16781, #1892.

## What Changed

- `firePublicTrigger` now prefers `X-Hub-Signature-256` over
`X-Hub-Signature` in `app_webhook` mode.
- Added tests for both headers, each header alone, an invalid SHA-256
header, and a SHA-1 header alone.

## Verification

- Codex ran these checks in its cloud sandbox.
- Run from `server/`: `../node_modules/.bin/vitest run
src/__tests__/routines-service.test.ts`
- Result: 85 tests passed, 0 failed, 0 skipped. Embedded Postgres ran.
- With the fix reversed, 2 of the 5 new tests failed. With the fix
restored, all 5 passed.
- The server TypeScript check passed.
- The full workspace typecheck did not finish because `cargo` was not
installed in the test environment.
- The full build and the repository-wide tests were not run. CI must
confirm them.

## Risks

- Low risk. The change affects only `app_webhook` mode.
- Behavior change: a delivery with a valid `sha256=` value in
`X-Hub-Signature` and an invalid `X-Hub-Signature-256` value was
accepted before. It now gets a 401.
- SHA-1 signatures stay rejected. This is an interoperability fix, not a
security fix.

## Model Used

- Implementation and tests: OpenAI Codex (cloud). The session did not
show the exact model ID, context window, or reasoning mode.
- Review and pull request text: Anthropic Claude Opus 5.5
(`claude-opus-5-5`), with tool use.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [ ] 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 (targeted suite only, in
the Codex sandbox, see Verification)
- [x] I have added or updated tests where applicable
- [ ] I have updated relevant documentation to reflect my changes (not
needed, the existing docs stay correct)
- [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
- [ ] I will address all Greptile and reviewer comments before
requesting merge
2026-11-24 15:44:57 -06:00
Stefan Lendl c9edffe605 fix(claude-local): label ACP usage rows from the run's AI connection (#20955)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - A `claude_local` agent can run on a managed AI connection. The
connection supplies the credentials and the routing, for example
OpenRouter or a gateway.
> - Each run writes usage rows to the cost ledger. The rows carry a
provider, a biller, a billing type and a model.
> - The ACP lane of the Claude adapter finds the billing identity from
the agent environment only. It treats a run as API-billed only when
`ANTHROPIC_API_KEY` is set.
> - A managed connection with bearer auth sets `ANTHROPIC_AUTH_TOKEN`
and `ANTHROPIC_BASE_URL`. It does not set `ANTHROPIC_API_KEY`. The run
is therefore labeled `anthropic` with the subscription billing type, and
the ledger records zero cost.
> - The ACP bridge also reports its own model alias (for example `opus`)
as the current model. The usage row then names that alias, not the model
that the endpoint received.
> - This pull request resolves the billing identity from the managed AI
connection first. It also names the requested model on usage rows for
those runs.
> - The benefit is that runs on an api_key connection show as metered
API usage with the correct provider and model in Costs.

## Linked Issues or Issue Description

Refs #18540

This pull request fixes the labels for the ACP lane. The Claude CLI lane
(`resolveClaudeBillingType`) and the price estimate stay open.

Related pull requests that I found. None of them changes the ACP billing
identity:

- #12000 (`fix(claude-local): distrust gateway-reported costs`) is open.
It touches the Claude CLI lane and the cost estimate.
- #11420 (`fix(pi-local): report a real billing type instead of
hardcoding unknown`) is open. It fixes the same kind of label problem in
the Pi adapter.

The report in #18540 also names a second problem. Claude Code estimates
the price with Anthropic list prices. This pull request does not change
that estimate.

## What Changed

- `claude-local/src/server/acp-billing.ts` (new):
`resolveManagedApiKeyBilling` reads the managed AI connection. For an
`api_key` connection it returns the billing type `metered_api`. The
provider and the biller are the connection provider. Bedrock routing
bills `aws_bedrock`. `resolveEnvBillingIdentity` holds the existing
env-based classification, moved out of `acp.ts` unchanged. This keeps
`acp.ts` under 1,000 lines.
- `claude-local/src/server/acp.ts`: `resolveClaudeAcpBillingIdentity`
tries the managed connection first. Other runs, subscription connections
included, keep the env-based result.
- `adapter-utils/src/acpx-engine/execute.ts`: the ACPX billing identity
gets an optional `preferRequestedModel` flag. The two accounting-model
calls pass it on.
- `adapter-utils/src/acpx-engine/accounting-model.ts`:
`acpxAccountingModel` takes an options argument. With `preferRequested`,
it returns the requested model, or `null` when the run requested none.
- Tests: `acp.test.ts` covers gateway, OpenRouter, local, Bedrock and
subscription connections. `accounting-model.test.ts` covers the new
option. `execute.test.ts` checks that the usage row and the result name
the requested model with the flag, and the bridge model without it.

## Verification

- `corepack pnpm install --frozen-lockfile`: succeeded.
- `corepack pnpm vitest run src/acpx-engine/accounting-model.test.ts
src/acpx-engine/execute.test.ts` (in `packages/adapter-utils`): 2 files,
271 tests passed.
- `corepack pnpm vitest run src/server/acp.test.ts` (in
`packages/adapters/claude-local`): 1 file, 46 tests passed.
- `corepack pnpm --filter @paperclipai/adapter-utils typecheck`: passed.
- `corepack pnpm --filter @paperclipai/adapter-claude-local typecheck`:
passed.
- I did not run the full repository test suite. I did not run a live run
against OpenRouter.

## Risks

- Low risk. The new path applies only when the run config has a managed
`api_key` connection. All other runs keep their current labels. A test
checks the subscription case.
- A run on an api_key connection whose config names no model now records
no model on its usage row. Before, the row carried the bridge alias.
- A connection that projects `ANTHROPIC_API_KEY` resolved to `api`
before and resolves to `metered_api` now. `normalizeLedgerBillingType`
in `server/src/services/heartbeat/run-state.ts` maps both values to
`metered_api`, and the Anthropic and Codex pricing accept both. The
ledger result is the same.
- Runs on an api_key connection change from `subscription_included` to
`metered_api`. Their cost is no longer forced to zero. Claude Code still
supplies the cost estimate. For a routed model, that amount can differ
from the amount that the provider bills.

> 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 Code (Anthropic) with tool use (shell, file edits, test runs).
Claude Fable 5.2 (`claude-fable-5-2`) directed the work. Claude Sonnet
5.5 (`claude-sonnet-5-5`) ported the change to current master and ran
the tests. Claude Opus 5.5 (`claude-opus-5-5`) reviewed it.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [ ] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [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-24 15:39:10 -06:00
Oke Iyanuoluwa Enoch ecef06d246 fix(agents): reject a blank taskKey on reset-session instead of resetting all task state (#19282)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Operators can reset an agent's runtime session with `POST
/agents/:id/runtime-state/reset-session`
> - A `taskKey` scopes the reset to one task. No key resets all task
state.
> - The schema accepted a whitespace-only `taskKey`, and the route
changed it to `null`
> - So a blank key took the full-reset path, and the activity entry
recorded `taskKey: null`
> - This pull request makes the schema trim the key and reject a blank
key with a 400
> - The benefit is that a scoped reset request can never become a full
reset by accident

## Linked Issues or Issue Description

Fixes #19080

Refs #19005 (the parent issue that #19080 was split out of)

I searched open and closed PRs for `19080`, `reset-session` and
`resetAgentSessionSchema`. I found no related PR.

## What Changed

- `resetAgentSessionSchema.taskKey` is now
`z.string().trim().min(1).optional().nullable()`. A blank or
whitespace-only key fails validation with a 400. An omitted key or
`null` still requests the full reset.
- The route uses the parsed `taskKey` directly. The schema already trims
it, so the route no longer has its own trim-and-null step.
- Added tests in `packages/shared/src/validators/agent.test.ts` for
omitted, `null`, trimmed and blank keys.

## Verification

- `pnpm exec vitest run packages/shared/src/validators/agent.test.ts`:
16 tests pass.
- `pnpm exec vitest run cli/src/__tests__/agent-lifecycle.test.ts`: 4
tests pass. The CLI parses its payload with the same schema.
- `pnpm --filter @paperclipai/shared typecheck` passes.
- I ran the server `tsc` locally. It reported no errors in
`server/src/routes/agents.ts`. My local Windows setup cannot build
`@paperclipai/paperclip-runner`, so the full server typecheck depends on
CI.

## Risks

- Low risk. A client that sends `taskKey: ""` or a whitespace-only key
now gets a 400 instead of a full reset. The board UI sends `null` or an
issue id, and the CLI omits the key when `--task-key` is not set.
Neither caller sends a blank key.

## Model Used

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

## Checklist

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

> - Paperclip is the open source app people use to manage AI agents for
work
> - Agents and board users keep plans and specs as issue documents, and
they change them through the documents API
> - An update (`PUT /api/issues/{id}/documents/{key}`) and a revision
restore return the saved document
> - The service builds that result from the row it read before the
write, so the result also carries the old `latestBody`
> - A client that reads `latestBody` from the response gets the previous
revision's text, next to the new `latestRevisionId` and
`latestRevisionNumber`
> - This pull request removes the stale field from the update and
restore results, so they have the same shape as a document read
> - The benefit is that a write response never shows old text as the
latest text

## Linked Issues or Issue Description

I searched open and closed issues and pull requests for this bug and
found no match. The related work below touches the same service, but not
this bug:

- Refs #18277 (open: locks the document row during upsert and restore;
it does not change the result shape)
- Refs #18171 and #12015 (plugin upsert drops `baseRevisionId`; a
different bug)

**What happened?**
`PUT /api/issues/{id}/documents/{key}` on an existing document returned
200. The response had the new `body`, `latestRevisionId` and
`latestRevisionNumber`. It also had a `latestBody` field with the text
of the previous revision. A `GET` on the same document right after
returned only the new body. A restore (`POST
/api/issues/{id}/documents/{key}/revisions/{revisionId}/restore`) has
the same problem.

**Expected behavior**
The update and restore responses have the same document shape as `GET
/api/issues/{id}/documents/{key}` (the shared `IssueDocument` type).
That type has `body` and no `latestBody`. No field in the response holds
text from an older revision.

**Steps to reproduce**
1. Create an issue document with body `A`.
2. Update it with body `B` and `baseRevisionId` set to the current
revision.
3. Read the response: `body` is `B`, but `latestBody` is `A`.
4. Restore revision 1. The response `latestBody` is `B`, the body before
the restore.

**Paperclip version or commit**
Seen on a current npm release. Reproduced on `master` at 51d77648bc with
the new service test.

**Deployment mode**
Not deployment-specific. The bug is in
`server/src/services/documents.ts`.

**Agent adapter(s) involved**
Not adapter-specific (core bug).

## What Changed

- `server/src/services/documents.ts`: the update path of
`upsertIssueDocument` and the `restoreIssueDocumentRevision` path remove
`latestBody` from the row they read before the write. Then they spread
the remaining fields into the result. The `body` field stays the new
text, as before.
- `server/src/__tests__/documents-service.test.ts`: a new test updates a
document and restores its first revision. It checks that each result is
equal to a fresh `getIssueDocumentByKey` read and has no `latestBody`
field.

## Verification

- Red-green, as AGENTS.md section 10 asks:
- Before the fix, the new test failed on the update result: `latestBody:
"# Plan"` (the old body) was in the response.
- With only the update fix applied, the test failed on the restore
result: `latestBody: "# Second plan"` (the body before the restore).
  - With both fixes, the test passes.
- `npx vitest run` on the 9 test files that write or read issue
documents through the service and routes: `documents`,
`documents-service`, `issue-document-restore-routes`,
`document-annotation-routes`, `document-annotations-service`,
`artifact-review-documents-service`, `artifact-review-document-routes`,
`native-plan-proposal-sync`, `case-mutation-fence.integration`. Result:
9 files, 68 tests passed.
- `pnpm --filter @paperclipai/server typecheck` passed.
- I did not run `pnpm verify` locally. The change is in a service that
the routes import, so the selection is very broad. The required CI
checks supply the broad coverage, as AGENTS.md section 7 allows.

## Risks

- Low risk. The response no longer has the undocumented `latestBody`
field. That field is not in the shared `IssueDocument` type, and after
an update or restore it always held old text. A client that read it got
wrong data. The routes read `id`, `key`, `title`, `format`,
`latestRevisionId`, `latestRevisionNumber` and `body` from the result.
Those fields do not change.
- No database or migration change.

## Model Used

- Provider: Anthropic. Model: Claude Opus 5.5 (`claude-opus-5-5`), in
Claude Code, with tool use (shell, file edit) and extended thinking. The
run did not show the context window size to the model, so I do not state
a number.
- The model found the cause, wrote the test and the fix, and ran the
checks above.

## 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 (no
update needed: the documented response shape does not change)
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

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

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 15:34:11 -06:00
0f257fe67f fix(recovery): stop re-waking a blocked task whose dependency runs keep failing (#22818)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - A blocked task waits on other tasks. When all its blockers are done,
Paperclip wakes the assignee. A periodic backstop does this when the
normal event is missed.
> - The backstop deduplicates wakes with a key that includes the blocked
cycle (`blockedTransitionAt`).
> - A woken run that fails can leave the task blocked again. That starts
a new cycle, so the next sweep sees a new key and wakes the task again.
> - When the failure is deterministic, this never stops. One hosted task
ran more than 11,000 failed runs in five days, about one every 20
seconds.
> - This pull request adds a circuit breaker to the backstop: after each
failed attempt, the next dependency wake waits longer (1m, 5m, 25m, ...
up to 24h).
> - The benefit is that a setup failure can no longer become thousands
of automatic runs.

## Linked Issues or Issue Description

**What happened?**
A blocked task had all blockers done. The issue graph liveness backstop
woke its agent with `issue_blockers_resolved`. Each run failed in setup
(`durable_prp_canonical_json_too_large`). The task returned to `blocked`
with a new `blockedTransitionAt`. The backstop then emitted another wake
with a new idempotency key. The activity log of the task had 11,215
`issue.blockers_resolved_wake_emitted` rows, each with a different key,
and 11,621 failed runs.

**Expected behavior**
A wake that did not help is not repeated without limit. Paperclip waits
longer after each failure, and then probes again. A newer blocker
result, an edit of the blocker set, or a run that does not fail starts a
fresh attempt.

**Steps to reproduce**
1. Create a blocked task with one done blocker and an agent assignee.
2. Record three `issue_blockers_resolved` wakes for the task, each with
a failed run and a different blocked-cycle key.
3. Run `reconcileResolvedDependencyWakes()`.
4. Before this change, the backstop emits a fourth wake.

Refs #22705, #22707 (the underlying setup size failure and its retry
classification). Those changes stop scheduled retries for that one
error. The backstop loop is a separate path and accepts any failure
class, so it needs its own breaker.

## What Changed

- New `server/src/services/recovery/dependency-wake-circuit-breaker.ts`.
It reads this agent's terminal runs on the task (any wake reason),
newest first. It reads runs through `heartbeat_runs.issue_id` (indexed).
It counts consecutive `failed` or `timed_out` runs that finished after
the latest blocker change: blocker completion, succeeded workspace
finalize, an added blocker relation, or an `issue.blockers_updated`
edit. Each run counts once. A run that did not fail ends the streak.
`interrupted` runs (restart, deploy) are neutral.
- The wait before the next dependency wake is 1 minute after one
failure, then multiplied by 5 per failure, capped at 24 hours. After the
wait, one wake probes again, so a fix that ships later is picked up.
- `reconcileResolvedDependencyWakeBackstop` calls the breaker before it
enqueues a wake. A skipped wake reports its retry time through
`onDeferredDeadline`. New counter: `failedWakeBackoffSkipped`. When a
task has three or more consecutive failures, the sweep logs one warning
with the task ids.
- Tests: backstop regressions (production shape, backoff elapsed, reset
by a later successful run, reset by a newer blocker result, reset by a
blocker-set edit) and unit tests for the policy (duplicate receipts,
interrupted runs, capped probe).

## Verification

- `cd server && npx vitest run
src/__tests__/heartbeat-issue-liveness-escalation.test.ts
src/services/recovery/dependency-wake-circuit-breaker.test.ts
src/services/workspace-recovery-dependency-finalize.test.ts
src/__tests__/issue-blocker-stall-wakeups.test.ts`: all pass.
- Red/green: with the backstop hook reverted, the production-shape test
fails (`expected 1 to be 0`: the backstop wakes the task again). With
the hook, it passes.
- Existing backstop tests (self-blocked, same-cycle dedup, blocker
completion) still pass.

## Risks

- A task whose dependency runs keep failing is woken less often, at most
once a day after about six failures. The failed run still shows its own
error and action. Before this change the same task ran without limit.
- The breaker adds one run read per candidate that passes all earlier
checks (four small aggregate reads more only when a recent run failed).
It does not run for tasks that are not ready or already have a wake.
- No schema change.

## Model Used

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

## Checklist

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

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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 15:25:25 -06:00
DottaandPaperclip 823e90d8b2 fix(e2e): follow current routine form and schedule controls (#22821)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The scheduled-routine journey checks creation, timed execution,
saved output and pause.
> - The routine page redesign changed its form and schedule controls.
> - The journey still used the old title placeholder, Responsible picker
and trigger editor.
> - It stopped before it could measure scheduling, even after the New
routine button fix.
> - This pull request follows the current controls and adds a
production-component browser regression.
> - The benefit is a usable schedule test with the same independent
behavior checks.

## Linked Issues or Issue Description

Refs #22182 and #22205. Related open #22340 changes other routine page
details; it does not update this journey.

**What happened?**
The scheduled-routine journey opens New routine, then times out on the
removed Routine title placeholder. The current form labels that field
Title. It has a Default agent picker and a separate Project picker. The
old journey also expects the removed Schedule trigger region and Enable
trigger control.

**Expected behavior**
The journey must use the current form, resume its owned schedule,
observe one attributed scheduled run, pause it, and check the next full
schedule boundary.

**Steps to reproduce**
Run the new credential-free browser control against the previous UI
actions. It renders the production RoutineEditDialog and fails waiting
for the old Routine title placeholder. The same control passes with this
repair.

**Paperclip version or commit**
Reproduced from master at d128e2db6f.
Published on current master after checking that all four existing
changed files were unchanged.

**Deployment mode**
Local Chromium production-component control, with no app server, model
or testing credentials. The observed staging failure supplied the
original report. This PR has no fresh full-stack staging pass.

## What Changed

- Extract the routine browser actions into a small journey-owned module.
- Fill Title and Instructions by accessible name. Open the agent and
project pickers explicitly.
- Use the schedule popover's Resume and Pause controls. Wait for each
exact trigger PATCH.
- Read created-task history on the base routine page. Keep configuration
version history separate.
- Add a Chromium control using the actual form, entity selectors and
routine page. It checks exact owner/project selection, missing-choice
refusal and the two owned trigger mutations. Unrelated display/editor
boundaries are stubbed.
- Keep the scheduler, native run, output, reload, duplicate-run,
deadline and cleanup oracles intact.
- Document the control and its limited acceptance scope.

## Verification

- Red: the production-component browser control timed out on
`getByPlaceholder("Routine title")` with the original actions.
- Green: `BROWSER_EXECUTABLE_PATH=/usr/bin/chromium node --import
/tmp/pap5819-tools/node_modules/tsx/dist/loader.mjs
tests/runner-e2e/product-journeys/routine-schedule-ui.browser.mjs`
passes.
- Focused Vitest: all 17 tests in routine-schedule-entry,
routine-schedule-evidence and routine-schedule-flow pass. The temporary
config selects only those suites.
- Local tools: Node 25.9.0, Vitest 5.0.3, Playwright 1.62.1 and system
Chromium. Dependencies were installed outside the checkout; no lockfile
changed.
- `pnpm verify` could not select tests: the managed Git storage guard
rejects `git ls-files`. This attempt has no verification verdict. The
first head passed selected CI. Those results do not qualify the revised
head; fresh CI and review remain pending.
- No new paid run, protected test-harness pin change or staging
deployment was made. Full scheduled acceptance remains separate.

- Review regression: the production route resolver rejects the old
/history task read; all 17 focused tests pass after the correction.
- Isolated dependency layout: the previous browser check cannot resolve
React without root React/React DOM. The revised check resolves UI-owned
peers and passes in that layout.

## Risks

- These actions target the current redesigned routine UI. An old UI
paired with this harness would not match the controls.
- The browser regression stubs unrelated display/editor boundaries. It
proves the real control actions, not a complete scheduler or
native-provider run.
- The fixture owns one schedule. Multiple matching schedule controls
cause an error rather than selecting an arbitrary trigger.

> 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

OpenAI GPT-6 in Codex, with tool use for source edits, Chromium, local
tests and GitHub API operations.

## 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-24 15:19:57 -06:00
DottaandClaude Opus 5.5 137bd29531 fix(heartbeat): a provider usage-limit hold applies only to the account that reported it (#22800)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Agents run on an AI connection: a connected provider account (a
connection grant), or the host's own account
> - When a provider reports an exhausted allowance, Paperclip holds new
work for that agent until the reported reset (`provider_limit_wait`),
and schedules one recheck at the reset
> - The hold was keyed by agent only. After a user connected a
different, working account and the agent moved to it, every new run was
still cancelled with the old account's reset time. A reply on the task
did not recheck the wait. Only a manual "Check now" got work moving
> - A usage limit belongs to the account that reported it. When that
account is gone or replaced, the hold must be gone too, and waiting work
must start without manual repair
> - The banner's "Check now" button also failed here. It answered 409
"Issue has no scheduled monitor", because the button calls the
issue-monitor route and this task has a scheduled retry, not a monitor
> - This pull request scopes the hold to the credential, releases
waiting work when the account changes or is revoked, makes a reply
recheck the wait, and makes "Check now" recheck a waiting retry
> - The benefit is that fixing the account fixes the task. The same
account stays held, so an exhausted account is not called again

## Linked Issues or Issue Description

No public issue exists. Bug report:

**What happened?**
An agent's connected provider account ran out of quota, with a reset
about six days away. Paperclip held the agent's work ("Pool exhausted",
runs cancelled with `provider_limit_wait`, one recheck scheduled 24
hours later). The user then connected a different, paid account. The old
account became revoked, and the agent was moved to the new account. The
agent's connection test passed. But every new run was still cancelled at
once with the old account's reset time. A new comment on the task did
not start a run, although the composer said "Sending a reply wakes the
agent now". The task stayed in `todo`. Pressing "Check now" on the "Pool
exhausted" banner did nothing: `POST /issues/:id/monitor/check-now`
answered 409, because the task has no issue monitor
(`triggerIssueMonitor` throws "Issue has no scheduled monitor").

**Expected behavior**
A limit reported on account A must not hold a run that uses account B.
When account A is revoked, removed or replaced on the agent, the hold
stops. Work that waited on it starts promptly. While the agent still
uses account A, the hold stays, with the plain message. A reply does
what the composer says.

**Steps to reproduce**
1. Bind an agent to connected account A.
2. Let a run fail with `quota_exhausted` and a reported reset days away.
The next wake is cancelled with `provider_limit_wait`, and a recheck is
scheduled about 24 hours later.
3. Connect account B and move the agent to it, or revoke account A.
4. Wake the agent on the task, or reply on the task. Before this change,
the run is cancelled with `provider_limit_wait` again, and the reply
does not recheck.

## What Changed

- `server/src/services/native-runtime/native-startup-retry.ts`: limit
evidence now comes only from runs on the checked credential. A run
records its grant in `contextSnapshot.aiConnection.grantId`. A run with
no recorded grant used the host's own account. Evidence from a revoked,
expired or removed grant never applies. A later success on another
account no longer clears this account's limit. New helpers resolve the
credential of an agent's next run from its saved binding
(`shared`/`delegated`: the bound grant; `responsible_user`: that user's
default grants for the provider).
- `server/src/services/heartbeat/provider-limit-wait.ts`: the
pre-dispatch hold checks the agent's current credential, and records the
limited grant on `providerLimitWait.grantId`. New
`releaseProviderLimitWaits` makes waiting usage-limit retries due now,
notifies retry dispatch in the same transaction, and logs
`issue.scheduled_retry_retry_now` activity with `source:
provider_limit_recheck`. The recheck goes through normal dispatch. It
reads saved evidence only, so a still-limited account is held again with
no provider work.
- `server/src/services/agent-configuration.ts`: a change to an agent's
`runtimeConfig.aiConnection` releases that agent's waits, in the same
transaction as the change.
- `server/src/services/tool-access/connections/grants.ts` and
`removal.ts`: revoking or removing an account releases the waits whose
limit was reported on it (after commit, best effort; the evidence rule
alone already stops the hold).
- `server/src/services/heartbeat/queue.ts`: a user's wake that is folded
into a usage wait (comment or other user wake) rechecks it at once.
Agent and system wakes keep the scheduled time, so they cannot loop.
- `server/src/routes/issues.ts`: `POST /issues/:id/monitor/check-now` on
a task with no monitor and a waiting scheduled retry now starts that
retry (the same path as "retry now"). The retry rechecks availability
before any work. It logs `issue.scheduled_retry_retry_now` with `source:
monitor_check_now`. If the check cannot start, the 409 has a plain
reason. Tasks with a monitor keep the old behavior.
- `ui/src/components/IssueMonitorBanner.tsx`: for a usage wait, the
composer now says "Sending a reply checks usage again now. The agent
starts as soon as usage is available." The banner says work also resumes
when the agent uses a different account.
- Upgrade safety: holds are derived from saved run evidence, so old
holds resolve by the new rule after deploy. A wait saved before this
change has no `grantId`; the release finds its account from the run that
reported the limit (`providerLimitWait.sourceRunId`).
- `queue.ts` was already far above 1,000 lines. This change adds one
small helper beside the two coalescing paths that need it, rather than a
new module for one call.

## Verification

- Red first: the new tests ran against the `origin/master` sources and 6
of them failed (hold on account A blocked a run on account B; revoked
account still held; rebind and reply did not release the 24-hour retry;
old-shape release missing). The shared-account test passed on master
too, as intended: it guards that the hold stays.
- Check now: a route test covers a `todo` task with no monitor and a
waiting retry (200, the retry starts, the monitor path is not called,
activity is logged) and a refused check (409 with a plain reason). An
integration test covers the exact saved state: `todo` task, cancelled
`provider_limit_wait` run, `scheduled_retry` successor, agent already
moved to another account. "Check now" starts the retry, and it is not
held again.
- Green: `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/heartbeat-provider-limit-wait.test.ts
src/services/native-runtime/native-provider-limit-cooldown.integration.test.ts
src/services/native-runtime/native-startup-retry.integration.test.ts`
passes (58 tests), and
`src/__tests__/issue-execution-policy-routes.test.ts`.
- UI: `ui/src/components/IssueMonitorBanner.test.tsx` passes (2 tests).
- `npx tsc --noEmit -p server` passes.
- `pnpm verify` exited 2 ("broader verification required"; its graph
worker was killed under machine load). I ran the focused checks above
and rely on required CI for broad coverage.
- New tests cover: same account still held with the plain message; agent
moved to another connected account starts; revoked account stops
holding; rebind releases the pending retry and logs activity; a wait
saved in the old shape is released when its account is revoked, and not
when another account is revoked; two agents on one account both stay
held when one agent moves away; a user reply rechecks at once and holds
again (keeping the reply) while the account is still limited, and an
agent's comment does not.
- Not run live: I did not reproduce this on a running instance. I read
the evidence from a local instance where the bug happened, and I did not
change that instance. Live confirmation of the release after deploy is
still to do.

## Risks

- Behavior change: a limit no longer carries over to a different
account. If two accounts share one provider-side quota, the agent can
make one call on the new account before that account gets its own hold.
- A `responsible_user` agent whose user has no saved default cannot
resolve its account before the run. In that case only the revoked-grant
rule applies, as before.
- A user reply on a still-limited account makes one cancelled recheck
run and a new scheduled wait. This is cheap (no workspace or provider
work) and is bounded by the number of user replies.
- No schema change and no new background worker.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, agentic coding 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
- [ ] 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 15:01:19 -06:00
DottaandClaude Opus 5.5 4401962e69 feat(google-workspace): run the six launch services on Google's MCP servers again (#22815)
Gmail, Drive, Docs, Sheets, Slides and Calendar go back to google_mcp because of Google's Workspace AI Tools Addendum; the REST tool set stays as the fallback. The REST argument checks that need no request to Google run before each MCP call, a Calendar delete reads the event first and refuses a recurring series, and a refresh that replaces saved REST definitions holds nothing for review.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 14:44:03 -06:00