mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-01 09:39:53 +01:00
158613ef81818228320ab8e306bd131fcf4b2b86
4746
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
158613ef81 |
Permit idle sleep with proved passive remote workspaces (#23335)
## Thinking Path > - Paperclip runs agent work and retains its files after a run ends. > - Remote workspaces save those files in a durable archive. > - The idle inventory still treats every remote workspace row as active work. > - A saved archive or an unused setup reservation can then keep an idle instance awake. > - This PR adds a read-only proof in the remote workspace owner and uses it in the existing idle check. > - The proof keeps active work and uncertain recovery awake and preserves all retained data. ## Linked Issues or Issue Description **What happened?** A retained `cloud_sandbox` workspace blocks idle sleep after its archive commits and its allocation is released. The passive workspace check only accepts local directories and git worktrees. An unused reservation can also remain after a bootstrap failure that started no provider work. **Expected behavior** An idle instance can sleep when existing receipts prove that its remote files are saved or that a setup reservation was never used. Missing, foreign, contradictory, and unfinished state must keep blocking sleep. **Steps to reproduce** 1. Save a remote workspace and finish its snapshot operation. 2. Release its allocation with the matching stop receipt, or retain no allocation. 3. Keep the workspace row and inspect idle safety. Before this change, the row still reports work. Related: remote workspace storage in #18403. No duplicate open sleep/workspace PR was found. ## What Changed - Add a pure SQL proof for a committed, scoped archive and its completed source operation. Require the stored encryption scheme and correctly shaped IV, tag, and ciphertext. An unchanged save can reuse an older snapshot. - Require exact release evidence for a retained location and every allocation of an unused reservation. Unused reservations require an ended legacy bootstrap, an explicit no-provider-work result, no live controller or retry, and no native finalization. A pristine reservation cannot carry retained recovery-file references. - Apply that proof through the existing passive workspace check. Keep runtime configuration, commands, due cleanup, reopen fences, and every independent run, lease, and recovery check. - Add PostgreSQL regression cases and describe the proof in the idle-safety documentation. The existing shared database fixture keeps the tests in one suite instead of adding another database startup. - Correct two pre-existing receipt browser assertions uncovered by required CI. Plain comments have supported keyed retries since October 28; the older tests assumed one POST even when receipt reads lose the race to backoff. Assert exact request identity and payload across retries, one saved comment, and preservation of the next draft. ## Verification - Receipt CI follow-up, Node 25.6.1 on macOS: the full `board-attachment-receipts.spec.ts` passed twice with four Chromium workers (28/28). Both corrected cases passed with delayed issue reads after reproducing both old failures under the same delay. `node scripts/typecheck-test-projects.mjs --reuse-declarations tests/e2e` and the focused test-budget check passed. Only browser assertions changed after the 323-test server verification. - Node 25.6.1 on macOS: `pnpm --filter @paperclipai/server typecheck` passed. - Final revision: `pnpm exec vitest run server/src/__tests__/idle-sleep-safety.test.ts server/src/__tests__/idle-sleep-diagnostics.test.ts`: 323 passed. Both suites used real embedded PostgreSQL. An earlier run also selected the remote-workspace lifecycle suite; its 16 cases were skipped because its external test database was not configured. - Red-green: the new saved-workspace regression failed before the first proof. Both unused-reservation cases failed before that proof was added. The focused regressions passed after the changes. Empty key material and a foreign allocation bound to an unused writer were also reproduced red-green during review. - `pnpm verify --explain` returned the documented exit 2 because the documentation path requires broader CI. Required CI will supply that coverage; a full local repository run was not substituted. - After rebasing onto current `master`, the focused passive-state tests and server typecheck passed again. - `git diff --check` and a staged secret/PII scan passed. - The previous revision (`078e60f`) received Greptile 5/5 with its key-format thread resolved. [Initial CI](https://github.com/paperclipai/paperclip/actions/runs/46536659729) failed in a Rust executable fixture (`ExecutableFileBusy`) and a browser receipt assertion. The targeted rerun passed Rust but failed the companion receipt test. Both browser assertions expected one POST, contrary to the documented keyed retry contract. A scratch fault fixture delaying issue reads by 1.6 seconds reproduced both old failures (`Expected: 1 / Received: 2`); both revised cases passed under the same delay. The delay fixture is kept outside the branch. Final head `97269b3420387b28fda5f35f69a6b9ed45d5bb54` is merge-ready: all required gates passed, 81 checks succeeded and four were skipped by workflow policy, Greptile is 5/5 on this head, and the one review thread is resolved. GitHub reports `MERGEABLE` / `CLEAN`. The skipped external-database local cases and earlier failed attempts remain recorded above. - No provider suspension, external wake, deployment, or cost-saving result is claimed from these local checks. The proof adds no provider call, recurring scan, or extra database round trip. It runs within the existing bounded, read-only snapshot. ## Risks This expands automatic sleep eligibility for proved passive remote state. A proof error could stop an instance with unfinished work. The new cases cover dirty or foreign authority, missing or malformed snapshot key material, incomplete operations, foreign or unverified leases, active ownership, retry state, and retained recovery references. The SQL checks the stored key format; archive decryption and object verification remain with the restore owner. The existing owned hold, generation checks, runtime probes, and final host authorization still apply. The change does not delete files, clear reservations, rewrite history, create receipts, change schedules, or add a migration. Revert the remote-provider predicate to restore the previous refusal behavior. Hosted stop/wake qualification remains part of deployment acceptance. ## Model Used OpenAI GPT-6.1-sol with xhigh reasoning through Codex in T3 Code. Tool-assisted implementation, source review, and PostgreSQL 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 described the issue in-PR following the bug report template - [x] I have not referenced internal/instance-local Paperclip issues or links - [x] My branch name describes the change and contains no internal ticket id or instance-derived details - [x] I have run relevant tests locally and they pass; skipped external-database cases are stated above - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation - [x] I have considered and documented risks - [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 - Final revision [ci / e2e](https://github.com/paperclipai/paperclip/actions/runs/46539276027/job/142275047883): passed. - Final revision [ci / verify](https://github.com/paperclipai/paperclip/actions/runs/46539276027/job/142275348382): passed. --------- Co-authored-by: Paperclip <noreply@paperclip.ing> |
||
|
|
fb6632530d |
feat(onboarding): start the first chat with a welcome and choices (#23334)
## Thinking Path > - Paperclip helps people assign and track work with AI agents. > - Onboarding connects the first agent and opens its chat. > - A new user needs a clear way to start a conversation. > - A saved welcome can appear as soon as chat opens. > - The standard question card lets the user pick a goal, a product overview, or a task. > - The connected model replies after the user sends the choice. ## Linked Issues or Issue Description **Subsystem affected** Onboarding, agent chat, and subscription sign-in. **Problem or motivation** New users can land in a chat before they know what to ask. The original welcome depended on a model run, which could delay the first interaction. Local Claude sign-in could lose its code field if the browser reloaded the onboarding tab during authorization. **Proposed solution** Save a personalized welcome and a standard question card. Type the welcome when the chat opens, then show the card above the composer. Use the choice and any task description to guide the connected model. Resume the local Claude sign-in attempt when the onboarding tab reloads. **Alternatives considered** A model-written welcome can vary, but it adds a model call before the user has chosen what to do. The saved welcome gives the user the same starting points each time. **Roadmap alignment** This improves the existing first-agent flow for local and Cloud-managed instances. Related PRs: #22433 covers clearing the organization name after Back. #23326 adds the separate Cloud mobile-to-desktop handoff. ## What Changed - Save the greeting and question card together. Reuse the saved chat on entry and keep the transcript in order after a reload. - Type the greeting in the chat and reveal the standard question card above the composer. Honor reduced motion. - Collect a task description before starting the first model turn for the task option. Guide the first reply for each choice. - Restore the original local Claude sign-in attempt when the onboarding tab reloads. Show progress while it connects, and offer retry on a failed or stalled code exchange. - Update the organization name helper text and the onboarding walkthrough tests. ## Verification - See the first-chat test drive for manual steps and the credential-free browser fixture. - 659 focused Vitest tests passed, with one skipped. The UI and server typechecks and the feature map validator passed. - All 18 Chromium tests passed across the first-chat, onboarding, sign-in resume, and mobile desktop handoff specs. Coverage includes the saved greeting, chat ordering, question handoff, Claude code submission and resume, and the Cloud-managed starter model path with scripted replies. - The published Cloud service and live subscriber credentials need separate acceptance testing. ## Risks - The greeting uses the existing conversation and interaction records. No database migration is needed. - Existing in-flight model greetings can finish through the previous path. - The Claude PTY change depends on the CLI's bracketed-paste support. The runner preserves separate input writes for terminals that do not announce support. ## Model Used OpenAI Codex, GPT-6.2 Sol and GPT-6.2 Astra, with terminal and browser tooling. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Scott Tong <1504818+scotttong@users.noreply.github.com> |
||
|
|
1eae356c55 |
fix(analytics): remove PostHog consent banner and opt-out gating for private beta (#23333)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Paperclip Cloud sends browser product analytics and session replays to PostHog when enabled for a hosted stack (self-hosted installs never load posthog-js) > - Previously, an EU/UK/Swiss consent banner and Profile settings opt-out toggle gated browser analytics and dropped metrics when visitors did not opt in > - During private beta, we want to stop showing the consent banner and opt-out prompt anywhere while continuing to send metrics (compliance will be handled separately later) > - This pull request removes the consent banner, Profile opt-out toggle, and client-side consent gating across the UI and sets `consentRequired: false` on the server response > - The benefit is zero banner friction during private beta and uninterrupted PostHog product metrics, while keeping all replay/autocapture privacy masking and pre-load event queuing intact ## Linked Issues or Issue Description **What existing behavior does this improve?** Paperclip Cloud browser product analytics initialization (`ProductAnalyticsGate`, `ui/src/lib/analytics`, `ProfileSettings`, `cloud-posthog-browser.ts`). **Subsystem affected** Cross-cutting (multiple of the above) — `ui/` and `server/`. **Current behavior** In EU/EEA/UK/Swiss regions (or unknown time zones), `ProductAnalyticsGate` renders `AnalyticsConsentBanner` and blocks loading `posthog-js` until the visitor clicks Accept. `ProfileSettings` also renders a `ProductAnalyticsSetting` opt-out switch. **Proposed behavior** Remove `AnalyticsConsentBanner`, `ProductAnalyticsSetting`, and client-side consent gating so `ProductAnalyticsGate` loads PostHog unconditionally when `browserAnalytics` is enabled for a Cloud stack. Return `consentRequired: false` from `resolveBrowserAnalyticsConfig` so cached older UI bundles also stop prompting during rollout, and keep `opt_in_capturing()` when `has_opted_out_capturing()` is true so previously opted-out browsers resume sending metrics. **Reason and benefit** During private beta, the EU/UK consent banner adds friction and drops PostHog product metrics. Removing the banner and opt-out gating restores full metric delivery while keeping all replay/autocapture privacy masking and pre-load event queuing intact. **Breaking changes** None — `browserAnalytics.consentRequired` remains on the session payload (as `false`), self-hosted installs still receive `browserAnalytics: null`, and per-stack env controls (`PAPERCLIP_POSTHOG_BROWSER_ENABLED`, `PAPERCLIP_POSTHOG_REPLAY_ENABLED=0`) continue to work. ## What Changed - Deleted `ui/src/components/AnalyticsConsentBanner.tsx`, `ui/src/components/ProductAnalyticsSetting.tsx`, `ui/src/lib/analytics/consent.ts`, and their unit tests. - Simplified `ui/src/components/ProductAnalyticsGate.tsx` to start PostHog unconditionally after the page settles and render `null`. - Simplified `ui/src/lib/analytics/product-analytics.ts` to remove consent-state gating while keeping pre-load event queuing (`MAX_QUEUED_PRODUCT_EVENTS`) and automatic opt-in for browsers with a prior PostHog opt-out. - Removed `ProductAnalyticsSetting` from `ui/src/pages/ProfileSettings.tsx` and its mock in `ui/src/pages/mobile-collections-responsive.test.tsx`. - Updated `server/src/services/cloud-posthog-browser.ts` to always return `consentRequired: false`. - Updated `ui/src/components/ProductAnalyticsGate.test.tsx`, `ui/src/lib/analytics/onboarding-analytics.test.tsx`, `server/src/__tests__/cloud-posthog-browser.test.ts`, `server/src/__tests__/auth-routes.test.ts`, and `doc/cloud-browser-analytics.md`. ## Verification - `pnpm vitest run ui/src/components/ProductAnalyticsGate.test.tsx ui/src/lib/analytics/onboarding-analytics.test.tsx ui/src/lib/analytics/product-analytics.test.ts ui/src/pages/mobile-collections-responsive.test.tsx server/src/__tests__/cloud-posthog-browser.test.ts server/src/__tests__/auth-routes.test.ts` — all passed. - `pnpm --filter @paperclipai/ui typecheck` — passed. - `pnpm --filter @paperclipai/server typecheck` — passed. ## Risks - Low risk: self-hosted installs remain unaffected (`browserAnalytics` is still `null`). All replay/autocapture privacy masking and `/_ph` proxy allowlists remain unchanged. Per-stack opt-out (`PAPERCLIP_POSTHOG_BROWSER_ENABLED` / `PAPERCLIP_POSTHOG_REPLAY_ENABLED=0`) continues to work. ## Model Used - Google Gemini (Antigravity agent with tool use and code execution) ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing> |
||
|
|
1949a8fa10 |
fix(onboarding): sign in through a plugin-managed execution environment (#23312)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Onboarding connects the first agent to an AI provider account, often with a Claude or Codex subscription sign-in > - A plugin can manage an execution environment whose driver declares `supportsLoginPty` and `requiresAgent`. Each agent's lifecycle prepares that environment for the agent, and the sign-in runs in it > - An instance can make such a plugin-managed execution environment its default > - The onboarding wizard offered browser sign-in only in a sandbox-driver environment, so it blocked the connect step in every plugin-managed execution environment > - The sign-in also cannot start until the agent's lifecycle has prepared the environment > - This pull request lets onboarding and the new-agent flow sign in through a plugin-managed execution environment, after the environment is prepared for the agent > - The benefit is that subscription sign-in works when the default environment is plugin-managed ## Linked Issues or Issue Description Refs #22695 and #20906. **What happened?** The default environment is a plugin-managed execution environment whose driver declares `supportsLoginPty`. A user starts onboarding and chooses Claude or Codex with a subscription. The connect step shows "This environment does not support browser sign-in. Go back to use an API key or choose another model." Connect stays disabled. **What did you expect to happen?** The connect step starts a browser sign-in in the plugin-managed execution environment for the onboarding agent. The agent configuration form and the AI Connections page already do this for plugin-managed environments. **Steps to reproduce** 1. Install an environment plugin with a `requiresAgent` driver that declares `supportsLoginPty`, and make its environment the instance default. 2. Start onboarding for a new company. 3. Choose Claude or Codex, and keep the subscription option. 4. See the message above. Connect is disabled. ## What Changed - The onboarding wizard and the new-agent flow use the shared `environmentSupportsLoginPty` rule. Before, both flows had their own sandbox-only check. - In a plugin-managed execution environment, onboarding sends the sign-in to its own setup agent (`requiresAgent` and `agentId` on `AdapterLoginPanel`). The new-agent flow does the same with its draft agent. - Onboarding polls the setup agent until the environment can take the sign-in for it: a Paperclip runner agent on the login environment in `verifying` or `ready`. Until then the step shows "Preparing your agent's computer…", the user-facing name for this environment. A failed preparation shows the error and a "Retry preparation" button. A failed agent read shows "Could not check your agent's computer." and retries the read. - The new-agent flow keeps the login panel unmounted until the environment is prepared (`loginHostPending` on `AgentProviderConnection`). The panel starts the sign-in on mount, and the disabled fieldset does not stop that. - Both flows latch the readiness per agent and environment (`useAgentComputerLoginReady`). A configuration change sends the setup draft through preparation again. That must not unmount a sign-in that is already on screen. - The auth-signal route now accepts a plugin-managed execution environment for `claude_local` and `codex_local`, and answers `unknown` there. Before, it returned 422, and the onboarding step stayed undecided and never showed the sign-in. The signal reads only host-local state, which says nothing about a plugin-managed environment. - The new-agent flow now says "Preparing your agent's computer…", the same as onboarding. - Each part of the login PTY question now has one owner: - Shared `environmentLoginRequiresAgent` decides whether a sign-in needs an agent. The four UI flows and the server's login target resolver use it instead of their own `driver === "plugin"` checks. - Shared `isPluginEnvironmentLoginAdapter` and `pluginEnvironmentLoginReadsCredential` decide which adapters sign in through a plugin-managed execution environment, and which of them must read the credential back. `environmentSupportsLoginPty` and the server's login target resolver use them. The server's capability resolver takes the adapter type instead of a credential-read flag. - `sandboxProviderSupportsLoginPty` decides sandbox-provider support for both the capability listing and the sign-in check. - The credential read uses `pluginSupportsLoginPty`, like the rest of the plugin login path. Before, it checked only the manifest flag and the read method. - The agent configuration form's gate is now the shared rule plus "not in create mode when an agent is required". Its duplicate driver check and an always-true condition are gone. ## Verification - `pnpm typecheck` in `ui/` and `server/`: no errors. - `npx vitest run src/lib/agent-computer-login.test.ts src/lib/agent-computer-login.hook.test.tsx src/components/new-agent/AgentProviderConnection.computer-login.test.tsx src/components/new-agent/AgentProviderConnection.test.tsx` in `ui/`: tests pass. The `AgentProviderConnection` sign-in test covers a slow preparation, and the readiness hook test covers a re-preparation of the same environment. - `npx vitest run src/__tests__/adapter-auth-signal-routes.test.ts` in `server/`: tests pass. The two new plugin-managed environment cases fail without the route change. - `pnpm typecheck` in `packages/shared/`: no errors. `npx vitest run src/environment-support.test.ts` in `packages/shared/`: 9 tests pass. - In `server/`: the device-login, setup-token, login-session runtime, sandbox-capability, credential-read and OpenAPI route suites pass (159 tests). A new credential-read case refuses a driver that does not meet the plugin login rule. - In `ui/`: the `AgentConfigForm`, `AgentProviderConnection`, `agent-computer-login` and onboarding analytics suites pass. - I did not do a live onboarding with a real plugin-managed execution environment. Reviewers who have such an instance can reproduce with the steps above. Expect "Preparing your agent's computer…", then the provider sign-in, then the hire. ## Risks - Onboarding waits for the environment's preparation before a subscription sign-in in a plugin-managed execution environment. A slow preparation makes the connect step wait for that time. An API key or a saved subscription does not wait. - The latch keeps the sign-in on screen while a configuration change prepares the same environment again. If the plugin refuses the sign-in in that window, the sign-in panel shows its usual error and retry. - The setup draft must resolve to the Paperclip runner in the plugin-managed environment. If it does not, the step stays on "Preparing your agent's computer…". Plugin-managed environments run only the Paperclip runner, so this is not expected. - No migration and no API contract change. The auth-signal route accepts one more environment driver. - The credential read now requires the full plugin login rule (`creationOperationVersion` 1 and every login worker method). A plugin that reaches the credential read already passed that rule when its login lease was acquired, so no working plugin should change. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), with extended thinking and tool use (code search, shell, tests) 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 - [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> |
||
|
|
48deef0135 |
fix(claude-local): fail runs whose prompt a UserPromptSubmit hook blocked (#17766)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The `claude_local` adapter runs the Claude Code CLI and turns its stream-json output into a run result > - A project can define a `UserPromptSubmit` hook, and that hook can block the prompt > - When the hook blocks the prompt, the CLI runs no turn, exits 0 and reports a successful `result` whose text echoes the whole prompt > - The adapter returned that echo as the agent's reply, the server posted it as a comment, and the next wake carried that comment in the task history > - So each retry doubled the prompt, and the run looked successful > - This pull request detects the blocked prompt and fails the run with a specific error code and no echoed reply > - The benefit is that a hook rejection is visible as a failed run, and the prompt stops growing ## Linked Issues or Issue Description No public issue exists for this. I searched open and closed issues and pull requests for `UserPromptSubmit`, `blocked_by_hook`, `prompt_submit_outcome` and "hook blocked prompt". Related, but different: #15417 (pass-through of hooks-only settings for managed connections), #11976 / #16443 (Hermes prompt echo). **What happened?** A project `UserPromptSubmit` hook blocked the wake prompt. Claude Code emitted a `system` event with subtype `informational` and `prompt_submit_outcome.kind = "blocked_by_hook"`, then a `result` event with `subtype: "success"`, `is_error: false`, `num_turns: 0` and `result` equal to `UserPromptSubmit operation blocked by hook: … Original prompt: <whole prompt>`. The process exited with code 0. The adapter treated the run as successful and used the echoed text as the summary. The server posted the echo as the agent's comment. The next wake included that comment in the task history, so the prompt grew on each retry. We observed a wake prompt of about 3.6 MB. **Expected behavior** A prompt that a hook blocked is a failed run. The run must not post the echoed prompt as a reply. The run error must say that a hook blocked the prompt and give the hook reason. **Steps to reproduce** 1. In an empty directory, create `.claude/settings.json` with `{"hooks":{"UserPromptSubmit":[{"hooks":[{"type":"command","command":"echo 'blocked by policy hook' >&2; exit 2"}]}]}}`. 2. Run `claude -p --output-format stream-json --verbose "say hi" < /dev/null`. 3. See the `informational` event with `prompt_submit_outcome: {"kind":"blocked_by_hook","prompt_kept":false,"reason":"blocked by policy hook"}`, then a `result` event with `subtype: "success"`, `num_turns: 0` and the echoed prompt, and exit code 0 (seen with Claude Code 2.1.309). 4. Use the same project for a `claude_local` agent and wake it. Before this change, the run succeeds and its summary is the echoed prompt. **Paperclip version or commit** Seen on v2026.1023.0. The patch base is `master` at `a67a18c171`. **Deployment mode** Self-hosted, `claude_local` with `engine: cli`. ## What Changed - `createClaudeStreamParser` records the reason from a `system`/`informational` event whose `prompt_submit_outcome.kind` is `blocked_by_hook`, and returns it as `promptBlockedReason`. - `execute` sets `errorMessage` to `Claude prompt was blocked by a UserPromptSubmit hook: <reason>`, `errorCode` to `claude_prompt_blocked_by_hook`, `stopReason` to `prompt_blocked_by_hook`, an empty summary and `result: null` in `resultJson`. A non-null `errorMessage` makes the server record the run as failed. - The new error code is not a transient code, so the bounded transient retry does not repeat the blocked prompt. - Add an execute regression test with a fake CLI that emits the real event sequence. ## Verification - `npx vitest run server/src/__tests__/claude-local-execute.test.ts`: 35 passed. - The new test fails on `master` without the source change (`expected null to be 'claude_prompt_blocked_by_hook'`). - `tsc --noEmit` in `packages/adapters/claude-local`: no errors. `tsc --noEmit` in `server` gives the same error list as unchanged `master` in the same environment (the only errors come from the unbuilt `@paperclipai/paperclip-runner` package). - Manual check of the CLI event shape with Claude Code 2.1.309, as in the steps above. ## Risks - Low risk. The new branch runs only when the CLI reports `prompt_submit_outcome.kind === "blocked_by_hook"`. - If a future CLI version changes this event shape, the adapter falls back to the current behavior. > 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 AI-assisted with Claude Code and OpenAI Codex coding agents; exact model versions are not listed. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [ ] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes (none needed: no documented behavior or setup 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 <noreply@anthropic.com> |
||
|
|
a1b9eed57d |
fix(mcp): stop masking upstream MCP and OAuth 502 errors as Paperclip outages (#23295)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - Users connect external MCP servers and OAuth apps in Paperclip so
agents can use their tools
> - When a remote MCP server or OAuth authorization server rejects
automatic registration or discovery (for example, returning HTTP 400
`invalid_redirect_uri` during Dynamic Client Registration), Paperclip
returns HTTP 502 with a structured upstream error payload
> - The UI error classifier previously treated every HTTP 502 without a
`CODE_COPY` entry as a Paperclip outage, so it discarded the server
message and showed "Paperclip is temporarily unavailable"
> - This pull request shares a canonical allowlist of upstream
MCP/OAuth/remote HTTP 502 error codes between the server and UI,
preserves upstream error messages with accurate retryability, shows
clear sign-in guidance with Paperclip's copyable callback URL, and
resumes the saved draft connection during manual client recovery
> - The benefit is that users immediately see why a remote MCP server
rejected sign-in and how to fix it (allowlisting Paperclip's callback
URL or entering a client ID) without hitting a false Paperclip outage or
creating duplicate connections
## Linked Issues or Issue Description
**What happened?**
When a user connects a remote MCP server with browser sign-in and the
remote authorization server rejects Dynamic Client Registration (for
example, returning HTTP 400 `invalid_redirect_uri` because it requires a
client allowlist), the Paperclip server returns HTTP 502 with `{ error:
"The authorization server rejected Paperclip's callback URL.", details:
{ code: "oauth_dynamic_client_registration_failed", providerError:
"invalid_redirect_uri", status: 400 } }`. The UI classified that HTTP
502 as a transient connectivity outage and displayed "Paperclip is
temporarily unavailable. Please try again in a moment." instead of the
actual reason.
**Expected behavior**
Paperclip should preserve its server-authored error message for
allowlisted upstream HTTP 502 responses, derive `retryable` accurately
(non-retryable for permanent upstream rejections, retryable for upstream
outages/5xx/rate-limits/timeouts), and avoid triggering the app-wide
outage banner. In the MCP connection flow, Paperclip should explain why
the remote server rejected automatic sign-in setup, expand the Browser
sign-in section with Paperclip's copyable callback URL above Client ID
and Client secret, and resume the saved draft connection instead of
creating duplicate numbered connections when the user retries.
**Steps to reproduce**
1. Open Apps and connect a custom MCP server URL whose OAuth
authorization server rejects Dynamic Client Registration (such as HTTP
400 `invalid_redirect_uri` or another upstream registration/metadata
error).
2. Start browser sign-in.
3. Observe that Paperclip previously showed "Paperclip is temporarily
unavailable. Please try again in a moment." instead of explaining the
callback URL or registration rejection.
**Paperclip version or commit**
Reproduced on `master` at commit `2d764bebc6` (and prior `bc98abda0c`).
**Deployment mode**
Other (applies to both Paperclip Cloud and self-hosted deployments).
## What Changed
- **Shared contracts (`packages/shared`)**:
- Added `packages/shared/src/upstream-failure-codes.ts` (re-exported
from `packages/shared/src/index.ts`) defining the single canonical
allowlist of upstream HTTP 502 error codes
(`UPSTREAM_MCP_OAUTH_FAILURE_CODES`,
`UPSTREAM_REMOTE_HTTP_FAILURE_CODES`,
`UPSTREAM_BAD_GATEWAY_FAILURE_CODES`,
`isUpstreamBadGatewayFailureCode`), transient HTTP status helper
(`TRANSIENT_UPSTREAM_HTTP_STATUSES`, `isTransientUpstreamHttpStatus`),
and shared retryability policy (`isRetryableUpstreamFailure`). Transient
HTTP statuses (408, 425, 429, and 5xx) are checked before the permanent
`oauth_dynamic_client_registration_failed` fallback so rate-limited or
timed-out registration attempts remain retryable. Any unlisted
structured 502 still falls back to the transient outage path.
- Updated `connectToolAppSchema` in
`packages/shared/src/validators/tool-access.ts` so `resumeConnectionId`
works for generic `link` connections as well as gallery apps (still
requiring `galleryKey || link`), enabling the recovery path to resume a
saved generic MCP draft instead of creating a duplicate connection.
- **Server (`server/`)**:
- Updated `server/src/services/mcp-connection-failure.ts` so
`mcpDiscoveryHttpFailure` emits `{ code: "mcp_remote_http_error", status
}` in `HttpError` details.
- Updated `server/src/services/tool-access/catalog/failures.ts` so
`sanitizeHttpFailure` imports `UPSTREAM_MCP_OAUTH_FAILURE_CODES` from
`@paperclipai/shared` and preserves upstream MCP/OAuth failure codes
with HTTP 502 instead of collapsing them to `"paperclip_error"`.
- Updated `server/src/routes/tool-access.ts` so when `svc.startOAuth`
throws a non-manual-client `HttpError` after creating a `draft`
connection, `error.details` includes `connectionId:
result.connectionId`.
- Updated `server/src/services/tool-access.ts` (`connectGalleryApp`) so
resuming a draft via `resumeConnectionId` with a generic `link` enforces
that the draft is not a curated gallery app and that its stored MCP
endpoint matches the requested `link`.
- **UI (`ui/`)**:
- Updated `ui/src/api/errors.ts` so `isStructuredUpstreamBadGateway` and
`isRetryableUpstreamBadGateway` delegate to
`isUpstreamBadGatewayFailureCode` and `isRetryableUpstreamFailure` from
`@paperclipai/shared` (keeping unlisted structured 502s,
`ApiUnavailableError`, and `TRANSIENT_CODES` on the outage banner path,
and returning `retryable: false` for permanent upstream rejections vs
`retryable: true` for upstream 5xx, rate limits, timeouts, or temporary
outages).
- Updated `ui/src/pages/apps/generic-mcp-connect.ts` with
`"oauth_client"` focus, plain-English guidance for DCR (including
temporary rate-limit/timeout/5xx guidance with `focus: "none"` vs
permanent rejection guidance with `focus: "oauth_client"`), metadata,
redirect, token, and remote HTTP failures, plus pure
`genericGuidanceFormPatch` and `resolveGenericDraftResumeId` helpers.
- Updated `ui/src/features/connections/oauthFailureMessages.ts` to cover
`oauth_dynamic_client_registration_failed` (including transient HTTP
429/408/425/5xx responses), `oauth_dcr_response_invalid`, and
`oauth_metadata_failed`, extract `connectionId` in
`readOAuthApiErrorDetails`, and add `oauthStartFailureMessage`.
- Added `ui/src/features/connections/useGenericDraftResume.ts`
(`useGenericDraftResume` + `grantKindFromConnection`) and updated
`ui/src/features/connections/GenericMcpConnectStep.tsx`,
`ui/src/features/connections/ConnectionSetupFlow.tsx`, and
`ui/src/pages/tools/PasteConfigTab.tsx` to deduplicate guidance form
transitions via `applyGenericConnectGuidance`, preserve and resume the
failed generic draft connection ID across retries without creating
duplicates while starting a fresh draft if the URL, company, credential
ownership (`grantKind`), or dedicated agent changes, clear stale drafts
on `404` / `connection_setup_not_incomplete`, display Paperclip's
copyable callback URL (using `useCopyAction`) above Client ID and Client
secret when Browser sign-in expands, and remove the unused `ApiError`
import. No source file crossed the 1,000-line threshold
(`ConnectionSetupFlow.tsx` and `tool-access.ts` were already above 1,000
lines).
- **Tests**:
- Synchronized `tests/runner-e2e/source-sdk-public-inputs.json` for the
`@paperclipai/shared` public source graph.
- Added/updated regression tests in
`packages/shared/src/upstream-failure-codes.test.ts`,
`packages/shared/src/validators/tool-access.test.ts`,
`ui/src/api/errors.test.ts`,
`ui/src/pages/apps/generic-mcp-connect.test.ts`,
`ui/src/features/connections/oauthFailureMessages.test.ts`,
`ui/src/features/connections/GenericMcpConnectStep.machine.test.tsx`,
`ui/src/features/connections/ConnectionSetupFlow.generic-mcp.test.tsx`,
`server/src/services/tool-access/catalog/failures.test.ts`,
`server/src/services/__tests__/mcp-connection-failure.test.ts`, and
`server/src/__tests__/generic-mcp-connection.test.ts`.
## Verification
Ran on latest commit `9d088abf91`:
- `pnpm --filter @paperclipai/shared build && pnpm --filter
@paperclipai/shared typecheck && pnpm --filter @paperclipai/shared exec
vitest run src/upstream-failure-codes.test.ts
src/validators/tool-access.test.ts` — passed (2 files, 20 tests).
- `pnpm --filter @paperclipai/ui typecheck` — passed (0 errors).
- `pnpm --filter @paperclipai/ui exec vitest run src/api/errors.test.ts
src/pages/apps/generic-mcp-connect.test.ts
src/features/connections/oauthFailureMessages.test.ts
src/features/connections/ConnectionSetupFlow.generic-mcp.test.tsx
src/features/connections/ConnectionSetupFlow.oauth.test.ts` — passed (5
files, 140 tests).
- `node tests/runner-e2e/source-sdk-public-inputs.mjs $(git rev-parse
HEAD) --check` — passed (`changed: false`, 582 inputs).
- `pnpm exec vitest run --config tests/runner-e2e/vitest.config.ts
tests/runner-e2e/source-sdk-public-inputs.test.mjs` — passed (13 tests).
Full GitHub CI & review gates on final head `9d088abf91` ([`ci` run
46468259760](https://github.com/paperclipai/paperclip/actions/runs/46468259760)):
- `ci / verify`, `ci / e2e` (all 16 shards), `ci / Typecheck + Release
Registry`, `ci / policy`, `ci / General tests` (20/20), `ci / Runner
support suite` (4/4), `ci / Verify Paperclip` (9/9), `ci / Verify
serialized server suites` (9/9), `ci / Sandbox profile`, `Superagent
Security Scan`, `Socket Security`, `Contributor trust`, `security/snyk`,
`commitperclip PR Review`, and `Greptile Review` (5/5, 0 unresolved
threads) all passed on `9d088abf91`.
Visual states covered via component and flow tests using existing design
tokens (`border-input`, `bg-muted/40`, `text-foreground`,
`text-muted-foreground`): initial generic MCP connect step, expanded
Browser sign-in with copyable Paperclip callback URL (`Copy` / `Copied`
/ `Copy failed`), inline guidance banner for DCR/metadata/credential
errors (including transient rate-limit/timeout/5xx copy), draft resume
on manual client retry, fresh draft creation on access ownership change,
and draft clearing on `404` / `connection_setup_not_incomplete`.
## Risks
- Low risk. Uncoded HTTP 502 responses, unlisted structured 502 codes,
proxy HTML `ApiUnavailableError` responses, and `tenant_app_unavailable`
/ `tenant_app_starting` responses still classify as `"transient"` and
still trigger the app-wide outage banner.
- Security: Untrusted upstream OAuth `error_description`, `error_uri`,
and response bodies remain blocked; only Paperclip-authored messages and
allowlisted RFC error codes drive UI copy. Generic draft resume enforces
route-level configure authorization
(`assertToolConnectionConfigureAccess`), rejects curated gallery drafts,
and requires a matching normalized server endpoint.
> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.
## Model Used
- Google DeepMind Antigravity (Gemini-based coding agent via ACPX
runtime) with tool use and code execution.
## Checklist
- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
---------
Co-authored-by: Paperclip <noreply@paperclip.ing>
|
||
|
|
3621d7204d |
fix(native-runtime): retire finished plugin owners after destroyed leases (#23292)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Paperclip Runner agents can run per-turn tasks on plugin environments that destroy each ephemeral lease after a turn completes. > - When a plugin environment destroys a finished per-turn lease, `createPluginEnvironmentDriver().destroyRunLease` releases the lease row with `status: "failed"`, `cleanupStatus: "success"`, a non-null `releasedAt`, and a bound `remoteExecutionTermination` stop receipt. > - On the next turn, `remoteExecutionHasStopped` accepts that lease as stopped, but `priorRemoteSandboxLeasesEnded` only accepts `released` or `expired`, so every follow-up fails with `runner_state_identity_mismatch: prior_owner_terminal_state_indeterminate; retirement_refused=prior_lease_active` until automatic recovery retries with `forceFreshSession`. > - Even after retirement succeeds on a `per_turn` run, `replaceAfterConfirmedProviderStateLoss` only inspected `persistedWarmSession` (undefined for `per_turn` runs) instead of checking the control-plane session checkpoint. > - This pull request accepts cleanly destroyed `failed` leases (`cleanupStatus === "success"`, `releasedAt !== null`, different `providerLeaseId`) in `priorRemoteSandboxLeasesEnded` and falls back to `controlPlane.loadSessionCheckpoint()` when computing `replaceAfterConfirmedProviderStateLoss` after `pluginCheckpointRetired`. > - The benefit is that per-turn plugin Runner follow-ups retire settled destroyed leases and continue on the first attempt instead of failing once and forcing a fresh-session retry on every turn. ## Linked Issues or Issue Description Refs #22973, #23007. **What happened?** On a plugin environment running `per_turn` Paperclip Runner tasks (`leasePolicy: "ephemeral"`), every completed turn tears down its lease through `createPluginEnvironmentDriver().destroyRunLease`, which stores `status: "failed"`, `cleanupStatus: "success"`, `failureReason: "paperclip_runner_destroy_after_turn"`, a non-null `releasedAt`, and a bound `remoteExecutionTermination` stop receipt. When the next follow-up turn ran for the same task session, `recoverPluginRunnerCheckpoint` confirmed that the prior task stopped with no retained checkpoint, `remoteExecutionHasStopped` returned `true` (because `hasRemoteTerminationReceipt` accepts `["released", "expired", "failed"]` with `cleanupStatus === "success"`), and `inspectFinishedPerTurnRunnerdOwner` then called `priorRemoteSandboxLeasesEnded`. Because `priorRemoteSandboxLeasesEnded` only accepted `status === "released" || status === "expired"`, every follow-up failed immediately with: `runner_state_identity_mismatch: prior_owner_terminal_state_indeterminate; retirement_refused=prior_lease_active` Recovery then retried ~20-30s later with `forceFreshSession`, which succeeded on a new session ID and repeated the same failure on the next turn. In addition, once a `per_turn` run retires a confirmed-unavailable plugin checkpoint (`pluginCheckpointRetired = true`), `replaceAfterConfirmedProviderStateLoss` only checked `persistedWarmSession`, which is `undefined` for `per_turn` runs (whose persisted checkpoint lives in `controlPlane.loadSessionCheckpoint()`). **Expected behavior** A finished prior run whose remote lease was destroyed with `status: "failed"`, `cleanupStatus: "success"`, `releasedAt !== null`, and a different `providerLeaseId` retires cleanly into `continuity-breaks` on the first follow-up attempt, and `per_turn` runs compute `replaceAfterConfirmedProviderStateLoss` from the control-plane session checkpoint when `persistedWarmSession` is absent (while still preserving same-session recovery for unfinished goals and pending-release Antigravity gates). **Steps to reproduce** Run `pnpm --filter @paperclipai/server exec vitest run src/services/native-runtime/native-session-executor.test.ts -t "retires a finished per-turn plugin owner after a destroyed lease"` against `2d764bebc6`. **Paperclip version or commit** Reproduced on `origin/master` at `2d764bebc6` (and observed on deployed `bc98abda0c`). **Deployment mode** Self-hosted / Cloud server with plugin Runner task environment. ## What Changed - `server/src/services/native-runtime/native-session-executor.ts`: - Updated `priorRemoteSandboxLeasesEnded` to select `cleanupStatus` and treat a prior lease as ended when `(status === "released" || status === "expired" || (status === "failed" && cleanupStatus === "success")) && cleanupStatus !== "failed" && releasedAt !== null && providerLeaseId !== currentProviderLeaseId`. - Updated `executePaperclipNativeSessionAttempt` to fall back to `await controlPlane.loadSessionCheckpoint()` when `pluginCheckpointRetired && !existingWarmSession` and `persistedWarmSession` is absent, passing the resulting checkpoint to `providerSessionReplaceableAfterStateLoss`. - File-length note: `native-session-executor.ts` is an existing >1,000-line module; this PR makes a surgical +12 net-line fix inside the two existing functions rather than introducing a new file. - `server/src/services/native-runtime/native-session-executor.test.ts`: - Added 5 parameterized red/green regressions (`retires a finished per-turn plugin owner after a destroyed lease only when cleanup succeeded`) covering destroyed per-turn plugin leases, active-goal preservation (`replaceAfterConfirmedProviderStateLoss: false`), failed cleanup refusal, unverified (`null`) cleanup refusal, and same-provider-task refusal (`retirement_refused=prior_lease_active`). ## Verification - **Red (before production fix)**: - `pnpm --filter @paperclipai/server exec vitest run src/services/native-runtime/native-session-executor.test.ts -t "retires a finished per-turn plugin owner after a destroyed lease"` - Result: `2 failed | 3 passed` — both `destroyed-after-turn` and `destroyed-after-turn-active-goal` failed with `Error: runner_state_identity_mismatch: prior_owner_terminal_state_indeterminate; retirement_refused=prior_lease_active`. - **Red for second-order fix (after Part 1 only)**: - Same command failed `1 failed | 4 passed` — `destroyed-after-turn` retired cleanly into `continuity-breaks` and then failed expecting `replaceAfterConfirmedProviderStateLoss: true` (received `false`). - **Green (after both fixes)**: - `pnpm --filter @paperclipai/server exec vitest run src/services/native-runtime/native-session-executor.test.ts -t "retires a finished per-turn plugin owner after a destroyed lease|handles unconfirmed plugin checkpoint status on replacement lease"` → `9 passed`. - `pnpm --filter @paperclipai/server typecheck` → passed (`below`, `cycle`, `above`, `tests`, `test-tree-0..2`). - `pnpm --filter @paperclipai/server exec vitest run src/services/native-runtime/native-session-executor.test.ts` → `1565 passed | 7 skipped (1572)`. ## Risks - Low risk. No database schema or migration changes. - Fail-closed guarantees are preserved: a `failed` lease with `cleanupStatus: "failed"` or `cleanupStatus: null`, an unreleased lease (`releasedAt === null`), a `released`/`expired` lease with `cleanupStatus === "failed"`, or a lease matching `currentProviderLeaseId` all still return `false` from `priorRemoteSandboxLeasesEnded` and refuse retirement. - Existing already-persisted `status: "failed", cleanupStatus: "success"` lease rows from previous releases retire cleanly immediately upon deploy (upgrade-safe). - Unfinished goals still keep `replaceAfterConfirmedProviderStateLoss: false`. ## Model Used - Google Gemini (Antigravity agentic assistant) with tool use (file read/edit, shell execution, browser inspection). ## 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> |
||
|
|
cf0ba4d9ee |
fix(native): continue a resume the environment refuses in a fresh session (#22512)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Native agent runs can execute in an environment that a plugin driver provides. A run that continues a saved provider session submits the task with `resumeFrom` > - The driver can refuse that submit with `admission_rejected` (#20762 added this result). The reason is `account_binding_mismatch` when the agent's account changed after the saved session started. It is `session_state_unavailable` when the saved session state is not available > - Core records the refusal as `runner_task_admission_rejected`, fails the run, blocks the task and stops automatic retries. A person must click Retry, which only starts a fresh session > - The local adapters already continue in a fresh session when a resume cannot be honoured (for example "Codex resume session ... is unavailable; retrying with a fresh session") > - This pull request makes Core continue the task once, in a fresh provider session in the same workspace, when the driver refuses to resume a saved session for either reason. It uses the existing fresh-session retry machinery > - The benefit is that a resume the driver cannot honour no longer stops the agent's work and asks a person for a Retry that adds nothing ## Linked Issues or Issue Description Refs #20762 **What existing behavior does this improve?** The handling of an `admission_rejected` refusal on a native run that resumed a saved provider session, with the reason `account_binding_mismatch` or `session_state_unavailable`. **Current behavior** The run fails with `runner_task_admission_rejected`. The task becomes `blocked` with a board-owned hold that says "Automatic retries are stopped". Nothing continues the task until a person clicks Retry. **Proposed behavior** An environment driver can refuse to resume a session because its account binding changed or because its saved session state is unavailable. In either case, Core schedules one continuation in a fresh provider session in the same workspace. The continuation carries the usual fresh-session handoff context and tells the agent which reason applied. The task stays in its status and shows a scheduled retry. If the fresh session is refused too, the run stops as today. **Reason and benefit** A fresh session cannot meet the same refusal, because it supplies no `resumeFrom`. So an automatic continuation is safe and bounded, and the person has nothing to decide. The first version of this pull request covered only `account_binding_mismatch`. The reviewer decided that `session_state_unavailable` must continue too, to match the local adapters' "resume unavailable, retry fresh" behavior. ## What Changed - `native-resume-refused-continuation.ts` (new): the lane's reason code, limit (one continuation) and 5 s delay. It also has the continuation message and the fresh session's instruction. Both name the refusal reason. - `native-provider-capacity-retry.ts`: a new `materializeNativeResumeRefusedContinuation` lane on `materializeNativeFreshSessionRetry` (`forceFreshSession`, `freshSessionRetryContext`, liveness continuation context). It continues only when all of these are true: - the run's environment lease records the refusal with the reason `account_binding_mismatch` or `session_state_unavailable` - the same lease records a non-empty `runnerTaskResumeFrom`, so the run resumed a saved session - the run has no Stop request - the run is not itself this lane's continuation The shared materializer now counts attempts with `executionRetryAttemptCount(run, reason)`. For the four existing lanes this is the same value as before (`failureRetries`). - `execution-recovery-attempt.ts`: the new reason is an uncharged lane with its own counter, like `interrupted_preparation`. The refused run did no provider work. - `native-session-executor.ts`: in the terminal-failure transaction (issue, coordinator and run are locked), a `runner_task_admission_rejected` failure on a task the agent still owns tries the lane. When it schedules a continuation, the task is not blocked and no board hold is written. The coordinator's `failureDetail` gets `successorRunId` and the continuation message. Other recovery paths already step aside for `successorRunId`. - `run-dispatch/adapters/postgres.ts` and `heartbeat.ts`: the new reason joins the other native fresh-session lanes for retry classification and continuation-ownership checks. - `doc/plugins/PLUGIN_RUNNER_EXECUTION.md`: describes how Core handles `admission_rejected`. - A refusal of a run that did not resume keeps today's behavior. ## Verification - `npx vitest run src/services/native-runtime/native-resume-refused-continuation.integration.test.ts` (in `server/`): 8 tests pass. They cover: - for each reason, a resumed session gets one fresh continuation. The task is not blocked, no hold is written, the task shows `retry_scheduled`, and the scheduler promotes the continuation - the instruction names the reason - for each reason, a fresh-session refusal stays permanent - for each reason, the continuation's own refusal stays permanent - a stopped run gets no continuation - Red-green check: with only the executor change reverted, both continuation tests fail and the other six pass. - Neighbouring suites pass: `execution-recovery-attempt.test.ts`, `native-tool-receipt-limit.integration.test.ts`, `native-provider-capacity.integration.test.ts`, `native-agent-blocker.integration.test.ts`, `native-closed-session-retry.integration.test.ts`, `plugin-runner-task.test.ts`, `native-sandbox-disk-full.test.ts`, `heartbeat-retry-scheduling.test.ts`, `run-dispatch/adapters/postgres.test.ts`, `native-session-executor.test.ts`. - Server typecheck (`node scripts/typecheck-layers.mjs`) passes. - Not run locally: the full suite and the Runner release and eviction integration suites. CI runs them. ## Risks - Behavior change: two refusals that blocked the task now continue it automatically. The continuation is limited to one per refused resume, and a person's Stop prevents it. - A `session_state_unavailable` continuation starts a new provider conversation. The earlier conversation is not carried over, but the fresh-session handoff context and the workspace are. - The failed run still shows its `runner_task_admission_rejected` error. The coordinator's next action and the scheduled retry explain the continuation. - The lane is uncharged, so it does not use the chain's failure-retry budget. A later resume that is refused again can continue again, once. - 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 - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, in Claude Code with tool use and code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Paperclip <noreply@paperclip.ing> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
63fffa8fcb |
test(server): drop heartbeat run-log cases duplicated by the module suite (#23191)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - The heartbeat run-log pipeline redacts secrets and images from chunks with `compactRunLogChunk`, then truncates oversized chunks. > - Two suites cover this function: `server/src/__tests__/heartbeat-run-log.test.ts` and the module suite `server/src/services/heartbeat/run-log.test.ts`. Both run in the default general-server lane. > - Two of the four cases in the `__tests__` file repeat contracts the module suite already proves with stronger, exact assertions (image-data redaction with the exact 1024-character threshold and consistency; truncation with exact head/tail/omission output and a redaction-before-truncation ordering check). > - This pull request deletes the two duplicated cases and keeps the two cases with unique coverage (Paperclip credential-shape redaction and the long-base64 performance guard). > - The benefit is less duplicated test code and two fewer executions of the same production path with no loss of failure detection. ## Linked Issues or Issue Description No public issue exists. Problem description: duplicated test coverage for `compactRunLogChunk`. The `__tests__/heartbeat-run-log.test.ts` suite was checking image-data redaction and chunk truncation through `compactRunLogChunk`, while `services/heartbeat/run-log.test.ts` proves the same contracts with exact boundary assertions. ## What Changed - Deleted "redacts inline base64 image data from structured log chunks" from `server/src/__tests__/heartbeat-run-log.test.ts`. Retained coverage: `services/heartbeat/run-log.test.ts` "preserves the image omission threshold at %i characters" (exact 1023/1024 boundary) and "omits every large image consistently across repeated calls". - Deleted "truncates oversized chunks after sanitizing them" from the same file. Retained coverage: "keeps the existing head, tail, and omission count for a custom limit" (exact truncation output) and "redacts credentials and image data before deciding whether a chunk needs truncation" (ordering proof). - Kept "redacts Paperclip credential shapes before persisting run-log chunks" (unique PAPERCLIP_API_KEY env/JSON/flag and refresh-token shapes) and "redacts a tool call that writes base64 of source text without stalling" (performance guard) unchanged. ## Verification - `npx vitest run src/__tests__/heartbeat-run-log.test.ts src/services/heartbeat/run-log.test.ts` (in `server/`): 2 files, 26 tests passed. - `npx tsc --noEmit -p .` (server package): clean. - Both files are selected in the default general-server lane per `scripts/general-server-shard-durations.json`. - Full CI (typecheck, all lanes, Greptile) runs on this PR; local runs of the full suite were not performed. ## Risks Low risk. Deletion-only change to one test file; production code is untouched. If a future regression removes image redaction or truncation, the retained services-level cases fail at their assertions. ## Model Used GLM (Z.ai) — openrouter/z-ai/glm-5.3, used via the Paperclip runner for test-suite analysis and this change. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes: #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [ ] I will address all Greptile and reviewer comments before requesting merge Co-Authored-By: Paperclip <Paperclip-Paperclip@users.noreply.github.com> |
||
|
|
1847abcd91 |
refactor(test): remove test support orphaned by the nightly soak prune (#23142)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - The server test tree under `server/src/__tests__/` keeps suites, fixtures, and helper modules that support them. > - The nightly soak prune in #22831 removed 483 soak suites, but eleven of their support files stayed behind. > - These files have no importer left. No test selects them. They never run, but every contributor still reads, compiles, and typechecks them. > - This pull request deletes the eleven orphaned support files. Each one is proven unreferenced. > - The benefit is 531 fewer lines of dead test support, and a test tree that holds only live code. ## Linked Issues or Issue Description No public issue exists for this cleanup. The problem is described here. **What existing behavior does this improve?** Test suite maintainability and typecheck scope of `server/src/__tests__/` after the nightly soak prune (#22831). **Subsystem affected** server/ — REST API & orchestration services **Current behavior** Eleven test-support files under `server/src/__tests__/helpers/` and `server/src/__tests__/fixtures/` have zero importers since the prune in #22831 removed every suite that used them. They match no vitest include pattern, so they never execute. **Proposed behavior** Delete the eleven dead files. Keep every live fixture and helper. Add no new code. ## What Changed - Deleted five orphaned helpers: `file-delivery-daytona.ts`, `native-question-owner.mjs`, `observer-replay-report.ts`, `recovery-population.ts`, and `maintenance/idle-work-capture-probe.ts`. - Deleted six orphaned fixtures: `daytona-worker-lifecycle-sdk.mjs`, `online-workspace-e2d-protocol.mjs`, its `online-workspace-e2d-protocol.provenance.json` build receipt, `sandbox-creation-receiver.ts`, `plugin-worker-deadline.cjs`, and `plugin-worker-idle.cjs`. - Deleted 531 test/support LOC. No production code, no test entry points, and no assertions were removed. ## Verification - Repo-wide reference scan: each of the eleven file stems was searched across every source, manifest, workflow, tsconfig, and doc file in the repository. Zero references exist. The scan also covers spawn patterns, because plugin-worker and other fixtures are referenced by exact file name everywhere they are used. - Selection check: `server/vitest.config.ts` selects only `src/**/*.test.ts` and `scripts/**/*.test.mjs`. None of the eleven files matches, so no run loses a suite. - `pnpm verify` reported the eleven deleted paths and asked for the required CI lanes (`typecheck_release_registry`, `general_tests`, `verify_paperclip_runner`, `build`, `verify_serialized_server`, `e2e_shards`), as designed for source deletions. Required CI will cover them. - Focused local run: `pnpm --filter @paperclipai/server exec vitest run src/services/issue-continuation-summary.test.ts` — 2/2 tests passed. - Kept siblings verified live: `idle-work-capture.ts`, `blocker-stall-fixture.ts` (benchmark consumer), and `tool-profile-matching-fixture.ts` (documented benchmark) are referenced and were not touched. ## Risks - Low risk. Each deleted file had no importer, so no behavior or coverage can change. If a future suite needs one of these helpers, it is in git history. ## Model Used - GLM (model id `openrouter/z-ai/glm-5.3`), driving a Paperclip test-gardening agent: tool use, shell execution, repository-wide reference scans, and local vitest runs. Assisted by no other model. ## 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 <Paperclip-Paperclip@users.noreply.github.com> Co-authored-by: Paperclip <noreply@paperclip.ing> |
||
|
|
8aba5a575e |
test: retire duplicated workspace-inheritance and environment-form cases (#22391)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - The repository keeps its regression proof in Vitest suites. Two suites and one UI suite held duplicate test cases. > - The file `server/src/__tests__/issues-service.test.ts` has two describe blocks with the same name. Each block held one copy of a test about workspace inheritance from a source issue. The two copies differed only in the `projectId` input. > - The file `ui/src/pages/CompanyEnvironments.test.tsx` held byte-identical second copies of two tests about the SSH remote-auth option, inside the same describe. > - Duplicate registrations run the same production path twice. They add CI work and maintenance cost, and they give no new proof. > - This pull request removes the duplicate registrations. It keeps one registration for each contract, with the same assertions and fixtures. > - The benefit is less duplicated test code and fewer repeated case executions, with the same regression safety. ## Linked Issues or Issue Description No public GitHub issue covers this cleanup. The problem follows the enhancement template. **What existing behavior does this improve?** The behavior of the existing test suites. The suites `issueService.create workspace inheritance` (server) and `CompanyEnvironments — test provider button` (ui) still protect the same contracts, without duplicate registrations. **Subsystem affected** - `server/src/__tests__/issues-service.test.ts` — the workspace-inheritance cases of `issueService.create`. - `ui/src/pages/CompanyEnvironments.test.tsx` — the SSH environment form cases for the remote-auth option. **Current behavior** - Two describe blocks in `issues-service.test.ts` register a test with the same name. One copy passes `projectId` to `create()`; the other copy omits `projectId` and asserts that the follow-up inherits the project from the source issue. All other assertions are the same. - `CompanyEnvironments.test.tsx` registers two tests twice. The second copies are byte-identical to the retained copies. **Proposed behavior** - One `it.each([true, false])` registration covers the explicit and the implicit `projectId` input. The `projectId` inheritance assertion runs in both variants. - The byte-identical second copies in `CompanyEnvironments.test.tsx` are removed. The retained copies stay without changes. **Reason and benefit** The removal keeps every assertion and every fixture. The retained registrations execute the same production code and detect the same regressions. The change deletes 136 lines of test code and adds 55 lines. It removes 4 repeated case executions per run of the UI file (1 + 3 `it.each` rows) and removes 1 duplicated registration in the server file. Duplicate work was searched before this pull request was opened. No open or merged pull request touches these duplicate cases. ## What Changed - `server/src/__tests__/issues-service.test.ts`: the retained test now uses `it.each([true, false])` for the explicit and the implicit `projectId` input. The assertion `expect(followUp.projectId).toBe(projectId)` was moved from the deleted copy and now runs in both variants. The duplicate copy in the second describe block was deleted. No fixture changed. - `ui/src/pages/CompanyEnvironments.test.tsx`: the byte-identical second copies of `defaults new SSH environments to the agent's Paperclip account` and `preserves the remote-auth option when editing an existing SSH environment (saved=%s)` were deleted. The retained copies were not changed. ## Verification - Base revision: `201abacd6e` (master). Branch head: `9bbc77867a`. - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/issues-service.test.ts` — 155 tests passed (all suites of the owner file, real embedded Postgres, no name filter). - `pnpm --filter @paperclipai/ui exec vitest run src/pages/CompanyEnvironments.test.tsx` — 43 tests passed with this change; the same command at the base revision reported 47 tests. The 4 removed cases were byte-identical duplicates of retained cases. - Keeper control 1: with a temporary production change that copies the source issue's `executionWorkspaceId` to the follow-up, both `it.each` variants fail at `expect(followUp.executionWorkspaceId).toBeNull()`. The production change was restored after the check; the file matched the committed bytes. - Keeper control 2: with a temporary production change that skips the `projectId` inheritance from the source issue, only the `explicitProjectId=false` variant fails, at `expect(followUp.projectId).toBe(projectId)`. The production change was restored after the check. - `pnpm --filter @paperclipai/ui typecheck` passed. - The server package typecheck could not run on this host: the `cycle` layer of `scripts/typecheck-layers.mjs` needs more memory than this machine has, and `tsc` was stopped by the operating system (SIGKILL) on both attempts. This is a host limit, not a product failure. CI runs the same typecheck on this PR head. - CI runs the full test lanes on this PR head. The checks below are the required proof. ## Risks - Low risk. No production code changed. No test selection, routing, or CI configuration changed. - The server consolidation keeps the same number of scenario executions (two) through the same production path, so it reduces maintenance cost, not server CI wall-time. - The UI deletions remove 4 repeated case executions per run of the file. No measured CI wall-time claim is made from this change. ## Model Used - OpenRouter `z-ai/glm-5.3` (GLM), operated as the Paperclip "Test Gardener (GLM)" agent. Tool use: file search and edit, shell test runs, GitHub publication through the `gh` CLI. Context window size: not tracked by the operator. Reasoning mode: default. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [ ] I will address all Greptile and reviewer comments before requesting merge --- ## Update (2026-11-24 rebase) Master's #22679 deleted `ui/src/pages/CompanyEnvironments.test.tsx`, which made this branch conflict. The branch was rebased onto master `28aa32e7`: the obsolete UI-file deduplication was dropped, and this PR now carries only the server-side deduplication in `server/src/__tests__/issues-service.test.ts` (single commit `4c115486`). Everything written above about the UI file describes work that no longer exists in this PR. Co-Authored-By: Paperclip <Paperclip-Paperclip@users.noreply.github.com> |
||
|
|
aa76a16879 |
refactor(server): retire the native input boundary alias (#22299)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - `server/src/__tests__/native-runner-input-boundary.test.ts` is a two-line alias: a comment plus one import of `packages/paperclip-runner/src/contracts/native-execution.test.ts`. It contributes no assertion, setup, or configuration of its own. > - The alias was added in #12591 (2026-08-31), before the Runner package suites ran in required PR CI. A 2026-10-13 audit receipt retained it for exactly that reason: the package suite was omitted from the root default project list, so the alias was its only root-suite entry point. > - Since then, `verify_paperclip_runner` became a required PR job whose default matrix includes `test:typescript:vitest --package-lane=K/3` for K in 1..3 (plus a native-server lane), and those lanes partition the full package vitest inventory (`src/**/*.test.ts` in `packages/paperclip-runner/vitest.config.ts`) as a complete, non-overlapping cover. `src/contracts/native-execution.test.ts` therefore runs in exactly one required package lane on every full-CI PR. > - The same suite also executed a second time per PR inside the serialized server lane through this alias. That is now a pure duplicate execution, so this pull request deletes the alias. ## Linked Issues or Issue Description - **What existing behavior does this improve?** Test cost only. Production code does not change. - **Subsystem affected** `server` test selection; `packages/paperclip-runner` unchanged. ## What Changed - Deleted `server/src/__tests__/native-runner-input-boundary.test.ts` (2 lines: comment + import of the package-owned `native-execution.test.ts`). - No production changes. The retained owner `packages/paperclip-runner/src/contracts/native-execution.test.ts` is untouched and still selected by the required package lanes. - `scripts/general-server-shard-durations.json` still lists a 272 ms weight for the deleted path; the shard script reads durations with a `?? fallbackWeight` default, so a stale manifest key is inert and the measurement bot refreshes the manifest. Left unchanged to keep the diff minimal. ## Verification - Static evidence for safe removal: - Package lane coverage: `packages/paperclip-runner/vitest.config.ts` includes `src/**/*.test.ts`; `scripts/run-pr-vitest-lane.mjs` + `scripts/vitest-package-lanes.mjs` partition that inventory into complete non-overlapping lanes; `.github/workflows/pr-trusted.yml` runs `test:typescript:vitest --package-lane=1/3..3/3` and `--native-server` in the `verify_paperclip_runner` matrix, and the final validation job asserts each planned suite result for that job. - The alias adds no setup or separate assertion: its whole body is one import (2-line file). - Whole-repository reference search for `native-runner-input-boundary`: only `doc/plans/*` receipts, `packages/paperclip-runner/docs/design/standalone-thin-paperclip-adapter.md`, and the shard duration manifest mention it; no executable test-selection command, generator, or import references it. - Duplicate gate: no open pull request's diff touches `server/src/__tests__/native-runner-input-boundary.test.ts` or `packages/paperclip-runner/src/contracts/native-execution.test.ts` (checked via the pulls API for every open PR matching the names). PR #21980 (open, `codex/test-garden-duplicate-forward-reconciliation-row`) touches a different file (`workspace-runtime.test.ts`); not this routine's work. - Local runs: **not run** — this execution workspace ran out of disk during `pnpm install` (the `pnpm-lock.yaml` refresh bot lags the ACPX pin bump, so a frozen install fails at master HEAD and the `--no-frozen-lockfile` install filled the 10 GB disk). No local test or typecheck could run; the deletion is a test entry-point removal whose safety rests on the selection evidence above, not on a green local run. - Baseline comparison: master HEAD `440f96247b` had the same install blocker; nothing about this 2-line deletion can affect module resolution for the retained suites. ## Risks - Contributors running only the root `pnpm test` no longer execute the native-execution suite in that run; it still runs under `pnpm --filter @paperclipai/paperclip-runner test:typescript` (local) and in the required package CI lanes. This matches how every other `packages/paperclip-runner` suite is already routed. - CI savings are estimated, not measured: the shard manifest weights the alias at ~272 ms per server-lane run plus module transform cost, but no wall-time measurement of this PR's lane was taken. - Remaining audit candidates (retained, not deleted this run): `devtools/browser/src/live/transcript-model.test.ts` vs `src/browser/transcript-model.test.ts` (near-identical titles, but each exercises its own production module — possible production duplication, out of test-gardening scope); the three `execute.acp-fallback.test.ts` adapter copies (each mocks its own protocol); `runner-tool-results.live.test.ts` (opt-in live suite, skipped by default). ## Model Used GLM-5.3 (openrouter/z-ai/glm-5.3) driving the Paperclip Test Gardener agent. ## Checklist - [x] No production behavior changes - [x] No checks weakened; the retained owner suite is selected in required PR CI - [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] No documentation files added or modified |
||
|
|
5f1178b966 |
Fix first-agent skill setup racing an uncommitted installation (#23308)
## Thinking Path > - Paperclip manages AI agents and the skills they need for work. > - First-agent setup assigns the bundled operating and onboarding skills. > - An environment plugin can initialize those skills inside a transaction. > - Another request could share that transaction's refresh promise and read before its commit. > - The hire then rejected valid default skills as unknown references. > - This pull request scopes shared refresh work to each database handle and makes concurrent bundled creation idempotent. ## Linked Issues or Issue Description **What happened?** First-agent onboarding on a fresh hosted stack failed with `Invalid company skill selection (unknown references: ...)` after the user entered a Claude API key. The failure occurred during skill assignment, before a provider connection could be verified. The environment plugin initialized the bundled library inside its skill-install transaction. The hire request awaited the same company-wide refresh promise. That promise settled before the outer transaction committed. The hire's separate connection then read an empty library and returned HTTP 422. **Expected behavior** A hire resolves committed bundled skills even when another installer is active. A failed competing transaction must not leave the hire dependent on rolled-back work. Concurrent callers must retain one installed skill per key. **Steps to reproduce** 1. Create a company with no initialized skill library. 2. Start bundled inventory initialization inside a transaction and hold its commit. 3. Resolve first-agent skill selections through the ordinary database handle while initialization is active. 4. Let initialization finish, while the outer transaction is still open. 5. Observe the unknown-reference error from the separate connection. The added real-PostgreSQL regression controls these boundaries without real-clock sleeps. **Paperclip version or commit** Observed on `79dadd86551e4deb254163dd1f952f2908f1d351`. Reproduced locally on `79ef76757879`. **Deployment mode** Hosted Docker deployment. The underlying transaction race also applies to other deployments. Related: #22477 repaired a different first-agent skill upload failure. Searches of open and closed skill/onboarding and skill/transaction changes found no duplicate of this repair. ## What Changed - Store in-flight inventory refreshes by database handle and company. Service instances on the same handle still share work. Other connections and transactions refresh through their own visibility boundary. - Take the existing skill publication advisory lock before the bundled-create recheck. Reuse a concurrent installation once it is visible. Keep normal user-created skill conflict handling intact. - Recheck a shipped release under the skill-row lock before inserting its version. Reuse a matching release and reject a concurrent snapshot with different contents. - Keep the fix in the existing inventory and import owner. No schema, provider, UI, or public API changes are required. - Add commit and rollback regressions that hold the installer open until the competing caller attempts publication. Preseed the folder metadata and use inline packages for this specific creation race so unrelated folder and object-store locks do not settle the race first. - Add concurrent release-seeding cases for matching and corrupted snapshots. Existing tests cover shared refreshes, separate actor visibility, and revoked project access. ## Verification - The original commit/rollback regressions reproduced the unknown-reference HTTP 422 before the repair. - Review regression, red: both concurrent release-seeding cases reproduced PostgreSQL `23505` on `company_skill_versions_skill_release_idx` before the release recheck was added. - Creation-race test: removing the bundled-create recheck makes the tightened commit case fail with HTTP 409. The protected code passes. This proves the test reaches the concurrent-creation boundary. - Green: all six inventory-concurrency cases pass, including commit, rollback, matching release reuse, corrupt release refusal, same-handle coalescing, and separate actor visibility. - Final revision: `5ac8f4d7acc1a2fe5111935d892c5d57ef54b5a6`. All 277 tests passed across nine focused files: company skill service, runtime concurrency, runtime selection, environment skills, plugin-managed skills, managed content, agent skill routes, package upload, and bundled release validation. - `pnpm --filter @paperclipai/server typecheck` passed, including source and test layers, on the final source. - Test command: `pnpm exec vitest run server/src/__tests__/{company-skills-runtime-concurrency,company-skills-service,company-skills-runtime-selection,environment-skills,plugin-managed-skills,managed-skill-content,agent-skills-routes,skill-package-upload}.test.ts server/src/services/bundled-skill-release-validation.test.ts`. - `node scripts/check-test-budget.mjs --files server/src/__tests__/company-skills-runtime-concurrency.test.ts` and `git diff --check` passed. - Environment: local macOS arm64 with real embedded PostgreSQL. Tests use controlled gates rather than real-clock sleeps. - The previous head, `088b8f8822d5bc218f4e5e7cfcf61c510de0776d`, passed all 270 focused tests, server source/test typechecks, and [CI](https://github.com/paperclipai/paperclip/actions/runs/46488494810). The 4/5 review identified the release race and the test gap addressed here. The final revision has now passed fresh CI and review; the results are recorded below. - `pnpm verify --explain` selected 1,981 tests, with 1,978 retained conservatively. Focused local checks cover this repair; required CI supplies the broader typecheck, build, test, Runner, and browser coverage. - Staging diagnosis used the served Core SHA, bounded request logs, and read-only database queries. The logs and row timestamps match the reproduced transaction race. - Test code and service behavior document this internal invariant; no user-facing command or API contract changed. - A deployed onboarding retry with the fixed revision has not been run. This PR does not deploy the repair or validate the user's provider credential. - Current-head [Greptile review](https://github.com/paperclipai/paperclip/pull/23308#issuecomment-7288511940) is 5/5 on `5ac8f4d7acc1a2fe5111935d892c5d57ef54b5a6`. Both prior review threads are resolved. - Final [CI run, attempt 2](https://github.com/paperclipai/paperclip/actions/runs/46491251884/attempts/2) completed successfully on `5ac8f4d7acc1a2fe5111935d892c5d57ef54b5a6`. Scope: typecheck/release registry, build, native Runner checks, general tests, serialized server suites, and all 16 browser shards. GitHub reports the branch as clean and mergeable. - Attempt 1 lost the runners for [browser shard 5](https://github.com/paperclipai/paperclip/actions/runs/46491251884/job/142104554848) and [browser shard 12](https://github.com/paperclipai/paperclip/actions/runs/46491251884/job/142104554842). Those interrupted attempts are not passes. GitHub initially rejected targeted retries while the parent workflow was running. Both shards passed in attempt 2. ## Risks Different database handles now perform their own inventory refresh. The bundled-create lock prevents duplicate publication when these refreshes overlap. Same-handle coalescing and the existing access checks remain effective. The change does not relax unknown-skill validation or normal edit/create conflicts. No migration is needed. ## Model Used OpenAI GPT-6.1 Sol (`gpt-6.1-sol`) through the Codex harness, with xhigh reasoning effort and tool use. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [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> |
||
|
|
fa283aeea2 |
feat(plugins): let an environment plugin report its task's startup stage (#22970)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - A run's environment can come from a plugin, which runs the agent's task through environment task operations such as prepare and submit. > - The stacked pull requests below this one make Core publish each run's startup stage from the steps it times, and show that stage in the task view. > - Core cannot see inside a plugin's task operation. A slow step there, such as a stopped machine starting, shows as whatever stage Core was in when it called the plugin. > - This pull request lets an environment plugin report its task's stage, from the same closed list Core uses, while one of its task operations runs. > - The benefit is that the task view names the real reason a plugin-backed turn has not started yet, with no stages only plugins know about. ## Linked Issues or Issue Description No public issue exists. Stacked on #22956 (UI), which is stacked on #22953 (server). **Subsystem affected** Plugin SDK (`packages/plugins/sdk`), plugin host services and environment task runtime (`server/src/services`), and the plugin docs. **Problem or motivation** A plugin's environment task operation can take many seconds, for example when it starts a stopped machine. The task view keeps the stage Core showed when it called the plugin, so the wait has the wrong name. **Proposed solution** Add `ctx.environmentTasks.reportStartupStage({ taskId, stage })`. Core accepts a report only while one of that plugin's task operations for a run is in flight. The reported stage shows instead of Core's stage until the operation returns. **Alternatives considered** - Free-form status text from the plugin. It would not match Core's stages, and each plugin would word the same step in a different way. - Stages that only plugins can report. One shared list keeps Core and plugins aligned, so the task view needs no plugin-specific labels. ## What Changed - SDK: `ctx.environmentTasks.reportStartupStage({ taskId, stage })` and the `environmentTasks.reportStartupStage` host method. The call needs the existing `environment.drivers.register` capability. The test harness records reports in `startupStageReports`. - Server: the environment task runtime opens a reporting window for the plugin and task while each task operation for a run is in flight. Inside the window, the plugin's stage shows instead of Core's stage, and may be an earlier stage (for example `starting_environment` during submit). When the last operation returns, Core's stage shows again. - Server: Core ignores a report outside a window, for another plugin's task, with an unknown stage, or after the agent's turn starts. A report never fails the task operation. - Docs: `PLUGIN_ENVIRONMENT_TASKS.md` has a "Startup stages" section, and `PLUGIN_SPEC.md` lists `ctx.environmentTasks`. - `tests/runner-e2e/source-sdk-public-inputs.json`: regenerated for the changed SDK sources. ## Verification - `npx vitest run tests/host-client-factory.test.ts tests/testing-environment-tasks.test.ts` in `packages/plugins/sdk`: the capability gate and the harness record (26 tests pass). - `npx vitest run src/services/run-startup-stage.test.ts src/__tests__/environment-task-runtime.test.ts` in `server`: windows open and close per operation, overlapping operations, reports outside a window or after the turn starts are ignored, an earlier stage shows during the window, and a report from inside a real task operation reaches the run (78 tests pass). - `node tests/runner-e2e/source-sdk-public-inputs.mjs <head> --write` reports no changes. - `pnpm --filter @paperclipai/plugin-sdk typecheck` and `pnpm --filter @paperclipai/server typecheck` pass. - CI runs the full suite. ## Risks - Low risk. The call is new and optional. Plugins that do not call it see no change. - A plugin can only report for its own task, only while Core waits on one of its operations, and only from the shared stage list. It cannot change the stage after the agent's turn starts. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use (shell, file edits). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [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> |
||
|
|
76e3b7e172 |
feat(runs): track each run's startup stage for the board (#22953)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - When a run starts, Core claims it, prepares the host, acquires and prepares the execution environment, restores the saved session, sets up tools, and starts the agent's runner. > - The task view shows "Thinking" for all of that time, so a slow cold start looks like a slow model. > - Core already times each of these steps (`heartbeat.prepare.*`, `native.controller.*` and the native run trace), but nothing tells the board which step is running. > - This pull request adds a closed list of startup stages and a process-local tracker that follows those timed steps. It sends the current stage to the board as a live event and adds it to active run reads. > - The benefit is that the board can say what a run is doing before the agent's turn starts. The UI change comes in a stacked pull request. ## Linked Issues or Issue Description No public issue exists. **Subsystem affected** Run execution status (`server/src/services/heartbeat*`, native runtime trace) and the shared run types. **Problem or motivation** From the claim to the agent's first turn, the task view always says "Thinking". On a test instance over 24 hours, the median time before the first agent event was 10 to 50 seconds. Most of it was environment setup, session migration (median 0.3 s, P90 14 s) and tool setup (median 8 s, P90 18 s), not model time. A user cannot tell a slow start from a slow model. **Proposed solution** Name the startup steps that every execution environment goes through and report the current one. Derive the stages from the steps Core already times, so the stage and the trace spans cannot drift apart. **Alternatives considered** Free text from each environment, which gives inconsistent wording and lets an environment show arbitrary text. Grouping by where the work runs, which breaks the order because Core does host work both before and after it acquires the environment. ## What Changed - `packages/shared`: add `RUN_STARTUP_STAGES` (`getting_ready`, `starting_environment`, `preparing_workspace`, `restoring_session`, `connecting_tools`, `starting_agent`), the `heartbeat.run.startup_stage` live event type and its payload type, and the `startupStage` and `startupSessionResumed` run fields. - `server/src/services/run-startup-stage.ts`: a process-local tracker. One table maps timed step names to stages. A run only moves forward within one execution attempt. Startup ends at the agent turn, turn submission or first agent activity (native runs), or when the heartbeat enters a direct adapter. When startup ends, the stage clears but the attempt keeps its resumed-session flag until the attempt ends. The store is bounded (512 runs, and a 1 hour TTL while a stage shows). - The preparation timing helper (`measure`) and the native run trace (`start`, which `record` also uses) report each step to the tracker. The heartbeat starts tracking when a run starts executing and stops when the execution ends. The native executor reports a resumed provider session. - `tests/runner-e2e/source-sdk-public-inputs.json`: regenerated, because the pinned shared SDK sources changed. - `decorateHeartbeatRunRuntimeStatus` adds `startupStage` and `startupSessionResumed` to active run reads and clears them for ended runs. - The native session executor ends startup when a run that reattached after a restart sees its turn already under way: a replayed `turn.submitted` or `turn.started`, or agent output, including output that arrives before this attempt saw its own `turn.started`. ## Verification - `npx vitest run src/services/run-startup-stage.test.ts` (13 tests): stage order, the forward-only rule, skipped stages, the end of startup, unknown runs, the resumed session (also after the turn starts), a new attempt, company and agent checks, TTL and the size bound, the real timing helper and native trace hooks, and active run reads. - `npx vitest run src/__tests__/heartbeat-execution-configuration.test.ts`: a new case runs a registered direct adapter through real preparation on the test Postgres. Each run publishes `getting_ready`, `starting_environment`, `preparing_workspace`, then the end of startup, and no stage shows while the adapter runs. - `cd tests/runner-e2e && npx vitest run source-sdk-public-inputs.test.mjs source-sdk-public-type.test.ts source-sdk-evidence.test.ts` (59 tests) after the registry refresh. - The CI failure in `adapter-utils` `run-fault-matrix.test.ts` (`case_14c`) is in a package this change does not touch. It passed three times locally. - Existing tests near the change pass: `native-run-trace.test.ts`, `native-run-trace-context.test.ts`, `heartbeat/preparation-timing-context.test.ts`, `heartbeat-run-runtime-status.test.ts`, `realtime/live-event-delivery.test.ts` (108 tests). - `npx vitest run src/services/native-runtime/native-session-executor.test.ts -t "native startup stage after a restart|native resumed preparation timing"` (16 tests): a reattached run leaves startup on a replayed turn start and on new agent output. Both new cases fail without the fix. - `pnpm --filter @paperclipai/shared typecheck` and `pnpm --filter @paperclipai/server typecheck` pass. - CI runs the full suite. ## Risks - Low risk. The tracker is in memory only and is never persisted. A server restart clears it, and the board then shows what it shows today. No run, session or launch state changes shape, so no saved state needs a migration. - Every hook is wrapped so that a tracker error cannot fail a run or its trace. - The live event uses the existing `heartbeat.run.*` delivery rule: it needs a `runId` and the viewer's run read access. - One extra live event per stage change (at most about seven for each run attempt). ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use (shell, file edits, Honeycomb trace queries for the timing data). ## 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> |
||
|
|
e7ed0c2f93 |
fix(workspaces): reconcile project-derived workspace bindings when a task moves projects (#23293)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - When a task is created in a project without explicit workspace overrides, Paperclip derives `projectWorkspaceId`, `executionWorkspaceSettings`, and a project-derived `workspaceSelection` (`source: "project"`). > - Moving that unbound task to a different project via `issues.update` left the old project's `projectWorkspaceId` and `workspaceSelection` behind. > - Subsequent runs kept resolving back to the old project's workspace and storage owner, causing repeated workspace validation or storage-incompatibility failures even after the user moved the task to a compatible project. > - This pull request re-derives project-derived workspace bindings when an unbound task moves projects, and reconciles already-moved unbound tasks with stale `source: "project"` bindings at run admission while preserving explicit workspace selections and bound execution workspaces. > - The benefit is that moving an unbound task to a compatible project immediately lets it run on the new project's workspace without hidden stale-workspace failures. ## Linked Issues or Issue Description Related: #17552, #22849. **What happened?** When a task was created in a project, `issues.create` automatically set `projectWorkspaceId` and `workspaceSelection` with `source: "project"`. If the task failed before binding an execution workspace (`executionWorkspaceId === null`) and the user moved the task to a different project (for example from a Core-storage project to a plugin-storage project), `issues.update` updated `projectId` but left `projectWorkspaceId` and `workspaceSelection` pointing to the old project's workspace. Every subsequent run still resolved the old project's workspace and storage policy and failed. **Expected behavior** - Moving an unbound task whose workspace binding is project-derived (`source: "project"`, or a legacy `projectWorkspaceId` belonging to the previous project with no `workspaceSelection`) re-derives `projectWorkspaceId`, `workspaceSelection`, and `executionWorkspaceSettings` from the new project (or clears them when moving to no project or a sourceless project). - Explicit workspace selections (`source !== "project"`), bound execution workspaces (`executionWorkspaceId != null`), pending workspace selections, and tasks with an active running run or pending workspace recovery keep their current workspace binding. - Tasks already moved on an older release with a stale `source: "project"` binding pointing to a different project are reconciled at run admission before workspace preparation. **Steps to reproduce** 1. Create a Core-storage project A with a Git workspace and a plugin-storage project B with a Git workspace. 2. Create an isolated task in project A (so `issues.create` sets `workspaceSelection.source = "project"`). 3. Move the task to project B via `issueService.update(id, { projectId: projectB.id })`. 4. Before this fix, `projectWorkspaceId` and `workspaceSelection.selection.projectWorkspaceId` still point to project A's workspace. **Paperclip version or commit** Reproduced against `origin/master` at `2d764bebc6ed`. **Deployment mode** Self-hosted / Cloud server. Verified locally on macOS arm64 with embedded PostgreSQL. ## What Changed - `server/src/services/project-move-workspace-reconciliation.ts`: add focused helpers (`isProjectDerivedWorkspaceBindingStale`, `deriveProjectDefaultWorkspaceBinding`, `hasActiveTaskWorkspaceRunHolder`) shared between issue updates and run admission. - `server/src/services/execution-workspaces.ts`: add `reconcileProjectWorkspaceForProjectMove` (used by `issues.update`) and `reconcileStaleProjectWorkspaceAtAdmission` (used at run admission for already-moved tasks with stale `source: "project"` bindings). Keeping the shared reconciliation helpers in a sibling module avoids growing `execution-workspaces.ts` and `issues.ts` unnecessarily. - `server/src/services/issues.ts`: invoke `reconcileProjectWorkspaceForProjectMove` inside `issues.update` after `changesPrivacy` when `projectId` changes and no explicit workspace fields were supplied. - `server/src/services/heartbeat.ts`: invoke `reconcileStaleProjectWorkspaceAtAdmission` alongside `releaseAncestorWorkspaceBindingAtAdmission` at run admission, marking `workspaceSelectionChanged = true` when reconciled. - `server/src/__tests__/issue-project-move-workspace.test.ts`: add red-green database regressions for moving to another project, moving to a sourceless/null project, preserving explicit selections, preserving bound `executionWorkspaceId`, deferring mid-run moves, and reconciling already-moved tasks at admission. - `server/src/__tests__/agent-project-access.test.ts`: use `source: "explicit"` for the explicitly-retained-source denial test and add a companion test verifying `source: "project"` re-derives on project move. ## Verification - **Red (before production edits)**: - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/issue-project-move-workspace.test.ts` failed on `re-derives a project-derived workspace when moving an unbound task to another project` and `clears a project-derived workspace when moving to no project or a sourceless project` because `projectWorkspaceId` and `workspaceSelection` stayed pinned to the old project. - **Green (after production edits)**: - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/issue-project-move-workspace.test.ts src/__tests__/agent-project-access.test.ts` — 20/20 passed. - `pnpm --filter @paperclipai/server typecheck` — passed. - `pnpm --filter @paperclipai/server build` — passed. - `pnpm --filter @paperclipai/server exec vitest run src/services/heartbeat/workspace-preparation.test.ts -t "names incompatible Core project storage|rejects Core Git worktree preparation"` — 2/2 passed. - `pnpm --filter @paperclipai/server exec vitest run src/services/task-interruption-presentation.test.ts` — 82/82 passed. - `pnpm verify --explain` selected 1978/2333 files due to touching central server services; required GitHub Actions CI supplies the broad suite coverage. - Live deployment and recovery of previously affected tasks on hosted instances are outside this PR's scope. ## Risks - Low risk. Reconciliation is gated to unbound tasks (`executionWorkspaceId == null`, `workspacePendingSelection == null`) with no active run holder or pending workspace recovery, and never alters explicit (`source !== "project"`) workspace selections or bound files. - Moving a task to a project whose trust boundary currently denies the assigned agent will not fail the move; execution access remains enforced at run admission. ## Model Used - Google Gemini (Antigravity agentic coding assistant) with tool use, shell execution, and local test verification. Exact deployment model ID and context window are not exposed to the session. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge |
||
|
|
2d764bebc6 |
feat(customer-success): add runs.search (/read-v3) and structured platform run diagnostics (#22985)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Paperclip Cloud inspects tenant stacks read-only through `/api/customer-success/v1` > - Today, inspection can only read raw byte slices of one run log at a time, and platform guard or launcher errors inside agent shell commands leave runs marked `succeeded` with `exitCode: 0` and no `errorCode` > - Finding how many runs hit an error string requires downloading megabytes of raw logs and pulling customer prompts into agent context > - This pull request adds bounded, match-only `runs.search` and stack-wide `count` on `/read-v3`, plus closed-vocabulary platform run diagnostics recorded on runs and surfaced in `view: "summary"` > - The benefit is fast, privacy-preserving prevalence diagnosis without exposing raw customer prose or missing errors hidden inside succeeded runs ## Linked Issues or Issue Description **Subsystem affected** Server and shared contracts: `/api/customer-success/v1` inspection endpoints, shared inspection wire contract, and run-event platform diagnostics. **Problem or motivation** When a platform wrapper (such as the Git storage guard or GitHub credential launcher) fails inside an agent tool call, the outer agent run often still finishes with `status: "succeeded"` and `errorCode: null`. Investigating prevalence through customer-success inspection previously required paging raw `runs.log` byte ranges one run at a time, pulling customer prompts into context and making fleet-wide triage impractical. **Proposed solution** 1. Extend the shared customer-success wire contract (`packages/shared/src/customer-success.ts`) with `runs.search` (1 to 5 literal substrings, no regex, optional creation window, counts/co-occurrence/sample pointers only by default, redacted excerpts only when `companyId` and `includeExcerpts: true` are set) and stack-wide `count` on `/api/customer-success/v1/read-v3`. 2. Execute `runs.search` inside the existing read-only, repeatable-read transaction using in-database `strpos` matching over `heartbeat_run_events` plus `heartbeat_runs` error fields, falling back to chunked `RunLogStore` scans with overlap windows for legacy/non-native runs or runs without stored events. 3. Add a closed-vocabulary platform diagnostic detector (`packages/shared/src/run-diagnostics.ts`) that records deduplicated `platform.diagnostic` rows in `heartbeat_run_events`, attaches `diagnostics` to `view: "summary"` run reads, and optionally reports bounded PII-free diagnostic codes to Paperclip Cloud when a stack diagnostics capability is configured. **Alternatives considered** Paging raw `runs.log` slices from Cloud or the agent. That transfers megabytes of unrelated customer prose, hits rate limits, and still fails to surface known platform errors in structured run summaries. ## What Changed - `packages/shared/src/customer-success.ts`: add `INSPECTION_SEARCH_READ_PATH` (`"/read-v3"`), `runs.search` operation and strict parser bounds, optional `companyId` for `runs.search` (without excerpts) and stack-wide `count`, and `InspectionRunSearchResult` types. - `packages/shared/src/run-diagnostics.ts` & `packages/shared/src/index.ts`: add closed-vocabulary `RUN_PLATFORM_DIAGNOSTIC_CODES` and deterministic `detectRunPlatformDiagnostics()`. - `server/src/services/customer-success-run-search.ts`: implement bounded read-only `searchCustomerSuccessRuns()` with in-DB `strpos` event matching, overlap-window `RunLogStore` fallback, co-occurrence tracking, diagnostic aggregation, and opt-in secret-redacted excerpts. - `server/src/services/customer-success-inspection.ts` & `server/src/routes/customer-success.ts`: mount `/read-v3`, enforce versioned path gating, support stack-wide `count`, and attach `diagnostics` to `runs` `view: "summary"`. - `server/src/services/run-platform-diagnostics.ts`, `server/src/services/native-runtime/paperclip-control-plane-port.ts`, `server/src/services/agent-task-run-telemetry.ts`, `server/src/services/native-runtime/native-run-log-export.ts`: detect and deduplicate `platform.diagnostic` run events, exclude them from PRP log export, and emit bounded PII-free Cloud reports when configured. - `server/src/__tests__/customer-success.test.ts`, `server/src/__tests__/run-platform-diagnostics.test.ts`, `server/src/__tests__/customer-success-cloud.test.ts`, `server/src/__tests__/openapi-routes.test.ts`, `doc/CUSTOMER-SUCCESS-INSPECTION.md`: unit tests, coordinated PostgreSQL qualification coverage, OpenAPI route list update, and documentation. ## Verification - `pnpm --filter @paperclipai/shared build && pnpm --filter @paperclipai/shared typecheck && pnpm --filter @paperclipai/server typecheck` — passed. - `cd server && pnpm exec vitest run src/__tests__/customer-success.test.ts src/__tests__/run-platform-diagnostics.test.ts src/__tests__/openapi-routes.test.ts` — 78/78 passed. - `cd server && PAPERCLIP_INSPECTION_CLOUD_DIST=<cloud-dist> pnpm exec vitest run src/__tests__/customer-success-cloud.test.ts` — passed end-to-end against two live PostgreSQL databases, verifying `/read-v3` `runs.search`, `diagnostics` in run summaries, default non-waking fleet queries, and `fleet.diagnostics`. ## Risks - Low risk. All inspection reads remain inside repeatable-read, read-only transactions behind EdDSA Cloud permits and replay fencing. - Older tenants without `/read-v3` answer 404, so Cloud fails closed with `tenant_inspection_version_unsupported` during rolling upgrades. - `platform.diagnostic` rows stay in the instance database (`heartbeat_run_events`); Cloud reporting is a no-op unless Cloud explicitly delivers `PAPERCLIP_RUNTIME_DIAGNOSTICS_CAPABILITY`, and emits only closed enum codes and run/driver metadata (never customer prose). ## Model Used - Google Gemini 4 Neon (High) in Antigravity with tool use (shell, file editing, test execution). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing> |
||
|
|
429a004da5 |
Honor device sign-in expiry during onboarding (#23270)
## Thinking Path > - Paperclip connects agents to model providers. > - Onboarding starts a device login for OpenAI. > - The login starts its session clock before it acquires a sandbox. > - The command must stop by the deadline shown for the session. > - The wizard can then offer a fresh code when that session expires. ## Linked Issues or Issue Description **Subsystem affected** Subscription onboarding and displayed-code login. Refs #23268. **Current behavior** An unattended OpenAI login can show a generic failure at expiry. **Proposed behavior** Use the session deadline and show the same expiry message as Claude. Show “Waiting…” for OpenAI and “Waiting for code…” for Claude. ## What Changed Bound the command timer to the remaining session lifetime. Arm the host timer before the command can schedule its own timeout. Keep the outcome fixed during cleanup. Updated the OpenAI waiting label. ## Verification All 79 tests in the device login service, runner, and login card suites passed. These cover delayed sandbox setup, failure before expiry, and timeout at the deadline. ## Risks Early command failures still need their own failure state. The change preserves those failures and explicit cancellation. ## Model Used OpenAI GPT-6 with Codex repository and test tools. ## 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 |
||
|
|
629281b1e8 |
fix(test): eliminate Cloud Readiness timeouts in route imports and multi-page arbiter drain tests (#23160)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Post-merge `Cloud readiness` runs the full server test suite with `--retry=0` before publishing new Core Docker images. > - Five consecutive `Cloud readiness` runs on `master` failed over 22 hours because two test timeout patterns surfaced under multi-worker CI shards. > - First, `issue-activity-events-routes.test.ts` and `issue-comment-attribution-audit-routes.test.ts` dynamically import `server/src/routes/issues.ts` inside the first `it()` block, crossing the 15s `testTimeout` when 5 fork workers simultaneously hit Vite's transform server. > - Second, `native-status-arbiter-corpus.test.ts` seeds 103 rows sequentially in its multi-page drain tests, crossing 60s under 7-worker shared-Postgres load and causing `afterEach` to time out before restoring real timers. > - This pull request moves those module imports into `beforeAll`, aligns `server/vitest.config.ts` `testTimeout` with `hookTimeout` (30s), batches the 103-row fixture seeding with bounded concurrency, and guards timer restoration in `try/finally`. > - The benefit is green, deterministic post-merge `Cloud readiness` builds without weakening any test assertion or retry policy. ## Linked Issues or Issue Description **What happened?** Five consecutive `Cloud readiness` workflow runs on `master` failed and cancelled over a 22-hour window, blocking new Core image publication: - Three runs failed with `Test timed out in 15000ms` on the first test of `server/src/__tests__/issue-activity-events-routes.test.ts` (twice) and `server/src/__tests__/issue-comment-attribution-audit-routes.test.ts` (once) while dynamically importing `server/src/routes/issues.ts` under 5-worker parallel serialized shards. - Two runs failed in `server/src/__tests__/native-status-arbiter-corpus.test.ts` when `drains more than one reconstruction page without replaying settled reviews` timed out at `60000ms` during 103 sequential `seedReview()` calls, which also timed out `afterEach` (`30000ms`) before restoring `vi.useRealTimers()`. **Expected behavior** All server route and native status arbiter tests pass reliably on post-merge `Cloud readiness` (`--retry=0`) without cold-transform timeouts or leaked fake timers. **Steps to reproduce** 1. Run `Cloud readiness` (`release-verify.yml`) on `master` with `--retry=0` on 8-core runners (`maxWorkers=5` serialized shards, `maxWorkers=7` general-server shards). 2. Observe cold dynamic imports of `routes/issues.ts` inside `it()` crossing `15000ms` and the 103-row sequential seed test in `native-status-arbiter-corpus.test.ts` crossing `60000ms`. **Paperclip version or commit** `c57471459f` (`master`) ## What Changed - **`server/src/__tests__/issue-activity-events-routes.test.ts`**: Register module mocks and import `routes/issues.js` and `middleware/index.js` once in `beforeAll` (30s timeout) instead of calling `vi.resetModules()` and re-importing on every test; keep full `vi.clearAllMocks()` and mock defaults reset in `beforeEach`. - **`server/src/__tests__/issue-comment-attribution-audit-routes.test.ts`**: Pre-import `routes/activity.js` and `routes/issues.js` in `beforeAll` alongside embedded Postgres startup (30s timeout) instead of lazily importing inside `createApp()` on the first test. - **`server/vitest.config.ts`**: Increase `testTimeout` from `15000` to `30000` (matching `hookTimeout` and `teardownTimeout`) so parallel cold Vite transforms on 5-worker CI shards do not flake the first test in sibling route suites. - **`server/src/__tests__/native-status-arbiter-corpus.test.ts`**: Seed the 103 fixtures in both multi-page drain tests in bounded concurrent batches of 8, parallelize the final status assertions, allow `30_000ms` for multi-page `flush()`, and wrap `coordinator?.stop()` in `try/finally` in both `afterEach` hooks so `vi.useRealTimers()` and `vi.restoreAllMocks()` always run. ## Verification - `pnpm --filter @paperclipai/server typecheck` — passed - `pnpm exec vitest run --project @paperclipai/server server/src/__tests__/issue-activity-events-routes.test.ts server/src/__tests__/issue-comment-attribution-audit-routes.test.ts server/src/__tests__/native-status-arbiter-corpus.test.ts` — passed (`3/3` files, `189/189` tests; `issue-activity-events-routes.test.ts` ran in `3.95s` total and test 1 of `issue-comment-attribution-audit-routes.test.ts` ran in `445ms`) ## Risks - Low risk: test-only and Vitest timeout configuration changes. No production server behavior, schema, or API contracts are changed, and no test assertions or retry policies are weakened. ## Model Used - Google DeepMind Antigravity (Gemini 3.1 Pro, agentic tool use with shell 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) |
||
|
|
c57471459f |
feat(responsibilities): add routine filter and routine agent avatars (#23159)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work.
> - The experimental Responsibilities dashboard (`outline_v2`) lists a
person's areas and responsibilities as a clean outline.
> - Today, operators cannot filter the Responsibilities outline by
whether a responsibility has routines, and rows do not show which agents
are assigned to those routines.
> - Operators need a quick visual signal of which responsibilities
already have agent-run routines and a fast way to focus on
responsibilities with or without routines.
> - This pull request adds `routineAgentIds` to `ResponsibilityRollup`,
adds the shared toolbar filter icon with "Has routines" and "No
routines" options (defaulting to either), and displays slightly
overlapping agent avatars on the right side of responsibility rows that
have assigned routines.
> - The benefit is faster scanning of routine coverage across
responsibilities without leaving the outline view.
## Linked Issues or Issue Description
**What existing behavior does this improve?**
The Responsibilities dashboard (`outline_v2` view at
`/<prefix>/responsibilities`) and the `ResponsibilityRollup` response
returned by `GET /api/companies/:companyId/responsibilities`.
**Subsystem affected**
Cross-cutting (multiple of the above)
**Current behavior**
The Responsibilities dashboard header shows only a search box, total
counts, and the New area button. Each responsibility row shows only its
bar sentence or title, with no visual indicator of which agents are
assigned to its routines and no filter to narrow by routine presence.
**Proposed behavior**
The header adds the shared toolbar Filter icon button beside the search
box, opening a popover with "Has routines" and "No routines" options
(both unchecked by default so either is shown) and a Clear action. Each
responsibility row with one or more non-archived routines assigned to
agents displays those agents' avatars slightly overlapping on the right
side of the row (up to 4 avatars with a `+N` overflow indicator and a
tooltip listing agent names).
**Reason and benefit**
Operators scanning their responsibilities need to see at a glance which
responsibilities already have agents running routines and quickly filter
to responsibilities that still need routines set up (or only those with
routines).
**Breaking changes**
Additive field `routineAgentIds: string[]` added to
`ResponsibilityRollup`. Existing callers ignore unknown fields.
## What Changed
- Added `routineAgentIds: string[]` to `ResponsibilityRollup` in
`packages/shared/src/types/responsibility.ts` and refreshed the pinned
hash in `tests/runner-e2e/source-sdk-public-inputs.json`.
- Updated `responsibilityService.computeRollups` and
`buildResponsibilityRollup` in `server/src/services/responsibilities.ts`
to select `routines.assigneeAgentId` (ordered deterministically by title
and id) and deduplicate non-null assignees across non-archived member
routines (direct and project-linked) with no extra queries.
- Added `OutlineV2RoutineFilter` and `filterOutlineV2Groups` in
`ui/src/lib/responsibility-outline-v2.ts`.
- Added the shared toolbar `Filter` icon popover ("Has routines" / "No
routines", default either) and live filtered counts to
`ui/src/pages/Responsibilities.tsx`.
- Updated `ui/src/components/responsibilities/DashboardOutlineV2.tsx` to
filter groups, unfold matching areas while filtered, show an empty-match
state with a Clear filter button, and render slightly overlapping
routine-agent avatars (`size={20}`, `-space-x-1.5`, capped at 4 with
`+N`) on the right side of each row that has routines with assigned
agents.
- Added unit, embedded-Postgres integration, jsdom UI, and Storybook
coverage (`server/src/__tests__/responsibilities-rollup.test.ts`,
`server/src/__tests__/responsibilities.test.ts`,
`ui/src/lib/responsibility-outline-v2.test.ts`,
`ui/src/components/responsibilities/DashboardOutlineV2.test.tsx`,
`ui/src/pages/Responsibilities.outline-v2.test.tsx`, and
`ui/storybook/stories/activity/responsibilities.stories.tsx`).
## Verification
- `pnpm --filter @paperclipai/shared build` — passed.
- `pnpm --filter @paperclipai/server typecheck` — passed (all 7 layers).
- `pnpm --filter @paperclipai/ui typecheck` — passed.
- `pnpm check:token-gates` — passed (all 4 gates clean).
- Focused Vitest suites (194 tests across 10 files) — passed:
- `server/src/__tests__/responsibilities-rollup.test.ts` (18/18)
- `server/src/__tests__/responsibilities.test.ts` (37/37, embedded
PostgreSQL)
- `server/src/__tests__/responsibility-summaries.test.ts`,
`responsibility-summary-generator.test.ts`,
`responsibility-tools.test.ts`
- `ui/src/lib/responsibilities.test.ts` (41/41),
`responsibility-views.test.ts` (35/35),
`responsibility-outline-v2.test.ts` (15/15)
- `ui/src/components/responsibilities/DashboardOutlineV2.test.tsx` (2/2)
- `ui/src/pages/Responsibilities.outline-v2.test.tsx` (1/1)
- Manually verified live Storybook preview (`Dashboard view: Outline v2,
routine avatars & filter`) in dark mode across default, "Has routines",
"No routines", and "Clear" states, confirming avatar overlap for 1, 2,
and 3 agents and empty states for rows without routines.
- Note: `pnpm verify` exited with code `2` because
`tests/runner-e2e/source-sdk-public-inputs.json` changed; CI supplies
the full broad suite.
## Risks
- Low risk. `routineAgentIds` is computed from the existing
`memberRoutines` query in `computeRollups` (adding one column selection
and deterministic ordering, no new queries or schema migrations).
## Model Used
- Google Gemini 4 Neon (High) via Antigravity with tool use and code
execution.
## Checklist
- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [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>
|
||
|
|
9c1fd24642 |
fix(secrets): keep a connected account's saved sign-in from being deleted or disabled (#23139)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - Agents run with an AI account that a person connects, for example a
personal Claude subscription
> - Paperclip keeps the saved sign-in of a personal account as a value
of a user secret, and that secret shows on the Secrets page
> - A person can delete or disable that secret, or its value in My
secrets, and Paperclip does not stop them
> - Then the connection still shows as healthy, but every agent run that
uses it fails with "Reconnect this AI account"
> - The reconnect also refuses the changed sign-in slot, so the person
cannot repair the account in place
> - This pull request refuses to delete or disable a user secret or its
value while a connected account uses it, and tells the person to
disconnect the account instead
> - The benefit is that a cleanup on the Secrets page cannot silently
stop all agent runs
## Linked Issues or Issue Description
**What happened?**
A user deleted the user secret that holds the saved sign-in of their
personal Claude subscription. The Secrets page did not warn them. After
that, every agent run failed with "Reconnect this AI account"
(`configuration_incomplete`). The connection still showed as healthy and
stayed the default for the provider. When the user tried to reconnect,
Paperclip refused the personal reconnect because the sign-in slot was
changed. The user then added a new company-shared account. Agents that
use "my default" ignore company-shared accounts, so the runs continued
to fail.
**Expected behavior**
Paperclip does not let a person delete or disable a secret that a
connected account uses. The message names the account and tells the
person to disconnect the account instead.
**Steps to reproduce**
1. Connect a personal Claude subscription and make it your default.
2. Open the Secrets page. Find the user secret with the key
`ai_<grantId>`.
3. Disable it or delete it.
4. Assign a task to an agent that uses your default AI account.
5. The run fails with "Reconnect this AI account". The AI account still
shows as healthy.
**Paperclip version or commit**
`master` at
|
||
|
|
c72c468708 |
fix(github): a failed run's request waits for its automatic continuation (#23117)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Each GitHub request to a review bot gets a comment that must end in a real reply or an honest notice, and stay correct > - When a run fails with a cause the system continues automatically (restart class, setup before provider work, recovery runs), a new run follows within minutes > - Both settle paths marked the request's comment "This turn stopped before completing" and final as soon as the failed run ended, so the continuation's answer never reached that thread > - On staging, a Ponytail review run failed twice across a deploy; the automatic retry succeeded three minutes later and updated the PR review to 5/5, but the inline thread still says "stopped" > - This pull request makes the request wait, for up to 30 minutes, while the system's continuation is still expected > - The benefit is that a recovered task's thread shows its real outcome instead of a stale failure notice ## Linked Issues or Issue Description Refs #22672, #23049 **Describe the bug** A review run failed with `native_continuation_requires_reconciliation` (twice, across a deploy). The system's automatic retry then succeeded and updated the PR's main review comment. The inline thread for the request had already been set to the final notice "This turn stopped before completing" and was never updated. **Steps to reproduce** 1. A request's run fails with an error the system continues automatically. 2. The publication transport (`failRun`) or the terminal sweep settles the request as "stopped" and final. 3. The automatic continuation succeeds and publishes, but the thread is final and is not revisited. **Expected behavior** The thread waits while the continuation is expected, then shows the continuation's reply or a link to the latest response; it says "stopped" only if no continuation comes. ## What Changed - `response-run-state.ts`: `responseRunColumns` adds `continuesAutomatically` (the existing `continuesAutomaticallySql`), read in the same statements as the rest of the run state. - `response-execution.ts`: `awaitsAutomaticContinuation(run, latestRun)`: the failed run continues automatically, is still the task's latest run, and ended under 30 minutes ago (`GITHUB_CONTINUATION_WAIT_MS`). While true the outcome is `waiting`, and the result carries `awaitingContinuation`. - `terminal-response-work.ts`: such a request is not parked, so the sweep reads it again on later passes. - `chat-github-response-comments.ts`: `failRun` defers with a conflict while the continuation is awaited; once a newer run exists it is refused as before and the sweep settles the request. ## Verification - New test `waits for the automatic continuation of a failed GitHub request run` (recent): fails on master (the thread says "stopped"), passes here: `failRun` defers, the sweep keeps "Working on this…", then the continuation and a newer response settle it with the link. Second case (failure 31 minutes old) still settles "stopped". - Updated `reconciles a GitHub working comment when execution stops without a publication` to a failure older than the wait window, which is what it tests. - GitHub chat integration suites (response maintenance, finding threads, workflow, retry and recovery, publications): 140 passed. Server typecheck is clean. ## Risks - A failed run's thread now shows "Working on this…" for up to 30 minutes while a continuation is expected, instead of "stopped" at once. - Waiting requests are re-read on each sweep pass (bounded by the 30-minute window). ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use and code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [ ] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
c49e80da6c |
fix(voice): exclude voice transport from tool health sweep and clarify Speko callback opt-in (#23116)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Speko voice connections create a channel-scoped tool connection with `transport: "voice"` so the assigned agent can call the responsible person through `call_my_phone`. > - The background tool-connection health sweep excluded `chat_sdk` and `runtime_auth` transports, but omitted `voice`. > - Every 15 minutes, the sweep called `checkConnectionHealth` on active Speko connections, hit `unsupportedToolConnectionTransport()`, and overwrote their health state to `error`. > - In addition, when `call_my_phone` was not present in an agent's tools for a task, the Speko skill did not explain how to help the user check Call my phone opt-in, tool access, or task eligibility. > - This pull request replaces the duplicated negative transport filters with a single positive `HEALTH_SWEEP_TRANSPORTS` allowlist, repairs already-corrupted active Speko voice connections in bounded atomic batches (while preserving real errors), handles `transport: "voice"` safely in manual `checkConnectionHealth`, and updates the Speko skill guidance. > - The benefit is that active Speko voice connections self-heal and stay healthy instead of degrading into false errors every 15 minutes, and agents give accurate troubleshooting guidance when `call_my_phone` is absent. ## Linked Issues or Issue Description Refs #23052 **Describe the bug** Active Speko voice connections (`transport: "voice"`) are picked up by the scheduled tool-connection health sweep after 15 minutes and marked `healthStatus: "error"` with `"This connection has no supported tool integration. Add a supported account or MCP connection from Connectors."`. **Steps to reproduce** 1. Connect and activate a Speko voice endpoint. 2. Wait 15 minutes for the scheduled tool-connection health sweep (or call `sweepConnectionHealth({ staleAfterMs: 0 })` / `scheduledHealth.load(companyId)`). 3. Inspect the Speko `tool_connections` row. **Expected behavior** Voice channel connections (`transport: "voice"`) are excluded from the generic tool-connection health sweep via a shared positive transport allowlist, previously corrupted active Speko voice rows self-heal without clearing real errors, and manual health checks do not overwrite them to `error`. ## What Changed - Export `UNSUPPORTED_TOOL_CONNECTION_TRANSPORT_MESSAGE` from `server/src/services/tool-access/catalog/failures.ts`. - Export `HEALTH_SWEEP_TRANSPORTS`, `healthSweepConnectionWhere()`, and `repairUnsupportedVoiceConnectionHealth()` in `server/src/services/tool-access/catalog/health.ts`; use the shared allowlist in both `sweepConnectionHealth` and `connectionHealthSchedule.load`. - Repair active Speko voice connections previously marked with `UNSUPPORTED_TOOL_CONNECTION_TRANSPORT_MESSAGE` (only when the paired active Speko endpoint has `last_error IS NULL`), registering health/chat notifications before the batch update, running once per `connectionHealthSchedule` instance, and handling `transport: "voice"` safely in `checkConnectionHealth`. - Update `server/src/services/voice/speko-skill.ts` so agents check task eligibility, tool access, and the `Call my phone` (`Allow this agent to call me about my tasks`) setting when `call_my_phone` is absent. - Add red-green regression tests in `server/src/__tests__/tool-access-service.test.ts` (including `scheduledHealth.load`, `sweepConnectionHealth`, `checkHealth`, multi-batch repair, and real-error preservation) and `server/src/__tests__/voice-session-store.integration.test.ts`. ## Verification - `pnpm --filter @paperclipai/server exec vitest run -t "sweeps enabled active connection health|repairs active Speko voice connections|delivers Speko guidance to existing agents" src/__tests__/tool-access-service.test.ts src/__tests__/voice-session-store.integration.test.ts` (3 passed) - `pnpm --filter @paperclipai/server typecheck` (passed, 0 errors across `below`, `cycle`, `above`, `tests`, `test-tree-0`, `test-tree-1`, `test-tree-2`) ## Risks - Low risk: excludes non-tool transports from the generic MCP/REST health sweep via an explicit allowlist of the four supported transports (`mcp_remote`, `rest_api`, `local_stdio`, `plugin`), repairs only rows matching the exact unsupported-transport error message on active Speko endpoints with `last_error IS NULL`, and refines one sentence of Speko skill text. No schema migrations or breaking API changes. ## Model Used - Google Gemini (Antigravity agentic coding assistant with extended 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 - [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> |
||
|
|
f78a6f5ae3 |
fix(github): a run that ends without its own reply links the latest response (#23111)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Each GitHub request to a review bot gets a comment that must end in a real reply or an honest, useful notice > - #22798 made the terminal sweep link the latest response on the same pull request when a request's own run did not reply > - A second path settles the same comments: when a run finishes without a GitHub reply, the publication transport calls `failRun` with a fixed notice > - That path never looked for a newer response, so a thread could say "ended without publishing" while the PR already showed a fresh review > - This pull request gives `failRun` the same latest-response link > - The benefit is that both settle paths agree, and readers are pointed at the review instead of a dead-end notice ## Linked Issues or Issue Description Refs #22798, #22672 **Describe the bug** On a pull request the author replied "Fixed in …" on a review bot's inline finding. The bot re-reviewed and updated the PR's main review comment to 5/5, then a second run said no new review was needed. The inline thread settled to "This turn ended without publishing a final response. See the Paperclip task for details." instead of linking the updated review. **Steps to reproduce** 1. An inline request is answered by a run that publishes nothing on GitHub. 2. A response for the same task and PR was published after the request arrived. 3. The publication transport settles the run through `failRun` with the fixed notice. **Expected behavior** The thread says "See the latest response" with a link to it. ## What Changed - `server/src/services/chat-github-response-comments.ts`: for each request of the run, `failRun` looks up the latest response published for the task on the same pull request or issue since the request arrived (`githubLatestTaskResponseUrl`, scoped by base thread) and links it; otherwise it keeps the given notice. - New test in `github-review-response-maintenance.integration.test.ts`: an inline request whose run ends without a reply, with a newer assessment on the same PR, settles with the link. ## Verification - New test fails on master ("ended without publishing") and passes here. - `github-review-response-maintenance`, `github-review-workflow`, `github-retry-and-recovery` integration suites and the response-comment unit tests: 99 passed. Server typecheck is clean. ## Risks - One indexed lookup per request when a run settles without a reply; it reuses the same query and index as the terminal sweep. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use and code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [ ] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
7d850ad65e |
fix(github): a superseded automatic review finishes instead of asking a person (#23064)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - GitHub review bots run automatic reviews for a specific pull request head > - When the head has moved on, the review tools refuse the stale review and explain why > - That explanation said "an authorized person can request a manual review", so an agent can read it as a blocker owned by a person > - On staging, a review task recovered for an already-merged PR did exactly that: it marked itself blocked and asked the PR author to request a review > - This pull request makes the refusal say the review is no longer needed and that the task should finish as done > - The benefit is that stale or merged-PR reviews close cleanly instead of waiting on a person ## Linked Issues or Issue Description Refs #23049 **Describe the bug** A review-bot task for a PR merged three days earlier was continued by the lost-wait recovery (#23049). Its automatic review targeted the PR's old head. The review tool refused with "no newer automatic review is queued for it. An authorized person can request a manual review", and the agent blocked the task, naming the PR author or a maintainer as owner. **Steps to reproduce** 1. An automatic review request targets head A of a pull request. 2. The pull request moves to head B (or is merged) with no newer automatic review queued. 3. The agent calls a review tool; the refusal tells it a person can request a manual review, and the agent blocks the task. **Expected behavior** The agent finishes the task as done; a merged or closed pull request needs no review, and nothing waits on a person. ## What Changed - `server/src/services/chat-github-reviews.ts`: `supersededAutomaticReview` receives the pull request. For a closed or merged PR the refusal says no review is needed; otherwise it says the review is no longer needed (or that a newer automatic review is queued). In every case it tells the agent to finish the task as done and not to block it or ask anyone to request a review. The error details add `pullRequestClosed`. - Test in `github-review-publications.integration.test.ts` for a closed and an open pull request whose head moved. ## Verification - New test (`tells a superseded automatic review to finish instead of waiting on a person`, closed and open): fails on master (the old message asks for a person), passes here. - `github-review-publications` and `github-review-workflow` integration suites: 39 passed. Server typecheck is clean. - After deploy: a recovered review for a merged PR should finish as done instead of blocking. ## Risks - Wording change for one refusal; the reason code and retryability are unchanged. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use and code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [ ] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
2caedfe7b0 |
feat(voice): support outbound call messages, issue transcripts, and optional setup test for Speko (#23052)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work.
> - The Speko voice connection lets agents call a person's saved phone
number via `call_my_phone` and receive inbound phone calls that create
or continue tasks.
> - Outbound `call_my_phone` took no parameters, so the agent could not
speak a specific update or question when the person picked up, and
outbound call transcripts were not projected onto the bound issue.
> - Setup also blocked activation behind a mandatory two-turn browser
microphone test and failed with HTTP 400 when a Speko persona used a
cascade-only voice on `runMode: "s2s"`.
> - This pull request adds an optional `message` parameter to
`call_my_phone`, projects outbound and inbound phone call transcripts
onto the bound issue, derives inbound task titles from the caller's
request, falls back to a supported S2S voice on 400, and lets verified
Speko setups finish without a browser microphone test.
> - The benefit is that both agent-initiated phone updates (with
responses recorded in the issue) and inbound phone tasks work end-to-end
with reliable setup and full issue transcript visibility.
## Linked Issues or Issue Description
**What existing behavior does this improve?**
Speko voice connection setup (`POST
/api/chat-endpoints/:endpointId/finish`, `ChatEndpointSetup`), outbound
agent phone callbacks (`call_my_phone`), outbound/inbound phone
transcript projection (`voiceCallReports`), and incoming low-trust task
creation (`voiceInboundService`).
**Subsystem affected**
Cross-cutting (multiple of the above)
**Current behavior**
- `call_my_phone` accepts no arguments (`properties: {}`) and always
opens with `"Hi, this is your Paperclip agent calling as requested. Is
now a good time?"`.
- Outbound `call.pre_call` sets `idleRePrompts` to `"I'm still working
on it."` every 10 seconds.
- `voiceCallReports.projectTranscript` only writes the transcript
document onto issues for `guest_intake` sessions, omitting authenticated
outbound and inbound phone calls.
- Incoming `guest_intake` tasks always use the generic title `"Incoming
phone conversation"`.
- Activating a Speko connection requires completing a two-turn browser
microphone conversation before **Call my phone** and **Incoming calls**
settings become accessible.
- `configureVoiceDefaults` fails with HTTP 400 if the selected Speko
persona uses a cascade-only voice when switching to `runMode: "s2s"`.
**Proposed behavior**
- `call_my_phone` accepts an optional `message` string (1–2000 chars)
while still strictly rejecting recipient/phone arguments. Speko speaks
`message` immediately as `firstMessage` and instructs the voice model to
submit caller replies via `submit_request`.
- Outbound `call.pre_call` uses a 25-second conversational check-in
re-prompt instead of `"I'm still working on it."`.
- `voiceCallReports.projectTranscript` writes `"Outbound phone call
transcript"` / `"Phone conversation transcript"` onto the bound issue
for all phone calls (`outbound_phone` and `inbound_phone`), preserving
quarantine guards for `guest_intake`.
- Incoming `guest_intake` tasks derive a readable title from the
caller's first spoken request.
- Verified Speko connections can finish setup via `POST
/api/chat-endpoints/:endpointId/finish` (**Skip test & finish**) without
requiring a browser microphone test.
- `configureVoiceDefaults` falls back to S2S voice `"marin"` if Speko
returns HTTP 400 on `runMode: "s2s"`.
**Reason and benefit**
Makes both core phone workflows usable in production: agents can call an
opted-in person to deliver a concrete update and capture their spoken
response in the issue, callers can phone an agent to start a titled
task, and operators can complete Speko setup without a microphone or
cascade-voice failure.
**Breaking changes**
None. `message` is optional on `call_my_phone` so `{}` callers remain
compatible; existing recipient restrictions (`additionalProperties:
false`) and quarantine boundaries are preserved.
## What Changed
- Added optional `message` parameter to `call_my_phone` in
`server/src/services/voice/speko-agent-tools.ts`, threaded
`openingMessage` into `voice-session-service.ts`, `voice-prompts.ts`
(`buildOutboundPhoneVoicePrompt`), and `speko-provider.ts`
(`createPhoneSession`), and updated `speko-skill.ts`.
- Extended `voiceCallReports.projectTranscript` in
`server/src/services/voice/voice-call-reports.ts` to project phone call
transcripts onto the bound issue for `outbound_phone` and
`inbound_phone` sessions while keeping `guest_intake` quarantine
enforcement intact.
- Derived readable issue titles from the first `submit_request` text for
incoming `guest_intake` calls and refined outbound `call.pre_call`
`idleRePrompts` in `server/src/services/voice/voice-inbound-service.ts`.
- Added S2S voice fallback (`voice: "marin"`) on HTTP 400 in
`speko-provider.ts` (`configureVoiceDefaults`).
- Enabled optional test skip (`POST
/api/chat-endpoints/:endpointId/finish`) for verified Speko endpoints in
`server/src/services/chat-channels/setup-probes.ts` and added a **Skip
test & finish** button in
`ui/src/pages/apps/chat/ChatEndpointSetup.tsx`.
- Updated `packages/shared/src/app-definitions/speko.json` guidance
copy.
- Added unit and real-Postgres integration regressions in
`server/src/__tests__/speko-provider.test.ts` and
`server/src/__tests__/voice-session-store.integration.test.ts`.
## Verification
- `pnpm --filter @paperclipai/shared build && pnpm --filter
@paperclipai/server typecheck && pnpm --filter @paperclipai/ui
typecheck` — passed (0 errors across server layers and UI).
- `pnpm exec vitest run server/src/__tests__/speko-provider.test.ts
server/src/__tests__/speko-protocol.test.ts
server/src/__tests__/speko-call-report.test.ts
server/src/routes/voice-sessions.auth.test.ts` — 53/53 passed.
- `pnpm exec vitest run
server/src/__tests__/voice-session-store.integration.test.ts` — 133/133
passed (including new `call_my_phone` message + outbound transcript
projection, derived inbound title, and Speko finish-without-test
regressions).
- `pnpm exec vitest run ui/src/api/voiceSessions.test.ts
ui/src/components/voice/ ui/src/lib/voice-call-attempt.test.ts
ui/src/lib/voice-session-controller.test.ts
ui/src/lib/voice-transcript.test.ts
server/src/__tests__/chat-channels/slack-setup-and-registration.integration.test.ts`
— 161/161 passed.
- `pnpm run check:token-gates` — all 4 gates clean.
- Live local verification against Speko API + webhook-only Cloudflare
quick tunnel: verified Speko setup + `/finish` activation, live
`claude_local` MCP discovery of `call_my_phone` with `message`, live
Speko session create/inspect/end + signed `call.status`/`call.report`
callbacks through tunnel, and inbound `call.pre_call` + `submit_request`
creating a titled task.
## Risks
- Low risk. Additive optional schema field on `call_my_phone` (still
rejects unknown keys such as `to`). No database migrations required.
Transcript projection for authenticated calls writes only to the
session's bound issue under the existing per-session advisory lock. Live
PSTN audio still requires real-phone end-to-end confirmation after
staging rollout.
## Model Used
- Google Gemini 4 Neon (High) via Antigravity 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
- [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>
|
||
|
|
9c91c097bd |
fix(workspaces): run the full-disk read-only inventory's Git reads under the sandbox storage guard (#23095)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - A Cloud sandbox saves the agent's workspace when a run ends. When the sandbox disk is full, a read-only fallback copies the workspace without writing to the sandbox (#19465). > - Before the copy, the fallback runs an inventory of the workspace inside the sandbox. For each Git repository, the inventory runs `git rev-parse`. For an untracked `node_modules` or virtual environment, it also runs `git ls-files`. > - Cloud sandboxes now put a Git storage guard first on `PATH`. The guard reads its limits from three environment settings: `PAPERCLIP_GIT_MIN_FREE_BYTES`, `PAPERCLIP_GIT_MIN_FREE_INODES` and `PAPERCLIP_GIT_MAX_GROWTH_BYTES`. Without them, it refuses every Git command as misconfigured (exit 75). > - The inventory gives Git a minimal environment, and that environment drops the three settings. Thus the guard refuses the first Git read, and the inventory refuses every Git workspace as an unsafe source. > - This pull request keeps the guard's three settings in the inventory's Git environment. It also records a guard refusal by its own reason. > - The benefit is that a full-disk save of a Git workspace can complete again. If the guard refuses Git below its free-space floor, the recorded cause says so. ## Linked Issues or Issue Description Refs #19465, #19619, #22546, #22848 **What happened?** On staging, full-disk workspace saves fail again on releases since the sandbox image added the Git storage guard. Nine saves from 2026-11-24 to 2026-11-27 recorded this cause: `remote_workspace_sandbox_disk_full: ...; remote_workspace_readonly_capture_failed: stage=inspect reason=unsafe_source transport=provider_error`. All of them ran on releases that contain #22546. Thus the earlier `budget_exceeded` refusal is fixed, and this refusal is the next one. **Expected behavior** The read-only inventory runs Git with the same guard settings that normal capture gets. Normal capture keeps `process.env` for Git, so the guard is configured there. A Git workspace that normal capture could save passes the inventory. **Steps to reproduce** 1. In a Cloud sandbox, put the storage guard first on `PATH`. Set its three settings in the sandbox environment (the image sets them for the sandbox process tree). 2. Run `readonlyWorkspaceInventoryScript()` on a Git workspace. 3. On `master`, the script exits 1 with `remote_workspace_readonly_capture_unsafe`. With this change, it returns the inventory. **Relevant logs or output** `paperclip_git_storage_limit: Git's storage guard is unavailable or misconfigured; Git did not complete.` The guard writes this message when its settings are missing. ## What Changed - `readWorkspaceInventory` copies the three guard settings from `process.env` into its Git environment when they are set. It copies no other variable. The Git isolation settings do not change. - When Git fails and the guard wrote a `paperclip_git_storage_limit:` line, the inventory reports `remote_workspace_readonly_capture_git_storage_limit` for a free-space, inode or growth refusal. It reports `remote_workspace_readonly_capture_git_storage_guard_unavailable` for any other guard refusal. All other Git failures still report `remote_workspace_readonly_capture_unsafe`. - The sandbox script passes these two fixed tokens through, the same as the budget token. It still writes no error text or paths. - `captureReadOnlyWorkspaceArchive` records them as `reason=git_storage_limit` and `reason=git_storage_guard_unavailable`. - The sandbox command filter (`READONLY_INVENTORY_FAILURE`) forwards the two new tokens. Without this, `command()` drops them and the fallback records `reason=operation_failed`. ## Verification - New `remote-workspace-readonly-inventory-git-guard.test.ts`: it puts a stand-in guard on `PATH` that behaves like the sandbox guard. All 3 tests fail on `master` with `remote_workspace_readonly_capture_unsafe`. All 3 pass with this change. - New case in `remote-workspace-readonly-capture-cause.test.ts`: a guard refusal of `ls-files` is recorded as `stage=inspect reason=git_storage_limit` before any transfer. I could not run this case locally because the sandbox has no full dependency install. CI verifies it. - Real guard check: I ran the inventory script from `master` and from this branch on a real 857 MB Paperclip workspace (18,849 entries). It ran through the actual sandbox guard, with the sandbox's own settings in the environment. `master` refused the workspace with `remote_workspace_readonly_capture_unsafe`. This branch returned the inventory. - A strict TypeScript check of the changed inventory module passes. CI runs the full typecheck. ## Risks - Low risk. Only the three guard settings are added to the Git environment. Git still runs with no system or global configuration, no hooks, no optional locks and no lazy fetch. - The guard still applies its free-space floor. Below the floor, it refuses `ls-files`. Thus a Git workspace with an untracked `node_modules` or virtual environment can still fail the fallback when free space is below the floor. The recorded cause now shows `reason=git_storage_limit` for that case, so a follow-up can use real evidence. - Outside a guarded sandbox, the settings are not set and nothing changes. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), with tool use and code execution in a Paperclip 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: paperclipbugbot <356415228+paperclipbugbot@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
635ed5a364 |
fix(skills): start skill package transfer deadlines after the I/O queue admits them (#22615)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work.
> - Before a run starts, Paperclip copies each selected skill version
from skill package storage into a local cache.
> - Skill package reads share small I/O queues for each process. Each
queue has 2 active permits and 32 waiting slots.
> - Each read started its 180-second deadline before it waited for a
permit. A read that waited behind other transfers used up its deadline
in the queue.
> - On a busy host, a run then failed before its agent started with
"Failed to materialize the selected skill version: The operation was
aborted due to timeout". The next run did the same cold read and failed
the same way.
> - This pull request starts each transfer deadline when the queue
grants the permit.
> - The benefit is that a cold skill read under load waits for its turn
and then gets its full transfer deadline.
## Linked Issues or Issue Description
**What happened?**
A staging host had a burst of 21 run failures in 15 minutes. All runs
were in one company, and each failed with "Failed to materialize the
selected skill version: The operation was aborted due to timeout". The
runs woke at the same time after a provider usage limit reset. The skill
cache was cold.
**Expected behavior**
A run that waits for a skill package I/O permit gets the full 180-second
deadline for its own transfer. Time spent in the queue must not count
against that deadline.
**Steps to reproduce**
1. Make the skill package cache cold for three companies.
2. Stall the archive reads of two companies, so that they hold both
storage permits.
3. Resolve the runtime skills of the third company. Its reads now wait
in the queue.
4. Wait longer than the transfer deadline, then release the stalled
reads.
5. On `master`, the third company's skill resolves as missing with the
timeout message. Its own transfer would take milliseconds.
**Paperclip version or commit**
`master` at
|
||
|
|
1480f716c9 |
test(recovery): pin the 7-day window for chat setup failures; reattach listSuspects docs (#23063)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The assigned-work sweep now continues a blocked chat-channel task whose latest run failed in setup before provider work (#23059) > - Review on #23059 left three non-blocking points: the 7-day run-age limit had no test, the `listSuspects` doc comment was separated from its function, and the rule has SQL and TypeScript twins > - This pull request adds the missing boundary test and restores the doc placement > - The benefit is that widening or removing the age limit now fails a test, and the code reads as it did ## Linked Issues or Issue Description Refs #23059, #23051 **Describe the bug** Review follow-up, no user-visible bug. The 7-day limit on how old a setup failure may be for a chat task to continue automatically had no test, so a regression that widened or removed it would pass. The `listSuspects` doc comment was split from `listSuspects` by a new helper. **Steps to reproduce** 1. Remove the run-age condition from `latestRunFailedBeforeProviderWork` and `chatFailedBeforeProviderWork`. 2. The existing tests still pass. **Expected behavior** A test fails when the 7-day limit is removed. ## What Changed - `assigned-work-invariant.test.ts`: a recently blocked chat task whose setup failure ended 8 days ago is not a sweep suspect and is judged a conversation wait. The test helper takes an optional `blockedAgoMs` so the block can be recent while the run is old. - `assigned-work-sweep.ts`: the `listSuspects` pre-filter doc comment sits directly on `listSuspects` again; the SQL predicate's comment names its TypeScript twin and the test that covers both. ## Verification - `assigned-work-invariant.test.ts`: 35/35 pass. With the age condition removed from both twins, the chat setup-failure test fails (checked), then passes again with it restored. - Server typecheck is clean. ## Risks - Test and comment changes only; no behavior change. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use and code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [ ] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
4a9ecd3aca |
fix(recovery): continue blocked chat tasks whose run failed before provider work (#23059)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The assigned-work sweep continues open agent tasks that have nothing running and do not wait on a person > - #23051 made a setup failure before provider work continue automatically. Two review tasks on staging stayed blocked after it was deployed. > - Both tasks come from a chat channel (GitHub review bots). The sweep treats every chat-channel task as "waiting on a person's next message". It leaves these tasks out of its suspect list and gives them the `conversation` waiting reason. > - The agent never got the message, because its only run failed in setup before provider work. So the task waits on the system, not on a person. > - This pull request lets the sweep judge a blocked chat-channel task like any other task when its latest run failed in setup before provider work. > - The benefit is that these review tasks continue without a Retry, and so do the two tasks on staging. ## Linked Issues or Issue Description Refs #23051 **What happened?** After #23051 was deployed to staging, two GitHub review tasks stayed `blocked` with no new run. The sweeps ran, and other blocked tasks were continued. Each task's only run was legacy, failed with `setup_failed` during environment lease acquisition, and recorded `executionRecovery: { kind: "bootstrap", providerWorkStarted: false }` about 43 hours earlier. The tasks have `originKind: "chat_channel"`. **Expected behavior** The sweep continues a blocked task whose run failed before provider work, with bounded backoff, also when the task comes from a chat channel. **Steps to reproduce** 1. Create a chat-channel task assigned to an agent. Its only run fails with `setup_failed` before provider work. Block the task, with or without a board recovery hold. 2. Run the assigned-work sweep. 3. Before this change, `listSuspects` does not return the task. `evaluateAssignedWork` returns `waiting: conversation`, and no continuation is queued. ## What Changed - `server/src/services/recovery/assigned-work-sweep.ts`: - The suspect pre-filter still leaves chat-channel tasks out, except a blocked one whose latest run (by its assignee) failed in setup before provider work within the last 7 days (`latestRunFailedBeforeProviderWork`). - The facts loader no longer marks such a task as a conversation (`chatFailedBeforeProviderWork`, the TS twin). The latest-run read now also carries `executionRecovery`. - Agent chat conversations (`conversationAgentId`) are unchanged. Chat tasks whose agent may have started work still wait for their conversation. - Retry limits do not change. The per-task continuation allowance, the process-wide repair budget, and the company-wide automatic run brake apply as for every other sweep continuation. ## Verification - New red/green test in `server/src/__tests__/assigned-work-invariant.test.ts`: "continues a chat-channel task blocked by a legacy setup failure before provider work, with or without a hold". It uses the staging run shape: legacy, `setup_failed`, the same `resultJson` keys, the only run, about 43 hours old. Before the fix it failed (the tasks were not sweep suspects). After the fix, both the held task and the unheld task are continued. A chat task whose provider work may have started still waits (`conversation`), and an in-progress chat task is not a suspect. - In the same test, with the real heartbeat wake queue, the continuation of a held chat task is admitted as a new `issue_continuation_needed` run. - `npx vitest run src/__tests__/assigned-work-invariant.test.ts`: 35/35 pass. - `tsc --noEmit` for `server` passes. ## Risks - The sweep now acts on some chat-channel tasks. The scope is narrow: the task is blocked, its latest run is its assignee's and failed in setup before provider work, and the run ended in the last 7 days. Retries stay bounded by the existing per-task allowance and the company-wide brake. - After deploy, chat tasks blocked this way in the last 7 days are continued. The repair budget and the brake pace them. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude Code with tool use (shell, file edits, test execution). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] 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> |
||
|
|
4ea6fa61d5 |
fix(runner): re-prepare OpenCode launch inputs for a replaced provider session (#23050)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - Native OpenCode agents run in remote sandboxes. The controller gives
each Runner launch the provider-pack paths of Node, the OpenCode proxy
and the OpenCode executable
> - When exact resume of a provider session fails, Paperclip archives
the old session and opens a replacement session on the same backend
> - The archive drops the restored provider artifacts and their launch
paths. The replacement transport reads its launch inputs when it is
built, before its Runner is staged
> - A session restored from saved artifacts never selects a pack root,
so the replacement had no OpenCode executable. The run failed as
`runner_remote_provider_artifact_incompatible` and the task stayed
blocked. Other replacements launched from the pack root while the saved
receipt named the artifact root, and the next continuation's Runner
rejected that launch
> - This pull request stages the launch inputs again before the
replacement opens, reports a missing launch input as a retryable
controller gap, and continues tasks that older releases blocked this way
> - The benefit is that a GitHub review (or any OpenCode task) that hits
a resume failure continues by itself instead of needing a Retry
## Linked Issues or Issue Description
Refs #22981 (it scoped staged provider assets per provider; it did not
cause or fix this failure)
**What happened?**
An OpenCode review run on a hosted instance failed with
`runner_remote_provider_artifact_incompatible: OpenCode executable is
missing from the provider pack`. The task stayed blocked with no later
run. The run log showed the adopted Runner first refusing `run.attach`
with "OpenCode run.prepare launch does not match the runner-owned
qualified profile". The previous run of the same session had replaced
its provider session after a failed exact resume.
**Expected behavior**
A replaced provider session launches with the same verified OpenCode
inputs as any other launch, and the task continues without a person
pressing Retry.
**Steps to reproduce**
1. Run an OpenCode agent in a remote sandbox with durable harness
storage, so the session restores its provider artifacts.
2. Make exact resume fail, so the backend opens a replacement session.
3. Build the replacement transport. It has no `opencodeCommand`, and the
transport throws "OpenCode executable is missing from the provider
pack".
**Paperclip version or commit**
master at
|
||
|
|
50633695e7 |
fix(native-runtime): keep external chat waits when finalization retries after the run settles (#23049)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - Native runs can end by waiting for the next external chat message,
for example a GitHub review agent that waits for the next push
> - The finalizer must prove that the run still owns the task before it
records that wait
> - When the first status commit loses a lock race, the finalizer
retries later. By then the heartbeat has settled the run and released
the task execution
> - The retry then reads "authorization lost", so the task stays
`in_progress` with no run and no registered wait
> - This pull request keeps the wait authority for a settled run whose
own saved result is still being applied, and gives tasks already in this
state one bounded continuation
> - The benefit is that these tasks never sit idle with no next step
## Linked Issues or Issue Description
**What happened?**
A GitHub review agent published a review and yielded with a
`response_wake` continuation. The run ended with
`finalizationReasonCode: external_chat_response_wait_authorization_lost`
and `finalizationFailureCount: 1`. The task stayed `in_progress` with no
run for more than 16 hours. Earlier runs on the same tasks ended with
`external_chat_response_waiting`. Two tasks showed this on staging.
**Expected behavior**
The run records `external_chat_response_waiting`, and the task waits for
the next GitHub event. If the wait truly cannot be registered while chat
access is still allowed, the task gets one continuation instead of an
idle `in_progress` state.
**Steps to reproduce**
1. Start a native external-chat turn that yields with `response_wake`.
2. Hold a row lock that the status committer needs (for example the chat
endpoint) until the finalizer's quick retries end with
`status_cas_exhausted`.
3. Settle the run as `succeeded` and release the task execution, as the
heartbeat does.
4. Let the scheduled finalization retry run. The decision is
`external_chat_response_wait_authorization_lost`.
**Paperclip version or commit**
`master` at
|
||
|
|
4bf6a50e9d |
fix(recovery): continue tasks blocked by a setup failure before provider work (#23051)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - Task recovery continues interrupted work so that nobody has to press
Retry
> - A run can fail during setup before any provider work starts. For
example, the environment lease is refused because the sandbox snapshot
qualification is stale.
> - Such a run records the generic `setup_failed` code with
`executionRecovery: { kind: "bootstrap", providerWorkStarted: false }`.
Only the named transient setup codes counted as "continues
automatically", so the board escalation kept the task blocked behind a
manual Retry.
> - On staging, two review tasks stayed blocked this way for days, with
no later run.
> - This pull request makes every setup failure that ended before
provider work continue automatically, under the existing per-task
allowance and the company-wide automatic run brake.
> - The benefit is that a task that never started does not need a
person. Tasks already blocked this way continue after deploy.
## Linked Issues or Issue Description
**What happened?**
Two review tasks on staging failed in their first run with
`setup_failed` ("Failed to acquire lease for environment ...
sandbox_snapshot_qualification_required"). No provider work started.
Each task stayed `blocked` with a system-owned failed interruption and
`canRetry: true`. No automatic continuation followed.
**Expected behavior**
A system-owned setup failure before provider work continues
automatically with bounded backoff. The needed-retry rate is 0%.
**Steps to reproduce**
1. A task's first run fails in setup before dispatch with the generic
`setup_failed` code (for example, a refused environment lease).
2. Generic continuation recovery escalates the task to a board-owned
stranded hold and blocks it.
3. The assigned-work sweep leaves the task to the hold owner
(`left_to_hold_owner`), because `continuesAutomatically` accepted only
the named transient setup codes.
## What Changed
- `continuation-cause.ts`: add `isSetupFailureBeforeProviderWork` and
its SQL twin `setupFailureBeforeProviderWorkSql`. Each matches any
`SETUP_FAILURE_CODES` value, including `setup_failed`, when the run
recorded bootstrap with `providerWorkStarted: false`.
`continuesAutomatically` and `continuesAutomaticallySql` use them for
first-run failures.
- `stranded-hold-continuation.ts`: a stranded hold from such a failure
stays eligible for 7 days (`STRANDED_PRE_PROVIDER_SETUP_MAX_AGE_MS`, the
same as the sweep's `STALE_BLOCK_MS`). Other causes keep the 24-hour
window. Tasks blocked before this release are continued after deploy
without a Retry.
- `assigned-work-sweep.ts`: the suspect pre-filter uses the same longer
window for this failure class.
- Repetition stays bounded by existing mechanisms: the per-task
`continuationAllowance` (2, 4, 8, then 15-minute spacing, at most 6 an
hour), the process-wide repair budget, and the company-wide automatic
run brake. The brake already counts `providerWorkStarted=false` failures
as `failed_before_starting`.
## Verification
- New red/green test in
`server/src/__tests__/assigned-work-invariant.test.ts`: "continues a
task blocked by an environment setup failure before any provider work,
including one blocked days ago". It failed before the fix (the task was
not a sweep suspect). It passes after the fix. A task blocked 40 hours
ago is continued once, and the hold resolves as restored. Work that may
have started, or a run without the bootstrap record, stays with the hold
owner. A block older than 7 days is not touched.
- The existing "temporary setup failure" case now uses an 8-day-old
block for its "old" control, because pre-provider setup failures are now
eligible for 7 days.
- `npx vitest run src/__tests__/assigned-work-invariant.test.ts`: 34/34
pass.
- Related suites: fresh-continuation-fallback, run-completion,
task-retry, task-interruption-presentation, retries, dot-runner,
issue-recovery-actions, recovery-observability,
released-writer-escalation, github retry/recovery integration, and
others. 920 tests pass. Locally, `run-completion.test.ts` reports only
an `afterAll` embedded-Postgres teardown timeout. All of its 263 tests
pass.
- `tsc --noEmit` for `server` passes.
## Risks
- A generic `setup_failed` that is really deterministic is now retried
automatically. The per-task allowance (at most 6 an hour, with backoff)
and the company-wide brake bound this. These are the same bounds that
recovery runs failing with `setup_failed` already use. Person-owned
causes have their own codes and are not affected.
- After deploy, blocked tasks from the last 7 days that match this class
are continued. The process-wide repair budget and the brake pace them.
- The stranded notice text for `setup_failed` still mentions Retry. The
sweep continues the task within the settling grace, and its activity
says that no Retry is needed.
## Model Used
- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude
Code with tool use (shell, file edits, test execution).
## Checklist
- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] 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>
|
||
|
|
8f6d94169a |
fix(ci): run merge-queue Docker builds on standard runners and skip wait on AWS master (#23043)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The merge-queue Docker workflow (`.github/workflows/docker-merge-group.yml`) pre-builds the production image on `merge_group` so `docker.yml` can promote it on `master` > - #22993 routed `amd64` merge-queue builds to `cloud-release-32`, which does not admit `docker-merge-group.yml`, leaving every merge-queue build queued forever > - While those builds sat queued, `docker.yml` waited 3 minutes in `Find the merge-queue build of this commit` before falling back to its fast AWS release runner > - This pull request moves `docker-merge-group.yml` back to standard GitHub-hosted `matrix.runner` runners and sets `MERGE_GROUP_FIND_WAIT_MS=0` when `CORE_RELEASE_AWS_ENABLED=true` > - The benefit is that merge-queue builds actually execute and promote when ready, while fast AWS `master` builds never lose 3 minutes waiting behind slower GitHub-hosted merge-queue legs ## Linked Issues or Issue Description Refs #22993, Refs #23000 **Describe the bug** Every `docker-merge-group.yml` run stayed queued forever on `build (linux/amd64)` because the `cloud-release-32` runner group does not admit that workflow. In addition, `docker.yml` waited 3 minutes polling unfinished merge-queue runs even when running on the faster AWS release fleet (`CORE_RELEASE_AWS_ENABLED=true`). **Steps to reproduce** 1. Merge a PR through the GitHub Merge Queue on `master`. 2. Inspect the triggered `Docker merge-queue build` run and see `build (linux/amd64)` queued indefinitely. 3. Inspect the subsequent `Docker` run on `master` and see `Find the merge-queue build of this commit` spend 3 minutes waiting before falling back to a source build. **Expected behavior** `docker-merge-group.yml` starts on standard GitHub-hosted runners (`ubuntu-latest` / `ubuntu-24.04-arm`), and `docker.yml` promotes an already-completed merge-queue build immediately without stalling 3 minutes when running on the AWS release fleet. ## What Changed - `.github/workflows/docker-merge-group.yml`: restore `runs-on: ${{ matrix.runner }}` for `build` so `amd64` runs on `ubuntu-latest` instead of queueing on `cloud-release-32`. - `.github/workflows/docker.yml`: pass `MERGE_GROUP_FIND_WAIT_MS: ${{ vars.CORE_RELEASE_AWS_ENABLED == 'true' && '0' || '180000' }}` to `Find the merge-queue build of this commit`. - `scripts/merge-group-image.mjs`: add `resolveFindWaitMs(env)` (clamped to `[0, 180000]`, defaulting to `180000`) and use it in `find`. - `server/src/__tests__/docker-runner-workflows.test.ts` & `scripts/merge-group-image.test.mjs`: add guard tests for standard runner placement and `resolveFindWaitMs` / `MERGE_GROUP_FIND_WAIT_MS`. ## Verification - `vitest run server/src/__tests__/docker-runner-workflows.test.ts`: 15/15 passed. - `node --test scripts/merge-group-image.test.mjs`: 10/10 passed. ## Risks - Low risk. Restores standard runner placement (matching #23000) and keeps the exact promotion verification contract unchanged; fail-open fallback to source build is preserved. ## Model Used - Google Antigravity agent (Gemini / Antigravity coding harness with shell execution and tool use). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge |
||
|
|
5a7150be7e |
test(ai-connections): start the receiver lock-wait deadline after child startup (#23014)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The managed AI connections service refreshes single-use quota credentials and must handle a receiver process that dies after a token exchange > - A server test spawns a real child process to prove this case, but it fails every time in the server General tests shard 7/8 > - The failure blocks unrelated PRs, for example Dependabot PR #22604 > - The child starts through tsx. Loading `services/ai-connections.ts` takes about 20–30 seconds on a 4-CPU runner. The test gave the child only 25 seconds from spawn to reach the advisory lock, so the deadline ended before the child ran its first line > - This pull request starts the 25-second lock-wait budget only after the child reports that its imports are done, and it makes the test setup safe for a retry > - The benefit is that the shard passes again and the test still proves the same behavior ## Linked Issues or Issue Description Refs #22604 **What happened?** The test "requires sign-in after the receiver process dies with an exchanged but unsaved token" in `server/src/__tests__/ai-connections.test.ts` fails with `expected false to be true` at `expect(blocked).toBe(true)`. On the vitest retry, it then fails with `duplicate key value violates unique constraint "company_memberships_company_principal_unique_idx"`. **Steps to reproduce** Run `pnpm vitest run server/src/__tests__/ai-connections.test.ts -t "receiver process dies"` on a 4-CPU machine. The test fails after 25 seconds. Tracing showed that the child process never ran its first statement before the deadline. A direct run of the child helper took 32 seconds cold and 21 seconds warm, all in module loading. **Expected behavior** The test waits for the child to start, then gives the child 25 seconds to block on the advisory lock after one provider exchange. A retry does not collide with rows from the first attempt. ## What Changed - `helpers/quota-credential-process.ts`: The child writes `ready` to stdout after its imports finish. It writes no credential data. - `ai-connections.test.ts`: The test pipes the child stdout and waits up to 150 seconds for `ready` (or for the child to exit). Then the existing 25-second lock-wait loop starts. - `ai-connections.test.ts`: The test owner is now unique per attempt (`quota-receiver-process-loss-<uuid>`), so a retry does not hit the membership unique index. - The test timeout increases from 40 seconds to 200 seconds to cover the startup wait. ## Verification - Before the fix: `pnpm vitest run server/src/__tests__/ai-connections.test.ts -t "receiver process dies"` failed at line 933 (`expected false to be true`), the same as CI. - After the fix: the same command passes. - `pnpm vitest run server/src/__tests__/ai-connections.test.ts`: 167 of 167 tests pass. - CI: the server General tests shard 7/8 must pass on this PR. ## Risks Low risk. Only test code changes. The assertions about the exchange count, the saved credential, the recovery journal, and re-authorization do not change. The test can take longer on a slow runner because startup now has its own wait. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use (shell, file edits) 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> |
||
|
|
bde164de54 |
test(server): fix the issue-prefix collision and the shared-role idle timeout that fail Cloud readiness (#23013)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Every master commit must pass Cloud readiness before Docker publishes it and staging deploys it > - Two server tests failed there on and off, so master stopped reaching staging > - Both failures came from test setup that leaked across suites, not from product behavior > - CI runs each shard against one shared PostgreSQL server, and each suite gets its own database on it > - This pull request removes both leaks at their cause and adds a guard for each > - The benefit is that Cloud readiness no longer fails on these two tests, and Docker publishing and staging deploys continue ## Linked Issues or Issue Description **What happened?** Cloud readiness failed on master in two server test shards. 1. `antigravity-swarm.db.test.ts` failed with `duplicate key value violates unique constraint "companies_issue_prefix_idx"`. 2. `git-workspace-expiration.test.ts` > "rolls back when new history appears after capture without changing files" returned `skipReason: "inspection_failed"` instead of `restore_point_contents_changed`. This failed on four attempts of one master commit. **Root cause** 1. The swarm suite and 20 other suites made company issue prefixes from four random hex characters (65,536 values). The swarm suite seeds about 65 companies in one database, so one run of that file had about a 3% chance of a collision. 2. `isolated-remote-workspace-source-lock.test.ts` and `native-workspace-finalizer.test.ts` ran `ALTER ROLE <current_user> SET idle_in_transaction_session_timeout = '1s'`. In CI all suites in a shard share one PostgreSQL server and one role. So every new session in every other suite also got a 1-second idle-in-transaction limit. The expiration test holds a transaction open while it runs Git commands. PostgreSQL closed that session, and the expiration recorded `CONNECTION_CLOSED` as `inspection_failed`. The lock suite never reset the setting. **Steps to reproduce** 1. Run the lock suite and then the expiration test on one shared test server (the same layout CI uses). 2. Before this change, 40 of 40 runs of the expiration test fail with `CONNECTION_CLOSED`. **Expected behavior** A suite's session settings apply only to its own database. Seeded companies never share an issue prefix. ## What Changed - Added `uniqueIssuePrefix(tag)`, a shared test helper that adds 48 random bits (12 uppercase hex characters) to a tag. - Changed all 24 company seeds that used four or fewer random characters (21 files) to use the helper. Updated one identifier assertion in `cases-routes.test.ts` for the longer prefix. - Changed the two suites from `ALTER ROLE ... SET` to `ALTER DATABASE <current_database()> SET`, so the 1-second limit applies only to their own disposable database. The finalizer suite still resets it after its test. - Added two guard tests: one proves the helper does not repeat across 70,000 prefixes, and one fails if any test file changes a setting for a whole role. ## Verification - Deterministic red for the Git expiration failure: one shared test server, lock suite first, then the expiration test 40 times. Before: 40 of 40 failed with `CONNECTION_CLOSED`. After: 40 of 40 passed, and 40 of 40 passed again with 12 CPU-burning processes running. - The same failure appeared in PR CI before the fix: with the full suite on one shared server, 17 runs of the looped expiration test failed with `CONNECTION_CLOSED`. - Deterministic red for the prefix generator: the old four-character generator gives 42,898 distinct prefixes from 70,000 calls. The new helper gives 70,000. - `antigravity-swarm.db.test.ts`: 30 of 30 runs passed with 12 CPU-burning processes running. - All 21 suites that changed seeds pass locally. The two changed lock suites pass (72 tests). ## Risks - Low risk. Only test files change. The product code is unchanged. - Longer test prefixes make test issue identifiers longer. One assertion that checked a four-character prefix is updated. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude Code with tool use (shell, file edits, GitHub CLI) 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 - [ ] 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> |
||
|
|
e1f1252a53 |
fix(docker): use numeric owner ids for the linked node_modules copy (#23010)
COPY --link builds the layer without the destination image's /etc/passwd, so --chown=node:node failed with 'invalid user index -1' and the master image could not build. Use the production stage's USER_UID/USER_GID build args, which the base stage assigns to the node user. A guard test requires numeric owner ids on every linked copy, in any flag order and instruction case, and equal id defaults in the base and production stages. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-Authored-By: Devin Foley <devinfoley@users.noreply.github.com> |
||
|
|
2f9dc4a4c6 |
fix(runner): continue in a fresh provider session after a confirmed lost plugin checkpoint (#23007)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work.
> - Paperclip Runner agents can run on plugin task environments that
keep a warm Runner between turns.
> - PR #22973 changed one recovery case. When the plugin confirms that
the prior task stopped and kept no session state, Core now retires the
settled prior owner instead of refusing the follow-up.
> - The follow-up still asked the new Runner to resume the old provider
session. The new Runner has no saved state for it, so the run failed
with `native_session_recovery_failed: ... PRP provider resume state is
unavailable`.
> - A retry reads the same empty state, so the task cannot continue.
Recovery must work without a person.
> - This pull request lets that follow-up replace the provider session
only when the Runner positively proves the saved state is gone. It
continues in a fresh provider session and records a continuity break.
> - The benefit is that the task continues, and Cloud readiness `verify
/ Verify Paperclip Runner (server-integration)` passes again, which
unblocks the Core Docker image and staging deploys.
## Linked Issues or Issue Description
Refs #22973.
**What happened?**
On master, four tests failed on every run in the Cloud readiness
`server-integration` lane: the "missing state" case of
`plugin-runner-eviction-{claude,codex}-{abrupt,retired}.integration.test.ts`
("4 failed | 439 passed"). The follow-up run failed with
`native_session_recovery_failed:
NativeRunnerResumeStateUnavailableError: PRP provider resume state is
unavailable`. A temporary revert of
|
||
|
|
3f1632c7b7 |
fix(workspaces): keep the saved strategy for fresh managed-storage retries (#23002)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Master publishes its Core Docker image only after the "Cloud readiness" run passes for the same commit > - Readiness fails on every verified master commit since #22972 and #22969 merged together, so the Docker image does not publish and staging cannot deploy > - Two server tests fail every time. One failure is a real product regression. One failure is a test that checks a mock call instead of the real retry decision > - This pull request fixes the regression and makes the test check the real scheduler outcome > - The benefit is that a fresh Retry on a managed-storage project works again, and master readiness and the Docker publish can pass ## Linked Issues or Issue Description Refs #22972, Refs #22969 **What happened?** 1. #22972 changed the strategy that heartbeat workspace preparation sends to a workspace-storage plugin. It sends `project_primary` for every fresh retry (`fresh || useIsolatedTaskDirectory`), not only for a private isolated task directory. A storage plugin that declares only `git_worktree` refuses the fresh retry with "The storage plugin does not support this workspace mode or strategy". Before #22972, a fresh retry sent the project's resolved strategy. 2. #22969 added a `hermes_gateway` test. The test expects that completion does not call `scheduleBoundedRetryForRun` for an ambiguous `create_run` HTTP 429/5xx failure. But completion always sends a `transient_upstream` failure to the scheduler (the same test asserts this call for the shutdown case). The scheduler then refuses with `legacy_execution_requires_reconciliation`. So no retry happens, but the mock assertion fails every time. **Expected behavior** 1. A fresh retry on a managed-storage project keeps the project strategy (for example `git_worktree`). Only a private isolated task directory uses `project_primary`. 2. An ambiguous `hermes_gateway` `create_run` failure does not schedule a retry. **Steps to reproduce** 1. `pnpm exec vitest run server/src/services/heartbeat/workspace-preparation.test.ts -t "fresh: true"` on master fails with "The storage plugin does not support this workspace mode or strategy". 2. `pnpm exec vitest run server/src/services/heartbeat/run-completion.test.ts -t "hermes_gateway shutdown"` on master fails with `expected "vi.fn()" to not be called at all`. **Paperclip version or commit** `origin/master` at `d21ae3724f`. Both failures are deterministic. Readiness first verified a commit after these merges at `8e8c1b9f4d` and failed there. The readiness "passes" on `168253f74d`, `e18fe61c8f` and `a74b4f8196` skipped `verify` at admission, so they did not run these tests. ## What Changed - `server/src/services/heartbeat/workspace-preparation.ts`: send `project_primary` to the storage plugin only when `useIsolatedTaskDirectory` is set (outside remote authority). A fresh retry sends the resolved project strategy again. The host workspace config still uses `project_primary` for fresh retries, as before #22972. - `server/src/services/heartbeat/run-completion.test.ts`: in the `hermes_gateway` `create_run` 429/5xx cases, route the scheduler mock to the real `createHeartbeatRetries` scheduler. Every dependency after the reconciliation gate throws. The test asserts that each call returns `not_scheduled` with `legacy_execution_requires_reconciliation`, and that no retry run exists. ## Verification - Red on `origin/master` (`d21ae3724f`), local embedded Postgres: `workspace-preparation.test.ts -t "prepares managed storage"` gives 1 failed, 10 passed (the `fresh: true` case). `run-completion.test.ts -t "hermes_gateway shutdown"` fails 3 of 3 runs. - The same two failures occur in master Cloud readiness runs 45705488994, 45709638795, 45710758887 and 45716955324 (General tests server shards 8/10 and 10/10). - Green on this branch: `workspace-preparation.test.ts` 160/160 passed. `run-completion.test.ts` 174/174 passed. - `pnpm --filter @paperclipai/server typecheck` passed. ## Risks - Low risk. The product change restores the pre-#22972 strategy for fresh retries on the storage-plugin path only. The private isolated task directory path from #22972 does not change. - The test change does not weaken the safety check. It now checks the real scheduler decision instead of a mock call. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use and shell execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
d21ae3724f |
fix(ci): run Runner image amd64 jobs on standard runners again (#23000)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - The Runner image workflow (`.github/workflows/runner-image.yml`)
builds the Runner image on each master push that changes Runner inputs
> - The Docker workflow waits for this Runner image before it publishes
the Core image
> - #22992 moved the master `Build and check (amd64)` and `Write the
build cache (amd64)` jobs to the `cloud-release-32` larger runner
> - On master, the amd64 build job stays queued with the
`cloud-release-32` label and never gets a runner. Jobs from other
workflows (for example `cloud-migrator-artifacts.yml`) get runners on
the same label at the same time. The runner group does not admit this
workflow.
> - Because of this, no Core image publishes after #22992, and staging
cannot deploy newer commits
> - This pull request puts the two jobs back on `matrix.runner` (the
runners before #22992). It keeps the parallel provider-pack archiving
from #22992.
> - The benefit is that Runner image and Core image publishing work
again on master
## Linked Issues or Issue Description
Refs #22992
**Describe the bug**
On master, every `Runner image` run after #22992 has its `Build and
check (amd64)` job queued forever with the `cloud-release-32` label. No
runner picks it up. The Docker publish waits on it, so no Core image
publishes.
**Steps to reproduce**
1. Merge any commit to master after #22992.
2. Open the `Runner image` run for that push.
3. See `Build and check (amd64)` queued with no runner for 30+ minutes,
while jobs from other workflows run on `cloud-release-32`.
**Expected behavior**
The amd64 build job starts on a runner, and the Runner image and the
Core image publish.
## What Changed
- `.github/workflows/runner-image.yml`: the `build` and `cache` jobs use
`runs-on: ${{ matrix.runner }}` again. The file is now identical to its
state before #22992. The comment about the larger runner is removed.
- `server/src/__tests__/runner-image-workflow.test.ts`: the guard test
now asserts that the `build` and `cache` jobs use `matrix.runner` and do
not reference `cloud-release-32` or `CORE_PUBLICATION_RUNNER`.
- The parallel archive change in
`scripts/create-provider-pack-archive.mjs` and its test from #22992 do
not change.
To use `cloud-release-32` for this workflow again, an owner must first
let the runner group admit `runner-image.yml`. With the current group
settings, the job never started on that runner. This PR does not change
repository variables, runner groups or organization settings.
## Verification
- `git diff
|
||
|
|
079fb1fe63 |
fix(secrets): add env-name secret guardrails, collision recovery, and API-access clarity (#22982)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - Operators configure agent and environment secrets across Environment
variables and Secret access settings
> - Three common mistakes currently fail poorly or leak credentials:
pasting a token into an environment variable name passes validation and
leaks into run settings and logs, converting a plain environment
variable onto an existing secret name dead-ends with a disabled submit
button, and adding an API-access secret does not clarify that processes
will not see `$NAME` unless it is also bound as an environment variable
> - Secret configuration should prevent credential leaks by default and
recover cleanly from common setup mistakes
> - This pull request rejects and redacts secret-shaped environment
variable names and access aliases across shared, server, and UI layers,
adds "Use existing secret" and "Save as new version" recovery actions on
secret name collisions, and explains API-only vs `$NAME` delivery with
an "Also bind as env var" quick action
> - The benefit is safer secret handling with zero raw token leaks in
errors, settings, or logs and a smoother operator workflow
## Linked Issues or Issue Description
**What happened?**
Three issues occur when operators configure agent and environment
secrets:
1. Pasting a credential token (for example `github_pat_...`, `ghp_...`,
or `sk-...`) into an environment variable Name field passes
`^[A-Za-z_][A-Za-z0-9_]*$` for underscore-based tokens (such as
`github_pat_...` and `ghp_...`) or echoes the raw token in the server
error message for dashed tokens (such as `sk-...`). Existing redactors
also scrub only values, not secret-shaped object keys, so legacy or
rejected payloads leak the token in run settings and logs.
2. Converting a plain environment variable to a secret via
`ConvertToSecretPopover` (or creating a secret via
`CreateSecretPopover`) disables submission with `"A secret with this
name already exists"` whenever the suggested name already exists,
forcing the operator to cancel and switch flows manually.
3. Binding a secret under `Secret access > API access (no env var)` does
not state clearly that agent processes and shell scripts will not see
`$NAME` unless the secret is also bound under Environment variables, and
provides no quick action to add the matching environment variable
binding.
**Expected behavior**
1. Both UI and server reject secret-shaped environment variable names
and access aliases with an actionable error that never echoes the token,
mask accidental token input immediately in the UI, and redact
secret-shaped keys in adapter configs, event payloads, command/text
redaction, and HTTP 4xx/5xx request logs.
2. When a secret name already exists in `CreateSecretPopover` /
`ConvertToSecretPopover`, the popover lets the operator bind the
existing secret directly or save the typed value as a new version
(rotate) without dead-ending.
3. `AgentSecretAccessEditor` clearly explains that API-access secrets
are not injected as `$NAME` in the process environment and offers an
`"Also bind as env var"` quick action for API-only bindings.
**Steps to reproduce**
1. Open an agent's Secrets & variables settings and paste a GitHub
fine-grained PAT (`github_pat_...`) into an environment variable Name
field and save; observe that it is accepted and returned verbatim in
redacted adapter config / logs.
2. Create a company secret named `gh_token`, then add a plain env var
`GH_TOKEN` with a value and click "Store as secret"; observe the
disabled `"Store & bind"` dead end.
3. Bind a secret under `Secret access > API access (no env var)` and
observe that no guidance mentions `$NAME` visibility for
processes/scripts and no quick action exists to also bind it as an
environment variable.
**Paperclip version or commit**
Reproduced on `origin/master` commit
`2d065677959b585065ff3fec8718156a4cf6f41d`.
## What Changed
- **Shared credential-token detection
(`packages/shared/src/validators/secret.ts`,
`packages/shared/src/validators/index.ts`,
`packages/shared/src/index.ts`)**: Exported `ENV_VAR_NAME_RE`,
`looksLikeCredentialToken`, `SECRET_SHAPED_ENV_NAME_ERROR`, and
`SECRET_SHAPED_ACCESS_ALIAS_ERROR` as a single source of truth shared by
`adapter-utils`, `server`, and `ui`. Updated pinned registry
`tests/runner-e2e/source-sdk-public-inputs.json`.
- **Server validation and defense-in-depth redaction
(`server/src/services/secrets.ts`, `server/src/redaction.ts`,
`server/src/middleware/redact-sensitive.ts`,
`packages/adapter-utils/src/command-redaction.ts`)**:
- Rejected credential-shaped env var names and `access.*` aliases in
`normalizeEnvConfig`, `normalizeAdapterConfigForPersistenceInternal`,
`assertSecretBindingConfigPath`, `resolveEnvBindings`, and
`resolveAdapterConfigForRuntime` without echoing the raw token.
- Redacted secret-shaped object keys in `redactAgentAdapterConfig`,
`sanitizeRecord`, and HTTP log `redactSensitive`, and expanded
`command-redaction.ts` / `redaction.ts` token patterns and hints to
cover `github_pat_`, `sk_live_`/`sk_test_`, `rk_live_`/`rk_test_`, Slack
(`xox*-`), AWS (`AKIA`/`ASIA`), Google (`AIza`), and GitLab (`glpat-`)
tokens.
- **UI env-name guardrails
(`ui/src/components/environment-variables-editor/sensitive.ts`,
`model.ts`, `Row.tsx`, `index.tsx`,
`ui/src/components/AgentSecretAccessEditor.tsx`)**:
- Flagged credential-shaped variable names and access aliases
immediately with an inline error, masked the input (`type="password"` +
`ANALYTICS_NO_CAPTURE_CLASS`), redacted credential-shaped names in the
unsaved-changes summary, disabled inline Save while present, and dropped
credential-shaped aliases from emitted access maps.
- **Plain-to-secret collision recovery
(`ui/src/components/environment-variables-editor/CreateSecretPopover.tsx`,
`Row.tsx`, `index.tsx`, `ui/src/components/AgentSecretAccessEditor.tsx`,
`ui/src/components/AgentConfigForm.tsx`,
`ui/src/pages/CompanyEnvironments.tsx`,
`ui/src/components/ProjectProperties.tsx`)**:
- Replaced the dead-end duplicate-name error in `SecretPopoverForm` with
an inline recovery panel offering `"Use existing secret"` and `"Save as
new version"` (when active and rotatable), wired to `secretsApi.rotate`
across agent, environment, and project editors.
- **API-access vs `$NAME` clarity
(`ui/src/components/AgentSecretAccessEditor.tsx`,
`ui/src/lib/secret-delivery.ts`,
`ui/src/components/AgentConfigForm.tsx`)**:
- Clarified under `API access (no env var)` that processes and shell
scripts will not see `$NAME` unless bound under Environment variables
above, and added an `"Also bind as env var"` quick action on API-only
secret summaries wired to `AgentConfigForm`.
- **Tests**: Extended existing owner suites
(`server/src/__tests__/redaction.test.ts`,
`server/src/__tests__/redact-sensitive.test.ts`,
`server/src/__tests__/agents-adapter-config-user-secret.test.ts`,
`ui/src/components/environment-variables-editor/model.test.ts`,
`ui/src/components/environment-variables-editor/EnvironmentVariablesEditor.test.tsx`,
`ui/src/components/AgentSecretAccessEditor.test.tsx`).
## Verification
- `pnpm vitest run
ui/src/components/environment-variables-editor/EnvironmentVariablesEditor.test.tsx
ui/src/components/AgentSecretAccessEditor.test.tsx
ui/src/components/environment-variables-editor/model.test.ts
ui/src/components/environment-variables-editor/sensitive.test.ts
server/src/__tests__/redaction.test.ts
server/src/__tests__/redact-sensitive.test.ts` — 6 files, 149/149
passed.
- `pnpm vitest run --hookTimeout=120000 --testTimeout=120000
server/src/__tests__/agents-adapter-config-user-secret.test.ts` — 1
file, 6/6 passed (embedded Postgres route test verifying HTTP 422
rejection without token echo for `github_pat_`, `ghp_`, and `sk-` env
var names).
- `pnpm vitest run packages/adapter-utils/src/command-redaction.test.ts`
— 1 file, 43/43 passed.
- `pnpm --filter @paperclipai/shared typecheck && pnpm --filter
@paperclipai/adapter-utils typecheck && pnpm --filter
@paperclipai/server typecheck && pnpm --filter @paperclipai/ui
typecheck` — PASS (0 errors, Storybook catalog clean).
- `pnpm check:token-gates` — PASS (all 4 token gates clean).
- `node scripts/check-test-budget.mjs --files
server/src/__tests__/redaction.test.ts
server/src/__tests__/redact-sensitive.test.ts
server/src/__tests__/agents-adapter-config-user-secret.test.ts
ui/src/components/environment-variables-editor/model.test.ts
ui/src/components/environment-variables-editor/EnvironmentVariablesEditor.test.tsx
ui/src/components/AgentSecretAccessEditor.test.tsx` — PASS.
- `pnpm verify --base
|
||
|
|
a74b4f8196 |
feat(retry): let a board user grant one agent the task Retry (#22988)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work.
> - When a run stops in a state that needs board approval, Paperclip
holds the task until a board user presses Retry (`POST
/api/issues/{id}/retry`).
> - Some companies run an operations agent that reviews stopped tasks
and identifies routine Retries, but the route currently rejects every
agent with `403 Board access required`.
> - The only workaround is sharing a board key with the agent, which
grants unrelated board powers and hides which agent requested the Retry.
> - This pull request adds one narrow, opt-in permission key
(`tasks:retry`) that a board user can grant to a named agent so the
agent can call `POST /api/issues/{id}/retry` as that person, under all
existing gates and a per-task daily cap.
> - The benefit is that routine Retries stop waiting on manual clicks
while preserving least privilege, existing pause/budget/hold gates, and
full audit attribution for both the agent and the granting person.
## Linked Issues or Issue Description
- Closes #21633
- Supersedes #21634 (rebased cleanly onto current `master` with synced
SDK public input pins, OpenAPI `429` response documentation, and
additional route integration coverage for pause gates, revoked grants,
inactive grantors, cross-company isolation, and chat tasks)
- Refs #20081 and #18599 (broader delegate proposals; this change stays
narrow to one action, one grant per agent, and a per-task daily cap)
## What Changed
- `packages/shared/src/constants.ts`: add `tasks:retry` to
`PERMISSION_KEYS`. New agents do not receive it by default.
- `server/src/services/agent-task-retry.ts` (new):
- `agentTaskRetryActor`: resolves the agent's unscoped `tasks:retry`
grant and the active same-company board member who saved it. Grants
without a granting user (for example, agent-written rows), grants saved
with a scope, revoked grants, and inactive grantors return `null` and
fail closed. Returns a board actor scoped strictly to the agent's
company with `isInstanceAdmin: false`.
- `agentOwnsRun`: verifies that the supplied run ID is a valid UUID
belonging to the calling agent in the same company.
- `recordAgentTaskRetry`: under a per-task PostgreSQL transaction
advisory lock (`agent-task-retry:{issueId}`), enforces a rolling 24-hour
cap of 3 Retries per agent per task (`429` with `details.code:
"agent_task_retry_cap_reached"`), counts replays of the same
`idempotencyKey` once, and writes `issue.retry_requested_by_agent` to
`activity_log` with the agent, run ID, `grantedByUserId`, and
`idempotencyKey`.
- `server/src/routes/issues.ts` (`POST /issues/:id/retry`; small
+33-line delegation calling into
`server/src/services/agent-task-retry.ts` so the existing >1,000-line
route module does not absorb service logic): for an agent with a valid
`tasks:retry` grant, enforces the agent's own limits first (refuses
scoped `skill_test`/`task_bridge` keys, requires the agent's own run ID,
enforces `issue:read` and actor-class/interaction `issue:mutate`
boundaries), then runs the existing board Retry checks as the granting
person (preserving visibility, `issue:mutate`, pause, budget, hold, and
blocker gates). Refuses chat tasks (`403`) and cross-company tasks
(`404`). Agents without a valid grant keep getting `403`.
- `server/src/routes/openapi.ts`: remove `POST /api/issues/{id}/retry`
from `BOARD_ONLY_OPERATIONS` so granted agents can discover it via API
search, and document `429` in the endpoint responses.
- `doc/agent-permission-defaults.md` and `docs/api/issues.md`: document
`tasks:retry`, its default-off behavior, run/key requirements, daily
cap, and activity attribution.
- `tests/runner-e2e/source-sdk-public-inputs.json`: refresh the pin for
`packages/shared/src/constants.ts`.
- `server/src/__tests__/issue-scheduled-retry-routes.test.ts` and
`server/src/__tests__/issue-agent-mutation-ownership-routes.test.ts`:
add 14 embedded-Postgres route integration tests and 1 mocked-boundary
test covering default refusal, agent-written grant refusal,
board-granted Retry promotion + activity attribution, pause-gate
preservation, grantor visibility gates, revoked grant / suspended
grantor fail-closed, cross-company 404, chat task 403, daily cap 429,
idempotency replay counting, foreign run ID refusal, scoped grant
refusal, low-trust read/write boundary enforcement, and scoped key
refusal.
## Verification
- RED check on base `2d065677959b585065ff3fec8718156a4cf6f41d` before
production changes:
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/issue-scheduled-retry-routes.test.ts -t "agent Retry with
a board user's tasks:retry grant"` failed because granted agents
received `403 Board access required` instead of `202` / `429` / `404`
and logged 0 `issue.retry_requested_by_agent` events.
- GREEN checks on head `14b5591073ea591251f2d24710a32e3c725a090c`:
- `pnpm --filter @paperclipai/shared build && pnpm --filter
@paperclipai/shared typecheck && pnpm --filter @paperclipai/server
typecheck`: passed (0 errors across `@paperclipai/shared` and all 7
`@paperclipai/server` typecheck layers).
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/issue-scheduled-retry-routes.test.ts
src/__tests__/openapi-routes.test.ts
src/__tests__/agent-default-configure-grants.test.ts`: passed (112/112
tests, including all 14 embedded-Postgres `agent Retry with a board
user's tasks:retry grant` tests and default-grant verification).
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/issue-agent-mutation-ownership-routes.test.ts`: passed
(229/229 tests).
- `pnpm exec vitest run --root tests/runner-e2e
source-sdk-public-inputs.test.mjs source-sdk-evidence.test.ts
source-sdk-public-type.test.ts
chat-catalog-domains/identity-accounting.test.ts`: passed (4 files,
98/98 tests).
- `node tests/runner-e2e/source-sdk-public-inputs.mjs $(git rev-parse
HEAD) --check`: passed (`changed: false`, 578 inputs in sync).
- `node scripts/check-test-budget.mjs --files
server/src/__tests__/issue-scheduled-retry-routes.test.ts
server/src/__tests__/issue-agent-mutation-ownership-routes.test.ts`:
passed (`110 nightly suites validated, 2 test file(s) checked`).
- `pnpm verify --base
|
||
|
|
e18fe61c8f |
perf(runner-image): parallelize pack archiving and use cloud-release-32 on master amd64 (#22992)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The Runner image workflow (`.github/workflows/runner-image.yml`) builds `ghcr.io/paperclipai/paperclip-runner` for `amd64` and `arm64` whenever Runner inputs change > - Profiling recent builds showed `Build and check (amd64)` taking ~12 minutes versus ~4m 38s on `arm64`, driven by 4-core CPU saturation during `create-provider-pack-archive.mjs` (which compressed every large provider-pack binary serially on a single core) and during OCI tar/gzip export on `ubuntu-latest` > - Because `docker.yml` waits for the Runner image whenever Runner inputs change, slow `amd64` Runner builds sit directly on the release critical path > - This pull request parallelizes zstd layer archive creation in `scripts/create-provider-pack-archive.mjs` with bounded concurrency while preserving byte-for-byte deterministic output, and routes canonical `master` `amd64` runs of `.github/workflows/runner-image.yml` to the larger GitHub-hosted runner (`cloud-release-32`) > - The benefit is cutting `amd64` Runner image build time substantially on `master` (and speeding up provider-pack archiving on every PR and architecture) without weakening the PR/fork security boundary or changing output bytes ## Linked Issues or Issue Description **What existing behavior does this improve?** `scripts/create-provider-pack-archive.mjs` layer compression throughput and `.github/workflows/runner-image.yml` `amd64` runner sizing on canonical `master` pushes. **Subsystem affected** Cross-cutting (multiple of the above) **Current behavior** `createProviderPackLayers` compresses `overlay.tar.zst` and each large provider-pack file (`0.tar.zst..N.tar.zst`) sequentially on one CPU core. In `.github/workflows/runner-image.yml`, canonical `master` `amd64` builds run on 4-core `ubuntu-latest` (~12 minutes total vs ~4m 38s on `arm64`). **Proposed behavior** `createProviderPackLayers` compresses `overlay.tar.zst` and the indexed large-file archives through a bounded worker pool (`min(availableParallelism(), 8)`), preserving exact file ordering, archive numbering, and byte-for-byte deterministic zstd frames. In `.github/workflows/runner-image.yml`, canonical `master` `amd64` pushes (`paperclipai/paperclip`, `push` to `refs/heads/master`) use `vars.CORE_PUBLICATION_RUNNER || 'cloud-release-32'`, while all PRs, forks, schedules, and `arm64` jobs stay on standard GitHub-hosted runners. **Reason and benefit** Eliminates single-core archiving bottlenecks across all environments and removes the 4-core `amd64` CPU bottleneck on `master` Runner image publications. **Breaking changes** None. ## What Changed - Updated `scripts/create-provider-pack-archive.mjs` to compress `overlay.tar.zst` and large-file archives via a bounded worker pool while preserving exact archive indices, receipt ordering, and byte-for-byte deterministic output. - Added `scripts/__tests__/create-provider-pack-archive.test.mjs` verifying serial (`concurrency: 1`) and parallel (`concurrency: 4`) runs produce identical receipts and archive bytes. - Updated `.github/workflows/runner-image.yml` to route canonical `master` `amd64` pushes to `vars.CORE_PUBLICATION_RUNNER || 'cloud-release-32'` while keeping PRs, forks, schedules, and `arm64` on `matrix.runner`. - Added a workflow guard in `server/src/__tests__/runner-image-workflow.test.ts` verifying only canonical `master` `amd64` pushes use the larger GitHub-hosted runner and never touch self-hosted AWS release fleets. ## Verification - `node --test scripts/__tests__/create-provider-pack-archive.test.mjs` (passed) - Vitest: `server/src/__tests__/runner-image-identity.test.ts` (42/42 passed) - Vitest: `server/src/__tests__/runner-image-workflow.test.ts` (18/18 passed) - PR CI also executes the live `Runner image` workflow end-to-end because both `scripts/create-provider-pack-archive.mjs` and `.github/workflows/runner-image.yml` are in its PR path filter. ## Risks - Low risk. Archive bytes and receipt structure are verified identical between serial and parallel runs. PRs, forks, and schedules remain on `ubuntu-latest` / `ubuntu-24.04-arm`, and `cloud-release-32` is the same GitHub-hosted larger runner already used on `master` by `docker.yml` and `cloud-migrator-artifacts.yml`. ## Model Used - Gemini 3 Pro (Antigravity agent with tool use, shell execution, and local test verification) ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing> |
||
|
|
168253f74d |
fix(telemetry): send agent.task_completed when a native run closes a task (#22963)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - Paperclip sends product telemetry, and the `agent.task_completed`
event counts each task that an agent finishes
> - Only the REST issue update route (`server/src/routes/issues.ts`)
sent `agent.task_completed` when an agent moved a task to `done`
> - Native runs close tasks through `commitNativeStatusDecision` in
`server/src/services/native-runtime/status-decision-committer.ts`, which
bypasses the REST route and therefore sent `agent.task_run` without ever
sending `agent.task_completed`
> - Deployments where agents close tasks through native runs
consequently under-report completed tasks
> - This pull request supersedes #21206 (rebased onto current `master`),
sending `agent.task_completed` once after a committed native transition
into `done` without blocking finalization, with full company/person
telemetry scope and underlying Paperclip runner harness `adapter_type`
resolution
> - The benefit is accurate, deduplicated `agent.task_completed`
telemetry across both API and native completion paths
## Linked Issues or Issue Description
Refs #21206
**What happened?**
A native run closes a task through `commitNativeStatusDecision` in
`server/src/services/native-runtime/status-decision-committer.ts`. The
task moves to `done` and the run sends `agent.task_run`, but no
`agent.task_completed` event is sent because the only sender is
`server/src/routes/issues.ts` and native completion does not go through
that route.
**Expected behavior**
Paperclip sends one `agent.task_completed` event each time an agent
moves a task into `done`, on both the REST issue route and native status
commits. The event carries the same dimensions, runner harness
`adapter_type`, company scope, and person attribution as the issue
route. Replayed commits and tasks that were already `done` send nothing.
**Steps to reproduce**
1. Seed a native run ready to commit a `done` status decision on an
`in_progress` task.
2. Call `commitNativeStatusDecision` (or `finalizeNativeRun`) with a
`done` decision.
3. Observe that the task moves to `done`, while
`trackAgentTaskCompleted` is called 0 times.
**Paperclip version or commit**
`master` at `2d065677959b585065ff3fec8718156a4cf6f41d`.
## What Changed
- `server/src/services/agent-task-run-telemetry.ts`: add
`emitAgentTaskCompleted`. It loads the agent within the task's
`companyId`, resolves the underlying runner harness with
`telemetryAdapterType(agent)`, resolves person attribution with
`resolveTelemetryPerson`, wraps `trackAgentTaskCompleted` in
`withTelemetryActor({ companyId, person }, ...)`, and never throws.
- `server/src/services/native-runtime/status-decision-committer.ts`:
select `originRun.responsibleUserId` alongside `originRun.agentId`,
capture the completion payload only when the committed transaction
transitions `issue.status` from non-`done` to `done` with an origin
agent, and invoke `void emitAgentTaskCompleted(input.db, completedTask)`
after commit when `!committed.replayed` so slow lookups cannot block run
finalization.
-
`server/src/services/native-runtime/native-task-completed-telemetry.test.ts`:
add embedded-Postgres regression tests covering single emission (with
company scope, person attribution, and underlying runner harness
`adapter_type`), no duplicate on replay, non-blocking commit while
telemetry is pending, and no emission when the task was already `done`.
- `server/src/__tests__/agent-task-run-telemetry.test.ts`: add unit/DB
coverage for `emitAgentTaskCompleted` (company/person scope, runner
harness `adapterType`, cross-company agent isolation, and error
swallowing).
-
`server/src/services/native-runtime/native-run-finalizer-telemetry.test.ts`:
add an end-to-end `finalizeNativeRun` integration test verifying a real
native run completion emits `agent.task_completed` once through the real
`trackAgentTaskCompleted` path and emits no duplicates on replay or
reconciliation.
Note: this PR supersedes #21206 (whose fork branch had merge conflicts
with pruned test suites and predated `withTelemetryActor` /
`telemetryAdapterType` on `master`, and whose fork repository did not
allow maintainer pushes from this account).
## Verification
- **RED (before fix on `2d065677959b585065ff3fec8718156a4cf6f41d`):**
`pnpm --dir server exec vitest run
src/services/native-runtime/native-task-completed-telemetry.test.ts`
Result: 1 failed | 1 passed — `sends agent.task_completed once with
company, person, and harness adapter_type when the runner closes a task`
failed with `AssertionError: expected "vi.fn()" to be called 1 times,
but got 0 times`.
- **GREEN (after fix):**
`pnpm --dir server exec vitest run
src/services/native-runtime/native-task-completed-telemetry.test.ts
src/__tests__/agent-task-run-telemetry.test.ts
src/services/native-runtime/native-run-finalizer-telemetry.test.ts
src/__tests__/heartbeat-status-preserving-telemetry.test.ts
src/__tests__/issue-telemetry-routes.test.ts`
Result: **5/5 files, 106/106 tests passed**
(`native-task-completed-telemetry.test.ts` 3/3,
`agent-task-run-telemetry.test.ts` 55/55,
`native-run-finalizer-telemetry.test.ts` 42/42 including end-to-end
`finalizeNativeRun`, `issue-telemetry-routes.test.ts` 5/5,
`heartbeat-status-preserving-telemetry.test.ts` 1/1).
- **Typecheck:** `pnpm --filter @paperclipai/server typecheck` —
**PASS** (0 errors across all layers).
- **Test budget:** `node scripts/check-test-budget.mjs --files
server/src/services/native-runtime/native-task-completed-telemetry.test.ts
server/src/__tests__/agent-task-run-telemetry.test.ts
server/src/services/native-runtime/native-run-finalizer-telemetry.test.ts`
— **PASS** (110 nightly suites validated, 3 test files checked).
- **Broader suite:** `pnpm verify --base
|
||
|
|
702368ffaf |
feat(github): graduate GitHub review bots out of experimental (#22996)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - GitHub Code Review Bot connects an agent to a dedicated GitHub App so it reviews pull requests and responds to GitHub mentions > - The feature was gated behind the default-off `enableGitHubReviewBots` experimental instance setting, hiding the catalog card, setup routes, identity links, and channel creation > - People had to find and flip an instance-level experimental switch before they could connect a GitHub review agent > - This pull request graduates GitHub review bots to a normal always-on feature, keeping `enableGitHubReviewBots` only as a deprecated compatibility key that always resolves to `true` > - The benefit is that every Paperclip instance exposes GitHub Code Review Bot setup, discovery, and management by default without requiring feature flags ## Linked Issues or Issue Description **What existing behavior does this improve?** GitHub Code Review Bot discovery, catalog visibility, setup/management routes, identity-link endpoints, and Agent Channels visibility (`enableGitHubReviewBots`). **Subsystem affected** Cross-cutting (`packages/shared`, `server/`, `ui/`, Storybook, E2E specs, docs). **Current behavior** GitHub Code Review Bot is hidden from Connectors, `connections_search`, chat-endpoint creation, identity-link confirmation, and UI setup/settings routes until an instance admin turns on **Settings → Experimental → GitHub review bots** (`enableGitHubReviewBots`). **Proposed behavior** GitHub Code Review Bot is always available as a standard feature on every instance (self-hosted and Cloud), matching AgentMail and graduated features such as Assistant connections (`enablePublicMcp`) and the AWS connector (`enableAwsConnector`). `enableGitHubReviewBots` stays in schemas and the feature catalog only as a deprecated compatibility key that always normalizes to `true`, ignores stored or Cloud-managed `false` values, and does not reject legacy `false` patches. Experimental chat providers (Slack, Discord, Microsoft Teams, Telegram, iMessage Photon, Speko) remain gated by `enableChatConnectors`. **Reason and benefit** Users can connect and manage GitHub review agents directly from Connectors without an admin enabling an experimental flag first, and Cloud stacks no longer require managed feature-flag overrides to expose GitHub review bots. **Breaking changes** No schema migration or breaking API change. Existing rows, API patches, and Cloud managed configs that still carry `enableGitHubReviewBots` continue to parse cleanly, while the effective value is always `true`. Instances that previously kept `enableGitHubReviewBots` off now display GitHub Code Review Bot in Connectors and allow authorized managers (`tools:manage_connections`) to create GitHub review bot endpoints. ## What Changed - `packages/shared`: marked `enableGitHubReviewBots` as a deprecated compatibility key in types, Zod defaults (`true`), and `INSTANCE_FEATURE_CATALOG` (`cloudDefault: true`, `selfHostedDefault: true`); updated `channelMethodEnabled` in `connector-availability.ts` so `github` is always enabled alongside `agentmail`. - `server` instance settings and Cloud staging: `normalizeExperimentalSettings` always returns `enableGitHubReviewBots: true`; `applyManagedExperimentalOverlay` and `updateExperimental` ignore retired `enableGitHubReviewBots` entries so Cloud managed configs cannot turn it off and legacy `false` patches are not rejected; removed `enableGitHubReviewBots` from `CLOUD_STAGING_EXPERIMENTAL_KEYS`. - `server` chat channels, discovery, and OpenAPI: allowed `github` in `assertChatProviderEnabledForCreate`, `assertIdentityProviderEnabled`, `assertIdentityLinkAccess`, and `connection-intents` discovery without experimental flags while keeping `enableChatConnectors` enforcement for experimental chat providers; updated the OpenAPI endpoint description. - `ui` and Storybook: removed the **GitHub review bots** Experimental settings toggle card; simplified `useChatConnectorsEnabled` and `chatProviderVisible` so `github` and `github-code-review-bot` are always visible; bypassed experimental loading wait for `provider=github` in `ChatConnectorsExperimentalGate`; made the classic Agent Detail Channels tab and `AgentChannelsPanel` empty-state copy always reflect available agent identities; updated `canEnterAppsConnect`, `Browse`, `ConnectionSetupFlow`, and `github-connections.stories.tsx`. - Tests, E2E, runner-e2e, docs, and maps: updated unit, integration, managed-overlay, runner-e2e, and Playwright E2E specs; refreshed `tests/runner-e2e/source-sdk-public-inputs.json`; updated `doc/connections/GITHUB.md`, `doc/connections/GITHUB-REVIEW-BOT.md`, and `maps/feature-map/chat-channels.md`. ## Verification - `pnpm --filter @paperclipai/shared build && pnpm --filter @paperclipai/shared typecheck && pnpm --filter @paperclipai/server typecheck && pnpm --filter @paperclipai/ui typecheck` — passed. - `node scripts/check-maps.mjs && node scripts/storybook-catalog.mjs` — passed. - `pnpm vitest run packages/shared/src/validators/instance.test.ts packages/shared/src/connector-availability.test.ts packages/shared/src/feature-catalog.test.ts server/src/__tests__/instance-settings-service.test.ts server/src/__tests__/instance-settings-managed-overlay.test.ts server/src/__tests__/instance-settings-cloud-defaults.test.ts server/src/routes/chat-channels.identity.test.ts server/src/__tests__/connection-intents-service.test.ts server/src/__tests__/chat-channels/slack-ingress-and-threads.integration.test.ts server/src/__tests__/chat-channels/github-setup-and-access.integration.test.ts` — all passed. - `pnpm vitest run ui/src/pages/apps/app-connect-policy.test.ts ui/src/components/chat/ExternallyConnectedTaskBanner.test.tsx ui/src/features/connections/ConnectionSetupFlow.slack-oauth.test.tsx` — 3 files, 62 tests passed. - `pnpm --dir tests/runner-e2e vitest run github-review-journey.test.ts` — 56 tests passed. - `pnpm verify --explain` — confirmed `tests/runner-e2e/source-sdk-public-inputs.json` is current; exited 2 for broad CI coverage (handled by required GitHub CI gates on this PR). ## Risks - Behavioral shift: instances that had `enableGitHubReviewBots` off now show GitHub Code Review Bot in Connectors and allow authorized users with `tools:manage_connections` to configure GitHub review bots. Existing permission boundaries (`tools:manage_connections`, company scoping, GitHub App OAuth/installation consent) are unchanged. - `useIssueChatBinding` now queries `/api/issues/:issueId/chat-binding` for normal tasks even when `enableChatConnectors` is off so GitHub-bound task banners remain visible; experimental chat bindings remain filtered out by `chatProviderVisible` while `enableChatConnectors` is off. - No database migration is required; stored `enableGitHubReviewBots` JSON values become inert. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Google Gemini (high reasoning) in Antigravity, with tool use (shell, file edits, test execution). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge |
||
|
|
73369c5d46 |
feat(connections): AWS connector out of experimental; role ARN comes back from the agent (#22994)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The AWS connector lets agents work in an AWS account through AWS's hosted MCP server, with a per-connection role and short-lived credentials (#22083, #22195, #22233, #22626) > - It has been behind the `enableAwsConnector` experimental setting. It is now proven on paperclip.staging: a connection was set up end to end, and the daily QA routine's agent uses it to read private test evidence from S3 > - On the role step, the person still had to paste the role ARN back, even when their own agent created the role and reported the ARN in its live checklist > - This pull request takes the connector out of experimental and has the page pick up the role ARN from the agent, keeping the field for people who set the role up by hand > - The benefit is AWS available to everyone, with a setup that is "paste a prompt, press Test connection" ## Linked Issues or Issue Description Refs #22233 (role setup), #22626 (live agent checklist). **Subsystem affected** Connections (AWS app definition, role setup UI), instance experimental settings. **Problem or motivation** - The AWS connector works, but is hidden unless an operator turns on an experimental flag. - The setup page always showed a Role ARN field, and the person had to copy the ARN from the agent's summary into it. **Proposed solution** - Remove `experimentalFeatureKey` from the AWS app definition. `enableAwsConnector` becomes a compatibility key: stored and Cloud-managed values are ignored, and old clients' writes are accepted (same pattern as `enableMcpAggregators` and `enablePublicMcp`). - Move the Role ARN field into "Or do it by hand". When the agent finishes, take the ARN from its finish summary, accepting only an IAM role ARN for this connection's own role name (`paperclip-<connectionId>`), so a summary cannot point the connection at another role. "Test connection" then works with nothing to paste. The by-hand section opens on its own when a test fails or the agent finished without a usable ARN. **Alternatives considered** - Letting the agent save the ARN through the checklist API: more surface on a token-only route. Reading it from the finish summary needs no new API, and the test still proves the role trusts only this connection. - Removing the field entirely: people who use CloudFormation or IAM by hand still need it. ## What Changed - `packages/shared/src/app-definitions/aws.json`, `scripts/app-definition-overrides/aws.json`: no `experimentalFeatureKey`. - `packages/shared/src/feature-catalog.ts`, `validators/instance.ts`: `enableAwsConnector` is "(compatibility)", default on. - `server/src/services/instance-settings.ts`: always on; Cloud-managed values skipped; old clients' writes accepted. - `ui/src/pages/InstanceExperimentalSettings.tsx`: the AWS toggle is removed. - `ui/src/features/connections/aws-role-arn.ts` (new): the role ARN rule and `roleArnFromAgentSummary`. - `ui/src/features/connections/AwsRoleSetup.tsx`: Role ARN under "Or do it by hand", auto-filled from the agent's summary, with copy updated ("hands back the role when it finishes", "the Role ARN field below"). - `doc/connections/AWS.md`: no longer described as experimental. ## Verification - Server: `aws-mcp-connector.test.ts` (connects even with a stored `enableAwsConnector: false`), `instance-settings-managed-overlay.test.ts` (stays on with stored and Cloud-managed false; an old client's false write is accepted), `instance-settings-service.test.ts`: 68 passed. The 4 new flag tests fail against master's source (red/green). - Shared: `app-definitions.test.ts` 43 passed; `scripts/app-definition-overrides.test.mjs` 3 passed. - UI: `aws-role-arn.test.ts` 3 passed (this connection's ARN from a summary, including role paths and a trailing period; another role, a longer name, a short account and no ARN are rejected). UI typecheck clean. - Storybook (headless Playwright, current branch): the default view has no Role ARN field; "agent done" shows "Your agent's role is ready. Test the connection to finish." with Test connection enabled; "test failed" opens "Or do it by hand" with the field at its end. No page errors. - Live: the connector was set up end to end on paperclip.staging (Test connection passed) and is in daily use by the QA routine. To re-check after deploy without the flag. ## Risks - Every instance now shows the AWS connector. It was already proven on staging; access is per connection and read-only connections are capped by AWS's `ReadOnlyAccess`. - The ARN auto-fill trusts only an ARN naming this connection's own role, and Test connection still verifies AWS accepts it, so a wrong or foreign ARN cannot be saved silently. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use (shell, file edits, Storybook with headless Playwright, the live staging instance). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
8e8c1b9f4d |
fix(sandbox): scope staged provider-pack assets per provider and default Daytona disk to 20 GiB (#22981)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - Native agents run inside remote Daytona sandboxes that require a
verified Runner provider pack
> - When a sandbox stages the provider pack into its workspace,
Paperclip copies, transfers, and verifies every
`provider-assets/<provider>` closure (~1.6 GB across pi, cursor,
copilot, kimi, and antigravity) even when the run only uses Claude,
Codex, OpenCode, or one provider
> - New image-backed Daytona sandbox environments also default to a 10
GiB disk, which leaves too little headroom for repository installs and
tests
> - This pull request stages and verifies only the
`provider-assets/<provider>` tree needed by the active run and raises
the Daytona plugin default disk size from 10 GiB to 20 GiB
> - The benefit is significantly more free workspace disk space, smaller
pack transfers, and safer default disk sizing without changing the
provider-pack archive format or breaking multi-provider workspace reuse
## Linked Issues or Issue Description
- Fixes: #19367
- Refs #19484
- Related: #19500 (ENOSPC fail-fast and full-sandbox recovery already
merged in #22068, #22239, #22383, #22466, and #22837), #22241
(deduplicated repeated bytes in staged packs)
## What Changed
- `server/src/services/native-runtime/provider-pack-compatibility.ts`:
add `requiredProviderAssetNames`, `isProviderAssetPathIncluded`, and
`providerAssetExcludeArgs` helpers that resolve the required
`provider-assets/<provider>` subset for a `PackProvider` (returning
unfiltered behavior when `provider` is omitted).
- `server/src/services/native-runtime/provider-pack-layers.ts`: filter
large layer entries by required provider assets before running the
remote reuse script and transferring missing layers, preserve
cross-provider image-twin reuse so core files can still reuse identical
bytes from excluded provider paths in the base image, and pass
`--exclude` flags to GNU `tar` for `overlay.tar.zst`.
- `server/src/services/native-runtime/provider-pack-archive.ts` and
`provider-pack-upload.ts`: forward `provider` and `manifest` into v1 and
v2 archive staging and exclude unused `provider-assets/*` during
extraction.
-
`server/src/services/native-runtime/remote-provider-pack-verification.ts`:
scope candidate asset tree digest checks to the active provider when
`provider` is passed and include `requiredAssets` in the verification
seal key so a pack verified for one provider cannot satisfy a seal check
for a different provider.
- `server/src/services/native-runtime/native-session-executor.ts` and
`server/src/services/kimi-connection-probe.ts`: pass the active
`PackProvider` to `prepareRemoteProviderPackOnTarget` and
`verifyRemoteProviderPackIdentity`.
- `packages/plugins/sandbox-providers/daytona/src/manifest.ts` and
`package.json`: raise the default `disk` allocation from `10` to `20`
GiB and bump the plugin version from `0.1.10` to `0.1.11` so
bundled-plugin boot reconciliation refreshes persisted manifests.
- Added unit and end-to-end tests in
`packages/plugins/sandbox-providers/daytona/src/plugin.test.ts`,
`server/src/services/native-runtime/provider-pack-archive.test.ts`,
`server/src/services/native-runtime/remote-provider-pack-verification.test.ts`,
and updated `server/src/__tests__/kimi-connection-probe.test.ts`.
## Verification
- **RED (before production edits):**
- `cd packages/plugins/sandbox-providers/daytona && npx vitest run
--config vitest.config.ts -t "bumps the plugin version|pre-fills
sizing|validates and passes the default 20 GiB"` — 3 failed (`0.1.10 !==
0.1.11`, `10 !== 20`).
- `cd server && npx vitest run
src/services/native-runtime/provider-pack-archive.test.ts -t "omits all
provider-assets|stages only the selected provider"` — 2 failed (unused
`provider-assets` staged on disk).
- `cd server && npx vitest run
src/services/native-runtime/remote-provider-pack-verification.test.ts -t
"verifies only the selected provider"` — 1 failed (`candidate_digest`
rejected Claude when `provider-assets/` was absent).
- **GREEN (after fix):**
- `cd server && npx tsc --noEmit -p tsconfig.json` — passed.
- `cd server && npx vitest run
src/services/native-runtime/provider-pack-archive.test.ts` — **56/56
passed**, including an end-to-end upload+verify test proving unfiltered
staging writes >= 6 MiB of provider assets, Claude staging omits all 6
MiB (< 256 KiB total) and verifies cleanly, and switching the same
workspace to Cursor rejects the Claude seal (`candidate_digest`) and
re-stages only Cursor (2 MiB, excluding Kimi and Pi).
- `cd server && npx vitest run
src/services/native-runtime/remote-provider-pack-verification.test.ts
src/services/native-runtime/remote-provider-pack.test.ts
src/services/native-runtime/retained-provider-pack-source.test.ts
src/__tests__/kimi-connection-probe.test.ts` — all passed
(`remote-provider-pack-verification.test.ts` 34/34,
`remote-provider-pack.test.ts` 60/60, `kimi-connection-probe.test.ts`
39/39, `retained-provider-pack-source.test.ts` all passed).
- `cd packages/plugins/sandbox-providers/daytona && pnpm typecheck &&
npx vitest run --config vitest.config.ts` — typecheck passed; all 15
offline test files passed (641 passed, 8 live tests skipped;
`archive-stream-window.test.ts` timed out once during parallel CPU
contention and passed in 6.17s when re-run).
- `node scripts/check-test-budget.mjs --files
server/src/services/native-runtime/provider-pack-archive.test.ts
server/src/services/native-runtime/remote-provider-pack-verification.test.ts
server/src/__tests__/kimi-connection-probe.test.ts` — passed (110
nightly suites validated, 3 test files checked).
- `pnpm verify --base
|
||
|
|
87fadcb108 |
feat(annotations): one-tap reactions on artifact comments (#22989)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - People review agent artifacts (plans, documents, routine descriptions, and case documents) with inline annotation comments > - Today a person must type a full reply to say "done", "checked", "looks good", or "I have a question" > - This slows down quick review feedback, and a question inside a reply does not automatically bring the assignee back > - This pull request adds four one-tap reactions to each annotation comment: Done, Check, Thumbs up, and Question > - A person's first Question reaction on an open task saves a durable wake receipt and wakes the task's assignee in a dedicated follow-up run to reply in that comment's thread (respecting chat ownership and wake rate limits) > - The benefit is fast review feedback without extra typing, while agents can read and set the same reactions through the API ## Linked Issues or Issue Description Refs #21637 (supersedes on current `master` with renumbered Drizzle migration, OpenAPI/experimental route contracts, durable wake receipts, chat ownership and rate-limit hardening, and current UI test suite) Refs #9336 (agent wake notifications for document annotation threads) Refs #9674 (agents cannot read inline document review comments) **What problem does this solve?** A reviewer cannot quickly acknowledge or question an annotation comment on an artifact. A short answer requires a typed reply, and nothing tells the agent that a person has a question about a comment. **Proposed solution** Add four fixed reactions per annotation comment: `done`, `check`, `thumbs_up`, and `question`. One tap adds a reaction and a second tap removes it. Each person or agent can add each reaction once per comment. A person's first `question` reaction on an open task commits a durable wake receipt in the same transaction and wakes the assignee once in a dedicated follow-up turn, with the comment included in the wake context. **Alternatives considered** Free-form emoji reactions. Fixed named reactions keep the API contract stable for agents and avoid storing arbitrary emoji strings on the server. ## What Changed - `packages/db`: Added `document_annotation_comment_reactions` table (`company_id`, `comment_id`, `reaction`, `actor_type`, `actor_id`, `created_at`, `removed_at`) with check constraints, cascade delete on comment deletion, and unique `(comment_id, reaction, actor_type, actor_id)` index. Generated online-compatible migration `0510_clear_speedball.sql`, refreshed Drizzle snapshot `0510_snapshot.json`, and pruned `0505_snapshot.json`. - `packages/shared`: Added `DOCUMENT_ANNOTATION_COMMENT_REACTIONS`, `DocumentAnnotationCommentReactionName`, `DocumentAnnotationCommentReactionActor`, `DocumentAnnotationCommentReactionSummary`, optional `reactions` on `DocumentAnnotationComment`, and `documentAnnotationCommentReactionSchema`. - `server`: Added `setCommentReaction` in `document-annotations.ts` using soft-delete (`removed_at`) and upsert revival (`(xmax = 0)` for `firstAdd`), and attached reaction summaries (`count`, `actors`, `reactedByMe`) to thread/comment reads. - `server` routes & contracts: Added `PUT` and `DELETE .../annotations/:threadId/comments/:commentId/reactions/:reaction` for issues, routines, and cases, registered them in `openapi.ts`, `experimental-api-metadata.ts`, and `experimental-api-paths.ts`, and logged activity (`*.document_annotation_comment_reaction_added` / `_removed`) only when a row changes. - `server` durable wake, chat ownership, rate limits & `packages/adapter-utils`: - A person's first `question` reaction on an open assigned issue inserts a recoverable `deferred_issue_execution` receipt in `agent_wakeup_requests` in the same DB transaction (`annotation-question-reaction:<id>`), passes `executionWaitRequestId` to `heartbeat.wakeup` (`reason: "issue_commented"`, `allowRunCoalescing: false`), resumes via `resumeDeferredExecutionReceipts` if immediate wake fails, and defers behind busy turns without duplicating receipts. - Recognized human annotation question reactions (`isHumanAnnotationQuestionWake`) as an independent wake cause for idle waiting agent chats while strictly enforcing chat ownership (`!conversationAgentId || conversationUserId === actorId`) across service, route, wake preflight, locked admission, and recovery queries. - Bounded distinct-comment question wakes under `issues ... FOR UPDATE` to at most 1 pending/in-flight wake per `(companyId, issueId, agentId)` and at most 3 original question receipts (`idempotency_key LIKE 'annotation-question-reaction:%'`) per `(companyId, issueId, user)` in a rolling 10-minute window. - `renderPaperclipWakePrompt` instructs the agent to answer the question in the annotation thread. - `ui`: Added four one-tap reaction buttons (`✅`, `✔️`, `👍`, `❓`) under each non-optimistic annotation comment in `DocumentAnnotationPanel` / `DocumentAnnotationPopover`, with counts, `aria-pressed`, hover tooltips naming actors, optimistic updates, client-scoped write serialization across panel/popover remounts (`WeakMap<QueryClient, Map<string, TargetReactionState>>`), live-update refetch overlay preservation, deferred invalidation while writes are pending, and updated Storybook fixture. - `docs/api` & `tests/runner-e2e`: Documented the reaction endpoints and wake bounds in `docs/api/issues.md` and `docs/api/routines.md`, and refreshed `tests/runner-e2e/source-sdk-public-inputs.json`. ## Verification - `pnpm --filter @paperclipai/db run check:migrations` and `migration-compatibility.ts`: `0510_clear_speedball.sql` classified `online_compatible`. - `pnpm --filter @paperclipai/db exec vitest run src/migration-snapshot-drift.test.ts src/migration-compatibility.test.ts`: passed (117/117). - `pnpm --filter @paperclipai/adapter-utils exec vitest run src/server-utils.test.ts -t "question reaction"`: passed. - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/document-annotations-service.test.ts` (20/20, embedded Postgres — covering durable wake recovery, idle waiting-chat wake, busy-turn deferral, non-owner chat wake denial, and rolling-window + pending-backlog wake bounds across full queue admission), `src/__tests__/document-annotation-routes.test.ts` (20/20), `src/__tests__/routine-document-annotation-routes.test.ts`, `src/modules/wake-queue/application/issue-wake-admission.test.ts` (15/15), and `src/modules/wake-queue/domain/policy.test.ts`: all passed. - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/openapi-routes.test.ts`: passed (59/59). - `pnpm --filter @paperclipai/ui exec vitest run src/hooks/useDocumentAnnotationMutations.test.tsx`: passed (9/9, covering optimistic updates, serialized writes across remounts, live-update refetch preservation, deferred invalidation across comments, and rendered `ThreadCard` DOM buttons/toggles). - Package typechecks (`@paperclipai/shared`, `@paperclipai/db`, `@paperclipai/adapter-utils`, `@paperclipai/server` all 7 layers, `@paperclipai/ui` + Storybook catalog): all passed. - `pnpm check:token-gates`, `node scripts/check-module-boundaries.mjs`, and `node scripts/check-test-budget.mjs`: all passed. - `node tests/runner-e2e/source-sdk-public-inputs.mjs $(git rev-parse HEAD) --check`: in sync (`inputs: 579, changed: false`). - Full-stack Playwright verification against a throwaway local server + embedded PostgreSQL: created a task, `plan` document, and annotation thread; verified invalid reaction returns `400`; clicked `thumbs_up` and `question` in the real document viewer; reloaded to prove PostgreSQL persistence; toggled `thumbs_up` off and reloaded to verify removal persisted. - PR CI on `4d892c8067`: 83/83 executed checks passing (including `ci / verify`, `ci / e2e` + all 16 E2E shards, all General/Serialized server shards, `Build`, `Typecheck + Release Registry`, `Verify Paperclip Runner`, `Superagent Security Scan`, and `Greptile Review` 5/5 with 0 unresolved threads). ## Risks - Low risk. Migration `0510_clear_speedball.sql` only creates a new table and its indexes (`online_compatible`), so running releases are unaffected. - `reactions` is optional on `DocumentAnnotationComment`, preserving backward compatibility for existing clients. - Question wakes are bounded by soft-delete revival (`firstAdd`), chat ownership enforcement, single pending/in-flight wake per `(companyId, issueId, agentId)`, and at most 3 original question wakes per `(companyId, issueId, user)` per 10-minute window. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Google Gemini (`gemini-3-pro` / Antigravity agentic coding environment with shell execution, file editing, embedded PostgreSQL, and Playwright verification), rebasing and extending prior work originally authored with Claude Opus 5.5 in #21637. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: lucktastic <13757243+lucktastic@users.noreply.github.com> Co-authored-by: Paperclip <noreply@paperclip.ing> |
||
|
|
0f52d90993 |
fix(github): detect writes outside GitHub App installations and stop advising Refresh access (#22978)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work.
> - Agents use managed GitHub App connections through the tool gateway
to open issues, post comments, and perform approved writes on GitHub
repositories.
> - A GitHub App user-to-server token can write only to repositories
inside accounts where the Paperclip GitHub App is installed; even on a
public third-party repository, GitHub rejects writes with `403 Resource
not accessible by integration`.
> - Previously, Paperclip did not check the App's installed accounts
before posting an approval card, mapped every `403 Resource not
accessible by integration` to `github_access_denied`, and told both the
user ("Manage GitHub access") and the agent ("select Refresh access") to
repair access through a flow that cannot reach third-party
organizations.
> - This wastes human approvals on doomed writes and sends operators
into a dead-end permission refresh loop.
> - This pull request adds a pre-check before posting approval cards for
managed GitHub App writes outside installed accounts, distinguishes
`github_repo_outside_app_installations` and
`github_app_installation_suspended` from `github_access_denied` across
server classification, MCP routes, and continuation delivery, and
renders accurate UI guidance without a misleading "Manage GitHub access"
link for external repositories.
> - The benefit is that unreachable external-org writes fail immediately
with actionable alternatives (post directly on GitHub, use a PAT
connection, or have an org admin install the App and refresh access),
suspended installations get explicit unsuspend guidance, and missing
repository grants on installed organizations keep the existing "Manage
GitHub access" and "Refresh access" repair flow.
## Linked Issues or Issue Description
No public issue exists. Refs #19315, #19655, #20141.
**What happened?**
When an agent requested an approval-gated GitHub write targeting a
public repository owned by an external organization where the Paperclip
GitHub App was not installed, Paperclip posted a normal approval card.
After the user approved it, GitHub returned `403 Resource not accessible
by integration`, and both the failed approval card and agent
continuation instructions advised clicking "Manage GitHub access" and
"Refresh access", which cannot grant write access to a third-party
organization.
**Expected behavior**
Paperclip should check managed GitHub App write targets against the
grant's installed accounts before posting an approval card, fail
unreachable external-organization writes cleanly without wasting an
approval, preserve suspended installations separately with unsuspend
guidance, keep incomplete webhook-invalidated snapshots on
`github_access_denied` until refreshed, and present accurate
alternatives in both the UI card and agent continuation instructions.
**Steps to reproduce**
1. Connect GitHub via the managed GitHub App installed on one
organization (for example `acme`), with an approval policy on GitHub
writes.
2. Ask an agent to run `create_issue` or `add_issue_comment` targeting a
repository in an external organization where the App is not installed
(for example `external-org/public-repo`).
3. Previously, Paperclip posted an approval card, executed it upon
approval, received `403 Resource not accessible by integration`, and
showed "GitHub access needed" / "Manage GitHub access" plus "Refresh
access" instructions.
**Paperclip version or commit**
`2d065677959b` (`master`, merged cleanly with `331e1a9fd3`)
**Deployment mode**
Local / Paperclip Cloud managed GitHub App connection
## What Changed
- `server/src/services/tool-access/github-access-discovery.ts`,
`packages/db/src/schema/tool_access.ts`,
`packages/shared/src/types/tool-access.ts`,
`packages/shared/src/validators/tool-access.ts`: Preserved suspended
installation owner logins separately in optional
`suspendedInstallationOwnerLogins` so active `installationOwnerLogins`
stays unchanged while suspended orgs are distinguishable from
uninstalled orgs. Added `github_repo_outside_app_installations` to
`ToolAccessReasonCode` and updated
`tests/runner-e2e/source-sdk-public-inputs.json`.
- `server/src/services/tool-access/github-access-errors.ts`: Added
`github_repo_outside_app_installations`,
`github_app_installation_suspended`, `isGitHubAccessErrorCode`,
`extractGitHubTarget` (`owner`+`repo`, `repository: "owner/repo"`,
`organization`/`org`, `fork_repository` destination-only handling, and
GitHub API URL fallback), `suspendedManagedGitHubOwner`,
`findUnreachableManagedGitHubTarget`,
`githubOutsideAppInstallationsInstructions`,
`githubSuspendedInstallationInstructions`, and
`githubAccessErrorInstructions`. Webhook-invalidated/incomplete
snapshots (`bindingSync` set or `installationIds` ahead of
`installationOwnerLogins` with `repositories` cleared) skip pre-check
blocking and stay on `github_access_denied` on runtime `403` until
access is refreshed.
- `server/src/services/tool-access-policy.ts` and
`server/src/services/tool-gateway.ts`: Reused the already-resolved
remote tool context from `resolveGovernedToolCall` (avoiding redundant
connection/grant lookups for non-GitHub providers), routed unreachable
approval-requiring managed GitHub writes through the canonical policy
denial path with `{ claimIdempotencyKey: false }` (inserting
`idempotencyKey: null` atomically in the single `INSERT` so retries
after installing the App are never falsely replayed), and propagated
`github_repo_outside_app_installations` /
`github_app_installation_suspended` (HTTP 403) without echoing raw
provider text into trusted instructions.
- `server/src/routes/tool-gateway.ts`,
`server/src/services/tool-action-delivery.ts`,
`server/src/services/continuation-cause.ts`,
`server/src/services/agent-task-run-telemetry.ts`: Treated all GitHub
access error codes as MCP `tools/call` `isError: true` results, routed
continuation wakes through `githubAccessErrorInstructions`, and
registered `github_repo_outside_app_installations` and
`github_app_installation_suspended` as person-owned `missing_access`
failure codes.
- `ui/src/components/IssueThreadInteractionCard.tsx` and
`ui/storybook/stories/questions-and-approvals/connection-reviews.stories.tsx`:
Added dedicated alert states for `github_repo_outside_app_installations`
("Repository outside GitHub App access", omitting dead-end "Manage
GitHub access") and `github_app_installation_suspended` ("GitHub App
installation suspended", with unsuspend guidance and "Manage GitHub
access"), using existing design tokens only, while keeping "GitHub
access needed" for `github_access_denied`.
- `doc/connections/GITHUB.md`: Documented pre-check, suspended
installation, incomplete webhook snapshot, and error classification
behavior.
- Added unit, UI component, and embedded-Postgres integration tests in
`server/src/services/tool-access/github-access-errors.test.ts`,
`server/src/__tests__/github-grant-metadata.test.ts`,
`server/src/__tests__/tool-gateway.test.ts`,
`server/src/__tests__/tool-gateway-action-approvals.test.ts`, and
`ui/src/components/IssueThreadInteractionCard.test.tsx`.
## Verification
- `pnpm vitest run
server/src/services/tool-access/github-access-errors.test.ts
server/src/services/tool-access/github-default-owner.test.ts
server/src/__tests__/github-grant-metadata.test.ts
ui/src/components/IssueThreadInteractionCard.test.tsx`: 4 files, 140/140
passed.
- `pnpm vitest run server/src/__tests__/tool-gateway.test.ts -t
"GitHub"`: 13/13 passed (covers pre-check blocking with atomic
`idempotencyKey: null`, installed-org missing-repo
`github_access_denied`, direct + MCP HTTP route `isError: true`,
approved-card runtime 403 URL classification, post-install retry,
suspended installation `github_app_installation_suspended`, and
webhook-invalidated `bindingSync` snapshot pass-through).
- `pnpm vitest run
server/src/__tests__/tool-gateway-action-approvals.test.ts -t "tells the
agent how to recover from"`: 9/9 passed (including
`github_repo_outside_app_installations` and
`github_app_installation_suspended` continuation wakes).
- `pnpm --filter @paperclipai/shared typecheck && pnpm --filter
@paperclipai/db typecheck && pnpm --filter @paperclipai/server typecheck
&& pnpm --filter @paperclipai/ui typecheck`: passed (0 errors across all
7 server layers, shared, db migration safety/compatibility, and UI +
Storybook catalog).
- `pnpm check:token-gates`: all 4 gates clean.
- `node tests/runner-e2e/source-sdk-public-inputs.mjs
|
||
|
|
38e3a71669 |
fix(connections): use Slack MCP user OAuth flow and surface OAuth errors in setup UI (#22976)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work.
> - Apps and Connections let operators connect external providers
through remote MCP servers and OAuth.
> - Slack's curated `mcp-oauth` method pins Slack's bot install
endpoints (`oauth/v2/authorize` and `oauth.v2.access`) while sending
user-only scopes (`search:read.public`, `search:read.private`, etc.) in
`scope`, so Slack rejects sign-in with `"Invalid permissions
requested"`.
> - In addition, when OAuth fails or returns an error for a
customer-owned OAuth app like Slack, `ConnectionSetupFlow`'s `KeyStep`
drops `oauthError` completely, hiding the failure banner, and
`OAuthClientFields` hides the method's `guidanceMd` prerequisites.
> - This pull request switches Slack's `mcp-oauth` method to Slack's
documented MCP user OAuth endpoints (`oauth/v2_user/authorize` and
`oauth.v2.user.access`), propagates allowlisted RFC OAuth
`providerError` codes without reflecting untrusted provider prose,
displays OAuth errors and popup fallback links on `KeyStep`, and renders
setup prerequisites (`guidanceMd`) beside customer OAuth fields.
> - The benefit is that customer-owned Slack MCP sign-in succeeds
(including when resuming pre-fix drafts) and any OAuth error or Slack
MCP prerequisite is clearly shown to the user.
## Linked Issues or Issue Description
Fixes: #13935
Refs #17258
Refs #14037
Builds on #17258 (`fix/slack-mcp-user-oauth-flow`) and adds the missing
customer-OAuth error surface and setup guidance in
`ConnectionSetupFlow`.
## What Changed
- Updated `packages/shared/src/app-definitions/slack.json` and
`scripts/ingest-app-definitions.mjs` so Slack's `mcp-oauth` method uses
`https://slack.com/oauth/v2_user/authorize` and
`https://slack.com/api/oauth.v2.user.access`, and added Slack MCP
prerequisites (`User Token Scopes`, callback URL, and `Model Context
Protocol`) to `guidanceMd`.
- Updated `server/src/routes/tool-access.ts` to propagate allowlisted
RFC `providerError` codes (`normalizeOAuthProviderError`, excluding
`unrecognized`) via `provider_error` on OAuth recovery redirects and
connection-intent postMessages, while continuing to never read or
reflect untrusted `error_description` or `error_uri`.
- Updated `ui/src/features/connections/ConnectionSetupFlow.tsx` and
`ui/src/lib/oauthWindowOutcome.ts` so:
- `KeyStep` renders `oauthError` (not only `connectMutation.error`) and
the `"Open sign-in in a new tab"` fallback link when popups are blocked.
- `oauthCallbackErrorMessage` and `oauthFailureMessage` map allowlisted
`providerError` values (such as `invalid_scope`, `invalid_redirect_uri`,
`invalid_client`) and Paperclip failure codes (including
`slack_mcp_access_disabled`) to actionable Paperclip-authored copy.
- Opener popup polling reads same-origin failure `code` and
`provider_error` details from the returned callback URL.
- `OAuthClientFields` renders `method.guidanceMd` for required
customer-owned OAuth apps whose client secret is optional.
- Updated `tests/runner-e2e/source-sdk-public-inputs.json` for the
changed `@paperclipai/shared` sources.
- Updated Slack OAuth test fixtures in
`server/src/__tests__/tool-access-service.test.ts` and
`server/src/services/tool-access/oauth/client-settings.test.ts`, and
added regressions in `packages/shared/src/app-definitions.test.ts`,
`server/src/__tests__/tool-access-service.test.ts`,
`ui/src/features/connections/ConnectionSetupFlow.oauth.test.ts`, and
`ui/src/features/connections/ConnectionSetupFlow.slack-oauth.test.tsx`.
## Verification
- Shared, UI, and OAuth client-settings unit + DOM tests (95/95 passed):
- `pnpm exec vitest run packages/shared/src/app-definitions.test.ts
ui/src/features/connections/ConnectionSetupFlow.oauth.test.ts
ui/src/features/connections/ConnectionSetupFlow.slack-oauth.test.tsx
ui/src/features/connections/ConnectionSetupFlow.architecture.test.ts
server/src/services/tool-access/oauth/client-settings.test.ts`
- Embedded-Postgres server OAuth start + legacy-draft upgrade + callback
error redirect + redaction tests:
- `pnpm exec vitest run server/src/__tests__/tool-access-service.test.ts
-t "uses Slack user OAuth endpoints even for legacy drafts|starts OAuth
from|refreshes|personal|slack"` (33 passed)
- `pnpm exec vitest run
server/src/__tests__/generic-mcp-connection.test.ts -t "returns browser
denials|denied and cancelled callbacks|redacts"` (9 passed)
- Typechecks & guardrails:
- `pnpm --filter @paperclipai/shared typecheck && pnpm --filter
@paperclipai/server typecheck && pnpm --filter @paperclipai/ui
typecheck` (all passed)
- `node scripts/check-test-budget.mjs --files
packages/shared/src/app-definitions.test.ts
server/src/__tests__/tool-access-service.test.ts
server/src/services/tool-access/oauth/client-settings.test.ts
ui/src/features/connections/ConnectionSetupFlow.oauth.test.ts
ui/src/features/connections/ConnectionSetupFlow.slack-oauth.test.tsx`
(PASS)
- `pnpm verify --base
|