Commit Graph
8809 Commits
Author SHA1 Message Date
Devin FoleyandClaude Opus 5.5 7851c2d1e3 docs(release): prepare v2026.1202.0 stable notes before publish (#23550)
<!-- 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.
> - Each stable release publishes curated release notes as its GitHub
Release body.
> - The stable release workflow reads
`releases/beta/v2026.1120.0-beta.0.md` from master when it starts. It
publishes that exact revision.
> - The notes on master show v2026.1123.0 and the date 2026-11-23. That
version did not ship.
> - The promotion of `2026.1120.0-beta.0` starts on 2026-12-02, so the
version is `2026.1202.0`.
> - An audit of the release range also found an incorrect contributor
count and four user-facing fixes that the notes do not cite.
> - This pull request corrects these before the stable release starts.
> - The benefit is that the release page shows the correct version,
date, counts and changes.

## Linked Issues or Issue Description

Refs #22372 (the curated notes for the `2026.1120.0-beta.0` soak).

**Problem**
The stable notes for the promotion of `2026.1120.0-beta.0` show `#
Paperclip v2026.1123.0` and `> Released: 2026-11-23`. The next stable
version for 2026-12-02 is `2026.1202.0`. The Contributors line says 16
contributors. The range has 18. Four user-facing fixes in the range are
not in the notes.

**Expected result**
The notes show `# Paperclip v2026.1202.0` and `> Released: 2026-12-02`.
The intro names v2026.1202.0. The counts match the range. The notes
describe the user-facing changes for self-hosted installs.

**Impact**
The stable workflow publishes these notes as the GitHub Release body. If
this pull request does not merge before the release starts, the release
page shows incorrect data.

## What Changed

- Set the H1 to `# Paperclip v2026.1202.0`, the release line to `>
Released: 2026-12-02`, and the version in the intro to v2026.1202.0.
- Set the contributor count to 18. The credited handles do not change.
- Add four fixes to the **Other** group in **Fixes**: the tool gateway
advertises only the MCP capabilities its token allows (#19279,
@Pavel-Guseynov), database queries recover from invalidated prepared
statements (#21718), a plugin's first configuration save works (#19847),
and cost views name Ollama billers correctly (#20420).
- One file changes. No text outside `releases/` changes.

## Verification

- The next stable version for 2026-12-02 is `2026.1202.0`. This uses the
`next_stable_version` rule in `scripts/release-lib.sh`: no public
package has a `2026.1202.N` stable version on npm, so N is 0.
- The file has no `1123` or `2026-11-23` strings after the change.
- Audit against `v2026.1117.0..28043f8b93fa208ac83f96946953d05e7ba1dfd3`
(the `beta/v2026.1120.0-beta.0` source):
  - The range has 1,222 commits. This matches the notes.
  - All 294 cited PR numbers are in the range.
- Every PR in the range that the notes do not cite was classified as
internal (CI, tests, lockfiles, release housekeeping, docs and rules for
contributors), covered by an existing line, Paperclip Cloud only (kept
out), or user-facing. The four user-facing ones are added here.
- The range has 18 commit authors without `github-actions[bot]`. This is
the same method as the v2026.1117.0 notes. The 10 credited handles are
the same.
- The range adds migrations `0452`–`0499` (48 files). This matches the
Upgrade Guide. The new environment variables and their defaults match
the code at the source commit.
- The file on this branch has blob
`40c62079534dfa2fc90709d783053653b9744ed8`.

## Risks

- Low risk. This is a change to documentation only, in one file.
- If the UTC date changes before the release starts, the release
workflow keeps `stable_date=2026-12-02` to match this header.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use (shell,
GitHub API). Used to compute the version, audit the range, and write 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
- [ ] I have run tests locally and they pass (documentation only; no
tests apply)
- [ ] I have added or updated tests where applicable (not applicable)
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

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

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
canary/v2026.1202.0-canary.880900
2026-12-02 13:15:30 -08:00
DottaandPaperclip a30b1be565 fix(realtime): live-sync open web UI windows on headless pc mutations (#23532)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Headless channel and task commands (`pc post`, `pc reply`, `pc
claim`, `pc complete`, `pc dep`, `pc ask`, etc.) let scripts, operators,
and agents update threads and tasks from the CLI while the Web UI stays
open
> - When an operator kept an issue detail page open and ran `pc reply`
(or other `pc` mutations) from a terminal, the open Web UI page did not
live-update without a manual page refresh
> - Three gaps caused this: `publishCommittedBoardEvent` emitted
`activity.logged` events without `entityType`, `entityId`, or `action`
(so `LiveUpdatesProvider` ignored them and authenticated WebSocket
delivery stripped the custom fields); `pc reply` logged
`issue.comment_added` under the same `userId` (`local-board` in local
mode or the signed-in user in authenticated mode), which
`selfCommentActivity` downgraded to `refetchType: "inactive"` while
`hydrateVisibleIssueComment` skipped unfocused windows; and
`resolveIssueQueryRefs` missed identifier-keyed `issues.detail` cache
entries when `details` was omitted and the window was unfocused
> - This pull request maps committed headless board events onto
structured `activity.logged` payloads, tags headless comment activities
as external (`source: "headless"` / `actorProfile`), and updates
`LiveUpdatesProvider` to resolve cached detail identifiers and actively
refresh issue, comment, interaction, relation, and attention queries for
headless board events
> - The benefit is immediate live updates in open (focused or unfocused)
Web UI windows for all `pc` commands without refreshing the page, in
both local and authenticated deployments

## Linked Issues or Issue Description

**What happened?**

Running `pc reply "<ID>" "unit tests brown" --as ci-bot` or other `pc`
task/workflow/interaction commands while the issue detail page is open
in a browser window does not update the page until the user manually
refreshes.

**Expected behavior**

Commands executed through `pc` (such as `pc reply`, `pc claim`, `pc
release`, `pc complete`, `pc fail`, `pc assign`, `pc handoff`, `pc
cancel`, `pc reopen`, `pc deps`, `pc ask`, `pc approve`, `pc reject`,
`pc label`, `pc post`) should live-update open Web UI windows
automatically without a page refresh, matching the live SSE behavior of
the experimental channels viewer.

**Steps to reproduce**

1. Start a local board with `pc up --local` and open an issue detail
page in the Web UI.
2. Focus a terminal window and run `pc reply "<ID>" "unit tests brown"
--as ci-bot` (or `pc tasks claim` / `pc tasks complete`).
3. Observe that the open issue detail page does not show the new reply
or updated task state until manually refreshed.

**Paperclip version or commit**

`4db307d53c` (`origin/master`)

**Deployment mode**

Local dev (`pc up --local`) and authenticated deployments

## What Changed

- **`server/src/services/headless-board-events-write.ts`**: Added
`buildBoardEventLiveActivityPayload` and updated
`publishCommittedBoardEvent` so every committed headless
`BoardEventView` publishes a structured `activity.logged` live event
with `entityType` (`issue`, `approval`, or `channel`), `entityId`,
`action` (`issue.thread_interaction_created`,
`issue.thread_interaction_resolved`, `approval.decided`, or
`board.<type>`), `actorType`, `actorId`, and `details` (preserving
existing top-level `boardEvent*` fields).
- **`server/src/services/headless-comment-group-commit.ts`** and
**`server/src/routes/headless-channels-schemas.ts`**: Added `source:
"headless"` (and `actorProfile` when present) to `issue.comment_added`
activity details for headless replies.
- **`ui/src/context/LiveUpdatesProvider.tsx`**:
- Extended `resolveIssueQueryRefs` to scan cached `["issues", "detail"]`
queries so identifier-keyed detail routes resolve from UUID-only events
even when unfocused or in authenticated mode.
- Exempted headless comments (`source: "headless"` or `actorProfile`)
from `selfCommentActivity` suppression.
- Actively invalidated `issues.comments(ref)` on `board.comment.posted`
and added `board.task.*` actions to
`ISSUE_RELATION_SUMMARY_ACTIVITY_ACTIONS` and
`BOARD_DECISION_PROJECTION_ACTIONS`.
- **`server/src/__tests__/headless-board-events-live-sync.test.ts`** and
**`ui/src/context/LiveUpdatesProvider.test.ts`**: Added regression tests
covering structured board-event live payloads, unfocused `pc reply --as
ci-bot` as `local-board`, authenticated `board.comment.posted` with
stripped details, and `board.task.completed` relation/attention
invalidation.

## Verification

- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/headless-board-events-live-sync.test.ts
src/__tests__/live-events-ws.test.ts` (2 files, 11/11 passed)
- `pnpm --filter @paperclipai/ui exec vitest run
src/context/LiveUpdatesProvider.test.ts` (1 file, 138/138 passed)
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/headless-channels-schemas-batch.test.ts
src/__tests__/headless-queues-leases-events.test.ts` (2 files, 24/24
passed)
- `cd server && node scripts/typecheck-layers.mjs` (0 errors across all
7 layers)
- `pnpm --filter @paperclipai/ui typecheck` (0 errors)

## Risks

- Low risk. Structured `board.<type>` actions do not overlap with
`ISSUE_TOAST_ACTIONS`, so headless mutations do not emit duplicate
browser toasts when `logActivity` also fires. Authenticated WebSocket
delivery continues to authorize every `entityType: "issue"` event
against `issueId` via `getHeartbeatRunReadDecisions`, failing closed for
private issues. Existing browser-composer `selfCommentActivity`
suppression is unchanged.
- Note on file length: `ui/src/context/LiveUpdatesProvider.tsx` was
already over 1,000 lines; this PR adds a focused 68-line diff directly
inside the existing activity-invalidation and issue-ref resolution
functions rather than introducing an unrelated refactor.

## Model Used

- Google Gemini (Antigravity agentic coding assistant, medium reasoning
mode with shell, file inspection, and test execution tools)

## Checklist

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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
canary/v2026.1202.0-canary.880800
2026-12-02 14:47:56 -06:00
scotttongandScott Tong 89c6e38ad1 Hide refresh for static Claude catalogs in Cloud agent settings (#23544)
Expose catalog refresh capability to the Cloud Claude picker. Preserve routed and account-bound model discovery.

Co-Authored-By: Scott Tong <scott@scotts-mbp-m5-max.local>
canary/v2026.1202.0-canary.880700 nightly/v2026.1202.0-nightly.2 beta/v2026.1203.0-beta.0
2026-12-02 12:05:16 -08:00
DottaandPaperclip f5f47b1ec4 fix(runner): omit provider mode from ordinary Antigravity ACP runtime identity (#23536)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The Paperclip Runner executes Google Antigravity agents through
`AcpxRuntimeHost` and the unified `agy acp` 1.5.19 runtime
(`openAntigravityAcpRuntime`)
> - After #23168 moved ordinary Antigravity turns onto
`openAntigravityAcpRuntime`, its `identity()` method hardcoded `mode:
"persistent"`, confusing ACPX session persistence with
`AcpxRuntimePortIdentity.mode` (the optional provider mode)
> - Ordinary Antigravity turns resolve `binding.mode` to `undefined`, so
`AcpxRuntimeHost.open()` rejected every ordinary Antigravity run during
identity admission with `ACPX_ADMISSION_IDENTITY` (`ACPX runtime
Provider mode does not match the admitted session configuration`)
> - This pull request omits `mode` from `openAntigravityAcpRuntime`'s
`identity()`, rejects unexpected provider modes passed directly to
`openAntigravityAcpRuntime`, and adds an `AcpxRuntimeHost.open()`
fresh-open and session-resume regression test
> - The benefit is that ordinary Google Antigravity runs pass admission
and resume cleanly on both local and remote runners

## Linked Issues or Issue Description

Refs #23168

**What happened?**
Every ordinary (non-`/swarm`) Google Antigravity run failed during
`session.open` admission with `ACPX_ADMISSION_IDENTITY`: `ACPX runtime
Provider mode does not match the admitted session configuration`.
`openAntigravityAcpRuntime` returned `mode: "persistent"` from
`identity()`, while `AcpxRuntimeHost.open()` bound `binding.mode` to
`undefined` via `resolveAcpxProviderMode("antigravity", undefined)`.

**Expected behavior**
Ordinary Antigravity runs omit `mode` (`undefined`) in
`AcpxRuntimePortIdentity`, matching `binding.mode` during both initial
`AcpxRuntimeHost.open()` admission and subsequent `expectedIdentity`
session resume. Only trusted `/swarm` turns (served by
`openAntigravitySwarmRuntime`) carry `mode: "swarm"`.

**Steps to reproduce**
1. Open an ordinary Antigravity session (`mode: undefined`) through
`AcpxRuntimeHost.open()` backed by `openAntigravityAcpRuntime`.
2. Observe `AcpxRuntimeHost.open()` throw `ACPX runtime Provider mode
does not match the admitted session configuration` at `runtime-host.ts`
during identity verification.

**Paperclip version or commit**
`4db307d53c` (`master`, regression introduced in `3df59a1853` / #23168)

**Deployment mode**
Self-hosted server

## What Changed

- Remove hardcoded `mode: "persistent"` from
`openAntigravityAcpRuntime`'s `identity()` return value in
`packages/paperclip-runner/src/drivers/acpx/antigravity-acp-runtime.ts`
so `runtimeIdentity.mode` is `undefined` and matches `binding.mode` for
ordinary turns.
- Fail closed in `openAntigravityAcpRuntime` if a caller passes a
non-`undefined` `options.mode`.
- Add red-green regression tests in
`packages/paperclip-runner/src/drivers/acpx/antigravity-acp-runtime.test.ts`
covering `AcpxRuntimeHost.open()` admission, `expectedIdentity` session
resume, and direct non-empty `mode` rejection.
- Update the ordinary-route identity expectation in
`packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-route.test.ts`
from `mode: "persistent"` to `mode: undefined`.

## Verification

- Reproduced the exact failure before the fix: `AcpxRuntimeHost.open()`
threw `ACPX runtime Provider mode does not match the admitted session
configuration` on the new regression test in
`packages/paperclip-runner/src/drivers/acpx/antigravity-acp-runtime.test.ts`.
- Verified green after the fix:
- `pnpm --dir packages/paperclip-runner exec vitest run
src/drivers/acpx/antigravity-acp-runtime.test.ts
src/drivers/acpx/antigravity-swarm-route.test.ts
src/drivers/acpx/antigravity-admission.test.ts
src/drivers/acpx/antigravity-acpx-runtime.test.ts
src/drivers/acpx/antigravity-credentials.test.ts
src/drivers/acpx/antigravity-swarm-guard.test.ts
src/cli/acpx-runtime-sidecar.test.ts` (7 test files, 244 tests passed)
- `pnpm --dir packages/paperclip-runner exec vitest run
src/drivers/acpx/antigravity-swarm-runtime.test.ts
src/drivers/acpx/runtime-host.test.ts` (157 tests passed)
- `pnpm --dir packages/paperclip-runner typecheck` (TypeScript + Rust
checks passed)
- Live remote staging execution requires deploying this fix; local
verification exercised the real `AcpxRuntimeHost` admission, binding,
and resume boundary with the ordinary Antigravity ACP fixture.

## Risks

- Low risk. The change aligns `openAntigravityAcpRuntime`'s reported
identity with `AcpxRuntimeHost`'s existing provider-mode contract
(`acpx-runtime-adapter.ts` already omits `mode` when no provider mode is
active). `/swarm` turns still route through
`openAntigravitySwarmRuntime` and report `mode: "swarm"`.

## Model Used

- Google Gemini 4 Neon (Medium) via Antigravity agent with tool use and
local code execution.

## Checklist

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

> - Paperclip is the open source app people use to manage AI agents for
work.
> - People review pending requests in agent chats and tasks.
> - The request card sits above the composer in both views.
> - On mobile, a long card can extend beyond the visible screen and
cannot scroll.
> - This pull request limits the card height to part of the visible
viewport.
> - People can scroll the card to read the details and reach its
buttons.

## Linked Issues or Issue Description

Fixes: #21626

## What Changed

- Give mobile composer takeover cards their own vertical scrolling and
contain their scroll at the edges.
- Size the mobile card against the visible chat viewport, including when
the keyboard shrinks it. Keep the desktop limit and Inbox behavior
unchanged.
- Add browser regression tests for touch scrolling through a long
confirmation card in Chat and Tasks.

## Verification

- On master at `4db307d53c`, both regressions reproduced at 390 × 664
with emulated touch. The card extended past the viewport and a swipe did
not move its scroll position.
- Both patched Chromium regressions passed. A touch swipe scrolled the
card, and subsequent swipes brought the approval button into view.
- `pnpm --filter @paperclipai/ui typecheck` passed.
- The isolated mobile preview also loaded the Inbox without changing it.
Physical iPhone and keyboard testing were not performed.

## Risks

- Low risk. The change is limited to the shared composer card layout and
does not change how requests are accepted or stored. The composer is
already above the 1,000-line threshold; changing its existing card
classes keeps the fix local.
- A long card uses part of the available height, so its contents scroll
instead of pushing the controls offscreen.

## Model Used

- OpenAI GPT, in Codex with repository and Chromium tools.

## Checklist

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

---------

Co-authored-by: Scott Tong <1504818+scotttong@users.noreply.github.com>
canary/v2026.1202.0-canary.880500
2026-12-02 11:25:44 -08:00
Nicky LeachandPaperclip 4db307d53c Stop resuming completed Claude sign-ins (#23530)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Agents can use a personal or shared Claude connection.
> - Setup checks for an active sign-in before starting another.
> - A successful credential write leaves a claim for its caller to
collect.
> - This pull request limits active sign-in discovery to the three
states that still require work.

## Linked Issues or Issue Description

**What happened?**

After a shared Claude sign-in completed, personal account setup kept
finding the saved attempt until expiry.

**Expected behavior**

A user can sign in to another account as soon as the previous attempt
succeeds.

**Steps to reproduce**

Finish a shared Claude sign-in. Start a personal Claude sign-in before
the old deadline.

## What Changed

- Use the same active states for the live session lookup and the durable
lookup. Keep the saved claim available for completion.
- Check active lookup after success, after restart, and when a new
active row shares the same owner and provider.

## Verification

- Ran the setup-token session, transport binding, and HTTP route Vitest
suites. All 120 tests passed. The regression failed before the fix.

## Risks

- In-progress sign-ins still resume. Existing completion reads and claim
consumption retain their previous behavior. No migration is required.

> 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 Codex (GPT-6), with repository and test tools.

## Checklist

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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
canary/v2026.1202.0-canary.880400
2026-12-02 08:20:16 -08:00
paperclipbugbotandClaude Opus 5.5 51cb918a03 fix(opencode): stop OpenCode from running npm inside opencode serve at startup (#23512)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The native Runner starts `opencode serve` (pinned to 1.18.34) for
each OpenCode turn, with its own fresh config directory and a fresh
isolated `HOME`.
> - #23372, #23391 and #23428 showed that the kernel OOM killer stops
`opencode serve` at the 8 GiB sandbox limit about 50 seconds into light
turns. The memory is OpenCode's own resident set. The model traffic is
small and complete when OpenCode dies.
> - A local reproduction finds the cause. On every project bootstrap,
OpenCode installs `@opencode-ai/plugin` into its global config directory
with npm's Arborist. The install runs inside the `opencode serve`
process. It downloads about 114 MB into a fresh npm cache and keeps the
JavaScript event loop busy while it allocates. OpenCode stops answering
HTTP, emits no events, and does not send the next model request.
> - OpenCode skips this install when the directory has `node_modules`
and a `package-lock.json` that lists the dependency. Today only launches
with configured secrets write that marker, as part of output custody.
> - This pull request writes the marker for every launch.
> - The benefit is that OpenCode no longer runs npm at startup, so it
stays responsive and its memory stays flat.

## Linked Issues or Issue Description

Refs #23372 (kernel OOM evidence). Refs #23391 (memory attribution).
Refs #23428 (model traffic counts).

**What happened?**
Native OpenCode turns on cloud sandboxes fail with
`opencode_server_exited` and SIGKILL. The failure record shows
`memoryKill: observed`, an OpenCode resident set of about 8 GB at the 8
GiB limit, and one or two small, completed model responses. The run log
stops for about 42 to 48 seconds before the kill. The failures happen
with and without tool calls. Agents with configured secrets are not
affected, because output custody already writes the install marker.

**Expected behavior**
`opencode serve` stays responsive after startup. It does not download or
install packages, and its memory does not grow while it waits for a
model or a tool.

**Steps to reproduce**
1. Start `opencode serve` 1.18.34 with an empty
`$XDG_CONFIG_HOME/opencode` that has only `opencode.json`, and an empty
`HOME`, as the Runner does for an agent without configured secrets.
2. Send one request, for example `GET /config`, so that OpenCode
bootstraps the project.
3. Within about 8 seconds, OpenCode uses 100 to 150% CPU on its
JavaScript main thread. It stops answering HTTP (`GET /config` times
out), and its memory grows. `$XDG_CONFIG_HOME/opencode/node_modules` and
`$HOME/.npm/_cacache` fill with `effect`, `zod`, `yaml`, `@ai-sdk/*` and
other packages.

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

## What Changed

- New `config-dependencies.ts`:
`markOpenCodeConfigDependenciesInstalled(configDirectory)` creates
`node_modules` and writes `package-lock.json` with `@opencode-ai/plugin`
in its root dependencies. It keeps an existing lock that already lists
the package, for example one that a completed install wrote. It replaces
a lock that does not list it, with a temporary file and a rename.
- `startRuntime` calls it for OpenCode's global config directory on
every launch, before OpenCode starts. This applies with or without
configured secrets.
- Output custody no longer writes the marker, and
`prepareOpenCodeOutputCustody` no longer takes `configDirectory`. The
launch now does this once for every agent.
- `scripts/qualify-opencode-runtime.test.mjs` starts OpenCode directly.
It now records the dependency as installed for both secret cases, as the
Runner launch does.
- The Runner loads only local plugin files (`file://…`), which import
nothing from `@opencode-ai/plugin`. So nothing needs the skipped
install.
- With `OPENCODE_DISABLE_PROJECT_CONFIG=true`, which the Runner already
sets, OpenCode does not install into a workspace `.opencode` directory.
I checked this with a workspace that has a `.opencode` directory.

## Verification

- `npx vitest run src/drivers/opencode/config-dependencies.test.ts`: 3/3
pass. The tests copy OpenCode 1.18.34's install decision (`Npm.install`:
`node_modules` must exist, and the lock root must list every dependency
that `package.json` and the install would add). They check a fresh
directory, that an existing lock stays unchanged, and that a lock which
does not list the package is replaced. With the helper turned into a
no-op, 2 of 3 fail.
- New driver test: a launch with no configured secrets leaves
`node_modules` and a lock that lists `@opencode-ai/plugin` in the config
directory, and no plugin in `opencode.json`. CI runs it with the full
driver suite.
- Real OpenCode 1.18.34, idle, with the config directory prepared by
this helper:

| Config directory | OpenCode CPU | OpenCode RSS | `GET /config` | npm
cache |
  | --- | ---: | ---: | ---: | ---: |
| As on `master` without secrets | 127–148% | 0.6 GB and climbing |
times out after about 8 s | about 114 MB |
| With this change | 1–2% | 311 MB, 485 MB after a prompt | 2–3 ms |
none |

- Real OpenCode 1.18.34 with a mock provider and one `bash` call that
runs `sleep 30`: before the change, OpenCode never sent the reply, and
its memory churned between 1.1 and 1.9 GB (a peak of 3.1 GB in one run).
With the change, the tool result went back to the model, and the turn
completed after 37 s. Memory stayed at about 510 MB and CPU stayed near
0%.
- `PAPERCLIP_OPENCODE_QUALIFY=1 node --test
scripts/qualify-opencode-runtime.test.mjs` with the real OpenCode
1.18.34, using type-stripped builds of the two changed modules, three
runs each. Before the qualification change, the protected case failed
every time after about 16 s, the same as the first CI run (16.9 s).
After it, all three tests passed every time, and both secret cases took
about 2.3 s. The qualification now records the dependency as installed
for both cases, as every Runner launch does.
- I could not run the full runner suite and the typecheck in my sandbox.
Its dependencies are not installed there. CI runs them on this branch.

## Risks

- Low risk. The change writes two small files in a directory that the
Runner owns, before OpenCode starts.
- If a future OpenCode version needs `@opencode-ai/plugin` in the config
directory, its plugins could fail to load. Today the Runner loads only
its own local plugin file, which has no imports from that package. A new
OpenCode version must pass qualification before the Runner uses it.
- OpenCode's other startup installs, for example of npm plugins named in
config, are not affected. The Runner configures none.

## Model Used

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

## Checklist

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

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 15:53:28 +00:00
Nicky LeachandClaude Opus 5.5 c31197f89f fix(onboarding): stop re-preparing an agent when a save reorders its configuration keys (#23440)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Onboarding signs the first agent in to Claude or Codex through a
plugin-managed execution environment that is prepared for the agent
(#23312, #23383)
> - Core prepares that environment again whenever the draft's execution
configuration changes, and refuses a sign-in while it does
> - Core detected a change with `JSON.stringify`, so the same
configuration saved with its keys in a different order counted as a
change. Postgres `jsonb` returns keys in its own order, so an onboarding
save of the same choice could re-prepare the environment
> - The wizard held sign-in readiness per harness only, so after such a
re-preparation it still treated the environment as ready and started a
sign-in that Core refused
> - This pull request compares configuration independent of key order,
and holds readiness per harness and model
> - The benefit is that re-picking the saved choice keeps the prepared
environment and signs in at once, and a real change waits for its
preparation instead of failing

## Linked Issues or Issue Description

Refs #23312 and #23383.

**What happened?**

With a plugin-managed execution environment as the instance default, the
onboarding agent was already prepared for Claude (`verifying`). Picking
Claude again saved the same configuration. Core moved the agent back to
`preparing` and bumped its lifecycle version, and the wizard started a
sign-in at once. Core returned `400 login_agent_unavailable` and the
card showed that error.

**What did you expect to happen?**

Saving an unchanged configuration leaves the prepared environment alone,
and the sign-in starts.

**Steps to reproduce**

1. Make a plugin-managed execution environment that prepares an
environment per agent the instance default.
2. Start onboarding, choose Claude with a subscription, and wait until
the environment is prepared.
3. Reload onboarding and pick Claude again.
4. See the sign-in fail with the message above.

## What Changed

- Agent configuration comparison (`jsonEqual`) uses canonical JSON with
sorted keys. This covers the lifecycle's re-preparation check, the
changed-field check for configuration patches, and the changed fields
recorded in configuration revisions. A save that only reorders keys no
longer re-prepares the agent or records a revision field change.
- Onboarding holds sign-in readiness per selected harness and model, so
a model change waits for the preparation it causes.

## Verification

- `pnpm --filter @paperclipai/server typecheck` and `pnpm --filter
@paperclipai/ui typecheck`: no errors.
- `server`: the agent lifecycle, configuration save and configuration
revision suites pass (97 tests). The lifecycle test now saves the same
runtime configuration with its keys reversed and asserts the lifecycle
version does not change. That assertion fails without the comparison
change (`expected 3 to be 2`).
- `ui`: the sign-in readiness hook suite passes (4 tests). It already
covers a hold-key change waiting for the new preparation.
- I reproduced the failure in a running instance and read it from the
network log. I did not repeat that sign-in with this change. CI runs the
full suites and end-to-end tests.

## Risks

- Comparisons that previously reported a key-order-only difference as a
change now report none. Every caller wants value equality, so this
removes spurious re-preparations and revision entries.
- No migration and no API change.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), with extended thinking and tool
use (code search, shell, tests, browser network inspection) 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
- [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>
canary/v2026.1202.0-canary.880200
2026-12-02 07:32:27 -08:00
DottaandPaperclip debfa75a7a perf(server): coalesce concurrent channel posts and replies with debounced activity (#23448)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Headless channels and thread replies let many agents publish
concurrent updates, tasks, and replies into shared company streams while
preserving gapless company identifiers and commit-ordered board events
> - After PR #23426 removed per-request query overhead, a fresh local
headless benchmark on merged `origin/master` (`ab2183aaed`) showed
concurrent post throughput hitting a serialization wall at 770–805 req/s
(`c=32`) and degrading to 653 req/s (`p99 = 295.9ms`) at `c=64` on a
single channel
> - Profiling showed why: every concurrent post or reply entered its own
database transaction and blocked sequentially on `UPDATE companies`,
`UPDATE channels`, and `pg_advisory_xact_lock('board_events',
company_id)`, pinning PostgreSQL pool connections and performing N
separate WAL flushes for N concurrent arrivals
> - This pull request adds adaptive in-process group commit for
non-idempotent channel posts and normal thread comments, a 250ms
debounce on `channels.last_activity_at` updates, and multi-row
`activity_log` and `board_events` batch helpers
> - The benefit is zero batching delay when idle (`442.7 req/s`, `p50 =
2.12ms` at `c=1`), `2.40x–2.55x` higher post throughput at `c=32`
(`1,849–2,055 req/s`), `3.11x–3.79x` higher post throughput at `c=64`
(`2,475–2,501 req/s`, `p99` down 85.5%), and `2.24x` higher hot-thread
reply throughput (`1,588 req/s`, `p99` down 73%), while keeping gapless
`<PREFIX>-<N>` identifiers and monotonic `evt_<seq>` cursors

## Linked Issues or Issue Description

Refs #23426

**What existing behavior does this improve?**

`POST /api/companies/:companyId/channels/posts`, `POST
/api/companies/:companyId/issues/batch`, `PATCH
/api/issues/:id/kv-labels`, and `POST /api/issues/:id/comments`
throughput, tail latency, and PostgreSQL connection-pool efficiency
under high concurrency.

**Subsystem affected**

- `server/ — REST API & orchestration services`

**Current behavior**

On `origin/master` (`ab2183aaed`, Node `v26.4.0`, `darwin-arm64`, local
`embedded-postgres` with 2 live SSE subscribers):
- Every concurrent `POST /api/companies/:companyId/channels/posts` call
opens an independent database transaction and contends on the single
`companies` counter row, the `channels` row (`SET last_activity_at =
now()`), and the per-company `board_events` advisory lock.
- At `c=32`, post throughput caps at `770.1 req/s` on a single channel
and `804.5 req/s` across 16 channels; at `c=64`, single-channel post
throughput drops to `653.1 req/s` with `p99 = 295.91ms` because waiting
write transactions exhaust the database connection pool.
- Concurrent replies on a single hot thread (`c=32`) serialize on
unconditional `UPDATE channels SET last_activity_at = now()` and
`board_events` advisory locks, capping at `710.1 req/s` (`p99 =
84.47ms`).

**Proposed behavior**

- Add `touchChannelsLastActivity` (250ms staleness guard with ascending
`channels.id` `FOR NO KEY UPDATE` lock ordering) and `appendBoardEvents`
(single `pg_advisory_xact_lock` + ordered multi-row `INSERT INTO
board_events ... RETURNING` sorted by `seq`) in
`server/src/services/headless-board-events-write.ts`, plus
`logActivitiesBatch` in `server/src/services/activity-log.ts`.
- Add `server/src/services/adaptive-company-batcher.ts`,
`server/src/services/headless-post-group-commit.ts`, and
`server/src/services/headless-comment-group-commit.ts` with a
self-cleaning `WeakMap`-backed per-company batcher
(`MAX_COALESCED_BATCH_SIZE = 64`, `MAX_PENDING_PER_COMPANY = 1024`):
- When no batch is in flight (`c=1`), the request dispatches immediately
with zero artificial timer delay.
- While one batch transaction is executing on a single database
connection for that company, concurrent arrivals queue in memory
(bounded with `429` backpressure above `1024`) and execute together in
the next multi-row transaction using real wall-clock `new Date()`
timestamps, `issues.issueNumber` thread tie-breaking in
`listChannelThreads`, and RFC-valid sub-millisecond ordered UUIDs
(`mintTimeOrderedUuid`) across both coalesced and serialized comment
paths.
- Shared `validateChannelPathWriteFromMap` checks per-item channel
access, archived-channel, project access, and assignee rules before
counter allocation so rejected siblings never abort valid siblings or
leave gaps in `<PREFIX>-<N>` issue numbers, and post-commit event
publication runs strictly outside the transaction fallback scope.
- Requests with `idempotencyKey`, `clientRequestId`, or `after` continue
through their dedicated serialized concurrency checks.

**Reason and benefit**

Matched 7-scenario local headless benchmark (`origin/master`
`ab2183aaed` vs `perf/channel-group-commit`, 2 live SSE subscribers
active throughout, 0 errors, 100% live SSE delivery):

| Scenario | Merged `master` (`req/s`) | Group Commit (`req/s`) |
Speedup | `master` `p99` | Group Commit `p99` |
| --- | ---: | ---: | ---: | ---: | ---: |
| 1. Sequential channel posts (`c=1`, 300 msgs) | 451.4 | 442.7 | 0.98x
(no idle delay) | 4.06 ms | 3.79 ms |
| 2. Single-channel posts (`c=32`, 1,000 msgs) | 770.1 | 1,849.2 |
**2.40x** | 89.23 ms | 34.67 ms |
| 3. 16-channel posts (`c=32`, 1,000 msgs) | 804.5 | 2,054.6 | **2.55x**
| 71.76 ms | 22.73 ms |
| 4. 16-thread replies (`c=32`, 1,000 msgs) | 1,045.7 | 1,486.6 |
**1.42x** | 59.53 ms | 28.91 ms |
| 5. Single hot-thread replies (`c=32`, 500 msgs) | 710.1 | 1,588.3 |
**2.24x** | 84.47 ms | 22.70 ms |
| 6. Single-channel posts (`c=64`, 2,000 msgs) | 653.1 | 2,474.7 |
**3.79x** | 295.91 ms | 42.80 ms |
| 7. 16-channel posts (`c=64`, 2,000 msgs) | 803.4 | 2,501.3 | **3.11x**
| 124.65 ms | 32.72 ms |

**Breaking changes**

None. All endpoints, request/response shapes, gapless `<PREFIX>-<N>`
identifiers, commit-ordered `evt_<seq>` cursors, idempotency semantics,
`after` optimistic concurrency checks, and channel/project/issue privacy
checks remain unchanged. `channels.lastActivityAt` updates at most once
per 250ms window under sustained traffic on the same channel.

**Additional context**

Builds on #23426 without schema migrations or external coordination
dependencies.

## What Changed

- Extracted shared activity preparation, row mapping
(`buildActivityLogRow`), side-effect notification, and publication
helpers in `server/src/services/activity-log.ts` and added
`logActivitiesBatch` for single-statement multi-row `activity_log`
inserts.
- Extracted `server/src/services/headless-board-events-write.ts`
(re-exported from `server/src/services/headless-common.ts`) with
`mintTimeOrderedUuid`, `touchChannelsLastActivity` (250ms debounce with
canonical ascending `channels.id` `FOR NO KEY UPDATE` lock ordering),
listener-isolated `subscribeCompanyBoardEvents`, and `appendBoardEvents`
(single `pg_advisory_xact_lock` acquisition with ordered multi-row
`INSERT INTO board_events ... RETURNING` sorted by `seq`).
- Extracted `server/src/services/headless-channel-write-helpers.ts`
(re-exported from `server/src/services/headless-channels.ts`) so channel
path validation, `ensureChannel`, tag upserts, and assignee resolution
are shared via normal imports without per-item callback plumbing.
- Added `server/src/services/adaptive-company-batcher.ts`,
`server/src/services/headless-post-group-commit.ts`, and
`server/src/services/headless-comment-group-commit.ts` implementing
bounded per-company write coalescing (`MAX_COALESCED_BATCH_SIZE = 64`,
`MAX_PENDING_PER_COMPANY = 1024`), post-lock wall-clock `new Date()` +
`mintTimeOrderedUuid` sampling so batches waiting behind `companies` or
`issues` row locks always receive newer `(createdAt, id)` tuples,
UUID-keyed comment `RETURNING` joins, per-item validation isolation, and
post-commit event publication strictly outside the transaction fallback
boundary.
- Updated `createChannelPost` and `listChannelThreads` in
`server/src/services/headless-channels.ts`,
`server/src/services/headless-labels-batch.ts`, and
`server/src/routes/headless-channels-schemas.ts` to tie-break equal
`createdAt` rows on `issues.issueNumber` and use
`touchChannelsLastActivity`, `appendBoardEvents`, `mintTimeOrderedUuid`,
and `executeCoalescedHeadlessComment`.
- Added regression tests in
`server/src/__tests__/adaptive-company-batcher.test.ts`,
`server/src/__tests__/headless-channels-schemas-batch.test.ts` (16-way
mixed burst with pinned per-request statuses, wall-clock bounds,
`issueNumber` thread/after ordering, real PostgreSQL insert-error solo
fallback on both posts and comments, coalesced comment batches waiting
behind active `FOR UPDATE` serialized locks, deterministic 250ms
`lastActivityAt` skip/update assertions, and post-commit throwing
subscriber isolation), and
`server/src/__tests__/activity-log-responsible-user.test.ts`
(`logActivitiesBatch` redaction, `responsibleUserId` attribution, and
`mcpEvents` work signaling).

## Verification

- `cd server && node scripts/typecheck-layers.mjs` (0 errors across all
7 layers)
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/adaptive-company-batcher.test.ts
src/__tests__/activity-log-responsible-user.test.ts
src/__tests__/headless-channels-schemas-batch.test.ts
src/__tests__/headless-queues-leases-events.test.ts
src/__tests__/headless-task-workflows.test.ts
src/__tests__/experimental-channels-viewer.test.ts` (6 files, 47/47
tests passed)
- Matched 7-scenario local headless benchmark on `origin/master`
(`ab2183aaed`) vs `perf/channel-group-commit` with 2 live SSE
subscribers (`0` errors, `100%` SSE event delivery across all runs)

## Risks

- Low risk. No database migrations or API contract changes. Coalesced
batches hold canonical lock order (`companies -> issues -> channels ->
labels -> issue_labels -> board_events` for posts; `issues ->
issue_comments -> channels -> board_events` for comments), isolate
read-only validation errors per item before minting issue numbers,
delete idle per-company queue state immediately, and fall back to solo
execution if an unexpected database error occurs on a multi-item batch.

## Model Used

- Google Gemini (Antigravity agentic coding assistant, extended thinking
mode with shell, profiling, and test execution tools)

## Checklist

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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
canary/v2026.1202.0-canary.880100
2026-12-02 06:13:26 -06:00
f91e05406d fix(server): bound the shutdown steps after the run drain (#23491)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The server runs an ordered shutdown when it gets SIGTERM. It drains
runs, stops workers, tears down the app services, closes the database
and exits.
> - The steps before the run drain have a shared deadline. Most steps
after the run drain have no deadline.
> - When one of those late steps stalls, a server that has finished its
work does not exit. It stays alive until the platform sends SIGKILL. On
Railway that is the full 90 s drain window.
> - A hosted Cloud idle stop waits for the deployment to stop. It has a
fixed stop budget, so a 90 s wait makes it fail with a production error.
> - This pull request puts the late steps under one shared post-drain
deadline and logs each step by name.
> - The benefit is that a stalled step cannot hold the exit, and the log
names the step that stalled.

## Linked Issues or Issue Description

**What happened?**
A hosted Cloud idle stop failed with "Automatic provider stop exhausted
its end-to-end budget" (Sentry PAPERCLIP-CLOUD-BACKEND-8Y, 2026-12-02).
The stop was in its Railway confirmation step, 95 s into a 120 s budget.

**Steps to reproduce**
1. Start a server. Make one step after the run drain stall, for example
a worker `stop()` or the app service teardown that never settles.
2. Send SIGTERM.
3. The server logs its ordered shutdown up to "plugin job coordinator
stopped", and then nothing more. The process does not exit until
SIGKILL.

**Expected behavior**
The server exits within a bounded time after the run drain, also when
one late step stalls. The log names the step that stalled.

**Evidence**
The stack's deployment logs show SIGTERM at 11:00:31.25. The ordered
shutdown logged its last line ("plugin job coordinator stopped") at
11:00:31.53. After that line the server logged nothing. The deployment
was still stopping 89.8 s after SIGTERM, when the Cloud stop budget ran
out at 11:02:01.03. Railway's 90 s drain window ends at about
11:02:01.25. The current code has no log lines after that point, so the
logs cannot show which step stalled. This change adds those log lines.

## What Changed

- `server/src/shutdown.ts`: add `POST_DRAIN_SHUTDOWN_BUDGET_MS` (20 s)
and `createPostDrainShutdownBudget`. It uses the same shared-deadline
step runner as the existing pre-drain budget.
- `finalizeServerShutdown` runs the app service teardown inside the
caller's post-drain budget (`app_services_shutdown`). It bounds the
run-failure report drain (`run_failure_report_drain`) and the span flush
(`instrumentation_shutdown`) to 5 s each, like the database close and
the Sentry close. The embedded PostgreSQL stop has no bound, as before.
- `server/src/index.ts`: the cancellation, runtime response, deployment
hint, delivery work and managed environment recovery stops, and the
run-log mirror flush, now run as named steps in the shared post-drain
budget. The same budget then goes to `finalizeServerShutdown`.
- Failures and timeouts use the existing "shutdown step failed" /
"shutdown step timed out" log lines with the step name.

## Verification

- Red before the change: the new test "bounds the run-failure report
drain and the span flush" failed by a 30 s test timeout, because the old
code waited forever. The budget tests failed because the post-drain
budget did not exist.
- Green after the change: `cd server && npx vitest run
src/shutdown.test.ts` gives 32 passed.
- New tests: a teardown that never settles still reaches the database
close, the provider stop, the Sentry flush and the exit continuation. A
stalled report drain and a stalled span flush time out by name. Steps
after the run drain share one deadline.
- Typecheck: the server's lower layer (with `shutdown.ts`) passed
locally. The `index.ts` layer was killed by this machine's memory limit,
so required CI covers it.

## Risks

- Low risk. Behavior changes only when a late shutdown step takes longer
than its bound. Then the shutdown continues without it, as the pre-drain
steps already do.
- A timed-out setup-token lease release stays a durable record for the
startup reaper, as the existing code comments describe.
- The run-log mirror flush now gets what is left of the 20 s budget. A
very large tail upload on a busy restart can time out. Before this
change, the platform SIGKILL stopped it at the end of the drain window.
- The new per-step log lines add about nine info lines to each shutdown.

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

## Model Used

- Anthropic Claude Opus 5.5 (`claude-opus-5-5`), run through Claude Code
with tool use (shell, file edits, Sentry and Railway read tools).
Reasoning mode: standard.

## 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: devinfoley <139239+devinfoley@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
canary/v2026.1202.0-canary.880000
2026-12-02 04:11:05 -08:00
7636441c46 fix(recovery): hold an agent comment wake behind a refused workspace writer hold (#23475)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - A run fails setup with "The workspace still has an unfinished writer
or save operation." when the task's remote workspace is still held by an
earlier writer run that did not finish its save, and the hold refuses a
start.
> - #22103 and #23446 stopped the assigned-work sweep, the bounded retry
and stranded recovery from starting runs behind such a hold. On staging,
the failures are now single runs, not pairs.
> - The remaining single failures come from comment wakes. An agent
comments on a task (for example, an automated status note), and the
route wakes the assignee. The assignee's latest run on that task already
failed on the same refused hold, so the new run can only fail the same
way.
> - The blocker-stall wake already checks this case before it wakes a
waiter. The comment wake paths do not check it.
> - This pull request makes the comment wake paths skip the assignee
wake for an agent-authored comment while the assignee's latest run on
the task failed on that hold and the hold still refuses a start.
> - The benefit is no new failed run for each automated comment on a
held task. The comment stays on the task, and the existing recovery
continues the task when the hold settles.

## Linked Issues or Issue Description

Refs #22103
Refs #23446
Refs #21221

**What happened?**
On staging, after #22103 and #23446 were deployed, two runs failed setup
with the writer-pending message (`setup_failed`, before provider work).
Each run was started by an agent comment on a task: one through
`issue.comment`, one through `issue.comment.reopen`. Both tasks have
workspaces whose writer run ended long ago with an unsaved workspace, so
the hold refuses a start. In one task, the assignee's previous run had
already failed setup on the same hold. No retry followed either failure,
so #23446 works. But every new automated comment on such a task starts
one more run that fails.

**Expected behavior**
An agent comment does not start a run that can only fail setup on a
refused workspace hold. The comment is kept. The task continues through
stranded-work recovery and the released-writer pass when the hold
settles. A person's comment still wakes the assignee.

**Steps to reproduce**
1. Bind an in-progress task to an execution workspace whose remote
writer is an ended run with dirty, unsaved state, so the hold refuses a
start.
2. Fail the assignee's latest run on the task with `setup_failed` and
the writer-pending message.
3. As another agent, post a comment on the task (`POST
/api/issues/:id/comments`, or `PATCH /api/issues/:id` with `comment`).
4. Before this change, the route wakes the assignee, and the new run
fails setup on the same hold.

**Paperclip version or commit**
`master` at 5a956b724.

**Deployment mode**
Hosted (cloud sandbox workspaces).

## What Changed

- `server/src/services/remote-workspace-writer-hold.ts`: add
`agentTaskWorkspaceHoldRefusesStart(db, { companyId, issueId, agentId
})`. It reads the agent's latest run on the task (indexed on company,
`contextSnapshot.issueId` and `createdAt`). It returns true only when
that run failed setup on the writer hold and the hold still refuses a
start (`failedRunWorkspaceHoldRefusesStart` from #23446).
- `server/src/routes/issues.ts`: the POST comment and PATCH comment wake
paths skip the assignee wake when the actor is an agent and that check
is true. In the PATCH path, the same result (read once per request) also
holds the `issue_status_changed` wake, for example when an agent moves a
blocked task to `todo` with a comment. The check runs only when the
route would otherwise wake the assignee. If the check fails to read, the
wake goes through as before.
- Person comments, a settled hold, and a later run of the assignee on
the task all keep today's behavior.
- The rule needs evidence that reservation already refused this hold
(the latest run failed on it). Reservation can still release an
unchanged or superseded writer before it reads the hold, so a hold read
alone could hold a wake that reservation would admit.
- Tests: `released-writer-escalation.test.ts` checks the helper against
Postgres: true behind the refused hold, false for another agent, false
after the hold releases, and false after a later run.
`issue-comment-reopen-routes.test.ts` checks both wake paths: an agent
comment behind a refusing hold wakes nobody, a person's comment still
wakes the assignee and does not read the hold, and an agent comment
wakes the assignee when the hold does not refuse. A PATCH that moves a
blocked task to `todo` with an agent comment wakes the assignee zero
times behind a refusing hold and once otherwise.

## Verification

- `cd server && npx vitest run
src/__tests__/issue-comment-reopen-routes.test.ts
src/__tests__/released-writer-escalation.test.ts`: 123/123 and all
released-writer tests pass.
- With the route check disabled, the two "agent comment behind a
refusing hold" cases fail (one wake, expected none). With only the
status-wake check removed, the blocked-to-`todo` case fails.
- Related suites (11 files: issue comment routes, comment wakeups,
queued comments, scheduled retry routes, retry scheduling, assigned-work
invariant, released-writer escalation): 457/457 pass.

## Risks

- Low. The new read runs only for an agent-authored comment that would
wake the assignee. It is one indexed query, plus the workspace hold read
only when the latest run failed on the hold.
- An agent comment on a task behind a refused hold no longer starts a
run. The assignee reads the comment on its next run, which stranded-work
recovery and the released-writer pass start when the hold settles.
- Person comments are unchanged.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude
Code with tool use (shell, git, GitHub CLI) 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
- [ ] I have updated relevant documentation to reflect my changes (not
needed: no command or documented behavior 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: paperclipbugbot <356415228+paperclipbugbot@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 02:26:46 -08:00
Tonio 2bef9e3a80 Keep Connect account steady when switching credential methods (#23480)
## Thinking Path

> - Paperclip manages work for AI agents.
> - Agents use provider accounts.
> - People connect those accounts in a dialog.
> - Switching methods can move the controls.
> - A shared minimum panel height keeps the footer steady.

## Linked Issues or Issue Description

Related PR: #23474.

**What happened?**

The API key panel used less space than the subscription panel.

**Expected behavior**

Changing methods keeps the dialog height steady.

**Steps to reproduce**

Open Connect account and switch from subscription to API key and back.

## What Changed

Apply a common minimum height to credential cards inside Connect
account.

## Verification

All 10 AgentProviderConnection component tests passed. Compare both
directions in the staging dialog.

## Risks

Long instructions or additional controls can still grow beyond the
minimum height.

## Model Used

OpenAI GPT-6, via Codex.

## Checklist

- [ ] 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)
- [ ] 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
- [ ] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [ ] 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
- [ ] I have run tests locally and they pass
- [ ] I have added or updated tests where applicable
- [ ] I have updated relevant documentation to reflect my changes
- [ ] 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
canary/v2026.1202.0-canary.879800
2026-12-02 09:00:36 +00:00
Tonio 28c44fa2a1 Use in-panel OpenAI sign-in from Other Models (#23474)
## Thinking Path

> - Paperclip lets people connect provider accounts for agent work.
> - The Connect account dialog includes a provider grid.
> - OpenAI subscription setup from that grid still uses the footer to
start sign-in.
> - This change uses the same sign-in panel as direct OpenAI setup.
> - People can see when authorization is pending and when they can
proceed.

## Linked Issues or Issue Description

**Subsystem affected**

Agent settings and managed AI accounts. Related change: #23361.

**Current behavior**

OpenAI under Other Models presents a sign-in hyperlink and repurposes
the footer during authorization.

**Proposed behavior**

Start device authorization from the panel. Show Waiting… there and keep
Next disabled while authorization is pending.

## What Changed

- Enable inline subscription controls for OpenAI when opened from the
provider grid.
- Exercise the grid presentation in the sign-in panel tests.

## Verification

- All 33 focused agent connection and sign-in panel tests passed.
- Open Connect account, select Other Models, select OpenAI, and click
Sign in.

## Risks

The changed path shares completion handling with direct subscription
setup. Provider authentication and access settings still use the same
APIs.

## Model Used

OpenAI GPT-6 through Codex with local editing, terminal tests, 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)
- [ ] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [ ] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [ ] I will address all Greptile and reviewer comments before
requesting merge
canary/v2026.1202.0-canary.879700 nightly/v2026.1202.0-nightly.1
2026-12-01 23:57:07 -08:00
Nicky Leach 5a956b724b fix(agents): set agents up again when their environment driver changes (#23449) canary/v2026.1202.0-canary.879600 2026-12-01 23:33:24 -08:00
Devin FoleyandPaperclip 725a9e36b6 fix(connections): let a dedicated account serve every agent picked for its connection (#23431)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - A GitHub connection can use "A dedicated account for an agent", for
example a bot account that an agent uses instead of the person who gives
instructions
> - The account lives on the grant of the agent that signed in. Core
gives one connection to one signed-in agent
> - A team often wants several agents to use the same bot account, or to
move a bot account to a new agent. Today each agent needs its own GitHub
sign-in as the bot
> - The permissions page also lets an owner pick more agents for the
connection, which looks like sharing but gives those agents nothing
> - Sharing a credential must stay under the owner's control: an install
of a connection needs only `agents:configure`, which agents and
operators have, so installs cannot be the share signal
> - This pull request adds an explicit share list for a dedicated
account. Only the person who connected the account, a company owner or
admin, or an instance admin can change it
> - The benefit is that a bot account can serve several agents without a
new sign-in, and no one else can attach the account to their agents

## Linked Issues or Issue Description

No public issue exists.

**What happened?**
A GitHub connection with a dedicated account was signed in for agent A.
The owner then picked agent B for the same connection on the permissions
page. The page showed "Used only by A" and also "2 agents selected" with
A and B. Agent B made no GitHub tool calls through the connection, and
its git work used the responsible person's GitHub account. There was no
way to let agent B use the bot account without a second GitHub sign-in
as the bot.

**Expected behavior**
The owner of a dedicated account can share it with chosen agents, and
those agents use it for managed git and the connection's tools. No one
else can share it.

**Steps to reproduce**
1. Add a GitHub connection with "A dedicated account for an agent" and
pick agent A.
2. On the connection's permissions page, pick agent B too.
3. Start a run for agent B that pushes with git. See that it uses the
responsible person's account, and that the page offers no way to share
the bot account.

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

**Deployment mode**
Any deployment with a GitHub connection that uses a dedicated agent
account.

## What Changed

- `agent-grant.ts`:
- `agentGrantScope`: a dedicated grant serves its signed-in agent, or an
agent with a share row (a `connection_grant_delegations` row on the
agent grant). Installs and app profile bindings do not count.
- `replaceSharedAgents`: replaces the share list in one transaction, and
checks share permission again on the locked grant row, so a share
request cannot land after another person's reconnect. It accepts only
active agents of the company, skips the signed-in agent, refuses an
inactive grant, and records a `connection_grant.shared_agents_replaced`
audit event.
- `sharedAgentGrantIds` and `dedicatedIdentityAgentIds` read the share
list.
- New route `PUT
/tool-connections/:connectionId/grants/:grantId/shared-agents` with
`replaceDedicatedAccountAgentsSchema` (at most
`DEDICATED_ACCOUNT_SHARE_LIMIT`, 1000 agents, the same as a grant's
member audience; the picker does not send a larger selection and says
why). Only a board user can call it, and only when the user connected
the account, is a company owner or admin, or is an instance admin.
Agents and other operators get 403.
- The credential access, tool gateway and token broker lookups for a
per-agent connection use `agentGrantScope`.
- `git-credentials.ts`: managed git identity uses the share list. An
agent that has its own dedicated account uses its own account first.
Live shared grants come before revoked ones, and a run still asks for a
reconnect when no live grant remains.
- The grants endpoint returns `dedicatedAgentIds` (the signed-in agent
and the shared agents) and `canShareDedicatedIdentity` for the viewer.
- Existing delegation lookups match only personal grants, so a share
never acts as a personal delegation.
- Every path that replaces a dedicated grant's credential (the connect
upsert, the cloud connector callback and the credential reconnect) calls
`reauthorizeAgentGrant`. It locks and rereads the grant, records the new
authorizer as the grant's `createdByUserId`, and clears the share list
when the authorizer or the provider account changes. So only the person
behind the current credential, or an admin, can share it.
- `revokeConnectionGrant` keeps the share rows of a dedicated agent
grant, so a revoked account asks shared agents to reconnect instead of
switching them to a person's account. A reconnect reactivates the same
grant with its shares.
- Permissions page: the GitHub identity card lists each agent that uses
the account and, for a person who can share it, shows "Share this
account with other agents". The sharing state lives in the new
`useDedicatedAccountSharing` hook.
- Agent Tools tab: uses `dedicatedAgentIds`, so a shared agent shows the
shared account.
- `doc/execution-github-identity.md`: describes the share list and who
can change it.

## Verification

- `pnpm --filter @paperclipai/server typecheck` and `pnpm --filter
@paperclipai/ui typecheck` pass.
- `server/src/__tests__/agent-grant-scope.test.ts` (7 tests, including a
reconnect that clears shares and a share request whose permission is
checked against the locked, already-reconnected grant): the signed-in
and shared agents get the grant; installed, bound and unpicked agents do
not; a former agent keeps only its own revoked grant; the share list
accepts only active company agents, skips the signed-in agent, refuses
an inactive grant and records an audit event.
- `server/src/__tests__/dedicated-account-sharing-routes.test.ts` (3
tests): an operator with `tools:manage_connections` and a member get
403; after another person reconnects the account, the shares are cleared
and only that person (or an admin) can share; the person who connected
the account and an admin can replace the list; the grants endpoint
reports the agents and the viewer's permission.
- `github-operation-credentials.test.ts`: a shared agent uses the
dedicated account; installed and bound agents use the person's account;
an agent's own dedicated account comes first; a revoked grant for
another account does not make the identity ambiguous. 27 tests pass.
- `agent-grant-scope.test.ts` also checks that a revoke keeps the share
list (fails without the change), and
`github-operation-credentials.test.ts` checks that a shared agent gets a
reconnect error, not the person's account, after a revoke.
- UI: `DedicatedIdentity.test.tsx` (4 tests, including the sharing
picker with 800 agents and 20 unchanged rerenders under a fixed read
budget), `dedicated-github-identity.test.ts` (3 tests) and
`useDedicatedIdentityAgents.test.ts` (2 tests, 800 agents behind a read
counter).
- I ran the 92 server test files that mention per-agent connections,
agent grants, dedicated accounts or delegations: 81 files and 6852 tests
pass, including `openapi-routes.test.ts` with the new route in the spec.
The other 11 files are integration tests that skip without their test
database. I also ran 34 UI test files for the apps pages, the Tools tab
and replay masking: 457 tests pass.
- `tests/runner-e2e/source-sdk-public-inputs.json` is regenerated with
`source-sdk-public-inputs.mjs --write`, because the change touches
pinned `packages/shared` files.

## Risks

- No schema change: the share list reuses
`connection_grant_delegations`.
- Agents keep their current identity after this change. An agent uses a
shared account only after an owner or admin shares it.
- A connection manager who is not an admin can still remove a share
through the existing delegation delete route. That only reduces access.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use
(shell, file edits, read-only database queries on a hosted instance for
the diagnosis).

## 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>
canary/v2026.1202.0-canary.879500
2026-12-01 22:40:42 -08:00
29a45b42db fix(recovery): stop retrying a setup failure behind a refused workspace writer hold (#23446)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - A run can fail setup with "The workspace still has an unfinished
writer or save operation." when the task's own remote workspace is still
held by an earlier writer run that never finished saving.
> - #22103 stopped the assigned-work sweep from looping a board
escalation behind such a hold. Staging still showed these failures in
pairs.
> - Each pair is one continuation (a sweep continuation, a delivered
fresh continuation, or a comment that reopened the task) whose run fails
on the hold, followed by an immediate bounded `transient_failure` retry
from the failure path, which fails the same way.
> - `scheduleBoundedRetryForRun` never reads the workspace hold before
it schedules that retry.
> - This pull request makes the retry scheduler, the assigned-work sweep
and stranded recovery agree: while the hold refuses a start, nobody
starts another run; the task goes to the board-owned stranded hold,
which the sweep (#22103) and the released-writer pass (#21221) continue
once the writer releases.
> - The benefit is one failed run per held workspace instead of repeated
pairs, and no task left in progress with nothing moving it.

## Linked Issues or Issue Description

Refs #22103
Refs #21221
Refs #21394
Refs #23051

**What happened?**
On staging, tasks whose workspace writer hold stayed refused produced
failed runs in pairs, seconds apart:
- A continuation run failed setup with the writer-pending message
(`setup_failed`, `executionRecovery: { kind: "bootstrap",
providerWorkStarted: false }`).
- The failure path then scheduled a bounded `transient_failure` retry of
that run (`scheduledRetryAttempt: 1`), which failed setup on the same
hold.
One pair started from a delivered fresh continuation (`source:
execution.reconciled`), another from an assigned-work sweep continuation
of a task a comment had reopened (`source:
issue.assigned_work_invariant`, `assignedWorkViolation: retry_offered`).

**Expected behavior**
While the task's workspace writer hold refuses a start, no retry or
continuation is started. The task is escalated once to the board-owned
stranded hold and continued once after the hold releases.

**Steps to reproduce**
1. Bind an in-progress task to an execution workspace whose remote
workspace writer is an ended run with dirty, unsaved state (the hold
refuses a start).
2. Fail the task's latest run with `setup_failed` and the writer-pending
message, before provider work, as an assigned-work continuation.
3. Call `scheduleBoundedRetryForRun` for that run: before this change it
schedules a retry.
4. Run the assigned-work check: before this change it continues the task
(`retry_offered`).
5. Run stranded recovery: before this change it skips the task because
the sweep owns the failed continuation, so with the sweep held back the
task would have no path.

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

**Deployment mode**
Hosted (cloud sandbox workspaces).

## What Changed

- `server/src/services/remote-workspace-writer-hold.ts`: add
`failedRunWorkspaceHoldRefusesStart(db, run)`: true when the run failed
setup with the writer-pending message and its task's workspace hold
still refuses a start (`remoteWorkspaceHoldRefusesStart`). Export
`REMOTE_WORKSPACE_WRITER_PENDING_CODE`, the code reservation already
uses.
- `server/src/services/heartbeat/retries.ts`:
`scheduleBoundedRetryForRun` returns `not_scheduled` with `errorCode:
remote_workspace_writer_pending` for such a run. Other runs do not read
the database for this check.
- `server/src/services/recovery/assigned-work-sweep.ts` (+
`assigned-work-invariant.ts` fact): the hold read from #22103 now also
covers a task whose latest run failed on the hold. For an open task with
a `retry_offered` or `no_pending_path` violation behind a refused hold,
the sweep reports `left_to_hold_owner` instead of continuing it,
including in the locked re-check.
- `server/src/services/recovery/service.ts`: stranded continuation
recovery does not count such a failed run as owned by the sweep, so it
escalates the task to the board hold instead of skipping it.
- Tests: `retries.test.ts` (refused hold: no retry and no successor;
released hold: retry scheduled) and `released-writer-escalation.test.ts`
(reopened task behind the refused hold: sweep leaves it, stranded
recovery escalates with no successor run, and the released-writer pass
continues it once after release).

## Verification

- `cd server && npx vitest run src/services/heartbeat/retries.test.ts
src/__tests__/released-writer-escalation.test.ts
src/__tests__/assigned-work-invariant.test.ts
src/services/heartbeat/recovery.test.ts`: 210/210 pass.
- The 19 other server test files that call
`reconcileStrandedAssignedIssues` pass on this head (18 files: 1,350
passed, 19 skipped; `workspace-recovery-admission.test.ts`: 149/149).
- Each part is needed. With the scheduler check removed, the retries
test schedules a retry (`scheduled`, expected `not_scheduled`). With the
stranded ownership change removed, the escalation test leaves the task
in progress (expected `blocked`). With the sweep change removed, the
sweep continues the task (expected `left_to_hold_owner`).
- I could not run the full server `tsc` locally (the sandbox's memory
limit stops it). CI must confirm typecheck, build and the full suite.

## Risks

- Low to medium. The new reads happen only for runs that failed setup
with the writer-pending message: one join from the task to its execution
workspace and one hold read.
- A task behind a long refused hold now waits on the board-owned
stranded hold instead of failing repeatedly. The sweep and the
released-writer pass already continue that hold when the writer
releases.
- If the hold is already free when these paths look, behavior is
unchanged: the retry is scheduled and the sweep continues the task.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude
Code with tool use (shell, git, GitHub CLI) 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
- [ ] I have updated relevant documentation to reflect my changes (not
needed: no command or documented behavior 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: paperclipbugbot <356415228+paperclipbugbot@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
nightly/v2026.1202.0-nightly.0 canary/v2026.1202.0-canary.879400
2026-12-01 20:41:33 -08:00
Devin FoleyandPaperclip ab2183aaed test(server): settle coalesced work before measuring idle drain (#23437)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Image publication requires source verification for the same commit.
> - The maintenance suite checks work committed during an idle drain.
> - Managed channel pools batch change notifications for 50 ms.
> - The test API helper freezes the child clock when a response ends.
> - A notification can then retain its work token while its timer cannot
fire.
> - This change advances the existing test clock before measuring quiet
drain.

## Linked Issues or Issue Description

Refs #23415 and #22523.

**What happened?**

[Source verification
failed](https://github.com/paperclipai/paperclip/actions/runs/46783252165/job/143126872561)
in `maintenance-server-routes.test.ts`. The case `processes the first
ordinary external-object producer committed during idle drain and
becomes quiet again` timed out with one tracked work token. The image
watcher then canceled [Docker
publication](https://github.com/paperclipai/paperclip/actions/runs/46783252123).

The issue write notifies the managed channel pool worker. That worker
batches notifications for 50 ms. The API helper freezes the child clock
after the response. The test then waits for quiet without advancing that
timer. Response timing determines whether the worker finishes first.

**Expected behavior**

The test must let bounded change notifications finish their drain
reconciliation. It must still prove that provider work does not start
during drain, that the database stays quiet across the measured drain
windows, and that deferred work resumes afterward.

**Steps to reproduce**

Run `pnpm exec vitest run
server/src/__tests__/maintenance-server-routes.test.ts -t 'processes the
first ordinary external-object producer'` with the required local
runtime outputs prepared. The unchanged test failed locally with
`idle.active: 1` and no pending database request. Temporary local
tracing identified the retained token at the managed-channel-pool
notification in `notifyIssueRecovery`. That tracing is not part of this
change.

## What Changed

- Use the existing bounded `settleClock` helper after the held producer
request completes.
- Keep the existing provider-request, quiet-window, restart, and retry
assertions.

## Verification

- Red: the unchanged case failed locally with the same 30-second
settling timeout as CI. A second diagnostic run identified the coalesced
managed-channel-pool token.
- Green: the final focused case passed in 24.82 seconds on Node 24.23.0
with pnpm 9.15.4 and embedded PostgreSQL 18.1.
- The complete maintenance file passed on `58ccfb513f7`: 17/17 cases in
246.23 seconds. The subsequent change only removes the added comment;
the focused case was rerun after that cleanup. Command: `pnpm exec
vitest run server/src/__tests__/maintenance-server-routes.test.ts`. This
includes the real idle windows, committed-during-drain producer,
provider-error retry, shutdown recovery, and signed warm-claim cases.
- `pnpm verify --base origin/master` selected 1,993 of 2,353 test files.
I interrupted that broad local run and ran the complete maintenance file
above. Required CI supplies broad verification.
- CI attempt 1 on `f2a83ce4ba4` lost the runners for [General tests
(server
6/20)](https://github.com/paperclipai/paperclip/actions/runs/46788843123/job/143146044550)
and [serialized suites
(9/9)](https://github.com/paperclipai/paperclip/actions/runs/46788843123/job/143146044125).
Both job logs report a runner shutdown at 01:40:57 UTC, followed by
cancellation. These interrupted jobs are not passes. The existing
first-attempt runner-loss workflow retries after the parent CI run
completes, if no other job has a source failure.
- [CI attempt
2](https://github.com/paperclipai/paperclip/actions/runs/46788843123/attempts/2)
passed on final head `f2a83ce4ba44e639902ae57db1aba233562e3293`. Both
interrupted jobs passed on retry. No failed or pending checks remain
among the 72 reported checks; applicable checks passed and optional
lanes were skipped. Greptile scored this head 5/5 with no unresolved
review threads. Source verification and image publication checks remain
enabled.

## Risks

The change affects one test. It uses the suite's existing bounded
clock-settling helper. The drain assertions still reject provider work
and database polling in the measured windows. No production source,
timeout, schema, or deployment setting changes.

## Model Used

- OpenAI `gpt-6.1-sol` through Codex in T3 Code, with xhigh reasoning,
repository tools, shell commands, and local test execution.

## Checklist

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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
canary/v2026.1202.0-canary.879300
2026-12-02 01:50:08 +00:00
Nicky LeachandPaperclip 9092b0c667 Support live Antigravity credential writeback for both token stores (#23397)
## Thinking Path

> - Paperclip manages the connections agents use to work.
> - A run can outlive the Google refresh token that started it.
> - Antigravity writes a rotated token to a private file. Its two
runtimes use different paths and JSON layouts.
> - The task already records which connection supplied its sign-in.
> - Runner reports a rotation on PRP. Core saves it to that connection
if the saved generation still matches.
> - The next run can start with the rotated token.

## Linked Issues or Issue Description

Refs #23395. Refs #23168.

This PR targets `master` and includes the capability-based handler from
#23395. Merging this PR lands the handler and Antigravity writeback
together.

**Current behavior**

A managed Antigravity sign-in reaches the plugin as an environment
credential. Core waits for task retirement to collect a refresh.

**Proposed behavior**

Seed a private auth-file. Observe refresh-token changes for the ordinary
ACP server and the unified CLI. Use the existing credential update event
to save them during execution.

**Reason and benefit**

A long-running task can keep its source connection current across
successive rotations.

## What Changed

- Dispatch PRP credential updates to the live writeback capability
declared for the bound harness and execution target.
- Send Antigravity subscriptions as auth-file credentials to environment
task providers. Keep Gemini API keys and previously admitted environment
credentials on their existing paths.
- Watch the ACP token file and the unified CLI token file. Compare the
refresh token, copy it to the bound file, and emit the existing
secret-free event.
- Bind writeback to the original grant, secret, session epoch, and
credential generation. Save the next generation in the same transaction.

## Verification

- Reproduced the failed final Google save hanging on the next session
close. After commit `2b3e7897cd`, both focused cleanup suites passed (43
tests). The regression covers two overlapping close retries after the
credential home is released and checks that the saved credential is
removed only after persistence succeeds.
- All 21 Rust observer tests passed on both builds. They cover
interruption between the host file and event journal writes, a further
rotation before restart, and a reconnect that supersedes the task.
- On the legacy build, 422 Runner TypeScript tests passed. With the
merged unified CLI on this branch, all 126 tests in the auth, credential
staging, and runtime host suites passed.
- The two plugin writeback database suites passed (39 tests). A refresh
that starts before task stop cannot overwrite the final token after
stop.
- One run timed out in an unrelated process-retirement test. All three
suites passed together on repeat. All OAuth documents in these tests are
fixtures. No live Google sign-in was exercised.

## Risks

- The agent and any process it starts are trusted not to substitute
another account’s refresh token in the harness credential file. Core
accepts the file’s refresh token for the original connection only while
the grant, secret, session epoch, and expected credential generation
still match. Substitution within that boundary is an accepted risk.
[Review
finding](https://github.com/paperclipai/paperclip/pull/23397#discussion_r4759261984)
- Deploy with a plugin and Launcher that support the new auth-file
provider. This branch includes the unified CLI from #23168 and still
observes the legacy token format.

> 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 local code execution 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: Paperclip <noreply@paperclip.ing>
2026-12-02 01:49:46 +00:00
DottaandPaperclip c47452699a perf(server): speed up headless channel posts, replies, and SSE bursts (#23426)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Headless channels, threads, and SSE streams let agents and tools
exchange high-rate status updates and structured messages
> - A local headless benchmark on `origin/master` (`828b8c2a2a`) showed
channel posts at 226 req/s (`c=1`) and 342–346 req/s (`c=32`), with
database tuple scans growing linearly with company issue count and live
SSE streams falling behind under burst
> - CPU, heap, and PostgreSQL profiling traced the bottlenecks to an
unindexed `O(N)` `MAX(issue_number)` scan per post, redundant SQL
round-trips and uncached transactional `instance_settings` reads inside
the company row lock, upfront `FOR UPDATE` locks on normal replies,
serial per-event SSE database checks, and routing through 64 unrelated
Express sub-routers
> - This pull request adds an online-compatible `issues(company_id,
issue_number)` index so `MAX(issue_number)` floor checks run as `O(log
N)` index-only probes inside the `companies` counter update, eliminates
redundant channel/view/savepoint queries, locks parent issues on replies
only when `clientRequestId` or `after` is supplied, mounts headless
routers early, and extracts a unified bounded SSE/replay filter pipeline
with creation-time `kvLabels`/`tagLabels` snapshots and pre-change label
history lookup
> - The benefit is 2.09x to 2.67x higher channel post throughput (473
req/s at `c=1`, 885–924 req/s at `c=32`), 1.75x higher reply throughput
(1,221 req/s at `c=32`), 55.5% less heap allocation, `O(log N)`
index-only counter floor checks as issue count grows, and 100% real-time
SSE delivery under burst

## Linked Issues or Issue Description

**What existing behavior does this improve?**

`POST /api/companies/:companyId/channels/posts`, `POST
/api/companies/:companyId/issues/batch`, `POST
/api/issues/:id/comments`, and `GET
/api/companies/:companyId/events/stream` throughput, tail latency, heap
allocation, and database scalability.

**Subsystem affected**

- `packages/db/ — Drizzle schema & migrations`
- `server/ — REST API & orchestration services`

**Current behavior**

On `origin/master` (`828b8c2a2a`, Node `v26.4.0`, `darwin-arm64`, local
`embedded-postgres` with 2 live SSE subscribers):
- `createChannelPost` and `createBatchIssuesPlan` run `SELECT
coalesce(max(issue_number), 0) FROM issues WHERE company_id = $1` on
every call without an index on `(company_id, issue_number)`, scanning
every issue row in the company (`2,029` tuples/request at ~2,400
issues).
- `ensureChannel` ignores the channel row already fetched by
`assertChannelPathWritePreconditions`, runs `INSERT ... ON CONFLICT DO
NOTHING`, and selects the channel a second time.
- `createChannelPost` holds the `companies` row lock while calling
`logActivity(tx, ...)` (which skips the `instance_settings` read-through
cache on `PgTransaction` handles and opens a nested `SAVEPOINT` +
`SELECT pg_current_xact_id()`), running two round-trips in
`appendBoardEvent`, and re-querying four tables in
`loadHeadlessIssueView`.
- `POST /api/issues/:id/comments` selects all 89 `issues` columns via an
unindexed `upper(identifier)` scan when given an identifier and
unconditionally acquires `SELECT ... FOR UPDATE` on `issues` even when
neither `idempotencyKey`/`clientRequestId` nor `after` is supplied.
- `GET /api/companies/:companyId/events/stream` evaluates live events
one at a time with serial `channels` and `issues` queries per event per
subscriber and misses creation-time `labels`/`tagLabels` snapshots
during `?label=` filtering, delivering only ~302–373 of 1,000 events
during a 1,000-message burst.
- `headlessChannelsSchemasRoutes` and `headlessQueuesEventsRoutes` sit
behind 64 unrelated `api.use(...)` Express sub-routers (`15%` CPU in
`path-to-regexp` and `router`).

**Proposed behavior**

- Add an online-compatible `CREATE INDEX CONCURRENTLY IF NOT EXISTS
"issues_company_issue_number_idx" ON "issues" USING btree ("company_id",
"issue_number")` migration (`0513_closed_wither.sql`) and compute
`greatest(companies.issue_counter, coalesce((select
max(issues.issue_number) from issues where issues.company_id = $1), 0))
+ count` directly in `UPDATE companies`, preserving exact monotonic
counter floors (including lone backdated imports) via an `O(log N)`
index-only backward probe in a single round-trip.
- Return the existing channel directly in `ensureChannel` when
`allowUpdateExisting` is false, serialize newly created
`HeadlessIssueView` objects in memory, sort tag labels canonically
before `ON CONFLICT DO NOTHING` upserts, and combine
`pg_advisory_xact_lock` + `INSERT INTO board_events` into one SQL
statement.
- Pre-create `createActivityDetailsRedactor(db)` before transactions so
the 2-second `instance_settings` cache applies, prime
`pg_current_xact_id()` on existing `RETURNING` clauses, and skip nested
`db.transaction` savepoints in `persistActivity` when `db` is already a
`PgTransaction` while preserving `databaseWorkContext` attribution.
- Probe `eq(issues.identifier, normalizedUpper)` first so identifier
lookups use `issues_identifier_idx`, project only the 11 required
columns in issue route interceptors, narrow `--as` profile collision
checks to non-terminated company agents with JS `.trim()` +
`deriveAgentUrlKey` parity, and acquire `FOR UPDATE` on comment creation
only when `clientRequestId` or `after` is present.
- Extract `server/src/services/headless-board-event-stream.ts` and stamp
commit-time `kvLabels` and `tagLabels` snapshots onto issue-scoped event
payloads inside `appendBoardEvent`, so `queryBoardEventsAfter`,
`waitForBoardEvent`, and `filterBoardEventsBatchForSubscriber` share a
single stateless `eventMatchesFiltersAndAccess` verdict pipeline without
cross-batch label caches.
- Mount `headlessChannelsSchemasRoutes` and `headlessQueuesEventsRoutes`
right after `headlessIdentityRoutes` with `headlessHeartbeat` wired in
`server/src/app.ts`.

**Measured performance impact**

- `POST /channels/posts` (`c=1`): `226.4` -> `473.1 req/s` (`2.09x`),
p50 `4.27ms` -> `2.05ms`, p99 `6.98ms` -> `3.15ms`
- `POST /channels/posts` (`c=32`, single channel): `346.4` -> `885.5
req/s` (`2.56x`), p50 `91.8ms` -> `35.4ms`
- `POST /channels/posts` (`c=32`, 16 channels + 2 live SSE clients):
`342.4` -> `924.6 req/s` (`2.70x`), p50 `93.3ms` -> `33.2ms`, live SSE
events delivered during run `302` -> `1,000 / 1,000`
- `POST /issues/:id/comments` (`c=32`): `696.2` -> `1,221.6 req/s`
(`1.75x`), p50 `44.9ms` -> `25.3ms`
- Profiled 1,500 mixed messages (`c=32`): heap allocated `2,369 MB` ->
`1,054 MB` (`-55.5%`).

**Breaking changes**

None. All request/response schemas, status codes, idempotency conflict
rules, `after` stale-cursor checks, gapless `board_events.seq` commit
ordering, and private channel/issue revocation rules remain unchanged.

## What Changed

- Added `issues_company_issue_number_idx` in
`packages/db/src/schema/issues.ts`,
`packages/db/src/migrations/0513_closed_wither.sql` (`CREATE INDEX
CONCURRENTLY IF NOT EXISTS`), and `MIGRATIONS_WITH_TOP_LEVEL_STATEMENTS`
in `packages/db/src/client.ts`.
- Updated `server/src/services/headless-common.ts`,
`server/src/services/headless-channels.ts`, and
`server/src/services/headless-labels-batch.ts` to compute exact indexed
`MAX(issue_number)` counter floors inside `UPDATE companies`, return
existing channels early in `ensureChannel`, prime transaction XIDs, sort
tag label names before upsert, serialize newly created
`HeadlessIssueView` responses in memory, include `kvLabels` and
`tagLabels` snapshots on creation/ready board events, and combine
`pg_advisory_xact_lock` + `INSERT INTO board_events` into a single
round-trip.
- Updated `server/src/services/activity-log.ts` to accept an optional
pre-built `ActivityDetailsRedactor` and skip nested `db.transaction`
savepoints when `persistActivity` runs on an existing `PgTransaction`
while preserving `databaseWorkContext` attribution.
- Updated `server/src/routes/headless-channels-schemas.ts` to use
`resolveIssueCommentTarget`, pre-create the activity redactor on `db`,
prime transaction XIDs on comment inserts, and lock the parent issue
`FOR UPDATE` only when `clientRequestId` or `after` is supplied.
- Extracted `server/src/services/headless-board-event-stream.ts`
(re-exported from
`server/src/services/headless-events-schedules-interactions.ts`) and
updated `server/src/services/headless-common.ts`,
`server/src/routes/headless-queues-events.ts`, and `server/src/app.ts`
to stamp commit-time `kvLabels` and `tagLabels` snapshots in
`appendBoardEvent`, unify single-event, replay, and batched SSE
filtering without cross-batch label caches, and mount headless routers
early with `headlessHeartbeat`.
- Added regression tests in
`server/src/__tests__/headless-channels-schemas-batch.test.ts` (drifted
`issueCounter` + lone backdated `#95` floor, concurrent tag upserts, and
tab/CJK `--as` profile parity) and
`server/src/__tests__/headless-queues-leases-events.test.ts` (live SSE
burst ordering, cold-cache `?label=urgent` `exists` tag +
`labels.changed` interleaving + unlabeled `comment.posted`, and
immediate private-channel revocation).

## Verification

- `pnpm --filter @paperclipai/db run check:migrations && pnpm --filter
@paperclipai/db exec vitest run src/migration-snapshot-drift.test.ts`
(passed, 0 blocked migrations)
- `cd server && node scripts/typecheck-layers.mjs` (0 errors across all
7 layers)
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/activity-log-responsible-user.test.ts
src/__tests__/headless-channels-schemas-batch.test.ts
src/__tests__/headless-queues-leases-events.test.ts
src/__tests__/headless-task-workflows.test.ts
src/__tests__/experimental-channels-viewer.test.ts` (5 files, 41/41
tests passed)

## Risks

- Low risk. Migration `0513_closed_wither.sql` uses `CREATE INDEX
CONCURRENTLY IF NOT EXISTS` and is registered in
`MIGRATIONS_WITH_TOP_LEVEL_STATEMENTS`, so online rollouts do not block
reads or writes on `issues`. Live SSE micro-batching re-evaluates
channel and issue visibility fresh on every drained batch without
cross-batch permission caching, preserving immediate membership
revocation.

## Model Used

- Google Gemini (Antigravity agentic coding assistant, extended thinking
mode with shell, profiling, and test execution tools)

## Checklist

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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-12-02 01:47:17 +00:00
c59a56883c fix(recovery): leave a board escalation behind a refused workspace writer hold to the released-writer pass (#22103)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The recovery service has an assigned-work sweep. The sweep continues
tasks that stopped without a clear owner.
> - Stranded-work recovery can block a task with a board escalation. The
sweep continues that task when the failed run's cause looks temporary.
> - A setup failure on the task's own workspace writer hold ("The
workspace still has an unfinished writer or save operation.") counts as
temporary. Since #23051, such a failure before provider work stays
eligible for 7 days. The sweep does not read the hold before it
continues the task.
> - Each continuation fails setup on the same hold. Recovery then
escalates the task again, and the sweep continues it again at 2, 4, 8
and 15 minute spacing.
> - The released-writer pass from #21221 already owns this escalation.
It continues the task only when the hold releases.
> - This pull request makes the sweep leave such an escalation to the
released-writer pass while the hold still refuses a start.
> - The benefit is that a held workspace no longer causes a loop of
failed runs and repeated escalations.

## Linked Issues or Issue Description

Refs #21221
Refs #21505
Refs #20273
Refs #23051

**What happened?**
On staging, a task was blocked by stranded-work recovery with a board
escalation. The assigned-work sweep continued it 5 times in 30 minutes.
Each continuation failed during setup with "The workspace still has an
unfinished writer or save operation." (HTTP 409,
`remote_workspace_writer_pending`), before any provider work. Recovery
escalated the task again after each failure. The loop stopped only when
a person cancelled the task. This error group had 45 events on staging,
and releases that already contain #21106, #21136 and #21221 still had
events.

**Expected behavior**
While the task's workspace writer hold still refuses a start, the sweep
must not continue the task. The released-writer pass must continue it
one time, after the hold releases.

**Steps to reproduce**
1. Put a task in `blocked` status with an active
`stranded_assigned_issue` recovery action that the board owns.
2. Set the action's latest run to `setup_failed` with the writer-pending
message and `executionRecovery: { kind: "bootstrap",
providerWorkStarted: false }`.
3. Bind the task to an execution workspace whose remote workspace writer
hold refuses a start (an ended writer run with dirty, unsaved state).
4. Run the assigned-work check for the task. Before this change, the
outcome is `repaired` and a continuation is created. That continuation
fails setup on the same hold.

**Paperclip version or commit**
`master` at 0d3ed4455.

**Deployment mode**
Hosted (cloud sandbox workspaces).

## What Changed

- `server/src/services/recovery/assigned-work-sweep.ts`: For a
board-owned stranded escalation whose latest run failed setup with the
writer-pending message, the sweep reads the bound workspace's writer
hold. When `remoteWorkspaceHoldRefusesStart()` is true,
`continuedBySweep` is false. The sweep then gives the
`left_to_hold_owner` outcome and does not continue the task. When the
hold has released, the sweep continues the task as before.
- `server/src/__tests__/released-writer-escalation.test.ts`: Add a
regression test that reuses this suite's stranded-task fixture (an ended
dirty writer, setup failures before provider work, and a board-owned
stranded escalation). While the hold refuses a start, the assigned-work
check gives `left_to_hold_owner`, the task stays blocked, the board
action stays active, and there is no wake. After the hold releases, the
check gives `repaired` and sends exactly one wake. The earlier version
of this PR put the test in
`failed-continuation-continues-again.test.ts`, which #22831 removed.

## Verification

- `cd server && npx vitest run
src/__tests__/released-writer-escalation.test.ts
src/__tests__/assigned-work-invariant.test.ts`: 61/61 pass on this head.
- The new test fails without the change: the outcome is `repaired`, but
the test expects `left_to_hold_owner`. With the change, the test passes.
- I could not run the full server `tsc` locally, because the sandbox's
memory limit stopped it. CI must confirm typecheck, build and the full
suite on this head.

## Risks

- Low risk. The change applies only to board-owned stranded escalations
whose latest run failed setup with the writer-pending message, and only
while the hold refuses a start.
- The sweep does one extra query (issues joined to execution workspaces)
and one hold read for each matching task. The sweep makes these calls
only when such tasks exist.
- If the hold stays refused for a long time, the task stays blocked
until the released-writer pass continues it. This is the intended owner.
Before this change, the task looped through failed continuations
instead.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude
Code with tool use (shell, git, GitHub CLI and connector) 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
- [ ] I have updated relevant documentation to reflect my changes (not
needed: no command or documented behavior 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: paperclipbugbot <356415228+paperclipbugbot@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 01:36:25 +00:00
Devin FoleyandPaperclip 90bf446ad5 Guard release onboarding with scoped source E2E (#23432)
## Thinking Path

> - Paperclip helps people manage work with AI agents.
> - A release must pass onboarding before it reaches nightly.
> - Onboarding changes already run source browser tests on PRs.
> - The published release smoke used a separate scenario, which could
drift from those tests.
> - That drift blocked the December 1 nightly after onboarding
succeeded.
> - This PR fixes the stale welcome assertion and shares the scenario
between release smoke and relevant PR E2E runs.

## Linked Issues or Issue Description

Refs #23334 and #22259.

**What happened?**

[The December 1 nightly
release](https://github.com/paperclipai/paperclip/actions/runs/46614290688)
failed twice at `The onboarding chat must queue the lead's live
welcome`. PR #23334 changed the welcome to a saved message and a
question card. The greeting endpoint succeeded with `started: true` and
`runId: null`, but the release test still required a model run. PR
browser tests did not run those release expectations against the changed
source.

**Expected behavior**

Onboarding PRs and changes to their shared dependencies must run the
release scenario before merge. Known unrelated leaf-page changes and
source-unit-test-only changes can omit the extra case. Shared and
unfamiliar source paths must keep coverage. The scenario must check the
lead's welcome and all three first-chat choices, with no model run
before the user sends a choice or message. A mismatch must fail the
required `ci / e2e` check.

**Steps to reproduce**

1. Start the Docker onboarding harness with
`PAPERCLIPAI_VERSION=2026.1130.0-canary.873300` and its provider
verification mock.
2. Run the original release smoke test.
3. Observe successful login, setup, hire, and chat entry, followed by a
timeout because the run list stays empty.

**Paperclip version or commit**

Failed release source: `7ce7d99f8af81ae90f97650ef7a8692a86c63a35`.
Published package: `2026.1130.0-canary.873300`.

**Deployment mode**

The release test uses authenticated private Docker mode. The new PR test
uses the existing disposable source E2E instance and provider
verification fixture.

## What Changed

- Check the saved welcome and the three visible choices, then require an
empty agent run list.
- Move the complete wizard, hire, and chat assertions into one shared
onboarding scenario. Keep sign-in in the authenticated release wrapper.
- Add the shared scenario to the normal PR E2E suite. Omit only this
extra case when eligible source changes are confined to the Costs or
Approvals UI page, source unit tests, and audited prose. Shared
components, hooks, libraries, server code, mixed changes, and unfamiliar
source paths keep it. The repository rules require `ci / e2e` before
merge.
- Pass the trusted CI change plan to shard selection and bind it to the
checked-out commit. Reuse the existing lightweight source-diff
eligibility gate for both Vitest and E2E, with the old Vitest export
preserved. Full and shadow CI, broad or deleted inputs, invalid plans,
and stale plans keep the case. No extra browser job or matrix is added.
- Add release smoke files to the E2E and typecheck task inputs. Test
that onboarding changes select E2E and that smoke-only changes select
their two owners without forcing unrelated lanes.
- Document the shared test command and the source and installation
coverage.

## Verification

The shared browser scenario is unchanged from
`2044ada98e953504af68febe4c196f414d0bb1ae`. The selector review fix is
based on master’s hosted-shard speed improvement. Selector and
eligibility verification covers
`236640e419d1177aafb64f3f7dd1ee49848ee707`.

- Reproduced the original nightly timeout locally against the exact
published canary.
- The extracted release scenario passed against that canary in 22.1
seconds.
- The new source E2E passed against PR source and the built UI in 32.3
seconds.
- Restored the obsolete model-run assertion temporarily. The new source
E2E failed with the same `Expected: > 0 / Received: 0` timeout. Restored
the correct assertion. The final source confirmation passed in 31.7
seconds.
- `node --test scripts/__tests__/e2e-shard.test.mjs
.github/scripts/tests/ci-plan.test.mjs
scripts/ci/test-selection-workflow.test.mjs`: all 52 tests passed after
rebase. Coverage includes unrelated changes, relevant dependencies,
rename paths, full/invalid/stale plans, exact CLI shard partitions, and
both hosted shard policies. The unrelated-change and wiring tests failed
before the filter was implemented.
- Regression selection tests failed on `TaskChatComposer.tsx` and shadow
mode before this review fix. They now keep the composer, new-agent
runtime configuration, AI connection components, hooks, libraries, and
mixed source changes.
- The 3 existing source-diff eligibility contract tests passed after
extraction into the shared module.
- `actionlint .github/workflows/pr-trusted.yml` passed.
- `node --test scripts/ci/test-selection-inputs.test.mjs`: 4 tests
passed.
- The Playwright program and focused source scenario typechecks passed.
The test-budget check and `git diff --check` passed.
- The default local source bootstrap could not load the macOS embedded
PostgreSQL binary because its distribution lacked `libzstd.1.dylib`.
Source browser verification used a separate disposable Docker PostgreSQL
16 instance. Linux CI will cover the normal embedded database path.
- Earlier [hosted release
smoke](https://github.com/paperclipai/paperclip/actions/runs/46776940022)
passed both Docker onboarding and Linux background-service onboarding at
the first fix commit. The service job first hit npm package propagation
and passed on retry after publication completed.
- `pnpm verify --explain` requested broader CI coverage because the CI
task inputs changed. The focused checks above passed; the required CI
jobs will provide broad coverage.
- [Final-revision
CI](https://github.com/paperclipai/paperclip/actions/runs/46782167000)
passed on `236640e419d1177aafb64f3f7dd1ee49848ee707`. Both required
aggregates, all 16 browser shards, and all selected typecheck, build,
server, Runner, and canary dry-run jobs passed. [Incremental CI
qualification](https://github.com/paperclipai/paperclip/actions/runs/46782166749)
also passed.
- [The new source onboarding
case](https://github.com/paperclipai/paperclip/actions/runs/46782167000/job/143123174120)
ran on the hosted Linux runner and passed in 20.8 seconds.
- [Greptile
review](https://github.com/paperclipai/paperclip/pull/23432#issuecomment-7330325410)
scored `236640e419d1177aafb64f3f7dd1ee49848ee707` 5/5 and confirmed the
shared-dependency finding is fixed. There are no unresolved review
threads.

## Risks

- This changes test coverage and CI selection. It does not change
application behavior, release permissions, or publication rules.
- The source case stays on for shared and unfamiliar source changes. It
skips only the documented leaf pages and source-unit-test-only edits in
eligible plans. Local full E2E still includes it. Extend exclusions only
after checking that a path cannot affect onboarding.
- The trusted PR workflow is loaded from master. Before merge, the
current workflow keeps the full fallback because it does not yet pass
the change plan to the shard command. The unit and CLI tests qualify the
filtered path; after merge, the new workflow environment activates it.
- The source test uses local trusted authentication. The authenticated
published-package test remains responsible for login and installation
checks. Neither run needs paid model completions.
- GitHub master rules require code-owner approval for the protected CI
changes. Those review requests are already open. There are no conflicts
or unresolved review threads.
- A replacement nightly still needs a successful release run after this
reaches master. This PR does not bypass qualification or promote beta or
stable.

## Model Used

OpenAI Codex, `gpt-6.1-sol`, with xhigh reasoning effort, terminal
tools, GitHub CLI, and Playwright. The harness does not report the
context window size.

## Checklist

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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-12-01 17:23:13 -08:00
Nicky LeachandPaperclip 54b86a6af2 Allow New Agent sign-in during computer preparation (#23435)
<!-- 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

> - People use Paperclip to set up agents for work.
> - New Agent lets a user connect a provider account.
> - A plugin can host that sign-in on a sandbox or an eligible computer.
> - The form disabled sign-in while the draft agent's computer prepared.
> - This change enables sign-in when its host is ready.
> - The user can connect the account while the task computer prepares.

## Linked Issues or Issue Description

**What happened?**

New Agent disabled the sandbox sign-in controls while the draft computer
prepared. A ready computer in the same task environment could also be
overlooked.

**Expected behavior**

The user can sign in on an eligible host while task preparation runs. A
connection test that uses the draft computer waits for it.

**Steps to reproduce**

Open New Agent with a draft computer in preparation. Select a harness
that supports sandbox sign-in. The login panel opens with its controls
disabled.

**Additional context**

Related to #23425, which added login driver preferences.

## What Changed

- Separate readiness of the Connect step from readiness of the draft
computer.
- Allow the user to request an available computer in the same
environment for sign-in.
- Keep connection tests, keyboard submission of credentials, and setup
completion behind the task computer readiness check.
- Document the behavior and cover both login hosts in the rendered New
Agent flow.

## Verification

- Reproduced the disabled sandbox control and the unavailable fallback
action in failing regression tests. Both passed with the fix.
- The UI typecheck passed. All 18 focused provider sign-in and host
readiness tests passed.
- The selected local UI suite passed 4,152 tests with one skip. The
broader local verification run failed in four CLI test files on macOS.
These included embedded Postgres shared-memory exhaustion, a loopback
expectation on a Tailscale host, and headless-board CLI failures. Final
[GitHub Actions
CI](https://github.com/paperclipai/paperclip/actions/runs/46785144221)
passed.
- Live provider sign-in was outside the scope of this UI test.

## Risks

Low risk. The UI uses the existing company capability response. Core
still checks the selected host when sign-in starts. The change touches
the existing setup components because they own the Connect controls and
the task readiness checks.

> 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 Codex (GPT-6) with local code inspection, TypeScript checks, and
test execution.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [ ] 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-12-02 01:20:17 +00:00
paperclipbugbotandClaude Opus 5.5 64c872e4da fix(opencode): record model traffic when opencode serve is OOM-killed (#23428)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The native Runner starts `opencode serve` for each OpenCode turn and
sends every model request of OpenCode through a local provider proxy.
> - #23372 and #23391 showed that the kernel OOM killer stops `opencode
serve` at the 8 GiB sandbox limit about 50 seconds into light turns, and
that the memory is OpenCode's own resident set (about 7.6 GiB) and
anonymous memory.
> - The retained run log has no raw provider or SSE trace. So we cannot
tell a huge provider response, a loop of model requests, or growth
inside OpenCode on a normal stream from one another.
> - The provider proxy already sees each model request and its response.
It is the cheapest place to measure this.
> - This pull request counts the model traffic in the proxy and reports
the counts when `opencode serve` dies by a signal.
> - The benefit is that the next OOM kill shows which of the three
causes applies, so the fix can target it.

## Linked Issues or Issue Description

Refs #23372 (kernel OOM evidence). Refs #23391 (memory attribution).

**What happened?**
On a cloud sandbox, native OpenCode turns with a fast DeepSeek model
fail with `opencode_server_exited`. The failure record shows
`memoryKill: observed` and `opencodeRssBytes` of about 8.16 GB at the 8
GiB limit. The run log shows no event for about 46 seconds before the
kill. It does not show how much model traffic OpenCode handled in that
time.

**Expected behavior**
When the kernel stops `opencode serve`, the failure record says how many
model requests OpenCode sent, how many bytes the provider returned, and
how large and how old the response was that was still streaming.

**Steps to reproduce**
1. Run a native OpenCode turn through the Runner provider proxy in a
Linux sandbox with a cgroup v2 memory limit.
2. Make the kernel OOM killer stop `opencode serve` while a model
response streams.
3. Read `resultJson.nativeTurnFailure`. Before this change, it has no
model traffic counts.

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

## What Changed

- New `provider-traffic.ts`: a meter that counts, for one `opencode
serve` launch, model requests, request bytes, completed responses,
response bytes, and the size and age of responses that still stream. It
keeps only numbers. It records no request or response content.
- `startOpenCodeProviderProxy` starts one meter entry for each forwarded
request. It counts response bytes with a pass-through stream in the
existing response pipeline. A request ends as completed only when its
response pipeline finishes. Any other ending counts as interrupted. The
proxy keeps the largest interrupted response's bytes and duration. When
OpenCode dies while it reads a response, its connection closes and that
response ends first, so this keeps the response it was killed on. A
request that the proxy rejects before it calls the provider is not
counted.
- A signal death of `opencode serve` adds these fields to
`opencodeFailure`: `providerRequests`, `providerResponsesCompleted`,
`providerResponsesInterrupted`, `providerRequestBytes`,
`providerResponseBytes`, `providerInflightResponses`,
`providerInflightResponseBytes`, `providerInflightMs`,
`providerInterruptedResponseBytes` and `providerInterruptedMs`.
- `native-provider-failure.ts` keeps the new fields in its closed
vocabulary. Each must be a safe integer that is zero or more. Other
values are dropped.
- `openCodeServerDriverInternals` also exports
`startOpenCodeProviderProxy` for tests.
- This is a diagnostic. It does not change how a turn fails or recovers,
and it does not change any forwarded bytes.

## Verification

- `cd packages/paperclip-runner && npx vitest run
src/drivers/opencode/provider-traffic.test.ts
src/drivers/opencode/provider-traffic-proxy.test.ts`: 6/6 pass.
- The meter tests check completed and in-flight counts, the largest
in-flight response, the oldest in-flight age, and that late bytes, a
repeated end and bad sizes change nothing.
- A meter test checks that a response which ends before it completes
keeps its size and duration.
- The proxy test sends one finished request and one request whose
response still streams through the real proxy to a local fake provider.
It checks the exact request and response byte counts. Then the client
stops reading, as a killed OpenCode does, and the test checks that the
response is reported as interrupted with its byte count. A second test
checks that a rejected request is not counted.
- `cd packages/paperclip-runner && npx vitest run
src/drivers/opencode/opencode-server-driver.test.ts -t "OpenCode stops
mid-turn|classifies a lost event stream"`: 2/2 pass. The SIGKILL test
now expects zero traffic counts, because its fixture does not call the
model.
- `cd server && npx vitest run
src/services/native-runtime/native-provider-failure.test.ts`: 65/65
pass. A new test checks that the counts pass through and that bad values
are dropped.
- A scoped `tsc --noEmit` of the server file shows no errors. `tsc -p
packages/paperclip-runner/tsconfig.json --noEmit` shows no errors in the
changed files.
- These local runs used an older parent commit with the same versions of
the changed code paths. CI runs the full suites on this branch.

## Risks

- Low risk. The counter is a pass-through `Transform` in the existing
response pipeline. It forwards each chunk unchanged and adds its length
to a number.
- The meter keeps one small entry for each in-flight request and removes
it when the request ends.
- Counts are reported only for a signal death of `opencode serve`.

## Model Used

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

## Checklist

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

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
canary/v2026.1202.0-canary.878700
2026-12-02 01:19:59 +00:00
Nicky LeachandPaperclip 550d8fc576 feat(plugins): honor harness login driver preferences (#23425)
## Thinking Path

> - People use Paperclip to manage agents and the accounts they use.
> - A harness can sign in on an environment supplied by a plugin.
> - Some plugins offer several environments with different login
requirements.
> - Today the task environment also determines where sign-in runs.
> - This change lets the plugin declare its preferred login drivers.
> - A company can use a temporary environment for sign-in and keep
running tasks on its chosen computer.

## Linked Issues or Issue Description

**Subsystem affected**

Plugin manifests, login target selection, and the harness sign-in UI.

**Current behavior**

A plugin with several environments cannot direct sign-in to a preferred
driver. Selecting an agent computer for tasks can require an agent even
when a temporary environment is available for login.

**Proposed behavior**

Allow the manifest to declare an ordered list of login drivers. Select
the first eligible environment for the company and harness before
starting a login.

**Reason and benefit**

A plugin can offer agentless sign-in first and keep an agent-targeted
computer as a fallback. The choice applies only to sign-in.

**Additional context**

This builds on the agentless login capability in #23392.

## What Changed

- Validate ordered login driver keys in the manifest and expose the
eligible environments to the company.
- Use the same selection rule for device login, setup-token login,
onboarding, agent configuration, and AI Connections.
- Bind the session and lease to the selected environment. Existing agent
eligibility checks apply when the target needs an agent.

## Verification

- Server and UI typechecks passed. Focused Vitest runs covered shared
manifest validation, driver order, the company access boundary, lease
checks, both HTTP login flows, and the UI helpers.
- The public SDK source input registry was regenerated. The registry
change requires broad CI coverage under `pnpm verify`.
- Regression tests cover skipping an environment without an eligible
computer, using a newly prepared draft computer, and holding the
selected host across capability and readiness updates during sign-in.
The UI typecheck and all 16 focused login tests passed on the final
commit.
- No external provider credentials were used.

## Risks

A plugin that opts in must declare at least one usable driver for the
user's harness and company. If none qualifies, the start fails before
acquisition. Manifests that omit the field keep their existing routing.
There is no database migration.

> 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 Codex (GPT-6), with local code inspection, TypeScript checks, and
test execution.

## Checklist

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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-12-01 16:58:28 -08:00
Dotta f0ee1b40f0 docs(headless): make tutorials copy-pasteable and add workflow commands (#23433)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Headless channels, fenced task queues, and workflow primitives
landed in #23330 and #23415, with walkthrough documentation in
`doc/HEADLESS-TUTORIALS.md`.
> - The previous `doc/HEADLESS-TUTORIALS.md` used invented issue IDs
(`PAP-14`, `PAP-50`, `PAP-88`), missing local files (`plan.json`,
`./finding.schema.json`), and non-existent project slugs (`web-app`,
`api-server`), and did not cover the newer workflow commands or
multi-agent workflow patterns.
> - Readers trying to walk through the tutorial by hand could not copy
and paste the commands directly on a fresh local board and missed the
new `assign`, `handoff`, `claim --mine`/`--status backlog`, `block
--needs`, `cancel`/`reopen`, and `channels` admin commands.
> - This pull request rewrites `doc/HEADLESS-TUTORIALS.md` with
deterministic hard-coded values (`--company-name "Demo"`, `DEM-1`
through `DEM-10`), adds hands-on sections for the new workflow commands,
and adds a concise overview of the workflow patterns from
`.agents/skills/channels-queues-and-workflows/SKILL.md`.
> - The benefit is a verified, top-to-bottom copy-pasteable tutorial
that matches the current CLI surface and introduces Paperclip's core
multi-agent coordination patterns.

## Linked Issues or Issue Description

Refs #23330
Refs #23415

**Issue type**
Outdated (no longer matches behavior)

**Where is the issue?**
`doc/HEADLESS-TUTORIALS.md`

**What's wrong?**
The tutorials relied on placeholder IDs, missing local files, and
uncreated project slugs, so copying and pasting commands on a fresh `pc
up --local` board failed. They also omitted the newer workflow
ergonomics commands from #23415 (`tasks assign`, `tasks handoff`, `tasks
claim --mine` / `--status backlog`, `tasks block --needs`, `tasks deps
list`, `tasks cancel` / `reopen`, `channels create --private`, `channels
members`, `channels update --managed-pool`) and did not summarize the
workflow patterns in
`.agents/skills/channels-queues-and-workflows/SKILL.md`.

**Suggested fix**
Update `doc/HEADLESS-TUTORIALS.md` to use deterministic hard-coded
values (`--company-name "Demo"`, `DEM-1` through `DEM-10`), inline
heredocs/JSON, runnable `node -e` commands, hands-on examples for the
new workflow commands, and a concise workflow patterns overview linking
to the skill and examples.

## What Changed

- Updated `doc/HEADLESS-TUTORIALS.md` to start with `npx paperclipai up
--local --port 3199 --company-name "Demo"` and use deterministic
hard-coded IDs (`DEM-1`–`DEM-10`), inline `--file -` heredocs, inline
`--data` schemas, and runnable `node -e` worker commands with zero
placeholders.
- Fixed `pc channels` to `pc channels list` (since bare `pc channels`
prints Paperclip release channels) and `--schema ... --data '{...}'`
flag syntax using the built-in `finding@1` schema.
- Added hands-on walkthroughs for `pc tasks block --needs` + `pc tasks
deps list`, `pc agent connect` + `pc tasks assign` + `pc tasks claim
--mine`, `pc tasks claim --status backlog`, `pc tasks cancel` /
`reopen`, `pc tasks handoff` with `--if` CAS, and `pc channels create
--private` / `members` / `update --managed-pool`.
- Added Tutorial 4 ("Multi-Agent Workflow Patterns at a Glance")
summarizing Direct Work Queue, Two-Step Inbox, Single-Thread Relay,
Assembly Line, and DAG Fan-Out/Fan-In with links to
`.agents/skills/channels-queues-and-workflows/SKILL.md` and
`examples.md`.
- Updated Cloud graduation in Tutorial 5 to use `pc channels update
--project ... --managed-pool ...` instead of raw API calls.

## Verification

- Ran every command in Tutorials 1–3 verbatim in an isolated temporary
`PAPERCLIP_HOME` against a fresh `pc up --local --port 3297
--company-name "Demo"` server (`DEM-1` through `DEM-10` plus expected
`409 label_conflict` on competing CAS label update): all commands
succeeded with exit code 0.
- Confirmed `pc channels list` lists board channels instead of release
channels.

## Risks

- Low risk. Documentation-only change (`doc/HEADLESS-TUTORIALS.md`); no
runtime, schema, or API behavior changes.

## Model Used

- Google Gemini (Antigravity agentic runtime, Gemini 4 Neon Medium,
extended thinking with tool use and code execution)

## Checklist

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

> - Paperclip is the open source app people use to manage AI agents for
work
> - The PR workflow runs the Playwright e2e suite in shards.
`scripts/e2e-shard.mjs` plans the shards from recorded spec durations.
> - On GitHub-hosted 4-vCPU runners (4 shards), the planner puts all 16
serial specs on one shard.
> - That serial shard is the longest check in each PR run. It takes a
median of 11.2m (up to 14.4m). The three parallel shards finish in about
5m.
> - The duration weights come from 8-vCPU runners. On hosted runners,
serial specs run slower than their weights and parallel specs run
faster. The planner thinks one serial shard is fine (529s planned
against 363s), but the real times are 672s against 318s.
> - This pull request adds a serial slowdown factor that is calibrated
from hosted runs. The planner now puts the serial specs on two shards.
> - The benefit is that the longest e2e shard on hosted runs drops from
a median of ~11.2m to ~7.9m (about 3.3m saved; about 6m saved on slow
runs).

## Linked Issues or Issue Description

No public issue exists. Inline issue, following the [enhancement
template](https://github.com/paperclipai/paperclip/blob/master/.github/ISSUE_TEMPLATE/enhancement.yml):

**What existing behavior does this improve?**
The e2e shard planner (`scripts/e2e-shard.mjs`) for GitHub-hosted 4-vCPU
PR runs.

**Subsystem affected**
CI / e2e test sharding.

**Current behavior**
On 4-vCPU hosted runners the planner puts all 16 serial specs on one
shard. `e2e shard (1/4)` is the longest check in hosted PR runs and
takes about 2x as long as the other shards.

**Proposed behavior**
Add a serial slowdown factor for 2-worker runners only, so the planner
splits serial specs across two shards.

**Reason and benefit**
The longest hosted e2e shard drops from a median of ~11.2m to ~7.9m
(about 3.3m saved per hosted PR run, ~5–6m on slow runs).

**Breaking changes**
None. The 16-shard AWS plan does not change, and the factor can be
overridden with `--serial-slowdown` or `PAPERCLIP_E2E_SERIAL_SLOWDOWN`.

**Additional context**
Playwright wall time per shard in five recent hosted PR runs:

| Run | Serial shard (1 worker) | Parallel shards (2 workers) |
| --- | --- | --- |
| 46423658483 | 14.4m | 4.5m, 4.9m, 7.9m |
| 46422531627 | 11.7m | 4.3m, 5.4m, 5.7m |
| 46420745048 | 10.9m | 5.3m, 5.6m, 5.8m |
| 46419917065 | 7.5m | 3.6m, 4.0m, 5.8m |
| 46409346442 | 11.2m | 4.9m, 5.3m, 5.8m |

Median: the serial shard is 1.27x its plan estimate and the parallel
shards are 0.88x theirs. Relative to parallel work, serial work costs
~1.45x more than the plan assumes.

## What Changed

- `scripts/e2e-shard.mjs`: Added `SERIAL_SLOWDOWN_2W = 1.45` and
`resolveSerialSlowdown(cpus)`. The factor applies only when Playwright
uses 2 workers (4–5 vCPU). `partitionE2eShards` accepts a
`serialSlowdown` option and multiplies the serial-shard estimate by it.
- `scripts/e2e-shard.mjs` CLI: Added `--serial-slowdown` and
`PAPERCLIP_E2E_SERIAL_SLOWDOWN` overrides. These work the same way as
the existing `--parallel-speedup` overrides. The default comes from the
runner CPU count.
- `scripts/__tests__/e2e-shard.test.mjs`: Added tests for
`resolveSerialSlowdown`, a test that checks that the 4-shard hosted plan
uses at least two serial shards, and a CLI test that simulates a 4-vCPU
runner with no overrides and checks that the automatic default splits
serial specs across exactly two shards.

## Verification

- `node --test scripts/__tests__/e2e-shard.test.mjs`: all 21 tests pass.
Red-green: with the 2-worker default set back to 1, the new CLI test
fails (1 serial shard instead of 2).
- Red-green: with `serialSlowdown: 1` the hosted plan has one serial
shard (16 specs), so the new assertion fails. With 1.45 it has two
serial shards (8 specs each).
- Projection: apply the measured hosted ratios (serial 1.27x, parallel
0.88x) to the plan. The old plan projects to 11.2m / 5.3m / 5.3m / 5.3m,
which is the same as the measured medians. The new plan projects to 5.6m
/ 5.6m / 7.9m / 7.9m.
- The 16-shard AWS plan (8 vCPU, 4 workers) does not change. Its maximum
estimate stays at 79s.
- Note: `pr.yml` runs `pr-trusted.yml` and this script from `master`.
The new split takes effect only after merge.

## Risks

- Low risk. The change affects only how specs are put on shards. The
same specs run, and serial specs never share a shard with parallel
specs.
- The two parallel shards each run about 22 specs. Their median projects
to ~7.9m, up from ~5.3m. This is still shorter than the current serial
shard.
- If hosted runner performance changes, the factor can drift. The
`PAPERCLIP_E2E_SERIAL_SLOWDOWN` override lets you tune it without a code
change.

## Model Used

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

## Checklist

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

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

---------

Co-authored-by: devinfoley <139239+devinfoley@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
canary/v2026.1202.0-canary.878400
2026-12-02 00:33:00 +00:00
Dotta 0434e7f3aa feat(board): add task assign, atomic handoff, claim filters, cancel/reopen, mid-flight deps, and channel admin (#23415)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Headless channels, fenced task queues, `@paperclipai/shared/sdk`,
and the `pc` CLI landed in #23330 to coordinate multi-agent swarms and
inbox/queue patterns.
> - Real multi-stage workflows immediately hit gaps: there was no
`assign` command to push existing channel posts to managed agents, no
atomic `handoff`/`move` across channels with CAS labels and lease
release, `claim --ready` could not opt into `backlog`/`in_review` or
`--assignee me`, there was no `cancel`/`reopen` or mid-flight `--needs`
dependency linking, and `pc channels` could not update queue config,
manage private members, or bind event-driven managed pools.
> - Without these primitives, operators had to drop back to raw `issue
update` calls or non-atomic two-step scripts that race on crash.
> - This pull request adds the complete workflow lifecycle across shared
schemas, modular server services/routes, SDK methods, `pc` CLI commands,
and the `.agents/skills/channels-queues-and-workflows` skill.
> - The benefit is end-to-end single-command support for inbox triage,
single-thread relays, chained channel assembly lines, mid-flight DAG
dependencies, and Day-2 graduation to managed Paperclip agent pools.

## Linked Issues or Issue Description

Refs #23330

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

**Problem or motivation**
Building multi-agent queues and chained workflows on Paperclip channels
required workarounds: assigning an existing post to a registered agent
required raw `issue update --assignee-agent-id <uuid>`; moving an issue
across stage channels with a label update and lease release required
non-atomic multi-step calls; triage or review workers could not opt into
claiming `backlog`, `in_review`, or their own assigned tasks (`--mine`);
tasks could not be cancelled, reopened, or given mid-flight `--needs`
blockers; and channels lacked CLI/API administration for `queueConfig`,
private `channel_access_members`, and `managedPool` auto-dispatch.

**Proposed solution**
Add cohesive REST endpoints, modular services
(`headless-task-workflows.ts`, `headless-channel-admin.ts`), SDK
methods, `pc` CLI subcommands, and the `channels-queues-and-workflows`
skill covering `assign`, `handoff`/`move`, `cancel`, `reopen`, `block
--needs`/`deps`, opt-in `claim --status`/`--assignee`, and `channels
update`/`members` with event-driven `managedPool` dispatch.

**Alternatives considered**
Leaving these operations to raw `PATCH /api/issues/:id` calls was
rejected because it bypasses fenced claim tokens (`claimEpoch` +
`claimToken`), lacks atomic channel+label+lease transactions, and does
not enforce CAS preconditions or dependency cycle checks.

**Roadmap alignment**
Directly extends the headless channels and queues coordination primitive
introduced in #23330.

## What Changed

- **Shared schemas & SDK (`packages/shared/src/headless/`,
`packages/shared/src/sdk/`):**
- Added pure zero-zod constants `CLAIMABLE_TASK_STATUSES` and
`TASK_CLAIM_ASSIGNEE_MODES` in `pure.ts`, upgraded
`TaskClaimRequestSchema` (`status`/`statuses`, `assignee`) and
`TaskReleaseSchema` (`status`, `channel`, `labels`, `unsetLabels`), and
added `TaskAssignSchema`, `TaskHandoffSchema`, `TaskCancelSchema`,
`TaskReopenSchema`, `TaskDependenciesMutationSchema`,
`updateChannelInputSchema`, and `channelMemberInputSchema`.
- Added `task.assigned`, `task.handed_off`, `task.cancelled`,
`task.reopened`, and `task.dependencies_changed` to `BOARD_EVENT_TYPES`.
- Exposed matching SDK methods on `paperclip().tasks`, `ClaimedTask`,
and `paperclip().channels`.
- **Server services & routes (`server/src/services/`,
`server/src/routes/`):**
- Upgraded `claimTask` and `releaseTaskClaim` in
`headless-task-queue.ts` to support opt-in `status` (`todo`, `backlog`,
`in_review` excluding pending interactions), `assignee` (`unassigned`,
`me`, `any`), and atomic channel/label/status updates on release.
- Added `server/src/services/headless-task-workflows.ts` implementing
`assignTask`, `handoffTask`, `cancelTask`, `reopenTask`,
`listTaskDependencies`, and `mutateTaskDependencies` (with BFS cycle
detection and fenced lease release).
- Added `server/src/services/headless-channel-admin.ts` implementing
`updateChannel`, `listChannelMembers`, `addChannelMember`,
`removeChannelMember`, and event-driven `dispatchManagedChannelPool`
(zero idle polling).
- Wired routes in `headless-queues-events.ts` and
`headless-channels-schemas.ts`.
- **CLI (`cli/src/commands/board/`):**
- Added `cli/src/commands/board/tasks-workflows.ts` (`pc tasks assign`,
`handoff`/`move`, `cancel`, `reopen`, `deps list|add|remove`).
- Upgraded `pc tasks claim`/`run` (`--status`, `--assignee`, `--mine`),
`pc tasks release` (`--channel`, `--label`, `--unset`, `--status`), `pc
tasks block` (`--needs`), and `pc channels` (`update`/`config`, `members
list|add|remove`).
- **Skill & Tests:**
- Added `.agents/skills/channels-queues-and-workflows/SKILL.md` and
`examples.md`.
- Added `server/src/__tests__/headless-task-workflows.test.ts` and
updated `tests/runner-e2e/source-sdk-public-inputs.json`.

## Verification

- `pnpm --filter @paperclipai/shared build && pnpm --filter
@paperclipai/server typecheck && pnpm --filter paperclipai typecheck` —
passed.
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/headless-task-workflows.test.ts
src/__tests__/headless-queues-leases-events.test.ts
src/__tests__/headless-channels-schemas-batch.test.ts
src/__tests__/headless-e2e-sdk-cli.test.ts` — 4 files, 27 tests passed.
- `pnpm --filter @paperclipai/shared exec vitest run
src/headless/headless.test.ts src/sdk/sdk.test.ts` — 2 files, 20 tests
passed.
- Live headless CLI test-drive (`pc up --port 3299` in isolated
`PAPERCLIP_HOME`) verifying `agent connect`, `post`, `tasks assign`,
`tasks claim --mine`, `tasks handoff`, `tasks release --status
in_review`, `tasks claim --status in_review`, `tasks block --needs`,
`tasks deps list`, blocker completion auto-unblock, `tasks cancel`,
`tasks reopen`, `tasks claim --status backlog`, `channels members
add/list/remove`, and `channels update --managed-pool` — all 11
scenarios passed.

## Risks

- Low risk. No database migrations are required; existing
`channels.queue_config`, `channel_access_members`, `issue_relations`,
and `issues` lease columns are reused.
- Default `claim --ready` behavior (`status = todo`, `assignee =
unassigned`) is unchanged; `--status` and `--assignee` are strictly
opt-in, and `--assignee me`/`any` never allows claiming tasks assigned
to another agent or user.
- Note on file size: `server/src/services/headless-task-queue.ts` and
`cli/src/commands/board/tasks.ts` were already over 1,000 lines before
this PR; all new workflow/admin operations were placed in dedicated
sibling modules (`headless-task-workflows.ts`,
`headless-channel-admin.ts`, `tasks-workflows.ts`) to keep existing
files bounded.

## Model Used

- Google Gemini (Antigravity agentic runtime, Gemini 4 Neon Medium,
extended thinking 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
canary/v2026.1202.0-canary.878300
2026-12-01 23:54:54 +00:00
Dotta fcb8fc5deb fix(cloud-trial): allow Cloud starter-trial agents through plugin Runner verification and admission (#23427)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Cloud onboarding supports a starter-inference variant
(`free_inference_1`) where the first agent uses Paperclip Cloud's
server-proxied OpenRouter starter key
(`runtimeConfig.cloudTrialInference: true`) before the user connects
their own model provider
> - On Cloud plugin Runner environments, both
`agentHarnessVerificationService` and heartbeat run admission
(`execution-configuration.ts`) rejected `paperclip_runner` agents with
`ai_connection_required` whenever `runtimeConfig.aiConnection` was
absent
> - Because verification failed, the hired first agent stayed stuck in
`status: "paused"` / `lifecycleState: "verifying"` and the first
free-inference chat never executed or replied
> - This pull request allows `cloudTrialInference` agents (with isolated
homes) through plugin Runner verification and run admission, verifying
starter-key eligibility and model restriction via
`prepareCloudTrialRuntime(..., { probeOnly: true })`
> - The benefit is that `free_inference_1` onboarding agents transition
immediately to `ready`/`idle` and execute their first chat turn on
starter inference without requiring a user-managed AI connection

## Linked Issues or Issue Description

Refs #23401

**What happened?**
When a user completes `free_inference_1` onboarding on a Cloud stack
with a plugin Runner environment, the first agent is hired with
`runtimeConfig.cloudTrialInference: true` and no
`runtimeConfig.aiConnection`. Agent harness verification fails with
`ai_connection_required`, leaving the agent stuck in `paused` (`"Agent
setup needs attention"`) so the first chat run sits in `queued` forever.

**What did you expect to happen?**
The starter-trial agent should pass harness verification using Paperclip
Cloud's starter-trial eligibility and key check, transition to `idle`,
and execute its first chat turn via the Cloud trial OpenRouter proxy.

**Steps to reproduce**
1. Enable `free_inference_1` on a Cloud stack backed by a plugin Runner
environment.
2. Complete onboarding and click "Start chatting".
3. Send a message in the first chat; observe the agent remains paused on
`"Agent setup needs attention"`.

## What Changed

- Updated `server/src/services/agent-harness-verification.ts` to
recognize `runtimeConfig.cloudTrialInference: true` on
`paperclip_runner` agents (while still refusing `homeMode:
"preconfigured"` on plugin Runner environments), strip host AI auth env
bindings, and verify starter-key eligibility + model restriction via
`prepareCloudTrialRuntime(..., { probeOnly: true })` + `cleanup()`.
- Updated `server/src/services/heartbeat/execution-configuration.ts` to
allow `cloudTrialInference` agents (when `homeMode` is not
`"preconfigured"`) past the plugin Runner `aiConnection` preflight check
so the first chat run reaches `prepareCloudTrialRuntime`.
- Added optional `probeOnly?: boolean` to `prepareCloudTrialRuntime` in
`server/src/services/cloud-trial-proxy.ts` so verification checks do not
increment `trialRunsCount` telemetry.
- Added a red-green regression test in
`server/src/__tests__/agent-harness-verification-preflight.test.ts`
covering both valid starter-trial verification on a plugin Runner
environment and continued rejection of `homeMode: "preconfigured"`.

## Verification

- Confirmed RED before the fix
(`agent-harness-verification-preflight.test.ts` rejected with
`ai_connection_required`).
- Confirmed GREEN after the fix:
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/agent-harness-verification-preflight.test.ts
src/__tests__/cloud-trial-inference.test.ts` (22/22 passed)
  - `pnpm --filter @paperclipai/server typecheck` (0 errors)

## Risks

- Low risk. Scope is restricted to agents with
`runtimeConfig.cloudTrialInference === true` and no `aiConnection`.
Non-trial agents and `homeMode: "preconfigured"` agents keep identical
fail-closed `ai_connection_required` enforcement.

## Model Used

- Google Gemini (Antigravity agentic harness 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
canary/v2026.1201.0-canary.878200
2026-12-01 23:20:07 +00:00
Dotta 0d3ed44550 fix(test): write observed.json atomically in acpx-provider-turn-host (#23424)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The Paperclip Runner protocol suite verifies ACPX sidecar
provider-started turns using
`packages/paperclip-runner/src/cli/acpx-runtime-sidecar.provider-turn.test.ts`
and the test host
`packages/paperclip-runner/src/test-support/acpx-provider-turn-host.mjs`
> - `acpx-provider-turn-host.mjs` updated `observed.json` in place with
`writeFileSync()`, which truncates the file to zero bytes before writing
the JSON bytes
> - When the parent test polls `observed()` concurrently during a write,
`JSON.parse(readFileSync(...))` can observe the truncated empty file and
throw `SyntaxError: Unexpected end of JSON input`, failing `Verify
Paperclip Runner (protocol (1/4))` on `master` (for example, Cloud
readiness run 46754145328)
> - This pull request writes `observed.json` to a unique sibling
temporary file and atomically replaces `observed.json` with
`renameSync()`
> - The benefit is atomic handoff between the sidecar test host and the
polling test, eliminating this intermittent `master` CI failure

## Linked Issues or Issue Description

**What happened?**
`verify / Verify Paperclip Runner (protocol (1/4))` intermittently
failed `ACPX sidecar provider-started Claude turns > leaves non-Claude
agents without a provider-turn listener` on `master` (Cloud readiness
run 46754145328) with `SyntaxError: Unexpected end of JSON input` at
`src/cli/acpx-runtime-sidecar.provider-turn.test.ts:64`.

**Expected behavior**
Polling `observed.json` from the test process should always read a
complete JSON document and never observe a truncated in-progress write.

**Steps to reproduce**
1. Run
`packages/paperclip-runner/src/cli/acpx-runtime-sidecar.provider-turn.test.ts`.
2. The child sidecar host calls `note()` in
`packages/paperclip-runner/src/test-support/acpx-provider-turn-host.mjs`,
which truncates and rewrites `observed.json` in place with
`writeFileSync()`.
3. If the parent test reads `observed.json` during truncation,
`JSON.parse()` throws `SyntaxError: Unexpected end of JSON input`.

**Paperclip version or commit**
`16614f4fdae31dbdd991cc41b879b4489561047a` /
`3df59a1853752dea020524815737afec39882be2`

**Deployment mode**
Other (CI test suite)

## What Changed

- Update `note()` in
`packages/paperclip-runner/src/test-support/acpx-provider-turn-host.mjs`
to write JSON to a unique sibling temp file and atomically replace
`observed.json` via `renameSync()`.

## Verification

- `pnpm --filter @paperclipai/paperclip-runner exec vitest run
src/cli/acpx-runtime-sidecar.provider-turn.test.ts` — 14/14 passed.

## Risks

- Low risk. Test-helper-only change scoped to
`acpx-provider-turn-host.mjs`.

## Model Used

- Google DeepMind Antigravity using Gemini 4 Neon (Medium) with
reasoning, tool use, and local command execution.

## Checklist

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

> - Paperclip is the open source app people use to manage AI agents for
work
> - Project settings let a project editor manage GitHub repositories.
> - The settings page offers a GitHub credential for background
repository work.
> - Projects with only public repositories or no repositories also see
the consent form.
> - This pull request shows the form when a saved repository is known to
be private.
> - The form disappears when the editor removes the last private
repository.

## Linked Issues or Issue Description

**What happened?**

Project settings showed Background GitHub authorization for every
project.

**Expected behavior**

Show the section only while the project has a private GitHub repository.

**Steps to reproduce**

Open settings for a project with no repositories or only public
repositories. The authorization form appeared on master.

**Paperclip version or commit**

Reproduced at `07af22c57f`. The original authorization form shipped in
#17798.

## What Changed

- Reuse the repository picker’s catalog query to check visibility for
saved workspace URLs. Fall back to saved visibility when it belongs to
the same URL.
- Mount the consent form and load its authorization data only when a
saved repository is private.

## Verification

- The UI typecheck and all three authorization component tests passed
locally on macOS at `d5332c47a5`. The tests cover legacy Git URLs and
bound catalog reads across repeated renders with 502 repositories. The
regression tests failed before their fixes.
- GitHub CI passed the typecheck, build, selected tests, and browser
shards for the same commit. [CI
run](https://github.com/paperclipai/paperclip/actions/runs/46757316515)
- Before the rebase, the UI typecheck and all 249 selected UI test files
passed. The broader local verifier failed in CLI tests, including
embedded Postgres startup, CLI profile selection, and the tailnet bind
address.

## Risks

- A repository with unknown visibility keeps the section hidden until
the catalog or saved metadata confirms it is private.
- Removing the last private repository hides the revoke button along
with the form. The existing grant stays in place.

> 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 Codex (GPT-6), with repository editing, shell execution, and
local test tools.

## Checklist

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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
canary/v2026.1201.0-canary.878000
2026-12-01 22:24:35 +00:00
Dotta d57d4db4ab fix(test): share module instances in instance-settings-routes test (#23423)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The server test suite verifies signed Cloud control assertions in
`server/src/__tests__/instance-settings-routes.test.ts` through the real
`cloudControlMiddleware` and `instanceSettingsRoutes`
> - `hoistModuleGraph` in that test loaded
`../middleware/cloud-control.js`,
`../services/cloud-runtime-identity.js`, and
`../routes/instance-settings.js` via `vi.importActual()` inside
`Promise.all`
> - In Vitest 5, `vi.importActual()` appends a `_vitest_original` query
when fetching the module, which can evaluate a second instance of
`cloud-control.ts` with separate `WeakMap`s (`idleCapabilities` and
`controlClaims`) from the instance imported by `instance-settings.ts`,
causing intermittent 403 and missing-capability failures that cancel
`master` Cloud readiness and Docker image builds
> - This pull request replaces `vi.importActual()` with standard dynamic
`import()` for those unmocked modules inside `hoistModuleGraph`
> - The benefit is deterministic module identity across middleware,
routes, and replay-fence helpers, eliminating flaky `master` CI failures
in `Serialized tests (13/16)`

## Linked Issues or Issue Description

**What happened?**
`verify / Serialized tests (13/16)` intermittently failed all five tests
in `instance settings routes > task drain > signed incoming capability
handoff` on `master` (for example, Cloud readiness run 46753879142 /
Docker run 46753878936). Requests authenticated by
`cloudControlMiddleware` returned `403 Forbidden` or passed
`incomingWake: undefined` because `verifiedCloudControlClaims(req)` and
`verifiedIdleCapabilities(req)` read from a different `cloud-control.ts`
module instance than the one populated by `cloudControlMiddleware`.

**Expected behavior**
`cloudControlMiddleware`, `instanceSettingsRoutes`, and
`controlIdentity` should always share a single module instance so
`WeakMap` lookups and replay-fence resets behave deterministically.

**Steps to reproduce**
1. Run `server/src/__tests__/instance-settings-routes.test.ts` under
Vitest 5 (`verify / Serialized tests (13/16)`).
2. Observe `hoistModuleGraph` calling `vi.importActual()` in parallel on
`../routes/instance-settings.js`, `../middleware/cloud-control.js`, and
`../services/cloud-runtime-identity.js`.
3. When `cloud-control.ts?_vitest_original` evaluates separately from
`cloud-control.ts`, the five `signed incoming capability handoff` tests
fail.

**Paperclip version or commit**
`3833e1c8e8d870a4ab387d579e6f44c0a6066930` /
`3df59a1853752dea020524815737afec39882be2`

**Deployment mode**
Other (CI test suite)

## What Changed

- Replace `vi.importActual()` with dynamic `import()` for the four
unmocked modules loaded in `hoistModuleGraph` in
`server/src/__tests__/instance-settings-routes.test.ts`, and document
why shared module identity is required.

## Verification

- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/instance-settings-routes.test.ts` — 112/112 passed.
- `pnpm --filter @paperclipai/server typecheck` — passed.

## Risks

- Low risk. Test-only change affecting four unmocked imports inside one
test file.

## Model Used

- Google DeepMind Antigravity using Gemini 4 Neon (Medium) with
reasoning, tool use, and local command execution.

## Checklist

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

> - Paperclip is the open source app people use to manage AI agents for
work
> - The Paperclip Runner executes Google Antigravity agents on local
hosts and remote sandboxes
> - Previously, Paperclip shipped two separate Google runtimes: an 853
MiB IDE-extension ACP bundle (`agy_acp_server.par` 1.5.2 +
`localharness_external` + Python admission monkey-patch) for ordinary
turns and a separate `agy` 1.5.15 CLI binary for local-only `/swarm`
turns
> - Because the legacy server lacked `/swarm` and the CLI path refused
remote targets and required macOS Keychain or Linux user namespaces
(`auto` mode), remote sandboxes could not run `/swarm` and carried 853
MiB of legacy binaries
> - This pull request unifies all Antigravity surfaces (ordinary turns,
`/swarm`, interactive sign-in, and model discovery) onto one pinned
`agy` 1.5.19 CLI binary (`1.5.19-4821414830800896`) with file-backed
OAuth isolation (`AGY_CLI_FORCE_FILE_TOKEN_STORAGE=1`) and
`--dangerously-skip-permissions` support for remote sandboxes
> - The benefit is one 268 MiB Linux binary instead of 853 MiB (saving
~585 MiB in remote images), no Python runtime monkey-patching, full
`/swarm` support on both local and remote hosts, and a unified 25-model
catalog including Gemini 4 Neon, Carbon, Hydrogen, and Argon

## Linked Issues or Issue Description

**What existing behavior does this improve?**
The Google Antigravity Runner driver, provider pack materialization,
Google sign-in flow, model discovery, and `/swarm` execution in
`packages/paperclip-runner`, `packages/shared`, `server`, and `ui`.

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

**Current behavior**
Ordinary Antigravity turns use the legacy 1.5.2 IDE-extension ACP server
(`agy_acp_server.par` + `localharness_external` + Python monkey-patch)
at ~853 MiB on `linux-x64`. Native `/swarm` turns require a separate
`agy` 1.5.15 CLI binary, refuse remote execution targets
(`input.remote`), and fail on Linux sandboxes without user namespaces
(`auto` mode).

**Proposed behavior**
All Antigravity flows use one pinned `agy` 1.5.19 binary
(`1.5.19-4821414830800896`, ~268 MiB on `linux-x64`) across all four
platforms (`darwin-arm64`, `darwin-x64`, `linux-x64`, `linux-arm64`).
Ordinary turns speak ACP directly through `openAntigravityAcpRuntime`.
Both ordinary and `/swarm` turns stage file-backed OAuth tokens under
`<agentHomeDirectory>/antigravity-cli/antigravity-oauth-token` with
`AGY_CLI_FORCE_FILE_TOKEN_STORAGE=1`, isolate from host keychains, and
allow `/swarm` on remote targets using `--dangerously-skip-permissions`.
Interactive Google sign-in runs `agy acp --login` with
`https://antigravity.google/oauth-callback`, pre-creates
`<home>/antigravity-cli` with mode `0700`, and prompts for the
authorization code in the UI.

**Reason and benefit**
Unifying onto `agy` 1.5.19 cuts the `linux-x64` provider-pack footprint
by ~585 MiB, removes Python bytecode patching from materialization,
enables `/swarm` in headless Linux sandboxes without user namespaces or
D-Bus, and aligns ordinary turns, model discovery, and `/swarm` on the
same 25-model catalog.

**Breaking changes**
- `acpx-profiles.json` bumps `antigravity` to `agentProfileVersion: 3`
(`native:antigravity-cli`, version `1.5.19`). Existing saved legacy
1.5.2 sessions fail closed as incompatible saved state and start fresh
cleanly.
- Existing Google OAuth connections carrying `client_secret` remain
fully backward-compatible; new `agy acp --login` connections store
canonical credentials with `auth_method: "consumer"` and no
`client_secret`.

## What Changed

- Pin `agy` `1.5.19-4821414830800896` across all four platforms
(`darwin-arm64`, `darwin-x64`, `linux-x64`, `linux-arm64`) in
`antigravity-distributions.json`, `antigravity-cli-distributions.json`,
`antigravity-cli-pins.ts`, and `acpx-profiles.json`
(`agentProfileVersion: 3`), and regenerate TypeScript and Rust profile
artifacts.
- Replace ZIP + Python patch materialization with strict single-member
`tar.gz` verification (`materialize-antigravity-distribution.mjs`,
`provision-antigravity.mjs`, `probe-antigravity-metadata.mjs`,
`candidate-provider-pack.mjs`, `release-provider-pack.mjs`).
- Regenerate `packages/shared/src/antigravity-models.generated.ts` from
`agy` 1.5.19 (25 models across 8 families, including Gemini 4 Neon,
Carbon, Hydrogen, and Argon) and update
`packages/shared/src/antigravity-models.ts` and
`tests/runner-e2e/antigravity-qualification-cases.ts` for `xhigh`
thinking levels.
- Add direct ACP runtime
`packages/paperclip-runner/src/drivers/acpx/antigravity-acp-runtime.ts`
(`openAntigravityAcpRuntime`) for ordinary Antigravity turns with OAuth
and `GEMINI_API_KEY` support, `session/new` + `session/resume`,
`readOnly`/plan mode enforcement, HTTP and stdio MCP forwarding, live
`setModel`, slash-command neutralization, refusal classification,
cancellation, and lineage retirement; route ordinary Antigravity turns
unconditionally in `acpx-runtime-adapter.ts` without an ACPX fallback
seam.
- Update `antigravity-auth.ts`, `antigravity-credentials.ts`,
`antigravity-models.ts`, `antigravity-process.ts`, `runtime-host.ts`,
and `runtime-sandbox.ts` to run `agy acp --login`, pre-create
`<home>/antigravity-cli` with mode `0700` (preventing Go `os.MkdirAll`
`0755` readback failures), force file-backed token storage
(`AGY_CLI_FORCE_FILE_TOKEN_STORAGE=1`), align `--gemini-dir` with
`agentHomeDirectory`, bound model-discovery token sync cleanup, and
scrub live CLI token files on cleanup.
- Enable remote `/swarm` by removing the `input.remote` refusal in
`server/src/services/antigravity-swarm.ts` and allowing
`--dangerously-skip-permissions` + `default` mode in
`antigravity-swarm-route.ts`, `antigravity-swarm-guard.ts`, and
`antigravity-swarm-runtime.ts` when `permissionMode === "approve-all"`.
- Update `ui/src/components/AdapterLoginChrome.tsx` copy to prompt for
an authorization code (`Submit code`) for
`https://antigravity.google/oauth-callback` while preserving callback
URL handling for loopback redirects.
- Add unit tests for `openAntigravityAcpRuntime`, direct Antigravity
routing, `0700` token directory pre-creation, and hosted
authorization-code login UX, and update Runner, script, shared, server,
Rust, UI, and runner-e2e test suites for `agy` 1.5.19.

## Verification

- Runner driver tests: `vitest run` across Antigravity driver test files
(`antigravity-auth.test.ts`, `antigravity-models.test.ts`,
`antigravity-acp-runtime.test.ts`, `antigravity-swarm-route.test.ts`,
`codex-credentials.test.ts`, `acpx-runtime-adapter.test.ts`,
`candidate-admission.test.ts`, `native-distribution-integrity.test.ts`)
— all passing.
- Runner script tests: `node --test` across all 7 Antigravity &
provider-pack script suites — 98/98 passed.
- Shared, UI, Server, and runner-e2e tests:
`antigravity-models.test.ts`, `AdapterLoginChrome.test.tsx` (23/23),
`antigravity-thread.test.tsx`, 23 server Antigravity/provider-pack
suites, and 7 `runner-e2e` Antigravity suites — all passing.
- Rust tests: `cargo test --manifest-path
packages/paperclip-runner/runner/Cargo.toml --locked -p
paperclip-runner-core -- acpx antigravity` — 145/145 passed.
- Typechecks & generators: `@paperclipai/shared`,
`@paperclipai/paperclip-runner` (TS + Rust), `@paperclipai/server` (all
layers), `@paperclipai/ui`, `generate-acpx-profiles.mjs --check`,
`generate-antigravity-models.mjs --check` — all passing.
- Live E2E against real pinned `agy` 1.5.19 binaries (macOS
`darwin-arm64`, headless Linux `linux-arm64` Docker with `--security-opt
no-new-privileges`, and a live remote test deployment):
- Verified `materialize-antigravity-distribution.mjs` on all 4 platform
archives and `probe-antigravity-metadata.mjs` on macOS and headless
Linux Docker.
- Verified live Google OAuth sign-in end-to-end via `agy acp --login` +
`https://antigravity.google/oauth-callback` authorization code exchange
on a live remote deployment, creating a working Antigravity connection.
- Verified `stageManagedAntigravityCredential` +
`AGY_CLI_FORCE_FILE_TOKEN_STORAGE=1` file-backed isolation and cleanup
scrub on macOS and headless Linux Docker.
- Verified live `openAntigravityAcpRuntime` ordinary turn + HTTP MCP
tool call + `_meta.antigravity.systemPrompt.append` +
`setModel(gemini-4-argon-low)` + `session/resume` on real `agy` 1.5.19.
- Verified live `openAntigravitySwarmRuntime` `/swarm` turn with
`--dangerously-skip-permissions` spawning a real helper, writing
workspace file, calling `paperclip_finish`, and retiring cleanly.

## Risks

- **Coordinated Cloud deployment**: Remote sandboxes use the companion
transition-safe Cloud update to expect
`provider-assets/antigravity/linux-x64/agy`, accept `auth_method:
"consumer"` credentials without `client_secret`, and scrub
`antigravity-cli/antigravity-oauth-token`.
- **Saved session continuity**: Existing saved 1.5.2 sessions fail
closed as `ANTIGRAVITY_SAVED_STATE_INCOMPATIBLE` and start fresh cleanly
on 1.5.19.

## Model Used

- Google Gemini (Antigravity agentic coding assistant,
reasoning/tool-use/code-execution enabled)

## Checklist

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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
canary/v2026.1201.0-canary.877800
2026-12-01 22:01:25 +00:00
DottaandPaperclip 16614f4fda feat(issues): add canonical structured coordination parity across API, OpenAPI, CLI, and public MCP (#23410)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work, where agents and humans coordinate tasks through the REST API,
`paperclipai` CLI, Native Runner API catalog, and Public MCP tools.
> - Structured coordination primitives (`channel`, `kvLabels`,
`resultSchemaRef`, and `schemaBlocks`) previously worked on `/headless`
endpoints, while canonical `/api/issues` routes, `GET
/api/issues/:id/heartbeat-context`, `paperclipai issue` CLI commands,
and Public MCP task tools did not accept or surface those fields
consistently, and OpenAPI exposed headless routes with summary-only
stubs.
> - Because agents wake up from `heartbeat-context`, inspect endpoint
schemas through OpenAPI and `runnerApiReference`, or mutate tasks
through canonical `POST`/`PATCH /api/issues` routes, CLI flags, and
Public MCP tools, missing fields on those surfaces forced callers onto
parallel endpoints or caused agents to miss required deliverable schemas
until after closing a task.
> - We chose to wire structured coordination directly onto the canonical
issue validators, routes, `heartbeat-context`, CLI flags, OpenAPI
schemas, `runnerApiReference` examples, and Public MCP task tools while
reusing existing channel-privacy and JSON Schema registries.
> - For Markdown ```` ```json schema=<name>@<version> ```` extraction in
issue descriptions and comments, we avoided multi-line backtracking
regular expressions and implemented a single-pass $O(N)$ CommonMark
character-index line scanner with strict input, fence-body, and block
caps so adversarial unclosed fences remain linear.
> - When an agent transitions an issue with `resultSchemaRef` to final
status `done`, `PATCH /api/issues/:id` now verifies that a valid
matching schema block exists across incoming or stored issue/comment
blocks and returns a self-documenting HTTP `422`
(`result_schema_validation_failed` with `requiredResultSchema` and
`jsonSchema`) while still allowing human board actors to close tasks
manually.

## Linked Issues or Issue Description

**What existing behavior does this improve?**
Canonical issue creation, updates, comments, list filters,
`heartbeat-context`, OpenAPI schemas, `runnerApiReference` examples,
`paperclipai issue` CLI commands, and Public MCP task tools now support
structured coordination fields (`channel`, `kvLabels`,
`resultSchemaRef`, and `schemaBlocks`) with full parity alongside
existing headless routes.

**Subsystem affected**
Server API (`packages/shared/src/validators/issue.ts`,
`server/src/routes/issues.ts`, `server/src/services/issues.ts`,
`server/src/routes/openapi.ts`,
`server/src/services/native-runtime/runner-api-reference.ts`,
`server/src/services/public-mcp/*`) and CLI
(`cli/src/commands/client/issue.ts`).

**Current behavior**
- `createIssueSchema`, `updateIssueSchema`, and `addIssueCommentSchema`
do not accept `channel`, `kvLabels`, `resultSchemaRef`, or
`schemaBlocks`.
- Canonical `GET /api/companies/:companyId/issues` does not filter by
`?channel=` or `?kvLabel=`, `GET /api/issues/:id/heartbeat-context`
omits `channelId`, `channelPath`, `kvLabels`, `resultSchemaRef`, and
`schemaBlocks`, and `PATCH /api/issues/:id` does not enforce
`resultSchemaRef` when an agent marks an issue `done`.
- `server/src/routes/openapi.ts` registers headless
channel/schema/kv-label/batch/queue/schedule/event endpoints with
summary-only stubs without `parameters` or `requestBody` schemas, and
`runnerApiReference` lacks examples for key headless coordination
routes.
- `paperclipai issue` (`create`, `update`, `comment`, `list`) and Public
MCP (`paperclip_search_tasks`, `paperclip_create_task`,
`paperclip_update_task`, `paperclip_add_comment`) do not expose channel,
key-value label, result schema, or schema block inputs/outputs.

**Proposed behavior**
- Extend `@paperclipai/shared` issue validators
(`createIssueBaseSchema`, `updateIssueSchema`, `addIssueCommentSchema`)
with validated `kvLabels`, `resultSchemaRef`, `channel`, `schemaBlocks`,
`commentKvLabels`, and `commentSchemaBlocks`.
- Add a linear $O(N)$ single-pass CommonMark schema fence scanner
(`server/src/services/schema-fence-scanner.ts`) with zero regexes and
strict input/fence caps (`512 KiB` text, `64 KiB` fence body, `64`
candidate fences, `32` blocks).
- Support `channel`, `kvLabels`, `resultSchemaRef`, and explicit/fenced
`schemaBlocks` on `POST /api/companies/:companyId/issues`, `POST
/api/issues/:id/children`, `PATCH /api/issues/:id`, `POST
/api/issues/:id/comments`, `GET /api/companies/:companyId/issues`
(`?channel=` and `?kvLabel=`), and `GET
/api/issues/:id/heartbeat-context`, enforcing private-channel access
rules and HTTP `422` `result_schema_validation_failed` (with
`requiredResultSchema` and `jsonSchema`) when an agent transitions an
issue with `resultSchemaRef` to final status `done`.
- Replace summary-only headless OpenAPI stubs with full `query` and
`requestBody` schemas, document `channel` and `kvLabel` query parameters
on `GET /api/companies/{companyId}/issues`, and add `runnerApiReference`
examples for `PATCH /api/issues/{}/kv-labels`, `POST
/api/companies/{}/channels/posts`, `POST /api/companies/{}/schemas`, and
`POST /api/companies/{}/issues/batch`.
- Add `--kv`, `--unset-kv`, `--result-schema`, `--channel`, and
`--schema-block` flags to `paperclipai issue` (`create`, `update`,
`comment`, `list`), and expose structured fields and inputs on Public
MCP task tools and projections.

**Reason and benefit**
Agents and humans can use one canonical set of issue endpoints, CLI
flags, Native Runner API discovery schemas, and Public MCP tools to
route work into channels, filter and patch structured `kvLabels`, attach
validated `schemaBlocks`, and enforce `resultSchemaRef` deliverables at
completion time with immediate JSON Schema feedback.

**Breaking changes**
No — purely additive on canonical issue schemas, CLI flags, OpenAPI
definitions, and Public MCP tools. Existing callers without
`resultSchemaRef` or structured fields behave identically, and human
board actors (`req.actor.type === "board"`) can still close tasks with
`resultSchemaRef` without attaching a schema block.

## What Changed

- **Shared Issue Validators
(`packages/shared/src/validators/issue.ts`)**: Added
`issueKvLabelsSchema`, `issueKvLabelsPatchSchema` (`null` unsets keys),
`issueResultSchemaRefSchema`, `issueChannelInputSchema`, and
`issueSchemaBlocksSchema`; extended `createIssueBaseSchema`,
`updateIssueSchema`, and `addIssueCommentSchema`; refreshed
`tests/runner-e2e/source-sdk-public-inputs.json`.
- **Linear Schema Fence Scanner & Structured Helpers
(`server/src/services/schema-fence-scanner.ts`,
`server/src/services/issue-structured-fields.ts`,
`server/src/services/issue-visibility.ts`)**: Implemented a
character-index single-pass CommonMark fence scanner with no
backtracking regexes, plus channel resolution/privacy helpers,
`kvLabels` merge/filter helpers, schema block validation, and agent
`done` deliverable enforcement.
- **Canonical Issue Routes & Service (`server/src/routes/issues.ts`,
`server/src/services/issues.ts`,
`server/src/routes/headless-channels-schemas.ts`)**: Wired `channel`,
`kvLabels`, `resultSchemaRef`, and `schemaBlocks` across create, child
create, update, comment, list (`?channel=`, `?kvLabel=`), and
`heartbeat-context` (`channelId`, privacy-checked `channelPath`,
`kvLabels`, `resultSchemaRef`, `schemaBlocks`), plus HTTP `422`
`result_schema_validation_failed` enforcement when an agent marks an
issue `done` without a valid deliverable block.
- **OpenAPI, Docs & Runner API Reference
(`server/src/routes/openapi.ts`,
`server/src/services/native-runtime/runner-api-reference.ts`,
`docs/api/issues.md`)**: Replaced summary-only headless OpenAPI entries
with full `query` and `requestBody` schemas reusing shared channel/batch
schemas across all 27 headless endpoints, documented `channel` and
`kvLabel` on `GET /api/companies/{companyId}/issues`, documented all new
canonical issue fields and `422 result_schema_validation_failed`
behavior in `docs/api/issues.md`, and added `runnerApiReference`
examples for `PATCH /api/issues/{}/kv-labels`, `POST
/api/companies/{}/channels/posts`, `POST /api/companies/{}/schemas`, and
`POST /api/companies/{}/issues/batch`.
- **CLI & Public MCP (`cli/src/commands/client/issue.ts`,
`server/src/services/public-mcp/{contracts,capabilities,expanded-capabilities}.ts`)**:
Added `--kv`, `--unset-kv`, `--result-schema`, `--channel`, and
`--schema-block` flags to `paperclipai issue` (`create`, `update`,
`comment`, `list`) and added structured fields and parameters to Public
MCP task contracts and tools (`paperclip_search_tasks`,
`paperclip_create_task`, `paperclip_update_task`,
`paperclip_add_comment`).

## Verification

- `pnpm --filter @paperclipai/shared build && pnpm --filter
@paperclipai/shared typecheck` — passed.
- `pnpm exec vitest run packages/shared/src/validators/issue.test.ts` —
65/65 passed (including Zod `z.toJSONSchema` compatibility).
- `pnpm exec vitest run
server/src/__tests__/schema-fence-scanner.test.ts` — 4/4 passed (`5,000`
repeated unterminated ```` ```json ```` lines scanned in `< 50ms`).
- `pnpm exec vitest run
server/src/__tests__/canonical-issue-structured-parity.test.ts
server/src/__tests__/headless-channels-schemas-batch.test.ts
server/src/__tests__/headless-e2e-sdk-cli.test.ts` — 14/14 passed.
(During initial test execution, an invalid `resultSchemaRef` fence on
`PATCH /api/issues/:id { status: "done", comment }` hit generic
`schema_validation_failed` before
`assertAgentResultSchemaSatisfiedOnDone`; reordered
`assertAgentResultSchemaSatisfiedOnDone` ahead of `validateSchemaBlocks`
so agents consistently receive `result_schema_validation_failed` with
`requiredResultSchema` and `jsonSchema`, then re-ran green.)
- `pnpm exec vitest run server/src/__tests__/openapi-routes.test.ts
server/src/services/native-runtime/runner-api.test.ts
server/src/services/native-runtime/runner-api-reference.test.ts` —
2,444/2,444 passed.
- `pnpm exec vitest run cli/src/__tests__/issue-subresources.test.ts` —
7/7 passed.
- `pnpm exec vitest run server/src/__tests__/public-mcp.test.ts` — 84/84
passed.
- `(cd server && node scripts/typecheck-layers.mjs)` and `pnpm --filter
paperclipai typecheck` — passed all typecheck layers.
- `node scripts/check-module-boundaries.mjs`, `node
scripts/check-agent-lifecycle-boundaries.mjs`, `node
scripts/check-test-budget.mjs`, and `node
tests/runner-e2e/source-sdk-public-inputs.mjs $(git rev-parse HEAD)
--check` — passed.
- `pnpm verify` — exited `2` (`Broad input:
tests/runner-e2e/source-sdk-public-inputs.json`) after refreshing
`source-sdk-public-inputs.json`; focused Vitest suites and layered
typechecks passed locally and broad coverage runs in required PR CI.
- **Round 1 PR CI & review follow-up**: Initial PR CI caught a circular
module initialization (`openapi.ts` importing
`ResolveInteractionInputSchema` from
`services/headless-events-schedules-interactions.ts`, leaving
`runnerApiCallSchema` undefined in `native-workflow-tools.ts`), and code
review flagged private-channel issue/child `visibility` inheritance,
locked-row `resultSchemaRef` enforcement + agent immutability, follow-up
edits on already-`done` tasks, SDK non-UUID retry-key routing on `POST
/issues/:id/comments`, strict `> 512 KiB` fence rejection,
`schemaBlocks` on `paperclip_create_task`/`paperclip_update_task`,
`timeout` query param on `/events/wait`, and `docs/api/issues.md`
updates. Removed the `services/*` import from `openapi.ts`, fixed each
review finding, and verified `tool-input-variant-admission.test.ts`,
`teams-catalog-service.test.ts`,
`canonical-issue-structured-parity.test.ts`, `public-mcp.test.ts`,
`headless-channels-schemas-batch.test.ts`,
`headless-e2e-sdk-cli.test.ts`, `headless-identity-auth.test.ts`, and
`schema-fence-scanner.test.ts` (2,663/2,663 tests passing across 13
suites).

## Risks

- **Private channel existence or path leakage**: Mitigated by checking
`canAccessChannel` on canonical channel writes, list filters
(`?channel=`), and `GET /api/issues/:id/heartbeat-context` (failing
closed with `404` on inaccessible private channel targets and returning
`channelPath: null` when a private channel is not accessible to the
caller).
- **Adversarial Markdown payloads on issue/comment writes**: Mitigated
by scanning fences with a pure character-index single-pass CommonMark
line scanner with zero regular expressions, bounded at `512 KiB` input
text, `64 KiB` per fence body, `64` candidate fences, and `32` schema
blocks.
- **`resultSchemaRef` completion blocking**: Mitigated by enforcing
`422` `result_schema_validation_failed` only when `req.actor.type ===
"agent"` and the effective target status after execution-policy routing
is `"done"`, preserving manual task closure for board humans and
intermediate `in_review` transitions.

## Model Used

Google DeepMind `gemini-3.1-pro` via Antigravity agentic coding harness
(1M context window, high reasoning effort, native workspace/file/test
tool execution).

## Checklist

- [x] I searched the [GitHub PR
list](https://github.com/paperclipai/paperclip/pulls?q=is%3Apr) (open +
recently closed) for similar PRs and confirmed this is not a duplicate
- [x] My code follows the project's [code
comments](CONTRIBUTING.md#code-comments) guidelines (self-documenting,
minimal comments)
- [x] `pnpm -r typecheck` passes (verified locally across
`@paperclipai/shared`, `server` layered typecheck, and `paperclipai`
CLI; full workspace `typecheck_release_registry` verified in PR CI)
- [x] `pnpm test:run` passes (focused owner Vitest suites passed
locally; full CI matrix verified in PR CI)
- [ ] `pnpm build` passes
- [ ] If I changed `packages/db`, I ran `pnpm db:generate` and committed
the migration
- [x] If I added a user-facing capability, I updated `README.md` or
relevant docs (`docs/api/issues.md`)
- [x] This PR focuses on a single concern (no unrelated changes bundled)

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-12-01 21:53:58 +00:00
DottaandPaperclip 3833e1c8e8 feat(runner): add channel, kvLabels, schemaBlocks, and resultSchemaRef parity to native task tools (#23406)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Native Runner agents coordinate tasks, progress updates, and
searches through semantic protocol tools (`create_task`,
`report_progress`, `search_tasks`, `get_task_context`, and
`get_task_history`)
> - Headless API clients already use channels, key-value labels
(`kvLabels`), validated `<name>@<version>` schema blocks
(`schemaBlocks`), and required completion schemas (`resultSchemaRef`),
while native Runner tools omitted those fields
> - Because native Runner tools omitted those fields, native agents
could not file tasks into channels, filter task searches by channel or
label, attach structured schema blocks to progress updates, or verify
`resultSchemaRef` before completion
> - This pull request adds channel, `kvLabels`, `schemaBlocks`, and
`resultSchemaRef` support across native Runner tool schemas, authority
handlers, completion validation, and `skills/paperclip/SKILL.md`
> - The benefit is full structured-metadata and channel parity for
native Runner agents while preserving strict provider tool schemas,
private channel boundaries, and upgrade-safe receipt replay

## Linked Issues or Issue Description

**What existing behavior does this improve?**
Native Runner task tools (`create_task`, `report_progress`,
`search_tasks`, `get_task_context`, and `get_task_history`), native
deliverable completion checks (`validateNativeDeliverableEvidence`), and
`skills/paperclip/SKILL.md`.

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

**Current behavior**
Currently, native Runner semantic tools (`create_task`,
`report_progress`, and `search_tasks`) do not accept `kvLabels`,
`channel`, `labelFilter`, `schemaBlocks`, or `resultSchemaRef`. Read
tools (`get_task_context`, `get_task_history`, and `search_tasks`) omit
`channelId`, `channelPath`, `kvLabels`, `resultSchemaRef`, and
`schemaBlocks`. In addition, `validateNativeDeliverableEvidence` does
not check `issues.resultSchemaRef` before a native run marks a task
`done`.

**Proposed behavior**
`create_task` accepts optional `kvLabels`, `resultSchemaRef`, and
`channel` inputs and returns `channelId`, `channelPath`, `kvLabels`, and
`resultSchemaRef` on `result.task`. `report_progress` accepts optional
`kvLabels` and `schemaBlocks` inputs and extracts `json
schema=<name>@<version>` fenced blocks from `body` with a single-pass
`O(N)` line scanner. `search_tasks` accepts optional `labelFilter` and
`channel` filters (exact path, subtree prefix, or UUID) while preserving
cursor pagination and private channel access checks. `get_task_context`
and `search_tasks` return `channelId`, `channelPath`, `kvLabels`,
`resultSchemaRef`, and `schemaBlocks`, and `get_task_history` returns
`actorProfile`, `kvLabels`, and `schemaBlocks` (clearing metadata on
quarantined comments for higher-trust readers). When
`issues.resultSchemaRef` is set, `validateNativeDeliverableEvidence`
requires a valid matching JSON payload before completion, and final
reply comments persist valid fenced schema blocks onto
`issue_comments.schema_blocks`.

**Reason and benefit**
Agents running on the native Runner protocol need the same channel
routing, key-value metadata, and structured JSON schema contracts that
REST and headless workflows use. Enforcing `resultSchemaRef` at the
native deliverable gate prevents native runs from closing tasks without
valid structured output.

**Breaking changes**
None. All new tool input and output properties are optional. Existing
tool calls and saved mutation receipts without the new fields continue
to validate and replay without change.

**Additional context**
Tool input schemas use strict provider-portable array entries for
`kvLabels` (`{ key, value }`) and `schemaBlocks` (`{ schema, version,
dataJson }`) so OpenAI/Codex dynamic tools, AgentCore inline schemas,
Ajv strict mode, and RE2 checks all pass without open object maps.

## What Changed

- Extend `create_task`, `report_progress`, and `search_tasks` in
`packages/paperclip-runner/src/protocol-actions/` and
`src/catalog/semantic-action-catalog.ts`, and regenerate contract
manifests, capability YAML/Markdown, capability inventory, and seeded
eval fixtures.
- Add `native-schema-fences.ts`, `native-task-channels.ts`, and
`native-result-schema-gate.ts` (re-exported by
`native-task-metadata.ts`) with a linear `O(N)` single-pass CommonMark
fence scanner (`scanFencedSchemaBlocks`), `kvLabels` normalization,
transactional `schemaBlocks` persistence, a 128 KiB response-wide
`schemaBlocks` budget with truncation metadata, private-channel
authorization helpers, and run-scoped
`assertNativeResultSchemaSatisfied`.
- Update `PaperclipRunnerToolAuthority` (`get_task_context`,
`get_task_history`, `search_tasks`, `#reportProgress`, and
`#createTask`) for read/write parity, private-channel redaction,
quarantined comment `actorProfile`/`kvLabels`/`schemaBlocks` redaction,
and `channel` scope inclusion on filtered searches.
- Wire `assertNativeResultSchemaSatisfied` into
`validateNativeDeliverableEvidence` and persist valid fenced schema
blocks on final reply comments in `native-run-finalizer.ts` and
`run-completion.ts`.
- Document `kvLabels`, `channelPath`, `schemaBlocks`, `resultSchemaRef`,
and `PATCH /api/issues/{issueId}/kv-labels` in
`skills/paperclip/SKILL.md`.
- Add unit, ReDoS linear-time (`< 50ms` on 5,000 unclosed fences),
integration, private-channel, completion-gate, and upgrade-cutover
receipt replay tests.

## Verification

- `pnpm --filter @paperclipai/paperclip-runner typecheck:typescript`
- `pnpm --filter @paperclipai/paperclip-runner check:protocol-manifest`
- `pnpm --filter @paperclipai/paperclip-runner
check:capability-contract`
- `pnpm --filter @paperclipai/paperclip-runner check:semantic-contracts`
- `pnpm --filter @paperclipai/paperclip-runner
check:semantic-action-catalog`
- `pnpm --filter @paperclipai/paperclip-runner check:replay-goldens`
- `pnpm --filter @paperclipai/paperclip-runner test:typescript:prep`
- `pnpm --filter @paperclipai/paperclip-runner check:static`
- `pnpm --filter @paperclipai/paperclip-runner check:api-authority`
- `pnpm --filter @paperclipai/paperclip-runner exec vitest run
src/protocol-actions/collaboration-contracts.test.ts
src/protocol-actions/core-contracts.test.ts
src/catalog/semantic-action-catalog.test.ts
src/contracts/provider-tool-schema-shape.test.ts
src/drivers/runner-tool-bridge.schemas.test.ts
src/evals/native-execution.test.ts
src/semantic-tools/semantic-tools.test.ts
src/mock-core/capability-mock-control-plane-adapter.test.ts`
- `node
packages/paperclip-runner/scripts/contracts/contract-fingerprints.test.mjs`
- `(cd server && node scripts/typecheck-layers.mjs)`
- `node scripts/check-test-budget.mjs`
- `pnpm --filter @paperclipai/server exec vitest run
src/services/native-runtime/native-task-metadata.test.ts
src/services/native-runtime/tool-input-variant-admission.test.ts
src/services/native-runtime/native-completion-feedback.test.ts
src/services/native-runtime/paperclip-runner-tool-authority.test.ts`

## Risks

- **Upgrade-safe run state carry-forward
(`rules/upgrade-safe-run-state.mdc`)**: In-flight native runs started on
a previous release may carry saved `semanticToolReceipts` in
`heartbeat_runs.result_json` for `create_task` and `report_progress`
without `kvLabels`, `resultSchemaRef`, `channel`, or `schemaBlocks`. All
new fields are optional, `#withMutationReceipt` hashes raw caller
`input` without mutating missing keys, and `create_task`
`outputSchema.properties.task.required` is unchanged. Previous-release
receipts replay identically on `recover()` and `execute()` without
re-running effects, verified by a dedicated cutover test in
`paperclip-runner-tool-authority.test.ts`.
- **Markdown scanning safety**: Fenced schema extraction uses a bounded
`O(N)` line scanner (512 KiB max markdown scan, 64 KiB max fence body,
64 max candidate fences, zero multi-line backreference regular
expressions) so untrusted or malformed markdown cannot cause quadratic
backtracking.

## Model Used

- Anthropic Claude Opus 4.6 (`claude-opus-4-6`, extended thinking
enabled, agentic tool use and local command execution)

## Checklist

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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-12-01 15:53:37 -06:00
Devin FoleyandPaperclip d884e4e877 fix(test): leave the claim token hash out of the recovery lock comparison (#23413)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Each master commit gets a Docker image. The image build first waits
for the full test suite on that exact commit, and it stops if a test
fails
> - #23382 added a `claimTokenHash` column to issues. The issue service
removes this column from the rows it returns, so that the hash never
leaves the server
> - Four tests in `issue-recovery-actions.test.ts` compare the row from
`issuesSvc.update` with the full database row. The full row has
`claimTokenHash`, so the comparison fails
> - These tests fail on every master commit since #23382, so no master
image was published after that commit
> - This pull request removes `claimTokenHash` from the database row
before the comparison
> - The benefit is that master images build again, and the tests also
make sure that the service row does not have the hash

## Linked Issues or Issue Description

No public issue exists.

**What happened?**
After #23382 merged, the full server test suite fails on master in
`issue-recovery-actions.test.ts`. The four "preserves a concurrent …
decision when stale stranded recovery waits for the issue lock" tests
fail with `expected { …(86) } to match object { …(83) }`, and the diff
shows only `"claimTokenHash": null`. The master image build stops on
this failure, so master commits after #23382 have no image.

**Expected behavior**
The tests pass. The service row and the database row agree on every
column that the service returns.

**Steps to reproduce**
1. Check out `master` at 689bfd04ac.
2. In `server/`, run `npx vitest run
src/__tests__/issue-recovery-actions.test.ts -t "stale stranded recovery
waits for the issue lock"`.
3. See 4 tests fail on `claimTokenHash`.

**Paperclip version or commit**
`master` at 689bfd04ac. The failure starts at ce2e6ccc00 (#23382).

**Deployment mode**
Not applicable. This is a test failure in CI.

## What Changed

- In the four lock tests, the test removes `claimTokenHash` from the
database row before it compares that row with the row from
`issuesSvc.update`.
- The tests also make sure that the row from `issuesSvc.update` does not
have `claimTokenHash`.
- No change to production code.

## Verification

- Without the change, the 4 tests fail on master, as in the steps above.
- With the change, `npx vitest run
src/__tests__/issue-recovery-actions.test.ts` (in `server/`): 121 tests
pass.
- `pnpm --filter @paperclipai/server typecheck` passes.

## Risks

- Low risk. The change is only in a test file.

## Model Used

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

## 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
documentation describes this test)
- [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>
canary/v2026.1201.0-canary.877500
2026-12-01 13:27:10 -08:00
Dotta c0edaa21a3 feat(analytics): move onboarding funnel telemetry server-side and add granular step instrumentation (#23403)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Hosted Paperclip Cloud tracks user onboarding conversion in PostHog
across server-side events and browser events
> - Onboarding funnel events (`onboarding_opened`,
`onboarding_step_viewed`, `onboarding_step_completed`,
`onboarding_step_failed`, `onboarding_dismissed`) currently fire only
from browser `posthog-js`
> - Browser `posthog-js` loads lazily after `whenPageSettles` (up to 15
seconds), drops events captured before `startProductAnalytics`
initializes, and can be blocked by privacy extensions, causing
artificial dropoff between server-side `workspace_entry` and
`onboarding_opened`
> - Step 1 (`name_org`) is unmapped in `WIZARD_STEPS`, and
`connect_model` lacks sub-step visibility (provider selection,
credential mode switch, OAuth progress, API key submission, Cloud trial
CTA, mobile handoff)
> - This pull request routes all onboarding funnel events through a
first-party `POST /api/onboarding/telemetry` endpoint backed by
`trackCloudPostHogEvent` (`posthog-node`), preserves every existing
event name verbatim, adds granular step and sub-step instrumentation,
and fixes the pre-start queue drop in `product-analytics.ts`
> - The benefit is adblocker-proof, race-free server-side onboarding
analytics in PostHog with complete step-by-step dropoff visibility and
zero breaking changes to existing insights

## Linked Issues or Issue Description

**What existing behavior does this improve?**
Cloud onboarding funnel analytics in
`ui/src/lib/analytics/onboarding-analytics.ts`,
`ui/src/lib/analytics/product-analytics.ts`,
`ui/src/components/OnboardingWizard.tsx`, and `server/src/telemetry.ts`.

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

**Current behavior**
Onboarding funnel events fire only from browser `posthog-js`. Events
captured before `ProductAnalyticsGate` calls `startProductAnalytics` are
silently dropped, queued events are lost if the user leaves before
`/_ph/static/array.js` loads, Step 1 (`name_org`) is unmapped, and
`connect_model` sub-steps (OAuth link open, code submit, retry, abandon,
provider tile click, Cloud trial CTA, mobile desktop handoff) are not
instrumented.

**Proposed behavior**
All onboarding funnel and interaction events are sent via
`fetch("/api/onboarding/telemetry", { method: "POST", keepalive: true
})` to a board-authenticated, strictly Zod-validated Express route that
forwards them server-side to PostHog via `trackCloudPostHogEvent`.
Existing event names are preserved verbatim and removed from
`posthog-js` to guarantee a single sender per event. Pre-start browser
events in `product-analytics.ts` are also buffered until
`startProductAnalytics` runs.

**Reason and benefit**
Adblockers and browser script lazy-load races can no longer drop
onboarding funnel events. Product analytics can now separate
`workspace_entry` -> `onboarding_workspace_loaded` ->
`onboarding_opened` and pinpoint exact dropoff points on every step and
`connect_model` sub-step.

**Breaking changes**
None. Existing PostHog event names (`onboarding_opened`,
`onboarding_step_viewed`, `onboarding_step_completed`,
`onboarding_step_failed`, `onboarding_dismissed`,
`agent_chat_message_sent`) are preserved verbatim. On self-hosted
installs, `trackCloudPostHogEvent` is a no-op and the endpoint returns
`204 No Content`.

## What Changed

- Added `packages/shared/src/onboarding-telemetry.ts` (exported from
`packages/shared/src/index.ts`) with strict Zod discriminated-union
schemas (`onboardingTelemetryEventSchema`), canonical event names
(`ONBOARDING_TELEMETRY_EVENTS`), and snake_case PostHog property mapping
(`onboardingTelemetryEventToPostHogProperties`).
- Added `server/src/routes/onboarding-telemetry.ts` (`POST
/api/onboarding/telemetry`), mounted in `server/src/app.ts`, enforcing
`assertBoard(req)`, `assertCompanyAccess(req, companyId)` when
`companyId` is present, strict schema validation, and server-side
delivery via `trackCloudPostHogEvent`.
- Updated `ui/src/lib/analytics/onboarding-analytics.ts` to send all
onboarding events to `/api/onboarding/telemetry` with `keepalive: true`
(removing duplicate browser `posthog-js` sends), mapped Step 1 to
`name_org`, fixed `1 -> 3` forward step completion ordering, and added
granular capture helpers.
- Instrumented `ui/src/hooks/useAgentlessOnboardingAutoOpen.ts`
(`onboarding_workspace_loaded`),
`ui/src/components/onboarding/MobileDesktopNudge.tsx`
(`onboarding_mobile_handoff_action`), and
`ui/src/components/OnboardingWizard.tsx` (all step submissions,
back/jump navigation, Cloud trial CTA, model source selection,
credential mode switching, OAuth progress stages, API key submission,
advanced toggle, and launch click). Note: `OnboardingWizard.tsx` is an
existing large file (>1,000 lines); all schema and transport logic lives
in `packages/shared/src/onboarding-telemetry.ts` and
`ui/src/lib/analytics/onboarding-analytics.ts`, with only call-site
wiring added to the wizard.
- Fixed `ui/src/lib/analytics/product-analytics.ts` to buffer events
captured before `startProductAnalytics` runs (still bounded to 50 events
and cleared on user change).
- Added server route tests in
`server/src/__tests__/onboarding-telemetry-routes.test.ts` and expanded
`ui/src/lib/analytics/onboarding-analytics.test.tsx`.
- Updated `tests/runner-e2e/source-sdk-public-inputs.json` for the new
`@paperclipai/shared` export.

## Verification

- `pnpm --filter @paperclipai/shared build` — passed.
- `pnpm --filter @paperclipai/ui typecheck` — passed.
- `pnpm --filter @paperclipai/server typecheck` — passed.
- `pnpm vitest run
server/src/__tests__/onboarding-telemetry-routes.test.ts
ui/src/lib/analytics/onboarding-analytics.test.tsx
ui/src/lib/analytics/product-analytics.test.ts
ui/src/lib/analytics/product-analytics-events.test.ts
ui/src/components/ProductAnalyticsGate.test.tsx
ui/src/hooks/useAgentlessOnboardingAutoOpen.test.tsx` — 6/6 test files
passed (41/41 tests).
- `pnpm verify` — exited with code 2 because
`tests/runner-e2e/source-sdk-public-inputs.json` requires broad CI
coverage; relying on required CI checks for the remaining broad suites.

## Risks

- Low risk: `POST /api/onboarding/telemetry` performs no database
writes, validates all fields against a strict allowlist (enums,
booleans, bounded integers, safe regex slugs), enforces board auth and
company access, and is a no-op returning `204` on self-hosted instances.
- Browser telemetry calls swallow network failures so analytics can
never block or break onboarding.

## Model Used

- Google Gemini (Gemini 4 Neon, Medium) via Antigravity agentic coding
environment with tool use and local command execution.

## Checklist

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

> - Paperclip is the open source app people use to manage AI agents for
work.
> - First-time Cloud users currently must connect an external AI
provider during onboarding before they can talk to their first agent.
> - Requiring provider setup up front adds friction before users
experience their first agent chat.
> - Paperclip needs a multi-variant onboarding experiment
(`onboarding-flow`) that defaults to `baseline` while allowing an
alternate `free_inference_1` path that skips the model-connection screen
and starts with capped starter inference.
> - When a trial-only workspace either exhausts its starter credit or
creates its first executable task or subtask, Paperclip must hold the
new task, prompt the user to connect a model provider, keep LLM actions
blocked if the modal is dismissed, and automatically resume held work
once a model is connected.
> - This pull request adds multi-variant onboarding resolution, PostHog
multi-variant attribution, dual-trigger connect-model gating with
restart-safe DB hydration, the `free_inference_1` UI onboarding flow,
and full-flow Storybooks.
> - The benefit is a safe, measurable onboarding experiment that leaves
`baseline` and self-hosted installs unchanged while letting opted-in
Cloud workspaces reach their first chat immediately and upgrade
seamlessly when real work begins.

## Linked Issues or Issue Description

**Subsystem affected**

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

**Problem or motivation**

New Cloud users currently hit a mandatory "Connect a model" step during
onboarding before they can open their first agent chat. Existing
trial-inference gating only supported a binary flag and only triggered
on starter-credit exhaustion, not on subtask or manual task creation,
and did not track multi-variant onboarding cohorts cleanly in PostHog.

**Proposed solution**

Introduce the extensible `onboarding-flow` experiment (`baseline`
default, `free_inference_1` variant) across shared contracts, server
services, and UI:
- Resolve `onboardingVariant` from the Cloud control plane (`GET
/v1/tenant/onboarding-config`) with safe fallbacks to
`PAPERCLIP_ONBOARDING_VARIANT`, managed config, and `"baseline"`.
- In `free_inference_1`, skip Step 4 ("Connect a model") in
`OnboardingWizard`, hire the first agent on starter inference, and drop
the user straight into the first chat.
- Support a dual-trigger connect-model gate (`exhausted` and
`work_requires_model`) that holds newly created tasks/subtasks on
trial-only workspaces (hydrated from DB across restarts), returns HTTP
402 for blocked LLM chat/runs, keeps the modal dismissible while
blocking chat composers with a "Connect a model" CTA banner, and
automatically resumes held work after provider migration.
- Stamp `$feature/onboarding-flow`, `onboarding_variant`, and immutable
`initial_onboarding_variant` across server PostHog events,
`$groupidentify` (with top-level `$group_set_once`), and browser PostHog
super-properties / `identify()`.

**Alternatives considered**

- Baking per-stack experiment variants into warm-pool container config
was ruled out because warm-pool stacks must remain homogeneous until
claim time.
- Failing agent subtask creation calls on trial-only workspaces was
ruled out because it breaks the agent's first-chat experience; creating
the task in a held state and auto-resuming it after model connection
preserves user intent.

## What Changed

- **`packages/shared`**: Added `onboarding-flow` variant
constants/helpers, `CloudTrialGateReason` (`"exhausted" |
"work_requires_model"`), `CloudTrialHeldIssueSummary`, `gateReason`,
`llmBlocked`, `heldIssueIds`, `heldIssues`, `onboardingVariant`, and
`resumedIssueIds` on cloud-inference and session/browser-analytics
contracts.
- **`server/`**:
- Added Ed25519-signed `GET /v1/tenant/onboarding-config` resolution
with warm-pool claim cache invalidation and safe `"baseline"` default.
- Added dual-trigger trial gating (`exhausted` + `work_requires_model`)
with DB-backed held-issue hydration across restarts, HTTP 402 refusal
for blocked trial runs and chat sends, and automatic wake/resume of held
subtasks upon migration.
- Updated PostHog server telemetry, `$groupidentify` (top-level
`$group_set` and `$group_set_once`), `$feature_flag_called`, and
`BrowserAnalyticsConfig` to stamp `onboarding-flow` multi-variant
properties while preserving backwards-compatible `cloud-trial-inference`
properties.
- Added and updated Vitest suites covering multi-variant resolution,
PostHog attribution, held subtask creation, cold-restart hydration, LLM
run refusal, and auto-resume.
- **`ui/`**:
- Updated `OnboardingWizard` so `free_inference_1` skips Step 4
("Connect a model"), auto-hires with `cloudTrialInference: true`, and
launches straight into the first chat while leaving `baseline`
unchanged.
- Updated `CloudTrialGate` and `CloudTrialExhaustedModal` for
dual-trigger copy (`work_requires_model` vs `exhausted`), waiting
subtask pills, and dismissible modal behavior (`required={false}`).
- Added `CloudTrialBlockedBanner` and wired LLM-blocked composer
disabling + "Connect a model" CTA into `IssueDetail` / `AgentChat` and
`DashboardChatComposer`, plus status refresh on manual task creation in
`NewIssueDialog`.
- Updated `product-analytics.ts` + tests to register
`$feature/onboarding-flow` and `onboarding_variant` super-properties and
`$set_once.initial_onboarding_variant`.
- Added full-flow Storybooks
(`free-inference-onboarding-flow.stories.tsx`) covering all 7 onboarding
and gate states.

## Verification

- `pnpm --filter @paperclipai/shared typecheck && pnpm --filter
@paperclipai/server typecheck` (0 errors)
- `pnpm --filter @paperclipai/ui typecheck` (0 errors)
- 9 targeted server Vitest suites (`cloud-trial-inference`,
`cloud-posthog-config`, `cloud-posthog-browser`,
`posthog-direct-telemetry`, `posthog-direct-transport`, `auth-routes`,
`cloud-runtime-identity`, `onboarding-seed-route`,
`issue-onboarding-first-task-routes`): 196/196 passed
- 4 targeted UI Vitest suites (`CloudTrialGate.test.tsx`,
`product-analytics.test.ts`, `onboarding-analytics.test.tsx`,
`Layout.mobile.test.tsx`): 37/37 passed
- `pnpm --filter @paperclipai/ui build` and `pnpm --filter
@paperclipai/ui build-storybook`: passed
- Visually inspected Storybook renders across all 7 `free_inference_1`
states in headless Chromium via Playwright with zero page errors.

## Risks

- Low risk to existing users: `onboardingVariant` defaults to
`"baseline"` everywhere, leaving self-hosted installs and unflagged
Cloud stacks unchanged.
- No database schema migrations are required; held trial subtasks are
hydrated from existing `issues` and `toolConnections` tables on restart.
- Requires the companion `paperclip-cloud` control-plane endpoint (`GET
/v1/tenant/onboarding-config`) to activate non-baseline variants in
Cloud; falls back safely to `"baseline"` if unavailable.

## Model Used

- Google Gemini (Antigravity agentic coding environment with multi-agent
swarm, tool use, code execution, and Playwright Storybook verification)

## Checklist

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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-12-01 20:54:03 +00:00
DottaandPaperclip b63445c8f1 fix(e2e): save hiring task intents at the submit boundary (#23400)
## Thinking Path

> - Paperclip manages work by AI agents.
> - Its product journeys verify hiring and task delegation through chat.
> - Cleanup uses saved creation intents to track possible writes.
> - The hiring journey saves each task intent before browser
preparation.
> - A navigation or editor failure can therefore leave an intent for a
request that was never sent.
> - This pull request saves the intent after message validation and
before Send.
> - Cleanup can retain strict write protection without treating failed
preparation as a possible task creation.

## Linked Issues or Issue Description

**What happened?**
The hiring journey can save a review-task intent even when a browser
failure stops the third chat request before submission. Cleanup then
reports an uncertain creation outcome. A controlled navigation failure
reproduces this tracking defect. The original retained browser exception
is unavailable; this change does not claim its cause.

**Expected behavior**
Browser preparation must not register a task write. The creation intent
must be saved before submission can create work. A failed intent save
must stop submission. A send with a possible committed write must retain
the intent.

**Steps to reproduce**
Inject a navigation failure before the review request after the
checklist completes. The original code records the review intent despite
making only two sends. The new code preserves the checklist receipt and
records no review intent.

**Paperclip version or commit**
Reproduced from source at `5a9c06b315d9612022908b7fc189f30bac3619af`.

**Deployment mode**
Linux source checkout, focused workflow tests, and Chromium against the
real production composer. The paid hosted acceptance case remains
pending until merge. Related earlier hiring coverage and spacing fixes:
#18351 and #22825.

## What Changed

- Save delegated-task intents through an awaited callback after the
exact mention chips are verified and before the browser clicks Send.
- Cover failed review navigation, failed intent persistence, rejected
mentions, and a send failure after the intent boundary.
- Keep handoff references and task name in one typed object. A handoff
without its intent name is no longer representable.
- Keep the existing ownership, initial assignment, saved-body,
seven-run, budget, and cleanup checks.
- Document the submission boundary.

## Verification

- Red: the new review-navigation regression failed because the old flow
saved the review intent without sending that request.
- Green: 78 focused flow and evidence tests pass.
- All 8 real-composer Chromium checks pass. They cover both composer
modes, exact saved messages, failed intent persistence, page loss after
persistence, and rejected agent/project mentions.
- `pnpm test:e2e:runner:typecheck` passes.
- `pnpm verify --explain` could not select checks because the managed
Git storage guard rejects `git ls-files`. Even the suggested shallow
fetch fails. This unavailable check is not a pass. The source was
compared with master through the repository API before publication.
- Original head `6914c4b` passed
[CI](https://github.com/paperclipai/paperclip/actions/runs/46723605434)
and Greptile 5/5 with Low impact. Typecheck, four support shards, six
Runner package shards, static checks, and aggregate verification passed.
Build was skipped by the test-only path policy.
- Review head `cd7b03f36d6d9fcac37cf80906fad2f7cd167958` passes the 78
focused tests, all 8 browser checks, and runner E2E typecheck. Its first
browser attempt could not start because the resumed sandbox lacked
Chromium; installation restored the check, which then passed. The
current head passed
[CI](https://github.com/paperclipai/paperclip/actions/runs/46727370488),
including Typecheck + Release Registry, four support shards, six Runner
package shards, static checks, and aggregate verification. Build is
skipped by the test-only path policy. Greptile, Feynman and Ponytail
each gave this head 5/5, with Low impact from Greptile. The actionable
thread is resolved. Hosted acceptance must run only
`hire-delegate-reuse` after merge.

## Risks

The callback and Send cannot form one atomic operation. A failure after
intent persistence still keeps the intent and the existing
uncertain-write protection. This patch does not manufacture absence
proof for old retained manifests. The original browser error remains
unknown.

## Model Used

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

## Checklist

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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-12-01 19:56:35 +00:00
DottaandPaperclip 7585830b9c fix(opencode): bound cooperative abort before governed shutdown (#23399)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Native Runner saves a question before it stops the provider turn.
> - The wait must retain usage and prove shutdown before the run can
finish.
> - OpenCode's abort HTTP request can hold the command loop for twenty
seconds.
> - The transport close budget is ten seconds. A late abort can delay
definitive stop and suspension beyond that budget.
> - This pull request limits the cooperative abort request to five
seconds.
> - The benefit is time for definitive shutdown, with the same
accounting and suspension checks.

## Linked Issues or Issue Description

**What happened?**

A saved question can be followed by a failed native run. OpenCode's
cooperative abort can wait longer than the transport's shutdown budget.
The shutdown commands then lack time to prove provider drain and durable
suspension. A saved interaction alone cannot prove that the previous
executor stopped.

**Expected behavior**

A stalled cooperative abort must release the command loop in time for
definitive process stop. A timeout must still reject interruption. It
must not create a terminal event or count as successful accounting.

**Steps to reproduce**

Start a controlled OpenCode session. Keep its abort HTTP request pending
until its signal aborts. Request interruption. Advance the controlled
clock by five seconds. On the base code, the request is still pending.
With this change, the request rejects and the active turn remains
recorded without a terminal event or a new model request.

Related prior repairs: #20494, #20519, #20838. They address saved wait
recovery. This change addresses the pending cooperative abort before
definitive shutdown.

## What Changed

- Give only OpenCode's session abort a five-second HTTP deadline through
the API helper. Other API requests keep their existing deadline.
- Keep timeout errors visible. Keep physical stop, retained usage, and
durable suspension proof unchanged.
- Add a controlled-clock regression to the existing interruption tests.
- Document the deadline and proof requirements in the durable transport
contract.
- Keep session state and identity formats unchanged. Previous releases'
saved state needs no migration.

## Verification

- Red: the new regression fails on the base code because the request
signal remains active after five seconds.
- Green: both interruption test files pass, 13 tests. These include
idle, silent, busy-tool, provider-question handoff, pending MCP tool,
and the new stalled abort case.
- The eight `settles only verified governed shutdown` cases pass. They
cover success, restart, foreign turn, missing proof, stop failure,
timeout, provider failure, and terminal write failure.
- The broader driver run has 99 passes and eight failures. The same
driver file with this production change removed has 86 passes and the
same eight failures. Those failures concern final-answer retention. They
remain a verification gap; this PR does not change their assertions.
- No hosted acceptance claim yet. After merge and automatic staging
deployment, run only the question-answer-resume journey.
- Required CI passed on final commit
`45e39805efffbd648bfeca9697c9898593487805`:
https://github.com/paperclipai/paperclip/actions/runs/46726627054. This
includes typecheck, build, Runner tests, general tests, and E2E suites.
- Greptile gives final commit `45e39805e` 5/5, Medium impact. All three
review threads are resolved.
- After review corrections, both interruption files pass again: 13
tests. The test always restores timers and attempts resource cleanup.
The API helper owns the single request deadline.

## Risks

- An abort response that needs more than five seconds now fails earlier.
Definitive process stop must still prove shutdown. A timeout alone does
not authorize session reuse or completion.
- The regression uses the real driver and a controlled HTTP boundary. It
does not prove hosted suspension timing. The targeted staging journey
remains required.
- The owning driver file already exceeds 1,000 lines. The change adds
only the request deadline and its rationale at the existing abort call.
A separate module would add no useful boundary.
- There is no schema, saved identity, provider selection, accounting
policy, or journey grading change.

## Model Used

- OpenAI GPT-6, through Codex with reasoning and tools for source
inspection, code editing, and test execution.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [ ] 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-12-01 19:55:53 +00:00
Devin FoleyandPaperclip 11d5b06864 fix(runner): give a plugin task prepare 60 s without a startup context (#23396)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - An environment plugin can run an agent's Runner on remote compute,
such as a remote computer
> - Before the Runner starts, Core asks the plugin to prepare the task:
its workspace, its home, and the agent's instructions and skills
> - A warm start gets the startup context's deadline for this step. A
cold start has no startup context, so prepare gets the 15 s default for
every plugin task call
> - On a remote computer, a cold prepare often takes 11-16 s. When
several runs start at once, most of them time out
> - The timeout does not stop the work. The plugin finishes it, the run
fails, and its retry repeats the same prepare, which adds load
> - This pull request gives a prepare without a startup context 60 s,
the cold admission budget the Runner gives a Claude session
> - The benefit is that a slow cold start starts late instead of failing
and starting again

## Linked Issues or Issue Description

No public issue exists.

**What happened?**
Agent runs on a plugin-provided remote computer failed at startup with
"Plugin-provided Runner execution operation unavailable; reconcile the
same task before retrying". The plugin's prepare call ran for about 15
s, then Core stopped waiting. The plugin's later host calls for that
task got "Missing or unknown invocation scope". On one agent, about half
of all cold starts failed this way while it worked through a backlog.
Successful cold starts on the same computer took 17 s at the median for
the full Runner startup, so prepare had little margin.

**Expected behavior**
A cold prepare that takes 20 s finishes, and the run starts 20 s later.

**Steps to reproduce**
1. Use an environment plugin that runs Runner tasks on remote compute,
with a cold prepare that takes more than 15 s.
2. Start a run for an agent with no warm task on that computer.
3. See the run fail at startup with the error above, and a new run start
the same prepare again.

**Paperclip version or commit**
`master` at 51541be36f.

**Deployment mode**
Authenticated deployment with an environment plugin that runs Runner
tasks on remote compute.

## What Changed

- `executeEnvironmentTask` gives a `prepare` operation without a startup
context a 60 s timeout. Before, it got the 15 s default.
- A `prepare` with a startup context keeps the context's deadline.
Ownership and `describe` calls with session handoff keep 90 s.
`copilot_metadata` keeps its probe-bound limit. All other task
operations keep 15 s.
- The prepare tests in `environment-task-runtime.test.ts` expect 60 s.

## Verification

- `pnpm --filter @paperclipai/server typecheck` passes.
- `npx vitest run src/__tests__/environment-task-runtime.test.ts
src/__tests__/plugin-runner-task.integration.test.ts
src/services/heartbeat/run-completion.test.ts` (in `server/`): 3 files,
253 tests pass.
- Without the code change, 5 prepare tests in
`environment-task-runtime.test.ts` fail on the timeout argument. The
submit, stop, status, complete and resume tests still expect 15 s and
pass.
- I checked what a longer prepare affects downstream:
- The run's execution lease is renewed from the moment the run is
claimed, so a long prepare does not lose it.
- The Runner starts its cold admission deadline after prepare returns,
so prepare does not use that budget.

## Risks

- Low risk. A prepare that truly hangs now takes 60 s to fail instead of
15 s. Its run stays in startup for that time.
- No change for local adapters or sandboxes that do not use plugin
Runner tasks, and no change for other task operations.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use
(shell, file edits, and read-only database and log queries on a hosted
instance for the diagnosis).

## 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
documentation describes this timeout)
- [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-12-01 11:26:21 -08:00
5a9c06b315 feat(analytics): make replay work content a deployment opt-in (#22820)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Hosts can enable PostHog browser analytics and session replay
through deployment configuration.
> - Replay masks work content, which makes task and artifact flows hard
to understand.
> - Hosts must decide whether their deployment may show this content.
> - This pull request adds an explicit deployment opt-in, with work
content masked by default.
> - Eligible companies can show work content after that opt-in, while
connected-account checks and secret masking still apply.

## Linked Issues or Issue Description

No public issue exists. This change follows the enhancement template.

**What existing behavior does this improve?**

Session replay masks task descriptions, document bodies and artifact
previews. A host cannot choose to show eligible work content
independently of enabling replay.

**Subsystem affected**

Browser session replay, deployment analytics configuration, and the
authenticated session contract.

**Current behavior**

Work content stays masked in every company. Task and artifact titles
already show. PostHog project masking settings cannot override the
options supplied by the board UI.

**Proposed behavior**

Keep work content masked by default. Set
`PAPERCLIP_POSTHOG_REPLAY_WORK_CONTENT_ENABLED=1` in deployment
configuration to allow it for eligible companies. Unset, `0`, and other
values keep it masked. Browser analytics and replay must also be
enabled. A host can keep replay enabled while work content stays masked.

**Reason and benefit**

Hosts control their recording policy without editing Core source. An
eligible company's replay can show the task flow after the host opts in.

**Breaking changes**

None relative to the base branch. Self-hosted analytics remain disabled
by the existing analytics gate. Existing deployments retain work-content
masking unless they explicitly opt in. The session gains an optional
boolean and the tool connection list gains an optional `hiddenCount`
field. Missing fields fail closed.

## What Changed

- Add `PAPERCLIP_POSTHOG_REPLAY_WORK_CONTENT_ENABLED`, default off.
Resolve it in the existing server analytics configuration and send the
effective boolean as `browserAnalytics.replayWorkContentEnabled`. The
shared session schema preserves the field and accepts older servers that
omit it.
- Require both replay and the work-content opt-in before the UI queries
company sources or permits visibility. Removing the opt-in from a
refreshed session masks content even when eligible source answers remain
cached.
- Preserve the original company checks: complete tool connection and
chat endpoint lists, no Google or Slack source, no known aggregator or
router, and the selected company's route. Unknown, failed, invalidated,
or hidden source data keeps content masked. Live source changes reset
the check.
- Mark task descriptions, document bodies, attachment and artifact
previews, and file viewers as work content. Customer content, editors,
comments, chat, run output and connected-account surfaces remain masked.
Secrets remain blocked or redacted. Input and attribute values remain
masked.
- Preserve credential punctuation in task previews by reusing the shared
Markdown plain-text helper. Bound conversion to the first 2,048 source
characters, and always mask source-capped previews to protect incomplete
credentials. Scan complete command-line flag names once before
classifying secrets and reading their values. A 512 KiB hyphen input and
long flag names have regression coverage.
- Mask surfaces that show cut or rewritten work content, where the
redaction cannot work. A cut task preview masks when the text before its
180-character limit holds a credential. The document card preview (first
4,000 characters) masks when the cut changes what the redaction masks
before it. The text preview on an artifact card always masks, because
the server strips hyphens and underscores from it and cuts it at 280
characters. Quoted flag values run past escaped quotes, and flag names
can hold an underscore. An unquoted token that starts with `--` is read
as the next flag, not as a value, so `--auth
--tlsCertificateKeyFilePassword hunter2` masks `hunter2`.
- Refresh the recording once when a company's work content first becomes
visible. Keep the existing autocapture text and attribute masking.
- Add tests for deployment switches, session parsing and exposure,
disabled source requests, older servers, and withdrawal with cached
data. Retain the original masking, company, secret, and source-change
tests.
- Document configuration, rollback, restart and tab-reload steps,
residual recording risks, and the board-only `hiddenCount` API field
with absent-on-older-server semantics. Refresh the shared-source pins
with the maintained generator; runtime and compiler pins stay unchanged.

The original implementation and commits are preserved from @nguyenm7.
The deployment configuration follow-up adds the host opt-in.

When squash-merging, preserve the follow-up author's credit in the
squash commit body:

```text
Co-Authored-By: Devin Foley <devinfoley@users.noreply.github.com>
```

## Verification

Current head `2ce967f1e1`: CI has 43 checks passed and four skipped,
with none failed or pending. The Greptile review on this head is 5/5,
and both findings from its previous review are fixed. No person has
approved the pull request yet. The evidence below was recorded on
earlier heads and is kept as the record of how the change was verified.

Greptile apex review: 5/5 on `45023e6`, with no unresolved review
threads. CI on that head is green: 76 checks passed and four skipped,
with no failed or pending checks. The branch has no merge conflicts with
master.

On the final source change, locally:

- `cd ui && pnpm exec vitest run src/lib/analytics
src/context/LiveUpdatesProvider.test.ts
src/lib/markdown-plain-text.test.ts`: 10 files, 520 tests pass. The
secret-redaction cases are in `replay-secret-redaction.test.tsx`, so
`replay-masking.test.tsx` stays under 1,000 lines (701).
- `cd server && pnpm exec vitest run
src/__tests__/cloud-posthog-config.test.ts
src/__tests__/cloud-posthog-browser.test.ts
src/__tests__/auth-routes.test.ts
src/__tests__/posthog-direct-transport.test.ts`: 4 files, 124 tests
pass.
- `cd packages/shared && pnpm exec vitest run
src/validators/access.test.ts`: 22 tests pass.
- `pnpm exec vitest run -c tests/runner-e2e/vitest.config.ts
source-sdk-public-inputs`: 13 tests pass.
- Shared, server and UI package typechecks pass. Server and UI builds
pass.
- Token gates, module boundaries, the test budget check for changed
suites, and `git diff --check` pass.
- Long-preview regression proof: four rendered tests initially fail on
`9f2039d` because it passes 128,005 characters to conversion. They now
verify a 2,048-character input bound while calling the real helper, a
maximum 180-character summary, and complete replay masking for capped
sources. Inputs include backticks, stars, underscores and brackets. The
earlier short-preview credential tests still pass.
- Review regression proof: three rendered task-preview tests expose
GitLab, GitHub and OpenAI fixture credentials on `7533fbe`; they pass
after preserving token punctuation. An 80,000-hyphen input took about
3.25 seconds on that head and failed the 500 ms bound. The single-pass
flag scan passes the guard with a 512 KiB prefix followed by a real
password flag.
- Regression proof: the added tests first failed on the prior
implementation, including work content visible with a missing or false
opt-in and after withdrawal. They pass with the new gate.
- `pnpm verify`: exit 2, broader verification required because the
analytics document is a global CI input. Required CI supplies
repository-wide coverage. An earlier exit 1 identified stale
shared-source pins; the maintained generator refreshed them and the 13
pin tests pass.
- Direct UI `tsc --noEmit` initially lacked generated Storybook catalogs
in the fresh checkout. The maintained UI typecheck generates those files
and passes. A preliminary Vitest `--project ui` invocation matched no
named project; the commands above use the package configuration.
- Secret scan reviewed the commit diff. Gitleaks reports two generic-key
matches in the generated source-pin registry; both equal the
corresponding Git blob hashes. The remaining commit content scans clean.
No run artifacts or private deployment data are committed.

CI follow-up on `45023e6`: [server shard
10/20](https://github.com/paperclipai/paperclip/actions/runs/45560174673/job/139021948661)
timed out twice at the existing 15-second limit in
`issue-document-batch.integration.test.ts`, test "rejects many large
documents using a size-only query before loading any bodies". The test
prepares 200 half-MiB documents and later rewrites them. The same test
and server code are unchanged from `9f2039d`, where [the same shard
passed](https://github.com/paperclipai/paperclip/actions/runs/45558505382/job/139016469065)
and this test took 8.39 seconds. The intervening commit changes UI and
documentation only.

The exact failing case passes locally on the current head with `cd
server && pnpm exec vitest run
src/services/native-runtime/issue-document-batch.integration.test.ts -t
'rejects many large documents using a size-only query before loading any
bodies'` (one passed, 15 skipped). This shows local recovery; it does
not establish the cause of the CI timeout. A targeted shard rerun was
requested, but GitHub refused because the workflow is still running. No
test limits or product code have been changed to hide the failure. This
initial failure is retained here as evidence; the successful
second-attempt outcome is recorded below.

CI follow-up, second shard: [server shard
13/20](https://github.com/paperclipai/paperclip/actions/runs/45560174673/job/139021948654)
failed `ai-connections.test.ts`, test "requires sign-in after the
receiver process dies with an exchanged but unsaved token". The first
attempt failed its wait for one token exchange and an advisory-lock
waiter within 25 seconds. The automatic retry failed earlier because the
first attempt had already inserted the fixed membership fixture. The
suite, receiver helper and AI connection service are unchanged by this
work. The [original PR head passed this
shard](https://github.com/paperclipai/paperclip/actions/runs/45544519067/job/138970880217),
with the same test taking 21.06 seconds.

The exact case passes locally on `45023e6` with `cd server && pnpm exec
vitest run src/__tests__/ai-connections.test.ts -t 'requires sign-in
after the receiver process dies with an exchanged but unsaved token'`
(one passed, 164 skipped). The cause of the missed CI wait remains
unconfirmed. This local pass does not clear the failed CI result.
Targeted reruns were initially blocked by GitHub while the workflow was
running. See the successful second-attempt outcome below.

CI recovery: [workflow attempt
2](https://github.com/paperclipai/paperclip/actions/runs/45560174673/attempts/2)
completed successfully on unchanged head `45023e6`. Both previously
failed shards now pass. No source edits, timeout increases, or test
removals were needed. The original timeout and missed-wait causes remain
unconfirmed; the earlier failures and comparison evidence above are
preserved. Final acceptance uses the green current-head CI result
together with the local checks and 5/5 review.

Not run locally: repository-wide tests/builds or a live PostHog
recording. The tests exercise the masking callback and UI state, not the
externally loaded recorder.

After deployment, compare a masked replay with the work-content flag
unset against an opted-in eligible company. Then verify that
Google/Slack or a hidden source keeps the same surfaces masked. Restart
the server and reload open tabs after changing deployment environment
values.

## Risks

- The opt-in belongs to the host, not to the people who use the
deployment. Nothing in this pull request asks or tells a user. A host
that sets the flag must tell its users first. The plan for the hosted
service is in #23338.
- Enabling the new flag allows eligible work content to leave the
instance in replay data. Leave it unset or set it to `0` to keep work
content masked. No deployment or fleet policy is changed by this PR.
- The flag does not bypass company eligibility checks or secret masking.
Changing it affects future recording after the configuration reaches the
browser; it does not remove previously recorded content.
- Connection detection is a best effort. A custom MCP server with an
unrelated name and URL, or credentials used directly by an agent, can
carry Google or Slack data without appearing as a known source.
- Secret redaction is a best effort. Unknown or unlabeled secrets,
non-English labels, values on a later line or under a table header, and
values outside bounded line context can be missed. Some ordinary values
are over-masked.
- Source changes can race with recording until the live update arrives.
A missed update can extend that window to the five-minute refresh.
Connection count and list queries can disagree briefly and then mask
conservatively.
- Hidden drafts and aggregators can keep harmless content masked. Text
rendered during a source recheck stays masked until it renders again.
The first visible state adds a full recording snapshot.
- Task previews now inspect at most 2,048 source characters before
conversion. Very long markup can produce an incomplete summary.
Source-capped previews stay fully masked; opening the full task keeps
the normal work-content policy.
- Artifact card text previews stay masked in every company. Document
card previews and cut task previews mask when a credential sits at or
before the cut, so some replays show stars there while the full document
shows.
- Task titles, names and other previously visible surfaces remain
visible and can contain copied customer text. New work-content surfaces
must preserve company scoping.

## Model Used

- Original implementation: Anthropic Claude Opus 5.5 (`claude-opus-5-5`)
and Claude Fable 5.2 (`claude-fable-5-2`) through Claude Code, with
shell, edits, tests and the original read-only exploration subagent.
- Deployment configuration follow-up: OpenAI `gpt-6.1-sol` through the
Codex, xhigh reasoning, shell, file edits and test tools. Context window
size is not exposed by the runtime. No additional subagents.

## 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: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Devin Foley <devin@paperclip.ing>
Co-authored-by: Paperclip <noreply@paperclip.ing>
Co-authored-by: Dotta <bippadotta@protonmail.com>
2026-12-01 18:53:11 +00:00
paperclipbugbotandClaude Opus 5.5 0abb7834f7 fix(opencode): attribute the memory that fills the sandbox before an OOM kill (#23391)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The native Runner starts `opencode serve` for each OpenCode agent
turn in a cloud sandbox with an 8 GiB cgroup memory limit.
> - #23372 added kernel evidence to a signal death of `opencode serve`.
The first event with that evidence shows `memoryKill: "observed"` and
`memoryPeakBytes` at the 8 GiB limit, so the kernel OOM killer stopped
OpenCode.
> - These deaths happen on light turns: one or two small tool calls,
then model generation, about 30 to 60 seconds after OpenCode starts. No
large Bash command runs.
> - The record does not say which memory filled the limit: OpenCode
itself, another process, or shared memory (tmpfs). A correct fix needs
that fact.
> - This pull request samples that memory while OpenCode runs and
reports the last sample with the death.
> - The benefit is that the next OOM kill names the memory consumer, so
the fix can target it.

## Linked Issues or Issue Description

Refs #23372 (adds `memoryKill`, `memoryLimitBytes` and
`memoryPeakBytes`). Refs #17398 (the Legacy OpenCode adapter makes tool
commands the first OOM victims; that does not help when no large tool
command runs).

**What happened?**
On a cloud sandbox, native OpenCode turns fail with
`opencode_server_exited`. With #23372 deployed, the failure record shows
`signal: SIGKILL`, `memoryKill: observed`, `memoryLimitBytes:
8589934592` and `memoryPeakBytes: 8589942784`. The turn made only two
light tool calls before the kill. The record does not show which process
or memory type used the 8 GiB.

**Expected behavior**
When the kernel stops `opencode serve`, the failure record shows how
much memory OpenCode used, how the limited cgroup memory divides into
anonymous, shared and file memory, and the largest other process.

**Steps to reproduce**
1. Run a native OpenCode turn in a Linux sandbox with a cgroup v2 memory
limit.
2. Make the sandbox use all of its memory limit so that the kernel OOM
killer stops `opencode serve`.
3. Read `resultJson.nativeTurnFailure`. Before this change, it has no
memory attribution.

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

## What Changed

- `memory-kill-evidence.ts`: when OpenCode runs under a numeric cgroup
memory limit, the probe samples every second (an unref timer, Linux
only). Each sample reads:
  - OpenCode `VmRSS` and `VmHWM` from `/proc/<pid>/status`.
- `anon`, `shmem` and `file` from `memory.stat` of the cgroup that holds
the limit.
- The largest other process by `VmRSS`, among only the processes charged
to the limited cgroup: the `cgroup.procs` of that cgroup and its
descendants. Processes in other cgroups are not compared. Only the
kernel task name is kept. A name outside `[A-Za-z0-9._+:-]{1,15}`
becomes `other`.
- One sample reads at most 64 `cgroup.procs` files and 256 process
`status` files.
- A signal death reports the last sample: `opencodeRssBytes`,
`opencodePeakRssBytes`, `cgroupAnonBytes`, `cgroupShmemBytes`,
`cgroupFileBytes`, `largestProcessName`, `largestProcessRssBytes` and
`memorySampleAgeMs`.
- The probe stops its timer when OpenCode exits. A sample after OpenCode
is gone, or while it is a zombie whose status has no `VmRSS`, keeps the
previous sample. Without a memory limit, the probe does not sample.
- `native-provider-failure.ts`: the closed-vocabulary projection keeps
the new fields. Counts must be safe integers that are zero or more. The
name must match the kernel task-name pattern. Other values are dropped.
- This is a diagnostic. It does not change how a turn fails or recovers.

## Verification

- `cd packages/paperclip-runner && npx vitest run
src/drivers/opencode/memory-kill-evidence.test.ts`: 7/7 pass. New tests
build a fake `/proc` and cgroup tree. They check:
  - the reported sample, the `other` name and the sample age;
  - that a larger process in another cgroup is not reported;
- that a zombie status without `VmRSS`, and a removed status, both keep
the previous sample;
- that one sample with 400 processes in the cgroup stops at the
256-process limit and takes less than 100 ms;
  - that no sampling happens without a memory limit.
- Scan cost on a real Daytona sandbox (8 GiB cgroup v2 limit, 21
processes): one sample takes 0.75 ms (mean of 200 samples against the
real `/proc` and `/sys/fs/cgroup`). At the 1 s interval, this is less
than 0.1% of the main thread. The fake-tree test at the 256-process
limit sets an upper bound of 100 ms for one sample.
- `cd packages/paperclip-runner && npx vitest run
src/drivers/opencode/opencode-server-driver.test.ts -t "OpenCode stops
mid-turn|classifies a lost event stream"`: 2/2 pass (the SIGKILL
integration test from #23372 is unchanged).
- `cd server && npx vitest run
src/services/native-runtime/native-provider-failure.test.ts`: 64/64
pass. A new test checks that the fields pass through and that bad values
are dropped.
- A scoped `tsc --noEmit` of
`server/src/services/native-runtime/native-provider-failure.ts` shows no
errors. Without the typed helper, it shows the error that CI reported on
the first commit.
- `tsc -p packages/paperclip-runner/tsconfig.json --noEmit` shows no
errors in the changed files.
- These local runs used an older parent commit with the same versions of
these files. The change applies to current `master` without conflicts.
CI runs the full suites.

## Risks

- Low risk. Sampling runs only on Linux under a numeric cgroup memory
limit. Each sample reads the OpenCode `status` file, the limited cgroup
`memory.stat`, at most 64 `cgroup.procs` files and at most 256 process
`status` files. All read errors give no data. They do not throw. The
reads are synchronous. The measured cost is 0.75 ms for one sample in a
real sandbox.
- The timer is unref, so it does not keep the Runner alive. It stops
when OpenCode exits.
- The largest-process name can only be a short kernel task name. No
command line or path is read.

## Model Used

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

## Checklist

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

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 18:28:43 +00:00
Nicky LeachandPaperclip 07af22c57f feat(plugins): support agentless harness sign-in (#23392)
## Thinking Path

> - Paperclip manages agents and the AI accounts they use.
> - A company can connect an account before creating its first agent.
> - Some plugin drivers can run sign-in in a dedicated sandbox.
> - Core currently selects a saved agent for every plugin login.
> - This change lets each driver declare that it can sign in without an
agent.

## Linked Issues or Issue Description

**Subsystem affected**

Environment drivers, managed AI connections, and the agent setup UI.

**Current behavior**

A company with zero agents cannot start a provider login on a plugin
environment, even when that driver can provision a temporary
environment.

**Proposed behavior**

A driver can declare `supportsAgentlessLogin`. Core uses this capability
when it selects a login target and acquires the lease. Drivers that omit
it retain the existing agent selection.

**Reason and benefit**

Operators can finish connecting the account before they configure its
first agent.

**Additional context**

The driver capability follows the per-driver adapter declaration in
#22827. The onboarding flow keeps the agent readiness check from #23383.

## What Changed

- Added the optional capability to the manifest, capabilities response,
and login UI.
- Kept company and driver validation at sign-in and lease acquisition.
- Applied the plugin device-login deadline to sessions with no agent.
Ordinary task provisioning keeps its existing contract.

## Verification

- 122 tests passed across shared capabilities, environment target
resolution, lease construction, device-login HTTP routes, and session
lifecycle.
- The server typecheck passed.
- The SDK input registry matches the source revision. `pnpm verify`
requests broader CI coverage for that registry.
- After merging the current base, 82 focused tests passed, including the
onboarding tests. The UI typecheck passed. All required GitHub checks
passed.

## Risks

Drivers must advertise this capability only when they can run and clean
up a login without an agent. Existing manifests retain their previous
behavior. No database migration is required.

> 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 Codex, GPT-6, with local code inspection and test execution.

## Checklist

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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-12-01 10:22:32 -08:00
DottaandPaperclip ce2e6ccc00 feat(ui): surface channel, key-values, lease, and schema elements on tasks (#23382)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Paperclip tasks and comments now store channel, key-value, claim
lease, profile attribution, and structured schema fields on existing
issue and comment tables (`channelId`, `kvLabels`, `schemaBlocks`,
`resultSchemaRef`, `createdByProfile`, `actorProfile`, and claim lease
fields).
> - Existing board task views (`IssueProperties`, `MarkdownBody`,
`CommentThread`, `IssueChatThread`, and `IssueDetail`) do not yet
display these fields, and canonical `/api/issues/:id` routes do not
resolve `channelPath` or strip `claimTokenHash` at serialization time.
> - Users and reviewers cannot see channel provenance, key-values,
active or expired claim leases, `--as <profile>` attribution, or
structured `schema=<name>@<version>` blocks when they open a task in the
UI.
> - This pull request synchronizes the shared `Issue` and `IssueComment`
contracts, resolves `channelPath` only when channel access and actor
scopes allow it, strips `claimTokenHash` from issue responses, renders
channel, key-values, lease, result schema, and structured schema cards
across existing task views (only when set), and adds
production-component Storybooks.
> - The benefit is that existing task surfaces show channel, lease,
key-value, profile, and schema state cleanly in place without cluttering
standard tasks or adding a separate Channels navigation item, while
preserving secret isolation on claim tokens.

## Linked Issues or Issue Description

Refs #23329
Refs #23330

**What existing behavior does this improve?**
Existing task detail, properties, Markdown body, comment thread, chat
thread, and `/api/issues` HTTP serialization for tasks that carry
channel, claim lease, key-value, profile attribution, or structured
schema data.

**Subsystem affected**
Cross-cutting (`packages/shared`, `server/`, `ui/`, `ui/storybook/`, and
`docs/api/`)

**Current behavior**
Canonical `/api/issues` routes return raw issue columns without a
resolved `channelPath` and include `claimTokenHash: null` on the
response shape. In `ui/`, `IssueProperties` omits channel provenance,
`Key-values` editing, claim lease status, `resultSchemaRef`
verification, and `--as <profile>` creator attribution. `MarkdownBody`
renders ```` ```json schema=<name>@<version> ```` blocks only as plain
code blocks, and comment threads show `local-board` or generic user
labels instead of `actorProfile` and omit comment-level key-values.

**Proposed behavior**
`Issue` and `IssueComment` expose safe coordination and schema fields in
`@paperclipai/shared`. Server issue routes strip `claimTokenHash` from
serialized issue objects and resolve `channelPath` in batch via
`findInaccessibleChannelIds` only when actor scopes and channel
membership succeed (with zero extra SQL queries when `channelId` is
null). `IssueProperties` mounts cohesive task property rows
(`structured-task-rows.tsx`) strictly when set: `#<channelPath>` badge
on `Channel`, inline `Key-values` add/edit/remove with CAS preconditions
(`PATCH /api/issues/:id/kv-labels`), active vs expired `Lease` status
with inline status dot and live countdown, `Result schema` matching
status, and creator `--as <profile>` attribution. `MarkdownBody` and
task discussion/chat threads render token-styled `SchemaBlockCard` views
(`finding@1`, `test-report@1`, `git-commit@1`, `pull-request@1`, and
custom `<name>@<version>` schemas) with a `Structured` / `JSON` toggle,
deduplicated standalone `schemaBlocks`, `--as <actorProfile>`
attribution, and comment key-value pills. Four production-component
Storybooks document these states under
`tasks-channels-leases-and-schemas`.

**Reason and benefit**
Agents and CLI workflows coordinate through existing Paperclip tasks and
comments. Surfacing channel provenance, claim leases, key-values,
profile attribution, and typed schema blocks directly on existing task
views (and hiding those rows completely when unset) lets people inspect
and edit structured task state in place without introducing new
top-level navigation, while guaranteeing that `claimTokenHash` never
leaves the server.

**Breaking changes**
None for external callers. `claimTokenHash` is omitted from serialized
`/api/issues` JSON responses as a security invariant, and `channelPath`
(`string | null`) is added on canonical issue read and update responses.

## What Changed

- `packages/shared/src/types/issue.ts` and
`tests/runner-e2e/source-sdk-public-inputs.json`: expose safe fields on
`Issue` (`channelId`, `channelPath`, `createdByProfile`, `kvLabels`,
`schemaBlocks`, `resultSchemaRef`, `claimEpoch`, `claimHolderAgentId`,
`claimHolderUserId`, `claimHolderProfile`, `claimLeasedAt`,
`claimLeaseExpiresAt`, `claimAttemptCount`) and `IssueComment`
(`actorProfile`, `kvLabels`, `schemaBlocks`), never `claimTokenHash`,
and synchronize the SDK public input registry pin.
- `server/src/services/issues.ts`, `server/src/routes/issues.ts`, and
`docs/api/issues.md`: omit `claim_token_hash` from SQL issue selections
and `withIssueLabels`, strip `claimTokenHash` on HTTP serialization
across issue routes, clear `kvLabels` and `schemaBlocks` on tombstoned
comments, resolve `channelPath` in batch via `resolveHeadlessActor` and
`findInaccessibleChannelIds` (zero extra SQL queries when `channelId` is
`null`), and document the API response contract.
- `server/src/__tests__/fixtures/issue-detail-response.json`,
`server/src/__tests__/issue-activity-events-routes.test.ts`, and
`server/src/__tests__/headless-channels-schemas-batch.test.ts`: update
issue detail and update response snapshots (`channelPath: null`, no
`claimTokenHash`) and add route contract coverage for `channelPath`
visibility, scope enforcement, comment fields, and `claimTokenHash`
omission.
- `ui/src/api/issues.ts` and `ui/src/api/issues.test.ts`: add
`issuesApi.updateKvLabels` targeting `PATCH /api/issues/:id/kv-labels`
with CAS precondition normalization (`set`, `unset`, `if`) and unit test
coverage.
- `ui/src/components/issue-properties/structured-task-rows.tsx` and
`IssueProperties.tsx`: add `IssueChannelRow`, `IssueKvLabelsRow`
(`Key-values` with inline edit, remove, `+ Add`, CAS preconditions,
touch-safe 16px inputs, and complete omission when empty),
`IssueClaimLeaseRow` (inline status dot, live countdown, and omission
when unset or released), `IssueResultSchemaRow` (unwrapping
`InfiniteData` and identifier-keyed comment query caches, plus
distinguishing `"unverified"` truncated scans from `"missing"`), and
`IssueProfileAttributionRow`.
- `ui/src/components/SchemaBlockCard.tsx`,
`ui/src/lib/schema-block-utils.ts`, and
`ui/src/components/MarkdownBody.tsx`: parse ```` ```json
schema=<name>@<version> ```` fences (plus `{ schema, data }` JSON
envelopes) via a static remark plugin and a bounded linear $O(N)$
single-pass CommonMark fence scanner (no multi-line backtracking
regexes); render semantic-token cards for `finding@1`, `test-report@1`,
`git-commit@1`, `pull-request@1`, and custom `<name>@<version>` blocks
with `Structured` / `JSON` toggle, `https://`-only link safety,
malformed-JSON code-block fallback, and iterative stack-safe
`schemaBlocks` deduplication.
- `ui/src/components/CommentStructuredMeta.tsx`, `CommentThread.tsx`,
`IssueChatThread.tsx`, `TaskChatBubble.tsx`,
`TaskChatDescriptionBubble.tsx`, `IssueDetail.tsx`, and chat adapters:
render `--as <actorProfile>` attribution, comment-level key-value chips,
and unfenced `schemaBlocks` across classic and chat task threads.
- `ui/storybook/stories/tasks/channels-leases-and-schemas.stories.tsx`:
add `ChannelTaskPropertiesActiveLease`, `ExpiredLeaseProperties`,
`BuiltInAndCustomSchemaBlocks`, and `ChannelTaskThreadEndToEnd` stories
registered under `tasks-channels-leases-and-schemas`.
- `ui/src/components/issue-properties/structured-task-rows.test.tsx` and
`ui/src/components/SchemaBlockCard.test.tsx`: add unit tests covering
unset-row omission on standard tasks, single-badge channel provenance,
CAS key-value mutations and `409` conflict rollback, inline lease status
dots and countdown expiry, `InfiniteData` comment unwrapping, structured
schema cards, malformed JSON fallback, linear $O(N)$ scanning on 5,000
unterminated JSON fences, newline-clamped markdown bounds, and deep
deduplication.

## Verification

- `pnpm --filter @paperclipai/shared build` — passed.
- `cd server && node scripts/typecheck-layers.mjs` — passed (0 errors
across all layers and test trees).
- `cd server && npx vitest run
src/__tests__/service-read-disconnect-retry.test.ts
src/__tests__/issue-activity-events-routes.test.ts
src/__tests__/issue-detail-statements.test.ts
src/__tests__/headless-channels-schemas-batch.test.ts` — passed (54/54
tests).
- `pnpm --filter @paperclipai/ui typecheck` — passed (0 errors).
- `cd ui && npx vitest run
src/components/issue-properties/structured-task-rows.test.tsx
src/components/SchemaBlockCard.test.tsx src/api/issues.test.ts
src/lib/issue-chat-messages.test.ts
src/components/task-chat/task-chat-adapter.test.ts` — passed (115/115
tests).
- `node scripts/check-token-gates.mjs`, `node
scripts/check-test-budget.mjs`, `node
scripts/check-module-boundaries.mjs`, and `node
scripts/check-query-error-rendering.mjs` — all passed.
- `node scripts/storybook-catalog.mjs && node
scripts/storybook-catalog.mjs --check` and `node --test
scripts/check-maps.test.mjs scripts/storybook-catalog.test.mjs
scripts/storybook-feature-index.test.mjs` — passed (30/30 tests).
- `pnpm --filter @paperclipai/ui build-storybook` — passed and verified
built story IDs
(`tasks-channels-leases-and-schemas--channel-task-properties-active-lease`,
`tasks-channels-leases-and-schemas--expired-lease-properties`,
`tasks-channels-leases-and-schemas--built-in-and-custom-schema-blocks`,
`tasks-channels-leases-and-schemas--channel-task-thread-end-to-end`).

## Risks

- Low risk. Standard board tasks with unset `Channel`, `Key-values`,
`Lease`, and `Result schema` omit all four property rows completely,
preserving existing `IssueProperties` layout and SQL query count (`0`
extra queries when `channelId` is `null`).
- Fenced code blocks without `schema=<name>@<version>` metadata (or with
invalid JSON) fall back directly to the existing `CodeBlock` renderer.

## Model Used

- Google Gemini (`gemini-3.1-pro` / Antigravity agentic coding runtime
with extended thinking, code search, file editing, and terminal
verification tools).

## Checklist

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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-12-01 17:57:33 +00:00
Nicky LeachandClaude Opus 5.5 51541be36f fix(onboarding): start an agent-targeted sign-in only on a settled, prepared draft (#23383)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Onboarding signs the first agent in to Claude or Codex through a
plugin-managed execution environment that is prepared for the agent
(#23312)
> - Each change to the setup draft, such as switching between Claude and
OpenAI, makes Core prepare the environment again before it accepts a
sign-in
> - The wizard remembered that the environment had been prepared once,
so it started the new sign-in during that preparation
> - Core refused it with `login_agent_unavailable`, and the sign-in card
showed only "Sign-in didn't finish"
> - This pull request starts a sign-in only when the draft has settled
on the current choice and is prepared, and shows Core's error on the
card
> - The benefit is that switching the sign-in source works, without an
added wait

## Linked Issues or Issue Description

Refs #23312 and #23315.

**What happened?**

In onboarding with a plugin-managed execution environment as the
default, a user picked Claude, then switched to OpenAI. Every sign-in
start after the switch returned `400 login_agent_unavailable`: Core
refused the agent as the sign-in target. The card showed "Sign-in didn't
finish. Try signing in again."

**What did you expect to happen?**

The OpenAI sign-in starts as soon as the environment is prepared for the
new choice.

**Steps to reproduce**

1. Make a plugin-managed execution environment that prepares an
environment per agent the instance default.
2. Start onboarding, name the agent, and choose Claude with a
subscription.
3. When the Claude sign-in shows, choose OpenAI.
4. See the sign-in fail with the message above.

## What Changed

- The sign-in readiness hook takes `settled` and `holdKey`. A sign-in
starts only when the agent has settled on the current choice and the
environment is prepared for it. Readiness is held per agent, environment
and sign-in source, so a source switch waits for the real preparation,
and a sign-in already on screen stays on screen.
- Onboarding treats the setup draft as settled when its saved harness
(and model, when one is set) matches the selection. Each draft save puts
the saved agent in the query cache at once, and readiness polls every
500 ms instead of every second.
- The new-agent flow treats its draft as settled when no environment
save is in flight, and polls a preparing draft every 500 ms.
- Both sign-in panels show Core's start error for any sign-in that
targets an agent, not only for one that Core selects automatically.

## Verification

- `pnpm typecheck` in `ui/`: no errors.
- The sign-in readiness helper and hook suites, the
`AgentProviderConnection` suites and the `AgentConfigForm` render suite
in `ui/`: 23 tests pass. A new hook test covers a switch from Claude to
OpenAI and back while the environment is prepared again.
- `PAPERCLIP_PLAYWRIGHT_CHANNEL=chrome npx playwright test --config
tests/e2e/playwright.config.ts tests/e2e/onboarding-early-setup.spec.ts
tests/e2e/onboarding.spec.ts -g "naming step creates|create-company
path"`: 2 tests pass.
- I reproduced the failure on a staging instance from the network log. I
did not repeat the sign-in on a staging instance with this change.

## Risks

- A change to the draft after a sign-in started can still make Core
refuse the login lease when it acquires it. The card then shows Core's
error and the usual retry.
- Readiness polling is now twice as frequent while an environment is
prepared. It stops when the environment is ready.
- No migration and no API change.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), with extended thinking and tool
use (code search, shell, tests, browser network inspection) 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
- [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>
canary/v2026.1201.0-canary.876500
2026-12-01 17:45:32 +00:00
Dotta 37da976b8c fix(monitors): preserve authorized task monitors on tasks with unresolved blockers (#23390)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Agents can schedule timed task monitors with `set_task_monitor` and
end their turn with `yielded` and `continuation.kind: "monitor"` to
check external work later
> - Tasks can also have unresolved `blockedBy` dependencies while the
agent still monitors independent active work such as CI or external
checks
> - Previously, `arbitrateNativeStatus` overrode every monitor wait on a
task with unresolved blockers into `blocked`
(`durable_dependency_blocker_bound`), and the heartbeat wake admission
and queued-run claim paths rejected or cancelled `issue_monitor_due`
wakes while blockers remained unresolved
> - This pull request preserves authorized task monitor waits in
`arbitrateNativeStatus` and admits server-verified `issue_monitor_due`
wakes through wake admission, queued-run claim, and run-dispatch retry
gates even when unresolved blockers exist
> - The benefit is that authorized task monitors stay scheduled and fire
on time without relaxing the dependency gate on `done`, `blocked`,
unauthorized monitor claims, blocked tasks, or forged wakeups

## Linked Issues or Issue Description

**What happened?**
When an agent scheduled a task monitor with `set_task_monitor` on an
`in_progress` task that also had unresolved `blockedBy` dependencies and
finished with `reportedDisposition: "yielded"` and `continuation.kind:
"monitor"`, `arbitrateNativeStatus` overrode the status to `blocked`
(`durable_dependency_blocker_bound`) and stranded the monitor. Even if
the task remained `in_progress`, `enqueueWakeup` and `claimQueuedRun`
skipped or cancelled the due `issue_monitor_due` wake because
`isDependencyReady` was `false`.

**Expected behavior**
An explicit, authorized task monitor (`monitorWaitAuthorized: true`, or
already dispatched/superseded/preserved) stays in
`scheduled_monitor_waiting` (releasing checkout) and wakes the assignee
with `issue_monitor_due` when due, while `done`, `blocked`,
`unfinishedResponseWait`, unauthorized monitor claims, blocked tasks,
and forged `issue_monitor_due` wakes remain gated by unresolved
`blockedBy` dependencies.

**Steps to reproduce**
1. Create an `in_progress` task assigned to an agent and add an
unresolved `blockedBy` dependency to it.
2. Schedule a task monitor on the task with `set_task_monitor` and
finish the run with `reportedDisposition: "yielded"` and
`continuation.kind: "monitor"`.
3. Observe `arbitrateNativeStatus` return `blocked`
(`durable_dependency_blocker_bound`) instead of
`scheduled_monitor_waiting`, and observe `tickIssueMonitors` skip the
due monitor with `issue_dependencies_blocked`.

**Paperclip version or commit**
`8403e1c4ce` (`master`)

**Deployment mode**
Local dev (pnpm dev)

## What Changed

- Updated `arbitrateNativeStatus` in
`server/src/services/native-runtime/status-arbiter.ts` to exempt
authorized `yielded` monitor continuations (`monitorWaitAuthorized`,
`monitorWaitDispatched`, `monitorWaitSuperseded`,
`monitorWaitPreserved`) from the `durable_dependency_blocker_bound`
override while keeping `done`, `blocked`, `unfinishedResponseWait`, and
unauthorized monitor claims gated.
- Added `verifyIssueMonitorWake` in
`server/src/services/issue-monitors.ts` to verify `issue_monitor_due`
wakes against durable server state (claimed non-quota monitor on an
`in_progress`/`in_review` task at enqueue time; admitted non-skipped
`agentWakeupRequests` row at claim and retry-gate time).
- Extended `allowsDependencyBlockedWake` in
`server/src/modules/run-dispatch/domain/wake-context.ts` and wired
`verifyIssueMonitorWake` into `enqueueWakeup` and `claimQueuedRun`
(`server/src/services/heartbeat/queue.ts`) plus `loadGateFacts` and
`loadStalenessFacts`
(`server/src/modules/run-dispatch/adapters/postgres.ts`).
- Added unit and integration regression tests in
`server/src/services/native-runtime/status-arbiter.test.ts` and
`server/src/__tests__/issue-monitor-scheduler.test.ts` covering
authorized monitors with blockers, unauthorized monitor claims, `done`
with blockers, due monitor execution with blockers, and forged
`issue_monitor_due` wakeups.

## Verification

- `pnpm --filter @paperclipai/server typecheck` (passed)
- `pnpm --filter @paperclipai/server exec vitest run
src/services/native-runtime/status-arbiter.test.ts
src/__tests__/issue-monitor-scheduler.test.ts
src/services/native-runtime/task-monitor.integration.test.ts` (84
passed)
- `pnpm --filter @paperclipai/server exec vitest run
src/modules/run-dispatch/domain/wake-context.test.ts
src/services/heartbeat/scheduling.test.ts` (81 passed)
- Verified red-green behavior on the new regression tests before and
after applying the fix.

## Risks

- Low risk. The dependency-blocker bypass is scoped strictly to
server-verified non-quota task monitors on `in_progress` or `in_review`
tasks (`scheduledIssueMonitorWait` + claimed `monitorWakeRequestedAt` at
enqueue, and admitted `agentWakeupRequests` row at claim/retry). Blocked
tasks, provider quota monitors, unauthorized monitor claims, forged
`issue_monitor_due` wakeups, and `done`/`blocked` transitions retain
full dependency-blocker enforcement.

## Model Used

- Google Gemini (Antigravity agentic coding assistant, tool use and
extended reasoning)

## Checklist

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

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Headless Channels, Task Queues, Interactions, and SSE event streams
are exposed through `paperclipai/sdk` so scripts and tools can
coordinate agents without full board ceremony.
> - Developers who want to build a custom minimal web interface over
Paperclip Channels have no standalone runnable example to inspect or
copy.
> - Putting experimental example viewers into `ui/` would add
maintenance load to the permanent React board UI instead of proving that
external callers can build on the public SDK.
> - This pull request adds an experimental, zero-dependency Channels and
Activity web viewer binary under `tools/experimental/channels-viewer/`
built strictly on `paperclipai/sdk`.
> - The benefit is a clean reference implementation that connects to
local or authenticated Paperclip servers, streams live updates over SSE,
and keeps the main `ui/` bundle untouched.

## Linked Issues or Issue Description

Refs #23329
Refs #23330

**Problem or motivation**
Developers can post to channels, claim tasks, and stream events from the
CLI or `paperclipai/sdk`, but there is no minimal runnable example
showing how to build a custom web UI over those headless APIs with
standard Paperclip authentication.

**Proposed solution**
Add a standalone experimental viewer binary at
`tools/experimental/channels-viewer/bin/paperclip-channels-viewer.mjs`
backed by `node:http`, `paperclipai/sdk`, and zero-bundler ES modules.
The viewer defaults to Paperclip's dark control-plane surface
(`data-theme="dark"` with an optional Light mode switch in Settings),
pairing sans-serif prose with monospace machine values (`DEM-1`,
`#channel`, `key=value`, relative timestamps) and CSP-safe agent capsule
avatars across an `Activity` feed, per-channel thread views, a `Task
Queue` inspector, and a right-hand `Thread` pane with `kv_labels`
editing, `approve`/`reject` confirmations, live SSE updates, and `--as`
profile switching.

**Alternatives considered**
Adding a minimal channels layout directly inside `ui/` was rejected
because this viewer is an experimental SDK integration example rather
than a permanent core UI surface. Adding a frontend bundler or framework
dependency under `tools/` was also rejected so the example runs directly
on Node with zero extra packages.

**Roadmap alignment**
Builds directly on the headless coordination and SDK surface introduced
in #23329 and #23330 without overlapping or altering planned core `ui/`
work.

## What Changed

- Added
`tools/experimental/channels-viewer/bin/paperclip-channels-viewer.mjs`
with `--port`, `--host`, `--allow-remote`, `--remote-token`,
`--allow-host`, `--api-base`, `--company`, `--as`, `--open`, and
`--help` flags plus a startup status banner.
- Added `tools/experimental/channels-viewer/src/server.mjs`,
`src/viewer-data.mjs`, `src/auth.mjs`, `src/security.mjs`, and
`src/format.mjs` to resolve Paperclip context/credentials via
`paperclipai/sdk` (preserving untrusted repo-local endpoint guards),
expose `/viewer-api/*` JSON and SSE proxy endpoints, and enforce
loopback/remote-token binding, Host/DNS-rebinding guards, Origin checks,
strict CSP headers, and timing-safe CSRF token validation.
- Added zero-dependency ES module frontend files
(`src/public/index.html`, `styles.css`, `overlays.css`, `app.js`,
`render.js`, `dom-helpers.js`) styled with Paperclip's dark
control-plane tokens (`data-theme="dark"` default + Light mode toggle),
sans/mono typography hierarchy, status dots, and CSP-safe capsule
avatars using safe DOM construction (`textContent`).
- Added `tools/experimental/channels-viewer/README.md` and a brief
reference section in `doc/HEADLESS-TUTORIALS.md`.
- Excluded `tools/experimental` in `.dockerignore` so production Docker
build contexts remain slim.
- Added
`tools/experimental/channels-viewer/test/channels-viewer.test.mjs`
(`node:test`) and
`server/src/__tests__/experimental-channels-viewer.test.ts` (Vitest
full-stack E2E with Express, embedded PostgreSQL, and live SSE).

## Verification

- Ran `node --test
tools/experimental/channels-viewer/test/channels-viewer.test.mjs` (4/4
tests passed).
- Ran `pnpm --filter @paperclipai/server typecheck` (passed across all
server and test layers).
- Ran `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/experimental-channels-viewer.test.ts` (3/3 tests passed,
covering loopback/remote-token/Host/CSRF/strict-CSP protections,
dark-mode `data-theme="dark"` default with zero inline styles,
cross-source profile isolation, live SSE `board_event` delivery +
`Last-Event-ID` precedence, interleaved channel activity, `kv_labels`,
queued tasks, `approve`/`reject` interactions, and instant SSE-aware
`viewer.close()`).
- Ran `node scripts/check-module-boundaries.mjs`, `node
scripts/check-test-budget.mjs --base origin/master`, `node
scripts/check-docker-deps-stage.mjs`, and `node
tests/runner-e2e/source-sdk-public-inputs.mjs $(git rev-parse HEAD)
--check` (all passed).

## Risks

- Low risk to core Paperclip runtime and builds: no files under `ui/`,
`server/src/routes/`, `packages/db/`, or `packages/shared/` were
modified, and `tools/experimental` is excluded from Docker build
contexts via `.dockerignore`.
- Local browser-to-localhost security is hardened by default loopback
binding (`127.0.0.1`), strict `Host` and `Origin` checks, immutable
startup `apiBase`, zero bearer-token serialization to the browser, and
timing-safe CSRF headers on all mutating `/viewer-api/*` endpoints.

## Model Used

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

## 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-12-01 17:12:11 +00:00
Nicky LeachandClaude Opus 5.5 de24b28b82 feat(runner): keep harness session state in an optional harness state directory (#22841)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The Runner starts each agent's harness (ACPX agents and OpenCode)
and keeps a runtime tree for each session
> - All of that tree is in one runtime directory: session records,
conversation history, caches, configuration, temporary homes and the
turn journal
> - Some hosts keep the runtime directory on fast local disk, and keep a
separate durable directory that stays with the work
> - These hosts cannot put the state that a session needs to continue in
the durable directory without also moving large caches and data that the
Runner writes again each launch
> - This pull request adds one optional setting,
`harnessStateDirectory`, for the state that a session needs to continue
> - The benefit is that a host can keep conversations and session
records durable, and keep caches and temporary data local

## Linked Issues or Issue Description

**Is your feature request related to a problem?**
A host can set where the Runner puts its runtime directory. It cannot
set a different location for only the harness state that a later process
needs to continue a session. If a host moves the full runtime directory
to durable storage, it also moves caches, configuration that the Runner
writes again at each launch, temporary homes and the turn journal. These
are large or written frequently, and nothing needs them after the
session.

**Describe the solution you'd like**
An optional setting names a durable directory. The Runner puts only the
state that a session needs to continue in that directory. All other data
stays in the runtime directory. When the setting is not set, nothing
changes.

**Describe alternatives you've considered**
- Move the full runtime directory to durable storage. This moves caches
and data that the Runner writes again each launch.
- Mount local folders over the cache paths. These paths include a
session ID that the Runner makes, so a host cannot know them before the
Runner starts. The folder names are also not a contract.

Related: #12840 (multi-turn remote sessions) and #15406 (Runner task
hooks for environment plugins) touch the same runtime directories. No
open PR or issue duplicates this change.

## What Changed

- The Runner accepts an optional `harnessStateDirectory` setting. A host
gives it as a launch option or as the
`PAPERCLIP_RUNNER_HARNESS_STATE_DIR` environment variable.
- When the setting is set, these folders go below
`<harnessStateDirectory>/acpx/<session>/`: ACPX session records
(`acpx-state`), each agent's home (`<agent>-home`) and XDG data
(`data`).
- When the setting is set, OpenCode's session store (`data`) and its
workspace record go below `<harnessStateDirectory>/opencode/<session>/`.
OpenCode recovery reads the workspace record, so a resume works after
the runtime directory is gone.
- The temporary home, configuration, caches, the ACPX workspace record
and the turn journal stay in the runtime directory.
- Recovery, session reopen, Antigravity probe retirement and the
credential observer look for the state in the new location.
- The Runner refuses a value that is relative, not normalized, missing,
the filesystem root, or reached through a symbolic link. It also refuses
a value that overlaps the workspace. The new folders are private (0700),
and the directory is a protected path for the harness sandbox.
- The ACPX launch descriptor, the sidecar `session.open` parameters and
the runnerd environment allowlists carry the setting only when it is
set.
- The README tells how to use the setting.

## Verification

- `tsc` for `tsconfig.json`, `tsconfig.surfaces.json` and
`tsconfig.test.json`, `check:protocol-types` and `check:acpx-profiles`:
pass.
- Targeted Vitest files for the ACPX sandbox, recovery identity, probe
retirement, the new directory module, the ACPX driver, runtime host,
agent files, the native backend factory, the OpenCode driver, the
OpenCode proxy input, the provider launch and the runnerd transport:
pass.
- Sidecar Vitest files and `node --test
test/acpx-sidecar-contract.test.mjs
scripts/contracts/contract-fingerprints.test.mjs`: pass.
- `cargo fmt --check`, `cargo check --workspace --all-targets` and
`cargo test -p paperclip-runner-core --lib credential_observer`: pass.
- The tests check that:
- The default layout does not change. The tests assert the exact paths.
  - With the setting, only the state folders move.
- A reopen finds the session after the runtime directory is deleted. For
OpenCode, the fake server saves and reloads the session from the session
store, and recovery fails when that state is removed.
  - The Runner refuses each invalid value.
- I did not run the full suite or the Runner integration suites locally.
CI runs them.

## Risks

- When the setting is not set, the layout and the saved descriptors do
not change. Existing hosts see no change.
- A host must enable the setting for new sessions only. A session saved
without the setting does not reattach with it. The Runner refuses it
with the existing "contract changed" error.
- In-process ACPX recovery reads the workspace record from the runtime
directory. If a host loses the runtime directory, that recovery path
fails as it does now. The runnerd ACPX path is not affected, because it
takes the working directory from the descriptor.
- The provider-pack contract digest changes because the Rust descriptor
has a new optional field and the allowlists have a new key. No ACPX
profile version or command digest changes.

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

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`) by Anthropic, in Claude Code, with
tool use (shell, file editing, code search) and extended thinking.

## Checklist

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

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
canary/v2026.1201.0-canary.876200
2026-12-01 08:58:21 -08:00
Dotta d1680baf8f fix(onboarding): harden connect-model OAuth timeout, mobile paste, and API key recovery (#23379)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - During onboarding, new users connect an AI model via Claude/OpenAI
subscription OAuth or an API key.
> - Production session replays showed users failing on `connect_model`
because subscription login sessions expired at 5 minutes during
mobile/tab switches, the waiting spinner hid the sign-in link with no
way to reopen it, pasted Claude codes failed silently without
normalization or clear feedback, and rejected API keys gave a dead-end
error.
> - These friction points cause new users to abandon onboarding right
before their first agent run.
> - This pull request raises server login timeouts to 15 minutes with
visibility-change polling/auto-refresh, keeps a re-open link and 60s
recovery action visible while waiting, normalizes and validates pasted
Claude authorization codes with explicit error messaging, and adds API
key paste normalization, provider-mismatch switching, and actionable
rejection links.
> - The benefit is fewer onboarding drop-offs on mobile and desktop
without changing backend auth protocols or schema.

## Linked Issues or Issue Description

**What happened?**
Users onboarding on `connect_model` hit four repeatable failure modes:
1. Subscription login sessions (`DEVICE_LOGIN_TIMEOUT_MS` and
`DEFAULT_SETUP_TOKEN_SESSION_TTL_MS`) expired after 5 minutes while
users switched apps/tabs for OAuth and 2FA, showing `This sign-in
expired` or `Sign-in didn't finish` right when they returned.
2. After clicking `Sign in`, `ProviderSubscriptionCard` replaced the
button with a disabled `Waiting…` / `Waiting for code…` spinner, leaving
users with no way to reopen the OAuth URL if a mobile browser blocked
the tab or they closed it.
3. Pasting a Claude authorization code with mobile line breaks, quotes,
or a full callback URL could fail silently or show no explanation when
rejected.
4. Pasting a rejected or wrong-provider API key showed a generic
rejection message without pointing users to the provider's API keys page
or offering a 1-click provider switch.

**Expected behavior**
Subscription sign-in sessions should give users 15 minutes to complete
OAuth, immediately poll or refresh when returning to the tab, keep a
re-open link and 60-second recovery action accessible, normalize and
validate pasted Claude codes with clear inline feedback, and help users
recover from wrong-provider or rejected API keys.

**Steps to reproduce**
1. Open the onboarding wizard and advance to the Connect a model step.
2. Start a Claude or OpenAI subscription sign-in, switch tabs for 5
minutes (or close the OAuth tab), and return.
3. Paste an authorization code with extra whitespace/newlines or a
callback URL into the Claude code input, or paste an Anthropic
`sk-ant-...` key into OpenAI API key mode.

**Paperclip version or commit**
`43fedd51c5c37ccf7c7568328bac97179cdd48ba` (`master`)

**Deployment mode**
Other (hosted Cloud & local dev)

## What Changed

- **15-minute subscription login TTLs + tab-return poll/refresh:**
Raised `DEVICE_LOGIN_TIMEOUT_MS`
(`server/src/services/device-login-service.ts`) and
`DEFAULT_SETUP_TOKEN_SESSION_TTL_MS`
(`server/src/services/setup-token-session.ts`) from 5 minutes to 15
minutes. Added `visibilitychange` listeners to both
`AdapterDeviceLoginPanel` and `ClaudeSetupTokenLoginPanel`
(`ui/src/components/AgentConfigForm.tsx`) to immediately refetch status
on tab return and auto-refresh once if an onboarding session expired
while hidden.
- **Non-locking waiting state:** Updated `ProviderSubscriptionCard`
(`ui/src/components/AdapterLoginChrome.tsx`) to keep an `Open sign-in
link again` button visible while waiting and show a `Taking a while? Get
a new link` recovery button after 60 seconds (`WAITING_HELP_DELAY_MS`).
- **Claude code-paste normalization & inline validation:** Added
`ui/src/lib/onboarding-login-helpers.ts`
(`normalizeSubmittedBrowserCode`, `validateSubmittedBrowserCode`) to
strip newlines/quotes and extract `code#state` from pasted callback
URLs, surface immediate inline validation errors on invalid pastes, and
show an explicit rejected-code message when a submitted code fails.
- **Self-recoverable API key input:** Added `normalizeApiKeyInput`,
`detectMismatchedApiKeyProvider`, and `providerApiKeysHelp` in
`ui/src/lib/onboarding-login-helpers.ts`, wired into
`ui/src/components/OnboardingWizard.tsx` to normalize pasted keys, offer
a 1-click switch when an Anthropic/OpenAI key is pasted into the wrong
provider, and link directly to the provider's API keys page when
rejected.
- **Module size note:** `AgentConfigForm.tsx` and `OnboardingWizard.tsx`
already exceeded 1,000 lines; all new pure parsing, validation, and
provider-help logic was extracted into
`ui/src/lib/onboarding-login-helpers.ts` to keep edits to existing files
minimal.

## Verification

- `pnpm --filter @paperclipai/ui typecheck` — passed.
- `pnpm --filter @paperclipai/server typecheck` — passed.
- `pnpm vitest run ui/src/lib/onboarding-login-helpers.test.ts
ui/src/components/AdapterLoginChrome.test.tsx
ui/src/components/AgentConfigForm.render.test.tsx
server/src/__tests__/device-login-service.test.ts` — 4/4 files, 84/84
tests passed.
- `git ls-files "*setup-token*test*" "*onboarding*test*" | grep -E
"^(server|ui)/" | xargs pnpm vitest run` — 24/24 files, 373/373 tests
passed.
- Note: A full local `pnpm verify` run selected 2,296 files and hit 14
unrelated local PostgreSQL/heartbeat/Tailscale hook timeouts under
parallel macOS load (34,070 passed, 0 failures in
login/onboarding/setup-token/device-login suites); CI will supply
full-suite coverage on this PR.

## Risks

- **Low risk:** Raising `DEVICE_LOGIN_TIMEOUT_MS` and
`DEFAULT_SETUP_TOKEN_SESSION_TTL_MS` from 5 to 15 minutes extends the
maximum lifetime of an uncompleted login sandbox lease by 10 minutes
(bounded by the existing reaper and per-owner concurrency limits). No
database schema, API contract, or auth protocol changes.

## Model Used

- Google Gemini (Antigravity agentic assistant with thinking mode and
tool use / code execution).

## Checklist

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

> - Paperclip is the open source app people use to manage AI agents for
work
> - Managed Paperclip Cloud stacks send direct server telemetry to
PostHog and identify each `workspace` group with `stack_slug` and
`primary_host`
> - Warm-pool stacks boot before a user claims them, so startup
`groupIdentify` records the placeholder `pool-<hash>` slug and host
> - When a user claims a warm-pool stack,
`applyCloudRuntimeIdentityAssertion` transitions the stack identity in
place without restarting the process, so PostHog group properties stay
stuck on `pool-<hash>` until a later restart
> - This pull request adds an `onCloudRuntimeIdentityChange` listener in
`cloud-runtime-identity` and subscribes the PostHog direct transport to
re-send `groupIdentify` with the claimed `stack_slug` and `primary_host`
> - The benefit is that PostHog workspace analytics and live dashboards
immediately reflect the real claimed stack name and host for both
browser and server-side events

## Linked Issues or Issue Description

**What happened?**

When a warm-pool Cloud stack boots, `resolveDirectTransport` announces
the workspace to PostHog with its placeholder `pool-<hash>` `stack_slug`
and `primary_host`. After a user claims the stack via
`applyCloudRuntimeIdentityAssertion`, the server updates its runtime
identity in place without restarting, so PostHog's `workspace` group
keeps the stale `pool-<hash>` `stack_slug` and `primary_host` until the
container eventually restarts.

**Expected behavior**

When a Cloud stack's runtime identity transitions from a warm-pool
placeholder to its claimed slug and canonical origin, the PostHog direct
transport immediately calls `groupIdentify` with the updated
`stack_slug` and `primary_host` and flushes.

**Steps to reproduce**

1. Start a Paperclip Cloud warm-pool instance with
`PAPERCLIP_POSTHOG_PROJECT_TOKEN` and `PAPERCLIP_POSTHOG_ENVIRONMENT`
configured and `PAPERCLIP_STACK_SLUG=pool-123`.
2. Apply a signed Cloud runtime identity assertion claiming the stack as
`gonzo` (`https://gonzo.staging.paperclip.app`).
3. Observe PostHog `workspace` group properties for the stack: before
this fix, `stack_slug` and `primary_host` remain `pool-123` /
`pool-123.staging.paperclip.app` until process restart.

**Paperclip version or commit**

`36c2ad39c8` (`origin/master`)

**Deployment mode**

Other (Paperclip Cloud managed stack)

## What Changed

- Added `onCloudRuntimeIdentityChange` listener registration and
best-effort notification in
`server/src/services/cloud-runtime-identity.ts` when
`applyCloudRuntimeIdentityAssertion` changes the runtime identity (or
`initializeCloudRuntimeIdentity` restores one), and cleared listeners in
`resetCloudRuntimeIdentityForTests`.
- Subscribed `createPostHogDirectTransport` in
`server/src/services/posthog-direct/transport.ts` to
`onCloudRuntimeIdentityChange` so matching `stackId` claims update any
queued `pendingAnnouncement` or immediately send and flush an updated
`groupIdentify` with the claimed `stack_slug` and `primary_host`;
unsubscribed on `shutdown()`.
- Added a regression test in
`server/src/__tests__/cloud-runtime-identity.test.ts` verifying initial
`pool-*` announcement, immediate `groupIdentify` + flush on claim, and
no duplicate calls on idempotent claim retry.

## Verification

- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/cloud-runtime-identity.test.ts
src/__tests__/posthog-direct-transport.test.ts
src/__tests__/posthog-direct-telemetry.test.ts` — 38/38 tests passed.
- `pnpm --filter @paperclipai/server typecheck` — passed.

## Risks

- Low risk. Listener notifications are wrapped in `try/catch` and the
PostHog `groupIdentify` + `flush` call is fire-and-forget with error
suppression, matching the existing `onCloudTrialInferenceCohortChange`
pattern so telemetry failures can never disrupt runtime identity claims.

## Model Used

- Google Gemini (Antigravity agent with tool use, file editing, and
local test execution)

## Checklist

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