Commit Graph
3733 Commits
Author SHA1 Message Date
Dotta 4ba596d268 fix(slack): recognize pre-pool Cloud stacks in managed Slack setup (#23783)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The Slack chat connector supports managed one-click setup on
Paperclip Cloud instances when
`PAPERCLIP_SLACK_MANAGED_SETUP_ENABLED=true` is set.
> - `createSlackManagerGrants` checked only `getCloudRuntimeIdentity()`
to detect a Cloud instance.
> - Pre-pool Cloud stacks have `isCloudManagedInstance() === true` (the
canonical Cloud predicate used by `/api/health`) but do not have a
persisted warm-pool runtime identity, so `getCloudRuntimeIdentity()`
returns `null`.
> - As a result, `/api/companies/:companyId/chat-slack/setup-options`
returned `defaultMethod: "automatic"` and `managedAvailable: false` on
those stacks, hiding managed Slack setup.
> - This pull request checks `Boolean(getCloudRuntimeIdentity()) ||
isCloudManagedInstance()` in `manager-grants.ts` and adds unit tests for
pre-pool Cloud stacks, self-hosted instances, and disabled flags.
> - The benefit is that managed Slack setup works consistently across
all Paperclip Cloud stacks while self-hosted instances remain completely
excluded.

## Linked Issues or Issue Description

**What happened?**

On a Paperclip Cloud stack without a warm-pool runtime identity record,
`GET /api/companies/:companyId/chat-slack/setup-options` returns
`{"defaultMethod":"automatic","managedAvailable":false,"workspaces":[]}`
even when `enableChatConnectors` is enabled,
`PAPERCLIP_SLACK_MANAGED_SETUP_ENABLED=true` is set, and the Cloud
Connector Broker advertises `slack.manager`.

**Expected behavior**

Any Paperclip Cloud stack where `isCloudManagedInstance()` is `true`,
`PAPERCLIP_SLACK_MANAGED_SETUP_ENABLED=true`, and Cloud Connector Broker
credentials are present should select `defaultMethod: "managed"` and
query the broker for `slack.manager` availability. Self-hosted instances
must continue to stay on `defaultMethod: "automatic"`.

**Steps to reproduce**

1. Run a Paperclip Cloud stack that sets
`PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN` (or `PAPERCLIP_MANAGED_CONFIG`)
without a persisted warm-pool `cloud-runtime-identity/v1` row.
2. Enable `enableChatConnectors` and set
`PAPERCLIP_SLACK_MANAGED_SETUP_ENABLED=true` with valid
`PAPERCLIP_CLOUD_CONNECTOR_*` credentials.
3. Call `GET /api/companies/:companyId/chat-slack/setup-options`.
Observe `defaultMethod: "automatic"` and `managedAvailable: false`.

**Paperclip version or commit**

`306437a2a5` (and `7e025ae65f`)

## What Changed

- Updated `server/src/services/connectors/slack/setup/manager-grants.ts`
to compute `const isCloud = Boolean(getCloudRuntimeIdentity()) ||
isCloudManagedInstance();` instead of relying only on
`getCloudRuntimeIdentity()`.
- Added
`server/src/services/connectors/slack/setup/manager-grants.test.ts`
verifying that:
- Pre-pool Cloud stacks (`isCloudManagedInstance()` true, no runtime
identity) select `defaultMethod() === "managed"` when
`PAPERCLIP_SLACK_MANAGED_SETUP_ENABLED=true`.
- Self-hosted instances stay on `"automatic"` even if
`PAPERCLIP_SLACK_MANAGED_SETUP_ENABLED=true` is set.
- Cloud stacks stay on `"automatic"` when
`PAPERCLIP_SLACK_MANAGED_SETUP_ENABLED` is not `"true"`.

## Verification

- `pnpm --filter @paperclipai/server exec vitest run
src/services/connectors/slack/setup/manager-grants.test.ts
src/__tests__/slack-development-manager.test.ts` — 11/11 passed.
- `pnpm --filter @paperclipai/server typecheck` — passed with 0 errors.

## Risks

- Low risk: `isCloudManagedInstance()` is already the canonical Cloud
predicate across the server (including `/api/health`). Self-hosted
instances never set `PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN` or
`PAPERCLIP_MANAGED_CONFIG`, and managed Slack setup still requires
`PAPERCLIP_SLACK_MANAGED_SETUP_ENABLED=true` plus valid
`PAPERCLIP_CLOUD_CONNECTOR_*` credentials and an active broker
`slack.manager` profile.

## 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
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
2026-12-04 17:25:17 -06:00
DottaandPaperclip 039e4c0a57 fix(native): stop paperclip_block from reassigning tasks and audit assignee changes (#23780)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Native Paperclip Runner agents report blockers with
`paperclip_block`, which includes a descriptive `blocker.owner` field
(`kind` and `name`).
> - PR #22962 made `paperclip_block` reassign `issue.assigneeAgentId`
whenever `blocker.owner` named another company agent, including when the
task was only waiting on a durable dependency
(`durable_dependency_blocker_bound`).
> - That collided directly with Paperclip's own execution prompt (which
instructs agents waiting on a child or prerequisite task to call
`set_dependencies` and then `paperclip_block` naming the dependency's
agent), silently transferred task ownership with no return path, could
cross multi-user AI credential boundaries, and omitted the assignee
change from the `issue.updated` activity record.
> - This pull request stops `paperclip_block` from reassigning tasks at
all, preserves the original assignee on dependency-gated blocks, guides
agents toward explicit delegation/reassignment tools (`create_task` +
`set_dependencies`, `reassign_task`, `handoff_case`) at report time when
no dependency exists, and records assignee field changes in native
`issue.updated` activity details.
> - The benefit is that waiting on a dependency resumes the original
owner cleanly, ownership transfers stay explicit and auditable, and
native assignee changes (such as configured review stages) appear in
task activity receipts.

## Linked Issues or Issue Description

Refs #22962, #21265, #22140, #22438.

**What happened?**
When an agent linked a prerequisite task via `set_dependencies` and
followed the execution prompt by calling `paperclip_block` with the
prerequisite's agent as `blocker.owner`, `status-arbiter.ts` emitted
`handoffAgentId` and `status-decision-committer.ts` permanently
overwrote `issue.assigneeAgentId` to that other agent. The same silent
reassignment also occurred on non-dependency `current_track` and
`task_wide` blocks naming another agent. Because
`status-decision-committer.ts` did not record `previousAssigneeAgentId`
/ `assigneeAgentId` in `issue.updated` details, the assignee change was
invisible in task history, and handing a task to an agent bound to
another user's unshared AI credential caused repeated
`ai_connection_credential_not_shared` wake failures.

**Expected behavior**
`blocker.owner` in `paperclip_block` is descriptive and never silently
reassigns a task:
- On dependency-gated blocks (`durable_dependency_blocker_bound`), the
reporting agent remains `assigneeAgentId` and `unblockDescriptor.owner`
so dependency completion wakes the original owner.
- On non-dependency blocks naming another agent, report-time feedback
rejects the report with actionable guidance pointing to `create_task` +
`set_dependencies`, `reassign_task` (or `handoff_case`), or
`blocker.owner.kind: "user"`. If such a report still reaches
finalization, it stays blocked for `"board"` without changing
`assigneeAgentId` or waking the other agent.
- Whenever any committed native status decision changes
`assigneeAgentId` or `assigneeUserId` (for example when starting a
configured review stage), the `issue.updated` activity row records
`previousAssigneeAgentId`, `assigneeAgentId`, `previousAssigneeUserId`,
`assigneeUserId`, and `changes`.

**Steps to reproduce**
1. Create two agents in one company (Agent A and Agent B), an upstream
task assigned to Agent B, and a parent task assigned to Agent A.
2. Link the upstream task as a dependency of the parent task (`blocks`).
3. Have Agent A call `paperclip_block` with `blocker.owner: { kind:
"agent", name: "<Agent B>" }`, then finalize Agent A's run.
4. Observe on `master` that the parent task's `assigneeAgentId` is
silently overwritten from Agent A to Agent B with no assignee-change
fields in the `issue.updated` activity log.

## What Changed

- **`server/src/services/native-runtime/status-arbiter.ts`**:
- Remove `handoffAgentId`, `blockerHandoffLocked`, and
`resolveBlockerHandoff` so `paperclip_block` never reassigns tasks.
- On `durable_dependency_blocker_bound`, keep `unblockDescriptor.owner`
on `{ agentId: input.agentId }` whenever `blocker.ownerKind === "agent"`
(including another agent or an unresolved/deprecated agent label), while
preserving named human/board owners (`#22438`).
- On non-dependency `task_wide` and `current_track` blocks naming
another agent, bind `unblockDescriptor.owner` to `"board"` without
reassigning, waking the other agent, or re-waking the reporting agent.
-
**`server/src/services/native-runtime/native-completion-feedback.ts`**:
- Check dependency readiness (memoized per call) before validating
`blocker.owner.kind === "agent"`: allow dependency-gated blocks naming
the dependency's agent descriptively, and reject non-dependency blocks
naming another or unknown agent with actionable guidance pointing to
`create_task` + `set_dependencies`, `reassign_task` / `handoff_case`, or
`blocker.owner.kind "user"`.
- **`server/src/services/native-runtime/native-run-finalizer.ts` &
`server/src/services/native-runtime/status-decision-committer.ts`**:
- Remove blocker-owner handoff checks and `assigneeAgentId` handoff
patching during finalization and commit.
- Record `previousAssigneeAgentId`, `assigneeAgentId`,
`previousAssigneeUserId`, `assigneeUserId`, and `changes` on native
`issue.updated` activity events whenever a committed native status
decision changes the task assignee.
- **Cleanup**:
- Remove unused
`server/src/services/native-runtime/blocker-owner-handoff.ts` and
`server/src/modules/external-agents/run-authorizer.ts` (and its export
from `server/src/modules/external-agents/index.ts`).
- **Tests**:
- Update `server/src/services/native-runtime/status-arbiter.test.ts` and
`server/src/__tests__/native-status-arbiter-corpus.test.ts` to cover
dependency-gated owner preservation (including chat-bound tasks and
unmatched agent labels) and non-dependency rejection + board fallback
without reassignment.
- Extend
`server/src/services/native-runtime/native-execution-policy-review-stage.test.ts`
to verify `issue.updated` activity details record assignee transitions
for both human and agent configured review stages.

## Verification

- **RED-before-fix (on base `c5a705ce92`)**:
- `pnpm --filter @paperclipai/server exec vitest run
src/services/native-runtime/status-arbiter.test.ts` -> 3 failed | 31
passed (34) (failed because `handoffAgentId` and `{ agentId: "reviewer"
}` were emitted on dependency and non-dependency blocks).
- **GREEN after fix**:
- `pnpm --filter @paperclipai/server exec vitest run
src/services/native-runtime/blocker-owner.test.ts
src/services/native-runtime/evidence-classifier.test.ts
src/services/native-runtime/status-arbiter.test.ts` -> 48 passed (48).
- `pnpm --filter @paperclipai/server exec vitest run
--hookTimeout=120000
src/services/native-runtime/native-execution-policy-review-stage.test.ts`
-> 16 passed (16).
- `pnpm --filter @paperclipai/server exec vitest run
--hookTimeout=120000 src/__tests__/native-status-arbiter-corpus.test.ts
-t "rejects a non-dependency|keeps accepting a human-owned|preserves the
original assignee on a dependency-gated"` -> 5 passed (5 selected; 169
skipped).
- `pnpm --filter @paperclipai/server exec vitest run
--hookTimeout=120000
src/services/native-runtime/native-agent-blocker.integration.test.ts` ->
17 passed (17).
- `pnpm --filter @paperclipai/server typecheck` -> PASS across all 7
layers.
  - `node scripts/check-module-boundaries.mjs` -> PASS.
- `node scripts/check-test-budget.mjs --base origin/master` -> PASS (113
nightly suites validated, 3 test file(s) checked).
- `pnpm --filter @paperclipai/server exec vitest run
../tests/runner-e2e/chat-catalog-domains/internal-timeline-native-milestone.test.ts`
-> 33 passed (33).
- **CI & Reviews on final head `d7c54badca`**:
- GitHub Actions PR workflow run
[`47436506671`](https://github.com/paperclipai/paperclip/actions/runs/47436506671):
`ci / verify` PASS, `ci / e2e` PASS, all 84 checks green/neutral
(including Socket Security, Superagent Security Scan, and Snyk).
- Greptile Review: `5/5` (zero open comments); Ponytail Paperclip
Review: `5/5`; Feynman Nuclear Review: `5/5`.

## Risks

- **Intentional behavior change from #22962**: Agents that previously
relied on `paperclip_block` naming another agent without a dependency to
silently reassign a task will now receive actionable report-time
feedback directing them to `create_task` + `set_dependencies` or
`reassign_task` (and any already-saved result reaching finalization will
fall back to `"board"` without reassigning).
- **Upgrade safety**: Existing `chat-control-recovery-stop.ts` read-only
ancestry checks for historical `bind_blocker` wakes are preserved.
Self-owned blocker continuations (#22140) and named human blocker
routing (#22438) are preserved unchanged.
- No database schema changes or migrations.

## Model Used

- Google Gemini (Antigravity, high reasoning mode with code 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
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-12-04 17:06:43 -06:00
DottaandPaperclip ee05db9e16 fix(budgets): add Anthropic rate cards with family-max fallback and surface paused-agent budget notices (#23658)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Cost accounting prices Anthropic token receipts against rate cards
so budget policies can track spend and enforce hard stops
> - `anthropic-pricing.ts` only had rate cards for `claude-sonnet-5` and
`claude-opus-5-5`, so newer shipped models such as `claude-fable-5-2`
settled as `unpriced`
> - Because budget policies default to `unpriced_usage_policy =
"block"`, creating a spend cap on an agent that ran an unpriced model
immediately triggered a budget hard stop even when observed spend was
far below the limit
> - Meanwhile, the chat thread notice for a budget-paused agent had no
action link and did not state that messages sent while paused will not
receive a reply, and the budget incident card did not clearly explain
unpriced-usage stops or what "Keep paused" does
> - This pull request adds rate cards for shipped Anthropic models with
a conservative family-maximum fallback for uncataloged models, clarifies
the paused-agent chat notice and unpriced budget incident card, and adds
Storybook coverage
> - The benefit is that budget caps track current and future Anthropic
models accurately without false unpriced-usage lockouts, and operators
immediately see why an agent is not replying and where to resolve it

## Linked Issues or Issue Description

**What happened?**

When an agent ran a shipped Anthropic model missing from `RATE_CARDS`
(such as `claude-fable-5-2`), its usage receipts settled with
`costStatus: "unpriced"`. Creating a budget policy (which defaults to
`unpriced_usage_policy: "block"`) immediately fired a hard-stop incident
and paused the agent even when known spend was well below the limit. In
the task chat thread, the paused-agent banner gave no link to the
agent's budget page and did not clearly warn that new messages would not
trigger replies; on the budget incident card, the unpriced-usage stop
looked like a regular spend-limit alert and dismissing it via "Keep
paused" left the agent paused with no clear explanation.

**Expected behavior**

Shipped Anthropic models should have explicit rate cards, and
uncataloged models in a known Claude family (`fable`, `mythos`, `opus`,
`sonnet`, `haiku`) should fall back conservatively to the most expensive
rate card in that family rather than settling as unpriced. When an agent
is paused in chat, the notice should clearly state that messages will
not get a reply until the agent is resumed and provide a direct "Review
budget" link for budget pauses. Unpriced-usage budget stops should
clearly explain why work stopped and that "Keep paused" dismisses the
alert without resuming work.

**Steps to reproduce**

1. Run an agent on `claude-fable-5-2` using direct Anthropic API billing
so usage receipts settle as `unpriced`.
2. Add a monthly budget policy (e.g. $1,000) on that agent.
3. Observe an immediate hard-stop budget incident pausing the agent
despite low observed spend.
4. Return to the agent's chat thread and observe the paused banner lacks
a budget link and does not clearly state that new messages will not get
a reply.

## What Changed

- `server/src/services/anthropic-pricing.ts`: Added explicit standard
API rate cards for shipped Anthropic models (`claude-fable-5-2`, `5-1`,
`5`; `claude-mythos-5-2`, `5-1`, `5`; `claude-opus-5-5`, `5`, `4-8`,
`4-7`, `4-6`, `4-5`; `claude-sonnet-5-5`, `5`, `4-6`, `4-5`;
`claude-haiku-5-5`, `4-5`), normalized optional `[1m]` suffixes, and
added a dynamic family-maximum fallback (`FAMILY_MAX_RATE_CARDS`) so any
uncataloged model in a known Claude family conservatively uses the
highest rate in that group with explicit provenance.
- `server/src/services/anthropic-pricing.test.ts`: Added unit tests
covering `claude-fable-5-2` (including `[1m]`), `claude-sonnet-5-5`,
`claude-haiku-4-5`, family-maximum fallbacks across all five Claude
families, and preserving unknown/non-Anthropic models as unpriced.
- `ui/src/components/IssueChatThread.tsx`: Updated
`IssueAssigneePausedNotice` to state clearly that messages sent while
paused will not get a reply, distinguish budget pauses in the title, and
render a direct "Review budget" link to `${agentUrl(agent)}/budgets`.
- `ui/src/components/BudgetIncidentCard.tsx`: Clarified unpriced-usage
hard stops (`unpriced usage stop`, known spend vs. limit, and why
unpriced usage blocked work) and added a muted note beside "Keep paused"
explaining that dismissing the alert keeps the scope paused.
- `ui/src/components/PausedBudgetNotices.test.tsx`: Added focused jsdom
unit tests for `IssueAssigneePausedNotice` (budget pause link and manual
resume action) and `BudgetIncidentCard` (unpriced-usage hard-stop copy).
-
`ui/storybook/stories/budgets-costs/paused-agent-chat-notice.stories.tsx`:
Added production-component Storybook stories (`BudgetPausedInChat`,
`BudgetPausedWithUnpricedIncident`, `ManuallyPausedInChat`) with
interaction tests.

## Verification

- `pnpm vitest run server/src/services/anthropic-pricing.test.ts
ui/src/components/PausedBudgetNotices.test.tsx`: 2 test files, 30 tests
passed.
- `pnpm --filter @paperclipai/server typecheck`: passed.
- `pnpm --filter @paperclipai/ui typecheck` (including `node
../scripts/storybook-catalog.mjs`): passed.
- Verified all three new Storybook stories interactively in a browser
against local Storybook (`http://localhost:6006`) with zero runtime
errors and passing Storybook play assertions.
- `pnpm verify` exited 2 due to pre-existing untracked local files;
relying on required CI for full-repo coverage.

## Risks

- Low risk. Existing rate cards for `claude-sonnet-5` and
`claude-opus-5-5` keep their exact rates and versions. Family-maximum
fallbacks are intentionally conservative upper bounds and are labeled in
`pricingProvenance.evidence` as estimates rather than invoices.
- Existing already-settled `unpriced` cost events in databases are not
retroactively rewritten; this prevents new runs on shipped or future
Claude-family models from settling as unpriced.

## Model Used

- Google Gemini (Gemini 4 Neon Medium via Antigravity), with file
editing, terminal execution, browser verification, and web search tools.

## Checklist

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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-12-04 15:50:56 -06:00
DottaandPaperclip c56463e6d1 feat(chat): use rich project selector and remove workspace option in GitHub bot settings (#23757)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Chat connections let operators set task defaults for new
conversations, including on GitHub review bot settings and repository
access views.
> - Today, task defaults render a plain native `<select>` for projects
and expose a Workspace selector for GitHub review bots.
> - Operators expect the same searchable, rich project selector used in
the task composer, and GitHub review bot tasks should always use
isolated workspaces / project defaults without a separate workspace
override.
> - This pull request replaces the native project select in
`ChatExecutionDefaults` with `InlineEntitySelector`, hides workspace
configuration for GitHub connections and repositories, and strips GitHub
workspace overrides on the server during reads, writes, and task
creation.
> - The benefit is faster, consistent project selection across chat
connections and simpler GitHub review bot settings that enforce isolated
workspace / project defaults.

## Linked Issues or Issue Description

**What existing behavior does this improve?**

Task defaults in chat connection settings (`ChatExecutionDefaults`),
specifically for GitHub review bot connection settings and
per-repository overrides.

**Subsystem affected**

Cross-cutting (`ui/` and `server/`).

**Current behavior**

`ChatExecutionDefaults` renders a plain native `<select>` for the
default project and displays a Workspace configuration selector on
GitHub review bot settings and repository defaults. Legacy workspace
overrides saved on GitHub endpoints or repositories remain visible and
apply during task creation.

**Proposed behavior**

`ChatExecutionDefaults` uses `InlineEntitySelector` with search, recent
projects, project color icons, and private-project indicators (matching
the task composer). For GitHub review bots (`allowWorkspace={false}`),
the Workspace selector is removed, the workspace choices query is
skipped, and the server strips any workspace override on read, write,
and task creation so new tasks always use isolated workspaces / project
defaults.

**Reason and benefit**

Operators can find projects quickly with the same picker they already
know from the task composer, and GitHub review bots no longer expose a
misleading workspace override that conflicts with isolated workspace /
project defaults.

**Breaking changes**

None for non-GitHub providers (Slack, Discord, Telegram, Teams,
iMessage, Email retain their Workspace selector and stored workspace
overrides). For GitHub review bots, any previously saved workspace
override is ignored so new tasks use isolated workspaces / project
defaults; saved project defaults are preserved.

## What Changed

- Updated `ui/src/components/InlineEntitySelector.tsx` to accept
optional `id` (for `<label htmlFor>`) and `contentClassName` (to match
full-width form triggers) without changing existing callers.
- Replaced the native project `<select>` in
`ui/src/pages/apps/chat/ChatExecutionDefaults.tsx` with
`InlineEntitySelector` (searchable by project name and description,
recent project ordering, colored folder icons, private lock badges,
unavailable-project handling, and stable `projectOptions` memoization).
- Added an `allowWorkspace` prop (default `true`) to
`ChatExecutionDefaults` so non-GitHub connections keep their Workspace
selector while GitHub connections
(`ui/src/pages/apps/chat/ChatEndpointDetail.tsx`) and GitHub
repositories (`ui/src/pages/apps/chat/GitHubBotManagement.tsx`) omit
workspace configuration and skip fetching workspace choices.
- Added `normalizeChatExecutionDefaultsForProvider` and provider-aware
stripping in `resolveChatExecutionDefaults`
(`server/src/services/chat-execution-defaults.ts`) and wired it through
endpoint serialization/updates
(`server/src/services/chat-channels/endpoints.ts`), resource
reads/writes
(`server/src/services/chat-channels/resource-reconciliation.ts`,
`server/src/services/chat-channels/github/resources.ts`), and inbound
task creation (`server/src/services/chat-channels.ts`).
- Added unit and realistic-size (400-project linear read budget) tests
in `ui/src/pages/apps/chat/ChatExecutionDefaults.test.tsx`, helper tests
in `server/src/__tests__/chat-execution-defaults.test.ts`, and an
embedded-Postgres integration test in
`server/src/__tests__/chat-channels/github-setup-and-access.integration.test.ts`.

## Verification

- `npx vitest run ui/src/pages/apps/chat/ChatExecutionDefaults.test.tsx`
— passed (5 tests, including 400-project resource-mode search and
recent-ordering linear read budget).
- `npx vitest run ui/src/pages/apps/chat/chat-ui-contract.test.ts` —
passed (12 tests).
- `npx vitest run server/src/__tests__/chat-execution-defaults.test.ts`
— passed (6 tests).
- `npx vitest run
server/src/__tests__/chat-channels/github-setup-and-access.integration.test.ts
-t "strips workspace overrides"` — passed (embedded Postgres integration
test verifying read, write, and inbound task creation).
- `pnpm --filter @paperclipai/ui typecheck && pnpm --filter
@paperclipai/server typecheck` — passed (exit 0).
- `node scripts/check-module-boundaries.mjs && node
scripts/check-test-budget.mjs && node
scripts/check-query-error-rendering.mjs` — passed.
- CI run on final head `d548e20a75`:
https://github.com/paperclipai/paperclip/actions/runs/47394038195 — all
66 checks passed (Build, Typecheck + Release Registry, policy, verify,
general/serialized/runner/e2e suites, security scans).
- Greptile Review on `d548e20a75`: 5/5 confidence score with zero
unresolved comments.

## Risks

- Low risk. Existing GitHub endpoints or repositories with a legacy
`workspace` entry in `executionDefaults` now ignore that entry and use
the project default / isolated workspace behavior instead. Non-GitHub
chat connections keep existing workspace configuration unchanged.

## Model Used

- Google Gemini 4 Neon (High reasoning mode, with tool use and code
execution) via Antigravity.

## Checklist

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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-12-04 14:23:22 -06:00
DottaandPaperclip ba1fc8884c fix(native-runtime): fix plugin task predecessor resume and confirmed-unavailable retirement (#23772)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The native runtime executes `per_turn` plugin Runner tasks across
remote sandboxes and verifies predecessor lease authority before it
reads checkpoints or resumes sessions.
> - Three coupled defects in predecessor resolution and retirement
caused valid follow-up and retry turns to fail with `Plugin Runner
retained session is not authorized (reason:
predecessor_candidate_missing)`.
> - First, same-run checkpoint reads called `resolvePluginTaskResume`
without `inspectCheckpoint: true`, which rejected an unsettled
predecessor lease before `read_state` could re-attest its status.
> - Second, cross-run checkpoint recovery skipped verified backups and
refused to retire a confirmed-unavailable plugin checkpoint when prior
verification returned `verified`, leaving the unretired root in place to
fail launch resume.
> - Third, `admission_rejected` cleared `runnerTaskIdentity` on the
rejected lease but kept `runnerTaskResumeFrom`, which disqualified the
original predecessor lease on retry; when clearing
`runnerTaskResumeFrom`, the attempted predecessor must still be recorded
inside `runnerTaskAdmissionRejection` so
`materializeNativeResumeRefusedContinuation` preserves automatic
fresh-session continuation.
> - This pull request fixes all three paths while keeping all
stop-proof, scope, and retirement fences intact, and adds red-before-fix
regression tests for each case.
> - The benefit is that `per_turn` plugin Runner tasks recover, retire
confirmed-unavailable checkpoints cleanly, and retry or continue after
admission rejection without spurious authorization failures.

## Linked Issues or Issue Description

**What happened?**

`per_turn` plugin Runner tasks failed on same-run recovery, cross-run
confirmed-unavailable checkpoint retirement, and retry after
`admission_rejected` with `Plugin Runner retained session is not
authorized (reason: predecessor_candidate_missing)`.

**Expected behavior**

1. Same-run checkpoint reads pass `inspectCheckpoint: true` to
`resolvePluginTaskResume` so `read_state` can re-attest status on the
predecessor lease.
2. Cross-run follow-ups inspect verified backups and retire finished
`per_turn` plugin owners (including archiving a verified suspended
`plugin-runner-state.json` receipt) when the provider confirms the prior
checkpoint is stopped and unavailable.
3. `admission_rejected` clears `runnerTaskResumeFrom` alongside
`runnerTaskIdentity` so a subsequent retry lease still resolves the
original predecessor lease, while recording the attempted `resumeFrom`
inside `runnerTaskAdmissionRejection` so
`materializeNativeResumeRefusedContinuation` still schedules a
fresh-session continuation.

**Steps to reproduce**

1. Run a same-run plugin Runner recovery (`resume_dead_runner` or
disposition retry) when the predecessor lease has
`runnerTaskSessionRetained: false`; `migrateRunnerdStateRoot` calls
`resolvePluginTaskResume` without `inspectCheckpoint: true` and fails
with `predecessor_candidate_missing`.
2. Run a cross-run `per_turn` plugin Runner follow-up when the prior
root verifies via `plugin-runner-state.json` or a verified harness
backup and `read_state` confirms `executionStopped: true,
sessionStateAvailable: false`; the prior root is not retired and launch
resume fails with `predecessor_candidate_missing`.
3. Submit a plugin Runner task on `lease2` with `resumeFrom: "task-1"`
that returns `admission_rejected`, release `lease2`, and call
`resolvePluginTaskResume` for `lease3` on the same run; stale
`runnerTaskResumeFrom` on `lease2` disqualifies `lease1` with
`predecessor_candidate_missing`.

**Paperclip version or commit**

`f4baaa4f48` (`master`)

**Deployment mode**

Self-hosted server

## What Changed

- Pass `inspectCheckpoint: true` to `resolvePluginTaskResume` in
`migrateRunnerdStateRoot`
(`server/src/services/native-runtime/native-session-executor.ts`) before
issuing same-run `read_state`, matching `recoverPluginRunnerCheckpoint`
and `environment-task-runtime.ts`.
- Inspect plugin checkpoints in `recoverPluginRunnerCheckpoint` when
`direct === "absent" && prior === "verified"` (verified harness backup
on disk).
- Allow `retireFinishedPerTurnRunnerdOwner` in `migrateRunnerdStateRoot`
when `pluginCheckpointUnavailableConfirmed && verification ===
"verified"`, preserving all existing stop-proof, lease, journal, and
recovery fences.
- Accept a verified suspended `plugin-runner-state.json` receipt in
`readSettledRunnerdProjection` when `options.confirmedGonePluginTask` is
true, and archive `plugin-runner-state.json` alongside continuity
entries in `moveNativeContinuityState` when retiring a
confirmed-unavailable plugin owner.
- Strip `'runnerTaskResumeFrom'` alongside `'runnerTaskIdentity'` on
`admission_rejected` in `executeEnvironmentTask`
(`server/src/services/environment-task-runtime.ts`), record the
attempted `resumeFrom` inside `runnerTaskAdmissionRejection`, and update
`materializeNativeResumeRefusedContinuation`
(`server/src/services/native-runtime/native-provider-capacity-retry.ts`)
to read `runnerTaskAdmissionRejection.resumeFrom` with fallback to
legacy `runnerTaskResumeFrom`.
- Add focused red-before-fix regression tests in
`server/src/services/native-runtime/native-session-executor.test.ts`,
`server/src/__tests__/environment-task-authority.integration.test.ts`,
and
`server/src/services/native-runtime/native-resume-refused-continuation.integration.test.ts`.

## Verification

- Confirmed all 5 new regression test cases failed with
`predecessor_candidate_missing` or stale `runnerTaskResumeFrom` before
applying the production fixes.
- Ran `pnpm --dir server exec vitest run
src/services/native-runtime/native-session-executor.test.ts
src/services/native-runtime/native-session-root-entries.test.ts
src/__tests__/environment-task-authority.integration.test.ts` — 3 test
files passed (1591 passed, 7 skipped, 0 failed).
- Ran `pnpm --dir server exec vitest run
src/services/native-runtime/native-resume-refused-continuation.integration.test.ts`
— 1 test file passed (9 passed, 0 failed).
- Ran `pnpm --dir server typecheck` — passed cleanly across all layers.

## Risks

- Low risk. All existing stop-proof (`remoteExecutionHasStopped`), prior
lease end (`priorRemoteSandboxLeasesEnded`), released controller lease,
and settled journal fences remain enforced before any
confirmed-unavailable plugin checkpoint is retired.
- `plugin-runner-state.json` remains in
`NATIVE_SESSION_ROOT_HELD_ENTRIES` and is only accepted and archived
when `confirmedGonePluginTask` is proven true and
`pluginRunnerdAuthorityLifecycle` matches the exact suspended identity
with no direct `runner/runner-state.json`.
- `materializeNativeResumeRefusedContinuation` falls back to legacy
`runnerTaskResumeFrom` for any lease written before this change.
- No database schema changes or migrations are included.

## Model Used

- Google DeepMind Gemini 4 Neon (Medium reasoning budget) with tool use
and code execution.

## Checklist

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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-12-04 14:20:15 -06:00
DottaandPaperclip 596bb8a512 fix(native-runtime): classify exited plugin Runner on restart reattachment (#23769)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Native remote runs use restart recovery (`reattach_remote_runner`)
to reattach to an existing Runner after a Core restart or deploy
> - For `plugin_task` Runners, `verifyPluginRunnerTaskReattachment`
threw a raw `Error("Plugin Runner is not running")` when the Runner
exited before reattachment, and `migrateRunnerdStateRoot` did not wrap
that error with `withRemoteRunnerTurnProof`
> - Without a structured `RemoteRunnerRecoveryError`, the executor never
emitted `native.remote_runner_recovery_failed` and
`requestRestartInterruptedTurnRetry` could not recognize the exited
Runner, leaving the run permanently failed
> - This pull request updates `verifyPluginRunnerTaskReattachment` to
throw structured `RemoteRunnerRecoveryError` diagnostics (distinguishing
proven `executionStopped === true` exits from `probe_failed`) and wraps
the call in `migrateRunnerdStateRoot` with `withRemoteRunnerTurnProof`
> - The benefit is that stopped `plugin_task` Runners record consistent
exit diagnostics and turn-proof evidence during restart reattachment so
recovery policy can classify and retry them accurately

## Linked Issues or Issue Description

**What happened?**
When Core restarts while a `per_turn` `plugin_task` Runner is active and
the Runner exits before `reattach_remote_runner` runs,
`verifyPluginRunnerTaskReattachment` throws a raw `Error("Plugin Runner
is not running")`. The executor does not emit
`native.remote_runner_recovery_failed`, does not attach
`providerTurnIssued: false` from the controller journal, and
`requestRestartInterruptedTurnRetry` fails to recognize the exited
Runner.

**Expected behavior**
When `status.executionStopped === true`,
`verifyPluginRunnerTaskReattachment` throws a
`RemoteRunnerRecoveryError` with `stage: "process_verification"` and
`reason: "process_not_running"`, attaches best-effort redacted
exited-runner diagnostics from `read_state` when
`status.sessionStateAvailable === true`, and `migrateRunnerdStateRoot`
wraps the error with `withRemoteRunnerTurnProof(error, scoped)`. When
the status probe returns a non-status result or a non-running phase
without `executionStopped === true`, it throws
`RemoteRunnerRecoveryError` with `reason: "probe_failed"` instead of
falsely proving exit.

**Steps to reproduce**
1. Start a native run backed by a `plugin_task` Runner with a controller
journal that proves no turn was issued.
2. Restart Core and trigger `reattach_remote_runner` after the plugin
task reports `executionStopped: true`.
3. Observe that `verifyPluginRunnerTaskReattachment` throws a raw
`Error("Plugin Runner is not running")` and
`executePaperclipNativeSession` does not emit
`native.remote_runner_recovery_failed`.

**Paperclip version or commit**
`f4baaa4f48` (`master`)

**Deployment mode**
Self-hosted server

**Installation method**
Built from source (pnpm dev / pnpm build)

## What Changed

- Updated `verifyPluginRunnerTaskReattachment` in
`server/src/services/native-runtime/plugin-runner-task.ts` to:
- Throw `RemoteRunnerRecoveryError({ stage: "process_verification",
reason: "probe_failed" })` when the status probe does not return `kind:
"status"` or reports `phase !== "running"` without `executionStopped ===
true`.
- Throw `RemoteRunnerRecoveryError({ stage: "process_verification",
reason: "process_not_running", ... })` when `status.executionStopped ===
true`, attaching best-effort redacted `describeExitedRemoteRunner` and
`describeExitedRemoteRunnerReason` diagnostics from `read_state` when
`status.sessionStateAvailable === true` and the identity matches.
- Wrapped `verifyPluginRunnerTaskReattachment(...)` in
`migrateRunnerdStateRoot`
(`server/src/services/native-runtime/native-session-executor.ts`) with
`withRemoteRunnerTurnProof(error, scoped)`, matching non-plugin sandbox
reattachment.
- Added unit tests in
`server/src/services/native-runtime/plugin-runner-task.test.ts` covering
stopped tasks with and without `sessionStateAvailable`, best-effort
`read_state` failure/mismatch, and `probe_failed` responses.
- Added an integration-style executor test in
`server/src/services/native-runtime/native-session-executor.test.ts`
verifying `providerTurnIssued: false` and
`native.remote_runner_recovery_failed` emission on
`reattach_remote_runner` for a stopped `plugin_task`.

## Verification

- Verified red-before-fix failures on both new test suites (`expected
Error: Plugin Runner is not running to be an instance of
RemoteRunnerRecoveryError`).
- `pnpm --dir server exec vitest run
src/services/native-runtime/plugin-runner-task.test.ts` — 120/120
passed.
- `pnpm --dir server exec vitest run
src/services/native-runtime/native-session-executor.test.ts -t
"classifies a stopped plugin_task on reattach_remote_runner|reattaches a
surviving plugin task through its owner"` — 6/6 passed.
- `pnpm --dir server typecheck` — passed.

## Risks

- Low risk. The change is scoped to `verifyPluginRunnerTaskReattachment`
and its `plugin_task` reattachment caller in `migrateRunnerdStateRoot`.
- Any caller or log parser that previously matched the unstructured
`"Plugin Runner is not running"` string now receives the standard
`RemoteRunnerRecoveryError`
(`runner_remote_process_identity_unavailable`) used by other remote
Runner reattachment paths. No existing tests or code in the repository
matched that string.
- Terminal phases without `executionStopped === true` report `reason:
"probe_failed"` rather than `process_not_running`, preserving the
invariant that only explicit `executionStopped === true` proves the task
and descendants stopped.

## Model Used

- Google DeepMind Gemini 4 Neon (Medium reasoning budget)

## Checklist

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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-12-04 14:09:30 -06:00
DottaandPaperclip 244e20a293 fix(server): settle prior pending_cleanup leases and recheck stopped ownership on same-run retry (#23770)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The server environment runtime and sandbox creation ownership layer
coordinate plugin-task leases across same-run retries and resumptions
> - Same-run plugin-task retries can fail with `setup_failed`: `Sandbox
creation has already transferred ownership` in two situations
> - First, `createOwnedSandbox` has a check-then-read race when the
prior lease finishes releasing with a valid termination receipt between
`createdSandboxStopped` and `getLeaseById`
> - Second, same-run native resumption with `nativeLeaseOwner` (without
`nativeRestartRecovery`) leaves `recoverPluginTask` false, and
`recoverPluginTask` in `environmentRunOrchestrator` does not retry plain
`pending_cleanup` plugin leases before checking
`remoteExecutionHasReleased`
> - This pull request closes the `createOwnedSandbox` race, enables
`recoverPluginTask` for same-run `nativeLeaseOwner` resumptions, and
retries prior `pending_cleanup` plugin leases before checking
termination receipts
> - The benefit is reliable same-run plugin-task recovery without
relaxing the invariant that no second sandbox starts without a proven
remote termination receipt

## Linked Issues or Issue Description

**What happened?**
Same-run plugin-task retries and resumptions fail with `setup_failed`:
`Failed to acquire lease for environment ... (plugin): Sandbox creation
has already transferred ownership`. This occurs either when a prior
lease finishes releasing with a stop receipt between
`createdSandboxStopped` and `getLeaseById` in `createOwnedSandbox`, or
when a prior `pending_cleanup` lease is not settled during same-run
recovery.

**Expected behavior**
When a prior lease has already stopped with a valid termination receipt,
`createOwnedSandbox` re-admits the replacement operation cleanly. When a
same-run native resumption runs with `nativeLeaseOwner`,
`recoverPluginTask` retries prior `pending_cleanup` plugin leases; if
teardown succeeds with a stop receipt, the replacement lease acquires
cleanly, and if teardown fails, recovery fails closed with
`native_plugin_recovery_termination_unconfirmed` without creating a
second sandbox.

**Steps to reproduce**
1. Run a `paperclip_runner` task on a plugin environment so an
`attached` row exists in `sandbox_creation_operations`.
2. Leave the prior lease in `pending_cleanup` (or release it with a
valid termination receipt between `createdSandboxStopped` and
`getLeaseById`).
3. Resume or retry the same run; before this change, acquisition fails
with `Sandbox creation has already transferred ownership` or fails
without retrying the `pending_cleanup` teardown.

**Paperclip version or commit**
`f4baaa4f48` (`master`)

## What Changed

- Re-check `createdSandboxStopped(db, operation)` in
`server/src/services/sandbox-creation-operations.ts` when `existing &&
existing.status !== "active"` after `getLeaseById`, and re-admit via
`admit(operation)` when the prior sandbox is proven stopped before
throwing.
- Enable `recoverPluginTask` in
`server/src/services/heartbeat/workspace-preparation.ts` for same-run
native resumptions with `runOptions.nativeLeaseOwner` when
`!restartRecovery`, `!priorVerificationLease`, and
`!portablePreparationLeaseId`.
- Retry prior `pending_cleanup` plugin leases in
`server/src/services/environment-run-orchestrator.ts` (using an atomic
`pendingCleanupInFlight` claim, `retryPendingSandboxTeardown`, and
`releaseLease`) before checking `remoteExecutionHasReleased`, releasing
the in-flight flag on failure and failing closed with
`native_plugin_recovery_termination_unconfirmed`.
- Add red-before-fix regression tests in
`server/src/__tests__/plugin-runner-task.integration.test.ts` and
`server/src/services/heartbeat/workspace-preparation.test.ts`.

## Verification

- Verified red-before-fix failures before editing production code:
- `pnpm --dir server exec vitest run
src/__tests__/plugin-runner-task.integration.test.ts -t
"pending_cleanup|createOwnedSandbox"` (3 failed: `pending_cleanup`
teardown not attempted /
`native_plugin_recovery_termination_unconfirmed`, and
`createOwnedSandbox` threw `Sandbox creation has already transferred
ownership`).
- `pnpm --dir server exec vitest run
src/services/heartbeat/workspace-preparation.test.ts -t "enables
recoverPluginTask"` (1 failed: `recoverPluginTask` was `false`).
- Verified green-after-fix:
- `pnpm --dir server exec vitest run
src/__tests__/plugin-runner-task.integration.test.ts` — 12/12 passed.
- `pnpm --dir server exec vitest run
src/services/heartbeat/workspace-preparation.test.ts -t "enables
recoverPluginTask|retired inherited runner|same-run"` — 4/4 passed.
  - `pnpm --dir server typecheck` — passed across all layers.

## Risks

- Low risk. No database schema or API contract changes.
- Preserves the fail-closed termination invariant: no second sandbox is
created unless every prior lease has a proven
`hasRemoteTerminationReceipt`, and concurrent cleanup attempts are
fenced by `pendingCleanupAttemptId` / `pendingCleanupInFlight`.

## Model Used

- Google DeepMind Gemini 4 Neon (Medium reasoning budget) 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>
2026-12-04 14:09:25 -06:00
DottaandPaperclip 686215ecdb fix(native-runtime): wait for prior lease release and read same-lease plugin checkpoint (#23768)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The native runtime coordinates per-turn and plugin-task runner state
across consecutive runs in
`server/src/services/native-runtime/native-session-executor.ts`.
> - A committed per-turn plugin run can finish while its async
environment lease cleanup is still running, so a follow-up run hits
`retirement_refused=prior_lease_active`, quarantines the scoped runner
root, and fails.
> - A same-run plugin-task retry that reuses the same environment lease
without restart recovery also skips `read_state` when local runner
authority is absent, which triggers `authority_indeterminate` and
quarantines the root.
> - This pull request adds a bounded wait for prior lease teardown
before refusing `prior_lease_active`, skips quarantine when the prior
lease stays active, and reads the plugin checkpoint on same-lease
retries when local authority is absent.
> - The benefit is that follow-up runs retire finished per-turn owners
cleanly instead of poisoning the scoped runner root, and same-lease
plugin retries verify their checkpoint instead of failing with
`authority_indeterminate`.

## Linked Issues or Issue Description

**What happened?**
When a per-turn plugin run commits its terminal result and its async
environment lease teardown is still in flight, a follow-up run fails
with `runner_state_identity_mismatch:
prior_owner_terminal_state_indeterminate;
retirement_refused=prior_lease_active` and quarantines the scoped runner
state root. On a same-run plugin-task retry that reuses the same
environment lease without restart recovery, `migrateRunnerdStateRoot`
skips reading the plugin runner checkpoint when local runner authority
is absent, which causes `runner_state_identity_mismatch:
authority_indeterminate` and quarantines the scoped root.

**Expected behavior**
Follow-up runs wait briefly for an in-flight prior lease release to
finish and then retire the finished per-turn owner cleanly. If the prior
lease remains active after the bounded wait, the run still refuses with
`retirement_refused=prior_lease_active` without retiring into
`continuity-breaks` and without quarantining the scoped root. Same-run
plugin-task retries on the same lease read and verify the plugin
checkpoint via `read_state` when local runner authority is absent and
unclaimed bootstrap retry does not apply.

**Steps to reproduce**
1. Commit a per-turn plugin run with a bound stop receipt while its
`environment_leases` row is still `status: "active"` and `releasedAt:
null`.
2. Start a follow-up run on a replacement lease before async lease
teardown marks the prior lease released.
3. Observe `migrateRunnerdStateRoot` refuse with
`retirement_refused=prior_lease_active` and move the scoped state root
into `quarantine/`.
4. Start a same-run plugin-task retry reusing
`identity.environmentLeaseId` without `restartRecovery` and without a
local `runner/runner-state.json`.
5. Observe `migrateRunnerdStateRoot` throw
`runner_state_identity_mismatch: authority_indeterminate` and quarantine
the root.

**Paperclip version or commit**
`master` (`f4baaa4f48`)

## What Changed

- Added `priorLeaseReleaseWait` (`5_000 ms` timeout, `100 ms` poll
interval), `isPriorRemoteSandboxLeaseEnded`, and
`waitForPriorRemoteSandboxLeasesToEnd` in
`server/src/services/native-runtime/native-session-executor.ts`.
- Updated `migrateRunnerdStateRoot` to wait for in-flight prior remote
sandbox lease release when `retireFinishedPerTurnRunnerdOwner` returns
`prior_lease_active`, and to retry retirement once if the prior lease
ends during the wait.
- Updated `migrateRunnerdStateRoot` to skip quarantining `scoped` when
retirement still refuses with `prior_lease_active`, matching the
existing non-quarantine behavior for `"active"` and `"unavailable"`.
- Updated `migrateRunnerdStateRoot` to call `read_state` and
`savePluginRunnerCheckpoint` on same-run, same-lease plugin-task retries
without `restartRecovery` when `admitUnclaimedNativeBootstrapRetry` does
not apply and `runnerdAuthorityLifecycle` is `"absent"`.
- Kept this minimal bugfix inside
`server/src/services/native-runtime/native-session-executor.ts` (which
already exceeds 1,000 lines) because it modifies existing state
migration and lease-retirement checks directly in their owning module
without introducing a new subsystem.
- Added red-then-green regression tests in
`server/src/services/native-runtime/native-session-executor.test.ts`
covering in-flight prior lease release, persistent unreleased prior
lease (no retirement and no quarantine), and same-lease plugin
checkpoint verification and mismatch rejection.

## Verification

- Verified all 4 new regression tests failed before the fix
(`retirement_refused=prior_lease_active`, `scoped` moved to quarantine,
and `authority_indeterminate`).
- Ran focused tests after the fix:
- `pnpm --dir server exec vitest run
src/services/native-runtime/native-session-executor.test.ts -t "handles
unconfirmed plugin checkpoint status on replacement lease|retires a
finished per-turn plugin owner|waits briefly for a stopped per-turn
prior lease|admits only an authorized same-run plugin checkpoint|reads
same-lease plugin checkpoint instead of quarantining|reattaches a
surviving plugin task"` (27 passed, including existing
`stopped-lease-unreleased`).
- Ran server typecheck:
  - `pnpm --dir server typecheck` (passed).

## Risks

- Low risk. The bounded wait applies only when
`retireFinishedPerTurnRunnerdOwner` refuses with `prior_lease_active`,
exits early when the prior lease holds the same `providerLeaseId` as the
current run or no prior leases exist, and re-runs the full retirement
proof before retiring. Same-lease `read_state` runs only after unclaimed
bootstrap retry checks and only when local runner authority is
`"absent"`, preserving fail-closed identity verification via
`savePluginRunnerCheckpoint`.

## Model Used

- Google DeepMind Gemini 4 Neon (Medium reasoning budget) with tool use
and code execution.

## Checklist

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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-12-04 14:08:51 -06:00
DottaandPaperclip f5457565de fix(heartbeat): retry setup on retryable remote_incomplete workspace failures (#23764)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Before a run starts its provider, Paperclip prepares the task
workspace through a workspace provider plugin using a deterministic
`operationId`
> - A workspace provider can fail preparation with the closed retryable
reason `remote_incomplete` when a remote storage or runtime request does
not finish
> - Setup recorded `remote_incomplete` as a generic `setup_failed` with
no bounded retry, and release recovery immediately marked the task
`blocked` without retrying the same workspace or showing the workspace
failure reason in the escalation notice body
> - This pull request gives a fresh pre-dispatch `remote_incomplete`
answer its own transient setup code, `workspace_storage_incomplete`,
routes it through the bounded bootstrap retry budget (deferring Sentry
reporting until the retry decision), and forwards saved
`workspaceProviderFailure` details into immediate execution-path
escalation notices
> - The benefit is that a task retries the same workspace automatically
across transient remote storage/runtime failures instead of immediately
blocking for a person

## Linked Issues or Issue Description

Refs #23362, #19249

**What happened?**

When a workspace provider returned the closed retryable reason
`remote_incomplete` (`"Workspace storage operation is incomplete; retry
the same workspace"`) during workspace bootstrap (`executionRecovery: {
kind: "bootstrap", providerWorkStarted: false }`), `failRunSetup`
recorded `errorCode: "setup_failed"` and scheduled no retry. Immediately
after, `releaseIssueExecution` treated `setup_failed` as non-retryable
continuation failure and marked the task `blocked` with a generic notice
that omitted the workspace failure reason.

**Expected behavior**

When a legacy run fails before provider dispatch with a retryable
`remote_incomplete` workspace provider answer, setup must classify it as
`workspace_storage_incomplete` and schedule a bounded bootstrap retry of
the same workspace (matching `workspace_storage_pending` and
`plugin_worker_unavailable`). Sentry must report only when no retry is
scheduled or retries are exhausted, and immediate execution-path
escalation notices must include the bounded `workspaceProviderFailure`
message when present.

**Steps to reproduce**

1. Start a legacy run whose workspace preparation calls a workspace
provider plugin.
2. Have the provider reject preparation with
`PluginWorkspaceOperationError("remote_incomplete")`.
3. Before this fix, `failRunSetup` writes `errorCode: "setup_failed"`,
schedules no bounded retry, and `releaseIssueExecution` immediately
blocks the task.

**Paperclip version or commit**

Reproduced on `master` (`01ecbadbf1`).

**Deployment mode**

Self-hosted server and managed plugin workspace environments
(`authenticated` and `local_trusted`).

## What Changed

- `server/src/services/workspace-provider-failure.ts`: add
`WORKSPACE_STORAGE_INCOMPLETE_CODE` (`workspace_storage_incomplete`) and
`findWorkspaceStorageIncompleteFailure` matching `kind === "provider" &&
reason === "remote_incomplete"`.
- `server/src/services/heartbeat/run-completion.ts`: map a fresh
pre-dispatch legacy `remote_incomplete` failure (with no native session
or runner instance) to `workspace_storage_incomplete`, route it through
`scheduleBoundedRetryForRun` (keeping accepted interaction retries owned
by the interaction lane), and defer Sentry reporting via
`workspaceStorageIncompleteRetry`.
- `server/src/services/failed-preparation-retry.ts`,
`server/src/services/heartbeat/retries.ts`,
`server/src/services/legacy-execution-recovery.ts`,
`server/src/services/recovery/service.ts`,
`server/src/services/agent-task-run-telemetry.ts`: handle
`workspace_storage_incomplete` alongside `workspace_storage_pending`.
- `server/src/services/recovery/stranded-notice.ts` &
`server/src/services/heartbeat.ts`: add a stranded escalation notice for
`workspace_storage_incomplete` and pass `workspaceProviderFailure:
readWorkspaceProviderFailure(input.runRow.resultJson)` into
`buildImmediateExecutionPathRecoveryNoticeSeed`.
- `server/src/services/run-failure-diagnostics.ts` &
`server/src/services/run-failure-report.ts`: add
`workspaceStorageIncompleteRetry` deferred Sentry reporting handshake.
- Add red-then-green regression tests in `run-completion.test.ts`,
`workspace-provider-failure.test.ts`,
`run-failure-report-sandbox-resume.test.ts`, and
`heartbeat-retry-scheduling.test.ts`.

## Verification

- Red before the fix:
- `pnpm --dir server exec vitest run
src/services/heartbeat/run-completion.test.ts -t "incomplete workspace
storage"` failed on the `fresh` scenario with `errorCode:
"setup_failed"` instead of `"workspace_storage_incomplete"`.
- Green after the fix:
- Focused `run-completion.test.ts`,
`run-failure-report-sandbox-resume.test.ts`,
`workspace-provider-failure.test.ts`,
`agent-task-run-telemetry.test.ts`, `heartbeat-retry-scheduling.test.ts`
(`bootstrap retries across restart`), and `pnpm --dir server typecheck`
all pass.

## Risks

- Low risk. No database schema, API route, or plugin wire protocol
changes.
- Retry applies only before provider dispatch on a legacy run with no
native session or runner instance, bounded by the existing bootstrap
retry budget (2 retries). Started and native runs keep `setup_failed`
with no automatic retry.
- Every workspace preparation call carries a deterministic `operationId`
derived from workspace ID, generation, and operation payload, and
`remote_incomplete` is explicitly marked `retryable: true` for the same
workspace.

## Model Used

- Google DeepMind Gemini 4 Neon (Medium reasoning budget), via
Antigravity with tool use (code search, file edits, local test
execution, and GitHub CLI).

## Checklist

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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-12-04 14:08:47 -06:00
e53cce2257 fix: accept nested git worktree folders for local adapters (#7957)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Local adapters such as `codex_local` need workspace validation
before launching agent runs.
> - The validator became too strict by requiring `.git` metadata
directly inside the adapter cwd.
> - Git itself treats subdirectories of a repository as valid worktree
paths, and Codex can operate from those nested folders.
> - Paperclip project folders can be configured as subdirectories inside
a larger Git worktree.
> - This pull request aligns Paperclip validation with Git's own
worktree detection.
> - The benefit is fewer false `workspace_validation_failed` errors
while still rejecting folders outside any Git worktree.

## Linked Issues or Issue Description

- Fixes: #7956

## What Changed

- Replace direct `cwd/.git` metadata checking with `git -C <cwd>
rev-parse --is-inside-work-tree`.
- Add regression coverage for a workspace-linked issue whose adapter cwd
is nested inside a parent Git worktree.
- Clean up the temporary Git fixture created by that regression test.
- Preserve rejection behavior for folders that are not inside any Git
worktree.

## Verification

- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/heartbeat-workspace-session.test.ts`
- `pnpm --filter @paperclipai/server typecheck`

Local validation results:

- `heartbeat-workspace-session.test.ts`: 107 tests passed.
- Server typecheck passed.

## Risks

- Low risk. This changes validation from a stricter direct `.git` file
check to Git's own worktree detection.
- Requires `git` to be available for git-sensitive local adapter
validation. These adapters already require Git-compatible workspaces.
- Still fails closed for missing, invalid, or non-git workspace paths.

> 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

Codex, GPT-5.5, with repository inspection, shell execution, local
runtime validation, and focused 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 run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] If this change affects the UI, I have included before/after
screenshots
- [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: zocomputer <help@zocomputer.com>
Co-authored-by: commitperclip[bot] <284812584+commitperclip[bot]@users.noreply.github.com>
2026-12-04 11:01:45 -08:00
luo jiyinandcommitperclip[bot] 42a800f0cc chore: fix typo cleanup across docs and worker warning (#4305)
Closes #4304

## Thinking Path

> - Paperclip is a control plane for AI-agent companies, so small
wording issues in docs and operator-facing logs still shape day-to-day
usability.
> - This branch only touches low-level text in documentation and one
server warning string.
> - The problem here is narrow: several obvious typos remained in
user-facing docs and a worker parse warning.
> - These should be corrected without changing product behavior, API
contracts, or control-plane invariants.
> - This pull request applies five isolated typo fixes, keeping each
file change minimal and reviewable.
> - The benefit is cleaner documentation and a more polished warning
message with essentially no functional risk.

## What Changed

- Fixed `entreprenuer` -> `entrepreneur` in `README.md`.
- Fixed `entreprenuer` -> `entrepreneur` in `cli/README.md`.
- Fixed `browseable` -> `browsable` in `doc/CLIPHUB.md`.
- Fixed `clonable` -> `cloneable` in
`doc/plans/2026-02-16-module-system.md`.
- Fixed `unparseable` -> `unparsable` in the worker parse warning string
in `server/src/services/plugin-worker-manager.ts`.

## Verification

- Ran `pnpm -r typecheck`.
- Re-checked the touched files with `typos` review workflow.

## Risks

- Low risk. These are text-only changes; the only non-doc edit is a
log-message wording correction with no behavior change.

## Model Used

- OpenAI Codex, GPT-5-based coding agent in the Codex CLI environment;
exact deployed model ID/context window not exposed in-session; used
terminal tool execution, repository inspection, and patch application.

## 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 run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] If this change affects the UI, I have included before/after
screenshots
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: commitperclip[bot] <284812584+commitperclip[bot]@users.noreply.github.com>
2026-12-04 10:58:35 -08:00
DottaandPaperclip 0960dd464d perf(chat): eliminate activity_log seq scans, chat load waterfalls, and transcript storms (#23750)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Persistent agent chat pages (`/:companyPrefix/chats/:agentRef`) are
a primary surface for collaborating with an agent across many tasks and
turns.
> - Opening an active agent chat page was slow: multiple endpoints
scanned the full `activity_log` table, the page bypassed the
single-request chat bootstrap, the native transcript hook aborted and
retried historical run fetches across multiple waves, and pending task
questions triggered N+1 per-task interaction requests.
> - These bottlenecks blocked the initial chat reveal for several
seconds and saturated server and database capacity during page open.
> - This pull request eliminates the `activity_log` sequential scans
with index-backed predicates (no schema migrations), batches
pending-question interaction hydration, defers completed saved-reply run
transcripts in persistent agent chats, stabilizes per-run transcript
lifecycles, and enables parallel chat resolution and chat-bootstrap
adoption on agent chat pages.
> - The benefit is dramatically faster agent chat page loads with far
fewer HTTP requests, zero `activity_log` full-table scans on hot chat
paths, and no schema migrations.

## Linked Issues or Issue Description

Related: #18461, #20355, #21650, #21671.

**What happened?**

Opening a persistent agent chat page with accumulated history and active
tasks took multiple seconds before the conversation became visible and
triggered dozens of concurrent API requests:

1. `decisionHistoryService.list` (`handledForBySource`) scanned all rows
of `activity_log` because `(details ->> 'handledForUserId') IS NOT NULL`
alone did not bind the second key of
`activity_log_company_handled_for_created_idx`, and `decisions` used
`NOT IN (SELECT id FROM issues ...)` which planned a full-company
privacy subquery even when no settled decisions existed.
2. `activityService.forIssue` scanned all rows of `activity_log` because
the `project.created` and `company.skill_created` branches omitted
`entity_type`, preventing index scans.
3. `attentionService.taskQuestions` executed steady-state write
transactions in `decision-retention` and unnecessary plan-document reads
on read paths, and `CoordinatorChatPendingQuestion` mounted an
`AttentionInteractionResolver` per question that fired one `GET
/api/issues/:taskId/interactions` request per pending question.
4. `TaskChatThread` disabled saved-reply transcript deferral in
`conversationMode`, fetching `/events` (and legacy `/log` fallbacks) for
every historical completed run in the comment window, while
`useNativeRunTranscripts` used a single shared `AbortController` that
aborted and restarted in-flight sibling reads whenever run membership or
live-stream state changed.
5. `AgentChat` waited serially for the agent roster and session before
fetching the chat by `:agentRef`, `IssueDetail` skipped
`startIssueChatBootstrap` for conversations, and the HTML preload plugin
omitted the `AgentChat` chunk on `/chats/:ref` hard loads.

**Expected behavior**

Opening an agent chat page resolves the conversation and its first-frame
data in parallel via `chat-bootstrap`, avoids sequential scans on
`activity_log`, avoids fetching completed run transcripts when a saved
reply is already visible, avoids aborting sibling in-flight transcript
reads, and renders pending task questions without per-task N+1
interaction requests.

**Steps to reproduce**

1. Create a company with a persistent agent chat that has 20+ historical
replies from completed native runs, several hundred tasks assigned to
that agent, pending `ask_user_questions` interactions across multiple
tasks, and a large `activity_log` table.
2. Open `/:companyPrefix/chats/:agentRef` directly or from the sidebar
and inspect the network waterfall and PostgreSQL query plans for
`/activity`, `/decision-receipts`, `/pending-questions`, and
`/heartbeat-runs/:id/events`.
3. Observe full-table `Seq Scan` plans on `activity_log`, bypassed
`chat-bootstrap`, repeated aborted `/events` requests, and N+1
`/issues/:taskId/interactions` calls.

**Paperclip version or commit**

Reproduced on `ca21075837` (rebased onto `a3719da3ca`, final head
`2995820afe`).

## What Changed

- **Eliminate `activity_log` sequential scans (zero migrations)**:
- `server/src/services/activity.ts`, `server/src/routes/activity.ts`,
`server/src/routes/issues.ts`: Scope `forIssue` secondary branches by
their canonical `entity_type` (`project` for `project.created`,
`company_skill` for `company.skill_created`) and accept `companyId` from
routes so PostgreSQL uses `BitmapOr` index scans instead of a full-table
`Seq Scan`.
- `server/src/services/decision-history.ts`: Add `(details ->>
'handledForUserId') >= ''` alongside `IS NOT NULL` in
`handledForBySource` so PostgreSQL binds the partial index
`activity_log_company_handled_for_created_idx`; replace
`decision_target_issues.issue_id NOT IN (...)` with correlated `NOT
EXISTS (...)`; add a `LIMIT 1` index probe before planning the full
`decisions` privacy query when no settled decisions exist.
- `server/src/services/conversation-decision-receipts.ts`,
`server/src/routes/issues.ts`: Reuse the route's already-authorized
conversation record instead of re-querying `source()`.
- **Batch pending-question hydration and avoid steady-state retention
writes**:
- `packages/shared/src/types/attention.ts`,
`server/src/services/issue-thread-interactions.ts`,
`server/src/services/attention.ts`: Add optional `interaction?:
IssueThreadInteraction | null` on `AttentionItem`, batch-hydrate
interactions in `issueThreadInteractionService.listByIds` (grouping by
`issueId` for acceptance readiness and skipping only `z.ZodError` legacy
payloads), restrict `planDocumentMap` to actual plan confirmation
interactions, and parallelize `decisionQueueItems` and `decisionTriage`
reads in `enrichAttentionItems`.
- `server/src/services/decision-retention.ts`: Add a read-only fast path
in `syncItems` so steady-state reads skip opening a write transaction
when retention rows are already current, while still syncing and bumping
versions whenever `activityAt` changes.
- `ui/src/components/AttentionInteractionResolver.tsx`,
`ui/src/components/coordinator/CoordinatorChatPendingQuestions.tsx`:
Accept optional `initialInteraction` so inline pending-question cards
render immediately without N+1 `GET /issues/:taskId/interactions`
requests while still honoring cache updates after mutations.
- **Remove agent chat load waterfalls and transcript abort storms**:
- `ui/src/components/TaskChatThread.tsx`,
`ui/src/lib/run-answer-visibility.ts`: Defer completed `succeeded` run
transcripts that already have a visible saved reply in
`conversationMode` while preserving immediate hydration for live,
failed, yielded, pending-interaction, and unanswered runs; precompute
visible-answer lookups in linear time (`O(comments + runs)`) instead of
quadratic scans.
- `ui/src/components/transcript/useNativeRunTranscripts.ts`: Manage
`AbortController`s and poll timers per run instead of one shared
controller so adding sibling runs or transitioning stream health never
aborts in-flight reads or refetches already-hydrated terminal runs;
clear aborted in-flight tracking cleanly so expanding compact history
refetches immediately.
- `ui/src/pages/AgentChat.tsx`, `ui/src/pages/IssueDetail.tsx`,
`ui/src/lib/vite-issue-detail-preload.ts`: Start `agentChatsApi.get` by
`:agentRef` in parallel with roster/session reads on cold loads, enable
`startIssueChatBootstrap` for conversations with an existing issue ID,
and preload the `AgentChat` chunk alongside `IssueDetail` on
`/chats/:ref` hard loads.
- **Tests & SDK pin**:
- Added/updated tests in
`server/src/__tests__/activity-service.test.ts`,
`server/src/__tests__/activity-routes.test.ts`,
`server/src/__tests__/decision-history.test.ts`,
`server/src/__tests__/issue-thread-interaction-routes.test.ts`,
`ui/src/components/AttentionInteractionResolver.initial.test.tsx`,
`ui/src/components/TaskChatThread.test.tsx`,
`ui/src/components/transcript/useNativeRunTranscripts.test.tsx`,
`ui/src/components/transcript/useNativeRunTranscripts.streaming.test.tsx`,
and `ui/src/lib/vite-issue-detail-preload.test.ts`.
- Updated `tests/runner-e2e/source-sdk-public-inputs.json` for
`packages/shared/src/types/attention.ts`.

## Verification

Local disposable PostgreSQL 18.1 benchmark (`200,000` `activity_log`
rows, `455` tasks, `82` interactions, alternating baseline/treatment
samples, `ANALYZE` run, positional `.values()` output equality verified
on both empty and populated `handledForUserId` sets):

| Caller/query | Before median | After median | Samples/spread |
Complete output/contract check | Scope |
| --- | --- | --- | --- | --- | --- |
| `activityService.forIssue(50)` | `53.66 ms` (`50.78 ms` SQL exec,
`11,147` buffers, `Seq Scan`) | `1.84 ms` (`0.31 ms` SQL exec, `23`
buffers, `BitmapOr` index scans) | 7 alternating samples (before
`48.03–62.79 ms`, after `1.34–3.18 ms`, `29.2x` speedup) | Pass (50
positional rows equal) | SQL |
| `decisionHistory.handledForBySource` (40 ids, 0 rows) | `13.71 ms`
(`11,193` buffers, `Seq Scan`) | `0.73 ms` (`2` buffers, `Bitmap Index
Scan` on partial index) | 7 alternating samples (before `11.56–15.45
ms`, after `0.64–0.99 ms`, `18.8x` speedup) | Pass (empty + populated
non-empty positional rows equal) | SQL |
| `decisionHistory.handledForBySource` (40 ids, 1 matching row) | `40.35
ms` SQL exec (`11,193` buffers, `Seq Scan`) | `0.04 ms` SQL exec (`2`
buffers, `Bitmap Index Scan` on partial index) | `EXPLAIN (ANALYZE,
BUFFERS)` | Pass (1 positional row equal) | SQL |

CI and reviews on final head `2995820afe`:
- **GitHub Actions CI (`ci / verify`)**: **PASS** (all 86 check runs
completed with 0 failures; `mergeStateStatus: CLEAN`).
- **Greptile Review**: **5/5** (`SUCCESS`, 0 unresolved findings).
- **Ponytail Paperclip Review**: **5/5** ("No actionable defects found
in the reviewed paths. Verdict: Ship.").
- **Feynman Nuclear Review**: **4/5** ("no confirmed defect in the new
commits").

Tests and builds also verified locally:
- `pnpm --filter @paperclipai/shared build` — pass
- `cd server && node scripts/typecheck-layers.mjs` — pass (all 7 layers)
- `pnpm --filter @paperclipai/ui typecheck` & `pnpm --filter
@paperclipai/ui build` — pass
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/approval-queue-seeding-work.test.ts
src/__tests__/decision-history.test.ts` — pass (28/28 and 14/14 on real
embedded PostgreSQL)
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/activity-service.test.ts
src/__tests__/openapi-routes.test.ts` — pass
- Focused UI suites (`TaskChatThread.test.tsx`,
`useNativeRunTranscripts.test.tsx`,
`useNativeRunTranscripts.streaming.test.tsx`,
`AttentionInteractionResolver.initial.test.tsx`,
`AttentionInteractionResolver.replace.test.ts`,
`IssueDetail.agentChatPanel.test.tsx`,
`vite-issue-detail-preload.test.ts`) — pass

## Risks

- **No schema migrations**: All SQL improvements use existing indexes.
- **Completed chat run transcripts**: Persistent agent chats now defer
completed `succeeded` runs that already have a visible saved reply,
matching compact task behavior. Live, failed, yielded,
pending-interaction, placeholder, progress-only, and hash-targeted runs
still hydrate immediately.
- **Inline interaction hydration**: `AttentionInteractionResolver` uses
`initialInteraction` when provided and valid, skipping the mount-time
`listInteractions` read; mutations and live updates continue to
update/invalidate `queryKeys.issues.interactions(issueId)` and
`["issues", "pending-questions"]`. Unparseable legacy interaction rows
(`z.ZodError`) are omitted from the batch map and fall back cleanly to
the per-issue read.
- **Synthetic local proof vs production**: Local PostgreSQL benchmarks
prove query plan and buffer reductions on synthetic data (`200k` rows);
deployed latency improvements depend on production dataset size and
cache warmth.

## Model Used

Google Antigravity (Gemini) with tool use, terminal execution, and local
embedded PostgreSQL profiling.

## Checklist

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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-12-04 12:28:02 -06:00
DottaandPaperclip c349b060db fix(runner): stop polling plugin task status during active per-turn runs (#23758)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - An environment plugin can run `paperclip_runner` tasks in a remote
computer or sandbox
> - After a task starts, the Paperclip Runner Protocol (PRP) WebSocket
checks if the Runner is alive and gives it a reconnect window across
network or service restarts
> - Warm plugin tasks stop polling the plugin `status` operation once
the task enters the `running` phase, as added in #17390
> - Per-turn plugin tasks, such as Google Antigravity runs, still polled
`status` every 500 ms for the full run and failed the run after a
15-second `status` outage
> - When the plugin host or Launcher restarted for more than 15 seconds
while the Runner and its PRP connection stayed healthy, every active
per-turn run failed as `native_provider_terminal_failed`
> - This pull request stops continuous `status` polling once a per-turn
plugin task is running, and checks `status` only on PRP reconnect, close
quiescence, or stop settlement
> - The benefit is that active per-turn runs survive temporary plugin
`status` outages and do not send recurring database and RPC status polls
during a turn

## Linked Issues or Issue Description

Refs #17029, #17390

**What happened?**

Active per-turn `paperclip_runner` tasks in a plugin environment
continued to call `environmentTask` with `{ kind: "status" }` every 500
ms after the task reached `phase: "running"` and authenticated over PRP.
When `status` calls failed for 15 seconds (for example during a plugin
worker or Launcher rollout) while the Runner and its PRP WebSocket
stayed alive, `createPluginRunnerTaskOwner` rejected
`registration.failure` with `Plugin Runner operation failed; reconcile
the saved task`. The session transport closed with
`notification_transport_failed` (`recoverable: false`), which failed the
run as `native_provider_terminal_failed` and stopped the healthy Runner.

**Expected behavior**

Once a per-turn plugin Runner task reaches `phase: "running"`, PRP owns
live failure detection, just as it does for warm plugin tasks. Temporary
`status` outages during an active turn must not fail a healthy PRP
session, and Core must not poll `status` every 500 ms throughout the
turn.

**Steps to reproduce**

1. Start a `per_turn` native Runner session through
`createPluginRunnerTaskOwner` (for example an ACPX `antigravity` or
`codex` per-turn session).
2. Wait for `registration.ready()` so the Runner task is in `phase:
"running"` and PRP ingress is connected.
3. Make the plugin `status` operation fail for more than 15 seconds
while PRP ingress stays healthy.
4. Before this fix, `registration.failure` rejects with `Plugin Runner
operation failed; reconcile the saved task` and terminates the active
turn.

**Paperclip version or commit**

Reproduced on `master` (`a6f7bcced3`).

**Deployment mode**

Self-hosted server and managed plugin sandbox environments
(`authenticated` and `local_trusted`).

## What Changed

- Stop the startup `readStatus()` loop in `createPluginRunnerTaskOwner`
as soon as a per-turn task reaches `phase: "running"`, matching warm
tasks so PRP owns live failure detection.
- Deduplicate `stop` dispatch (`sendStopOnce()`) and status probing
(`probeStatusOnce()` / `pollUntilStopped()`) across startup abort,
`child.kill()`, `checkpoint()`, reconnect probing, and close quiescence
so `stop` is sent once and status settlement follows one policy.
- Check `status` once without failing the run on PRP reconnect attempts,
including the first post-authentication redial (`connecting` after
authentication resets `attempt` to zero) and later `reconnecting`
attempts. A crashed sandbox Runner (`executionStopped: true`) resolves
`completion` immediately without waiting out the reconnect grace, while
a transient `status` error lets PRP reconnect continue.
- Poll `status` on `quiesce()` when `runner.suspend` commits the Runner
exit (guarding `outbound?.quiesce?.()` for partial test ingress
handles), so `transport.close()` observes natural process exit
immediately without waiting for `waitForProcess` or
`adoptedRunner.isAlive()` to time out.
- Update `doc/plugins/PLUGIN_RUNNER_EXECUTION.md` and add unit,
setup-probe, and real `paperclip-runnerd` two-turn regressions.

## Verification

- Red before the fix:
- `pnpm --dir server exec vitest run
src/services/native-runtime/plugin-runner-task.test.ts` failed in `does
not poll Launcher status or fail an active per-turn task during a
mid-turn status outage` with `Error: Plugin Runner operation failed;
reconcile the saved task`.
- `pnpm --dir server exec vitest run
src/services/native-runtime/plugin-runner-task-warm.integration.test.ts`
failed in `keeps a real per-turn plugin Runner session quiet during an
active turn and settles cleanly on close` with 27 mid-turn `status`
calls instead of 0.
- Green after the fix:
- `pnpm --dir server exec vitest run
src/services/native-runtime/plugin-runner-task.test.ts` (115 passed,
including real `connectRunnerPrpIngress` post-auth disconnect/crash and
startup abort deduplication)
- `pnpm exec vitest run
server/src/services/native-runtime/plugin-runner-probe.test.ts` (15
passed)
- `pnpm --dir server exec vitest run
src/services/native-runtime/plugin-runner-task-warm.integration.test.ts`
(2 passed, including real `paperclip-runnerd` two-turn per-turn
execution and session resume)
- `pnpm --dir server exec vitest run
src/__tests__/plugin-runner-task.integration.test.ts
src/__tests__/environment-task-authority.integration.test.ts
src/__tests__/antigravity-plugin-task-credential-writeback.test.ts
src/services/native-runtime/antigravity-run-start.test.ts` (39 passed)
  - `pnpm --dir server typecheck` (passed across all layers)

## Risks

- Low risk. No database schema, API route, or plugin wire protocol
changes.
- Startup before `phase: "running"` still enforces the 15-second
`readStatus()` deadline, and `checkpoint()` / `child.kill()` still
require `executionStopped: true` before `complete` releases task grants.
- If a sandbox Runner crashes mid-turn while PRP is connected, WebSocket
close triggers a post-authentication reconnect attempt (`connecting`,
then `reconnecting`), which checks `status` once per reconnect cycle and
resolves `completion` immediately when `executionStopped: true` is
reported.

## Model Used

- Google DeepMind Gemini 4 Carbon (Medium reasoning budget), via
Antigravity with tool use (code search, file edits, local test
execution, and GitHub CLI).

## Checklist

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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-12-04 12:27:37 -06:00
DottaandPaperclip cfe5042378 fix(opencode): fix API key env/secret resolution and support Antigravity connector (#23387)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Agent setup, environment testing, and managed AI connections pass
provider API keys into the OpenCode adapter and Paperclip Runner
> - OpenCode setup failed with `Secret not found` when a user supplied a
direct Gemini API key alongside a stale or auto-selected secret binding,
and the OpenCode runtime reported `GOOGLE_GENERATIVE_AI_API_KEY` missing
because Paperclip only passed `GEMINI_API_KEY` and limited OpenCode to
OpenRouter credentials
> - Users need reliable direct provider API keys and Google/Antigravity
API-key connectors across legacy OpenCode, native Paperclip Runner, and
Plugin Runner environments without exposing raw keys to child tool
shells
> - This pull request strips probe-overridden secret references
(including symmetric Google key aliases) before secret resolution,
prioritizes pasted API keys in setup, routes direct OpenCode provider
credentials through a runner-owned loopback proxy, and enables API-key
AI connections (including the Google / Antigravity connector) for
`opencode_local`
> - The benefit is that OpenCode agents test and run reliably with
direct provider keys or connected Google/Antigravity API keys without
false `Secret not found`, missing `GOOGLE_GENERATIVE_AI_API_KEY` errors,
or raw key leaks into child environments

## Linked Issues or Issue Description

- Fixes: #23359
- Refs #23370 (related community fix by @dev-787 for the initial Gemini
API key issue)

## What Changed

- **Server test-environment secret stripping and inheritance
(`server/src/routes/agents.ts`)**: Strip any credential key supplied in
`testCredentials` (including the symmetric `GEMINI_API_KEY` /
`GOOGLE_GENERATIVE_AI_API_KEY` pair and `hermes_gateway` `apiKey`) from
both `adapterConfig` and resolved environment `envVars` before secret
persistence normalization and runtime resolution. Scope `opencode_local`
inheritable credential groups from `@paperclipai/shared`
(`OPENCODE_PROVIDER_CREDENTIAL_ENV_KEYS`), skip inheritance when the
child supplies any OpenCode credential, and isolate multi-provider
parents to one matching provider group.
- **UI setup credential precedence (`ui/src/lib/provider-credential.ts`,
`ui/src/components/new-agent/NewAgentSetup.tsx`)**: Prefer an explicitly
entered raw API key over an auto-selected organization or personal
secret, and clear stale provider secret bindings and Google alias keys
when switching credentials or providers.
- **OpenCode direct provider keys and Gemini aliasing
(`packages/adapters/opencode-local/`, `packages/adapter-utils/`)**:
Mirror non-empty `GEMINI_API_KEY` into `GOOGLE_GENERATIVE_AI_API_KEY`
during OpenCode runtime config preparation and model discovery while
preserving blank managed isolation. Register `google`, `xai`, `groq`,
and `opencode` API key names in `api-billing-type`.
- **Runner-owned loopback credential proxy and allowlist parity
(`packages/paperclip-runner/`, `packages/plugins/sdk/`,
`packages/shared/`)**: Export canonical
`OPENCODE_PROVIDER_CREDENTIAL_ENV_KEYS` and
`OPENCODE_CREDENTIAL_ENV_KEYS` from `@paperclipai/shared`. Route direct
OpenCode provider API keys (`google`, `anthropic`, `openai`, `xai`,
`groq`, `opencode`) through a runner-owned loopback proxy
(`packages/paperclip-runner/src/drivers/opencode/provider-proxy.ts`)
with per-session bearer tokens, model-pinned endpoint allowlists, native
upstream auth header injection, request secret redaction, and redirect
refusal so raw keys never enter `opencode serve` child environments or
`opencode.json`. Allow direct provider keys across TypeScript, Rust, and
Plugin SDK allowlists, reserve `GOOGLE_API_KEY` and `GROK_API_KEY` in
TS/Rust configured-environment projections, strip ambient provider keys
(including `OPENROUTER_API_KEY`) from sanitized OpenCode runner
environments unless explicitly supplied, and redact provider keys in
output custody.
- **Antigravity / multi-provider API-key AI connections for OpenCode
(`packages/shared/`, `server/src/services/`,
`ui/src/components/ai-connections/`)**: Enable `api_key` AI connections
for `google` (Antigravity catalog slug), `anthropic`, `openai`, and
`xai` on `opencode_local` (keeping OAuth `subscription` methods
excluded), enforce provider-to-model prefix compatibility, mirror
`GEMINI_API_KEY` to `GOOGLE_GENERATIVE_AI_API_KEY` in
`prepareManagedAiRuntime`, isolate project config with
`OPENCODE_DISABLE_PROJECT_CONFIG=true`, and scope child-auth override
detection in `agent-ai-connection-default.ts` to non-empty OpenCode
credentials (supporting plain values, `secret_ref.secretId`, and
`user_secret_ref.key`).
- **Tests and pinned input registry**: Added unit, route, cross-layer
allowlist parity, and pinned `opencode@1.18.34` `bash`-tool credential
isolation tests across `adapter-utils`, `adapter-opencode-local`,
`paperclip-runner`, `server`, and `ui`, and synchronized
`tests/runner-e2e/source-sdk-public-inputs.json`.

## Verification

- `@paperclipai/adapter-utils`: `src/api-billing-type.test.ts` (17/17
tests), `typecheck`, `build` — passed
- `@paperclipai/adapter-opencode-local`:
`src/server/runtime-config.test.ts`, `src/server/models.test.ts`,
`typecheck`, `build` — passed
- `@paperclipai/shared`: full suite (123/123 files, 1426/1426 tests),
`typecheck`, `build` — passed
- `@paperclipai/paperclip-runner`: `typecheck:typescript`,
`build:typescript`, `check:package-boundaries`,
`opencode-server-driver.test.ts` (101/101 including pinned
`opencode@1.18.34` `bash`-tool test), `output-custody.test.ts` (13/13),
`configured-environment.test.ts` (35/35),
`antigravity-credentials.test.ts` (11/11), and
`durable-prp-control-plane.test.ts` — passed
- `@paperclipai/server`: `typecheck` and targeted suites
(`ai-connections.test.ts` 170/170, `agent-hire-ai-connections.test.ts`
84/84, `agent-test-environment-routes.test.ts` 72/72,
`agent-hire-auth-inheritance-routes.test.ts` 29/29,
`plugin-runner-credentials.test.ts` 43/43,
`plugin-runner-credential-names.test.ts` 6/6 cross-layer TS/Rust parity,
`opencode-local-adapter-environment.test.ts` 4/4,
`ai-auth-failure.test.ts` 32/32, `ai-provider-routing.test.ts` 21/21,
`antigravity-runner-credentials.test.ts`) — passed
- `@paperclipai/ui`: `typecheck`, `provider-credential.test.ts`,
`AiConnectionSelect.test.tsx` (20/20 tests) — passed
- `@paperclipai/plugin-sdk`: `build`, `environment-tasks.test.ts`,
`environment-task-release-resume.test.ts` (104/104) — passed on
`03dc341957`
- `@paperclipai/paperclip-runner`: `provider-traffic.test.ts` &
`provider-traffic-proxy.test.ts` alongside OpenCode/Antigravity/custody
suites (169/169) — passed on `03dc341957`
- `node tests/runner-e2e/source-sdk-public-inputs.mjs
03dc341957 --check` — passed (`changed:
false`, 602 inputs)
- GitHub CI on `03dc341957`: all 95 checks green (`MERGEABLE` / `CLEAN`)
— `ci / verify` ([run
47315344108](https://github.com/paperclipai/paperclip/actions/runs/47315344108)),
`ci / e2e`, `Verify Paperclip Runner` (static checks, Rust, Vitest
package & native server suites), `Runner Windows` ([run
47315343800](https://github.com/paperclipai/paperclip/actions/runs/47315343800)),
`Runner image` (`amd64` + `arm64`, [run
47315343840](https://github.com/paperclipai/paperclip/actions/runs/47315343840)),
`macOS OpenCode SSH runtime` ([run
47315343817](https://github.com/paperclipai/paperclip/actions/runs/47315343817)),
`Verify serialized server suites` (1/9–9/9), `Superagent Security Scan`,
`Greptile Review` (5/5), `Paperclip Review` (5/5), `Socket Security`,
and `security/snyk` passed.
- Local verification gap: `cargo` is not installed in this container;
Rust checks (`typecheck:rust` / `test:rust`) ran and passed in GitHub CI
(`verify_paperclip_runner`).

## Risks

- Low to moderate risk. No database schema or migration changes are
included.
- Touches provider credential allowlists in both TypeScript and Rust
(`codex_provider.rs`, `configured_environment.rs`), the runner-owned
loopback proxy for direct OpenCode providers, and secret-stripping logic
in `POST /companies/:companyId/adapters/:type/test-environment`. Parity
between TypeScript and Rust allowlists is enforced by
`plugin-runner-credential-names.test.ts`, and Rust build/test checks
pass in CI.
- `opencode_local` AI connection compatibility enforces that the
selected model prefix matches the connected provider (for example,
`google/...` for a Google/Antigravity API-key connection). Existing
`openrouter/...` connections remain compatible.

## Model Used

- Google Gemini (Antigravity agent runtime) with reasoning, repository
code navigation, shell execution, and automated 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
- [ ] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-12-04 12:20:32 -06:00
DottaandClaude Opus 5.5 a6f7bcced3 fix(native): release a superseded failed run's foreign owner after the bounded wait (#23696)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Native runs keep a finalization claim. The expired-owner pass
(`native-failed-run-owner-release.ts`) settles the claim of a run that
already failed, after it proves the old owner stopped.
> - A run can fail while its controller on another server still holds
that claim. The pass cannot verify a controller in another process
space. It holds the task for the board and names the old run.
> - When the task has moved on to a newer run, nothing ends that hold.
Restart recovery stops at `issue_execution_lock_changed`. Operator
containment accepts only the local reason. The active hold also removes
the pass's only wake.
> - This pull request lets the expired-owner pass release such an owner
after the existing bounded wait, with its existing proofs. It also
resolves the hold that names the old run.
> - The benefit is that the task is not blocked indefinitely. Automatic
continuation and the user's Retry work again.

## Linked Issues or Issue Description

Refs #19131 (related: it retires `retryable_failure` sources only after
a committed successor. It does not cover an `observed` claim whose
successor also failed.)

**What happened?**
A native run failed while its controller on another server still held
its finalization claim (phase `observed`). A newer run of the same task
started after it. Then:
- the expired-owner pass could not verify the foreign controller, so it
opened a board-owned `native_restart_recovery_blocked` hold that names
the old run;
- restart recovery checked the old run every minute and returned
`issue_execution_lock_changed` with no write;
- operator containment accepts only the local
`controller_process_space_unverified` reason, not the remote one;
- `nextAbandonedNativeOwnerReleaseAt` excludes rows with an active hold,
so the pass had no wake for this row.

The user's Retry was refused with `previous_execution_unverified`, and
assigned-work wakes were refused every cycle. The task stayed blocked
for more than 9 hours.

**Expected behavior**
An unverifiable lapsed controller is system uncertainty, not a person's
decision. When a newer run has taken over the task, the old claim must
settle after the bounded wait, and the task must continue on its normal
paths.

**Steps to reproduce**
1. Make a native run fail while its coordinator stays `observed` with a
lease owner from another process space.
2. Clear the task's execution lock and start a newer run of the same
task.
3. Run `releaseAbandonedNativeOwners`. It opens the board hold.
4. Before this change: `nextAbandonedNativeOwnerReleaseAt` returns
`null`, and later passes never settle the claim or the hold.

## What Changed

All changes are in `native-failed-run-owner-release.ts`, in the existing
`expired_owner` release:
- For a foreign-space owner, the pass now releases the claim when all of
these are true: the task's lock is not on the run, a newer run of the
task exists, the lease lapsed at least
`NATIVE_NAMESPACE_UNVERIFIED_WAIT_MS` ago, the run has no recorded
process (PID or group), and the owner is not a finalizer/cleanup owner.
Otherwise it keeps the old behavior (surface the board hold, return).
- The existing proofs still apply: settled environment lease, no pending
Stop, `runProcessMayBeLive` (in-process executions, live controller
lease, recorded process), and no accepted result. Only the foreign
controller probe is skipped, because a foreign PID is not local
evidence. This is the same bounded-wait policy restart recovery uses for
unverifiable controllers.
- The settlement uses the existing write path: `terminal_failure`,
activity entry `native.failed_run_owner_released` (now with
`supersededByRunId`), and settlement notifications. It records
`successorRunId` and `supersededByRunId`, and resolves (`cancelled`) the
board hold whose fingerprint is `native-controller-space:<runId>:…`.
- `nextAbandonedNativeOwnerReleaseAt` now also wakes the pass at
`leaseExpiresAt + NATIVE_NAMESPACE_UNVERIFIED_WAIT_MS` for such an
attended owner.
- The first revision changed restart recovery and
`native-superseded-retry.ts`. After review, those changes are removed.

## Verification

- New
`server/src/services/native-runtime/native-superseded-failed-owner.integration.test.ts`
(embedded Postgres, real owner-release pass):
- Before the fix (master code): `releases the old owner and its hold
once the bounded wait has passed` failed.
`nextAbandonedNativeOwnerReleaseAt` returned `null` after the hold was
raised.
- After the fix: 7/7 pass. The claim goes to `terminal_failure` with
`successorRunId`. The run keeps `failed` and
`native_session_interrupted`. The lock stays `null`. No active hold
remains. One activity entry is written, and a later pass does not raise
the hold again.
- Safety cases (pass before and after): the claim and the hold stay
unchanged within the bounded wait, with no newer run, with a recorded
run process, with a live run controller lease, while this server
executes the run, and while the task's lock is on the run.
- Neighbouring suites: `native-failed-run-owner-release.test.ts`,
`execution-control-work.test.ts`,
`native-restart-recovery-isolation.test.ts` (63 passed with the new
file). `heartbeat-native-restart-suspension`,
`task-interruption-automatic-path`, `execution-projection`,
`native-runner-restart-recovery.integration` (421 passed, 22 skipped).
- I did not run the full server typecheck locally because of the sandbox
memory limit. CI runs it.

## Risks

- Scope: only a foreign-space owner of a run that already ended, when a
newer run of the same task exists and the run has no recorded process.
Other cases keep their behavior.
- Safety: the old controller's stop is still not verified. This follows
the existing bounded-wait policy for unverifiable controllers. A newer
run already holds the task, so this changes no isolation decision. The
release does not start a turn and does not change the task's lock.
- Load: one extra indexed query in the release-time calculation. A due
row that still cannot be released (for example, an accepted result)
makes the pass check at the normal reconciliation interval.
- Unchanged: the separate defect where the finish call of a run is not
captured (`native_finalization_missing` with `reportedWorkDisposition:
yielded`).

## Model Used

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

## 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
- [ ] I will address all Greptile and reviewer comments before
requesting merge

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 11:22:13 -06:00
Dotta c5a705ce92 fix(trust): enforce low-trust sourceTrust quarantine on native comments and documents (#23621)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The low-trust review preset isolates untrusted agent runs and marks
their raw outputs with `sourceTrust` quarantine metadata so higher-trust
agents do not ingest raw output without promotion
> - HTTP route writes tagged low-trust comments and documents with
`sourceTrust`, but internal native completion replies, finalizer
recoveries, continuation summary updates, and non-Muse native runner
tool writes (`report_progress`, `write_document`) persisted
`sourceTrust: null`
> - Higher-trust non-Muse native runner reads (`list_documents`,
`read_document`) also bypassed document quarantine redaction
> - This pull request resolves `sourceTrust` centrally in
`issueService.addComment` and `documentService.upsertIssueDocument`
whenever an agent writes without an explicit `sourceTrust` value,
removes the `museRuntime` gate on native runner `report_progress` and
`write_document` writes, and redacts quarantined documents on
higher-trust non-Muse native runner reads
> - The benefit is that raw outputs from low-trust native runs retain
quarantine metadata across all comment and document write paths and stay
redacted from higher-trust agents until promoted

## Linked Issues or Issue Description

**What happened?**
When an agent running under the `low_trust_review` preset completed a
native run or called native runner tools (`report_progress`,
`write_document`), its comments and documents were saved with
`sourceTrust: null`. Because `sourceTrust` was null, higher-trust agents
could read the raw low-trust output directly through ordinary comment
and document access without promotion.

**Expected behavior**
All agent-authored comments and documents produced under
`low_trust_review`—including native run completion replies, recovered
finalizer replies, continuation summary updates, and non-Muse native
runner `report_progress` / `write_document` writes—must persist
`sourceTrust` with `preset: "low_trust_review"` and `disposition:
"quarantined"`, and higher-trust agents must receive the quarantined
redaction placeholder instead of the raw body.

**Steps to reproduce**
1. Configure an agent with `trustPreset: "low_trust_review"` and a valid
`trustBoundary`.
2. Run a native task on that agent so it writes a completion reply,
calls `report_progress` or `write_document`, or refreshes
`continuation-summary`.
3. Read the resulting comment or document as a standard-trust agent via
`get_task_history`, `list_documents`, `read_document`, or ordinary
comment reads.
4. Before this fix, `sourceTrust` is `null` and the raw body is returned
unredacted.

**Paperclip version or commit**
`master` (`ce204a223a`)

## What Changed

- **`server/src/services/issues.ts`**: Updated `issueService.addComment`
to select `projectId` and `executionPolicy` on the target issue and
resolve `sourceTrust` via `resolveActorSourceTrustForIssue` whenever
`actor.agentId` is set and `options?.sourceTrust === undefined`. This
covers native run completion replies (`run-completion.ts`), recovered
finalizer replies (`native-run-finalizer.ts`), status decision committer
comments (`status-decision-committer.ts`), and internal agent comment
writes.
- **`server/src/services/documents.ts`**: Updated
`documentService.upsertIssueDocument` to select `projectId` and
`executionPolicy` on the target issue and resolve `sourceTrust` via
`resolveActorSourceTrustForIssue` whenever `input.createdByAgentId` is
set and `input.sourceTrust === undefined`. This covers continuation
summary refreshes (`issue-continuation-summary.ts`), native plan writes
(`native-session-executor.ts`), and internal agent document writes.
-
**`server/src/services/native-runtime/paperclip-runner-tool-authority.ts`**:
Removed the `this.binding.museRuntime` guard on
`resolveActorSourceTrustForIssue` in `report_progress` and
`write_document` so all `paperclip_runner` runs tag writes consistently,
and added higher-trust quarantine redaction
(`redactQuarantinedBodyForHigherTrust`) for non-Muse `list_documents`
and `read_document` reads.
- **`server/src/__tests__/source-trust.test.ts`**: Added red-green
regression tests covering `addComment` without explicit `sourceTrust`,
`upsertIssueDocument` without explicit `sourceTrust`, and non-Muse
`PaperclipRunnerToolAuthority` `report_progress` / `write_document`
writes read by a higher-trust agent via `get_task_history`,
`list_documents`, and `read_document`.

## Verification

- Confirmed the new regression tests failed before the fix
(`sourceTrust` received `null` on `addComment` and
`upsertIssueDocument`).
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/source-trust.test.ts` — 10/10 passed.
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/low-trust-red-team-routes.test.ts` — 14/14 passed.
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/issue-continuation-summary.test.ts` — 8/8 passed.
- `pnpm --filter @paperclipai/server typecheck` — passed with 0 errors.
- `pnpm verify` exited 2 (broad CI coverage required); CI will run the
full required check matrix on this PR.

## Risks

- Low risk. Standard-trust agent writes continue to resolve to
`sourceTrust: null` (unchanged behavior).
- Callers that already pass an explicit `sourceTrust` value (such as
promotion flows or HTTP routes) keep their explicit value without extra
work.
- Only newly inserted comments and agent-authored document upserts
without an explicit `sourceTrust` perform the policy lookup inside the
existing transaction.

## Model Used

- Google Gemini (Antigravity agentic coding assistant) with tool use and
local code/test execution.

## Checklist

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

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The agent lifecycle module owns agent purge and company deletion.
> - The repository test budget rule asks to add a narrow database case
to the owning suite, not to a small standalone file.
> - Two small test files each start their own embedded Postgres for a
few purge cases only.
> - This pull request moves those cases into the agent lifecycle owner
suite and deletes the two small files.
> - The benefit is two fewer test workers and two fewer database setups
in CI, with the same assertions kept.

## Linked Issues or Issue Description

No public GitHub issue exists for this change. The problem is described
here, using the enhancement template labels.

**What existing behavior does this improve?**

The layout of the agent lifecycle test suites and their CI setup cost.

**Subsystem affected**

server/ — REST API & orchestration services (agent lifecycle and company
deletion tests).

**Current behavior**

Two test files each boot an own embedded Postgres for a few purge cases:

- `server/src/services/agent-cost-history-deletion.test.ts` (61 lines)
covers the `agent_cost_history_retained` purge guard.
- `server/src/services/case-deletion.test.ts` (69 lines) covers company
deletion with retained case handoffs and the
`agent_case_history_retained` purge guard.

Each file pays a separate Vitest worker import and a separate embedded
database start. The `rules/test-budget.mdc` rule says: do not keep a
standalone embedded-Postgres file for one narrow regression case; add
the case to the owning service suite. The owner suite
`server/src/modules/agent-lifecycle/__tests__/lifecycle.test.ts` already
imports the same production modules (`createAgentLifecycle`,
`deleteCompany`) and uses the same database fixture.

**Proposed behavior**

The owner suite holds these cases inside two nested describe blocks. The
two small files no longer exist. No assertion changed.

**Reason and benefit**

CI runs two fewer standalone database files in the general server lane.
The moved cases reuse the database the owner suite already started. The
historical duration manifest recorded about 6 s and 8 s per file at its
recorded revision; these weights are scheduling estimates, not measured
savings for this change.

**Breaking changes**

None. Test code only.

## What Changed

- Moved 4 purge cost-history cases (cost event by run, cost event by
agent, finance event by run, and the positive purge case) into the owner
suite under `describe("agent purge with retained cost history")`.
- Moved 3 company-deletion-with-case-handoff cases (an `it.each` over
three handoff states, an `it.each` over source and target roles, and the
unrelated-agent purge case; 6 test registrations in total) into the
owner suite under `describe("deletion with retained case handoffs")`.
- Deleted `server/src/services/agent-cost-history-deletion.test.ts` and
`server/src/services/case-deletion.test.ts`.
- Added the `cases`, `caseAccessSources`, `caseHandoffs`, `costEvents`,
and `financeEvents` table imports to the owner suite.
- Net change: 131 deleted and 102 added test lines. No production line
changed.

The owner suite is a test file and was already longer than 1,000 lines
before this change. Extending the designated owner suite is the remedy
the test budget rule names for these files.

## Verification

Commands run on this branch (head `01bc9384`), local sandbox, Node
v25.9.0:

- `cd server && ../../node_modules/.bin/vitest run
src/modules/agent-lifecycle/__tests__/lifecycle.test.ts` — 1 file
passed, 86 tests passed, all 10 moved registrations included.
- Intended-failure control 1: the `agent_cost_history_retained` guard in
`server/src/services/agent-deletion.ts` was disabled for a moment. The 3
moved cost-history cases failed on their expected 409 conflict. The
positive purge case still passed. The file was then restored with `git
checkout` and the diff was checked clean.
- Intended-failure control 2: the `agent_case_history_retained` guard
was disabled the same way. The 2 moved handoff purge cases failed on
their expected 409 conflict. The other matched cases still passed. The
file was restored the same way.
- `node scripts/check-test-budget.mjs --files
server/src/modules/agent-lifecycle/__tests__/lifecycle.test.ts` — PASS.
- The full owner suite was run again after the restorations: 86 tests
passed.

Not run locally: the repository typecheck and the full test suite. The
runner build dependency for the typecheck did not fit the free disk of
this sandbox. The required CI checks passed on the PR head `01bc9384`:
68 checks succeeded (typecheck, build, all 20 general server test
shards, chat and workspaces-b shards, runner support, Greptile). Six
conditional lanes were skipped as not applicable. Three independent bot
reviews scored the change 5/5 with no findings.

## Risks

- Low risk. Test files only; no production code changed.
- The moved cases now share the database instance the owner suite
starts. Each moved case still creates its own rows with fresh
identifiers, and the controls above show each case still fails at its
own guard.
- The general server shard durations manifest still lists the two
deleted files. The manifest is regenerated from CI runs by
`scripts/ci/refresh-test-durations.mjs`; stale entries do not route
work.

## Model Used

GLM 5.3 (z-ai/glm-5.3; exact model ID `openrouter/z-ai/glm-5.3`), run by
the Paperclip Test Gardener agent, with tool use and code execution. No
extended thinking mode.

## Checklist

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

> - Paperclip is the open source app people use to manage AI agents for
work
> - The sidebar Recents list shows the tasks from a person's own recent
activity
> - A person can run a routine manually with "Run now", and the run
creates a task
> - That task does not show in Recents, and opening it does not keep it
there, because Recents only admits tasks under the Mine participation
rule. This also affects every routine, channel, and agent-created task
that a person opens
> - The Mine rule keeps these tasks out of Mine on purpose, so we must
not change that rule
> - This pull request adds a separate Recents eligibility flag. It also
admits tasks that the viewer opened and tasks from manual routine runs
that the viewer started. The UI records the new task in Recents when the
run starts
> - The benefit is that people can find the task they just started from
the sidebar at once, and Mine stays unchanged

## Linked Issues or Issue Description

**Is your feature request related to a problem? Please describe.**
When I run a routine manually and it creates a task, the task is not in
my Recents list. I must go to the routine or the task list to find it.

**Describe the solution you'd like**
When I run a routine manually and a task is created, add that task to my
Recents list automatically, even if I did not open it.

Also, a task that a routine creates does not show in Recents even after
I open it.

**Additional context**
Mine must continue to keep routine tasks out by default, including
routines that a person starts manually (see `doc/PRODUCT.md`).

## What Changed

- `server/src/services/issue-summaries.ts`: navigation summaries return
a new `isRecentEligibleForMe` flag. It is true when one of these
conditions is true:
  - The viewer participates under the Mine rule.
- The viewer opened the task. The check is the viewer's
`issue_read_states` row, which is unique on company, issue, and user.
- The viewer started the manual routine run that created the task. The
check is a `routine_runs` row found through the indexed
`linked_issue_id`, with `source = 'manual'` and the same ID as the
issue's `originRunId`. The issue `createdByUserId` must be the viewer,
with no creating agent.
  `isParticipantForMe`, Mine, and unread state do not change.
- `packages/shared`: add `isRecentEligibleForMe` to `IssueSummary`.
- `ui/src/hooks/useRecentTasks.ts`: Recents uses `isRecentEligibleForMe`
(with a fallback to `isParticipantForMe` for older cached summaries) to
show, keep, and prune entries.
- `ui/src/lib/recent-tasks.ts`: add `recordStartedRoutineRunTask`. It
puts the run's task at the top of Recents. The summary fetch then
supplies the title and status and confirms eligibility.
- New `useRecordRoutineRunInRecents` hook. All five "Run now" paths call
it on success: Routines (both list variants), Routine detail, Execution
workspace detail, and the Responsibility screen.
- `tests/runner-e2e/source-sdk-public-inputs.json`: refresh the pin for
`packages/shared/src/types/issue.ts`.
- `doc/PRODUCT.md`: document the Recents behavior.

## Verification

- `cd ui && npx vitest run src/hooks/useRecentTasks.test.tsx`: 29
passed. The new test "shows a task from the viewer's manual routine run
at the top before it is opened" fails on the old hook (red) and passes
with the change (green). Other new tests cover a run that the server
does not confirm (for example, a coalesced run) and a repeat run for a
task that is already in Recents.
- `cd server && npx vitest run
src/__tests__/issue-summaries-routes.test.ts` (embedded Postgres): 24
passed. One new test checks that a manual run by the viewer is
Recents-eligible but not a Mine participant, and that runs by another
person and scheduled runs are not eligible. Another new test checks that
a routine task the viewer opened is Recents-eligible, and that a task
opened only by another person is not. That test fails on the previous
service code (red) and passes with the change (green).
- `ui` typecheck: no errors in changed files. (Errors exist only in
ungenerated Storybook feature-map indexes, which this change does not
touch.)
- The full `server` typecheck was killed by the local memory limit. CI
covers it.
- Manual check: run a routine with "Run now", then look at sidebar
Recents. The new task shows at the top before you open it. Mine does not
show it.

## Risks

- Low risk. No schema change and no migration.
- The summaries query adds two `EXISTS` subqueries per requested task.
Both use indexes (the read-state unique index and
`routine_runs_linked_issue_idx`). The request is bounded by
`ISSUE_SUMMARIES_MAX_IDS`.
- Behavior change: Recents now keeps tasks that the person opened, also
when the task is automatic work. Old local Recents entries for automatic
tasks that the person read can come back.
- If a manual run coalesces into an existing task that the viewer did
not start, the entry is pruned after the summary read. That task does
not show in Recents.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), via Claude Code with tool use
(shell, file edit, test runs).

## Checklist

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

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

---------

Co-authored-by: devinfoley <139239+devinfoley@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 20:54:26 -08:00
Devin FoleyandPaperclip 3f882fc589 fix(native): stage task-description attachments for native agents (#23688)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - People often create a task with a screenshot in its description and
assign it to a native agent.
> - The native Runner stages wake-comment files into the agent
workspace, so the agent can open an image with its file reader.
> - Files attached to the task description have no comment, so the
Runner never staged them.
> - The agent then said that it could not see the screenshot, or it
guessed from the text.
> - This pull request stages the task's own files on every native wake.
> - The benefit is that an agent can see the screenshot that explains
the task.

## Linked Issues or Issue Description

**What happened?**

A user created a task with the description "This list should probably be
sorted alphabetically" and pasted a screenshot of the list. A Claude
agent on a native sandbox replied that it could not open the screenshot
and asked which list to sort. It found the attachment through the API,
but the run had no staged path and no tool that put the image in its
workspace. When the same image was attached to a comment, the agent
opened it at once.

**Expected behavior**

A native agent can inspect files that are attached to the task
description, the same as files attached to a wake comment.

**Steps to reproduce**

1. Create a task and paste an image into its description.
2. Assign the task to a native `paperclip_runner` agent.
3. Ask the agent what the image shows.
4. The prompt has no "Paperclip native attachment access" entry for the
image, and the agent cannot see it.

**Paperclip version or commit**

`master` at c5f5d3163d.

## What Changed

- New column `issue_attachments.issue_level` (boolean, default `false`,
migration `0514`). It marks a file that a person attached to the task
itself.
- The UI sets `issueLevel` for new-task files, the task attachment
picker and drop zone, the task side panel upload button and drop zone,
the description editor, and task document images. Inline description
draft images that are bound at publication are also marked.
Comment-composer uploads, agent uploads and system files (for example
workspace-recovery archives) stay unmarked.
- The upload route accepts an optional `issueLevel` multipart field
(`true` or `false`). A file with a comment is never issue-level.
- `resolveNativeRunnerWakeAttachmentSelections` adds task files without
a comment after the wake comment's files. A task file is marked
issue-level, or the saved description links to it by its attachment or
asset content path (this covers files saved before the marker, with no
backfill). They come oldest first, within the existing 20-file limit. A
full wake keeps its comment files and does not fail. Only files a person
uploaded count; agent uploads, which carry no per-file trust, never do.
A quarantined low-trust task does not stage them.
- Staged descriptors for these files carry `taskAttachment: true`, so
the agent can tell them from the current wake's files.
- Runner download grants accept a null source comment for `wake` grants
only. The download route requires that the file is in the current wake
selection and has no comment. `history` grants still require a comment.

## Verification

- New `native-runner-task-attachment-staging.test.ts` (embedded
Postgres, with the migration): local staging of a task image, an
unmarked file that the description links to, comment-first ordering, an
unsent composer upload that is not staged and returns 404 on download,
an agent upload that is marked and linked from the description but is
not staged, the 20-file limit, low-trust quarantine, and the Runner
download grant (200 for the task file, 404 for crossed comment/task
grants, and no history grant without a comment).
- `issue-attachment-routes.test.ts`: `issueLevel` is saved for `true`,
is `false` when absent, and an invalid value returns 400.
- `chat-attachment-read`, `native-chat-workspace`,
`native-runner-attachment-staging`, `antigravity-run-start`,
`paperclip-control-plane-port`, `native-stop-accounting.integration`:
pass. `native-session-executor.test.ts`: 1572 passed, 7 skipped.
- `pnpm run typecheck` in `server` and `ui`: passed.
`IssueDetail.mobile.test.tsx`: passed.
- `pnpm verify` asks for full CI because of the migration. The pinned
runner-e2e source inputs are refreshed.

## Risks

- Schema change: one `ADD COLUMN ... DEFAULT false NOT NULL`. PostgreSQL
11 and later add it without a table rewrite.
- Existing attachments stay `false`. Older files that the description
links to are still staged. Other older files without a comment are not
staged. This fails closed, and a person can attach the file again.
- The migration is a constant-default `ADD COLUMN` only;
`migration-compatibility --check` passes.
- A file attached through a task-level surface stays a task file until
it is deleted, also if it is later removed from the description text. It
stays in the task's Attachments list for everyone on the task.
- Each native wake on a task with task files stages those files again.
The 20-file and 10 MiB Runner download limits apply. Each wake adds one
indexed query.
- Adapter (non-native) runs do not change.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use
(shell, file edits, database reads of a test instance) and extended
thinking.

## Checklist

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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-12-03 17:44:15 -08:00
Devin FoleyandPaperclip c5f5d3163d test: remove recovery and Tailscale readiness races (#23678)
## Thinking Path

> - Paperclip requires checks for an exact Core source commit before it
publishes images.
> - Cloud readiness runs the server integration tests without retries.
> - Server shard 18/20 failed in recovery cleanup and Tailscale
enrollment.
> - The recovery test returned before its status wake reached the
heartbeat drain.
> - The Tailscale fixture exposed state before it was safe to read or
observe.
> - This pull request makes those fixtures wait for their actual
completion boundaries.

## Linked Issues or Issue Description

Refs #23227. Related earlier cleanup fix: #23673.

**What happened?**

[Docker run
47225196060](https://github.com/paperclipai/paperclip/actions/runs/47225196060)
stopped after [Cloud readiness server shard
18/20](https://github.com/paperclipai/paperclip/actions/runs/47225196237/job/144677926140)
failed. Staging image preparation then waited for a verified Core image.
The previous Runner reattachment cleanup fix passed its protocol lane in
that run.

The recovery test deleted agents after a late wake inserted a child row.
The Tailscale test failed its first connection. On the [next master
run](https://github.com/paperclipai/paperclip/actions/runs/47227863572/job/144687185775),
the Tailscale blocked-save test timed out while waiting for a callback
that startup might never reach.

**Expected behavior**

Fixture teardown must join the status wake. The fake Tailscale CLI must
publish complete state and receive each simulated consent event
reliably. Tests must await enrollment completion and fail promptly when
connection setup fails.

**Steps to reproduce**

Run the two changed test files or server shard 18/20 with retries
disabled. The unmodified local files reproduced a consent callback
failure. The CI links above record the foreign-key and blocked-save
failures. The foreign-key failure did not reproduce in the initial local
run.

**Paperclip version or commit**

Failures on `07150650c926d8947ae591f61e4ed854ca284149` and
`ba521863f6090e40a37ed3cb6b1ecaf358a11424`. The fix starts from the
latter and is rebased onto `86042310917c15eb04be121baf58a6929e52a7d2`,
which adds release notes only.

**Deployment mode**

Source checkout in GitHub Actions. Local checks use macOS arm64, Node
25.6.1, hermetic Tailscale executables, and disposable embedded
PostgreSQL.

Searched open PRs and issues for the failing files, `ENOTEMPTY`, Runner
cleanup, and Tailscale tests. No duplicate fix was found. Issue #23227
describes the startup-dependent expiry window and is also addressed
here.

## What Changed

- Wait for the accepted recovery status change to persist its wake
before the existing heartbeat drain deletes fixture tables. The wake has
an asynchronous route prologue that can outlive the HTTP response.
- Register a signal handler in the owned fake CLI before exposing the
login URL. Publish fixture state atomically, then signal that exact
child to simulate consent. This removes the dependency on filesystem
notification delivery.
- Await the network manager's completion promise instead of a short
callback polling window.
- Start the expiry test with a valid window, advance the application
clock after startup, and submit late consent. Keep real subprocess
timers and restore the clock spy in `finally`.
- Race blocked-save admission against early connection settlement so
startup failures are reported instead of hanging the test.
- Only two test files change. Runtime behavior, release gates, and
deployment policy do not change.

## Verification

- Baseline: the unmodified two-file run failed the consent callback
assertion; 129 tests passed. The recovery cleanup passed locally, with
its CI failure retained above.
- An intermediate expiry check failed its one-second callback wait. A
later parallel shard run still lost a filesystem notification. The final
fixture uses an explicit consent signal and awaits manager completion.
- That eight-worker shard run also timed out in unchanged
workspace-trust and runtime-control fixtures while a monolithic
typecheck ran concurrently. Those two unchanged files passed in a serial
control with the changed fixtures: 186 tests passed across four files.
The final shard is run separately with four workers and retries
disabled.
- `pnpm exec tsc --noEmit -p tsconfig.json` from `server/`: passed.
- After the release-notes-only rebase, the Tailscale file passed again:
9 tests, retries disabled. The two fixture file contents are identical
to the final shard run.
- `PAPERCLIP_VITEST_RETRY=0 PAPERCLIP_VITEST_MAX_WORKERS=4 pnpm
test:run:general -- --group general-server-without-chat-or-native-runner
--shard-index 17 --shard-count 20`: passed on the final fixture
contents. 85 files passed, 3 skipped; 1945 tests passed, 18 skipped.
Duration: 160 seconds.
- `node scripts/check-test-budget.mjs --files
server/src/__tests__/issue-recovery-actions.test.ts
server/src/services/connectors/tailscale/device-login-network.test.ts`:
passed.
- `git diff --check` and local secret/PII review: passed.
- [Greptile
review](https://github.com/paperclipai/paperclip/pull/23678#issuecomment-7396242983):
5/5 on head `13bf3586bcf3201ce137f674812e8faf778ee77d`, with a
successful current-head check and no actionable findings or review
threads. The [full PR CI
workflow](https://github.com/paperclipai/paperclip/actions/runs/47231990509)
passed on attempt 1. All 71 reported checks are clean on this head;
GitHub reports `CLEAN` / `MERGEABLE` and there are no unresolved review
threads.

## Risks

Low risk. The change is limited to fixtures. A missing status wake or
failed enrollment still fails the tests. The expiry case now checks
actual late-consent rejection without making success depend on process
startup time. No schema, API, or runtime changes are required. The tests
and PR explain the behavior; no documentation update is needed. A new
verified master image is still required before staging can resume.

## Model Used

OpenAI `gpt-6.1-sol` through the Codex harness in T3 Code, with xhigh
reasoning effort, shell and file tools. The harness does not expose the
context window size.

## Checklist

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

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-12-03 16:22:38 -08:00
Nicky LeachandClaude Opus 5.5 c2a8821809 fix(agents): keep a prepared agent setup when its configuration changes (#23669)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - A new agent can use a plugin environment that requires an agent. A
lifecycle plugin prepares that environment before the agent can work.
> - The setup flow creates a draft agent first, so that this preparation
can start before the person finishes setup.
> - Each change to the draft's harness, model, or sign-in started
preparation again. The hire also started it again.
> - Verification cannot start until the last preparation is complete. So
the early preparation did not decrease the wait after the hire.
> - This pull request keeps the preparation when the agent stays on the
same environment driver.
> - The benefit is that a person who finishes setup waits only for
verification.

## Linked Issues or Issue Description

I searched the open and closed issues and pull requests. I did not find
a duplicate.

**What happened?**

Create an agent in setup on a plugin environment that declares
`requiresAgent: true`. The draft is prepared. Then choose a harness,
sign in, and hire the agent. Each of these three steps starts
`preparing` again. The agent page shows preparation after the hire,
although the environment was ready before the person signed in.

**Expected behavior**

A change to the harness, model, credentials, or instructions does not
change the environment. It must not start preparation again. The hire
must go directly to verification. If preparation is in progress, the
hire must join it.

**Steps to reproduce**

1. Install a lifecycle plugin with an environment driver that declares
`requiresAgent: true`.
2. Make that environment the instance default.
3. Create a setup draft and wait until `lifecycleState` is `verifying`.
4. Save a different model on the draft. `lifecycleState` goes back to
`preparing`.
5. Hire the draft. `lifecycleState` goes back to `preparing` again.

**Paperclip version or commit**

`7e025ae65f`

**Deployment mode**

Self-hosted server with a plugin environment that requires an agent.

## What Changed

- A configuration change restarts `preparing` only when the agent moves
to an environment that needs setup. The existing environment and driver
check makes this decision.
- A prepared setup draft stays prepared when its harness, model,
credentials, or runtime configuration change.
- The hire of a prepared draft goes directly to `verifying` with a new
operation.
- The hire of a draft that is still `preparing` keeps the operation and
its version. Verification starts when that operation is complete.
- A hire that moves to an environment that needs setup starts
`preparing` again, as before.
- A save that changes an environment to another driver of the same
plugin now also refuses `preparing` agents, the same as `ready` and
`verifying` ones.
- A change to instructions alone does not restart verification. The hire
writes the managed instruction files immediately after it commits, and
verification does not read them.
- The hire clears an old lifecycle error on the draft.
- These behaviors do not change:
  - a draft that no longer needs preparation goes to `pausing`
  - a hire that needs approval, a hire with a hold, and a company hold
  - an edit to other execution configuration during verification
  - an edit during `resuming`
- `doc/AGENT-LIFECYCLE.md` describes the new rules.

## Verification

- `npx vitest run src/modules/agent-lifecycle`: 224 passed. Four new
tests cover a prepared draft, a hire from a prepared draft, a hire
during preparation, and an instruction change. Three of them failed
before the change. The fourth could not run because a test before it
left the fixture blocked.
- `npx vitest run` on the hire, lifecycle delivery, agent secret,
pending approval, secret binding, managed plugin environment, and plugin
task tests: all passed.
- `npx vitest run` on the two Dot onboarding files: 25 passed.
- `pnpm --filter @paperclipai/server typecheck`: passed.
- Not done: a live test with a plugin environment.

Three existing tests used an agent in `preparing` to test that a
configuration change fences verification. They now use `verifying`.

## Risks

- A lifecycle plugin that reads the agent's harness or model during
`preparing` is not called again when they change. The lifecycle request
does not carry them. Verification still tests the final configuration.
- A prepared environment can be lost between preparation and hire.
Verification then fails and retries, and a pause and resume prepares it
again. Before this change, the hire prepared it again.
- An edit during `preparing` does not cancel the attempt in progress. A
plugin must not fail because the agent's configuration changed during
its call.
- No migration.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, in Claude Code, with
extended thinking, 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: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 15:55:56 -08:00
Nicky LeachandClaude Opus 5.5 ba521863f6 perf(skills): import environment skills when a setup draft is created (#23672)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - A plugin environment driver can declare `skillKeys`. Core adds those
managed skills to each run on the environment.
> - Before a run can use a skill, Core imports it into the company's
skill library. This occurs once for each company.
> - The import occurs when the first task starts. So the first task in a
new company waits for it.
> - Each missing skill is imported in its own transaction. Each import
checks all bundled skills two times, and the transactions do not share
that check.
> - This pull request starts the import when a person creates a setup
draft, and checks the bundled skills once.
> - The benefit is that the first task starts sooner. The setup does not
wait for the import.

## Linked Issues or Issue Description

I searched the open and closed issues and pull requests. I did not find
a duplicate.

**What happened?**

The first task on a plugin environment with four managed skills spent
more than ten seconds in skill import. Most of this time was the check
and first import of Core's bundled skills. That check ran again for each
managed skill.

**Expected behavior**

The import must start before the first task, while the person completes
setup. One import must check the bundled skills once.

**Steps to reproduce**

1. Install a plugin with an environment driver that declares several
`skillKeys`.
2. Make that environment the instance default.
3. Create a company, set up its first agent, and give it a task.
4. Measure the skill selection part of the first run's preparation.

**Paperclip version or commit**

`7e025ae65f`

**Deployment mode**

Self-hosted server with a plugin environment that declares managed
skills.

## What Changed

- When a person creates a setup draft, the server imports the
environment's missing skills in the background. The response does not
wait for this import.
- A failed background import writes a warning. It does not change the
draft. Run admission still installs the skills that are missing.
- The background import is counted as active work, so an idle drain
waits for it. It runs once and does not poll or retry.
- An environment skill import checks the bundled skills once before it
installs the missing skills. Before, each skill did this check two times
in its own transaction.
- `importPackageFiles` reads the library rows after its own inventory
check. It no longer does the check a second time.
- `doc/skills-and-teams-catalog.md` describes the new behavior.

Skill selection, version pins, and the files that a run receives do not
change.

## Verification

- `npx vitest run src/__tests__/environment-skills.test.ts`: 7 passed.
Two tests are new. They fail when I remove the single check and the
background import.
- `npx vitest run` on the company skill service, managed skill content,
company portability, agent adapter validation, and agent lifecycle
tests: all passed.
- `src/__tests__/ai-connections.test.ts`: 5 of its tests failed in the
same local run. The reconnect tests also fail at `7e025ae65f` without
this change on the same local database. They do not use this code.
- `pnpm --filter @paperclipai/server typecheck`: passed.
- Not done: a measurement of the first task with this change.

## Risks

- A draft that a person abandons leaves the imported skills in the
company library. The same skills are imported for the next agent on that
environment.
- The background import and a first task can run together. The existing
lock for each skill makes the second one wait and use the first result.
- The bundled skill check now runs outside the skill's transaction. If
the skill import then fails, the bundled skills remain imported. They
are imported by other library reads too.
- No migration.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, in Claude Code, with
extended thinking, 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: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 15:29:50 -08:00
7e025ae65f fix(workspaces): start a new remote workspace when the task's saved one is retired (#23655)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Before a run starts, Paperclip prepares the task's execution
workspace. With remote workspace storage, it reserves the task's saved
remote workspace.
> - A task stays bound to its workspace after that workspace is archived
or its cleanup fails.
> - For a retired host workspace, the next run already creates a new
workspace. For a retired remote workspace, preparation sent the retired
workspace to the reservation. The reservation refused it with "Workspace
ownership changed." (`remote_workspace_retired`, since #23582).
> - So the task could never run again. Each wake, recovery, or Retry
failed in setup with the same conflict.
> - This pull request makes a retired remote workspace act like a
retired host workspace: the run starts a new remote workspace.
> - The benefit is that a reopened task with an archived remote
workspace runs again, and the retired workspace and its saved snapshot
stay unchanged.

## Linked Issues or Issue Description

**What happened**
A task's own remote workspace was archived by hand (no terminal-cleanup
reason) and later moved to remote storage. When the task was opened
again, every run failed in setup with "Workspace ownership changed." The
task was then escalated for recovery, and the next wake failed in the
same way.

**Expected behavior**
A retired workspace is not reused. The run starts a new workspace for
the task, as it does for a host workspace. A native recovery or a saved
Retry that is bound to the retired workspace still stops with the
conflict.

**Steps to reproduce**
1. Bind a task to its own remote-storage workspace. Set the workspace
status to `archived` or `cleanup_failed`.
2. Start a run for the task with a Paperclip Runner agent in a sandbox
environment.
3. Setup fails with a 409 conflict, "Workspace ownership changed."
(`remote_workspace_retired`).

**Paperclip version or commit**
master at 0208bbfbf7.

Refs #23582 (gave this conflict its stable code). Related: #21954
(releases a binding to *another* task's closed workspace; this change is
about the task's *own* retired remote workspace).

## What Changed

- `remote-workspaces.ts`: add `isRetiredExecutionWorkspaceStatus`
(`archived` or `cleanup_failed`). When the caller requests no workspace,
`reserveRemoteWorkspace` does not fall back to an issue binding to a
retired workspace. It creates a new workspace and moves the issue
binding to it. An explicitly requested retired workspace still gets the
`remote_workspace_retired` conflict.
- `heartbeat/workspace-preparation.ts`: do not offer a retired
remote-storage workspace for reuse. The retired workspace still decides
the storage authority, so the task stays on remote storage even when the
instance does not enroll new tasks. This does not apply to a native
recovery, a persisted native execution input, or a saved Retry/fresh
attempt. Those stay bound to the workspace that they admitted.
- Tests: three preparation tests (`archived`, `cleanup_failed`, and
`archived` with new-task remote storage off) and one native-recovery
safety test in `workspace-preparation.test.ts`. Two reservation tests in
`remote-workspaces.integration.test.ts`.

## Verification

- Red before the fix: `cd server && npx vitest run
src/services/heartbeat/workspace-preparation.test.ts -t "saved remote
workspace is"` failed with `Workspace ownership changed.` for both
statuses. With only the reservation change removed, the two new
`remote-workspaces.integration.test.ts` tests also failed with
`Workspace ownership changed.`
- Green after the fix: `npx vitest run
src/services/heartbeat/workspace-preparation.test.ts
src/services/remote-workspaces.integration.test.ts -t "saved remote
workspace is|native recovery bound to a task workspace|stable conflict
code|when no workspace is requested"`: 8 of 8 pass. The storage-off case
failed before the follow-up commit (the run fell back to the host path).
- The tests check that the new workspace is active and bound to the
task, that the binding revision goes up by one, and that the retired row
and its snapshot metadata do not change. The existing explicit-request
conflict test still passes, and a native recovery still gets the
conflict.
- Full files: `npx vitest run
src/services/heartbeat/workspace-preparation.test.ts
src/services/remote-workspaces.integration.test.ts
src/services/workspace-recovery-admission.test.ts`: 433 of 433 pass
(Linux x64, Node 24.23.0, embedded Postgres).

## Risks

- Behavior change: a task whose own remote workspace is retired now
continues in a new workspace. Files that were only in the retired
workspace's snapshot are not restored into the new workspace. This is
the same as for a retired host workspace. The retired snapshot is not
deleted.
- A native recovery or a saved Retry still stops on a retired workspace,
so a run that is in progress does not change its workspace silently.
- No schema or API change.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), with tool use and code execution
in a 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>
2026-12-03 13:45:10 -08:00
Dotta 1fb8ddb740 feat(trust): allow transient workspace_prepare checkout for low-trust in-boundary projects (#23656)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The low-trust review preset isolates untrusted review agents inside
sandboxes with no runtime GitHub tokens and no sandbox network access
> - When a low-trust agent is explicitly assigned to a
private-repository project with `git.read` enabled, workspace
preparation routed the setup-time clone through
`resolveGitHubOperationCredentials`, which blocks all low-trust
credential export and caused `stage=clone git=auth_failed exit=128`
before the agent could start
> - Setup-time `prepareRemoteWorkspaceDirectory` runs on the trusted
controller path before the agent starts, uses transient `GIT_CONFIG_*` /
`PAPERCLIP_GIT_TOKEN` environment variables with `-c
core.hooksPath=/dev/null`, and writes zero credentials into
`.git/config`
> - This pull request adds `resolveGitHubWorkspacePrepareCredentials`
for controller-only `workspace_prepare` call sites, allowing transient
clone credentials strictly for a repository configured on a project
inside `trustBoundary.projectIds` when `git.read` is permitted
(preferring an agent-installed GitHub PAT connection when present),
while keeping runtime shell credentials
(`resolveGitHubOperationCredentials`) strictly denied
> - The benefit is that assigning a low-trust agent to a private-repo
project works out of the box for local read-only code review without
exposing any live GitHub token to the agent runtime

## Linked Issues or Issue Description

**What happened?**
When an agent configured with `trustPreset: "low_trust_review"` and
`allowedToolClasses: ["git.read"]` was assigned a task in a project with
a private GitHub repository workspace, workspace preparation failed
before the agent started with `remote_workspace_prepare_failed:
stage=clone git=auth_failed exit=128 program=git`.

**Expected behavior**
When a `low_trust_review` run has `git.read` enabled and targets a
project explicitly listed in `trustBoundary.projectIds`, the trusted
controller should clone that project's configured repository during
`workspace_prepare` using transient credentials (preferring an
agent-installed GitHub PAT connection if configured, otherwise the run's
managed GitHub identity), while leaving zero credentials in
`.git/config` and keeping runtime GitHub credential export strictly
denied.

**Steps to reproduce**
1. Create a project with a private GitHub repository workspace.
2. Configure an agent with `trustPreset: "low_trust_review"`,
`projectIds: [projectId]`, and `allowedToolClasses: ["git.read"]`.
3. Run a task in that project on a cloud sandbox environment.
4. Before this fix, `createGitRemoteAuthProvider` falls back to
anonymous clone and fails at `stage=clone git=auth_failed exit=128`.

**Paperclip version or commit**
`master` (`23ca89e376`)

## What Changed

- **`server/src/services/github-operation-credentials.ts`**: Added
`resolveGitHubWorkspacePrepareCredentials`,
`allowsLowTrustWorkspacePrepareCheckout`, and
`resolveAgentInstalledGitHubPat`. For `low_trust_review` runs, transient
prepare-time clone auth is permitted only when `trust.kind ===
"low_trust_review"`, `git.read` is in `allowedToolClasses`, the task's
project is explicitly in `trustBoundary.projectIds`, and `remoteUrl`
matches a configured `project_workspaces.repo_url` on that project.
Prefers an active agent-installed GitHub `api_key` (PAT) connection when
present and otherwise falls back to `resolveManagedGitHubCredential`.
Runtime `resolveGitHubOperationCredentials` remains unchanged and
strictly denied for low-trust runs.
- **`server/src/services/git-credentials.ts`**: Added optional
`purpose?: "workspace_prepare"` to `createGitRemoteAuthProvider` so only
controller workspace-preparation call sites invoke
`resolveGitHubWorkspacePrepareCredentials`.
- **`server/src/services/heartbeat/workspace-preparation.ts`** and
**`server/src/services/heartbeat/workspaces.ts`**: Passed `purpose:
"workspace_prepare"` at the four controller workspace-preparation call
sites.
- **`server/src/__tests__/github-operation-credentials.test.ts`**: Added
unit, security-boundary, and end-to-end
`prepareRemoteWorkspaceDirectory` tests covering managed identity
prepare checkout, agent-installed GitHub PAT preference, runtime
credential denial, unrelated repo denial, missing `git.read` denial, and
zero credentials persisted in `.git/config`.

## Verification

- `pnpm --filter @paperclipai/server typecheck` — passed with 0 errors.
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/github-operation-credentials.test.ts` — 30/30 passed
(including the 3 new low-trust `workspace_prepare` and local E2E
`prepareRemoteWorkspaceDirectory` tests).

## Risks

- Low risk. Runtime agent credential endpoints
(`/runtime-tools/github/credentials`, native GitHub broker, skill-source
fetch) continue calling `resolveGitHubOperationCredentials` and stay
strictly denied for `low_trust_review`.
- Prepare-time credentials are scoped strictly to repositories already
configured in `project_workspaces` for a project explicitly inside
`trustBoundary.projectIds` and only when `git.read` is enabled.

## Model Used

- Google Gemini (Antigravity agentic coding assistant) with tool use and
local code/test execution.

## Checklist

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

> - Paperclip is the open source app people use to manage AI agents for
work
> - A run in a sandbox must start its Runner before a deadline
> - A startup that passes the deadline is cancelled, and its sandbox
task is stopped
> - The cancelled run then has no successor, so the server blocks the
task
> - The answers and messages that wait behind the run stay held until a
person acts
> - The agent did no work, so nothing needs a person
> - This pull request queues the same wake again when the evidence shows
that no work started
> - The benefit is that a slow startup delays a task but does not block
it

## Linked Issues or Issue Description

No issue exists.

**What happened?**

A user answered an agent's question. The new run passed its startup
deadline. The server stopped the sandbox task and confirmed the stop.
The server then set the task to blocked, and the answer was not
delivered.

**Expected behavior**

The server starts the run again with the same answer. It continues the
saved session if that is safe.

**Steps to reproduce**

1. Use an agent whose environment provider runs Runner tasks.
2. Start a run on a task.
3. Make the startup pass its deadline before the Runner connects.
4. Wait for the server to confirm the stop.
5. See that the task is blocked and that a new message stays held.

**Paperclip version or commit**

`dc16c47362`

**Deployment mode**

Self-hosted server with a sandbox environment plugin.

## What Changed

- The server queues the same wake again after it confirms the stop of a
startup that timed out. The new run keeps the wake reason, the comments
and the answer.
- The server does this only with all of this evidence:
  - The startup deadline is the only cause of the cancellation.
  - The provider confirmed that the task stopped.
- No process request, session, turn, Runner checkpoint or result exists.
  - No workspace recovery or file copy is open.
- The new run uses the existing retry limits for an interrupted
preparation.
- The server queues the new run before it acknowledges the cleanup. The
new run cannot start until the cleanup is acknowledged. Held messages
stay in order behind it.
- The new run continues the saved session when the stopped task still
holds the session state of an earlier run. Otherwise, it starts a new
session.
- If the server stops between these steps, the next cleanup pass
completes them. It queues one run only.
- If any evidence is missing, or the server cannot queue the run, the
task is blocked as before.
- A Stop by a person, a pause, a budget or a reassignment does not
change.

## Verification

- `npx vitest run
src/services/native-runtime/native-startup-requeue.test.ts`: 46 passed.
These tests use embedded Postgres. They test the full cancellation, the
two server-stop points, 24 refusals, the session state transfer, and
which run the next run resumes.
- `npx vitest run` on the 14 test files that use the changed modules:
2146 passed, 7 skipped, 1 failed. The failed test is `archives a damaged
prior epoch before completing guarded same-task replacement with real
runnerd`. It also fails at `dc16c47362` on the same computer, without
this change.
- `npx vitest run` on the retry scheduling and early Stop tests: 79
passed.
- `npx tsc --noEmit` in `server` has no errors.
- Not done: a live test of this change. CI runs the Runner integration
suites.

## Risks

- A wrong decision could run work twice. The server refuses when any
saved record shows provider work, and the resume path checks the same
records again.
- A startup that always times out now retries. The existing limit and
backoff apply. After the last retry, the task is blocked as before.
- The new run uses another sandbox start. Budget checks and retry counts
apply to it as to other retries.
- A task that is already blocked by this problem does not change. A
person must retry it or send a message.
- No migration.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, in Claude Code, with
extended thinking, 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: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 09:34:26 -08:00
Dotta bba20403ba fix(cloud-trial): do not attach Connect OpenRouter repair card on starter-trial auth failures (#23633)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - When a normal agent fails with a provider authentication error,
`connectionIntentService.requestForRunAuthFailure` infers the AI
provider from the agent's model and attaches a pending `"Connect
<Provider>"` interaction card on the issue thread.
> - Cloud starter-inference agents (`runtimeConfig.cloudTrialInference:
true`, no saved `aiConnection`) run OpenCode with
`openrouter/openai/gpt-6-luna` through Paperclip Cloud's server-side
proxy instead of a user-saved OpenRouter connection.
> - If a starter-inference run ever encounters an OpenRouter 401
failure, `requestForRunAuthFailure` attached a pending `"Connect
OpenRouter"` card, causing the agent to keep nagging the user to respond
to that card on subsequent turns even after succeeding.
> - This pull request skips `requestForRunAuthFailure` for agents using
Cloud starter inference without a saved `aiConnection`, leaving
`CloudTrialGate` as the single owner of prompting users to connect a
model provider.
> - The benefit is that starter-inference chats never accumulate stale
`"Connect OpenRouter"` cards.

## Linked Issues or Issue Description

Refs #23401, #23616

**Summary**
Skip creating a `"Connect OpenRouter"` `connection_intent` card in
`requestForRunAuthFailure` when the agent runs on Cloud starter
inference (`runtimeConfig.cloudTrialInference: true` without a saved
`aiConnection`).

**Steps to Reproduce**
1. Run an OpenCode agent configured with
`runtimeConfig.cloudTrialInference: true` and `adapterConfig.model:
"openrouter/openai/gpt-6-luna"` (no `runtimeConfig.aiConnection`).
2. Trigger an OpenRouter HTTP 401 authentication failure on a run.
3. Observe `requestForRunAuthFailure` creating a pending `"Connect
OpenRouter"` `issue_thread_interactions` row on the chat issue.

**Expected Behavior**
`requestForRunAuthFailure` returns `null` and creates no pending
`"Connect OpenRouter"` interaction for Cloud starter-inference agents.

## What Changed

- `server/src/services/connection-intents.ts`: Returned `null` in
`requestForRunAuthFailure` when `!saved && !router &&
isAgentUsingCloudTrialInference(agent.runtimeConfig)`.
- `server/src/__tests__/connection-intents-service.test.ts`: Added a
regression test proving that an OpenRouter 401 failure on a Cloud
starter-trial agent returns `null` and creates zero
`issue_thread_interactions` rows.

## Verification

- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/connection-intents-service.test.ts -t "does not create a
Connect OpenRouter card|adopts a Copilot account"` — passed (2/2 tests).
- `pnpm --filter @paperclipai/server typecheck` — passed (0 errors).

## Risks

- Low risk. Narrow 1-line guard scoped strictly to agents with
`runtimeConfig.cloudTrialInference === true` and no saved
`aiConnection`. Normal agents with or without saved AI connections keep
their exact existing auth-repair behavior.

## Model Used

- Google Gemini (Antigravity agentic runtime, thinking mode with tool
use and local code execution).

## Checklist

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

> - Paperclip is the open source app people use to manage AI agents for
work
> - The conversation an agent has on a task is called a session. Each
task saves a pointer to its session (the session link), and the next run
uses it to continue the conversation
> - A run's own record keeps its session id. The task gets its pointer
to that session only when the run's result is accepted
> - A stopped run has no accepted result, so it saves no pointer. If a
task's first run is stopped, the task has no pointer. The next run
starts a new session and the agent has forgotten the first run
> - A later run can also start a new session, for example after an
assignment, a retry or a configuration change. If that run is stopped,
the pointer still names the older session. The next message goes back to
the older session or starts another one
> - Saving the pointer on every stop would be unsafe. The agent's turn
might still be open, a request might still be waiting, or the provider
might not have kept the session
> - This pull request copies the session id from a stopped run to the
task only when the records show that the stop was acknowledged, the turn
started and then ended with nothing waiting, the provider kept the
session, and no newer run has taken over the task. Otherwise, the
pointer does not change
> - The benefit is that someone can stop a run, send a correction, and
continue the same conversation

## Linked Issues or Issue Description

No issue exists.

**What happened?**

A user stopped the first run of a task. The user then sent a message.
The agent started a new session and did not remember the first run. The
same loss happens when a user stops a later run that started a new
session.

**Expected behavior**

The agent continues the session of the stopped run.

**Steps to reproduce**

1. Use an agent whose environment provider runs Runner tasks and keeps
their session state.
2. Create a task and wait for the first run to start a turn.
3. Stop the run during the turn.
4. Send a message on the task.
5. See that the new run has a new session.

**Paperclip version or commit**

`4db307d53c`

**Deployment mode**

Self-hosted server with a sandbox environment plugin.

## What Changed

- A stopped run now links its session after its environment lease is
released.
- The link needs all of this evidence:
  - The Stop was delivered and acknowledged.
- The provider accepted a turn. The next prompt leaves out messages that
the linked run received, so a run whose turn did not start cannot be
linked.
  - The turn ended. No request, background work or goal is waiting.
  - The controller journal is settled.
- The provider reports that the task stopped and that it kept the
session state.
  - No newer run, reset or conversation owns the task.
- An existing link is replaced only if its run belongs to the same task
and agent and finished before the stopped run started. Accepted results
already use this rule. Both paths now share one function.
- If any evidence is missing, the link does not change, as before.
- If the provider later confirms that the kept state is gone, the next
run starts a new session. The acknowledged Stop replaces the committed
result in that proof. All other checks in that proof still apply.

## Verification

- `npx vitest run` on the publication tests for stopped runs, the
publication tests for accepted results, the runtime execution tests and
the terminal state reader test: 121 passed. The executor tests ran on an
earlier commit, and the executor code has not changed since.
- The publication tests use embedded Postgres. They test six saves and
37 refusals. Each refusal checks that the task session row did not
change.
- The executor tests check that a stopped run retires after a confirmed
state loss. They also check that an unacknowledged Stop and a different
failure stay refused.
- `npx tsc --noEmit` in `server` has no errors.
- Saved evidence from two real first-run stops during a turn shows ended
turns with no request waiting. The first has a released lease with kept
session state. The second failed its lease cleanup, so this change still
refuses it.
- Saved evidence from two real later-run stops: one kept its session,
and the next run resumed it. The other kept no session and had no
settled turn, and the next run failed. This change refuses to link the
second.
- Two of 104 real stops with a cancelled terminal had no accepted turn.
The turn check refuses them.
- Not done: a live test of this change. CI runs the Runner integration
suites.

## Risks

- A wrong link could resume an unsafe session. The link uses the same
evidence that the resume path checks again, so the resume path still
refuses an unsettled session.
- A link that turns out to be unusable now replaces an older link
instead of no link. The next run then usually fails, and the run after
it usually starts a new session, as it does for an unusable link from a
finished run.
- The change applies only to providers that run Runner tasks and report
kept session state. Local Runners and other sandboxes have no equal
evidence, so they keep the previous behavior.
- A stop while the agent waits for background work is not covered. The
Runner holds its terminal event in that state, so the evidence is
missing.
- The saved link keeps that run's Runner checkpoint, as any other link
does.
- No migration.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, in Claude Code, with
extended thinking, 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: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 08:17:44 -08:00
Nicky LeachandClaude Opus 5.5 dc16c47362 refactor(runner): remove the unused plugin task source recovery path (#23590)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - An agent run uses a Runner task that an environment plugin provides.
When a Runner stops, the next run can need its saved session
> - #19134 and #19196 added one way to do this. The next run claims the
stopped Runner's task, and then starts that task again under its own
control
> - Those pull requests added the claim and its checks. They did not add
a caller. #19157 was to add the caller, and it did not merge
> - Nothing on `master` calls the claim. No lease gets the two records
that the claim writes, so every check of those records does nothing
> - The unused path still looks active. A reader can change it, and can
think that the change fixes a failure
> - This pull request removes the claim and all code that only reads its
records
> - The benefit is that the code shows only the recovery paths that can
run

## Linked Issues or Issue Description

Refs #19134, #19196 (added the path), #19157 (closed draft that called
it).

**Issue type**

Dead code

**What happened?**

`claimPluginTaskSourceRecovery` has no caller on `master`. Only the
claim writes `runnerTaskSourceConsumer` and `runnerTaskSourceRecovery`
to a lease. Six other server files read those records.

**Expected behavior**

The server contains only recovery code that can run.

**Steps to reproduce**

1. Run `git grep claimPluginTaskSourceRecovery master -- server`.
2. See only the definition.
3. Run `git log -G claimPluginTaskSourceRecovery master`.
4. See that the commits added the path, and later removed its tests. No
commit added a caller.

## What Changed

- Removed the source recovery claim and its checks
(`plugin-task-source-recovery.ts`).
- Removed the special handling of a claimed source from plugin task
dispatch, task resume, checkpoint writes, task ownership, and retained
and warm sandbox expiry.
- A Runner task owner no longer takes `codexSourceRecoveryVersion`.
Nothing set it, so the owner always refused to prepare a predecessor's
launch. It still refuses.
- The checkpoint writer still locks both runs, and still refuses a late
write from a session that moved to another task.
- The plugin SDK still accepts `codexSourceRecoveryVersion` and
`acpxSourceRecoveryVersion`, so a plugin that sends them does not fail.
The guide now says that Core does not use them.
- The Runner package does not change.

## Verification

- `npx vitest run` on eight test files for the changed code: 319 tests
pass.
- `npx tsc --noEmit` in `server` has no errors.
- The test of a late write to a retired checkpoint used the removed
records. It now uses the records of a session that moved to another
task.
- Not run locally: the suites that start a real Runner. CI runs them.

## Risks

- No production code wrote these records, so no saved lease should
contain them. A lease that does contain them is no longer held by them.
- #19157 depended on this path. It is closed and did not merge.
- No migration. No change to the plugin or Runner protocol.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, in Claude Code, with
extended thinking, 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: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 07:43:49 -08:00
Nicky LeachandClaude Opus 5.5 0134081be8 fix(native): resume a saved session whatever the task status (#23533)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - A native agent keeps a warm session between the turns of a task
> - After the warm session leaves memory, the server recovers it from
saved state
> - That recovery required the task status to be `in_progress`
> - Some runs start on a task that is not `in_progress`, by design
> - Those runs lost their session, although the saved session was intact
> - Run dispatch already decides which tasks a run may start on
> - This pull request removes the status check from recovery
> - The benefit is that a comment on a task in review continues the same
conversation

## Linked Issues or Issue Description

Refs #16451 (added this recovery), #21001 (separated the two kinds of
refusal).

**What happened?**

A task was in review. The warm session was no longer in memory. A
comment started a run. The run failed with `native_session_interrupted`
and `warm_recovery_refused=current_run_not_admitted`. The task then
continued in a fresh session.

A comment soon after the previous run did resume the session. That path
uses the session in memory and does not read the task status.

**Expected behavior**

The run must resume the saved session. Automatic checkout leaves a task
in review on purpose. The agent skill tells the agent to check out the
task after it reads the comment. The agent cannot do that before its
session resumes.

**Steps to reproduce**

1. Run a task on a remote environment with a warm session.
2. Let the agent move the task to review.
3. Wait until the warm session leaves memory.
4. Add a comment to the task.

I saw this failure once on a live task. An API call had set that task to
review. The new test shows the cause. I did not repeat steps 1 to 4 on a
task that an agent moved to review.

**Paperclip version or commit**

The check is on `master` at 4db307d53c.

## What Changed

- Warm session recovery no longer checks the task status.
- The status check did not stop the run. It only lost the saved session.
On a closed task the automatic fresh continuation does not apply, so the
run failed.
- The ownership, cancellation, agent and lease checks do not change.
- Automatic checkout does not change.

## Verification

- `npx vitest run
src/services/native-runtime/remote-warm-session-recovery.test.ts` in
`server`: 11 tests pass on an embedded PostgreSQL database.
- The file tests every task status, and each ownership and cancellation
refusal.
- The tests replace only the parser of the saved execution input and the
saved checkpoint. The suite setup reads the same database settings as
the suite gate.
- I ran the same tests against the previous check. The cases for a
status other than `in_progress` failed. The other cases passed.
- `npx tsc --noEmit` in `server` has no errors. CI runs the other test
suites.

## Risks

- A run can now resume on a task whose status changed while the run
started. The path that uses the session in memory already allows this.
- A person who closes a task, and any actor who cancels one, also stops
its run. The run checks then refuse recovery. If an agent marks the task
done while the run starts, the run continues and keeps its session.
- Saved state does not change. A session saved by the previous release
resumes as before, or resumes where it was refused.
- Other failures of the current run can still end in a fresh session.
This pull request does not change that policy.

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

## Model Used

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

## Checklist

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

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 07:39:29 -08:00
Dotta 8e2381a1d1 fix(cloud-trial): use stable HMAC-signed proxy tokens across warm OpenCode sessions (#23616)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Cloud starter-inference OpenCode runs in remote Daytona sandboxes
reuse warm OpenCode sessions across consecutive chat turns.
> - Inside the warm sandbox, `startOpenCodeProviderProxy` stays alive
bound to the first run's `PAPERCLIP_OPENROUTER_PROXY_TOKEN`.
> - Because `cloud-trial-proxy.ts` generated a random per-run token and
deleted it in `cleanup()`, every reused-session turn failed on attempt
#1 with HTTP 401 (`Trial proxy token is no longer active on this server
instance`) and posted `"The OpenCode run failed before it completed."`
into the chat before auto-retry recovered.
> - This pull request replaces single-run random tokens with
deterministic HMAC-SHA256 signed per-`(companyId, agentId,
allowedModel)` tokens (`pctrial_v1.<payload>.<sig>`) that remain valid
across warm turns and stack restarts/sleep-wake, while still failing
closed on tampering, `work_requires_model`, `$1` exhaustion, disallowed
models, and provider migration.
> - The benefit is zero spurious 401 failure messages on consecutive
chat turns in warm starter-inference sessions.

## Linked Issues or Issue Description

Refs #23401, #23559, #23571

**Summary**
Use stable HMAC-signed proxy tokens for Cloud starter-inference OpenCode
sessions so reused warm sessions succeed on attempt #1.

**Steps to Reproduce**
1. Start a Cloud starter-inference (`free_inference_1`) chat with an
OpenCode agent in a warm Daytona sandbox.
2. Send a first message and wait for the reply.
3. Send a second message in the same chat (`sessionReused: true`).
4. Observe HTTP 401 (`Trial proxy token is no longer active on this
server instance`) and `"The OpenCode run failed before it completed."`
before auto-retry starts a fresh process.

**Expected Behavior**
Consecutive messages on a reused warm OpenCode session authenticate
cleanly on attempt #1 with zero 401 failures, while tokens still fail
closed on tampering, `work_requires_model`, `$1` exhaustion, disallowed
models, or migration to a user provider.

## What Changed

- `server/src/services/cloud-trial-proxy.ts`: Replaced single-run random
`pctrial_` tokens with deterministic HMAC-SHA256 signed
`pctrial_v1.<payload>.<sig>` tokens derived from the stack's stable
secret (`PAPERCLIP_CLOUD_CONNECTOR_SIGN_PRIVATE_KEY` /
`PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN` / `PAPERCLIP_AGENT_JWT_SECRET` /
`BETTER_AUTH_SECRET`, with a per-process random fallback). Kept
`cleanup()` probing OpenRouter usage without deleting the token on
normal run exit, and added `revokeCompanyTokens(companyId)`.
- `server/src/services/cloud-trial-inference.ts`: Called
`proxy.revokeCompanyTokens(companyId)` upon `migrateTrialAgents`
completion and exposed `revokeCompanyTokens`.
- `server/src/__tests__/cloud-trial-inference.test.ts`: Added regression
test verifying warm session token reuse after `cleanup()`, survival
across a fresh controller restart, HTTP 401 on tampered tokens, and HTTP
401 after `revokeCompanyTokens`.

## Verification

- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/cloud-trial-inference.test.ts
src/__tests__/cloud-trial-proxy-middleware-order.test.ts` — passed (8/8
tests).
- `pnpm --filter @paperclipai/server typecheck` — passed (0 errors).

## Risks

- Low risk. Tokens are HMAC-SHA256 verified with `timingSafeEqual`,
strictly scoped to `(companyId, agentId, allowedModel)`, never contain
the raw OpenRouter key, and fail closed on `work_requires_model`, `$1`
budget exhaustion, disallowed models, and company migration.

## Model Used

- Google Gemini (Antigravity agentic runtime, thinking mode with tool
use and local code execution).

## Checklist

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

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Paperclip can keep a task's workspace in remote storage. Only a
Paperclip Runner agent in a sandbox environment, or a supported agent in
an SSH environment, can restore and save that workspace.
> - An agent can move to another environment, for example from a sandbox
to a plugin computer. Its tasks keep their saved remote workspaces.
> - When such a task woke, workspace preparation threw a bare 409: "This
workspace requires a supported remote execution environment." The run
ended `setup_failed`. The task offered Retry, and each Retry failed the
same way. Sentry received each refusal as an unexpected run failure.
> - This is a known configuration state that only an owner can repair,
like the project-storage mismatch from #22398.
> - This pull request refuses that run as `configuration_incomplete`
with a named reason, and it tells the owner what to do.
> - The benefit is an actionable task notice, no Retry loop, and no
Sentry noise for this state.

## Linked Issues or Issue Description

Refs #22398 (the same treatment for a source project's storage that the
environment cannot serve).
Refs #23568 (that change gave this refusal its own run-failure group, so
it became visible as a separate error).

**What happened?**

A task's workspace was saved in remote storage by an agent in a Daytona
sandbox. The agent was later moved to a plugin computer environment. An
automatic wake on the task failed setup with "This workspace requires a
supported remote execution environment." The run ended `setup_failed`.
The task notice said to press Retry. Retry cannot help, because the
agent's environment still cannot use the saved workspace. Sentry
received the refusal as an unexpected run failure.

**Expected behavior**

The refusal names the cause: the saved workspace is in remote storage,
and the agent's environment cannot use it. The run fails
`configuration_incomplete`. The task notice tells the owner to assign
the task to an agent that can use the saved workspace, or to change the
agent's environment. Sentry does not receive this known configuration
state. The saved workspace stays unchanged.

**Steps to reproduce**

1. Save a task workspace in remote storage with a Paperclip Runner agent
in a sandbox environment.
2. Change the agent's environment to a plugin computer (or assign the
task to an agent in another environment).
3. Wake the agent on the task. The run fails `setup_failed` with the
bare 409 message.

**Paperclip version or commit**

Seen on hosted staging. The new regression tests fail on `master` at
fc09515c7e and pass with this change.

## What Changed

- `remote-workspaces.ts`: extract
`supportsRemoteWorkspaceExecution(adapterType, driver)`.
`shouldUseRemoteWorkspaces` uses it. Its own behavior is unchanged.
- `workspace-preparation.ts`: when the task's existing workspace has
remote authority and the selected executor cannot use it, preparation
throws `ConfigurationIncompleteFailure` with reason
`remote_workspace_environment_incompatible`. This happens before
workspace resolution and environment acquisition. The payload records
the workspace, environment, driver, adapter, a stable fingerprint, and
the agent runtime action URL. Controller-only runs keep their existing
path.
- `run-failure-report.ts`: the exact pre-dispatch outcome is skipped,
together with `project_storage_environment_incompatible`. A marker after
provider work started, during execution, under another error code, or
outside the setup report is still reported.
`PAPERCLIP_SENTRY_RUN_FAILURES=all` still reports it.
- `stranded-notice.ts` and `recovery/service.ts`: the task notice and
the recovery next action name the owner action. Before this change, the
unknown reason fell back to the "missing secret" text.
- `doc/workspace-storage.md`: describe the new outcome.

## Verification

- Red before the fix, green after (red captured on fc09515c7e with only
the tests applied):
- `server/src/services/heartbeat/workspace-preparation.test.ts` › "names
a remote-storage workspace that the agent's environment cannot use as an
owner configuration gap". Before: the run failed with the bare 409 "This
workspace requires a supported remote execution environment." After:
`configuration_incomplete` with the named reason and payload. The test
also confirms that no workspace is resolved, no environment is acquired,
the saved remote authority is unchanged, and the task keeps its
workspace binding.
-
`server/src/services/__tests__/run-failure-report-remote-workspace-environment.test.ts`
› "keeps a remote workspace the agent's environment cannot use on the
task before dispatch". Before: Sentry received the run.
-
`server/src/services/recovery/stranded-notice-remote-workspace-environment.test.ts`.
Before: the notice said that a secret was missing.
- Safety cases (pass before and after): 11 marker variants are still
reported (other status, `setup_failed`, executing stage, exit code,
signal, no bootstrap marker, provider work started, other reason, no
setup phase, execute phase, `all` mode). The existing remote-workspaces
integration cases "preserves enrolled workspaces after disabling
enrollment and rejects a legacy writer" and "keeps enrollment
conditional…" pass. The full `workspace-preparation.test.ts` (161 tests)
passes, including the sandbox enrollment paths.
- Commands (local, Node 24.23, embedded Postgres):
- `pnpm exec vitest run
src/services/recovery/stranded-notice-remote-workspace-environment.test.ts
src/services/__tests__/run-failure-report-remote-workspace-environment.test.ts
src/services/__tests__/run-failure-report-project-access.test.ts
src/services/heartbeat/workspace-preparation.test.ts
src/__tests__/run-failure-sentry.test.ts` (server)
- `pnpm exec vitest run
src/services/remote-workspaces.integration.test.ts -t "preserves
enrolled workspaces|keeps enrollment conditional"` (server)
- `PAPERCLIP_TYPECHECK_LOW_MEMORY=1 pnpm --filter @paperclipai/server
typecheck` (passed)
- `pnpm verify` selected a broad plan because a doc changed. Required CI
supplies the broad coverage.

## Risks

- Low risk. The new path runs only where `shouldUseRemoteWorkspaces`
already threw. No run that started before can fail now.
- For those refused runs, only the failure code, the message, the
notice, and the Sentry decision change.
- The saved remote workspace and the task's binding are not changed. The
owner still chooses a compatible agent or environment.

## Model Used

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

## 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: paperclipbugbot <356415228+paperclipbugbot@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 22:51:09 -08:00
917a38efd7 fix(server): give the retired task workspace conflict a stable code (#23582)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Before a run starts, Paperclip reserves the task's remote workspace.
It refuses a workspace that is archived or whose cleanup failed, with
the message "Workspace ownership changed.".
> - When setup fails, the server sends a run-failure report to Sentry.
Since #23568, the report groups a setup conflict by the stable code in
its details.
> - This conflict has no code. Its reports use the fallback grouping and
share a Sentry group with other uncoded setup conflicts.
> - This pull request gives the conflict the code
`remote_workspace_retired`.
> - The benefit is a separate Sentry group for runs that fail on a
retired task workspace.

## Linked Issues or Issue Description

**What happened**
A task's execution workspace was archived. Automatic recovery then
started new runs for the task. Each run failed setup with "Workspace
ownership changed.". These reports went into a shared Sentry group with
unrelated setup conflicts, because the conflict had no code.

**Expected behavior**
The conflict has a stable code. Its run-failure reports get their own
Sentry group.

**Steps to reproduce**
1. Reserve a remote task workspace, then set its status to `archived` or
`cleanup_failed`.
2. Reserve the workspace again for a new run.
3. The reservation rejects with a 409 conflict that has no
`details.code`.

**Paperclip version or commit**
master at 8379dedd9.

Refs #23568 (reads `details.code` for run-failure grouping).

## What Changed

- `remote-workspaces.ts`: the "Workspace ownership changed." conflict
now has `details.code` `remote_workspace_retired`. The message and the
409 status do not change.
- `remote-workspaces.integration.test.ts`: a new test reserves an
`archived` and a `cleanup_failed` workspace and expects the conflict
with the new code.
- `run-failure-sentry.test.ts`: the example of an uncoded conflict now
uses another conflict that still has no code.

## Verification

- `cd server && npx vitest run
src/services/remote-workspaces.integration.test.ts -t "stable conflict
code"`: 2 of 2 pass. Without the change to `remote-workspaces.ts`, both
fail.
- `npx vitest run src/services/remote-workspaces.integration.test.ts
src/__tests__/run-failure-sentry.test.ts
src/services/__tests__/run-failure-diagnostics.test.ts`: 301 of 302
pass. The one failure, "cleans saved reads with read-only folders", also
fails on unchanged master in my sandbox (file mode 256 instead of 292).
It is not related to this change.

## Risks

- Low risk. The message, the status and the control flow do not change.
Only the conflict details get a code.
- Expected change: after deploy, Sentry reports for this conflict move
to a new group.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), with tool use and code execution
in a 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>
2026-12-02 22:13:09 -08:00
Michael NguyenandClaude fc09515c7e Emit Cloud chat.started when a chat with an agent starts (#23558)
<!-- claude-projects-attribution: {"github_login":"nguyenm7"} -->

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Paperclip Cloud measures activation with a funnel: account created,
org named, agent named, model connected, chat launched, first agent run
succeeded, first task created
> - `model.connected`, `agent.task_run` and `task.created` come from the
server, but "chat launched" comes only from the browser
(`onboarding_step_completed` with `step=launch`)
> - `task.created` skips chats on purpose, so a person who only chats
with their agent has no server-side step after "first agent run"
> - #23403 added a Cloud-only direct PostHog path
(`trackCloudPostHogEvent`) for onboarding events that must not depend on
the browser
> - This pull request uses that path to emit `chat.started` when the
chat owner's first message or first question-card answer commits
> - The benefit is a server-side "chat started" step that counts a real
action by the person, once per chat, whichever way they reached the chat

## Linked Issues or Issue Description

Refs #23403

**What existing behavior does this improve?**
Server-side activation funnels on Paperclip Cloud.

**Current behavior**
The only "chat launched" signal is the browser `launch` step. Browser
events can be lost (wizard skipped or resumed, navigation, ad blockers
on older builds). On the server, a chat creates an issue but
`emitTaskCreatedAfterCommit` returns early for it, so no event records
that the chat started.

**Proposed behavior**
When the chat owner's first turn commits (their first message, or their
first answer to a question card such as the onboarding welcome card),
the server emits the Cloud-only event `chat.started` with `surface`
(`onboarding_chat` | `agent_chat`) and `agent_id`. Creating or preparing
a chat emits nothing, because onboarding prepares the chat before the
person clicks Launch. The Launch click itself is already relayed
server-side as `onboarding_step_completed` (`step=launch`).

**Reason and benefit**
Funnel steps should come from real product actions that the server
records. With `chat.started`, a funnel can count "chat launched" from
the server and see people who chat but never create a task.

**Breaking changes**
None. The event is new and is Cloud-only.

## What Changed

- `server/src/services/product-telemetry.ts`: add `CHAT_STARTED_EVENT`
and `emitChatStartedIfFirstOwnerTurn`. It runs inside the transaction
that wrote the person's turn and locks the chat's issue row. It checks
that the actor is the chat owner (not an agent, run, or system actor),
and that the owner has no other message and no other answered question
card in the chat. Cancelled or skipped cards do not count. Then it emits
`chat.started` through `trackCloudPostHogEvent` after commit.
- Callers: `addComment` (`issues.ts`), `answerQuestions`
(`issue-thread-interactions.ts`), both headless comment paths
(`headless-comment-group-commit.ts` and the serialized insert in
`routes/headless-channels-schemas.ts`), and the headless one-line
resolve (`headless-events-schedules-interactions.ts`).
- `server/src/__tests__/chat-started-telemetry.test.ts`: unit tests for
the first turn, both surfaces, and every case that must not emit.
- `server/src/__tests__/product-telemetry.test.ts`: embedded-Postgres
tests. Chat creation and system or other-person messages emit nothing.
The owner's first message emits once. A first message after a cancelled
card still emits. A rolled-back first message and a task comment emit
nothing.
- `docs/api/onboarding-telemetry.md`: document the server-emitted
`chat.started` event.

## Verification

- `npx vitest run server/src/__tests__/chat-started-telemetry.test.ts`:
10 passed (helper unit tests).
- `pnpm --filter @paperclipai/server typecheck`: passed.
- The cases in `product-telemetry.test.ts` need embedded Postgres, which
could not start in my environment (it runs as root). CI runs them.

## Risks

- Low. The event is fire-and-forget after commit, inside a `try`. It
does nothing on self-hosted installs, when `PAPERCLIP_POSTHOG_DIRECT=0`,
or when the PostHog environment is not set.
- One event per chat: the check runs under the chat's issue row lock,
and a rolled-back write emits nothing. `/new` in an existing chat does
not emit again.
- Two extra indexed reads run on a person's chat message or answer, and
only on chats.

### Open questions for reviewers

1. **Consent.** Like `model.connected` and the #23403 relay, this server
event is not gated by the browser cookie banner. This PR does not add a
consent check. The only switch is the existing
`PAPERCLIP_POSTHOG_DIRECT=0`. If people who decline cookies must be
excluded from server-side product events, that should be one rule for
all Cloud direct events, not a rule in this PR.
2. **New name or existing name.** This PR adds a new name,
`chat.started`, instead of emitting `onboarding_step_completed`
(`step=launch`) from the server. A new name keeps the browser and server
signals separate, so the two funnels can be compared and the existing
insights do not double count. The other choice is to emit the existing
name with a `source: server` property. Please say which one you prefer.

Not in this PR: "Agent named" has no clean server moment (the setup
agent is saved with a default name before the person names it, and
`agent.created` fires at launch), and `agent.task_run` still does not
say whether a run was a chat reply or a task. That needs a new
registered dimension in the telemetry contract, so it is a follow-up.

## Model Used

Claude Code (Anthropic Claude, agentic coding 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)
- [ ] 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

https://claude.ai/code/session_01KmUZthscGtSrd1KaWnwzWm

---
_Generated by [Claude Code](https://claude.ai/code)_

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-12-02 20:20:25 -08:00
paperclipbugbotandClaude Opus 5.5 49165825a0 fix(native): restart an unclaimed continued-session follow-up instead of reattaching (#23434)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Native runs can execute in remote Daytona sandboxes. After a server
restart, restart recovery decides how each interrupted run continues.
> - Recovery can restart an incomplete bootstrap, or it can reattach to
a live remote runner.
> - A continued-session follow-up gets the previous turn's checkpoint
and provider session (`sessionIdBefore`) at admission, before an
executor claims it.
> - The unclaimed-bootstrap check (#20214) refuses every run that has
`sessionIdBefore`. Thus a real follow-up never matches it. Recovery
falls through to the generic fallback and reattaches to a runner that
never started.
> - This pull request lets the unclaimed-bootstrap check accept such a
follow-up when all of its session evidence is inherited.
> - The benefit is that the run restarts cleanly. It does not fail, and
it does not cause the next follow-up to fail.

## Linked Issues or Issue Description

Refs #20214, #20153, #20642, #20979, #20226, #19373

**What happened?**
A hard restart reached a continued-session follow-up on a new Daytona
sandbox before any executor claimed it (coordinator attempt 0,
controller generation 0). Recovery chose `reattach_remote_runner` from
the inherited provider session ID only. The run failed with
`remote_reattach_root_missing`. The next follow-up selected the failed
run as its source and failed with
`native_controller_recovery_unsupported:metadata_format`.

**Steps to reproduce**
1. Admit a continued-session follow-up on a remote sandbox. Admission
sets `sessionIdBefore` and rebinds the previous turn's checkpoint to the
run.
2. Hard-restart the server before an executor claims the run.
3. Restart recovery claims the run with `reattach_remote_runner`,
`providerAttempt: 0`, `controllerGeneration: 1`.

**Expected behavior**
Recovery restarts the bootstrap (`bootstrap_incomplete`, reason
`remote_execution_never_claimed`), as it does for an unclaimed first
run.

**Environment**
Staging, remote Daytona sandboxes, master that includes all of the
linked fixes.

## What Changed

- `native-restart-recovery.ts`: `unclaimedBootstrap` accepts
`sessionIdBefore` when all of these are true:
- `sessionIdBefore` equals the rebound checkpoint's `providerSessionId`.
- The checkpoint is continued-session-only and inherited-only: no
cursor, turns, active turn, result, terminal state, pending requests or
provider events.
- A settled earlier run of the same native session saved that exact
provider session (`carriesSettledPredecessorSession`).
- All other unclaimed-bootstrap guards stay the same: no execution-start
evidence, no own runner identity, prepared remote workspace, preparation
fencing.
- `continuedSessionOnly` and `pendingInheritedRequests` move above
`unclaimedBootstrap`. Their definitions do not change.
- `native-runner-restart-recovery.integration.test.ts`: one new
`it.each` with five cases. The rebound follow-up restarts. A session
with no settled predecessor, a carried active turn, a projected provider
event, and a `sessionIdBefore` that differs from the checkpoint all stay
held.

## Verification

- Red on master: the new `restarts an unclaimed continued-session
follow-up` case received `reattach_remote_runner`, `providerAttempt: 0`,
`controllerGeneration: 1`. These are the same values as the staging
failure.
- Green with this change: `npx vitest run
src/services/native-runtime/native-runner-restart-recovery.integration.test.ts`
(from `server/`) gives 232 passed and 22 skipped. The skipped tests need
`PAPERCLIP_TEST_RUNNER_CONTAINER`, and they skip on master too.
- Also passed locally: `heartbeat/recovery.test.ts`,
`heartbeat/live-runner-adoption.test.ts`,
`native-restart-recovery-isolation.test.ts`,
`native-stop-accounting.integration.test.ts`,
`native-warm-transition-restart.integration.test.ts`,
`native-scheduled-resume-lock.test.ts`,
`native-controller-identity.test.ts`,
`__tests__/heartbeat-native-restart-suspension.test.ts`,
`__tests__/heartbeat-native-early-hand-off.test.ts`.
- Not run locally:
`native-runner-restart-preparation.integration.test.ts`,
`remote-workspace-migration.test.ts`,
`heartbeat/workspace-preparation.test.ts`, typecheck and build. The
local sandbox could not run `git`, and those fixtures need it. CI covers
them.

## Risks

- Low risk. The change only adds one more shape to an existing restart
path. The shape needs a settled predecessor that saved the same provider
session, and the run must have no evidence of its own work.
- If the evidence is incomplete, recovery holds the run as before. It
does not reattach or restart it.

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

## Model Used

- Anthropic Claude Opus 5.5 (`claude-opus-5-5`), used as an 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
- [ ] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [ ] I will address all Greptile and reviewer comments before
requesting merge

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 02:23:39 +00:00
c852420baf fix(server): group setup conflicts by their detail code in run-failure reports (#23568)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - When an agent run fails, the server sends a run-failure report to
Sentry. The fingerprint of the report sets the Sentry group.
> - Setup failures without a root error code use a fallback fingerprint:
the exception name and the HTTP status.
> - The `conflict()` helper keeps its stable code in `details.code`. The
diagnostics read only `code` and `reasonCode` on the error. They ignore
`details.code`.
> - Thus every coded 409 setup conflict gets the fingerprint
`exception:Error` + `status:409`. Unrelated causes go into one Sentry
group. For example, an unfinished workspace writer and a missing remote
execution environment share one group.
> - This pull request reads a bounded identifier from `details.code`
when the error has no own code.
> - The benefit is one Sentry group for each setup conflict cause. A fix
for one cause no longer shows as a regression of another cause.

## Linked Issues or Issue Description

**What happened**
One Sentry group receives three different setup failures. They are "The
workspace still has an unfinished writer or save operation.", "This
workspace requires a supported remote execution environment." and
"Workspace ownership changed." Each one has a different cause. The first
two have a stable code in `details.code`
(`remote_workspace_writer_pending` and
`remote_workspace_execution_required`). The run-failure diagnostics do
not read that code, so all three get the same fallback fingerprint.

**Expected behavior**
A setup conflict with a stable code gets a fingerprint with that code.
Different causes go into different Sentry groups.

**Steps to reproduce**
1. Make a run fail setup with `conflict(message, { code:
"remote_workspace_writer_pending" })`.
2. Make another run fail setup with `conflict(message, { code:
"remote_workspace_execution_required" })`.
3. Look at the run-failure fingerprints. Both are `[setup_failed,
<adapter>, setup, exception:Error, status:409]`.

**Paperclip version or commit**
master at 53bebb59f.

Refs #23475, #23446, #22103 (fixes for the unfinished-writer cause; this
change lets Sentry show that cause by itself).

## What Changed

- `run-failure-diagnostics.ts`: when an exception has no `code` and no
`reasonCode`, read `details.code`. Accept it only when it is a lowercase
identifier of 2 to 100 characters (`^[a-z][a-z0-9_]{1,99}$`). Do not
read other fields of `details`.
- An own `code` or `reasonCode` on the error still has priority.
- Tests: a diagnostics test for the accepted and rejected detail values,
and a Sentry capture test that sends real `conflict()` errors through
the diagnostics and checks the fingerprints.

## Verification

- `cd server && npx vitest run
src/services/__tests__/run-failure-diagnostics.test.ts
src/__tests__/run-failure-sentry.test.ts`: 184 of 184 pass.
- Without the change to `run-failure-diagnostics.ts`, the two new tests
fail. The other 182 tests pass.
- All 19 server test files that use run-failure diagnostics or reports
pass (921 passed, 35 skipped).

## Risks

- Low risk. The change affects only Sentry run-failure reports. No other
code reads these exception codes.
- Expected behavior change: setup conflicts with a `details.code` move
from the shared fallback group to new Sentry groups, one for each code.
Uncoded conflicts stay in the fallback group.
- The code value also goes into the `root_error_code` tag and the
`run_exception_N` context. The strict pattern keeps free text and
secrets out.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), with tool use and code execution
in a 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>
2026-12-02 18:13:08 -08:00
scotttong b0f682b66b Measure when users see a reply to their onboarding chat input (#23574) 2026-12-02 18:03:08 -08:00
Devin FoleyandPaperclip 6e340a3f96 Verify onboarding models and explain provider failures (#23563)
Verify deployment-configured model preferences with the selected account.
Preserve structured provider failures and show descriptive messages for known
causes through the existing onboarding error display. Keep the existing failure
buttons, account binding, and retry/sign-in behavior.

Validation: UI typecheck, 38 focused tests, four browser journeys, all applicable
CI checks, and Greptile 5/5 with no unresolved review comments.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-12-02 16:47:58 -08:00
Nicky LeachandPaperclip cc2e1d9d43 Honor plugin task driver concurrency defaults on hire (#23535)
## Thinking Path

> - Paperclip schedules work for agents.
> - Each agent has a limit on simultaneous runs.
> - A task driver can provide an execution environment with its own
capacity.
> - Previously the creation form sent the same limit for every driver.
> - A driver can now declare the value Core saves when a new agent has
no explicit limit.

## Linked Issues or Issue Description

**Subsystem affected**

Agent hiring and plugin environment drivers.

**Current behavior**

The create form, API, and import flow supply the global concurrency
default before the task driver can provide one.

**Proposed behavior**

Let each task driver declare an optional per-agent concurrency default.
Apply it once during hire and honor explicit agent limits.

## What Changed

- Refreshed the three SDK source pins for the changed files.
- Added the optional driver field `defaultMaxConcurrentRuns` with
integer bounds from 1 through 50.
- Applied it during hire using the resolved task environment. Saved the
resolved runtime configuration in hire approvals.
- Removed early defaults from the creation form, routes and new-agent
imports. Preserved saved limits on export, including explicit values
equal to the global default. Kept the current limit when importing an
update with an omitted limit.

## Verification

- [Full PR
CI](https://github.com/paperclipai/paperclip/actions/runs/47000023360)
passed on `83cce42b9a`. Server shard 16 passed on retry after a
PostgreSQL connection reset on the first attempt.
- `pnpm -r typecheck` passed. The SDK source pin check passed. `pnpm
verify` selected broad CI coverage because the SDK input registry
changed.
- On rebased commit `83cce42b9a`, all 441 tests in six focused Vitest
suites passed, including the MCP rollback test corrected in #23560. The
SDK source pin check passed.

## Risks

This affects new hires on drivers that opt in. Existing agents retain
their saved configuration. Single-run provider limits still apply. An
older client that explicitly sends the global default will keep that
value.

## Model Used

OpenAI GPT-6 via Codex. Used local source inspection, code editing,
TypeScript and test execution.

## Checklist

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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-12-02 16:23:42 -08:00
Dotta 85b9586dd5 fix(cloud-trial): transfer OpenRouter starter proxy credentials to remote plugin Runners (#23559)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Cloud starter-inference onboarding (`free_inference_1`) runs the
first OpenCode agent inside a remote plugin Runner environment using a
per-run server proxy (`PAPERCLIP_OPENROUTER_PROXY_URL` and
`PAPERCLIP_OPENROUTER_PROXY_TOKEN`) instead of exposing the raw
OpenRouter key.
> - On remote plugin Runner environments, OpenCode runs failed
immediately with OpenRouter HTTP 401 (`No cookie auth credentials
found`) because the proxy URL and token never reached the sandbox.
> - Three boundaries stripped the proxy credentials:
`preparePluginRunnerCredentials` returned early when
`managedAiCredentialIdentity` was absent,
`ENVIRONMENT_TASK_PROVIDER_CREDENTIAL_KEY_SETS.opencode` did not allow
the proxy pair, and Rust `OPENCODE_PROVIDER_ENVIRONMENT_KEYS` in
`codex_provider.rs` did not forward those keys.
> - This pull request adds the `[PAPERCLIP_OPENROUTER_PROXY_URL,
PAPERCLIP_OPENROUTER_PROXY_TOKEN]` pair across all three boundaries
while keeping raw starter keys strictly server-side and failing closed
on partial or ambiguous credentials.
> - The benefit is that Cloud starter-inference OpenCode runs
authenticate cleanly through the server proxy inside remote plugin
Runner sandboxes.

## Linked Issues or Issue Description

Refs #23401, #23427

**Summary**
Transfer `PAPERCLIP_OPENROUTER_PROXY_URL` and
`PAPERCLIP_OPENROUTER_PROXY_TOKEN` through the plugin Runner credential
boundary and Rust `runner-core` allowlist for Cloud starter-inference
OpenCode runs.

**Steps to Reproduce**
1. Create a Cloud starter-inference (`free_inference_1`) workspace
running OpenCode in a remote plugin Runner environment.
2. Send a message in the onboarding chat.
3. Observe `APIError` HTTP 401 (`No cookie auth credentials found`) from
OpenRouter because the sandbox OpenCode proxy received neither
`PAPERCLIP_OPENROUTER_PROXY_URL` nor `OPENROUTER_API_KEY`.

**Expected Behavior**
The remote plugin Runner receives `{ PAPERCLIP_OPENROUTER_PROXY_URL,
PAPERCLIP_OPENROUTER_PROXY_TOKEN }` via the `opencode` `provider-env`
credential channel, forwards them to OpenCode, and routes inference
through the server-side starter proxy.

## What Changed

- `packages/plugins/sdk/src/environment-tasks.ts`: Added
`["PAPERCLIP_OPENROUTER_PROXY_URL", "PAPERCLIP_OPENROUTER_PROXY_TOKEN"]`
to `ENVIRONMENT_TASK_PROVIDER_CREDENTIAL_KEY_SETS.opencode`.
-
`packages/paperclip-runner/runner/crates/runner-core/src/codex_provider.rs`:
Added `"PAPERCLIP_OPENROUTER_PROXY_URL"` and
`"PAPERCLIP_OPENROUTER_PROXY_TOKEN"` to
`OPENCODE_PROVIDER_ENVIRONMENT_KEYS`.
- `server/src/services/native-runtime/plugin-runner-credentials.ts`:
Allowed `opencode` runs with both `PAPERCLIP_OPENROUTER_PROXY_URL` and
`PAPERCLIP_OPENROUTER_PROXY_TOKEN` to transfer that `provider-env`
credential when `identity` is absent (using `"cloud-trial"` as
`accountIdentity`).
-
`server/src/services/native-runtime/plugin-runner-credentials.test.ts`:
Added regression coverage for transferring the Cloud starter proxy pair
without a managed AI connection identity and failing closed on partial
or ambiguous combinations.
- `tests/runner-e2e/source-sdk-public-inputs.json`: Updated reviewed SDK
public inputs pin for `packages/plugins/sdk/src/environment-tasks.ts`.

## Verification

- `pnpm --filter @paperclipai/plugin-sdk build` — passed.
- `pnpm --filter @paperclipai/plugin-sdk exec vitest run
tests/environment-tasks.test.ts
tests/environment-task-release-resume.test.ts` — passed (104/104 tests).
- `pnpm --filter @paperclipai/server exec vitest run
src/services/native-runtime/plugin-runner-credentials.test.ts
src/__tests__/plugin-runner-credential-names.test.ts` — passed (45/45
tests, verifying SDK allowlist, Runner TS allowlist, and Rust
`codex_provider.rs` allowlist together).

## Risks

- Low risk. Only the ephemeral per-run proxy URL and `pctrial_` token
pair is allowed when both are present and non-empty; partial or mixed
sets still fail closed in `environmentTaskCredentialSchema`, and raw
OpenRouter keys never leave the server process.

## Model Used

- Google Gemini (Antigravity agentic runtime, thinking mode with tool
use and local code execution).

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [ ] I will address all Greptile and reviewer comments before
requesting merge
2026-12-02 16:53:07 -06:00
DottaandPaperclip 9aaeae40bf test: prune orphaned test-support fixtures and helpers (#23360)
Co-Authored-By: Paperclip <Paperclip-Paperclip@users.noreply.github.com>
2026-12-02 16:40:01 -06:00
Dotta 86927d4933 feat(cloud-trial): enable fast responses by default with starter inference key (#23556)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Fast responses send a brief acknowledgement in the agent's voice
while the full agent run starts.
> - During Cloud starter-inference onboarding (`free_inference_1`),
users start chatting immediately before connecting their own model
provider, so no `company_fast_responses` connection exists yet.
> - Without a default fast-response path, the first chat waits silently
while the Runner starts up and thinks.
> - This pull request enables fast responses by default while Cloud
starter inference is active, routing acknowledgements through the
server-held OpenRouter starter key with `$1` quota and `llmBlocked` gate
enforcement.
> - The benefit is immediate, responsive first-chat acknowledgements out
of the box with a clean handoff once the user connects their own model
provider.

## Linked Issues or Issue Description

Refs #23401, #23427

**Summary**
Enable fast-response acknowledgements by default for companies running
on active Cloud starter inference (`free_inference_1`), using the
existing server-side OpenRouter starter inference key.

**Problem Statement**
Fast responses currently require both the experimental
`enableFastResponses` instance flag and an explicit shared API
connection in `company_fast_responses`. New Cloud starter-inference
workspaces have no saved API connection yet, so users do not get fast
acknowledgements during their initial onboarding chat.

**Proposed Solution**
Fall back to the server-side Cloud starter inference OpenRouter key
(`FAST_RESPONSE_DEFAULT_MODEL`, `openai/gpt-oss-120b`) when a company
has no `company_fast_responses` row and is actively on trial-only
inference without a blocked gate. Respect explicit company
configuration/opt-out, enforce `responsibleUserId` and `issue:read`
authorization, disallow sponsored webhooks on the starter key, mark the
trial exhausted on HTTP 402/limit errors, and stop using the starter key
automatically once the user connects their own model provider.

## What Changed

- `server/src/services/cloud-trial-proxy.ts` &
`server/src/services/cloud-trial-inference.ts`: Added
`isCloudTrialFastResponseEligible` and `prepareCloudTrialFastResponse`.
Keeps the raw OpenRouter key strictly in server process memory, enforces
`isCompanyOnTrialOnlyInference`, the `$1` quota, and the
`work_requires_model` / `exhausted` gates, wraps `fetch` to call
`markExhausted` immediately on HTTP 402/limit responses, and probes
usage on cleanup.
- `server/src/services/fast-responses.ts`: Updated
`enqueueFastResponse`, `fastResponseSourceCurrent`, `settings`,
`availability`, `resolve`, `process`, and `history` to use Cloud starter
inference by default when no `company_fast_responses` row exists and
starter inference is active and unblocked. Explicit
`company_fast_responses` rows (including opt-out `enabled: false`)
always take precedence, and connecting a user model provider cleanly
ends starter-key usage.
- `packages/shared/src/fast-response.ts`: Added optional
`usingCloudTrialDefault?: boolean` to `FastResponseSettings`.
- `server/src/__tests__/fast-responses.test.ts`: Added regression tests
covering starter-inference default fast responses (even when
`enableFastResponses` is `false`), raw key non-leakage,
`work_requires_model` gate blocking, HTTP 402 exhaustion, explicit
opt-out, and clean handoff after connecting a user model provider.

## Verification

- `pnpm --filter @paperclipai/shared typecheck` — passed (0 errors).
- `pnpm --filter @paperclipai/server typecheck` — passed (0 errors).
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/fast-responses.test.ts
src/__tests__/cloud-trial-inference.test.ts` — passed (44/44 tests).

## Risks

- Low risk. No database schema migration is required
(`fast_response_requests.connection_id` and `grant_id` are already
nullable). Self-hosted instances and `baseline` Cloud stacks are
unaffected because `trialInferenceEnabled` is `false`. Companies that
explicitly configure or disable `company_fast_responses` or connect
their own AI provider never fall back to the starter key.

## Model Used

- Google Gemini (Antigravity agentic runtime, thinking mode with tool
use and local code execution).

## Checklist

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

> - Paperclip is the open source app people use to manage AI agents for
work.
> - A connection starts as a draft. The operator saves its actions and
agent access at the finish step.
> - A saved draft can resume through the same connection path as a
removed connection.
> - That path restored default access for every saved connection,
including a new draft.
> - This created a company binding before the operator selected an
audience. Finish then checked every agent in the company.
> - This pull request keeps a resumed draft unbound until finish.
Previously configured connections keep their restore behavior.
> - A small audience now has a small authorization cost, even in a large
company.

## Linked Issues or Issue Description

**What happened?**

A saved MCP draft gained a company-wide profile when setup resumed.
Saving access for one agent then caused 16,610 SQL queries in a local
fixture with 1,100 agents. The request took about 8 seconds with a local
database. A remote setup request can exceed the client's deadline while
its write still completes later.

**Expected behavior**

A new draft must have no profile or access binding until the operator
saves access. Saving one selected agent must not check the full company
roster.

**Steps to reproduce**

1. Create a disabled MCP URL draft in a company with 1,100 agents.
2. Resume it with `reconnectConnectionId` and complete catalog
discovery.
3. Finish with one selected agent and one Ask first action.
4. Before this fix, the draft has a company binding and finish runs
thousands of queries.

**Paperclip version or commit**

Reproduced on `master` at `3d0e0b6dd989baeb469f99380b496c273b0b290a`.

**Deployment mode**

Any server with saved connection drafts. The local proof uses embedded
PostgreSQL and the real service and HTTP route.

Related work:
[#22080](https://github.com/paperclipai/paperclip/pull/22080) resumes
saved sign-in drafts. This change fixes the default access restored
during a draft resume.

## What Changed

- `connectGalleryApp` does not request default restoration when the
retained connection is still a draft.
- Active and archived connections keep the existing restoration path.
- Two database regressions cover URL drafts and gallery API-key drafts.
The URL test uses 1,100 agents, the real finish route, an owner session,
and a bound of fewer than 200 SQL queries. It also checks that only the
selected agent is installed and the Ask first policy is saved.
- Tests stay in the existing service suite. Its shared PostgreSQL
fixture already owns setup, finish, and restore coverage. No new
production module or schema is needed.

## Verification

- Red: both new tests failed on the old code. The saved drafts had an
active profile or a company binding before finish.
- Green: 7 focused tests passed. These include both new regressions,
archived action restoration, retained archived managed-profile
restoration, active custom MCP reconnect, and two OAuth draft resume
paths.
- Local probe before the fix: 16,610 SQL queries and about 8 seconds for
finish with 1,100 agents. The new regression requires fewer than 200
queries after the fix. It does not use a wall-clock timing assertion.
- `pnpm verify` could not run: the managed Git storage guard rejects
`git ls-files` with exit 75. The two changed files were compared with
the pinned master files before the patch. Remote file bytes were
verified after Git Data API publication.
- Full preflight installed dependencies and built shared and plugin SDK
packages. It could not build Rust Runner binaries because `cargo` is
unavailable. The focused tests completed with the real embedded
database.
- `pnpm --filter @paperclipai/server typecheck` passed, including its
test layers.
- Final-head CI passed at `b166b20550de98337842fb6fee96ca1024e09c34`:
[run
46979210544](https://github.com/paperclipai/paperclip/actions/runs/46979210544),
including typecheck, build, tests, and all 16 E2E shards. Greptile
scores this revision 5/5; all review threads are resolved. Staging
acceptance remains pending.

## Risks

- The status check must preserve restoration for a connection that was
already configured or removed. The focused suite checks active and
archived reconnects.
- A draft that already has retained access keeps those saved rows. This
change prevents the default-restoration call; it does not delete
existing access.
- The change does not relax permission checks, change Ask first
behavior, increase timeouts, or retry writes.

## Model Used

OpenAI GPT-6 Codex agent, with reasoning, shell tools, code execution,
and GitHub API tools.

## Checklist

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

hint: if you need to wait for this pull request to be reviewed, merged,
or closed before continuing, use this instead of polling:
gh event listen --resource
https://github.com/paperclipai/paperclip/pull/23553 --event
com.github.pull_request.review.submitted.v1,com.github.pull_request.state.changed.v1
- It prints the first event as a JSON line on stdout and exits; run it
again to wait for the next one.
- Add `--timeout` to stop waiting after a while, for example `--timeout
30m`; it then exits with status 8.
  - Events carry no details; read the pull request to see what changed.
- It misses changes made before it starts, so read the pull request once
it is running.
  - See `gh event listen --help` for other event types.
- Event subscriptions are in preview and may not be enabled for your
account.

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-12-02 16:09:19 -06:00
DottaandPaperclip a30b1be565 fix(realtime): live-sync open web UI windows on headless pc mutations (#23532)
## Thinking Path

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

## Linked Issues or Issue Description

**What happened?**

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

**Expected behavior**

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

**Steps to reproduce**

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

**Paperclip version or commit**

`4db307d53c` (`origin/master`)

**Deployment mode**

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

## What Changed

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

## Verification

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

## Risks

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

## Model Used

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

## Checklist

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

---------

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

Co-Authored-By: Scott Tong <scott@scotts-mbp-m5-max.local>
2026-12-02 12:05:16 -08:00
Nicky LeachandPaperclip 4db307d53c Stop resuming completed Claude sign-ins (#23530)
## Thinking Path

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

## Linked Issues or Issue Description

**What happened?**

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

**Expected behavior**

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

**Steps to reproduce**

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

## What Changed

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

## Verification

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

## Risks

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

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

## Model Used

OpenAI Codex (GPT-6), with repository and test tools.

## Checklist

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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-12-02 08:20:16 -08:00
DottaandPaperclip debfa75a7a perf(server): coalesce concurrent channel posts and replies with debounced activity (#23448)
## Thinking Path

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

## Linked Issues or Issue Description

Refs #23426

**What existing behavior does this improve?**

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

**Subsystem affected**

- `server/ — REST API & orchestration services`

**Current behavior**

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

**Proposed behavior**

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

**Reason and benefit**

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

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

**Breaking changes**

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

**Additional context**

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

## What Changed

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

## Verification

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

## Risks

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

## Model Used

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

## Checklist

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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-12-02 06:13:26 -06:00
7636441c46 fix(recovery): hold an agent comment wake behind a refused workspace writer hold (#23475)
## Thinking Path

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

## Linked Issues or Issue Description

Refs #22103
Refs #23446
Refs #21221

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

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

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

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

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

## What Changed

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

## Verification

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

## Risks

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

## Model Used

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

## Checklist

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

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

---------

Co-authored-by: paperclipbugbot <356415228+paperclipbugbot@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 02:26:46 -08:00
Nicky Leach 5a956b724b fix(agents): set agents up again when their environment driver changes (#23449) 2026-12-01 23:33:24 -08:00
Devin FoleyandPaperclip 725a9e36b6 fix(connections): let a dedicated account serve every agent picked for its connection (#23431)
## Thinking Path

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

## Linked Issues or Issue Description

No public issue exists.

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

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

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

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

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

## What Changed

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

## Verification

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

## Risks

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

## Model Used

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

## Checklist

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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-12-01 22:40:42 -08:00
29a45b42db fix(recovery): stop retrying a setup failure behind a refused workspace writer hold (#23446)
## Thinking Path

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

## Linked Issues or Issue Description

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

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

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

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

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

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

## What Changed

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

## Verification

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

## Risks

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

## Model Used

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

## Checklist

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

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

---------

Co-authored-by: paperclipbugbot <356415228+paperclipbugbot@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 20:41:33 -08:00