Commit Graph
8569 Commits
Author SHA1 Message Date
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
DottaandClaude Opus 5.5 71ff1c8600 fix(runner): read an assigned skill by its short name (#22813)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Agents use saved company skills; on the native runner they read a
skill's files with `read_assigned_skill`
> - The daily QA staging smoke test `saved-skill-use` has been failing:
the agent finishes the task, but no skill read is recorded
> - The private run events show why: the agent called
`read_assigned_skill` with the skill's short name (`qa-saved-skill-…`),
the name the task gives it (`/qa-saved-skill-…`) and the skill's own
frontmatter `name`. The runner matches only the full company key
(`company/<id>/qa-saved-skill-…`) or the runtime name
(`qa-saved-skill-…--<hash>`), so it answered `runner_skill_not_assigned`
for a skill that was assigned. The agent then read the file with bash
> - This pull request lets the runner find an assigned skill by its
short name too
> - The benefit is that agents read saved skills through the verified,
pinned path the first time, instead of falling back to the filesystem

## Linked Issues or Issue Description

**Subsystem affected**
Native runner bridge tools (`read_assigned_skill`).

**Problem or motivation**
In the November 24 QA staging smoke run, `saved-skill-use` failed. Run
events (private QA evidence) show `read_assigned_skill` with
`{"skill":"qa-saved-skill-journey-…","path":"SKILL.md"}` returning
`{"outcome":"failed","code":"runner_skill_not_assigned"}`, followed by a
`bash` read of the same SKILL.md. The skill was in the agent's desired
skills and on disk.

**Proposed solution**
After the exact key/runtime-name match, accept the key's last part (with
or without a leading `/`) when exactly one assigned skill has it.

**Alternatives considered**
- Changing the task text or the test to pass the runtime name: the agent
is told `/short-name`; the product should accept what it tells agents.
- Matching the frontmatter `name`: the short name is already the key's
last part for company skills, and needs no file read before the lookup.

## What Changed

- `server/src/services/native-runtime/runner-bridge-tools.ts`:
`assignedSkillByName` finds an assigned skill by key, runtime name, or
unique short name; `readAssignedSkill` uses it.
- `server/src/services/native-runtime/runner-bridge-tools.test.ts`: the
short name (and `/short-name`) reads the skill; a short name two
assigned skills share names neither; the runtime name still
disambiguates.

## Verification

- `runner-bridge-tools.test.ts`: the new cases fail on master with
`runner_skill_not_assigned` and pass with the fix (red/green); 11
passed.
- Not run locally: server typecheck (this worktree's local
`paperclip-runner` build is stale; unrelated errors in other files). CI
typechecks the change.
- After deploy: the next QA staging smoke run's `saved-skill-use` should
record a native skill read.

## Risks

- Low. Lookup only widens to a unique short name among skills already
assigned to this run; it grants no access to unassigned skills, and
every file read keeps its manifest and digest checks.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use
(shell, AWS CLI read of the private QA evidence, file edits).

## Checklist

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

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 14:38:50 -06:00
Dotta d128e2db6f feat(analytics): track onboarding step failures and agent chat sends (#22814)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - On Paperclip Cloud, browser analytics tracks onboarding wizard steps
through PostHog
> - Today, failures on the model connection step and user replies in the
onboarding chat emit no browser analytics events
> - Without those events, teams cannot tell whether users hit an error
during model setup or leave after the automatic welcome greeting
> - This pull request adds structured enum-only browser events for
onboarding step failures and agent chat message sends
> - The benefit is clear visibility into onboarding drop-offs and
post-launch engagement without sending customer text or raw error
strings

## Linked Issues or Issue Description

**What existing behavior does this improve?**
Cloud browser onboarding analytics in
`ui/src/lib/analytics/onboarding-analytics.ts`,
`ui/src/components/OnboardingWizard.tsx`, `ui/src/pages/AgentChat.tsx`,
and `ui/src/pages/IssueDetail.tsx`.

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

**Current behavior**
The onboarding wizard emits `onboarding_opened`,
`onboarding_step_viewed`, `onboarding_step_completed`, and
`onboarding_dismissed`. Failures during API key storage, subscription
sign-in, adapter environment tests, agent creation, and onboarding
welcome greeting emit no failure event. Onboarding also launches into
Agent Chat (where server-side `task.created` skips conversations), so
user replies after launch emit no distinct engagement event.

**Proposed behavior**
Add two browser analytics events on Cloud (inert on self-hosted installs
and gated on existing analytics consent):
- `onboarding_step_failed` with bounded `step`, `reason`, sanitized
`provider`, and `method` fields.
- `agent_chat_message_sent` with `surface` (`onboarding_chat` or
`agent_chat`).

**Reason and benefit**
Teams can separate actual setup errors (bad API key, failed OAuth,
failed environment test, failed greeting) from user abandonment on the
model-connect step, and separate passive greeting-only visits from
active replies in Agent Chat.

**Breaking changes**
None. Existing event names and properties are unchanged, and no
`PAPERCLIP_EVENTS` server event names are captured from the browser.

## What Changed

- Add `onboarding_step_failed` (`captureOnboardingStepFailed`) and
`agent_chat_message_sent` (`captureAgentChatMessageSent`) to
`ui/src/lib/analytics/onboarding-analytics.ts`, with bounded reason
enums and provider slug validation.
- Wire `captureOnboardingStepFailed` into the failure paths in
`ui/src/components/OnboardingWizard.tsx` (API key save, subscription
sign-in failure, environment test failure, agent creation failure, chat
launch failure) and `ui/src/pages/AgentChat.tsx` (onboarding greeting
failure).
- Wire `captureAgentChatMessageSent` in `ui/src/pages/IssueDetail.tsx`
when a user posts a comment to an Agent Chat conversation.
- Add unit tests in `ui/src/lib/analytics/onboarding-analytics.test.tsx`
covering failure capture, unsafe provider filtering, and chat surface
tagging.

## Verification

- `pnpm --filter @paperclipai/ui typecheck` — passed after rebase onto
`origin/master`.
- `pnpm --filter @paperclipai/ui exec vitest run
src/lib/analytics/onboarding-analytics.test.tsx
src/lib/analytics/product-analytics-events.test.ts
src/lib/analytics/product-analytics.test.ts` — 3 test files, 28/28 tests
passed (including the event-ownership test proving no `PAPERCLIP_EVENTS`
are captured from UI code).
- Prior to rebase, ran the full `ui/src/lib/analytics/` directory — 7
test files, 255/255 tests passed.

## Risks

- Low risk. Browser product analytics stays completely inert on
self-hosted installs and respects Cloud consent gates. No message
content, raw error text, credentials, or PII leave the browser.

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

## Model Used

- Google Gemini (high reasoning mode) in Antigravity, with file editing,
git, and shell tool use.

## Checklist

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

> - Paperclip is the open source app people use to manage AI agents for
work
> - Plugins can provide connectors; a connection saves each tool's
definition from the plugin manifest when it is connected
> - The gateway advertised those saved definitions to agents, and its
freshness check only compared tool name and risk
> - So a plugin upgrade that changed a tool's input schema never reached
existing connections until someone refreshed the catalog by hand
> - This pull request treats a plugin connection's static tools as
Paperclip-defined, so the gateway reads their schema from the installed
plugin
> - The benefit is that plugin upgrades reach every existing connection
at once, with no manual step

## Linked Issues or Issue Description

**What happened?**
An upgraded connector plugin added a `count` operation and `order` and
`view` inputs to one tool. On a stack that had connected before the
upgrade, the agent's tool still rejected `count` ("must be one of the
allowed values") and `order` ("must NOT have additional properties"),
even though the installed manifest declared them. A manual catalog
refresh fixed that one connection.

**Expected behavior**
After a plugin upgrade, agents see the installed plugin's current tool
definitions on every existing connection.

**Steps to reproduce**
1. Install a connector plugin and connect it for an agent.
2. Upgrade the plugin so a tool's `parametersSchema` gains a property.
3. List the agent's session tools: the old schema is still advertised.

## What Changed

- `server/src/services/plugin-connector-runtime.ts`:
`pluginConnectionToolDefinition` returns the installed manifest's
definition of one static tool, built with the same descriptor the
catalog uses.
- `server/src/services/connectors/paperclip-defined-tools.ts`: the
Paperclip-defined tool registry now also covers plugin connections with
a static tool list, and its definition callback receives the connection.
- `server/src/__tests__/plugin-connector-tool-definitions.test.ts`: an
upgrade that adds an input is visible in the agent's session without a
catalog refresh.

## Verification

- New test passes; without the registry change it fails with `expected {
type: 'object' } to match object { properties: { order: ... } }`.
- `npx vitest run src/__tests__/plugin-connector-*.test.ts
src/__tests__/plugin-connectors-*.test.ts` plus catalog publication
tests: 42 passed, 1 skipped.

## Risks

- Low. Only plugin connections with a static tool list change. Dynamic
plugin catalogs and other connectors are unchanged. Catalog publication
already treats Paperclip-defined tools as trusted, so a plugin's own
updated definitions are not held for review.

## Model Used

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

## Checklist

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

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 14:24:05 -06:00
DottaandClaude Opus 5.5 496efd201f fix(native-runtime): recover external-chat task replies skipped by copy-back failure (#22807)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - A native agent run ends with an accepted final reply. Paperclip
posts that reply on the task.
> - The live completion path posts the reply. If a post-result step
fails (for example, workspace copy-back), a background presentation
worker recovers and posts the accepted reply later.
> - The recovery path did not accept a task whose run was woken by an
external chat message, such as a GitHub review comment. The worker found
the run, recovery refused it, and after 6 attempts the reply was marked
failed and lost.
> - The live path posts these replies normally, so the recovery rule was
stricter than the live rule for no reason.
> - This pull request lets recovery post a `done` or `needs_review`
reply for a non-conversation task that an external chat woke, with the
same authorization and source rules as the live path.
> - The benefit is that the agent's real answer reaches the task even
when copy-back fails after the result is accepted.

## Linked Issues or Issue Description

Refs #22798

**What happened?**
On a hosted instance, some native runs finished `succeeded` with a
committed result, but their final reply never appeared on the task. The
run's `responsePublication` ended with `state: "failed"` and
`lastReason: "publication_refused"` after 6 attempts. Every affected run
had `source: "chat:github"`, a `done` result, and a
`native.post_result_failure` event with `retryReasonCode:
"workspace_sync_out_failed"`. Runs on the same task that did not hit the
copy-back failure posted their reply on the live path.

**Expected behavior**
When the live path is skipped after the result is accepted, recovery
posts the accepted final reply once, as the live path would.

**Steps to reproduce**
1. Wake a native agent on an ordinary (non-conversation) task from an
external chat message, so the run context has `source: "chat:..."`.
2. Let the agent report `done` with a final agent message.
3. Make workspace copy-back fail after the result is accepted, so the
live completion path does not post the reply.
4. The presentation worker finds the run, but
`recoverCommittedNativeChatResponse` returns `false`. The worker records
`publication_refused` until it gives up.

**Additional context**
In `recoverCommittedNativeChatResponseInScope`, `ordinaryTaskReply`
required `!isExternalChatPresentationContext(...)`. An external-chat
`done` reply then fell through to the `response_wake` branch, which
returns `false` for anything other than `yielded`. The candidate query
in `native-response-presentation-query.ts` has no such exclusion, so the
worker kept selecting a run that recovery always refused.

## What Changed

- `native-run-finalizer.ts`: recovery now treats a `done` or
`needs_review` reply on a non-conversation task that an external chat
woke as an ordinary task reply.
- That reply uses the authorization that
`resolveChatRunPresentationAuthorizationReason` resolves, as the live
path does. GitHub-origin replies resolve to `internal_agent_write`, so
they stay a local task comment. Other chat providers keep their normal
provider-visible reply.
- That reply prefers the final agent message over an existing run
comment, as the live path does for external chat
(`preferFinalResponseOverExistingComment`).
- Conversation tasks keep their current rules. Blocked replies, governed
review replies, and `response_wake` replies are unchanged.
- `agent-chat-response-recovery.test.ts`: new red/green regression cases
for `chat:github` + `done`, `chat:github` + `needs_review`, and
`externalChatContinuation: true` + `done`. Each case checks that the
reply posts once, the run records `committed_task_response_recovered`,
and a second recovery does not post again.

## Verification

- Red: before the fix, all 3 new cases failed. `work.check` returned a
retry entry (the `publication_refused` path), the same outcome as on the
hosted instance.
- Green: `npx vitest run
src/services/native-runtime/agent-chat-response-recovery.test.ts` passes
67/67.
- `npx tsc --noEmit -p server` is clean.
- `pnpm verify` selected 2374 of 2737 test files (the finalizer is
widely imported) and did not finish in 25 minutes locally. The 2
failures it reached are unrelated load-timing tests. Required CI
supplies the broad coverage.
- After deploy: confirm on staging that a new external-chat task run
with a copy-back failure posts its reply, and that no new
`issue.response_publication_failed` activity appears for this pattern.

## Risks

- Low risk. The change only widens recovery for non-conversation tasks
woken by external chat, and only for `done` and `needs_review` replies
that the candidate query already selects.
- For a non-GitHub chat provider, the recovered reply goes to the
provider, as it does on the live path. Recovery runs only when the run
has no recorded presentation decision or comment, so it does not post a
second reply.
- Runs that already ended as `responsePublication.state: "failed"`
before this change stay failed. This change does not backfill them.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), via Claude Code with tool use
(shell, file edits, browser reads of the staging API).

## Checklist

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

> - Paperclip is the open source app people use to manage AI agents for
work.
> - A task can run Google's Antigravity CLI as a swarm: one coordinator
and several helpers work in the task folder.
> - Today the task shows the swarm only as a flat list of step titles,
such as "Started helper writer-a".
> - Antigravity's own Swarm UI shows a goal, threads, helpers with their
state and current step, and a numbered message board.
> - We did not know which of these facts Paperclip actually receives. We
also did not know how the facts could look in a task.
> - This pull request records what Paperclip receives, from real
recorded runs. It also adds design-proposal stories that show three
directions, built only from those facts.
> - The benefit is a grounded design decision. The next step is clear:
read the swarm's own files and fix one driver bug.

## Linked Issues or Issue Description

Refs #22731 (the swarm driver). Refs #22733 (the `/swarm` command).

**Subsystem affected**
Task chat and run activity for the Antigravity CLI swarm turn
(`packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-*`).
Storybook design proposals.

**Problem or motivation**
During a swarm, the user sees only short step titles. The user cannot
see which helper does what, which helper is blocked, or how far the work
is. Antigravity's own UI shows all of this. We did not know if Paperclip
can get the same data.

**Proposed solution**
Record the evidence in
`doc/plans/2026-11-24-antigravity-swarm-events.md`. The short answer is
"partly":

- Over ACP, Paperclip gets everything the coordinator does. This
includes the swarm title, each helper's name and brief, a
goal/task/thread plan, the coordinator's own messages, finish and stop,
and one usage total.
- Paperclip gets nothing that the helpers do over ACP. The results of
`swarm status` and `read_board` are not forwarded.
- The CLI writes the board, the roster and each helper's steps as
structured JSON in its private `--gemini-dir`. Paperclip already owns
that folder.

Then show three directions in Storybook, built only from this data. Each
element has a tag that tells where its data comes from.

**Alternatives considered**
- Show only the facts that come over ACP. With this choice, the task
cannot show helper state, the current step or helper messages.
- Ask the coordinator to post summaries. This costs tokens, and the
summaries are still prose.
- Wait for Google to expose more. The work graph, a Google review state
and the narrator overview are not available today. The stories show them
only in a variant with the label "Needs Google".

**Additional context**
The inventory found a driver bug. The coordinator writes its plan to
`<state-dir>/antigravity-cli/brain/<session>/.system_generated/swarm/plan.json`,
because its built-in `swarm_pane` skill tells it to.
`antigravityOutsideChange` thinks that this is a write outside the task
folder, so the driver stops the swarm. This happened in 3 of 7 recorded
swarm turns. This PR does not fix it. The fix is to exempt that one
folder, with a red/green test.

## What Changed

- `doc/plans/2026-11-24-antigravity-swarm-events.md`: the inventory. It
lists each element of the reference UI, where the data comes from (ACP
update, tool input or file), samples, timing and risk.
- `ui/storybook/fixtures/antigravity-swarm.sample.json`: redacted events
from one real 4-helper swarm run (CLI 1.5.15, auto mode, isolated state
folder). It holds the ACP updates and the swarm files.
- `ui/storybook/support/design-proposals/swarm-activity/`: turns the
fixture into a view model (helpers, state, current step, messages,
progress, threads) and adds the state variants. It also holds
presentational parts that reuse shipped primitives: the runner header,
the activity group, the subagent tree, `StatusGlyph`, `Tabs`, `Badge`
and `Button`.
- `ui/storybook/stories/design-proposals/swarm-activity.stories.tsx`
(`design-antigravity-swarm-activity`) adds 16 stories:
  - Compare directions.
  - Today: the step titles from the current driver.
  - Direction 1 · Inline helpers (running, helper blocked, finished).
  - Direction 2 · Swarm panel (overview, helpers, messages).
  - Direction 3 · Summary card (collapsed, expanded).
- The states starting, running, helper blocked, stopping, stopped,
failed, not available and finished.
  - A long swarm with 11 helpers and 25 messages.
  - Narrow width.
  - "Would need Google to expose".
- No product code changes. Nothing is connected to live pages.

## Verification

- `node scripts/storybook-catalog.mjs --check`: pass (371 files, 3480
stories).
- `node --test scripts/storybook-catalog.test.mjs`: 13/13 pass.
- `node scripts/check-token-gates.mjs`: all gates clean.
- `cd ui && npx tsc -p tsconfig.json --noEmit`: 0 errors.
- `pnpm build-storybook`: pass. A headless Playwright run opened each of
the 16 stories in light and dark at 1440 px (390 px for the narrow
story) and saved screenshots. No story scrolls horizontally.
- Evidence for the inventory: 7 recorded swarm turns and 1 new real run,
about 3 minutes and 180k coordinator tokens.

## Risks

- Low risk. The change adds Storybook files and a doc only.
- The design depends on files that the CLI does not document. A future
reader must pin to the CLI version and use fixture tests. The doc tells
this.

## Model Used

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

## Checklist

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

> - Paperclip is the open source app people use to manage AI agents for
work
> - Review agents answer GitHub pull request threads; each request's
comment must end in a real reply or an honest final notice
> - After #22672 and #22710, 13 of 85 new review-bot comments on staging
still ended as status notices, and 10 old placeholders on merged PRs
never settled
> - Run data on staging shows two causes: runs that yield on purpose to
wait for a response (`external_chat_response_waiting`), and runs whose
final reply was refused (`responsePublication.state = failed`)
> - The first marked inline threads "ended without publishing" while a
later run posted the review; the second looked like presentation still
pending, forever
> - This pull request makes both settle: link the latest response, wait
while the task is open, and use the honest notice only when nothing was
published
> - The benefit is that every request comment ends in a useful final
state

## Linked Issues or Issue Description

Refs #22672, #22710

**Describe the bug**
- On #22732 the author replied on five review threads at once. Each
reply woke its own run; those runs yielded with
`external_chat_response_waiting`, and a later run posted the review.
Four threads still ended with "This turn ended without publishing a
final response."
- On #22658 (and the other merged PRs with stuck "Working on this…"),
the request's run finished `succeeded`/`committed` with no presentation
decision because its final reply publication failed after 6 attempts
(`publication_refused`). The settle logic treated that as presentation
pending and never settled the thread.

**Steps to reproduce**
1. An inline request's run yields with a response-wake continuation; a
later run publishes a review.
2. Or: an inline request's run finishes with `responsePublication.state
= "failed"` and no presentation decision.
3. The thread says "ended without publishing" (1) or stays "Working on
this…" forever (2).

**Expected behavior**
The thread links the latest published response, waits while the task is
still open, and otherwise ends with an honest notice.

## What Changed

- `githubLatestTaskResponseUrl`: the latest processed GitHub publication
(comment, formal review, assessment) for the task after the request
arrived.
- `githubResponseExecution`: when the request's run did not reply, link
that latest response if any. An inline request whose run deliberately
waits keeps waiting while the task is open. A run whose reply was
refused says so. The main PR comment keeps its passive-wait cancellation
(`mainPullResponse`).
- `nativePresentationPending` is false when `responsePublication.state =
failed`; new `responsePublicationFailed` column.
- Terminal sweep decision version is now `v3`, so requests parked under
v2 are read again once.

## Verification

- New integration tests (red on master, green here): links a waited
thread to a later response; settles a waited thread when the task
finishes with no response; settles a thread whose run's reply could not
be published.
- Updated `keeps per-request fallback outside the main GitHub PR review
wait`: waits while the task is open, then settles when done.
- `keeps native presentation idle until its committed GitHub outcome`
(main PR passive) still passes.
- `server/src/services/chat-channels/github/` and response comment
tests: 67 passed. GitHub integration group: 538 passed before the
main-PR scoping fix; the two affected tests pass after it.
- After deploy: re-measure the stuck rate on staging for comments
created after the deploy.

## Risks

- One extra indexed query per request that settles without its own reply
(to find the latest response). Settled requests leave the backlog.
- A waited inline thread stays "Working on this…" while its task is open
and nothing was published yet; that is the honest state.
- Separate, not fixed here: why the native finalizer refuses some final
replies (`publication_refused`).

## Model Used

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

## Checklist

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

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 13:36:30 -06:00
DottaandClaude Opus 5.5 7a9f099cc4 fix(maintenance): report an owner's exact offline migration refusal (#22801)
## Thinking Path

- Paperclip Cloud moves a hosted instance off its volume with an offline
maintenance process (`server/src/maintenance/ephemeral-migration*.ts`).
Each data owner either migrates its records or refuses with a fixed
code; the maintenance receipt reports that code to the Cloud enrollment
driver, which rolls back and records it.
- The workspace owner refuses as
`remote_workspace_migration_blocked:<reason,reason>` (for example
`...:workspace_recovery_unresolved` or
`...:archived_git_source_unavailable,local_source_unsafe_or_missing`).
- The receipt only accepted bare `[a-z_]` codes, so every workspace
refusal collapsed to `owner_migration_failed`, and the process logged
nothing. Two hosted enrollments rolled back with only
`owner_migration_failed`, leaving the admin unable to see which owner
refused or why.
- This change lets the owner's fixed reason list through (still
lowercase codes only, never free text) and logs the blocked phase and
code so the deployment log carries it too.

## Linked Issues or Issue Description

No existing issue; described in-PR per the bug report template. Related:
paperclipai/paperclip-cloud#1777 (Cloud side of the same fix).

### What happened?

Offline (maintenance) enrollment of two hosted instances rolled back.
The recorded reason was only `failure: "owner_migration_failed"` (Cloud
showed `phase: "unreported"`), and the maintenance deployment log
contained no refusal at all.

### Expected behavior

The receipt and the deployment log name the refusing owner and its fixed
reason codes, e.g.
`remote_workspace_migration_blocked:workspace_recovery_unresolved`.

### Steps to reproduce

Start `startEphemeralMigrationService` with a `migrate` that throws
`remote_workspace_migration_blocked:archived_git_source_unavailable,local_source_unsafe_or_missing`
(what `reserveMigration` throws for a blocked workspace); `GET /status`
reports `owner_migration_failed` and nothing is logged. The new test in
this PR does exactly this.

### Paperclip version or commit

7d26bdaa (deployed) and origin/master 4daeab5c76; the maintenance files
are identical.

### Deployment mode

Hosted (Cloud-managed), offline maintenance entry
`server/dist-runtime/ephemeral-migration.mjs`.

## What Changed

- `server/src/maintenance/ephemeral-migration-service.ts`: new
`ownerRefusalCode`. A bare `[a-z_]` code passes as before. Only an
allowlisted reason-list owner (`remote_workspace_migration_blocked`) may
carry `:reason,reason`; each reason must be a fixed lowercase code, a
malformed list keeps just the owner code, and more than 32 reasons keep
the first 31 plus `more_reasons_truncated`. Anything else reports
`owner_migration_failed`. Logs `{event: "ephemeral_migration_blocked",
phase, failure}` to stderr when blocked.
- `server/src/maintenance/ephemeral-migration-service.test.ts`: receipt
and log for a structured refusal with a workspace phase; sanitized log
for an arbitrary error; allowlist, malformed and truncation cases.

## Verification

- Red: new test failed on origin/master (`failure:
"owner_migration_failed"`).
- Green: `cd server && npx vitest run
src/maintenance/ephemeral-migration-service.test.ts` (16/16). `npx tsc
-p server/tsconfig.json --noEmit` clean.
- `pnpm verify` selected a broad server shard; stopped it after 30 min
per AGENTS.md section 7 and rely on CI for broad coverage.
- Not run: a live enrollment.

## Risks

- Low. Diagnostics only; migration and blocking behavior are unchanged.
The accepted shape cannot carry paths, URLs, secrets or stack text.
Rollback: revert.

## Model Used

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

## Checklist

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

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 13:36:00 -06:00
DottaandPaperclip 1a36a8f3c0 fix(e2e): wait for agreeing dependency run observations (#22802)
## Thinking Path

> - Paperclip lets people manage AI agents and their work.
> - A blocked task must start once after its blocker is complete.
> - The dependency journey checks this through task and agent run reads.
> - These independent reads can see the same run at different stages of
completion.
> - The collector can stop while the agent read still says `running`.
> - This pull request waits for both reads to agree before it saves the
finished and reopened points.
> - The test can then measure the completed work with the existing
strict rules.

## Linked Issues or Issue Description

**What happened?**

The dependency journey can report `dependency_one_automatic_resume`
after one correct automatic run. Its completion wait accepts the task
run as `succeeded` while the agent run read still says `running`. A
later read agrees, but the saved finished point remains split.

**Expected behavior**

Wait for matching task and agent run facts within the existing campaign
deadline. Keep the two observations independent. Fail if they never
agree.

**Steps to reproduce**

Use the flow fixture to return a completed task run and a lagging agent
run detail. Run the new `agent detail still running after task detail
completed` case against the old collector. It fails with
`dependency_one_automatic_resume`.

**Paperclip version or commit**

Base: `3ca9b6d471e100fe248c650f30453db4d3bc55fb`.
Related: #21732 added valid wake producers. That repair is already
present and does not address this read timing error.

## What Changed

- Compare task and agent run facts with the same normalized facts used
by the grader.
- Require agreement before the collector ends its completion wait and
after it reopens the result.
- Tag fixture projections explicitly, with separate agent lag counters
before and after reopening.
- Share the full settled predicate between both waits; agreeing stale
reads cannot count as completion.
- Add temporary and permanent cases for agent lag, task-only and
agreeing stale run views, task status, missing document, active locks
and native phase.
- Document the completion wait. Keep the grader, run budget and deadline
unchanged.

## Verification

- Red: the new lagging-read regression fails on the base collector with
`dependency_one_automatic_resume`.
- Green: three focused dependency suites pass, 126 tests. This includes
permanent disagreement, duplicate or unrelated runs, early execution,
history and output checks.
- Command: `node /tmp/pap5740-test-tools/node_modules/vitest/vitest.mjs
run --config /tmp/pap5740-test-tools/vitest.config.mjs`. The temporary
config selects
`tests/runner-e2e/product-journeys/task-dependency-resume*.test.ts`.
Tools: Vitest 5.0.3, Playwright 1.62.1 and Zod 4.
- `pnpm verify` could not run: the managed Git storage guard rejects
`git ls-files` with `paperclip_git_storage_limit`. CI must supply
broader checks.
- No new paid journey was run. Staging acceptance remains open. No
reviewed harness pin was changed.
- Follow-up commit: `16bb94c256769fe76b014e865259b742b35773ea`. The
reopened-only regression fails on the prior commit with
`dependency_one_automatic_resume`; it passes after this repair.
- Second follow-up: `45d60118fb36fd1f426e088f263d04c91484cfee`. Ten of
twelve new stale-state cases fail on `16bb94c`; all pass after sharing
the settled predicate.
- Exact finished-run binding:
`24d7b2f67a9f51ac6d996211f651a92772ff2a55`. Both reopened projections
must match the normalized saved finished-run facts. Two additional
agreeing-but-different run-facts cases fail before this change and pass
afterward.
- CI and Greptile passed on `16bb94c`; reviews also cleared `45d6011`.
Fresh CI and reviews are pending on `24d7b2f`.

## Risks

Low risk. A mismatch now uses the remaining campaign wait rather than
reaching the grader early. Permanent disagreement still fails at the
deadline. This change does not start another agent run, alter production
state, replace either independent read, or relax the grader.

## Model Used

OpenAI GPT-6 through Codex, with reasoning and code execution. The
runtime did not expose a more specific model ID.

## 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 13:34:14 -06:00
096060598d Add project pinning to the Coordinator sidebar (#22805)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Operators use projects to organize and review related tasks.
> - The Coordinator sidebar provides quick access to pinned items.
> - Project pins were available from Recents after a project visit.
> - This PR makes each project pinnable directly from More → Projects.
> - Pinned project rows expand in place so operators can open a recent
task from the sidebar.

## Linked Issues or Issue Description

**What existing behavior does this improve?**

Project navigation in the Coordinator workspace.

**Subsystem affected**

The board UI, specifically the Projects list and the left sidebar.

**Current behavior**

Users who review work by project must visit a project before they can
pin it from Recents. Project rows use a separate expand control. Hidden
sidebar controls also reserve space that can truncate project and task
names.

**Proposed behavior**

Give each Coordinator project row a pin action. Let users click the
sidebar project row to open or close its recent tasks, and give labels
the full available width while row controls are hidden.

**Reason and benefit**

Users can set up several project shortcuts from one page and reach the
tasks they review regularly from the sidebar.

## What Changed

- Add pin and unpin actions to Coordinator Projects rows using the
existing per-user browser preference.
- Make pinned and recent project rows expand and collapse their tasks.
Show closed and open folder icons for the two states.
- Match nested task spacing to adjacent navigation items and give nested
tasks a small indent.
- Reserve sidebar label space for controls when they are visible. Keep
the project icon and text centered in the Projects list.
- Scope project star and join or leave controls to Classic mode.

## Verification

- Run `pnpm --filter @paperclipai/ui typecheck`.
- Run the focused workspace preference, project query, and pinned
navigation Vitest files.
- Run `tests/e2e/project-pinning.spec.ts` in Chromium to verify pinning,
persistence, label width, expansion, and task navigation.
- In Chromium, open More → Projects and pin a project. Reload and
confirm the shortcut persists. Expand it using the mouse or keyboard,
open a nested task, reorder pins, and unpin from either the list or the
sidebar.
- Check label widths at rest and with hover, keyboard focus, and touch
controls. Check that Classic mode shows the star and membership
controls.

- GitHub Actions passed on `e96959bffe`, including build, typecheck, and
all eight browser shards. Two server shards passed on retry. [CI
run](https://github.com/paperclipai/paperclip/actions/runs/45466386598)
- Greptile gave the same commit 5/5 with no open review threads.
[Review](https://github.com/paperclipai/paperclip/pull/22805#issuecomment-7141648518)

## Risks

- Clicking a project row in the Coordinator sidebar now opens its task
list in place. Users can still open the full project from the Projects
page.
- This UI change reuses the existing browser preference and project task
query. It requires no database migration.

## Model Used

OpenAI Codex with GPT-6.2-Sol. Used local code execution, Chromium, and
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
- [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 11:31:38 -08:00
Dotta cffd17e78a perf(ci): Phase 3 PR CI under 3m — 4x Runner support, 12x E2E, incremental TS 7 cache, pure-Node postinstall, and rebalanced shards (#22804)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Pull request CI verifies every change before merge across build,
typecheck, server tests, Runner tests, and Playwright E2E shards.
> - After Phase 1 (#22679) and Phase 2 (#22729), full-fanout PR CI still
takes 9m45s wall-clock on 4-core AWS runners because of five
bottlenecks: an unsharded 7m22s `Runner support suite`, stale
server/chat/Runner shard duration manifests plus newly landed SSH/soak
whales, 28s of `pnpm -r run postinstall` replay on every job, cold
server/UI typecheck and single-build overhead, and 3 oversized (>180s)
Playwright E2E specs across 8 shards with double-start Postgres template
boot.
> - Docs-only prose edits under `doc/**` and `docs/**` also fanned out
to 66 CI jobs because only three doc paths bypassed global dependencies.
> - This pull request shards `Runner support suite` 4 ways with `pool:
"threads"`, shards E2E 12 ways after splitting the 3 oversized specs and
removing double-start Postgres boot, adds pure-Node workspace
postinstall replay, adds read-only master-warmed incremental TS 7 and
Runner dist caches, rebalances all server/chat/Runner duration
manifests, demotes 48 new non-invariant soak whales to nightly, and
routes audited prose docs without triggering 66-job storms.
> - The benefit is driving ordinary PR CI toward under 3 minutes
wall-clock while preserving every invariant check, cache boundary, and
full master/nightly test coverage.

## Linked Issues or Issue Description

Refs #22679
Refs #22729

**What existing behavior does this improve?**
Pull request CI wall-clock latency across
`.github/workflows/pr-trusted.yml`,
`.github/workflows/release-verify.yml`,
`.github/actions/setup-ci-dependencies/action.yml`, typecheck
orchestration, Vitest/Runner lanes, and Playwright E2E shards.

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

**Current behavior**
Full-fanout PR CI takes 9m45s on 4-core runners (run `45440355579`),
dominated by `Runner support suite` (7m22s), `e2e shards` (5m02s–6m24s),
`General tests (server/chat)` (5m37s–6m01s), `Verify Paperclip Runner
(vitest package)` (6m25s on stale manifests), `Typecheck` (4m13s–6m30s),
`Build` (~4m), and 28s of `pnpm -r postinstall` per job. Prose edits
under `doc/**` trigger 66 jobs.

**Proposed behavior**
Shard `Runner support suite` (4x) and `e2e_shards` (12x), split the 3
oversized E2E specs, boot disposable E2E Postgres in a single
non-durable start, replay workspace `postinstall` in pure Node (<1s),
cache prebuilt Runner dist and TS 7 `.tsbuildinfo` from canonical
`master` pushes (read-only in PRs), use emit-only server compile in
ordinary PR `Build`, rebalance all shard duration manifests, demote 48
new non-invariant soak whales to nightly, and route audited prose docs
cleanly.

## What Changed

- **Pure-Node postinstall replay
(`scripts/replay-workspace-postinstall.mjs`,
`.github/actions/setup-ci-dependencies/action.yml`):** Replaces the 28s
`pnpm -r --if-present run postinstall && pnpm run postinstall` call on
every CI job with a pure-Node parallel runner (~0.84s locally) with
fallback for older checkouts.
- **4-way sharded `Runner support suite` + `threads` pool
(`.github/ci-task-matrix.json`, `.github/workflows/pr-trusted.yml`,
`tests/runner-e2e/run-unit.mjs`, `tests/runner-e2e/vitest.config.ts`):**
Shards Vitest and `node:test` suites 4 ways (`--shard-index 0..3
--shard-count 4`) and switches `tests/runner-e2e` to `pool: "threads"`
with CPU-aware `maxWorkers` while preserving `isolate: true`.
- **12-way E2E shards, single-start E2E Postgres boot, and 3 oversized
spec splits (`tests/e2e/start-e2e-server.ts`, `tests/e2e/*.spec.ts`,
`tests/e2e/playwright.config.ts`, `scripts/e2e-shard.mjs`,
`scripts/e2e-shard-durations.json`, `.github/ci-task-matrix.json`):**
Boots cold ephemeral E2E Postgres in one `initdb --no-sync` +
non-durable `postgresql.conf` start overlapped with server module
import; splits `agent-chat-projects`, `chat-adapters-ui-providers`, and
`chat-adapters-ui-messaging` cleanly with zero tests removed; balances
all 54 specs across 12 shards (6.8s spread).
- **Incremental TS 7 typecheck & Runner dist caching
(`server/scripts/typecheck-layers.mjs`, `scripts/ci-typecheck-lane.mjs`,
`scripts/typecheck-test-programs.mjs`,
`scripts/typecheck-test-projects.mjs`,
`.github/workflows/pr-trusted.yml`,
`.github/workflows/release-verify.yml`):** Preserves portable
`.tsbuildinfo`/`.d.ts` with `layer-map.json` invalidation and
stale-declaration pruning, wires read-only `runner-dist-v1` and
`typecheck-incremental-v1` restores in `pr-trusted.yml` (zero
`actions/cache/save`) paired with canonical-`master`-only guarded
writers in `release-verify.yml`, skips redundant Runner Rust `cargo
check` on TS-only shared PRs, and uses LPT scheduling with concurrency 3
(4-core) / 4 (8-core).
- **Emit-only PR `Build` & audited prose doc routing
(`.github/workflows/pr-trusted.yml`, `.github/scripts/ci-inputs.mjs`):**
Passes `PAPERCLIP_TSC_EMIT_ONLY=1` on ordinary PR `Build` jobs (full
`pnpm build` on `full-ci` / `master`), and classifies audited prose
Markdown under `doc/**` and `docs/**` as `guidance` / `historical` while
keeping `docs/api/**`, JSON/TS fixtures, `maps/**`, and unknown files
fail-closed.
- **Rebalanced shard manifests & new soak demotions
(`scripts/ci/nightly-only-suites.json`,
`scripts/*-shard-durations.json`,
`packages/paperclip-runner/scripts/vitest-lane-durations.json`,
`packages/paperclip-runner/vitest.config.ts`,
`packages/paperclip-runner/scripts/vitest-sequencer.mjs`):** Demotes 48
newly landed/grown non-invariant soak suites (including 4 real-SSH
integration suites) to nightly, refreshes all 4 timing manifests from
live CI measurements (0.1s–0.6s LPT skew), and scales Runner package
Vitest CI `maxWorkers` to 3 on 4-core / 6 on 8-core.

## Verification

- `node --test .github/scripts/tests/*.test.mjs
scripts/__tests__/runner-release-crate-cache.test.mjs
scripts/__tests__/public-install-closure.test.mjs
scripts/__tests__/merge-queue-checks-workflow.test.mjs
scripts/__tests__/e2e-shard.test.mjs
scripts/__tests__/ci-typecheck-lane.test.mjs
scripts/__tests__/run-vitest-stable-shard.test.mjs
scripts/__tests__/run-vitest-stable-pr-mode.test.mjs
scripts/__tests__/runner-vitest-package-lanes.test.mjs
scripts/typecheck-test-programs.test.mjs
scripts/check-test-budget.test.mjs
scripts/ci/test-selection-pr-timings.test.mjs
scripts/ci/test-selection-timings.test.mjs` — **973/973 PASS**
- `node scripts/check-test-budget.mjs --base origin/master` — **PASS**
(`609` nightly suites validated, zero protected invariants demoted)
- `node scripts/check-maps.mjs` — **PASS**
- `pnpm exec vitest run --config tests/runner-e2e/vitest.config.ts
tests/runner-e2e/source-sdk-public-inputs.test.mjs
tests/runner-e2e/unit-launcher.test.mjs` — **PASS**
- `pnpm --filter @paperclipai/paperclip-runner exec vitest run
scripts/vitest-sequencer.test.mjs` — **PASS**
- `cd server && node ../node_modules/vitest/vitest.mjs run
scripts/typecheck-layers.test.mjs
scripts/typecheck-layers-incremental.test.mjs` — **56/56 PASS** (real TS
7.0.2 incremental soundness tests)
- `node scripts/run-tsc.mjs -p tests/e2e/tsconfig.json --noEmit && node
scripts/run-tsc.mjs -p tests/tsconfig.playwright.json --noEmit && pnpm
run test:e2e:runner:typecheck` — **0 errors**
- Live Playwright smoke passed across all 6 split E2E spec files on the
cold non-durable Postgres boot path
(`PAPERCLIP_TEST_POSTGRES_TEMPLATE=0`).
- Live sharded `tests/runner-e2e` runs passed under `pool: "threads",
maxWorkers: 4` (shard `1/4` 172/172 PASS; shard `2/4` all Vitest + 65/65
`node:test` PASS).

## Risks

- **Cache invalidation on incremental typecheck / Runner dist:**
Mitigated by exact-key hashing (including
`packages/{shared,adapter-utils,plugins/sdk}/src/**` and
`packages/paperclip-runner/spec/**`) with no `restore-keys:` on
`runner-dist-v1`, SHA-256 self-validation inside
`prepare-runner-vendor.mjs`, `layer-map.json` invalidation + stale
`.d.ts` pruning in `typecheck-layers.mjs`, and read-only PR restores
(only canonical `master` pushes save caches).
- **Shard rebalancing & soak demotions:** All demoted suites remain in
`nightly-only-suites.json` and run on `full-ci` / `master` / nightly;
`check-test-budget.mjs` enforces zero protected invariants are demoted.
- **Workflow security boundaries:** `ci-routing.yml`, `pr.yml`,
`CODEOWNERS`, and all `runs-on:` expressions are unchanged;
`pr-trusted.yml` performs zero `actions/cache/save` calls.

## Model Used

- Google Gemini (Antigravity agent swarm) with extended reasoning, tool
use, and local code/test execution across 6 parallel worker roles
(`ci-pipeline`, `vitest-runner`, `server-prune`, `e2e-opt`,
`typecheck-opt`, `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 13:25:46 -06:00
3ca9b6d471 refactor(plugin-sdk): remove archivedState from the resume result (#22443)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Native Runner sessions can run in a remote environment task that a
plugin provider owns
> - A provider can relaunch a parked Runner as the next run, and it
reports the result to Core
> - The resume result could carry `archivedState`, so Core could check
that the park was a settled cut
> - #22442 makes the provider the authority on the park, and Core stops
reading `archivedState`
> - This pull request removes the field from the SDK result schema
> - The benefit is a smaller provider contract with no unused fields

## Linked Issues or Issue Description

Refs #22442

**What existing behavior does this improve?**

The environment task resume result contract in the plugin SDK.

**Subsystem affected**

`packages/plugins/sdk` (environment tasks), and the tests in
`server/src/services/native-runtime` that build resume results.

**Current behavior**

After #22442, a resumed relaunch result can carry an optional
`archivedState`. Core accepts it and does not read it.

**Proposed behavior**

The resume result has no `archivedState` field. The strict schema
refuses it.

**Reason and benefit**

The field has no reader. Removing it keeps the contract to the fields
that Core uses.

**Breaking changes**

A provider that still sends `archivedState` on a resume result fails the
schema check, and the relaunch fails. Deploy this with or after the
provider change that stops sending the field.

**Additional context**

Stacked on #22442.

## What Changed

- SDK: removed `archivedState` from the `resume` result schema, and
simplified the relaunch check in `parseEnvironmentTaskResult`.
- SDK test: a relaunch result with `archivedState` now fails; one
without it passes.
- `plugin-runner-task.test.ts`: removed the field from the fixtures, and
removed the test that checked Core ignores it.
- `plugin-runner-release-resume.integration.test.ts`: the fixture
provider no longer returns the field.
- `doc/plugins/PLUGIN_ENVIRONMENT_TASKS.md`: removed the note about the
field.

## Verification

- `pnpm run typecheck` in `server` (builds all dependent packages):
pass.
- `pnpm vitest run
src/services/native-runtime/plugin-runner-task.test.ts` in `server`: 116
passed.
- `pnpm vitest run tests/environment-task-release-resume.test.ts` in
`packages/plugins/sdk`: 48 passed.
- I did not run the embedded-Postgres integration suite locally. CI runs
it.

## Risks

- A provider that still sends the field makes the relaunch fail. Deploy
this with or after the provider change that stops sending it. It can
ship in the same deploy as #22442.
- Low risk otherwise: the change removes an unused optional field.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), through Claude Code with tool use
(shell, file edit, code search). Extended thinking on.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [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: Paperclip <noreply@paperclip.ing>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 10:25:32 -08:00
0b2acfb956 refactor(runner): let the provider decide whether a released Runner relaunches (#22442)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Native Runner sessions can run in a remote environment task that a
plugin provider owns
> - After a turn, the provider can park the Runner, and the next run can
relaunch it from the saved state
> - Core kept its own local record of each released Runner, and the
provider kept its park record too
> - Core lost its copy when the local session directory was not durable.
Then Core restored from a checkpoint although a park existed, and the
turn was slower
> - This pull request makes the provider the only authority on the park.
Core resumes the source from its durable checkpoint, and the provider
answers "resumed" or "unavailable"
> - The benefit is fewer missed relaunches, and less code in Core

## Linked Issues or Issue Description

**What existing behavior does this improve?**

The relaunch of a parked Runner for the next run of a native session.

**Subsystem affected**

Native runtime: `server/src/services/native-runtime`, the Runner control
plane in `packages/paperclip-runner`, and the environment task SDK.

**Current behavior**

Core writes a released-Runner record (source identity, task id and scope
digest) to the local session directory when a release completes. Core
relaunches a parked Runner only when that record exists. Core also
checks the archived Runner state on the provider's relaunch reply. When
the local directory is gone (for example, after the server process
restarts on a new host), Core restores from a checkpoint into a fresh
task, although the provider still has the park.

**Proposed behavior**

Core resumes the source identity from its durable controller checkpoint
on the lease's current task. The provider decides from its own park
record. When no park of that source exists, the provider answers
`unavailable`, and Core starts a fresh task from the saved session, as
it does today for other unavailable answers.

**Reason and benefit**

One record for one fact. Core no longer needs local state to relaunch,
so more runs relaunch. The change removes about 160 lines.

**Breaking changes**

A provider must answer `unavailable` when it has no park for the
requested source. A provider that answers with an error instead makes
the resume fail. The `archivedState` field on a resumed relaunch result
becomes optional. Providers can continue to send it; Core does not read
it.

**Additional context**

Reattach to a live Runner process in the same server is not changed. A
relaunch after a restart still requires the process configuration to
match, because the relaunch reuses the parked launch. A changed
configuration starts a fresh task.

## What Changed

- Removed the local released-Runner record: its writer, its readers, the
scope digest, and the resume and retire callbacks that cleared it.
- Derived the relaunch source from the durable Runner identity. Kept the
check that the task is the lease's current task.
- After a restart, Core takes the released source from the durable
identity for every provider that releases tasks: one that relaunches the
parked Runner, and one that hands it over.
- Added a test that a checkpoint saved with the old released-Runner
record still loads.
- When a restart recovery resumes a released source and the provider
answers `unavailable` with the task stopped and its state saved, Core
now starts a fresh task from the saved session, as it does for a
relaunch. The fallback finishes the old task's startup context before it
inspects the replacement task. An executor test covers this path.
- Updated the SDK source pin in
`tests/runner-e2e/source-sdk-public-inputs.json`.
- Stopped the check of the archived state on the relaunch reply. Removed
`isSettledReleasedRunnerCut` and the resume `settled` hook.
- SDK: a resumed relaunch result no longer requires `archivedState`.
- Updated `doc/plugins/PLUGIN_ENVIRONMENT_TASKS.md` and the tests.

## Verification

- `pnpm run typecheck` in `server` (builds all dependent packages):
pass.
- `pnpm vitest run
src/services/native-runtime/plugin-runner-task.test.ts
src/services/native-runtime/remote-warm-session-recovery.test.ts` in
`server`: 147 passed.
- `pnpm vitest run
src/services/native-runtime/native-session-executor.test.ts -t "releases
settled|accepts only the
attached|released|relaunch|warm|unavailable|recover"` in `server`: 594
passed.
- `runnerd-codex-transport.test.ts` in `packages/paperclip-runner`: 337
passed.
- SDK release and resume tests in `packages/plugins/sdk`: 48 passed.
- `runnerd-codex-transport-release-resume.test.ts -t relaunched` in
`packages/paperclip-runner`: 3 passed. `pnpm run typecheck` in
`packages/paperclip-runner`: pass.
- `tests/runner-e2e/source-sdk-public-inputs.test.mjs`: 13 passed.
- `plugin-runner-release-resume.integration.test.ts -t "completes claude
runs through a retained adopted process"`: pass. I did not run the rest
of the two embedded-Postgres integration suites locally. CI runs them.

## Risks

- A provider that does not answer `unavailable` for a missing park makes
the resume fail. Deploy the provider change first, or in the same deploy
before this Core version takes traffic. This PR and #22443 are one stack
and can ship in one deploy.
- A server restart now relies on the existing unavailable-reuse fallback
to start a fresh task. Tests cover this path.
- Medium risk overall: the change is in the warm-session path. The cold
path is not changed.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), through Claude Code with tool use
(shell, file edit, code search). Extended thinking on.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [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: Paperclip <noreply@paperclip.ing>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 10:25:32 -08:00
DottaandClaude Opus 5.5 8b616b949d fix(connections): drop MCP wording and the MCP guide link from Google Workspace setup (#22793)
<!-- Write all pull request text in Simplified Technical English
(ASD-STE100): short sentences, one instruction per sentence, simple
approved vocabulary, and the active voice. -->

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Agents use Google Workspace through the built-in Google Workspace
connection
> - Since #22634, Gmail, Drive, Docs, Sheets, Slides, and Calendar run
on Paperclip's own REST tools, not on Google's hosted MCP servers
> - The connect screen still showed "Secure MCP sign-in" and a "Review
requirements" link to Google's MCP servers guide
> - This text is wrong for this connection, it is internal jargon, and
Google's OAuth reviewers read this screen
> - This pull request removes the MCP wording and the MCP guide link
from Google Workspace setup and from its audit details
> - The benefit is that users and reviewers see only true, plain text
for this connection

## Linked Issues or Issue Description

Refs #22634

**What happened?**

On a Cloud workspace, the Google Workspace connect page showed the
subtitle "Secure MCP sign-in" while the sign-in opened and after it
failed to open. The setup page also showed a "Review requirements" link
to `developers.google.com/workspace/guides/configure-mcp-servers`. On a
self-hosted instance, the "How to set up a Google OAuth client" link
went to the same MCP servers guide. Audit details for a Google REST call
showed "Transport: mcp_remote" and "MCP method: tools/call".

**What did you expect to happen?**

The connect page says "Secure sign-in". The Paperclip-managed method on
Cloud has no requirements link, because the user has no requirements to
review. On a self-hosted instance, the customer-owned client method
links to Google's OAuth client guide. Audit details for a Google REST
call do not show MCP terms.

**Steps to reproduce**

1. Turn on the Google Workspace connector in **Settings →
Experimental**.
2. Open **Apps** and choose **Google Workspace**.
3. Start the sign-in, then close or block the sign-in window.
4. Before this change: the header shows "Secure MCP sign-in", and the
setup step shows "Review requirements" with a link to Google's MCP
servers guide.

## What Changed

- `ui/src/features/connections/ConnectionSetupFlow.tsx`:
`OAuthConnectStateScreen` shows "Secure sign-in" for a curated app. A
server that the user pasted as an MCP server keeps "Secure MCP sign-in".
This is generic: there is no Google-specific code.
- `packages/shared/src/app-definitions/google-workspace.json`: remove
the top-level `docsUrl` (the MCP servers guide). The Paperclip-managed
method now has no "Review requirements" link. The customer-owned
method's `consoleLinks.docs` is now Google's OAuth client guide
(`create-credentials#oauth-client-id`). The "Review requirements" link
and the self-hosted "How to set up a Google OAuth client" link both use
it. Its guidance text names the Gmail, Drive, Docs, Sheets, Slides, and
Calendar APIs instead of "the Google Workspace MCP APIs". This file is a
reviewed definition: `scripts/ingest-app-definitions.mjs` copies it
as-is, so a regeneration keeps the fix.
- `server/src/services/tool-gateway.ts`: an audit record for a Google
Workspace REST call no longer has `mcpMethod`.
- `ui/src/pages/tools/AuditTab.tsx`: audit details show the connection
type label ("Remote HTTP") as "Type" instead of the raw `mcp_remote`
value. This uses the same label as the connection's "Connection
details".
- `doc/connections/GOOGLE-WORKSPACE.md`: the self-hosted section links
Google's OAuth client guide.
- `tests/runner-e2e/source-sdk-public-inputs.json`: refreshed pinned
inputs.

## Verification

- Red first, then green:
- `packages/shared/src/google-workspace-setup-links.test.ts`: no Google
Workspace method links the MCP servers guide, the managed method has no
requirements link, the customer method links the OAuth client guide, and
method text has no "MCP". It failed 4/4 before the fix.
- `ui/src/features/connections/OAuthConnectStateScreen.google.test.tsx`:
in the preparing, opening, and "couldn't open the sign-in window"
states, the Google Workspace screen shows "Secure sign-in", no "MCP",
and no link to `configure-mcp-servers`. A pasted server keeps "Secure
MCP sign-in". It failed 3/4 before the fix.
- `server/src/__tests__/google-workspace-rest-transport.test.ts`: the
Gmail REST audit record has no `mcpMethod`. It failed without the server
change.
- `npx vitest run` for shared app definition tests (67 passed),
`ui/src/pages/tools` and `ui/src/pages/apps/app-detail` (121 passed),
and the server REST transport file (53 passed).
- `tsc --noEmit` for `server` and `ui`: no new errors.
- `pnpm verify` exits 2 because a doc under `doc/connections` is a
global CI input. Required CI supplies the broad coverage.

## Risks

- Low risk. Text and link changes only, plus one optional audit field.
- Other curated OAuth apps now show "Secure sign-in" instead of "Secure
MCP sign-in" on the sign-in state screen. The new text is true for every
curated app.
- Audit details for all connectors show "Type: Remote HTTP" instead of
"Transport: mcp_remote".
- Saved Google Workspace connections still show
`https://workspacemcp.googleapis.com/mcp/v1` as the address in
"Connection details". It is the stored connection identity. This pull
request does not change stored data.

## Model Used

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

## Checklist

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

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 12:01:21 -06:00
d01d3c40ad fix(ui): defer the Connectors announcement until a return visit (#22790)
## Thinking Path

> - People use Paperclip to manage AI agents at work.
> - New users now meet their agent in chat after setup.
> - The Connectors card previously checked for an open onboarding task.
> - Chat-first onboarding creates no such task, so the card could appear
three seconds into a first visit.
> - This change holds that promotion until the person returns after 30
minutes of inactivity.

## Linked Issues or Issue Description

Refs: #19514, #22077

**What happened?**

On master at `11cfe0910d`, a new user could see the Connectors card in
their first agent chat.

**Expected behavior**

The card stays hidden through the first visit and can appear when the
user returns after a 30-minute gap in activity.

**Steps to reproduce**

With the Connectors announcement active, finish chat-first onboarding in
a fresh browser profile and wait for the announcement delay.

## What Changed

- Track the first visible board visit per account in browser storage.
Local input and visits in other tabs extend the first session. After the
first qualifying return, the browser remembers eligibility and stops
tracking input.
- Apply this rule to the published Connectors announcement ID. The
existing checks for dismissal, open dialogs, and legacy onboarding tasks
still apply.
- Exercise the onboarding chat, reload, idle return, account isolation,
and activity in another tab.

## Verification

- Before the fix, the Vitest regression displayed
`2026-09-14-connectors` on the first visit.
- The announcement and workspace identity Vitest suites passed locally
(28 tests). The UI typecheck passed.
- Chromium passed all four tests in `announcement-first-session.spec.ts`
and `announcement-placement.spec.ts` against a local test server.
- A second red-green regression covers dismissal in another browser
while the first tab sits idle. The return triggers a fresh check and
keeps the card hidden until it succeeds.
- At `8fab1932fa`, GitHub reported 73 successful checks and three
skipped checks. [CI
run](https://github.com/paperclipai/paperclip/actions/runs/45449353624)

## Risks

A new browser profile or cleared site data starts the visit history
again. Storage failures keep the Connectors card hidden. Existing users
start accumulating visit history when they first use this version.

## Model Used

OpenAI Codex, GPT-6.2 Astra (`gpt-6.2-astra`), with shell, Vitest, and
Playwright.

## 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 09:57:37 -08:00
DottaandClaude Opus 5.5 6385c171fa fix(connections): show only the privacy policy link in the Google Workspace picker (#22795)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The built-in Google Workspace connection lets agents use Gmail,
Drive (with Docs, Sheets and Slides) and Calendar
> - Before Google consent, the user chooses services in the "Connect
Google Workspace" picker
> - On Nov 17, #21998 added two text sections to this picker: "What
agents can do" and "How your data is used"
> - On Nov 24, the owner decided that this screen must show only the
privacy policy link and no other explanatory text
> - This pull request removes the two sections and keeps the privacy
policy link directly under the service rows
> - The benefit is a short picker that matches the owner decision, for
new setup and reconnect, in the Apps flow and the task-hosted flow

## Linked Issues or Issue Description

Refs #22634

**What happened?**
The "Connect Google Workspace" picker shows a "What agents can do"
section and a "How your data is used" section with bullet sentences. The
text changes with the selected services. The owner does not want this
text on the screen.

**What did you expect to happen?**
The picker shows the title, the three service rows (each with its access
select and switch), the privacy policy link, and Cancel / Continue. It
shows no other explanatory text for any selection.

**Steps to reproduce**
1. Open Apps and start a Google Workspace connection, or reconnect an
existing one.
2. Look at the service picker with all services on, with read only, and
with one service on.
3. See the two text sections above the footer.

## What Changed

- `ui/src/features/connections/GoogleWorkspaceServices.tsx`: remove the
`DataUseDisclosure` block. The privacy policy link ("Read our privacy
policy, including how we meet Google's Limited Use requirements",
`https://paperclip.ing/privacy`, new tab) now sits directly under the
service rows for every selection, including no selection. The "Select at
least one service to continue." status stays. The screen-reader
description "Choose the Google services to connect." stays. The URL
constant `GOOGLE_WORKSPACE_PRIVACY_POLICY_URL` moves into this file.
- `ui/src/features/connections/googleWorkspaceDisclosure.ts`: deleted.
Nothing else used the copy builder.
- `ui/src/features/connections/GoogleWorkspaceServices.test.tsx` (new;
the earlier suite was removed in #22729): for all services read & write,
all read only, one service, and no service, the dialog has no section
headings, no lists and none of the removed sentences. The link has its
text, href and new-tab target. The dialog keeps its accessible
description. Continue stays disabled with no service and submits the
chosen services.
-
`ui/storybook/stories/connection-setup/google-workspace-services.stories.tsx`:
the `ProductionPickerReadOnly` play test now checks that the removed
text is absent and the link is present.
- Docs: `doc/memory/google-connector-memory.md` gets a dated Nov 24
decision row with the risk.
`doc/plans/2026-11-17-google-workspace-production-checklist.md` no
longer claims a disclosure in the picker.
`doc/plans/2026-11-17-google-workspace-code-fixes.md` item 1 records the
removal.

The dialog now contains, from top to bottom: the Google Workspace logo
and the title "Connect Google Workspace"; Gmail, Drive ("Docs, Sheets,
and Slides") and Calendar rows, each with a "Read only / Read & write"
select and a switch; the privacy policy link; the empty-selection status
(only with no service on); Cancel and Continue in one footer row.

## Verification

- Red first: the new test ran against the old picker and 4 of 5 tests
failed (removed text present; link absent with no selection). After the
change all 5 pass.
- `cd ui && npx vitest run src/features/connections
src/pages/apps/AppDetail.test.tsx src/pages/apps/AppsConnect.test.tsx`:
8 files, 55 tests pass.
- `cd ui && node ../scripts/run-tsc.mjs -b`: no errors.
- `node scripts/check-token-gates.mjs`: all gates clean. `node
scripts/check-test-budget.mjs --files
ui/src/features/connections/GoogleWorkspaceServices.test.tsx`: pass.
`node scripts/storybook-catalog.mjs`: pass.
- `pnpm verify` exits 2 (a global CI input changed:
`doc/memory/google-connector-memory.md`). Required CI supplies the broad
coverage.
- Headless Playwright against Storybook dev, `ProductionPicker` at
1280x900 (dark and light) and `ProductionPickerMobile` at 375x812: the
dialog text is only the title, the rows, the link, and Cancel /
Continue. No horizontal scroll at 375 px. The link sits under the last
row with the normal dialog gap, and the footer follows it.
- Before: see the screenshots in #21998. After: the same dialog without
the two text sections.

## Risks

- Policy risk: Google's user data policy may expect a disclosure inside
the product, before consent, that says what data the app uses and how. A
privacy policy link alone may not satisfy a Google reviewer. This is a
recorded owner decision. If a reviewer asks, restore a short statement
above the link. The memory doc and the production checklist record this
risk.
- Low code risk. The change is UI-only. Selection, requested scopes,
OAuth and saved state do not change.

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

## Model Used

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

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] 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 11:47:32 -06:00
4daeab5c76 Add count, newest-first and lean run reads to customer-success inspection (#22781)
<!-- Write all pull request text in Simplified Technical English
(ASD-STE100): short sentences, one instruction per sentence, simple
approved vocabulary, and the active voice. -->

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Paperclip Cloud can inspect a tenant stack read-only through the
customer-success inspection API
> - That API can only list rows in id order. It has no totals, and each
run row holds large JSON columns
> - A customer-success agent must page every run of a stack to find the
latest run or the failed-run total
> - That is too slow and too large for a refresh across many stacks
> - This pull request adds a `count` operation, a creation-time `order`
for lists, and a lean `summary` view for runs
> - The benefit is one small read per metric, with the same read-only,
company-scoped rules

## Linked Issues or Issue Description

**Subsystem affected**

Server: the customer-success inspection API (`/api/customer-success/v1`)
and its shared query contract.

**Problem or motivation**

Customer-success inspection reads cannot answer summary questions. To
get the latest run, the run count or the failed-run count, a reader must
page through every run. Each run row can be hundreds of KB, because it
holds the result, usage, context snapshot and runner profile.

**Proposed solution**

Add read-only summary reads to the inspection contract: a `count` that
groups by status, a newest-first or oldest-first `order` for `list`, and
a `summary` view of runs without the large JSON columns.

**Alternatives considered**

Paging all runs with a smaller page size. That still reads every large
row. A new aggregated endpoint outside the reader catalog. That would
skip the existing catalog, permit and transaction rules.

## What Changed

- `packages/shared/src/customer-success.ts`: add the `count` operation,
`order` (`newest`/`oldest`, `list` only), `view` (`summary`, `runs`
list/get only), `InspectionCount`, and `inspectionReadPath()`. The
parser rejects these fields where they do not apply.
- `server/src/services/customer-success-inspection.ts`: `count` returns
`{total, byStatus}` (grouped by the reader's `status` column, or
`byStatus: null`). `order` sorts by `createdAt`, then id. `view:
"summary"` selects the `RUN_SUMMARY_COLUMNS` allowlist and adds
`durationMs`. All reads stay in the same read-only, repeatable-read
transaction and keep the existing run redaction.
- `server/src/routes/customer-success.ts`: serve the same handler on
`/read` and the new `/read-v2`. `/read` refuses queries that use the new
features. A tenant without `/read-v2` answers 404, so Cloud fails closed
with `tenant_inspection_version_unsupported`.
- `server/src/__tests__/customer-success.test.ts`: tests for counts,
company scope, newest-first paging, the summary allowlist and duration,
parser bounds, and the path split.
- `server/src/__tests__/customer-success-cloud.test.ts`: the registry
double now has the batch reads (`getStacks`, `getAccounts`) that the
current Cloud broker uses. The test also runs a count and a newest-first
summary read end to end.
- `server/src/__tests__/openapi-routes.test.ts`: list `/read-v2` with
the other inspection protocol routes.
- `doc/CUSTOMER-SUCCESS-INSPECTION.md`: document the summary reads and
the path split.

## Verification

- `cd server && pnpm exec vitest run
src/__tests__/customer-success.test.ts
src/__tests__/openapi-routes.test.ts
src/__tests__/customer-success-run-liveness.test.ts`: 78 tests pass.
- Red check: the new count/order/summary test fails against the previous
service (`Unsupported inspection operation`).
- Coordinated qualification with a local build of the Cloud broker
branch: `PAPERCLIP_INSPECTION_CLOUD_DIST=… pnpm exec vitest run
src/__tests__/customer-success-cloud.test.ts` passes, including the
count and newest-first summary reads over `/read-v2`.

## Risks

- Low risk. The new features are read-only and use the existing catalog,
company boundary, permit check and read-only transaction.
- The summary view is an allowlist. A new run column stays out of the
summary until someone adds it.
- Mixed versions are safe in both orders. An older Cloud never sends the
new fields. A newer Cloud sends them only to `/read-v2`, and an older
tenant answers 404 there.
- No migration.

## Model Used

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

## Checklist

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

> - Paperclip is the open source app people use to manage AI agents for
work
> - "Set it up with your agent" screens give the person's own agent a
setup checklist to fill in, shown live on the page (#22626, AWS role
setup first)
> - Testing it end to end on staging, the agent's updates appeared
within 0.3–0.6 seconds and the page showed "Your agent set up AWS" with
the role ARN, then a few seconds later replaced it with a blank new
checklist
> - When the live connection reconnects or the tab becomes visible
again, the app refreshes every query on screen. The checklist's handoff
query refetched, found no checklist in storage (a finished one is
removed so it is never reused), and created a new one
> - This pull request makes a refetch keep the checklist the page
already has; only Start again, or a finished checklist from an earlier
visit, makes a new one
> - The benefit is that a finished setup stays on screen with its
summary until the person moves on

## Linked Issues or Issue Description

Refs #22626 (the setup checklist this fixes).

**Subsystem affected**
Connections (agent-guided setup), UI.

**Problem or motivation**
On paperclip.staging, after the agent finished, the AWS setup step
showed "Your agent set up AWS" and the role ARN to paste, then about 7
seconds later went back to "Paste the prompt into your agent" with a
new, empty checklist. The page's network log showed a second `POST
/api/companies/{companyId}/agent-setup-progress`. The person loses the
role ARN they were about to copy.

**Proposed solution**
The handoff query's fetch returns the handoff already in the cache
unless the page asked to replace it (`renew`). Creating a checklist
stays a deliberate action.

**Alternatives considered**
- Excluding the handoff key from the live reconcile
(`LIVE_EVENT_FREE_QUERY_KEYS`): covers that one caller but not any other
broad invalidation. Guarding the fetch covers them all.
- Keeping a finished checklist in storage: it would then be reused by a
later visit, which #22626 deliberately avoids (a finished checklist
takes no more updates).

## What Changed

- `ui/src/components/AgentSetupProgress.tsx`: the handoff query's
`queryFn` returns the cached handoff unless `renew` set a one-shot
`replacing` flag.
- `ui/src/components/AgentSetupProgress.test.tsx`: regression test. A
checklist finishes, then every active query is invalidated (as the live
reconcile does); the checklist is created once and "Your agent set up
AWS" with the role ARN stays.

## Verification

- New test fails on master (`create` called twice) and passes with the
fix (red/green).
- `AgentSetupProgress.test.tsx` and `AwsRoleSetup.test.tsx`: 26 passed.
UI typecheck clean.
- Staging reproduction (before this fix), paperclip.staging on 980caf1:
the agent's requests with only the prompt's token (no Paperclip sign-in)
were accepted through the Cloud front door: 401 without the token, 200
for set/update/finish, 409 for an update after finishing. The page
showed each update 603 ms, 567 ms and 326 ms after the request, then
replaced the finished checklist about 7.5 s later. To re-run on staging
after deploy.

## Risks

- Low. One query's fetch function; creation paths (first open, Start
again, earlier-visit renewal, another account) keep their tests.

## Model Used

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

## 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 11:17:27 -06:00
Dotta 0731cd3afc perf(ci): Phase 2 PR CI under 4 minutes (dynamic workers, fast E2E boot, typecheck overlap, test-budget gate) (#22729)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Pull-request CI checks run on every commit before maintainers can
merge code
> - PR #22679 cut PR CI from 15–30+ minutes down toward 4.5–5.5 minutes
on 4-core runners
> - Remaining wall-clock bottlenecks sit in unsharded `workspaces-b`,
serial typecheck preparation, E2E server/UI startup, fixed Vitest worker
caps, and remaining soak and duplicated UI tests
> - This pull request adds Phase 2 optimizations across server soak
triage, typecheck DAG overlap, E2E fast boot and shard balance, dynamic
CPU-aware workers, pure-Node workspace link preflight, UI pruning, and
permanent test-budget enforcement
> - The benefit is ordinary feature PRs finish in ~3.1–3.8 minutes on
4-core runners and scale automatically to ~2.0–3.0 minutes on 8-core
runners while keeping core invariants and nightly coverage intact

## Linked Issues or Issue Description

Refs #22679

**Problem Statement**
After #22679 landed, several PR lanes still took 4.5–6 minutes on 4-core
runners (`general-workspaces-b` ran unsharded, `Typecheck + Release
Registry` waited on a serial server build before starting UI and
test-program checks, E2E shards paid full `cli onboard` + minified UI
build overhead, and Vitest worker counts did not scale with runner CPU
count).

**Proposed Solution**
Split `general-workspaces-b` across two duration-balanced shards,
overlap typecheck preparation tasks behind a shared runner-vendor node,
replace E2E `onboard` with a direct template-PG boot + unminified inline
UI build, scale Vitest/Playwright/Typecheck workers dynamically by CPU
and RAM, replace `tsx` in workspace-link preflight with pure Node, prune
redundant mocked UI tests and additional real-clock server soak suites
(still run on `master`, `release-verify`, `cloud-readiness`, and
`PAPERCLIP_CI_FULL=1`), and add a permanent test-budget policy check.

**Expected Benefit**
Brings ordinary PR CI wall-clock down to ~3.1–3.8 minutes on 4-core
runners (and ~2.0–3.0 minutes on 8-core runners) with automated
guardrails against future test-time regressions.

## What Changed

- **Server soak triage & permanent test-budget guardrail
(`scripts/ci/nightly-only-suites.json`, `rules/test-budget.mdc`,
`.greptile/files.json`, `scripts/check-test-budget.mjs`,
`scripts/check-test-budget.test.mjs`,
`.github/workflows/pr-trusted.yml`):** Expanded the PR-excluded
soak/heavy-integration manifest to 568 genuine heavy suites (preserving
100% of company isolation, authz, checkout, approval, budget,
activity-log, security, telemetry, and serialized suites on every PR)
and wired `node scripts/check-test-budget.mjs` into the `policy` job.
- **Typecheck DAG overlap & CPU/RAM scaling
(`scripts/ci-typecheck-lane.mjs`, `scripts/typecheck-test-programs.mjs`,
`scripts/__tests__/ci-typecheck-lane.test.mjs`,
`scripts/typecheck-test-programs.test.mjs`):** Moved `build server
without type checks` and `check server runtime assets` out of serial
`prepare` into parallel DAG nodes behind `prepare runner vendor`, added
`computeResourceProfile` scaling across 2/4/8-core runners, and added
missing UI/Runner consumer routing inputs (`packages/paperclip-runner/`
for `@paperclipai/ui`, `packages/adapter-utils/` for Runner test
programs).
- **E2E fast boot, dynamic workers & 8-shard rebalance
(`tests/e2e/start-e2e-server.ts`, `tests/e2e/playwright.config.ts`,
`scripts/e2e-shard.mjs`, `scripts/e2e-shard-durations.json`,
`.github/workflows/pr-trusted.yml`,
`.github/workflows/release-verify.yml`):** Added direct throwaway
template-PG boot (`fsync=off`), unminified inline Vite fallback build,
dynamic parallel workers (`min(4, floor(cpus/2))`), empirical `1.5x`
parallel speedup weighting across 8 shards, targeted trims to slowest
E2E specs, and hashed workspace `package.json` manifests into the
`e2e-ui-dist-v2` cache key.
- **Dynamic Vitest workers, 2-shard `workspaces-b`, and pure-Node
preflight (`scripts/ci/vitest-workers.mjs`,
`scripts/ci/workspaces-b-shard.mjs`,
`scripts/ensure-workspace-package-links.mjs`,
`scripts/ci-dependency-cache.mjs`,
`packages/db/src/test-embedded-postgres.ts`,
`.github/ci-task-matrix.json`,
`.github/actions/setup-ci-dependencies/action.yml`, `package.json`):**
Scaled Vitest workers dynamically (`4→7` general, `3→5` serialized) with
`max_connections=300` before PostgreSQL start, split
`general-workspaces-b` into 2 duration-weighted shards
(backward-compatible unsharded for release workflows), replaced `tsx`
workspace-link preflight with pure Node (~29× faster), and parallelized
`ci-dependency-cache.mjs` child queries.
- **UI Vitest worker scaling, fake timers & E2E-duplicated suite pruning
(`ui/vitest.config.ts`, 4 `maps/` files, and UI test suites):** Scaled
UI `maxWorkers` dynamically, converted real-clock sleeps in kept suites
to fake timers, removed 34 E2E-duplicated mocked jsdom suites, and
updated corresponding `maps/` prose references.

## Verification

- `node --test .github/scripts/tests/ci-plan.test.mjs
.github/scripts/tests/ci-dependency-cache.test.mjs
.github/scripts/tests/pr-dependency-cache.test.mjs
scripts/__tests__/run-vitest-stable-shard.test.mjs
scripts/__tests__/run-vitest-stable-pr-mode.test.mjs
scripts/__tests__/ci-typecheck-lane.test.mjs
scripts/typecheck-test-programs.test.mjs
scripts/__tests__/e2e-shard.test.mjs scripts/check-test-budget.test.mjs
scripts/ci/test-selection-pr-timings.test.mjs`: **160/160 PASS**
- `node scripts/check-test-budget.mjs`: **PASS** (`568` nightly suites
validated)
- `node scripts/check-maps.mjs`: **PASS** (`35 areas, 192 capability
IDs`)
- `pnpm --filter @paperclipai/ui typecheck` & `pnpm --filter
@paperclipai/db typecheck`: **PASS**
- Live CI verification runs on the new `pr-trusted.yml@master` (from
#22679) with `profile-ci` enabled to export the full job/step/file
waterfall to Honeycomb `paperclip-ci`.

## Risks

- Medium CI scope: touches workflow matrix partitioning, E2E startup,
and test runners; does not change production app runtime behavior.
- All PR-demoted soak suites continue to execute on `master`,
`release-verify`, `cloud-readiness`, local `pnpm test:run`, and
`PAPERCLIP_CI_FULL=1`.
- All new `policy` and `setup-ci-dependencies` commands keep
file-existence guards so reruns of older PR branches continue to work.

## Model Used

- Google Gemini (Antigravity swarm orchestrating specialized worker
agents with shell, file editing, and test execution tools) and Anthropic
Claude Opus (verification and optimization sub-agents).

## Checklist

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

> - Paperclip is the open source app people use to manage AI agents for
work
> - Plan mode makes an agent write a plan document. The user then
approves the plan or requests changes on a review card. After approval,
the agent does the work on the same task.
> - For Codex and Claude, the agent session reports the plan as a
provider event. Paperclip opens the review card from that event.
> - Google Antigravity and other ACPX agents have no such event. They
write the plan with a tool, and they must open the review card with
another tool.
> - When the agent does not open the card, the run settles as "waiting
for a response" and the task shows no action. This happened in a live
run: the Antigravity process was stopped during a Plan-mode run, and the
automatic continuation wrote a new plan revision but did not open the
card.
> - This pull request makes the server open the review card when a
Plan-mode run settles with a plan revision that has no review card. It
does this for every harness.
> - The benefit is that a Plan-mode task always shows the user the next
action, also after a crash or restart.

## Linked Issues or Issue Description

Refs #22727

**What happened?**

A Google Antigravity agent ran a task in Plan mode. The agent process
was stopped during the run. Paperclip continued the run automatically.
The new run wrote a new plan revision and finished with "waiting for
plan review". It did not open the Approve / Request changes card. The
task stayed in progress with no action for the user.

**Expected behavior**

When a Plan-mode run settles with a new plan revision, the user sees
exactly one review card for that revision. Retries, restarts and
duplicate settles do not add more cards. A Plan-mode run that produces
no plan does not leave the task waiting with no action.

**Steps to reproduce**

1. Assign a task to an Antigravity agent in Plan mode.
2. Stop the agent process while the run is in progress.
3. Let Paperclip continue the run automatically.
4. See that the continuation writes the plan but no review card opens.

**Paperclip version or commit**

master at 18aa2b353d.

## What Changed

- New `server/src/services/native-runtime/native-plan-review-card.ts`.
It opens the Plan-mode review card for the current plan revision, unless
an explicit plan review already covers it. Only a card bound to the plan
revision is a plan review: the server card, the Codex/Claude card, or an
agent card opened with the plan target. A confirmation without a plan
target is an ordinary request: it never covers a revision, never starts
execution and is never withdrawn by this logic. Per state of the
revision's card: pending is the gate; accepted, rejected, or withdrawn
by the user count as the user's decision (the agent is asked once to
revise); withdrawn by an agent or the system, expired or failed get a
fresh card. The idempotency key is bound to the revision (and to the
card it replaces), so concurrent settles open one card. Cards bound to
an older revision are withdrawn after re-reading the plan under a lock.
One card builder serves this and the Codex/Claude plan cards. A revision
that a person wrote is not put up for review. The call that inserts the
card logs it in the activity log.
- `heartbeat/task-markdown.ts`: the native Plan-mode directive says
Paperclip asks the user to approve the saved plan, so the agent does not
open its own card. This keeps the common case at one card.
- `native-run-finalizer.ts`: when a Plan-mode run settles successfully
and does not report done, the finalizer calls the new function before it
reads the governance gate. If the card cannot be opened, the run still
settles (the error is logged) and the recovery pass opens the card
later. The new card then becomes the gate, and the task waits in review
on it (`governed_response_waiting`), as for Codex and Claude.
- `plan-mode-status.ts` + `status-arbiter.ts`: a Plan-mode run (assigned
or started by a comment) that yields a response wait with no plan to
review (no plan, or the current revision already answered) no longer
settles as a silent wait. The agent gets one continuation that asks it
to save its plan. If that also fails, the task keeps its status and gets
a recovery action with a plain-language next step
(`plan_mode_plan_not_produced`). This uses the existing bounded
incomplete-report path.
- `issue-thread-interactions.ts`: a new `afterInsertInTransaction`
create option runs only when the call inserted the card (not on an
idempotent replay).
- `recovery/service.ts`: the existing stranded-task pass opens the card
for a Plan-mode task that an older release left in this state. No new
background worker.

## Verification

- `pnpm vitest run server/src/__tests__/native-plan-review-card.test.ts
server/src/__tests__/native-plan-review-card-finalizer.test.ts`
- Red on master, green on this branch:
- Finalizer: a recovered Plan-mode run with a new revision and no card
now gets exactly one card and waits in review (master: no card,
`response_wake_waiting_for_input`).
- Finalizer: a Plan-mode run with no plan gets the bounded "save your
plan" continuation (master: silent wait).
- Recovery pass: a task an older release left without a card gets one
card, also on a second pass, with no agent wake (master: no card).
- Table-driven tests: every way a Plan-mode run can settle (no plan;
plan with no card; agent card; current, historical and dismissed
questions; each governed card kind and status; a card by someone else;
Request changes with and without a new revision) leaves at most one plan
review card, or the "save your plan" continuation, and a repeat settle
changes nothing. Arbiter table: assigned and comment-started runs, with
and without a card, and the second miss.
- Also covered: an agent-opened card means no second card; concurrent
and repeated settles from several runs give one card; after Request
changes, the next revision gets a new card and the rejected card stays
rejected; a pending card for an older revision is expired and cannot be
accepted; Standard-mode response waits are unchanged; the card that
Codex and Claude open from their plan event stays the only card; a
person's own plan edit is not put up for review.
- `pnpm verify` passed for the selected suites.
- Not run live. The local Antigravity instance runs older code and was
not restarted for this change.

## Risks

- Low to medium. The change only acts on tasks in Plan mode. Standard,
Ask and conversation turns are not changed, except that the card
function can also run for a Plan-mode conversation run that has an
unreviewed plan.
- A Plan-mode run that reports done is not changed.
- An agent card without a document target is treated as covering the
revision when it was created after the revision. A plan card from Codex
or Claude has a target and is matched on that.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), via 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 00:32:12 -06:00