Commit Graph
3380 Commits
Author SHA1 Message Date
Dotta d57d4db4ab fix(test): share module instances in instance-settings-routes test (#23423)
## Thinking Path

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

## Linked Issues or Issue Description

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

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

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

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

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

## What Changed

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

## Verification

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

## Risks

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

## Model Used

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

## Checklist

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

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

## Linked Issues or Issue Description

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

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

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

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

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

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

## What Changed

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

## Verification

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

## Risks

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

## Model Used

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

## Checklist

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

---------

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

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

## Linked Issues or Issue Description

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

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

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

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

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

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

## What Changed

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

## Verification

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

## Risks

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

## Model Used

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

## Checklist

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

---------

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

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

## Linked Issues or Issue Description

No public issue exists.

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

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

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

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

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

## What Changed

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

## Verification

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

## Risks

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

## Model Used

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

## Checklist

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

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-12-01 13:27:10 -08:00
Dotta c0edaa21a3 feat(analytics): move onboarding funnel telemetry server-side and add granular step instrumentation (#23403)
## Thinking Path

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

## Linked Issues or Issue Description

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

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

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

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

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

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

## What Changed

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

## Verification

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

## Risks

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

## Model Used

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

## Checklist

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

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

## Linked Issues or Issue Description

**Subsystem affected**

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

**Problem or motivation**

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

**Proposed solution**

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

**Alternatives considered**

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

## What Changed

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

## Verification

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

## Risks

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

## Model Used

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

## Checklist

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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-12-01 20:54:03 +00:00
Devin FoleyandPaperclip 11d5b06864 fix(runner): give a plugin task prepare 60 s without a startup context (#23396)
## Thinking Path

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

## Linked Issues or Issue Description

No public issue exists.

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

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

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

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

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

## What Changed

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

## Verification

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

## Risks

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

## Model Used

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

## Checklist

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

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-12-01 11:26:21 -08:00
5a9c06b315 feat(analytics): make replay work content a deployment opt-in (#22820)
## Thinking Path

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

## Linked Issues or Issue Description

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

**What existing behavior does this improve?**

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

**Subsystem affected**

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

**Current behavior**

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

**Proposed behavior**

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

**Reason and benefit**

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

**Breaking changes**

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

## What Changed

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

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

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

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

## Verification

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

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

On the final source change, locally:

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

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

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

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

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

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

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

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

## Risks

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

## Model Used

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

## Checklist

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Devin Foley <devin@paperclip.ing>
Co-authored-by: Paperclip <noreply@paperclip.ing>
Co-authored-by: Dotta <bippadotta@protonmail.com>
2026-12-01 18:53:11 +00:00
Nicky LeachandPaperclip 07af22c57f feat(plugins): support agentless harness sign-in (#23392)
## Thinking Path

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

## Linked Issues or Issue Description

**Subsystem affected**

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

**Current behavior**

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

**Proposed behavior**

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

**Reason and benefit**

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

**Additional context**

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

## What Changed

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

## Verification

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

## Risks

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

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

## Model Used

OpenAI Codex, GPT-6, with local code inspection and test execution.

## Checklist

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

---------

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

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

## Linked Issues or Issue Description

Refs #23329
Refs #23330

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

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

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

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

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

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

## What Changed

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

## Verification

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

## Risks

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

## Model Used

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

## Checklist

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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-12-01 17:57:33 +00:00
Dotta 37da976b8c fix(monitors): preserve authorized task monitors on tasks with unresolved blockers (#23390)
## Thinking Path

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

## Linked Issues or Issue Description

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

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

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

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

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

## What Changed

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

## Verification

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

## Risks

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

## Model Used

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

## Checklist

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

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

## Linked Issues or Issue Description

Refs #23329
Refs #23330

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

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

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

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

## What Changed

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

## Verification

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

## Risks

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

## Model Used

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

## Checklist

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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-12-01 17:12:11 +00:00
Dotta e32b1b057f fix(telemetry): re-identify PostHog workspace group on Cloud stack claim (#23389)
## Thinking Path

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

## Linked Issues or Issue Description

**What happened?**

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

**Expected behavior**

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

**Steps to reproduce**

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

**Paperclip version or commit**

`36c2ad39c8` (`origin/master`)

**Deployment mode**

Other (Paperclip Cloud managed stack)

## What Changed

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

## Verification

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

## Risks

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

## Model Used

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

## Checklist

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

> - Paperclip is the open source app people use to manage AI agents for
work
> - Environment plugins can run agent tasks on remote computers, and can
run the provider sign-in for those computers
> - Core decides which adapters can sign in on a plugin environment from
a fixed Claude and Codex rule and a `supportsCodexLogin` flag
> - A plugin cannot say which adapters it supports, so Grok has no
sign-in on a plugin computer, and a plugin can run an adapter that it
cannot sign in
> - This pull request lets a Runner task driver declare its supported
adapters, and makes support mean the full adapter lifecycle: runs and,
where Paperclip offers one, sign-in
> - The benefit is one extensible support contract per driver, with no
partial matrix, and Grok subscription sign-in on plugin computers

## Linked Issues or Issue Description

**Subsystem affected**

Plugin SDK environment drivers, plugin sign-in (login pseudo-terminal),
plugin Runner task credentials, and agent Runner selection.

**Problem or motivation**

Core allows plugin-computer sign-in only for Claude, and for Codex when
the plugin can read back a credential file. The flag for that is named
`supportsCodexLogin`, which does not describe what it does. A plugin
cannot advertise which adapters it supports. Grok has a device sign-in
in Core, but it has no sign-in on a plugin computer, and a Grok
subscription cannot reach a plugin task. A plugin can also run an
adapter that has no sign-in on that plugin. This gives a partial support
matrix.

**Proposed solution**

A Runner task driver declares `supportedAdapters`. Support for an
adapter means the full lifecycle. The driver must run the adapter, and
it must run the Paperclip sign-in when the adapter has one. Core
validates the declaration in the manifest, and Core checks it again
against the methods of the running worker. An adapter that fails either
check is not offered for sign-in, for save, or for runs. The sign-in
contract moves to one shared map, so a new adapter sign-in is one entry
in that map.

**Alternatives considered**

A separate per-capability table (runs, sign-in, credential read-back)
was rejected. It permits the partial matrix that this change removes.
The existing sign-in map and credential sets already contain the
necessary data.

**Additional context**

Related open pull requests: Refs #14001 (Kubernetes plugin login
pseudo-terminal), Refs #21327 (Grok device link in the sign-in UI).

## What Changed

- Environment drivers can declare `supportedAdapters`. The manifest is
rejected when the list has duplicates, when the driver is not a Runner
task driver, or when it lists an adapter that has a Paperclip sign-in
and the driver does not declare the login pseudo-terminal with
`creationOperationVersion: 1`.
- Core removes a listed adapter when the running worker does not
implement the methods it needs (task methods, and sign-in methods with
credential read-back for file sign-ins). Core logs a warning one time
for each removed adapter.
- `supportsCodexLogin` is replaced by `loginAdapters`, the adapters that
can sign in on that environment. Drivers without `supportedAdapters`
keep the current behaviour: Claude, and Codex when the worker reads back
credentials.
- A new shared sign-in map holds the adapters that Paperclip signs in
and where each sign-in leaves its credential (terminal output or a
file). Manifest validation, server admission, environment presentation,
and the Connections sign-in step use this map. Two hard-coded Claude and
Codex lists are removed.
- Credential read-back accepts any file sign-in key and returns `{ kind:
"auth-file", content }`.
- The plugin task credential `codex-auth-json` becomes `{ type:
"auth-file", provider: "codex" | "grok", content }`.
- A Grok subscription is delivered to plugin tasks as an `auth-file`
credential. A refreshed Grok file returns to the account through the
existing write-back. The write-back record now stores its provider.
- On a driver that lists adapters, Core refuses to save, offer, or
submit a Runner harness that is not on the list. The error is
`agent_runner_unavailable`.
- The SDK README and the plugin environment task and AI connection docs
describe the contract.

## Verification

- `pnpm --filter @paperclipai/server typecheck`, `pnpm --filter
@paperclipai/plugin-sdk typecheck`, and `pnpm --filter @paperclipai/ui
typecheck` pass.
- Targeted server tests pass: plugin environment driver capabilities,
plugin login credential, plugin Runner credentials, plugin task
credential write-back (Codex and Grok, with a provider mismatch case),
environment task runtime submit gating, agent Runner selection, login
environment, login session runtime, device login routes and service,
setup token, login command, and adapter routes.
- Plugin Runner probe and integration tests pass (run from the
repository root).
- Shared tests (77) and plugin SDK tests (129) pass, including the new
manifest validation cases.
- UI AI connection tests (67) pass.
- Not run locally: the full suite (CI runs it), a render test for the
Connections credential step, and an end-to-end route test for computer
device sign-in admission. Unit tests cover that admission.

## Risks

- Breaking change for plugins that use the plugin SDK task credential or
credential read-back. `codex-auth-json` becomes `auth-file`, and the
read-back result kind changes. A plugin must update to the new SDK
shapes in the same release.
- Plugins that do not declare `supportedAdapters` keep the current
behaviour. No warning is logged for them.
- `supportedAdapters` applies to Runner task drivers only. Sandbox
providers reject the field. Support for sandbox providers is a separate
change.
- The new-agent screen does not offer sign-in on a plugin computer. That
sign-in needs a target computer, and the Connections flow selects it.
This is the current behaviour for Claude and Codex.
- No migration. The write-back record treats a missing provider as
Codex, so records written before this change still work.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use
(shell, file edits, test runs) 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>
Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-12-01 08:13:39 -08:00
36c2ad39c8 feat(runner): seed ACPX file credentials from a host file (#22843)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The Paperclip Runner runs ACPX agents, such as Codex and Grok, in an
isolated provider home for each session
> - The Runner seeds that home only from an inline credential secret, so
a host that keeps the login in a file it owns must copy it into a
variable for every session
> - The credential observer now writes refreshes back to a named host
file (#23340), so a session should also start from that file
> - This pull request seeds the isolated home from
`PAPERCLIP_ACPX_AUTH_JSON_FILE` and documents the host contract
> - The benefit is that a host can keep one login file per account
across sessions without giving the provider access to the host's
directory

## Linked Issues or Issue Description

**Subsystem affected**

Paperclip Runner ACPX credential staging, the Runner environment
boundary (runnerd and the Rust sidecar transport), and Core's server
environment handling.

**Problem or motivation**

An ACPX Codex or Grok session always stages its `auth.json` into the
Runner's isolated home from
`PAPERCLIP_ACPX_{CODEX,GROK}_AUTH_JSON_SECRET`. A host that keeps the
credential in its own file must copy the file into a variable before
each session.

**Proposed solution**

`PAPERCLIP_ACPX_AUTH_JSON_FILE` names an absolute host file. The Runner
validates the file and seeds the isolated home from it; the credential
observer writes refreshes back to it. The provider never sees the host
path.

**Alternatives considered**

Point `GROK_HOME` at the host directory, as
`PAPERCLIP_RUNNER_PREPARED_HARNESS_HOME` does for Claude. Rejected: the
Runner writes its permission policy into `GROK_HOME` for every session,
and a shared home would share session history between sessions.

**Roadmap alignment**

None in `ROADMAP.md`; this extends the Runner's existing ACPX credential
staging.

**Additional context**

Builds on #23339 (write-back rules) and #23340 (observer write-back).

## What Changed

- New variable `PAPERCLIP_ACPX_AUTH_JSON_FILE` for ACPX sessions whose
agent uses a file credential (Codex, Grok). Any other agent, a relative
path, or a combination with the inline secret or the provider API key
fails admission.
- Seeding reads the host file with the existing source reader (a regular
file that is not a symlink, owned by the Runner user, with no group or
other access, at most 256 KiB) and checks the Codex or Grok format on
the exact bytes it stages. Seeding copies the file and never writes it.
- The inline-secret and API-key conflicts are checked at both launch
boundaries, runnerd and the Rust sidecar transport, before the
environment is filtered, so a secret the allowlist drops still
conflicts.
- The variable crosses the sidecar boundary only for Codex and Grok and
never reaches the provider. Core's server removes it from Runner
environments and refuses it as an environment binding, so only the
execution host can name a file.
- With a host file, the lease keeps the final `auth.json` as
`auth-refresh.json` when the provider stops, even when admission fails,
and the next lease leaves that file in place. A warm `run.attach` or
idle restart therefore cannot discard a refresh made during shutdown
before the observer writes it back.
- `managedCodexCredentialSourcePath` becomes
`managedCredentialSourcePath` and covers Grok.
- The Runner README documents the contract in a "Host credential file"
section, and the protocol README notes write-back.
- No code comments are added, per CONTRIBUTING.md.

## Verification

- Runner vitest: `credential-file`, `grok-credentials`, `runtime-host`,
`codex-credentials`, `codex-acpx-driver`, `runnerd-codex-transport`,
`durable-prp-control-plane` (830 passed). They cover seeding Codex and
Grok homes from a host file without exposing its path or changing the
host copy; a startup refresh kept for write-back across the next start;
ambiguous, relative and malformed files failing admission; the format
validators; the runnerd boundary's agent and conflict checks; and the
spawn-boundary allowlist.
- Server vitest: `native-session-executor` and `heartbeat-project-env`
(1609 passed, 7 skipped), covering the variable removed from Runner
environments and refused as a binding.
- `cargo test -p paperclip-runner-core --test acpx_sidecar_transport`
for the sidecar boundary (Codex and Grok receive the path, Claude and a
conflicting secret fail closed).
- Runner and server typecheck; `cargo fmt -p paperclip-runner-core --
--check`.
- Tests trimmed while splitting: the runtime host's unsafe-permission
and linked-source cases (the shared reader's own tests cover both) and
its Claude case (runnerd and the sidecar refuse Claude first, with their
own tests).
- Not run locally: clippy, the full Runner workspace tests, and the
release and eviction integration suites. CI runs them.

## Risks

- Both providers rotate refresh tokens, and a rotated token stops
working. Each provider's own coordination stays inside the session's
isolated home, and the Runner does not lock the host file. Copies of one
sign-in share its refresh token wherever they live, so when two copies
refresh separately the later refresh can fail that command or turn, or
the provider can revoke the sign-in and the user signs in again. The
README describes this and leaves the choice of how many sessions share a
sign-in to the host.
- The host directory must let the Runner user create and rename files
beside the host file.
- No migration.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use
(shell, file edits, cargo and vitest runs) 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
- [x] I will address all Greptile and reviewer comments before
requesting merge

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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 15:55:38 +00:00
DottaandPaperclip ea56320e10 feat(board): add headless channels, fenced task queues, paperclipai/sdk, and pc CLI (#23330)
<!-- Write all pull request text in Simplified Technical English
(ASD-STE100): short sentences, one instruction per sentence, simple
approved vocabulary, and the active voice. -->

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Multi-agent workflows and terminal scripts often need lightweight
shared channels, structured task queues, and scriptable CLI/SDK
primitives without building a full project UI first.
> - Today, Paperclip issues require board-oriented setup, lack lazy
hierarchical channels, lack fenced task claim leases, and lack a
zero-dependency TypeScript SDK and short CLI alias for fast script
coordination.
> - Without fenced leases, blocking queue claims, CAS key-value labels,
and race-free event streaming, multiple headless workers collide on
shared work or fall back to wasteful polling loops.
> - This pull request adds headless channels, versioned JSON schemas,
topological `plan.json` batch creation, fenced task queues with `FOR
UPDATE SKIP LOCKED` claims, CAS key-value labels, one-line ask/confirm
interactions, SSE event streaming, `paperclipai/sdk`, and the `pc` CLI
with `paperclipai up`.
> - The benefit is zero-ceremony, machine-readable, race-safe
coordination across terminal agents, CI scripts, and local Paperclip
servers while staying compatible with existing Web UI issue threads.

## Linked Issues or Issue Description

**Subsystem affected**

Cross-cutting (`packages/db`, `packages/shared`, `server/`, `cli/`,
`doc/`, `skills/`)

**Problem or motivation**

Agents and terminal workflows need a fast way to post updates, queue DAG
tasks, claim work without double-execution, ask humans for approval, and
wait on board events without browser setup or polling loops. Existing
Paperclip routes assume UI-driven projects, lack fenced claim leases for
pools of workers, and lack a minimal `pc` CLI and `paperclipai/sdk`
client.

**Proposed solution**

Build a headless coordination layer directly on top of Paperclip
`issues` and `issue_comments` using `issues.scope = 'channel'`:

- **Database & Contracts (`packages/db`, `packages/shared`)**: Add
`0511_pale_kronos.sql` (`issues.scope`) and `0512_stormy_the_hood.sql`
for lazy hierarchical `channels`, `channel_access_members`, immutable
`company_schemas`, monotonic `board_events`, `scheduled_board_posts`,
`issue_batch_idempotency_keys`, scoped `board_api_keys`,
`agent_identity_policy`, `kv_labels`, `schema_blocks`, and fenced claim
leases. Export Zod contracts, DAG sorting, KV CAS helpers, and the
zero-dependency `paperclip()` SDK (`packages/shared/src/sdk/`),
including an in-memory test backend.
- **Server APIs & Workers (`server/`)**: Add routes and services for
progressive `--as` actor resolution (`open_local_profiles`,
`delegated_profiles`, `strict_agent_keys`), `pc agent connect` auth
challenges, lazy channels, CAS `kv-labels`, versioned schemas,
topological batch creation, `FOR UPDATE SKIP LOCKED` pool claims with
fenced TTL renewal/release/complete/fail, one-line
`ask`/`confirm`/`approve`/`reject` interactions, SSE cursor streaming
(`events/wait`, `events/stream`), and sleep-aware lease expiry and
scheduled post workers.
- **CLI, Launcher & Docs (`cli/`, `doc/`, `skills/`)**: Expose the `pc`
binary alias and `paperclipai/sdk` export, add the zero-prompt
`paperclipai up` / `pc up` local launcher, add `pc` commands (`post`,
`reply`, `read`, `channels`, `label`, `tasks`, `ask`, `confirm`,
`approve`, `reject`, `schemas`, `schedule`, `tail`, `wait`, `agent
connect/login`), add documentation (`doc/CHANNELS-AND-QUEUES.md`,
`doc/CLI.md`, `doc/HEADLESS-TUTORIALS.md`), and add
`skills/paperclip-lite/SKILL.md`.

**Alternatives considered**

- **Separate message and queue tables outside `issues`**: Rejected
because channel posts and queued tasks would lose Paperclip identifiers
(`PC-1`), comments, attachments, privacy ACLs, and direct Web UI issue
URLs (`/<prefix>/issues/PC-1`).
- **Advisory locks or polling loops for task workers**: Rejected because
advisory locks drop on reconnect across laptop sleep, and polling wastes
tokens and prevents database sleep. Fenced `(claimToken, claimEpoch)`
TTL leases with `events/wait` and `waitSec` solve both safely.

**Roadmap alignment**

Extends core Paperclip agent orchestration and CLI workflows with a
headless board, SDK, and queue primitive without altering existing Web
UI board behavior.

**Additional context**

This PR builds on the `issues.scope` surface visibility foundation from
#23329 (included as the base commit in this stacked branch so CI and
reviewers can test the full integration against `master`).

## What Changed

- **Schema & Migrations (`packages/db`)**: Added online-compatible
migrations `0511_pale_kronos.sql` and `0512_stormy_the_hood.sql`, schema
definitions (`channels.ts`, `company_schemas.ts`, `headless_board.ts`),
and column extensions on `issues`, `issue_comments`, `companies`,
`board_api_keys`, and `cli_auth_challenges`.
- **Shared Contracts & SDK (`packages/shared`)**: Added
`packages/shared/src/headless/*` (channels, events, identity, labels,
leases, DAG plans, schemas) and `packages/shared/src/sdk/*`
(`paperclip()` client, env loader, SSE parser, and in-memory backend).
- **Server Routes & Services (`server/`)**: Added
`headless-channels-schemas.ts`, `headless-queues-events.ts`,
`headless-identity.ts` routes and supporting services
(`headless-channels.ts`, `headless-common.ts`,
`headless-events-schedules-interactions.ts`, `headless-identity.ts`,
`headless-labels-batch.ts`, `headless-schemas.ts`,
`headless-task-queue.ts`), plus `issues.scope` visibility isolation and
`board-auth.ts` extensions.
- **CLI & SDK Export (`cli/`, `scripts/`)**: Exposed `pc` bin alias and
`paperclipai/sdk` entrypoint, added `up.ts` zero-prompt launcher and
`cli/src/commands/board/*` commands (`post`, `reply`, `read`,
`channels`, `label`, `tasks`, `ask`, `confirm`, `approve`, `reject`,
`schemas`, `schedule`, `tail`, `wait`, `agent`).
- **Docs, Skill & Runner Registry (`doc/`, `skills/`,
`tests/runner-e2e/`)**: Added `doc/CHANNELS-AND-QUEUES.md`,
`doc/CLI.md`, `doc/HEADLESS-TUTORIALS.md`, plan docs,
`skills/paperclip-lite/SKILL.md`, and synchronized
`tests/runner-e2e/source-sdk-public-inputs.json`.

## Verification

- `pnpm --filter @paperclipai/shared build` — passed.
- `pnpm --filter @paperclipai/db check:migrations` — passed
(`0511_pale_kronos.sql` and `0512_stormy_the_hood.sql` verified
online-compatible, 2 new migrations since `630cf0423024`, none blocked).
- `node tests/runner-e2e/source-sdk-public-inputs.mjs $(git rev-parse
HEAD) --check` — passed (`598` inputs, `changed: false`).
- `pnpm exec vitest run --config tests/runner-e2e/vitest.config.ts
tests/runner-e2e/source-sdk-public-inputs.test.mjs` — 13/13 tests
passed.
- `node scripts/check-maps.mjs` — passed (`35` areas, `192` capability
IDs aligned).
- `pnpm exec vitest run packages/shared/src/headless/headless.test.ts
packages/shared/src/sdk/sdk.test.ts
cli/src/__tests__/headless-board-cli.test.ts` — 3 files, 22/22 tests
passed.
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/issue-scope-visibility.test.ts
src/__tests__/headless-channels-schemas-batch.test.ts
src/__tests__/headless-identity-auth.test.ts
src/__tests__/headless-queues-leases-events.test.ts
src/__tests__/headless-e2e-sdk-cli.test.ts` — 5 files, 25/25 tests
passed.
- `pnpm --filter @paperclipai/shared typecheck && pnpm --filter
@paperclipai/db typecheck && pnpm --filter @paperclipai/server typecheck
&& pnpm --filter paperclipai typecheck` — all passed.
- `pnpm --filter paperclipai build` — passed.

## Risks

- **Two new migrations (`0511`, `0512`)**: Both migrations are marked
online-compatible (`NOT VALID` constraints validated afterwards,
`CONCURRENTLY` index creation, idempotent statements for
non-transactional execution) and checked by `check:migrations`. If
#23329 lands separately with `0511` modified or renumbered, this branch
will rebase on top cleanly.
- **Large surface area (91 files)**: Changes are primarily additive new
modules (`headless-*`, `cli/src/commands/board/*`,
`packages/shared/src/headless/*`, `packages/shared/src/sdk/*`); existing
Web UI board behavior remains isolated via `issues.scope`.
- **Full repository Vitest suite**: Only the targeted headless, SDK,
CLI, server, and runner-e2e pin suites ran locally after rebasing; full
cross-package CI checks will validate the remaining suite.

## Model Used

- Google DeepMind Antigravity (Gemini coding 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
- [ ] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-12-01 08:12:19 -06:00
6678554a5a fix(heartbeat): retry setup when project storage is still being prepared (#23362)
## 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.
> - A provider can answer a polled preparation with the closed reason
`storage_pending`. This means that the project's storage is still being
prepared. The provider gives this answer before any workspace effect.
> - Setup recorded this answer as a generic `setup_failed`. It scheduled
no retry. The task waited for a person to press Retry, and Sentry
received an error for each attempt.
> - This pull request gives the answer its own transient setup code,
`workspace_storage_pending`. Setup then retries the same workspace
within the bounded bootstrap budget.
> - The benefit is that a task continues by itself when the project's
storage becomes ready, and Sentry gets a report only when no retry owns
recovery.

## Linked Issues or Issue Description

Refs #19249 (the same retry for a stopped plugin worker)
Refs #21510 (the same deferred Sentry report for a saved-sandbox resume
outage)

**What happened?**
On staging, runs failed in the preparing stage with "Project storage is
still being prepared; retry the same workspace shortly". Each run waited
about 3.5 minutes in the polled preparation. Then the provider answered
`storage_pending`. The run got `setup_failed` with
`workspaceProviderFailure: { kind: "provider", reason:
"storage_pending", retryable: true }` and `executionRecovery: { kind:
"bootstrap", providerWorkStarted: false }`. No retry was scheduled. A
person pressed Retry several times, and each attempt sent a new Sentry
error.

**Expected behavior**
No workspace effect or provider work started, and the provider marks the
reason retryable. The run must retry within the bounded bootstrap
budget, as it does for `plugin_worker_unavailable`. Sentry must get a
report only when no retry is scheduled.

**Steps to reproduce**
1. Use a project whose workspace storage is still being provisioned.
2. Wake an agent whose legacy run prepares a workspace through that
provider.
3. The provider answers `storage_pending` at the end of its wait. The
run fails with `setup_failed`. No retry is scheduled.

**Paperclip version or commit**
master at 7ce7d99f8a.

## What Changed

- `workspace-provider-failure.ts`: add `WORKSPACE_STORAGE_PENDING_CODE`
(`workspace_storage_pending`) and `findWorkspaceStoragePendingFailure`.
The finder matches only a provider answer with the closed reason
`storage_pending`.
- `run-completion.ts`: map that answer to `workspace_storage_pending`.
Do this only before provider dispatch and only for a legacy run with no
native session or runner instance. These are the same guards as for the
sibling transient codes.
- `failed-preparation-retry.ts`: add the code to the transient
preparation codes, so setup schedules the bounded bootstrap retry. An
accepted interaction keeps its own continuation retry, as for the
sibling codes.
- Retry, legacy recovery, recovery service and telemetry: treat the code
like the other bootstrap-only transient codes. The stranded-task notice
has a title and a next action for it.
- `run-failure-report.ts`: wait for the retry decision before the Sentry
report (`workspaceStoragePendingRetry`), with the same handshake as
`sandboxResumeRetry`. A scheduled retry is not reported. An unscheduled
or exhausted retry is reported.
- Other retryable provider reasons (`remote_incomplete`,
`context_changed`, `deadline_exceeded`) do not change. These reasons can
follow a started effect, so they keep `setup_failed`.

## Verification

- Red: the new `run-completion` test failed on the unchanged code. A
fresh `storage_pending` answer got `setup_failed`, the same code that
staging recorded.
- Green: the same test passes. A fresh answer gets
`workspace_storage_pending`, `providerWorkStarted: false` and a bounded
retry. A started or native run keeps `setup_failed` and gets no retry.
Provider text does not reach the run.
- New test: `remote_incomplete`, `context_changed` and
`deadline_exceeded` answers keep `setup_failed` and get no retry.
- New report tests: a pending or scheduled decision sends no Sentry
report. An unscheduled decision, an unknown decision, `all` mode, and
another error code are reported once, without provider text.
- `heartbeat-retry-scheduling`: the new code is bounded across a restart
and honors resume, pause, Stop and a blocking dependency.
- `vitest run src/services/heartbeat/run-completion.test.ts
src/services/__tests__/run-failure-report-sandbox-resume.test.ts`: 190
passed.
- `vitest run src/__tests__/heartbeat-retry-scheduling.test.ts -t
"bootstrap retries across restart"`: 20 passed.
- `vitest run src/__tests__/workspace-provider-failure.test.ts
src/__tests__/agent-task-run-telemetry.test.ts`: 61 passed.
- Review fix: the escalated `workspace_storage_pending` notice no longer
says that Paperclip retried automatically, because recovery can show it
when no retry was scheduled. A new notice test failed on the old wording
and passes now (`workspace-provider-failure.test.ts`: 7 passed).
- `PAPERCLIP_TYPECHECK_LOW_MEMORY=1 pnpm --filter @paperclipai/server
typecheck`: all seven layers pass. (A single-program `tsc -p server` run
was stopped by the memory limit of the local machine; the layered check
is the documented low-memory path.)

## Risks

- Low risk. The retry uses the existing bounded bootstrap budget (two
retries). When the budget is exhausted, the existing board recovery
action takes over and Sentry gets the report.
- The retry applies only before provider dispatch on a legacy run. A
native run or a started run keeps the old behavior.
- A wrapper that drops the error `cause` keeps the old `setup_failed`
behavior. It does not cause a wrong retry.
- Project storage that never becomes ready still needs a fix in the
provider. This change only stops a short wait from needing a person.

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

## Model Used

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

## Checklist

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

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

---------

Co-authored-by: devinfoley <139239+devinfoley@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 10:20:56 +00:00
b3fd921cfb test(browser-use): keep the capture-month rollover test ahead of the database clock (#23363)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Agents can use Browser Use Cloud. Paperclip records its usage cost
in the cost ledger and the monthly budget.
> - A server test checks that a usage change after a UTC month rollover
goes into the correct month. The test uses a fixed fake clock:
2026-11-30T23:59:59.900Z, then 2026-12-01T00:00:00.100Z.
> - Browser Use sessions get `next_poll_at` from the database `now()`.
The poll compares that value with the fake JavaScript clock.
> - After the real time passed 2026-11-30T23:59:59.900Z, the fake clock
was behind the database clock. The poll did not select the session, so
the test failed.
> - The test fails on every `master` commit since 2026-12-01. The
post-merge Cloud readiness check fails, the Core Docker image build
stops, and staging cannot get new Core commits.
> - This pull request calculates the rollover from the next UTC month
boundary after the real time. The fake clock is always ahead of the
database clock again.
> - The benefit is that `master` image builds and staging deploys can
continue. The test still checks the same month rollover.

## Linked Issues or Issue Description

**What happened?**
`server/src/__tests__/browser-use-connection.test.ts` > "dates a new
cumulative delta in its capture month and keeps that receipt's retry
time stable" fails on current `master`. The error is `expected { …(15) }
to match object { eventsDrained: +0, result: { …(1) } }`. The budget
hold shows `amountCents: "0.0000000"` and has no `accountedCentsExact`
or `receipt`, so the first usage report (0.15 USD) was not accounted.

**Expected behavior**
The test passes on any date. A test with a fake clock must not depend on
the real date.

**Steps to reproduce**
1. Check out `master` (for example 743c18f3b2) on or after 2026-12-01.
2. Run `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/browser-use-connection.test.ts -t "capture month"`.
3. See the test fail.

**Paperclip version or commit**
`master` at 743c18f3b2. The last green Core image build was fb6632530d
(2026-11-30T23:13Z).

## What Changed

- `server/src/__tests__/browser-use-connection.test.ts`: calculate
`before`, `after` and the later retry time from the next UTC month
boundary after the real time plus one day. Do not use fixed 2026 dates.
The test still crosses a UTC month boundary, and the assertions do not
change.

## Verification

- Red: on `master` (743c18f3b2), `pnpm --filter @paperclipai/server exec
vitest run src/__tests__/browser-use-connection.test.ts -t "capture
month"` fails with the error above.
- Green: with this change, `pnpm --filter @paperclipai/server exec
vitest run src/__tests__/browser-use-connection.test.ts` passes, 65/65.
- No product code changes.

## Risks

- Low risk. The change is in one test only. The test checks the same
rollover behavior at a later month boundary.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`) through Claude Code, with tool use
(shell, git, 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
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

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

Co-authored-by: devinfoley <139239+devinfoley@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 09:54:48 +00:00
acb52955b7 fix(issues): lock the issue before the run when adopting an unowned checkout (#23355)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Agents change tasks through the issue routes. Before each change,
the server checks that the agent's run owns the task's checkout
(`assertCheckoutOwner`).
> - This check clears terminal run locks and can adopt a checkout. Each
step uses a short transaction that locks rows.
> - The clears and the stale adoption lock the issue first and then the
heartbeat run. The unowned-checkout adoption locked the run first and
then updated the issue.
> - Two requests for the same task can then wait on each other.
PostgreSQL stops one with `deadlock detected`, and the agent's change
fails with a 500.
> - This pull request makes the unowned-checkout adoption lock the issue
before the run.
> - The benefit is one lock order (issue, then run) in all checkout
ownership paths. Concurrent requests now wait in turn and do not
deadlock.

## Linked Issues or Issue Description

**What happened?**
A hosted staging server reported `Error: Failed query: select
"heartbeat_runs"."id" from "heartbeat_runs" where "heartbeat_runs"."id"
= $1 for update`. The chained cause was `PostgresError: deadlock
detected` (40P01). The stack was `assertAgentIssueMutationAllowed` →
`assertCheckoutOwner` → a transaction that locks a heartbeat run.

**Steps to reproduce**
1. Make an `in_progress` task with an agent assignee, no
`checkoutRunId`, and a live `executionRunId` (run A).
2. Run A calls an issue mutation. `assertCheckoutOwner` adopts the
unowned checkout: it locks run A, then updates the issue.
3. At the same time, another run of the same agent (run B) calls an
issue mutation. `clearExecutionRunIfTerminal` locks the issue, then
waits for run A.
4. PostgreSQL detects the cycle and stops run B's request.

**Expected behavior**
Run A adopts the checkout. Run B gets an ordinary 409 ownership
conflict.

**Actual behavior**
Run B's request fails with a 500 that wraps `deadlock detected`.

No public GitHub issue exists. Related earlier work: #5413 and #4258
(they added the adoption paths). No open PR fixes this deadlock.

## What Changed

- `adoptUnownedCheckoutRun` in `server/src/services/issues.ts` now locks
the issue row (`FOR UPDATE`) before it locks the actor's heartbeat run.
This is the same order that `clearExecutionRunIfTerminal`,
`clearCheckoutRunIfTerminal`, and `adoptStaleCheckoutRun` use.
- New test
`server/src/__tests__/issue-checkout-adoption-lock-order.test.ts`. It
pauses the adoption inside its transaction, starts a concurrent
ownership check from a second run, and expects no deadlock.

## Verification

- Red: without the fix, the new test fails. The second request rejects
with `PostgresError 40P01 deadlock detected` on `select
"heartbeat_runs"."id" ... for update`. This is the same error that
Sentry reported.
- Green: with the fix, the new test passes. Run A adopts the checkout,
and run B gets a 409.
- `npx vitest run
src/__tests__/issue-checkout-adoption-lock-order.test.ts` (server): 1
passed.
- `npx vitest run src/__tests__/issues-service.test.ts -t
"checkout|adopt|ownership"` (server): 14 passed.

## Risks

- Low risk. The adoption transaction now also takes the issue row lock.
The transaction then updates the same row, so it already needed this
lock. The only change is the order of the locks.
- No schema, API, or UI change.

## Model Used

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

## Checklist

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

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

---------

Co-authored-by: devinfoley <139239+devinfoley@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 09:30:46 +00:00
e67009db3f fix(voice): let board incoming-call requests wait for membership locks (#23353)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Voice connections (Speko) let a board user approve incoming phone
calls and see call history in the board UI
> - The incoming-call panel polls `GET
/companies/:companyId/voice-phone/:endpointId/incoming` every two
seconds
> - The inbound voice service checks the caller's company membership
with a `FOR SHARE NOWAIT` lock on every request, including these board
requests
> - When another transaction holds that membership row, the poll fails
with Postgres error `55P03` and the error handler returns a 500 and
reports it to Sentry
> - This pull request makes the board routes wait for the row lock, like
the other board voice routes do, and keeps `NOWAIT` for provider
callbacks
> - The benefit is that ordinary lock contention no longer causes 500
responses or Sentry noise for board users

## Linked Issues or Issue Description

No public issue exists. This is the problem description.

**What happened?**
On staging, board requests to the voice incoming-call routes failed with
`Failed query: select "id" from "company_memberships" ... for share
nowait`, caused by `PostgresError: could not obtain lock on row in
relation "company_memberships"` (`55P03`). The culprit frame is
`authorizeCaller` in `voice-session-store.ts`. Sentry recorded 32 events
in one day, all on staging.

**Expected behavior**
A board request waits for a short row lock that another transaction
holds, and then returns its normal result. A concurrent membership
change must not cause a 500.

**Steps to reproduce**
1. Open a transaction that locks the caller's `company_memberships` row
(`FOR NO KEY UPDATE`).
2. While the lock is held, call the inbound voice `list` or `decide`
service method for that caller.
3. The call fails immediately with `55P03`.

**Relevant logs or output**
`Error: Failed query: select "id" from "company_memberships" where (...
"membership_role" is distinct from 'viewer') for share nowait` caused by
`PostgresError: could not obtain lock on row in relation
"company_memberships"`.

## What Changed

- `server/src/services/voice/voice-inbound-service.ts`: add a second
session store, `boardStore`, without `nonblockingAuthority`. The board
routes (`configuration`/`saveConfiguration` through `manager`, `list`,
`history`, and `decide`) use it. The provider callback and tool paths
(`lifecycle`, `pendingTool`, `authorizeGuest`) keep the `NOWAIT` store.
- `server/src/__tests__/voice-session-store.integration.test.ts`: add a
regression test. It holds the caller's membership row lock, calls `list`
and `decide`, checks that both wait on the lock, releases the lock, and
checks that both succeed.

## Verification

- Red: with the service change stashed, the new test failed. Both
requests rejected with `55P03` (`for share nowait`), which is the same
error as in Sentry.
- Green: `cd server && npx vitest run
src/__tests__/voice-session-store.integration.test.ts` passes all 135
tests, the new test included.
- `cd server && pnpm typecheck` passes.

## Risks

- Low risk. Board voice requests can now wait for a row lock instead of
failing at once. This matches `voice-session-service`, which already
uses ordinary share locks for board routes. Each board transaction takes
the membership lock as its first statement, so this change adds no new
lock-order cycle.
- Provider callbacks keep their fail-fast behavior.

## Model Used

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

## Checklist

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

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

Co-authored-by: devinfoley <139239+devinfoley@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 08:28:04 +00:00
5abce3b492 fix(tool-access): keep OAuth redirect-policy refusals out of Sentry (#23349)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - People connect remote MCP servers to Paperclip. Many of these
servers use OAuth with dynamic client registration (RFC 7591).
> - Some authorization servers refuse Paperclip's callback URL with HTTP
400 `invalid_redirect_uri`. They do this because of their own redirect
policy, for example an allowlist of approved clients or an HTTPS rule.
> - Paperclip only sends a callback URL that it builds from a configured
or trusted origin. Paperclip cannot change the provider's answer. The
person already gets a 502 with remediation text: ask the provider to
allowlist the callback URL, or enter a client ID.
> - #22416 kept all registration 400s in Sentry on purpose, because some
400s (`invalid_client_metadata`, unknown codes) can show that Paperclip
sent bad metadata. Thus each provider redirect-policy refusal still
makes a Sentry crash report.
> - This pull request stops the Sentry report only for a registration
400 with `invalid_redirect_uri`. All other registration failures that
#22416 reports stay reported.
> - The benefit is that Sentry shows Paperclip faults, not expected
provider policy decisions. The person sees the same error and guidance
as before.

## Linked Issues or Issue Description

Refs #22416

**What happened?**
A remote MCP authorization server answered Paperclip's dynamic client
registration with HTTP 400 and the OAuth error `invalid_redirect_uri`.
Paperclip correctly answered the person with a 502 and the message "The
authorization server rejected Paperclip's callback URL." But the error
handler also sent the error to Sentry as a server crash. One production
event was recorded with the tags
`oauth_operation=dynamic_client_registration`,
`oauth_provider_status=400` and
`oauth_provider_error=invalid_redirect_uri`.

**Expected behavior**
A provider's redirect-policy refusal is an expected external failure.
Paperclip must answer with the same 502 and remediation, and must not
report a crash to Sentry. Registration failures that can show a
Paperclip fault must stay reported.

**Steps to reproduce**
1. Connect a generic MCP server whose registration endpoint answers `400
{"error":"invalid_redirect_uri"}`.
2. Start the browser sign-in.
3. See the 502 with the callback-URL guidance, and see a new Sentry
event for the same request.

**Paperclip version or commit**
master at 66a8aa7f7e.

## What Changed

-
`server/src/services/tool-access/oauth/provider-failure-diagnostics.ts`:
add `isExpectedOAuthProviderFailure(error)`. It is true only when the
recorded diagnostics show `dynamic_client_registration`, HTTP status 400
and provider error `invalid_redirect_uri`.
- `server/src/middleware/error-handler.ts`: do not send that error to
Sentry. The HTTP response does not change.
- `server/src/__tests__/oauth-dcr-failure-reporting.test.ts`: add a test
that a 400 `invalid_redirect_uri` gives the same 502 body and no crash
report. Add tests that a 422 `invalid_redirect_uri`, a 400 with an
unknown code and a 400 with no code are still reported.

## Verification

- Red: with only the new tests, `pnpm --filter @paperclipai/server exec
vitest run src/__tests__/oauth-dcr-failure-reporting.test.ts` fails. The
400 `invalid_redirect_uri` case calls `captureException` one time.
- Green: with the fix, the same command passes.
- `src/__tests__/sentry-oauth-provider-failure.test.ts` and
`src/__tests__/error-handler.test.ts` also pass.
- CI runs the full typecheck, build and test suite for this head.
- After the review fix (a9211af9ca, code comments removed, no behavior
change): `oauth-dcr-failure-reporting`, `sentry-oauth-provider-failure`,
`error-handler`, `error-handler-client-abort` and
`error-handler-tool-gateway` tests pass, 38/38.

## Risks

- Low risk. The change affects only Sentry reporting for one exact case:
a registration 400 with `invalid_redirect_uri` that Paperclip itself
recorded on the error. The HTTP status, message, code and details do not
change.
- If Paperclip someday sends a bad callback URL, this case is no longer
visible in Sentry. The callback URL is built only from configured or
trusted origins, and an unsupported origin fails before the request
(`oauth_redirect_origin_unsupported`), so this risk is small.

## Model Used

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

## Checklist

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

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

---------

Co-authored-by: devinfoley <139239+devinfoley@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 07:11:17 +00:00
DottaandPaperclip c737187ec7 fix(lifecycle): classify native hello timeouts (#18216)
## Thinking Path

> - Paperclip verifies an agent's execution setup before it becomes
ready.
> - Native hello probes return a structured environment-test check.
> - A timeout uses the check suffix `_hello_probe_timeout`.
> - The lifecycle mapper only recognized the older
`_hello_probe_timed_out` spelling.
> - It therefore reported a native timeout as a generic test failure.
> - This change maps both spellings to the existing timeout category.
> - Operators receive the existing fixed timeout guidance without
provider output.

## Linked Issues or Issue Description

**What happened?**

On current main, `testNativeRunnerAuthentication` emits
`codex_hello_probe_timeout`. `assertHarnessTestPassed` classified it as
`harness_test_failed` instead of `harness_probe_timed_out`. The OpenCode
spelling in the unit table checks the generic suffix contract. It does
not add or qualify a native OpenCode producer on current main.

**Expected behavior**

Recognize the native producer's timeout code. Keep the existing timeout
category, legacy spelling, and fixed error text.

**Steps to reproduce**

Pass a failed environment result with the source-defined Codex timeout
code to `assertHarnessTestPassed`. The added owner controls fail before
the mapping change and pass afterward.

The related open #16652 changes a legacy Claude probe timeout and UI
behavior. It does not change this mapper.

## What Changed

- Accept `_hello_probe_timeout` beside the existing
`_hello_probe_timed_out` suffix.
- Cover the actual Codex producer spelling, the forward-compatible
OpenCode spelling, and a lookalike suffix that must remain a generic
failure.
- Retain existing authentication, model, command, directory,
unexpected-output and success handling.

## Verification

- The real owner unit suite produced **2 failing timeout cases and 25
passing controls** before the fix. The same suite passes **all 27
controls** after the fix under a focused local source-alias
configuration.
- Standard owning command: `pnpm --filter @paperclipai/server exec
vitest run src/__tests__/agent-harness-verification.test.ts`.
- Local scoped noEmit did not pass. Reused local dependency links
produced ambient Express declarations, missing `tar-stream`, and
mixed-source type errors. The initial load and typecheck failures are
preserved. Normal remote CI must supply the final typecheck and build
evidence.
- `git diff --check` passes. The diff contains only the mapper and its
existing unit test.
- Exact-head normal CI passed on `db56f63`: 55 successful checks, two
skipped checks and one neutral review check. Required `ci / verify`, `ci
/ e2e` and `ci / Build` passed. Greptile and the Paperclip reviewer both
report 5/5 with no findings or open threads. No CI rerun was needed.
Local noEmit setup remains a recorded limitation.
- Native probes, model calls, databases, application builds and
end-to-end journeys were not run locally. This source regression does
not establish the cause of any recorded evaluation failure.

## Risks

Low scope. The existing closed failure category changes for the native
timeout spelling. A string that only contains that suffix in the middle
still maps to generic failure. Authentication keeps priority. Failure
text stays fixed. This change preserves lifecycle ownership, deferral,
retry limits and deadlines.

## Model Used

OpenAI GPT-6 through Codex, with source analysis and pure unit tests.
The exact serving model ID and context-window size are not exposed to
this worker.

## Checklist

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

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-12-01 04:00:56 +00:00
DottaandPaperclip 66a8aa7f7e feat(issues): add issues.scope surface visibility foundation (#23329)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Issues currently store human board tasks, agent-created operational
tasks, and persistent 1:1 Agent Chats in the same `issues` table.
> - Default board lists, counts, and Mine views previously relied on
ad-hoc creator and origin predicates to hide chats and separate agent
tasks.
> - Upcoming headless channels also need a clean way to isolate channel
issues from default board lists without inventing a separate task
entity.
> - This pull request adds an explicit `issues.scope` column (`board`,
`channel`, `agent`, `chat`) across the schema, shared types, service
filters, client filters, and issue routes.
> - The benefit is unified surface visibility filtering and explicit
scope derivation while keeping rolling deploys safe and preserving
existing Agent Chat and board behavior.

## Linked Issues or Issue Description

**Subsystem affected**

Cross-cutting (`packages/db`, `packages/shared`, `server/` REST API &
orchestration services, `ui/` client filters, and `docs/api/issues.md`).

**Problem or motivation**

Paperclip uses the `issues` table for human board work, automated or
agent-created operational work, and persistent 1:1 Agent Chats. Without
a dedicated surface-scope column, list, count, and Mine queries depend
on `conversationAgentId`, `createdByAgentId`, and `originKind` checks,
and there is no first-class way to isolate channel streams from default
board views.

**Proposed solution**

Add an `issues.scope` column (`board` | `channel` | `agent` | `chat`)
with `issues_scope_check` and composite indexes, expose `scope` in
shared types and Zod validators, derive default scope on issue creation
and batch imports, protect `chat` scope on 1:1 conversations and block
unauthorized agent `scope: "board"` writes across routes and
`issueService`, update server visibility queries and `applyIssueFilters`
on the client to honor `scope`, add `scope` filtering on `GET
/api/companies/:companyId/issues` and `/count`, and document the new
parameter in `docs/api/issues.md`.

**Alternatives considered**

1. Create separate tables for chats and channels. We ruled this out
because Paperclip builds assignment, comments, approvals, and execution
around a single `issues` model.
2. Add a DB `CHECK ((conversation_agent_id IS NULL) OR (scope =
'chat'))` constraint in this expand migration. We ruled this out for the
initial rollout because `ADD CONSTRAINT ... NOT VALID` still enforces
checks on new writes from older server instances that omit `scope`
during a rolling deploy.
3. Continue filtering only by `originKind` and `conversationAgentId` at
query time. We ruled this out because it cannot distinguish an explicit
chat-to-board handoff from a background agent task.

**Roadmap alignment**

Supports the **Agent Chat (including CEO Chat)** and **Work Queues** /
channel-intake directions in `ROADMAP.md` by separating surface
visibility on the shared `issues` table.

**Additional context**

This PR introduces the expand-phase schema, shared contract,
service-layer derivation, client filter handling, API filter foundation,
and API documentation. Follow-up work will build channel UI surfaces on
`issues.scope` and add the contract-phase DB check constraint after
older writers drain and re-backfill any rolling-deploy conversation
rows.

## What Changed

- Added `scope` (`board` | `channel` | `agent` | `chat`, default
`board`) to `packages/db/src/schema/issues.ts` with
`issues_scope_check`, `issues_company_scope_status_idx`, and
`issues_company_scope_updated_idx`.
- Added online-compatible migration
`packages/db/src/migrations/0511_simple_the_hunter.sql` (plus updated
Drizzle snapshot/journal and `MIGRATIONS_WITH_TOP_LEVEL_STATEMENTS`
entry in `packages/db/src/client.ts`) to backfill existing `chat` and
`agent` rows in bounded 1,000-row primary-key cursor batches matching
`isAgentCreatedIssue`, validate `issues_scope_check` with `NOT VALID` +
`VALIDATE CONSTRAINT`, and build indexes `CONCURRENTLY`.
- Exported `ISSUE_SCOPES`, `IssueScope`, and `deriveDefaultIssueScope`
in `packages/shared`, added `scope?: IssueScope` to `Issue` and
`CompactIssue`, and added optional `scope` validation to
`createIssueSchema` and `updateIssueSchema`.
- Extracted `parseScopeFilter` and `surfaceScopeCondition` in
`server/src/services/issue-visibility.ts`, and updated `issueService`
(`create`, `importIssues`, `update`, `list`, `count`, blocked inbox
counts, and Mine views) to derive default scope (including `scope:
"agent"` for creatorless imports), enforce `chat` scope on 1:1
conversations, reject `scope: "chat"` on non-conversation issues, reject
unauthorized agent `scope: "board"` creation without handoff provenance,
default chat-to-board handoffs to `board`, preserve
`nonIdleSlackIssueCondition` on non-chat/channel scope filters, let
explicit `scope` filters override `includeAgentCreatedTasks=false`, and
exclude `chat` and `channel` rows from default board queries unless
filtered by `scope`, `q`, or `issueIds`.
- Updated `applyIssueFilters` (`isBoardVisibleByDefault`) in
`ui/src/lib/issue-filters.ts` so agent-created tasks with `scope:
"board"` (such as chat-to-board handoffs) stay visible by default.
- Added `scope` query parsing (`parseIssueListScopeQueryParam`
delegating to `parseScopeFilter`) and `assertActorMayWriteIssueScope`
across `POST /companies/:companyId/issues`, `POST /issues/:id/children`,
`POST /issues/:id/accepted-plan-decompositions`, and `PATCH /issues/:id`
in `server/src/routes/issues.ts`, included `scope` in `toCompactIssue`,
and documented `scope` in `docs/api/issues.md`.
- Added tests in `server/src/__tests__/issue-scope-visibility.test.ts`
and `ui/src/lib/issue-filters.test.ts`, updated
`server/src/__tests__/fixtures/issue-detail-response.json` and
`server/src/__tests__/issues-creation-visibility.test.ts`, and refreshed
`tests/runner-e2e/source-sdk-public-inputs.json`.

## Verification

- `pnpm --filter @paperclipai/db typecheck` (`check:migrations` + `tsc
--noEmit`), `pnpm --filter @paperclipai/shared typecheck`, and `pnpm
--filter @paperclipai/server typecheck` — passed on
`3db819854ff28ebc5e875b8d9d0daa74055bef35`.
- `npx vitest run packages/db/src/migration-snapshot-drift.test.ts
server/src/__tests__/issue-scope-visibility.test.ts
server/src/__tests__/issues-creation-visibility.test.ts
server/src/__tests__/company-portability-import-batching.test.ts
ui/src/lib/issue-filters.test.ts` — 5 files, 51 tests passed (1
pre-existing skip in `company-portability-import-batching.test.ts`).
- `node tests/runner-e2e/source-sdk-public-inputs.mjs
3db819854f --check` — exited 0
(`"changed":false`).
- Full CI + security/review checks passed on
`3db819854ff28ebc5e875b8d9d0daa74055bef35` (88/88 check runs completed
with 0 failures; `mergeable: MERGEABLE`, `mergeStateStatus: CLEAN`;
Greptile `5/5` with 0 unresolved threads).

## Risks

- Migration `0511_simple_the_hunter.sql` runs outside a transaction
(`MIGRATIONS_WITH_TOP_LEVEL_STATEMENTS`) because it commits bounded
1,000-row primary-key cursor backfill batches and builds indexes with
`CREATE INDEX CONCURRENTLY`. All statements are idempotent, and
`issues_scope_check` uses `NOT VALID` followed by `VALIDATE CONSTRAINT`.
- The DB-level `conversation_agent_id -> scope = 'chat'` check
constraint is deferred to a follow-up contract migration (which must
re-run the bounded `scope = 'chat'` backfill before adding/validating
the constraint) so rolling deploys with previous writers do not fail 1:1
chat inserts; `issueService.create` and `issueService.update` enforce
this invariant in application code, and
`nonChatAndChannelIssueCondition()` continues checking
`isNull(issues.conversationAgentId)`.
- Behavioral shift: `GET /api/companies/:companyId/issues` and
blocked/Mine aggregations now isolate `scope = 'channel'` and `scope =
'chat'` from default board views unless `scope`, `q`, or `issueIds` is
explicitly passed.

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

## Model Used

- Google DeepMind Antigravity (Gemini coding agent) with tool use and
code execution.

## Checklist

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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-30 19:57:23 -06:00
Devin FoleyandPaperclip 158613ef81 Permit idle sleep with proved passive remote workspaces (#23335)
## Thinking Path

> - Paperclip runs agent work and retains its files after a run ends.
> - Remote workspaces save those files in a durable archive.
> - The idle inventory still treats every remote workspace row as active
work.
> - A saved archive or an unused setup reservation can then keep an idle
instance awake.
> - This PR adds a read-only proof in the remote workspace owner and
uses it in the existing idle check.
> - The proof keeps active work and uncertain recovery awake and
preserves all retained data.

## Linked Issues or Issue Description

**What happened?**

A retained `cloud_sandbox` workspace blocks idle sleep after its archive
commits and its allocation is released. The passive workspace check only
accepts local directories and git worktrees. An unused reservation can
also remain after a bootstrap failure that started no provider work.

**Expected behavior**

An idle instance can sleep when existing receipts prove that its remote
files are saved or that a setup reservation was never used. Missing,
foreign, contradictory, and unfinished state must keep blocking sleep.

**Steps to reproduce**

1. Save a remote workspace and finish its snapshot operation.
2. Release its allocation with the matching stop receipt, or retain no
allocation.
3. Keep the workspace row and inspect idle safety. Before this change,
the row still reports work.

Related: remote workspace storage in #18403. No duplicate open
sleep/workspace PR was found.

## What Changed

- Add a pure SQL proof for a committed, scoped archive and its completed
source operation. Require the stored encryption scheme and correctly
shaped IV, tag, and ciphertext. An unchanged save can reuse an older
snapshot.
- Require exact release evidence for a retained location and every
allocation of an unused reservation. Unused reservations require an
ended legacy bootstrap, an explicit no-provider-work result, no live
controller or retry, and no native finalization. A pristine reservation
cannot carry retained recovery-file references.
- Apply that proof through the existing passive workspace check. Keep
runtime configuration, commands, due cleanup, reopen fences, and every
independent run, lease, and recovery check.
- Add PostgreSQL regression cases and describe the proof in the
idle-safety documentation. The existing shared database fixture keeps
the tests in one suite instead of adding another database startup.
- Correct two pre-existing receipt browser assertions uncovered by
required CI. Plain comments have supported keyed retries since October
28; the older tests assumed one POST even when receipt reads lose the
race to backoff. Assert exact request identity and payload across
retries, one saved comment, and preservation of the next draft.

## Verification

- Receipt CI follow-up, Node 25.6.1 on macOS: the full
`board-attachment-receipts.spec.ts` passed twice with four Chromium
workers (28/28). Both corrected cases passed with delayed issue reads
after reproducing both old failures under the same delay. `node
scripts/typecheck-test-projects.mjs --reuse-declarations tests/e2e` and
the focused test-budget check passed. Only browser assertions changed
after the 323-test server verification.
- Node 25.6.1 on macOS: `pnpm --filter @paperclipai/server typecheck`
passed.
- Final revision: `pnpm exec vitest run
server/src/__tests__/idle-sleep-safety.test.ts
server/src/__tests__/idle-sleep-diagnostics.test.ts`: 323 passed. Both
suites used real embedded PostgreSQL. An earlier run also selected the
remote-workspace lifecycle suite; its 16 cases were skipped because its
external test database was not configured.
- Red-green: the new saved-workspace regression failed before the first
proof. Both unused-reservation cases failed before that proof was added.
The focused regressions passed after the changes. Empty key material and
a foreign allocation bound to an unused writer were also reproduced
red-green during review.
- `pnpm verify --explain` returned the documented exit 2 because the
documentation path requires broader CI. Required CI will supply that
coverage; a full local repository run was not substituted.
- After rebasing onto current `master`, the focused passive-state tests
and server typecheck passed again.
- `git diff --check` and a staged secret/PII scan passed.
- The previous revision (`078e60f`) received Greptile 5/5 with its
key-format thread resolved. [Initial
CI](https://github.com/paperclipai/paperclip/actions/runs/46536659729)
failed in a Rust executable fixture (`ExecutableFileBusy`) and a browser
receipt assertion. The targeted rerun passed Rust but failed the
companion receipt test. Both browser assertions expected one POST,
contrary to the documented keyed retry contract. A scratch fault fixture
delaying issue reads by 1.6 seconds reproduced both old failures
(`Expected: 1 / Received: 2`); both revised cases passed under the same
delay. The delay fixture is kept outside the branch. Final head
`97269b3420387b28fda5f35f69a6b9ed45d5bb54` is merge-ready: all required
gates passed, 81 checks succeeded and four were skipped by workflow
policy, Greptile is 5/5 on this head, and the one review thread is
resolved. GitHub reports `MERGEABLE` / `CLEAN`. The skipped
external-database local cases and earlier failed attempts remain
recorded above.
- No provider suspension, external wake, deployment, or cost-saving
result is claimed from these local checks. The proof adds no provider
call, recurring scan, or extra database round trip. It runs within the
existing bounded, read-only snapshot.

## Risks

This expands automatic sleep eligibility for proved passive remote
state. A proof error could stop an instance with unfinished work. The
new cases cover dirty or foreign authority, missing or malformed
snapshot key material, incomplete operations, foreign or unverified
leases, active ownership, retry state, and retained recovery references.
The SQL checks the stored key format; archive decryption and object
verification remain with the restore owner. The existing owned hold,
generation checks, runtime probes, and final host authorization still
apply. The change does not delete files, clear reservations, rewrite
history, create receipts, change schedules, or add a migration. Revert
the remote-provider predicate to restore the previous refusal behavior.
Hosted stop/wake qualification remains part of deployment acceptance.

## Model Used

OpenAI GPT-6.1-sol with xhigh reasoning through Codex in T3 Code.
Tool-assisted implementation, source review, and PostgreSQL
verification.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have described the issue in-PR following the bug report template
- [x] I have not referenced internal/instance-local Paperclip issues or
links
- [x] My branch name describes the change and contains no internal
ticket id or instance-derived details
- [x] I have run relevant tests locally and they pass; skipped
external-database cases are stated above
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation
- [x] I have considered and documented risks
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

- Final revision [ci /
e2e](https://github.com/paperclipai/paperclip/actions/runs/46539276027/job/142275047883):
passed.

- Final revision [ci /
verify](https://github.com/paperclipai/paperclip/actions/runs/46539276027/job/142275348382):
passed.

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-30 17:29:31 -08:00
scotttongandScott Tong fb6632530d feat(onboarding): start the first chat with a welcome and choices (#23334)
## Thinking Path

> - Paperclip helps people assign and track work with AI agents.
> - Onboarding connects the first agent and opens its chat.
> - A new user needs a clear way to start a conversation.
> - A saved welcome can appear as soon as chat opens.
> - The standard question card lets the user pick a goal, a product
overview, or a task.
> - The connected model replies after the user sends the choice.

## Linked Issues or Issue Description

**Subsystem affected**

Onboarding, agent chat, and subscription sign-in.

**Problem or motivation**

New users can land in a chat before they know what to ask. The original
welcome depended on a model run, which could delay the first
interaction. Local Claude sign-in could lose its code field if the
browser reloaded the onboarding tab during authorization.

**Proposed solution**

Save a personalized welcome and a standard question card. Type the
welcome when the chat opens, then show the card above the composer. Use
the choice and any task description to guide the connected model. Resume
the local Claude sign-in attempt when the onboarding tab reloads.

**Alternatives considered**

A model-written welcome can vary, but it adds a model call before the
user has chosen what to do. The saved welcome gives the user the same
starting points each time.

**Roadmap alignment**

This improves the existing first-agent flow for local and Cloud-managed
instances.

Related PRs: #22433 covers clearing the organization name after Back.
#23326 adds the separate Cloud mobile-to-desktop handoff.

## What Changed

- Save the greeting and question card together. Reuse the saved chat on
entry and keep the transcript in order after a reload.
- Type the greeting in the chat and reveal the standard question card
above the composer. Honor reduced motion.
- Collect a task description before starting the first model turn for
the task option. Guide the first reply for each choice.
- Restore the original local Claude sign-in attempt when the onboarding
tab reloads. Show progress while it connects, and offer retry on a
failed or stalled code exchange.
- Update the organization name helper text and the onboarding
walkthrough tests.

## Verification

- See the first-chat test drive for manual steps and the credential-free
browser fixture.
- 659 focused Vitest tests passed, with one skipped. The UI and server
typechecks and the feature map validator passed.
- All 18 Chromium tests passed across the first-chat, onboarding,
sign-in resume, and mobile desktop handoff specs. Coverage includes the
saved greeting, chat ordering, question handoff, Claude code submission
and resume, and the Cloud-managed starter model path with scripted
replies.
- The published Cloud service and live subscriber credentials need
separate acceptance testing.

## Risks

- The greeting uses the existing conversation and interaction records.
No database migration is needed.
- Existing in-flight model greetings can finish through the previous
path.
- The Claude PTY change depends on the CLI's bracketed-paste support.
The runner preserves separate input writes for terminals that do not
announce support.

## Model Used

OpenAI Codex, GPT-6.2 Sol and GPT-6.2 Astra, with terminal and browser
tooling.

## Checklist

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

---------

Co-authored-by: Scott Tong <1504818+scotttong@users.noreply.github.com>
2026-11-30 23:01:24 +00:00
DottaandPaperclip 1eae356c55 fix(analytics): remove PostHog consent banner and opt-out gating for private beta (#23333)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Paperclip Cloud sends browser product analytics and session replays
to PostHog when enabled for a hosted stack (self-hosted installs never
load posthog-js)
> - Previously, an EU/UK/Swiss consent banner and Profile settings
opt-out toggle gated browser analytics and dropped metrics when visitors
did not opt in
> - During private beta, we want to stop showing the consent banner and
opt-out prompt anywhere while continuing to send metrics (compliance
will be handled separately later)
> - This pull request removes the consent banner, Profile opt-out
toggle, and client-side consent gating across the UI and sets
`consentRequired: false` on the server response
> - The benefit is zero banner friction during private beta and
uninterrupted PostHog product metrics, while keeping all
replay/autocapture privacy masking and pre-load event queuing intact

## Linked Issues or Issue Description

**What existing behavior does this improve?**
Paperclip Cloud browser product analytics initialization
(`ProductAnalyticsGate`, `ui/src/lib/analytics`, `ProfileSettings`,
`cloud-posthog-browser.ts`).

**Subsystem affected**
Cross-cutting (multiple of the above) — `ui/` and `server/`.

**Current behavior**
In EU/EEA/UK/Swiss regions (or unknown time zones),
`ProductAnalyticsGate` renders `AnalyticsConsentBanner` and blocks
loading `posthog-js` until the visitor clicks Accept. `ProfileSettings`
also renders a `ProductAnalyticsSetting` opt-out switch.

**Proposed behavior**
Remove `AnalyticsConsentBanner`, `ProductAnalyticsSetting`, and
client-side consent gating so `ProductAnalyticsGate` loads PostHog
unconditionally when `browserAnalytics` is enabled for a Cloud stack.
Return `consentRequired: false` from `resolveBrowserAnalyticsConfig` so
cached older UI bundles also stop prompting during rollout, and keep
`opt_in_capturing()` when `has_opted_out_capturing()` is true so
previously opted-out browsers resume sending metrics.

**Reason and benefit**
During private beta, the EU/UK consent banner adds friction and drops
PostHog product metrics. Removing the banner and opt-out gating restores
full metric delivery while keeping all replay/autocapture privacy
masking and pre-load event queuing intact.

**Breaking changes**
None — `browserAnalytics.consentRequired` remains on the session payload
(as `false`), self-hosted installs still receive `browserAnalytics:
null`, and per-stack env controls (`PAPERCLIP_POSTHOG_BROWSER_ENABLED`,
`PAPERCLIP_POSTHOG_REPLAY_ENABLED=0`) continue to work.

## What Changed

- Deleted `ui/src/components/AnalyticsConsentBanner.tsx`,
`ui/src/components/ProductAnalyticsSetting.tsx`,
`ui/src/lib/analytics/consent.ts`, and their unit tests.
- Simplified `ui/src/components/ProductAnalyticsGate.tsx` to start
PostHog unconditionally after the page settles and render `null`.
- Simplified `ui/src/lib/analytics/product-analytics.ts` to remove
consent-state gating while keeping pre-load event queuing
(`MAX_QUEUED_PRODUCT_EVENTS`) and automatic opt-in for browsers with a
prior PostHog opt-out.
- Removed `ProductAnalyticsSetting` from
`ui/src/pages/ProfileSettings.tsx` and its mock in
`ui/src/pages/mobile-collections-responsive.test.tsx`.
- Updated `server/src/services/cloud-posthog-browser.ts` to always
return `consentRequired: false`.
- Updated `ui/src/components/ProductAnalyticsGate.test.tsx`,
`ui/src/lib/analytics/onboarding-analytics.test.tsx`,
`server/src/__tests__/cloud-posthog-browser.test.ts`,
`server/src/__tests__/auth-routes.test.ts`, and
`doc/cloud-browser-analytics.md`.

## Verification

- `pnpm vitest run ui/src/components/ProductAnalyticsGate.test.tsx
ui/src/lib/analytics/onboarding-analytics.test.tsx
ui/src/lib/analytics/product-analytics.test.ts
ui/src/pages/mobile-collections-responsive.test.tsx
server/src/__tests__/cloud-posthog-browser.test.ts
server/src/__tests__/auth-routes.test.ts` — all passed.
- `pnpm --filter @paperclipai/ui typecheck` — passed.
- `pnpm --filter @paperclipai/server typecheck` — passed.

## Risks

- Low risk: self-hosted installs remain unaffected (`browserAnalytics`
is still `null`). All replay/autocapture privacy masking and `/_ph`
proxy allowlists remain unchanged. Per-stack opt-out
(`PAPERCLIP_POSTHOG_BROWSER_ENABLED` /
`PAPERCLIP_POSTHOG_REPLAY_ENABLED=0`) continues to work.

## Model Used

- Google Gemini (Antigravity agent with tool use and code execution)

## Checklist

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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-30 22:49:39 +00:00
Nicky LeachandClaude Opus 5.5 1949a8fa10 fix(onboarding): sign in through a plugin-managed execution environment (#23312)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Onboarding connects the first agent to an AI provider account, often
with a Claude or Codex subscription sign-in
> - A plugin can manage an execution environment whose driver declares
`supportsLoginPty` and `requiresAgent`. Each agent's lifecycle prepares
that environment for the agent, and the sign-in runs in it
> - An instance can make such a plugin-managed execution environment its
default
> - The onboarding wizard offered browser sign-in only in a
sandbox-driver environment, so it blocked the connect step in every
plugin-managed execution environment
> - The sign-in also cannot start until the agent's lifecycle has
prepared the environment
> - This pull request lets onboarding and the new-agent flow sign in
through a plugin-managed execution environment, after the environment is
prepared for the agent
> - The benefit is that subscription sign-in works when the default
environment is plugin-managed

## Linked Issues or Issue Description

Refs #22695 and #20906.

**What happened?**

The default environment is a plugin-managed execution environment whose
driver declares `supportsLoginPty`. A user starts onboarding and chooses
Claude or Codex with a subscription. The connect step shows "This
environment does not support browser sign-in. Go back to use an API key
or choose another model." Connect stays disabled.

**What did you expect to happen?**

The connect step starts a browser sign-in in the plugin-managed
execution environment for the onboarding agent. The agent configuration
form and the AI Connections page already do this for plugin-managed
environments.

**Steps to reproduce**

1. Install an environment plugin with a `requiresAgent` driver that
declares `supportsLoginPty`, and make its environment the instance
default.
2. Start onboarding for a new company.
3. Choose Claude or Codex, and keep the subscription option.
4. See the message above. Connect is disabled.

## What Changed

- The onboarding wizard and the new-agent flow use the shared
`environmentSupportsLoginPty` rule. Before, both flows had their own
sandbox-only check.
- In a plugin-managed execution environment, onboarding sends the
sign-in to its own setup agent (`requiresAgent` and `agentId` on
`AdapterLoginPanel`). The new-agent flow does the same with its draft
agent.
- Onboarding polls the setup agent until the environment can take the
sign-in for it: a Paperclip runner agent on the login environment in
`verifying` or `ready`. Until then the step shows "Preparing your
agent's computer…", the user-facing name for this environment. A failed
preparation shows the error and a "Retry preparation" button. A failed
agent read shows "Could not check your agent's computer." and retries
the read.
- The new-agent flow keeps the login panel unmounted until the
environment is prepared (`loginHostPending` on
`AgentProviderConnection`). The panel starts the sign-in on mount, and
the disabled fieldset does not stop that.
- Both flows latch the readiness per agent and environment
(`useAgentComputerLoginReady`). A configuration change sends the setup
draft through preparation again. That must not unmount a sign-in that is
already on screen.
- The auth-signal route now accepts a plugin-managed execution
environment for `claude_local` and `codex_local`, and answers `unknown`
there. Before, it returned 422, and the onboarding step stayed undecided
and never showed the sign-in. The signal reads only host-local state,
which says nothing about a plugin-managed environment.
- The new-agent flow now says "Preparing your agent's computer…", the
same as onboarding.
- Each part of the login PTY question now has one owner:
- Shared `environmentLoginRequiresAgent` decides whether a sign-in needs
an agent. The four UI flows and the server's login target resolver use
it instead of their own `driver === "plugin"` checks.
- Shared `isPluginEnvironmentLoginAdapter` and
`pluginEnvironmentLoginReadsCredential` decide which adapters sign in
through a plugin-managed execution environment, and which of them must
read the credential back. `environmentSupportsLoginPty` and the server's
login target resolver use them. The server's capability resolver takes
the adapter type instead of a credential-read flag.
- `sandboxProviderSupportsLoginPty` decides sandbox-provider support for
both the capability listing and the sign-in check.
- The credential read uses `pluginSupportsLoginPty`, like the rest of
the plugin login path. Before, it checked only the manifest flag and the
read method.
- The agent configuration form's gate is now the shared rule plus "not
in create mode when an agent is required". Its duplicate driver check
and an always-true condition are gone.

## Verification

- `pnpm typecheck` in `ui/` and `server/`: no errors.
- `npx vitest run src/lib/agent-computer-login.test.ts
src/lib/agent-computer-login.hook.test.tsx
src/components/new-agent/AgentProviderConnection.computer-login.test.tsx
src/components/new-agent/AgentProviderConnection.test.tsx` in `ui/`:
tests pass. The `AgentProviderConnection` sign-in test covers a slow
preparation, and the readiness hook test covers a re-preparation of the
same environment.
- `npx vitest run src/__tests__/adapter-auth-signal-routes.test.ts` in
`server/`: tests pass. The two new plugin-managed environment cases fail
without the route change.
- `pnpm typecheck` in `packages/shared/`: no errors. `npx vitest run
src/environment-support.test.ts` in `packages/shared/`: 9 tests pass.
- In `server/`: the device-login, setup-token, login-session runtime,
sandbox-capability, credential-read and OpenAPI route suites pass (159
tests). A new credential-read case refuses a driver that does not meet
the plugin login rule.
- In `ui/`: the `AgentConfigForm`, `AgentProviderConnection`,
`agent-computer-login` and onboarding analytics suites pass.
- I did not do a live onboarding with a real plugin-managed execution
environment. Reviewers who have such an instance can reproduce with the
steps above. Expect "Preparing your agent's computer…", then the
provider sign-in, then the hire.

## Risks

- Onboarding waits for the environment's preparation before a
subscription sign-in in a plugin-managed execution environment. A slow
preparation makes the connect step wait for that time. An API key or a
saved subscription does not wait.
- The latch keeps the sign-in on screen while a configuration change
prepares the same environment again. If the plugin refuses the sign-in
in that window, the sign-in panel shows its usual error and retry.
- The setup draft must resolve to the Paperclip runner in the
plugin-managed environment. If it does not, the step stays on "Preparing
your agent's computer…". Plugin-managed environments run only the
Paperclip runner, so this is not expected.
- No migration and no API contract change. The auth-signal route accepts
one more environment driver.
- The credential read now requires the full plugin login rule
(`creationOperationVersion` 1 and every login worker method). A plugin
that reaches the credential read already passed that rule when its login
lease was acquired, so no working plugin should change.

## Model Used

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

## Checklist

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

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 14:10:58 -08:00
Andrii VasylievandClaude 48deef0135 fix(claude-local): fail runs whose prompt a UserPromptSubmit hook blocked (#17766)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The `claude_local` adapter runs the Claude Code CLI and turns its
stream-json output into a run result
> - A project can define a `UserPromptSubmit` hook, and that hook can
block the prompt
> - When the hook blocks the prompt, the CLI runs no turn, exits 0 and
reports a successful `result` whose text echoes the whole prompt
> - The adapter returned that echo as the agent's reply, the server
posted it as a comment, and the next wake carried that comment in the
task history
> - So each retry doubled the prompt, and the run looked successful
> - This pull request detects the blocked prompt and fails the run with
a specific error code and no echoed reply
> - The benefit is that a hook rejection is visible as a failed run, and
the prompt stops growing

## Linked Issues or Issue Description

No public issue exists for this. I searched open and closed issues and
pull requests for `UserPromptSubmit`, `blocked_by_hook`,
`prompt_submit_outcome` and "hook blocked prompt". Related, but
different: #15417 (pass-through of hooks-only settings for managed
connections), #11976 / #16443 (Hermes prompt echo).

**What happened?**

A project `UserPromptSubmit` hook blocked the wake prompt. Claude Code
emitted a `system` event with subtype `informational` and
`prompt_submit_outcome.kind = "blocked_by_hook"`, then a `result` event
with `subtype: "success"`, `is_error: false`, `num_turns: 0` and
`result` equal to `UserPromptSubmit operation blocked by hook: …
Original prompt: <whole prompt>`. The process exited with code 0. The
adapter treated the run as successful and used the echoed text as the
summary. The server posted the echo as the agent's comment. The next
wake included that comment in the task history, so the prompt grew on
each retry. We observed a wake prompt of about 3.6 MB.

**Expected behavior**

A prompt that a hook blocked is a failed run. The run must not post the
echoed prompt as a reply. The run error must say that a hook blocked the
prompt and give the hook reason.

**Steps to reproduce**

1. In an empty directory, create `.claude/settings.json` with
`{"hooks":{"UserPromptSubmit":[{"hooks":[{"type":"command","command":"echo
'blocked by policy hook' >&2; exit 2"}]}]}}`.
2. Run `claude -p --output-format stream-json --verbose "say hi" <
/dev/null`.
3. See the `informational` event with `prompt_submit_outcome:
{"kind":"blocked_by_hook","prompt_kept":false,"reason":"blocked by
policy hook"}`, then a `result` event with `subtype: "success"`,
`num_turns: 0` and the echoed prompt, and exit code 0 (seen with Claude
Code 2.1.309).
4. Use the same project for a `claude_local` agent and wake it. Before
this change, the run succeeds and its summary is the echoed prompt.

**Paperclip version or commit**

Seen on v2026.1023.0. The patch base is `master` at `a67a18c171`.

**Deployment mode**

Self-hosted, `claude_local` with `engine: cli`.

## What Changed

- `createClaudeStreamParser` records the reason from a
`system`/`informational` event whose `prompt_submit_outcome.kind` is
`blocked_by_hook`, and returns it as `promptBlockedReason`.
- `execute` sets `errorMessage` to `Claude prompt was blocked by a
UserPromptSubmit hook: <reason>`, `errorCode` to
`claude_prompt_blocked_by_hook`, `stopReason` to
`prompt_blocked_by_hook`, an empty summary and `result: null` in
`resultJson`. A non-null `errorMessage` makes the server record the run
as failed.
- The new error code is not a transient code, so the bounded transient
retry does not repeat the blocked prompt.
- Add an execute regression test with a fake CLI that emits the real
event sequence.

## Verification

- `npx vitest run server/src/__tests__/claude-local-execute.test.ts`: 35
passed.
- The new test fails on `master` without the source change (`expected
null to be 'claude_prompt_blocked_by_hook'`).
- `tsc --noEmit` in `packages/adapters/claude-local`: no errors. `tsc
--noEmit` in `server` gives the same error list as unchanged `master` in
the same environment (the only errors come from the unbuilt
`@paperclipai/paperclip-runner` package).
- Manual check of the CLI event shape with Claude Code 2.1.309, as in
the steps above.

## Risks

- Low risk. The new branch runs only when the CLI reports
`prompt_submit_outcome.kind === "blocked_by_hook"`.
- If a future CLI version changes this event shape, the adapter falls
back to the current behavior.

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

## Model Used

AI-assisted with Claude Code and OpenAI Codex coding agents; exact model
versions are not listed.

## Checklist

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

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

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-30 20:46:25 +00:00
DottaandPaperclip a1b9eed57d fix(mcp): stop masking upstream MCP and OAuth 502 errors as Paperclip outages (#23295)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Users connect external MCP servers and OAuth apps in Paperclip so
agents can use their tools
> - When a remote MCP server or OAuth authorization server rejects
automatic registration or discovery (for example, returning HTTP 400
`invalid_redirect_uri` during Dynamic Client Registration), Paperclip
returns HTTP 502 with a structured upstream error payload
> - The UI error classifier previously treated every HTTP 502 without a
`CODE_COPY` entry as a Paperclip outage, so it discarded the server
message and showed "Paperclip is temporarily unavailable"
> - This pull request shares a canonical allowlist of upstream
MCP/OAuth/remote HTTP 502 error codes between the server and UI,
preserves upstream error messages with accurate retryability, shows
clear sign-in guidance with Paperclip's copyable callback URL, and
resumes the saved draft connection during manual client recovery
> - The benefit is that users immediately see why a remote MCP server
rejected sign-in and how to fix it (allowlisting Paperclip's callback
URL or entering a client ID) without hitting a false Paperclip outage or
creating duplicate connections

## Linked Issues or Issue Description

**What happened?**

When a user connects a remote MCP server with browser sign-in and the
remote authorization server rejects Dynamic Client Registration (for
example, returning HTTP 400 `invalid_redirect_uri` because it requires a
client allowlist), the Paperclip server returns HTTP 502 with `{ error:
"The authorization server rejected Paperclip's callback URL.", details:
{ code: "oauth_dynamic_client_registration_failed", providerError:
"invalid_redirect_uri", status: 400 } }`. The UI classified that HTTP
502 as a transient connectivity outage and displayed "Paperclip is
temporarily unavailable. Please try again in a moment." instead of the
actual reason.

**Expected behavior**

Paperclip should preserve its server-authored error message for
allowlisted upstream HTTP 502 responses, derive `retryable` accurately
(non-retryable for permanent upstream rejections, retryable for upstream
outages/5xx/rate-limits/timeouts), and avoid triggering the app-wide
outage banner. In the MCP connection flow, Paperclip should explain why
the remote server rejected automatic sign-in setup, expand the Browser
sign-in section with Paperclip's copyable callback URL above Client ID
and Client secret, and resume the saved draft connection instead of
creating duplicate numbered connections when the user retries.

**Steps to reproduce**

1. Open Apps and connect a custom MCP server URL whose OAuth
authorization server rejects Dynamic Client Registration (such as HTTP
400 `invalid_redirect_uri` or another upstream registration/metadata
error).
2. Start browser sign-in.
3. Observe that Paperclip previously showed "Paperclip is temporarily
unavailable. Please try again in a moment." instead of explaining the
callback URL or registration rejection.

**Paperclip version or commit**

Reproduced on `master` at commit `2d764bebc6` (and prior `bc98abda0c`).

**Deployment mode**

Other (applies to both Paperclip Cloud and self-hosted deployments).

## What Changed

- **Shared contracts (`packages/shared`)**:
- Added `packages/shared/src/upstream-failure-codes.ts` (re-exported
from `packages/shared/src/index.ts`) defining the single canonical
allowlist of upstream HTTP 502 error codes
(`UPSTREAM_MCP_OAUTH_FAILURE_CODES`,
`UPSTREAM_REMOTE_HTTP_FAILURE_CODES`,
`UPSTREAM_BAD_GATEWAY_FAILURE_CODES`,
`isUpstreamBadGatewayFailureCode`), transient HTTP status helper
(`TRANSIENT_UPSTREAM_HTTP_STATUSES`, `isTransientUpstreamHttpStatus`),
and shared retryability policy (`isRetryableUpstreamFailure`). Transient
HTTP statuses (408, 425, 429, and 5xx) are checked before the permanent
`oauth_dynamic_client_registration_failed` fallback so rate-limited or
timed-out registration attempts remain retryable. Any unlisted
structured 502 still falls back to the transient outage path.
- Updated `connectToolAppSchema` in
`packages/shared/src/validators/tool-access.ts` so `resumeConnectionId`
works for generic `link` connections as well as gallery apps (still
requiring `galleryKey || link`), enabling the recovery path to resume a
saved generic MCP draft instead of creating a duplicate connection.
- **Server (`server/`)**:
- Updated `server/src/services/mcp-connection-failure.ts` so
`mcpDiscoveryHttpFailure` emits `{ code: "mcp_remote_http_error", status
}` in `HttpError` details.
- Updated `server/src/services/tool-access/catalog/failures.ts` so
`sanitizeHttpFailure` imports `UPSTREAM_MCP_OAUTH_FAILURE_CODES` from
`@paperclipai/shared` and preserves upstream MCP/OAuth failure codes
with HTTP 502 instead of collapsing them to `"paperclip_error"`.
- Updated `server/src/routes/tool-access.ts` so when `svc.startOAuth`
throws a non-manual-client `HttpError` after creating a `draft`
connection, `error.details` includes `connectionId:
result.connectionId`.
- Updated `server/src/services/tool-access.ts` (`connectGalleryApp`) so
resuming a draft via `resumeConnectionId` with a generic `link` enforces
that the draft is not a curated gallery app and that its stored MCP
endpoint matches the requested `link`.
- **UI (`ui/`)**:
- Updated `ui/src/api/errors.ts` so `isStructuredUpstreamBadGateway` and
`isRetryableUpstreamBadGateway` delegate to
`isUpstreamBadGatewayFailureCode` and `isRetryableUpstreamFailure` from
`@paperclipai/shared` (keeping unlisted structured 502s,
`ApiUnavailableError`, and `TRANSIENT_CODES` on the outage banner path,
and returning `retryable: false` for permanent upstream rejections vs
`retryable: true` for upstream 5xx, rate limits, timeouts, or temporary
outages).
- Updated `ui/src/pages/apps/generic-mcp-connect.ts` with
`"oauth_client"` focus, plain-English guidance for DCR (including
temporary rate-limit/timeout/5xx guidance with `focus: "none"` vs
permanent rejection guidance with `focus: "oauth_client"`), metadata,
redirect, token, and remote HTTP failures, plus pure
`genericGuidanceFormPatch` and `resolveGenericDraftResumeId` helpers.
- Updated `ui/src/features/connections/oauthFailureMessages.ts` to cover
`oauth_dynamic_client_registration_failed` (including transient HTTP
429/408/425/5xx responses), `oauth_dcr_response_invalid`, and
`oauth_metadata_failed`, extract `connectionId` in
`readOAuthApiErrorDetails`, and add `oauthStartFailureMessage`.
- Added `ui/src/features/connections/useGenericDraftResume.ts`
(`useGenericDraftResume` + `grantKindFromConnection`) and updated
`ui/src/features/connections/GenericMcpConnectStep.tsx`,
`ui/src/features/connections/ConnectionSetupFlow.tsx`, and
`ui/src/pages/tools/PasteConfigTab.tsx` to deduplicate guidance form
transitions via `applyGenericConnectGuidance`, preserve and resume the
failed generic draft connection ID across retries without creating
duplicates while starting a fresh draft if the URL, company, credential
ownership (`grantKind`), or dedicated agent changes, clear stale drafts
on `404` / `connection_setup_not_incomplete`, display Paperclip's
copyable callback URL (using `useCopyAction`) above Client ID and Client
secret when Browser sign-in expands, and remove the unused `ApiError`
import. No source file crossed the 1,000-line threshold
(`ConnectionSetupFlow.tsx` and `tool-access.ts` were already above 1,000
lines).
- **Tests**:
- Synchronized `tests/runner-e2e/source-sdk-public-inputs.json` for the
`@paperclipai/shared` public source graph.
- Added/updated regression tests in
`packages/shared/src/upstream-failure-codes.test.ts`,
`packages/shared/src/validators/tool-access.test.ts`,
`ui/src/api/errors.test.ts`,
`ui/src/pages/apps/generic-mcp-connect.test.ts`,
`ui/src/features/connections/oauthFailureMessages.test.ts`,
`ui/src/features/connections/GenericMcpConnectStep.machine.test.tsx`,
`ui/src/features/connections/ConnectionSetupFlow.generic-mcp.test.tsx`,
`server/src/services/tool-access/catalog/failures.test.ts`,
`server/src/services/__tests__/mcp-connection-failure.test.ts`, and
`server/src/__tests__/generic-mcp-connection.test.ts`.

## Verification

Ran on latest commit `9d088abf91`:
- `pnpm --filter @paperclipai/shared build && pnpm --filter
@paperclipai/shared typecheck && pnpm --filter @paperclipai/shared exec
vitest run src/upstream-failure-codes.test.ts
src/validators/tool-access.test.ts` — passed (2 files, 20 tests).
- `pnpm --filter @paperclipai/ui typecheck` — passed (0 errors).
- `pnpm --filter @paperclipai/ui exec vitest run src/api/errors.test.ts
src/pages/apps/generic-mcp-connect.test.ts
src/features/connections/oauthFailureMessages.test.ts
src/features/connections/ConnectionSetupFlow.generic-mcp.test.tsx
src/features/connections/ConnectionSetupFlow.oauth.test.ts` — passed (5
files, 140 tests).
- `node tests/runner-e2e/source-sdk-public-inputs.mjs $(git rev-parse
HEAD) --check` — passed (`changed: false`, 582 inputs).
- `pnpm exec vitest run --config tests/runner-e2e/vitest.config.ts
tests/runner-e2e/source-sdk-public-inputs.test.mjs` — passed (13 tests).

Full GitHub CI & review gates on final head `9d088abf91` ([`ci` run
46468259760](https://github.com/paperclipai/paperclip/actions/runs/46468259760)):
- `ci / verify`, `ci / e2e` (all 16 shards), `ci / Typecheck + Release
Registry`, `ci / policy`, `ci / General tests` (20/20), `ci / Runner
support suite` (4/4), `ci / Verify Paperclip` (9/9), `ci / Verify
serialized server suites` (9/9), `ci / Sandbox profile`, `Superagent
Security Scan`, `Socket Security`, `Contributor trust`, `security/snyk`,
`commitperclip PR Review`, and `Greptile Review` (5/5, 0 unresolved
threads) all passed on `9d088abf91`.

Visual states covered via component and flow tests using existing design
tokens (`border-input`, `bg-muted/40`, `text-foreground`,
`text-muted-foreground`): initial generic MCP connect step, expanded
Browser sign-in with copyable Paperclip callback URL (`Copy` / `Copied`
/ `Copy failed`), inline guidance banner for DCR/metadata/credential
errors (including transient rate-limit/timeout/5xx copy), draft resume
on manual client retry, fresh draft creation on access ownership change,
and draft clearing on `404` / `connection_setup_not_incomplete`.

## Risks

- Low risk. Uncoded HTTP 502 responses, unlisted structured 502 codes,
proxy HTML `ApiUnavailableError` responses, and `tenant_app_unavailable`
/ `tenant_app_starting` responses still classify as `"transient"` and
still trigger the app-wide outage banner.
- Security: Untrusted upstream OAuth `error_description`, `error_uri`,
and response bodies remain blocked; only Paperclip-authored messages and
allowlisted RFC error codes drive UI copy. Generic draft resume enforces
route-level configure authorization
(`assertToolConnectionConfigureAccess`), rejects curated gallery drafts,
and requires a matching normalized server endpoint.

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

## Model Used

- Google DeepMind Antigravity (Gemini-based coding agent via ACPX
runtime) with tool use and code execution.

## Checklist

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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-30 14:20:23 -06:00
DottaandPaperclip 63fffa8fcb test(server): drop heartbeat run-log cases duplicated by the module suite (#23191)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The heartbeat run-log pipeline redacts secrets and images from
chunks with `compactRunLogChunk`, then truncates oversized chunks.
> - Two suites cover this function:
`server/src/__tests__/heartbeat-run-log.test.ts` and the module suite
`server/src/services/heartbeat/run-log.test.ts`. Both run in the default
general-server lane.
> - Two of the four cases in the `__tests__` file repeat contracts the
module suite already proves with stronger, exact assertions (image-data
redaction with the exact 1024-character threshold and consistency;
truncation with exact head/tail/omission output and a
redaction-before-truncation ordering check).
> - This pull request deletes the two duplicated cases and keeps the two
cases with unique coverage (Paperclip credential-shape redaction and the
long-base64 performance guard).
> - The benefit is less duplicated test code and two fewer executions of
the same production path with no loss of failure detection.

## Linked Issues or Issue Description

No public issue exists. Problem description: duplicated test coverage
for `compactRunLogChunk`. The `__tests__/heartbeat-run-log.test.ts`
suite was checking image-data redaction and chunk truncation through
`compactRunLogChunk`, while `services/heartbeat/run-log.test.ts` proves
the same contracts with exact boundary assertions.

## What Changed

- Deleted "redacts inline base64 image data from structured log chunks"
from `server/src/__tests__/heartbeat-run-log.test.ts`. Retained
coverage: `services/heartbeat/run-log.test.ts` "preserves the image
omission threshold at %i characters" (exact 1023/1024 boundary) and
"omits every large image consistently across repeated calls".
- Deleted "truncates oversized chunks after sanitizing them" from the
same file. Retained coverage: "keeps the existing head, tail, and
omission count for a custom limit" (exact truncation output) and
"redacts credentials and image data before deciding whether a chunk
needs truncation" (ordering proof).
- Kept "redacts Paperclip credential shapes before persisting run-log
chunks" (unique PAPERCLIP_API_KEY env/JSON/flag and refresh-token
shapes) and "redacts a tool call that writes base64 of source text
without stalling" (performance guard) unchanged.

## Verification

- `npx vitest run src/__tests__/heartbeat-run-log.test.ts
src/services/heartbeat/run-log.test.ts` (in `server/`): 2 files, 26
tests passed.
- `npx tsc --noEmit -p .` (server package): clean.
- Both files are selected in the default general-server lane per
`scripts/general-server-shard-durations.json`.
- Full CI (typecheck, all lanes, Greptile) runs on this PR; local runs
of the full suite were not performed.

## Risks

Low risk. Deletion-only change to one test file; production code is
untouched. If a future regression removes image redaction or truncation,
the retained services-level cases fail at their assertions.

## Model Used

GLM (Z.ai) — openrouter/z-ai/glm-5.3, used via the Paperclip runner for
test-suite analysis and this change.

## Checklist

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


Co-Authored-By: Paperclip <Paperclip-Paperclip@users.noreply.github.com>
2026-11-30 19:33:26 +00:00
1847abcd91 refactor(test): remove test support orphaned by the nightly soak prune (#23142)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The server test tree under `server/src/__tests__/` keeps suites,
fixtures, and helper modules that support them.
> - The nightly soak prune in #22831 removed 483 soak suites, but eleven
of their support files stayed behind.
> - These files have no importer left. No test selects them. They never
run, but every contributor still reads, compiles, and typechecks them.
> - This pull request deletes the eleven orphaned support files. Each
one is proven unreferenced.
> - The benefit is 531 fewer lines of dead test support, and a test tree
that holds only live code.

## Linked Issues or Issue Description

No public issue exists for this cleanup. The problem is described here.

**What existing behavior does this improve?**
Test suite maintainability and typecheck scope of
`server/src/__tests__/` after the nightly soak prune (#22831).

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

**Current behavior**
Eleven test-support files under `server/src/__tests__/helpers/` and
`server/src/__tests__/fixtures/` have zero importers since the prune in
#22831 removed every suite that used them. They match no vitest include
pattern, so they never execute.

**Proposed behavior**
Delete the eleven dead files. Keep every live fixture and helper. Add no
new code.

## What Changed

- Deleted five orphaned helpers: `file-delivery-daytona.ts`,
`native-question-owner.mjs`, `observer-replay-report.ts`,
`recovery-population.ts`, and `maintenance/idle-work-capture-probe.ts`.
- Deleted six orphaned fixtures: `daytona-worker-lifecycle-sdk.mjs`,
`online-workspace-e2d-protocol.mjs`, its
`online-workspace-e2d-protocol.provenance.json` build receipt,
`sandbox-creation-receiver.ts`, `plugin-worker-deadline.cjs`, and
`plugin-worker-idle.cjs`.
- Deleted 531 test/support LOC. No production code, no test entry
points, and no assertions were removed.

## Verification

- Repo-wide reference scan: each of the eleven file stems was searched
across every source, manifest, workflow, tsconfig, and doc file in the
repository. Zero references exist. The scan also covers spawn patterns,
because plugin-worker and other fixtures are referenced by exact file
name everywhere they are used.
- Selection check: `server/vitest.config.ts` selects only
`src/**/*.test.ts` and `scripts/**/*.test.mjs`. None of the eleven files
matches, so no run loses a suite.
- `pnpm verify` reported the eleven deleted paths and asked for the
required CI lanes (`typecheck_release_registry`, `general_tests`,
`verify_paperclip_runner`, `build`, `verify_serialized_server`,
`e2e_shards`), as designed for source deletions. Required CI will cover
them.
- Focused local run: `pnpm --filter @paperclipai/server exec vitest run
src/services/issue-continuation-summary.test.ts` — 2/2 tests passed.
- Kept siblings verified live: `idle-work-capture.ts`,
`blocker-stall-fixture.ts` (benchmark consumer), and
`tool-profile-matching-fixture.ts` (documented benchmark) are referenced
and were not touched.

## Risks

- Low risk. Each deleted file had no importer, so no behavior or
coverage can change. If a future suite needs one of these helpers, it is
in git history.

## Model Used

- GLM (model id `openrouter/z-ai/glm-5.3`), driving a Paperclip
test-gardening agent: tool use, shell execution, repository-wide
reference scans, and local vitest runs. Assisted by no other model.

## Checklist

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



Co-Authored-By: Paperclip <Paperclip-Paperclip@users.noreply.github.com>

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-30 19:33:22 +00:00
DottaandPaperclip 8aba5a575e test: retire duplicated workspace-inheritance and environment-form cases (#22391)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The repository keeps its regression proof in Vitest suites. Two
suites and one UI suite held duplicate test cases.
> - The file `server/src/__tests__/issues-service.test.ts` has two
describe blocks with the same name. Each block held one copy of a test
about workspace inheritance from a source issue. The two copies differed
only in the `projectId` input.
> - The file `ui/src/pages/CompanyEnvironments.test.tsx` held
byte-identical second copies of two tests about the SSH remote-auth
option, inside the same describe.
> - Duplicate registrations run the same production path twice. They add
CI work and maintenance cost, and they give no new proof.
> - This pull request removes the duplicate registrations. It keeps one
registration for each contract, with the same assertions and fixtures.
> - The benefit is less duplicated test code and fewer repeated case
executions, with the same regression safety.

## Linked Issues or Issue Description

No public GitHub issue covers this cleanup. The problem follows the
enhancement template.

**What existing behavior does this improve?**

The behavior of the existing test suites. The suites
`issueService.create workspace inheritance` (server) and
`CompanyEnvironments — test provider button` (ui) still protect the same
contracts, without duplicate registrations.

**Subsystem affected**

- `server/src/__tests__/issues-service.test.ts` — the
workspace-inheritance cases of `issueService.create`.
- `ui/src/pages/CompanyEnvironments.test.tsx` — the SSH environment form
cases for the remote-auth option.

**Current behavior**

- Two describe blocks in `issues-service.test.ts` register a test with
the same name. One copy passes `projectId` to `create()`; the other copy
omits `projectId` and asserts that the follow-up inherits the project
from the source issue. All other assertions are the same.
- `CompanyEnvironments.test.tsx` registers two tests twice. The second
copies are byte-identical to the retained copies.

**Proposed behavior**

- One `it.each([true, false])` registration covers the explicit and the
implicit `projectId` input. The `projectId` inheritance assertion runs
in both variants.
- The byte-identical second copies in `CompanyEnvironments.test.tsx` are
removed. The retained copies stay without changes.

**Reason and benefit**

The removal keeps every assertion and every fixture. The retained
registrations execute the same production code and detect the same
regressions. The change deletes 136 lines of test code and adds 55
lines. It removes 4 repeated case executions per run of the UI file (1 +
3 `it.each` rows) and removes 1 duplicated registration in the server
file.

Duplicate work was searched before this pull request was opened. No open
or merged pull request touches these duplicate cases.

## What Changed

- `server/src/__tests__/issues-service.test.ts`: the retained test now
uses `it.each([true, false])` for the explicit and the implicit
`projectId` input. The assertion
`expect(followUp.projectId).toBe(projectId)` was moved from the deleted
copy and now runs in both variants. The duplicate copy in the second
describe block was deleted. No fixture changed.
- `ui/src/pages/CompanyEnvironments.test.tsx`: the byte-identical second
copies of `defaults new SSH environments to the agent's Paperclip
account` and `preserves the remote-auth option when editing an existing
SSH environment (saved=%s)` were deleted. The retained copies were not
changed.

## Verification

- Base revision: `201abacd6e` (master). Branch head: `9bbc77867a`.
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/issues-service.test.ts` — 155 tests passed (all suites of
the owner file, real embedded Postgres, no name filter).
- `pnpm --filter @paperclipai/ui exec vitest run
src/pages/CompanyEnvironments.test.tsx` — 43 tests passed with this
change; the same command at the base revision reported 47 tests. The 4
removed cases were byte-identical duplicates of retained cases.
- Keeper control 1: with a temporary production change that copies the
source issue's `executionWorkspaceId` to the follow-up, both `it.each`
variants fail at `expect(followUp.executionWorkspaceId).toBeNull()`. The
production change was restored after the check; the file matched the
committed bytes.
- Keeper control 2: with a temporary production change that skips the
`projectId` inheritance from the source issue, only the
`explicitProjectId=false` variant fails, at
`expect(followUp.projectId).toBe(projectId)`. The production change was
restored after the check.
- `pnpm --filter @paperclipai/ui typecheck` passed.
- The server package typecheck could not run on this host: the `cycle`
layer of `scripts/typecheck-layers.mjs` needs more memory than this
machine has, and `tsc` was stopped by the operating system (SIGKILL) on
both attempts. This is a host limit, not a product failure. CI runs the
same typecheck on this PR head.
- CI runs the full test lanes on this PR head. The checks below are the
required proof.

## Risks

- Low risk. No production code changed. No test selection, routing, or
CI configuration changed.
- The server consolidation keeps the same number of scenario executions
(two) through the same production path, so it reduces maintenance cost,
not server CI wall-time.
- The UI deletions remove 4 repeated case executions per run of the
file. No measured CI wall-time claim is made from this change.

## Model Used

- OpenRouter `z-ai/glm-5.3` (GLM), operated as the Paperclip "Test
Gardener (GLM)" agent. Tool use: file search and edit, shell test runs,
GitHub publication through the `gh` CLI. Context window size: not
tracked by the operator. Reasoning mode: default.

## Checklist

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

---

## Update (2026-11-24 rebase)

Master's #22679 deleted `ui/src/pages/CompanyEnvironments.test.tsx`,
which made this branch conflict. The branch was rebased onto master
`28aa32e7`: the obsolete UI-file deduplication was dropped, and this PR
now carries only the server-side deduplication in
`server/src/__tests__/issues-service.test.ts` (single commit
`4c115486`). Everything written above about the UI file describes work
that no longer exists in this PR.

Co-Authored-By: Paperclip <Paperclip-Paperclip@users.noreply.github.com>
2026-11-30 19:33:10 +00:00
Dotta aa76a16879 refactor(server): retire the native input boundary alias (#22299)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - `server/src/__tests__/native-runner-input-boundary.test.ts` is a
two-line alias: a comment plus one import of
`packages/paperclip-runner/src/contracts/native-execution.test.ts`. It
contributes no assertion, setup, or configuration of its own.
> - The alias was added in #12591 (2026-08-31), before the Runner
package suites ran in required PR CI. A 2026-10-13 audit receipt
retained it for exactly that reason: the package suite was omitted from
the root default project list, so the alias was its only root-suite
entry point.
> - Since then, `verify_paperclip_runner` became a required PR job whose
default matrix includes `test:typescript:vitest --package-lane=K/3` for
K in 1..3 (plus a native-server lane), and those lanes partition the
full package vitest inventory (`src/**/*.test.ts` in
`packages/paperclip-runner/vitest.config.ts`) as a complete,
non-overlapping cover. `src/contracts/native-execution.test.ts`
therefore runs in exactly one required package lane on every full-CI PR.
> - The same suite also executed a second time per PR inside the
serialized server lane through this alias. That is now a pure duplicate
execution, so this pull request deletes the alias.

## Linked Issues or Issue Description

- **What existing behavior does this improve?** Test cost only.
Production code does not change.
- **Subsystem affected** `server` test selection;
`packages/paperclip-runner` unchanged.

## What Changed

- Deleted `server/src/__tests__/native-runner-input-boundary.test.ts` (2
lines: comment + import of the package-owned
`native-execution.test.ts`).
- No production changes. The retained owner
`packages/paperclip-runner/src/contracts/native-execution.test.ts` is
untouched and still selected by the required package lanes.
- `scripts/general-server-shard-durations.json` still lists a 272 ms
weight for the deleted path; the shard script reads durations with a `??
fallbackWeight` default, so a stale manifest key is inert and the
measurement bot refreshes the manifest. Left unchanged to keep the diff
minimal.

## Verification

- Static evidence for safe removal:
- Package lane coverage: `packages/paperclip-runner/vitest.config.ts`
includes `src/**/*.test.ts`; `scripts/run-pr-vitest-lane.mjs` +
`scripts/vitest-package-lanes.mjs` partition that inventory into
complete non-overlapping lanes; `.github/workflows/pr-trusted.yml` runs
`test:typescript:vitest --package-lane=1/3..3/3` and `--native-server`
in the `verify_paperclip_runner` matrix, and the final validation job
asserts each planned suite result for that job.
- The alias adds no setup or separate assertion: its whole body is one
import (2-line file).
- Whole-repository reference search for `native-runner-input-boundary`:
only `doc/plans/*` receipts,
`packages/paperclip-runner/docs/design/standalone-thin-paperclip-adapter.md`,
and the shard duration manifest mention it; no executable test-selection
command, generator, or import references it.
- Duplicate gate: no open pull request's diff touches
`server/src/__tests__/native-runner-input-boundary.test.ts` or
`packages/paperclip-runner/src/contracts/native-execution.test.ts`
(checked via the pulls API for every open PR matching the names). PR
#21980 (open, `codex/test-garden-duplicate-forward-reconciliation-row`)
touches a different file (`workspace-runtime.test.ts`); not this
routine's work.
- Local runs: **not run** — this execution workspace ran out of disk
during `pnpm install` (the `pnpm-lock.yaml` refresh bot lags the ACPX
pin bump, so a frozen install fails at master HEAD and the
`--no-frozen-lockfile` install filled the 10 GB disk). No local test or
typecheck could run; the deletion is a test entry-point removal whose
safety rests on the selection evidence above, not on a green local run.
- Baseline comparison: master HEAD `440f96247b` had the same install
blocker; nothing about this 2-line deletion can affect module resolution
for the retained suites.

## Risks

- Contributors running only the root `pnpm test` no longer execute the
native-execution suite in that run; it still runs under `pnpm --filter
@paperclipai/paperclip-runner test:typescript` (local) and in the
required package CI lanes. This matches how every other
`packages/paperclip-runner` suite is already routed.
- CI savings are estimated, not measured: the shard manifest weights the
alias at ~272 ms per server-lane run plus module transform cost, but no
wall-time measurement of this PR's lane was taken.
- Remaining audit candidates (retained, not deleted this run):
`devtools/browser/src/live/transcript-model.test.ts` vs
`src/browser/transcript-model.test.ts` (near-identical titles, but each
exercises its own production module — possible production duplication,
out of test-gardening scope); the three `execute.acp-fallback.test.ts`
adapter copies (each mocks its own protocol);
`runner-tool-results.live.test.ts` (opt-in live suite, skipped by
default).

## Model Used

GLM-5.3 (openrouter/z-ai/glm-5.3) driving the Paperclip Test Gardener
agent.

## Checklist

- [x] No production behavior changes
- [x] No checks weakened; the retained owner suite is selected in
required PR CI
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] No documentation files added or modified
2026-11-30 19:26:26 +00:00
Devin FoleyandPaperclip 5f1178b966 Fix first-agent skill setup racing an uncommitted installation (#23308)
## Thinking Path

> - Paperclip manages AI agents and the skills they need for work.
> - First-agent setup assigns the bundled operating and onboarding
skills.
> - An environment plugin can initialize those skills inside a
transaction.
> - Another request could share that transaction's refresh promise and
read before its commit.
> - The hire then rejected valid default skills as unknown references.
> - This pull request scopes shared refresh work to each database handle
and makes concurrent bundled creation idempotent.

## Linked Issues or Issue Description

**What happened?**

First-agent onboarding on a fresh hosted stack failed with `Invalid
company skill selection (unknown references: ...)` after the user
entered a Claude API key. The failure occurred during skill assignment,
before a provider connection could be verified.

The environment plugin initialized the bundled library inside its
skill-install transaction. The hire request awaited the same
company-wide refresh promise. That promise settled before the outer
transaction committed. The hire's separate connection then read an empty
library and returned HTTP 422.

**Expected behavior**

A hire resolves committed bundled skills even when another installer is
active. A failed competing transaction must not leave the hire dependent
on rolled-back work. Concurrent callers must retain one installed skill
per key.

**Steps to reproduce**

1. Create a company with no initialized skill library.
2. Start bundled inventory initialization inside a transaction and hold
its commit.
3. Resolve first-agent skill selections through the ordinary database
handle while initialization is active.
4. Let initialization finish, while the outer transaction is still open.
5. Observe the unknown-reference error from the separate connection.

The added real-PostgreSQL regression controls these boundaries without
real-clock sleeps.

**Paperclip version or commit**

Observed on `79dadd86551e4deb254163dd1f952f2908f1d351`. Reproduced
locally on `79ef76757879`.

**Deployment mode**

Hosted Docker deployment. The underlying transaction race also applies
to other deployments.

Related: #22477 repaired a different first-agent skill upload failure.
Searches of open and closed skill/onboarding and skill/transaction
changes found no duplicate of this repair.

## What Changed

- Store in-flight inventory refreshes by database handle and company.
Service instances on the same handle still share work. Other connections
and transactions refresh through their own visibility boundary.
- Take the existing skill publication advisory lock before the
bundled-create recheck. Reuse a concurrent installation once it is
visible. Keep normal user-created skill conflict handling intact.
- Recheck a shipped release under the skill-row lock before inserting
its version. Reuse a matching release and reject a concurrent snapshot
with different contents.
- Keep the fix in the existing inventory and import owner. No schema,
provider, UI, or public API changes are required.
- Add commit and rollback regressions that hold the installer open until
the competing caller attempts publication. Preseed the folder metadata
and use inline packages for this specific creation race so unrelated
folder and object-store locks do not settle the race first.
- Add concurrent release-seeding cases for matching and corrupted
snapshots. Existing tests cover shared refreshes, separate actor
visibility, and revoked project access.

## Verification

- The original commit/rollback regressions reproduced the
unknown-reference HTTP 422 before the repair.
- Review regression, red: both concurrent release-seeding cases
reproduced PostgreSQL `23505` on
`company_skill_versions_skill_release_idx` before the release recheck
was added.
- Creation-race test: removing the bundled-create recheck makes the
tightened commit case fail with HTTP 409. The protected code passes.
This proves the test reaches the concurrent-creation boundary.
- Green: all six inventory-concurrency cases pass, including commit,
rollback, matching release reuse, corrupt release refusal, same-handle
coalescing, and separate actor visibility.
- Final revision: `5ac8f4d7acc1a2fe5111935d892c5d57ef54b5a6`. All 277
tests passed across nine focused files: company skill service, runtime
concurrency, runtime selection, environment skills, plugin-managed
skills, managed content, agent skill routes, package upload, and bundled
release validation.
- `pnpm --filter @paperclipai/server typecheck` passed, including source
and test layers, on the final source.
- Test command: `pnpm exec vitest run
server/src/__tests__/{company-skills-runtime-concurrency,company-skills-service,company-skills-runtime-selection,environment-skills,plugin-managed-skills,managed-skill-content,agent-skills-routes,skill-package-upload}.test.ts
server/src/services/bundled-skill-release-validation.test.ts`.
- `node scripts/check-test-budget.mjs --files
server/src/__tests__/company-skills-runtime-concurrency.test.ts` and
`git diff --check` passed.
- Environment: local macOS arm64 with real embedded PostgreSQL. Tests
use controlled gates rather than real-clock sleeps.
- The previous head, `088b8f8822d5bc218f4e5e7cfcf61c510de0776d`, passed
all 270 focused tests, server source/test typechecks, and
[CI](https://github.com/paperclipai/paperclip/actions/runs/46488494810).
The 4/5 review identified the release race and the test gap addressed
here. The final revision has now passed fresh CI and review; the results
are recorded below.
- `pnpm verify --explain` selected 1,981 tests, with 1,978 retained
conservatively. Focused local checks cover this repair; required CI
supplies the broader typecheck, build, test, Runner, and browser
coverage.
- Staging diagnosis used the served Core SHA, bounded request logs, and
read-only database queries. The logs and row timestamps match the
reproduced transaction race.
- Test code and service behavior document this internal invariant; no
user-facing command or API contract changed.
- A deployed onboarding retry with the fixed revision has not been run.
This PR does not deploy the repair or validate the user's provider
credential.

- Current-head [Greptile
review](https://github.com/paperclipai/paperclip/pull/23308#issuecomment-7288511940)
is 5/5 on `5ac8f4d7acc1a2fe5111935d892c5d57ef54b5a6`. Both prior review
threads are resolved.
- Final [CI run, attempt
2](https://github.com/paperclipai/paperclip/actions/runs/46491251884/attempts/2)
completed successfully on `5ac8f4d7acc1a2fe5111935d892c5d57ef54b5a6`.
Scope: typecheck/release registry, build, native Runner checks, general
tests, serialized server suites, and all 16 browser shards. GitHub
reports the branch as clean and mergeable.
- Attempt 1 lost the runners for [browser shard
5](https://github.com/paperclipai/paperclip/actions/runs/46491251884/job/142104554848)
and [browser shard
12](https://github.com/paperclipai/paperclip/actions/runs/46491251884/job/142104554842).
Those interrupted attempts are not passes. GitHub initially rejected
targeted retries while the parent workflow was running. Both shards
passed in attempt 2.

## Risks

Different database handles now perform their own inventory refresh. The
bundled-create lock prevents duplicate publication when these refreshes
overlap. Same-handle coalescing and the existing access checks remain
effective. The change does not relax unknown-skill validation or normal
edit/create conflicts. No migration is needed.

## Model Used

OpenAI GPT-6.1 Sol (`gpt-6.1-sol`) through the Codex harness, with xhigh
reasoning effort and tool use.

## Checklist

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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-30 11:21:05 -08:00
Nicky LeachandClaude Opus 5.5 fa283aeea2 feat(plugins): let an environment plugin report its task's startup stage (#22970)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - A run's environment can come from a plugin, which runs the agent's
task through environment task operations such as prepare and submit.
> - The stacked pull requests below this one make Core publish each
run's startup stage from the steps it times, and show that stage in the
task view.
> - Core cannot see inside a plugin's task operation. A slow step there,
such as a stopped machine starting, shows as whatever stage Core was in
when it called the plugin.
> - This pull request lets an environment plugin report its task's
stage, from the same closed list Core uses, while one of its task
operations runs.
> - The benefit is that the task view names the real reason a
plugin-backed turn has not started yet, with no stages only plugins know
about.

## Linked Issues or Issue Description

No public issue exists. Stacked on #22956 (UI), which is stacked on
#22953 (server).

**Subsystem affected**
Plugin SDK (`packages/plugins/sdk`), plugin host services and
environment task runtime (`server/src/services`), and the plugin docs.

**Problem or motivation**
A plugin's environment task operation can take many seconds, for example
when it starts a stopped machine. The task view keeps the stage Core
showed when it called the plugin, so the wait has the wrong name.

**Proposed solution**
Add `ctx.environmentTasks.reportStartupStage({ taskId, stage })`. Core
accepts a report only while one of that plugin's task operations for a
run is in flight. The reported stage shows instead of Core's stage until
the operation returns.

**Alternatives considered**
- Free-form status text from the plugin. It would not match Core's
stages, and each plugin would word the same step in a different way.
- Stages that only plugins can report. One shared list keeps Core and
plugins aligned, so the task view needs no plugin-specific labels.

## What Changed

- SDK: `ctx.environmentTasks.reportStartupStage({ taskId, stage })` and
the `environmentTasks.reportStartupStage` host method. The call needs
the existing `environment.drivers.register` capability. The test harness
records reports in `startupStageReports`.
- Server: the environment task runtime opens a reporting window for the
plugin and task while each task operation for a run is in flight. Inside
the window, the plugin's stage shows instead of Core's stage, and may be
an earlier stage (for example `starting_environment` during submit).
When the last operation returns, Core's stage shows again.
- Server: Core ignores a report outside a window, for another plugin's
task, with an unknown stage, or after the agent's turn starts. A report
never fails the task operation.
- Docs: `PLUGIN_ENVIRONMENT_TASKS.md` has a "Startup stages" section,
and `PLUGIN_SPEC.md` lists `ctx.environmentTasks`.
- `tests/runner-e2e/source-sdk-public-inputs.json`: regenerated for the
changed SDK sources.

## Verification

- `npx vitest run tests/host-client-factory.test.ts
tests/testing-environment-tasks.test.ts` in `packages/plugins/sdk`: the
capability gate and the harness record (26 tests pass).
- `npx vitest run src/services/run-startup-stage.test.ts
src/__tests__/environment-task-runtime.test.ts` in `server`: windows
open and close per operation, overlapping operations, reports outside a
window or after the turn starts are ignored, an earlier stage shows
during the window, and a report from inside a real task operation
reaches the run (78 tests pass).
- `node tests/runner-e2e/source-sdk-public-inputs.mjs <head> --write`
reports no changes.
- `pnpm --filter @paperclipai/plugin-sdk typecheck` and `pnpm --filter
@paperclipai/server typecheck` pass.
- CI runs the full suite.

## Risks

- Low risk. The call is new and optional. Plugins that do not call it
see no change.
- A plugin can only report for its own task, only while Core waits on
one of its operations, and only from the shared stage list. It cannot
change the stage after the agent's turn starts.

## Model Used

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

## Checklist

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

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 16:22:09 +00:00
Nicky LeachandClaude Opus 5.5 76e3b7e172 feat(runs): track each run's startup stage for the board (#22953)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - When a run starts, Core claims it, prepares the host, acquires and
prepares the execution environment, restores the saved session, sets up
tools, and starts the agent's runner.
> - The task view shows "Thinking" for all of that time, so a slow cold
start looks like a slow model.
> - Core already times each of these steps (`heartbeat.prepare.*`,
`native.controller.*` and the native run trace), but nothing tells the
board which step is running.
> - This pull request adds a closed list of startup stages and a
process-local tracker that follows those timed steps. It sends the
current stage to the board as a live event and adds it to active run
reads.
> - The benefit is that the board can say what a run is doing before the
agent's turn starts. The UI change comes in a stacked pull request.

## Linked Issues or Issue Description

No public issue exists.

**Subsystem affected**
Run execution status (`server/src/services/heartbeat*`, native runtime
trace) and the shared run types.

**Problem or motivation**
From the claim to the agent's first turn, the task view always says
"Thinking". On a test instance over 24 hours, the median time before the
first agent event was 10 to 50 seconds. Most of it was environment
setup, session migration (median 0.3 s, P90 14 s) and tool setup (median
8 s, P90 18 s), not model time. A user cannot tell a slow start from a
slow model.

**Proposed solution**
Name the startup steps that every execution environment goes through and
report the current one. Derive the stages from the steps Core already
times, so the stage and the trace spans cannot drift apart.

**Alternatives considered**
Free text from each environment, which gives inconsistent wording and
lets an environment show arbitrary text. Grouping by where the work
runs, which breaks the order because Core does host work both before and
after it acquires the environment.

## What Changed

- `packages/shared`: add `RUN_STARTUP_STAGES` (`getting_ready`,
`starting_environment`, `preparing_workspace`, `restoring_session`,
`connecting_tools`, `starting_agent`), the `heartbeat.run.startup_stage`
live event type and its payload type, and the `startupStage` and
`startupSessionResumed` run fields.
- `server/src/services/run-startup-stage.ts`: a process-local tracker.
One table maps timed step names to stages. A run only moves forward
within one execution attempt. Startup ends at the agent turn, turn
submission or first agent activity (native runs), or when the heartbeat
enters a direct adapter. When startup ends, the stage clears but the
attempt keeps its resumed-session flag until the attempt ends. The store
is bounded (512 runs, and a 1 hour TTL while a stage shows).
- The preparation timing helper (`measure`) and the native run trace
(`start`, which `record` also uses) report each step to the tracker. The
heartbeat starts tracking when a run starts executing and stops when the
execution ends. The native executor reports a resumed provider session.
- `tests/runner-e2e/source-sdk-public-inputs.json`: regenerated, because
the pinned shared SDK sources changed.
- `decorateHeartbeatRunRuntimeStatus` adds `startupStage` and
`startupSessionResumed` to active run reads and clears them for ended
runs.
- The native session executor ends startup when a run that reattached
after a restart sees its turn already under way: a replayed
`turn.submitted` or `turn.started`, or agent output, including output
that arrives before this attempt saw its own `turn.started`.

## Verification

- `npx vitest run src/services/run-startup-stage.test.ts` (13 tests):
stage order, the forward-only rule, skipped stages, the end of startup,
unknown runs, the resumed session (also after the turn starts), a new
attempt, company and agent checks, TTL and the size bound, the real
timing helper and native trace hooks, and active run reads.
- `npx vitest run
src/__tests__/heartbeat-execution-configuration.test.ts`: a new case
runs a registered direct adapter through real preparation on the test
Postgres. Each run publishes `getting_ready`, `starting_environment`,
`preparing_workspace`, then the end of startup, and no stage shows while
the adapter runs.
- `cd tests/runner-e2e && npx vitest run
source-sdk-public-inputs.test.mjs source-sdk-public-type.test.ts
source-sdk-evidence.test.ts` (59 tests) after the registry refresh.
- The CI failure in `adapter-utils` `run-fault-matrix.test.ts`
(`case_14c`) is in a package this change does not touch. It passed three
times locally.
- Existing tests near the change pass: `native-run-trace.test.ts`,
`native-run-trace-context.test.ts`,
`heartbeat/preparation-timing-context.test.ts`,
`heartbeat-run-runtime-status.test.ts`,
`realtime/live-event-delivery.test.ts` (108 tests).
- `npx vitest run
src/services/native-runtime/native-session-executor.test.ts -t "native
startup stage after a restart|native resumed preparation timing"` (16
tests): a reattached run leaves startup on a replayed turn start and on
new agent output. Both new cases fail without the fix.
- `pnpm --filter @paperclipai/shared typecheck` and `pnpm --filter
@paperclipai/server typecheck` pass.
- CI runs the full suite.

## Risks

- Low risk. The tracker is in memory only and is never persisted. A
server restart clears it, and the board then shows what it shows today.
No run, session or launch state changes shape, so no saved state needs a
migration.
- Every hook is wrapped so that a tracker error cannot fail a run or its
trace.
- The live event uses the existing `heartbeat.run.*` delivery rule: it
needs a `runId` and the viewer's run read access.
- One extra live event per stage change (at most about seven for each
run attempt).

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use
(shell, file edits, Honeycomb trace queries for the timing data).

## Checklist

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

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 16:22:07 +00:00
Dotta e7ed0c2f93 fix(workspaces): reconcile project-derived workspace bindings when a task moves projects (#23293)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - When a task is created in a project without explicit workspace
overrides, Paperclip derives `projectWorkspaceId`,
`executionWorkspaceSettings`, and a project-derived `workspaceSelection`
(`source: "project"`).
> - Moving that unbound task to a different project via `issues.update`
left the old project's `projectWorkspaceId` and `workspaceSelection`
behind.
> - Subsequent runs kept resolving back to the old project's workspace
and storage owner, causing repeated workspace validation or
storage-incompatibility failures even after the user moved the task to a
compatible project.
> - This pull request re-derives project-derived workspace bindings when
an unbound task moves projects, and reconciles already-moved unbound
tasks with stale `source: "project"` bindings at run admission while
preserving explicit workspace selections and bound execution workspaces.
> - The benefit is that moving an unbound task to a compatible project
immediately lets it run on the new project's workspace without hidden
stale-workspace failures.

## Linked Issues or Issue Description

Related: #17552, #22849.

**What happened?**

When a task was created in a project, `issues.create` automatically set
`projectWorkspaceId` and `workspaceSelection` with `source: "project"`.
If the task failed before binding an execution workspace
(`executionWorkspaceId === null`) and the user moved the task to a
different project (for example from a Core-storage project to a
plugin-storage project), `issues.update` updated `projectId` but left
`projectWorkspaceId` and `workspaceSelection` pointing to the old
project's workspace. Every subsequent run still resolved the old
project's workspace and storage policy and failed.

**Expected behavior**

- Moving an unbound task whose workspace binding is project-derived
(`source: "project"`, or a legacy `projectWorkspaceId` belonging to the
previous project with no `workspaceSelection`) re-derives
`projectWorkspaceId`, `workspaceSelection`, and
`executionWorkspaceSettings` from the new project (or clears them when
moving to no project or a sourceless project).
- Explicit workspace selections (`source !== "project"`), bound
execution workspaces (`executionWorkspaceId != null`), pending workspace
selections, and tasks with an active running run or pending workspace
recovery keep their current workspace binding.
- Tasks already moved on an older release with a stale `source:
"project"` binding pointing to a different project are reconciled at run
admission before workspace preparation.

**Steps to reproduce**

1. Create a Core-storage project A with a Git workspace and a
plugin-storage project B with a Git workspace.
2. Create an isolated task in project A (so `issues.create` sets
`workspaceSelection.source = "project"`).
3. Move the task to project B via `issueService.update(id, { projectId:
projectB.id })`.
4. Before this fix, `projectWorkspaceId` and
`workspaceSelection.selection.projectWorkspaceId` still point to project
A's workspace.

**Paperclip version or commit**

Reproduced against `origin/master` at `2d764bebc6ed`.

**Deployment mode**

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

## What Changed

- `server/src/services/project-move-workspace-reconciliation.ts`: add
focused helpers (`isProjectDerivedWorkspaceBindingStale`,
`deriveProjectDefaultWorkspaceBinding`,
`hasActiveTaskWorkspaceRunHolder`) shared between issue updates and run
admission.
- `server/src/services/execution-workspaces.ts`: add
`reconcileProjectWorkspaceForProjectMove` (used by `issues.update`) and
`reconcileStaleProjectWorkspaceAtAdmission` (used at run admission for
already-moved tasks with stale `source: "project"` bindings). Keeping
the shared reconciliation helpers in a sibling module avoids growing
`execution-workspaces.ts` and `issues.ts` unnecessarily.
- `server/src/services/issues.ts`: invoke
`reconcileProjectWorkspaceForProjectMove` inside `issues.update` after
`changesPrivacy` when `projectId` changes and no explicit workspace
fields were supplied.
- `server/src/services/heartbeat.ts`: invoke
`reconcileStaleProjectWorkspaceAtAdmission` alongside
`releaseAncestorWorkspaceBindingAtAdmission` at run admission, marking
`workspaceSelectionChanged = true` when reconciled.
- `server/src/__tests__/issue-project-move-workspace.test.ts`: add
red-green database regressions for moving to another project, moving to
a sourceless/null project, preserving explicit selections, preserving
bound `executionWorkspaceId`, deferring mid-run moves, and reconciling
already-moved tasks at admission.
- `server/src/__tests__/agent-project-access.test.ts`: use `source:
"explicit"` for the explicitly-retained-source denial test and add a
companion test verifying `source: "project"` re-derives on project move.

## Verification

- **Red (before production edits)**:
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/issue-project-move-workspace.test.ts` failed on
`re-derives a project-derived workspace when moving an unbound task to
another project` and `clears a project-derived workspace when moving to
no project or a sourceless project` because `projectWorkspaceId` and
`workspaceSelection` stayed pinned to the old project.
- **Green (after production edits)**:
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/issue-project-move-workspace.test.ts
src/__tests__/agent-project-access.test.ts` — 20/20 passed.
  - `pnpm --filter @paperclipai/server typecheck` — passed.
  - `pnpm --filter @paperclipai/server build` — passed.
- `pnpm --filter @paperclipai/server exec vitest run
src/services/heartbeat/workspace-preparation.test.ts -t "names
incompatible Core project storage|rejects Core Git worktree
preparation"` — 2/2 passed.
- `pnpm --filter @paperclipai/server exec vitest run
src/services/task-interruption-presentation.test.ts` — 82/82 passed.
- `pnpm verify --explain` selected 1978/2333 files due to touching
central server services; required GitHub Actions CI supplies the broad
suite coverage.
- Live deployment and recovery of previously affected tasks on hosted
instances are outside this PR's scope.

## Risks

- Low risk. Reconciliation is gated to unbound tasks
(`executionWorkspaceId == null`, `workspacePendingSelection == null`)
with no active run holder or pending workspace recovery, and never
alters explicit (`source !== "project"`) workspace selections or bound
files.
- Moving a task to a project whose trust boundary currently denies the
assigned agent will not fail the move; execution access remains enforced
at run admission.

## Model Used

- Google Gemini (Antigravity agentic coding assistant) with tool use,
shell execution, and local test verification. Exact deployment model ID
and context window are not exposed to the session.

## Checklist

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

> - Paperclip is the open source app people use to manage AI agents for
work
> - Paperclip Cloud inspects tenant stacks read-only through
`/api/customer-success/v1`
> - Today, inspection can only read raw byte slices of one run log at a
time, and platform guard or launcher errors inside agent shell commands
leave runs marked `succeeded` with `exitCode: 0` and no `errorCode`
> - Finding how many runs hit an error string requires downloading
megabytes of raw logs and pulling customer prompts into agent context
> - This pull request adds bounded, match-only `runs.search` and
stack-wide `count` on `/read-v3`, plus closed-vocabulary platform run
diagnostics recorded on runs and surfaced in `view: "summary"`
> - The benefit is fast, privacy-preserving prevalence diagnosis without
exposing raw customer prose or missing errors hidden inside succeeded
runs

## Linked Issues or Issue Description

**Subsystem affected**

Server and shared contracts: `/api/customer-success/v1` inspection
endpoints, shared inspection wire contract, and run-event platform
diagnostics.

**Problem or motivation**

When a platform wrapper (such as the Git storage guard or GitHub
credential launcher) fails inside an agent tool call, the outer agent
run often still finishes with `status: "succeeded"` and `errorCode:
null`. Investigating prevalence through customer-success inspection
previously required paging raw `runs.log` byte ranges one run at a time,
pulling customer prompts into context and making fleet-wide triage
impractical.

**Proposed solution**

1. Extend the shared customer-success wire contract
(`packages/shared/src/customer-success.ts`) with `runs.search` (1 to 5
literal substrings, no regex, optional creation window,
counts/co-occurrence/sample pointers only by default, redacted excerpts
only when `companyId` and `includeExcerpts: true` are set) and
stack-wide `count` on `/api/customer-success/v1/read-v3`.
2. Execute `runs.search` inside the existing read-only, repeatable-read
transaction using in-database `strpos` matching over
`heartbeat_run_events` plus `heartbeat_runs` error fields, falling back
to chunked `RunLogStore` scans with overlap windows for
legacy/non-native runs or runs without stored events.
3. Add a closed-vocabulary platform diagnostic detector
(`packages/shared/src/run-diagnostics.ts`) that records deduplicated
`platform.diagnostic` rows in `heartbeat_run_events`, attaches
`diagnostics` to `view: "summary"` run reads, and optionally reports
bounded PII-free diagnostic codes to Paperclip Cloud when a stack
diagnostics capability is configured.

**Alternatives considered**

Paging raw `runs.log` slices from Cloud or the agent. That transfers
megabytes of unrelated customer prose, hits rate limits, and still fails
to surface known platform errors in structured run summaries.

## What Changed

- `packages/shared/src/customer-success.ts`: add
`INSPECTION_SEARCH_READ_PATH` (`"/read-v3"`), `runs.search` operation
and strict parser bounds, optional `companyId` for `runs.search`
(without excerpts) and stack-wide `count`, and
`InspectionRunSearchResult` types.
- `packages/shared/src/run-diagnostics.ts` &
`packages/shared/src/index.ts`: add closed-vocabulary
`RUN_PLATFORM_DIAGNOSTIC_CODES` and deterministic
`detectRunPlatformDiagnostics()`.
- `server/src/services/customer-success-run-search.ts`: implement
bounded read-only `searchCustomerSuccessRuns()` with in-DB `strpos`
event matching, overlap-window `RunLogStore` fallback, co-occurrence
tracking, diagnostic aggregation, and opt-in secret-redacted excerpts.
- `server/src/services/customer-success-inspection.ts` &
`server/src/routes/customer-success.ts`: mount `/read-v3`, enforce
versioned path gating, support stack-wide `count`, and attach
`diagnostics` to `runs` `view: "summary"`.
- `server/src/services/run-platform-diagnostics.ts`,
`server/src/services/native-runtime/paperclip-control-plane-port.ts`,
`server/src/services/agent-task-run-telemetry.ts`,
`server/src/services/native-runtime/native-run-log-export.ts`: detect
and deduplicate `platform.diagnostic` run events, exclude them from PRP
log export, and emit bounded PII-free Cloud reports when configured.
- `server/src/__tests__/customer-success.test.ts`,
`server/src/__tests__/run-platform-diagnostics.test.ts`,
`server/src/__tests__/customer-success-cloud.test.ts`,
`server/src/__tests__/openapi-routes.test.ts`,
`doc/CUSTOMER-SUCCESS-INSPECTION.md`: unit tests, coordinated PostgreSQL
qualification coverage, OpenAPI route list update, and documentation.

## Verification

- `pnpm --filter @paperclipai/shared build && pnpm --filter
@paperclipai/shared typecheck && pnpm --filter @paperclipai/server
typecheck` — passed.
- `cd server && pnpm exec vitest run
src/__tests__/customer-success.test.ts
src/__tests__/run-platform-diagnostics.test.ts
src/__tests__/openapi-routes.test.ts` — 78/78 passed.
- `cd server && PAPERCLIP_INSPECTION_CLOUD_DIST=<cloud-dist> pnpm exec
vitest run src/__tests__/customer-success-cloud.test.ts` — passed
end-to-end against two live PostgreSQL databases, verifying `/read-v3`
`runs.search`, `diagnostics` in run summaries, default non-waking fleet
queries, and `fleet.diagnostics`.

## Risks

- Low risk. All inspection reads remain inside repeatable-read,
read-only transactions behind EdDSA Cloud permits and replay fencing.
- Older tenants without `/read-v3` answer 404, so Cloud fails closed
with `tenant_inspection_version_unsupported` during rolling upgrades.
- `platform.diagnostic` rows stay in the instance database
(`heartbeat_run_events`); Cloud reporting is a no-op unless Cloud
explicitly delivers `PAPERCLIP_RUNTIME_DIAGNOSTICS_CAPABILITY`, and
emits only closed enum codes and run/driver metadata (never customer
prose).

## Model Used

- Google Gemini 4 Neon (High) in Antigravity with tool use (shell, file
editing, test execution).

## Checklist

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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-30 14:44:08 +00:00
Tonio 429a004da5 Honor device sign-in expiry during onboarding (#23270)
## Thinking Path

> - Paperclip connects agents to model providers.
> - Onboarding starts a device login for OpenAI.
> - The login starts its session clock before it acquires a sandbox.
> - The command must stop by the deadline shown for the session.
> - The wizard can then offer a fresh code when that session expires.

## Linked Issues or Issue Description

**Subsystem affected**

Subscription onboarding and displayed-code login. Refs #23268.

**Current behavior**

An unattended OpenAI login can show a generic failure at expiry.

**Proposed behavior**

Use the session deadline and show the same expiry message as Claude.
Show “Waiting…” for OpenAI and “Waiting for code…” for Claude.

## What Changed

Bound the command timer to the remaining session lifetime. Arm the host
timer before the command can schedule its own timeout. Keep the outcome
fixed during cleanup. Updated the OpenAI waiting label.

## Verification

All 79 tests in the device login service, runner, and login card suites
passed. These cover delayed sandbox setup, failure before expiry, and
timeout at the deadline.

## Risks

Early command failures still need their own failure state. The change
preserves those failures and explicit cancellation.

## Model Used

OpenAI GPT-6 with Codex repository and test tools.

## Checklist

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

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Post-merge `Cloud readiness` runs the full server test suite with
`--retry=0` before publishing new Core Docker images.
> - Five consecutive `Cloud readiness` runs on `master` failed over 22
hours because two test timeout patterns surfaced under multi-worker CI
shards.
> - First, `issue-activity-events-routes.test.ts` and
`issue-comment-attribution-audit-routes.test.ts` dynamically import
`server/src/routes/issues.ts` inside the first `it()` block, crossing
the 15s `testTimeout` when 5 fork workers simultaneously hit Vite's
transform server.
> - Second, `native-status-arbiter-corpus.test.ts` seeds 103 rows
sequentially in its multi-page drain tests, crossing 60s under 7-worker
shared-Postgres load and causing `afterEach` to time out before
restoring real timers.
> - This pull request moves those module imports into `beforeAll`,
aligns `server/vitest.config.ts` `testTimeout` with `hookTimeout` (30s),
batches the 103-row fixture seeding with bounded concurrency, and guards
timer restoration in `try/finally`.
> - The benefit is green, deterministic post-merge `Cloud readiness`
builds without weakening any test assertion or retry policy.

## Linked Issues or Issue Description

**What happened?**
Five consecutive `Cloud readiness` workflow runs on `master` failed and
cancelled over a 22-hour window, blocking new Core image publication:
- Three runs failed with `Test timed out in 15000ms` on the first test
of `server/src/__tests__/issue-activity-events-routes.test.ts` (twice)
and
`server/src/__tests__/issue-comment-attribution-audit-routes.test.ts`
(once) while dynamically importing `server/src/routes/issues.ts` under
5-worker parallel serialized shards.
- Two runs failed in
`server/src/__tests__/native-status-arbiter-corpus.test.ts` when `drains
more than one reconstruction page without replaying settled reviews`
timed out at `60000ms` during 103 sequential `seedReview()` calls, which
also timed out `afterEach` (`30000ms`) before restoring
`vi.useRealTimers()`.

**Expected behavior**
All server route and native status arbiter tests pass reliably on
post-merge `Cloud readiness` (`--retry=0`) without cold-transform
timeouts or leaked fake timers.

**Steps to reproduce**
1. Run `Cloud readiness` (`release-verify.yml`) on `master` with
`--retry=0` on 8-core runners (`maxWorkers=5` serialized shards,
`maxWorkers=7` general-server shards).
2. Observe cold dynamic imports of `routes/issues.ts` inside `it()`
crossing `15000ms` and the 103-row sequential seed test in
`native-status-arbiter-corpus.test.ts` crossing `60000ms`.

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

## What Changed

- **`server/src/__tests__/issue-activity-events-routes.test.ts`**:
Register module mocks and import `routes/issues.js` and
`middleware/index.js` once in `beforeAll` (30s timeout) instead of
calling `vi.resetModules()` and re-importing on every test; keep full
`vi.clearAllMocks()` and mock defaults reset in `beforeEach`.
-
**`server/src/__tests__/issue-comment-attribution-audit-routes.test.ts`**:
Pre-import `routes/activity.js` and `routes/issues.js` in `beforeAll`
alongside embedded Postgres startup (30s timeout) instead of lazily
importing inside `createApp()` on the first test.
- **`server/vitest.config.ts`**: Increase `testTimeout` from `15000` to
`30000` (matching `hookTimeout` and `teardownTimeout`) so parallel cold
Vite transforms on 5-worker CI shards do not flake the first test in
sibling route suites.
- **`server/src/__tests__/native-status-arbiter-corpus.test.ts`**: Seed
the 103 fixtures in both multi-page drain tests in bounded concurrent
batches of 8, parallelize the final status assertions, allow `30_000ms`
for multi-page `flush()`, and wrap `coordinator?.stop()` in
`try/finally` in both `afterEach` hooks so `vi.useRealTimers()` and
`vi.restoreAllMocks()` always run.

## Verification

- `pnpm --filter @paperclipai/server typecheck` — passed
- `pnpm exec vitest run --project @paperclipai/server
server/src/__tests__/issue-activity-events-routes.test.ts
server/src/__tests__/issue-comment-attribution-audit-routes.test.ts
server/src/__tests__/native-status-arbiter-corpus.test.ts` — passed
(`3/3` files, `189/189` tests; `issue-activity-events-routes.test.ts`
ran in `3.95s` total and test 1 of
`issue-comment-attribution-audit-routes.test.ts` ran in `445ms`)

## Risks

- Low risk: test-only and Vitest timeout configuration changes. No
production server behavior, schema, or API contracts are changed, and no
test assertions or retry policies are weakened.

## Model Used

- Google DeepMind Antigravity (Gemini 3.1 Pro, agentic tool use with
shell verification)

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
2026-11-28 14:06:21 +00:00
DottaandPaperclip c57471459f feat(responsibilities): add routine filter and routine agent avatars (#23159)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The experimental Responsibilities dashboard (`outline_v2`) lists a
person's areas and responsibilities as a clean outline.
> - Today, operators cannot filter the Responsibilities outline by
whether a responsibility has routines, and rows do not show which agents
are assigned to those routines.
> - Operators need a quick visual signal of which responsibilities
already have agent-run routines and a fast way to focus on
responsibilities with or without routines.
> - This pull request adds `routineAgentIds` to `ResponsibilityRollup`,
adds the shared toolbar filter icon with "Has routines" and "No
routines" options (defaulting to either), and displays slightly
overlapping agent avatars on the right side of responsibility rows that
have assigned routines.
> - The benefit is faster scanning of routine coverage across
responsibilities without leaving the outline view.

## Linked Issues or Issue Description

**What existing behavior does this improve?**
The Responsibilities dashboard (`outline_v2` view at
`/<prefix>/responsibilities`) and the `ResponsibilityRollup` response
returned by `GET /api/companies/:companyId/responsibilities`.

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

**Current behavior**
The Responsibilities dashboard header shows only a search box, total
counts, and the New area button. Each responsibility row shows only its
bar sentence or title, with no visual indicator of which agents are
assigned to its routines and no filter to narrow by routine presence.

**Proposed behavior**
The header adds the shared toolbar Filter icon button beside the search
box, opening a popover with "Has routines" and "No routines" options
(both unchecked by default so either is shown) and a Clear action. Each
responsibility row with one or more non-archived routines assigned to
agents displays those agents' avatars slightly overlapping on the right
side of the row (up to 4 avatars with a `+N` overflow indicator and a
tooltip listing agent names).

**Reason and benefit**
Operators scanning their responsibilities need to see at a glance which
responsibilities already have agents running routines and quickly filter
to responsibilities that still need routines set up (or only those with
routines).

**Breaking changes**
Additive field `routineAgentIds: string[]` added to
`ResponsibilityRollup`. Existing callers ignore unknown fields.

## What Changed

- Added `routineAgentIds: string[]` to `ResponsibilityRollup` in
`packages/shared/src/types/responsibility.ts` and refreshed the pinned
hash in `tests/runner-e2e/source-sdk-public-inputs.json`.
- Updated `responsibilityService.computeRollups` and
`buildResponsibilityRollup` in `server/src/services/responsibilities.ts`
to select `routines.assigneeAgentId` (ordered deterministically by title
and id) and deduplicate non-null assignees across non-archived member
routines (direct and project-linked) with no extra queries.
- Added `OutlineV2RoutineFilter` and `filterOutlineV2Groups` in
`ui/src/lib/responsibility-outline-v2.ts`.
- Added the shared toolbar `Filter` icon popover ("Has routines" / "No
routines", default either) and live filtered counts to
`ui/src/pages/Responsibilities.tsx`.
- Updated `ui/src/components/responsibilities/DashboardOutlineV2.tsx` to
filter groups, unfold matching areas while filtered, show an empty-match
state with a Clear filter button, and render slightly overlapping
routine-agent avatars (`size={20}`, `-space-x-1.5`, capped at 4 with
`+N`) on the right side of each row that has routines with assigned
agents.
- Added unit, embedded-Postgres integration, jsdom UI, and Storybook
coverage (`server/src/__tests__/responsibilities-rollup.test.ts`,
`server/src/__tests__/responsibilities.test.ts`,
`ui/src/lib/responsibility-outline-v2.test.ts`,
`ui/src/components/responsibilities/DashboardOutlineV2.test.tsx`,
`ui/src/pages/Responsibilities.outline-v2.test.tsx`, and
`ui/storybook/stories/activity/responsibilities.stories.tsx`).

## Verification

- `pnpm --filter @paperclipai/shared build` — passed.
- `pnpm --filter @paperclipai/server typecheck` — passed (all 7 layers).
- `pnpm --filter @paperclipai/ui typecheck` — passed.
- `pnpm check:token-gates` — passed (all 4 gates clean).
- Focused Vitest suites (194 tests across 10 files) — passed:
  - `server/src/__tests__/responsibilities-rollup.test.ts` (18/18)
- `server/src/__tests__/responsibilities.test.ts` (37/37, embedded
PostgreSQL)
- `server/src/__tests__/responsibility-summaries.test.ts`,
`responsibility-summary-generator.test.ts`,
`responsibility-tools.test.ts`
- `ui/src/lib/responsibilities.test.ts` (41/41),
`responsibility-views.test.ts` (35/35),
`responsibility-outline-v2.test.ts` (15/15)
- `ui/src/components/responsibilities/DashboardOutlineV2.test.tsx` (2/2)
  - `ui/src/pages/Responsibilities.outline-v2.test.tsx` (1/1)
- Manually verified live Storybook preview (`Dashboard view: Outline v2,
routine avatars & filter`) in dark mode across default, "Has routines",
"No routines", and "Clear" states, confirming avatar overlap for 1, 2,
and 3 agents and empty states for rows without routines.
- Note: `pnpm verify` exited with code `2` because
`tests/runner-e2e/source-sdk-public-inputs.json` changed; CI supplies
the full broad suite.

## Risks

- Low risk. `routineAgentIds` is computed from the existing
`memberRoutines` query in `computeRollups` (adding one column selection
and deterministic ordering, no new queries or schema migrations).

## Model Used

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

## Checklist

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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-28 12:53:18 +00:00
Devin Foley 9c1fd24642 fix(secrets): keep a connected account's saved sign-in from being deleted or disabled (#23139)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Agents run with an AI account that a person connects, for example a
personal Claude subscription
> - Paperclip keeps the saved sign-in of a personal account as a value
of a user secret, and that secret shows on the Secrets page
> - A person can delete or disable that secret, or its value in My
secrets, and Paperclip does not stop them
> - Then the connection still shows as healthy, but every agent run that
uses it fails with "Reconnect this AI account"
> - The reconnect also refuses the changed sign-in slot, so the person
cannot repair the account in place
> - This pull request refuses to delete or disable a user secret or its
value while a connected account uses it, and tells the person to
disconnect the account instead
> - The benefit is that a cleanup on the Secrets page cannot silently
stop all agent runs

## Linked Issues or Issue Description

**What happened?**

A user deleted the user secret that holds the saved sign-in of their
personal Claude subscription. The Secrets page did not warn them. After
that, every agent run failed with "Reconnect this AI account"
(`configuration_incomplete`). The connection still showed as healthy and
stayed the default for the provider. When the user tried to reconnect,
Paperclip refused the personal reconnect because the sign-in slot was
changed. The user then added a new company-shared account. Agents that
use "my default" ignore company-shared accounts, so the runs continued
to fail.

**Expected behavior**

Paperclip does not let a person delete or disable a secret that a
connected account uses. The message names the account and tells the
person to disconnect the account instead.

**Steps to reproduce**

1. Connect a personal Claude subscription and make it your default.
2. Open the Secrets page. Find the user secret with the key
`ai_<grantId>`.
3. Disable it or delete it.
4. Assign a task to an agent that uses your default AI account.
5. The run fails with "Reconnect this AI account". The AI account still
shows as healthy.

**Paperclip version or commit**

`master` at c72c468708

**Deployment mode**

Authenticated (hosted)

Related: #19406 (reuses the private sign-in slot when a person
reconnects a removed connection).

## What Changed

- `server/src/services/secrets.ts`: Add `assertNoConnectionSignsInWith`.
It takes a user secret definition or one value. It looks for a
connection that is not archived, or a grant that is not revoked, that
refers to one of the values. If it finds one, it throws a 409 with the
code `secret_used_by_connection` and the connection name.
- Add `withoutConnectionSignIn`. It holds
`withAccountHomeSecretMutationLock` for the company across the check and
the change. A reconnect (`aiConnectionService.save`) holds the same lock
while it rotates the value and reactivates the grant, so a reconnect
cannot land between the check and the change. The lock is re-entrant, so
the nested secret removals share it.
- The check applies to:
- `removeUserSecretDefinition`, and `updateUserSecretDefinition` with
`status: "deleted"`;
- `updateUserSecretDefinition` when the status changes away from
`active` (for example `disabled`);
- `removeCurrentUserSecretValue` (My secrets delete), and
`updateCurrentUserSecretValue` with `status: "deleted"`;
- `updateCurrentUserSecretValue` when the status changes away from
`active`.
- Other changes are not affected, for example a new name or a
reactivation to `active`. The internal disconnect cleanup uses
`secrets.remove` after it revokes the grant, so it does not change.
- The Secrets page already shows the error text in its toast, so the UI
does not change.

## Verification

- New test
`server/src/__tests__/secrets-service-connection-sign-in.test.ts`
(embedded Postgres). It saves a real personal Claude subscription
connection and checks that:
- a delete is refused with 409, names the account, and leaves the secret
and its definition active;
  - a disable is refused, and a rename still works;
- a delete or disable of the value from My secrets is refused, and a
reactivation to `active` still works;
- a delete that waits behind a reconnect is refused when the reconnect
reactivates the grant first;
  - after a disconnect (grant revoked), the delete succeeds.
- Without the change in `secrets.ts`, the refusal tests fail. With only
the first version of the check (outside the lock, definitions only), the
My secrets test and the reconnect-order test fail.
- `pnpm exec vitest run
server/src/__tests__/secrets-service-connection-sign-in.test.ts
server/src/__tests__/secrets-service.test.ts
server/src/__tests__/secrets-service-dangling-user-secret.test.ts
server/src/__tests__/secrets-routes.test.ts
server/src/__tests__/secrets-service-user-secret-owner-scoped.test.ts
server/src/__tests__/antigravity-disconnect-sign-in.test.ts
server/src/__tests__/agent-hire-ai-connections.test.ts
server/src/__tests__/github-catalog-timing.test.ts
server/src/__tests__/tool-gateway.test.ts`: 9 files, 393 tests pass.
- `pnpm --filter @paperclipai/server typecheck` passes.

## Risks

- Low risk. The check only blocks a delete or a disable of a user secret
definition or value. The disconnect flows remove the sign-in through a
different path (`secrets.remove` after the grant is revoked), so they do
not change.
- These deletes and disables now wait for the company's secret mutation
lock. A concurrent secret write can delay them for a short time.
- A person who wants to remove the secret must now disconnect the
account first. This is the intended order.
- This change does not repair a connection whose secret is already gone.
Such a connection still shows as healthy. The owner must disconnect it
and connect the account again.

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

## Model Used

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

## Checklist

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

> - Paperclip is the open source app people use to manage AI agents for
work
> - Each GitHub request to a review bot gets a comment that must end in
a real reply or an honest notice, and stay correct
> - When a run fails with a cause the system continues automatically
(restart class, setup before provider work, recovery runs), a new run
follows within minutes
> - Both settle paths marked the request's comment "This turn stopped
before completing" and final as soon as the failed run ended, so the
continuation's answer never reached that thread
> - On staging, a Ponytail review run failed twice across a deploy; the
automatic retry succeeded three minutes later and updated the PR review
to 5/5, but the inline thread still says "stopped"
> - This pull request makes the request wait, for up to 30 minutes,
while the system's continuation is still expected
> - The benefit is that a recovered task's thread shows its real outcome
instead of a stale failure notice

## Linked Issues or Issue Description

Refs #22672, #23049

**Describe the bug**
A review run failed with `native_continuation_requires_reconciliation`
(twice, across a deploy). The system's automatic retry then succeeded
and updated the PR's main review comment. The inline thread for the
request had already been set to the final notice "This turn stopped
before completing" and was never updated.

**Steps to reproduce**
1. A request's run fails with an error the system continues
automatically.
2. The publication transport (`failRun`) or the terminal sweep settles
the request as "stopped" and final.
3. The automatic continuation succeeds and publishes, but the thread is
final and is not revisited.

**Expected behavior**
The thread waits while the continuation is expected, then shows the
continuation's reply or a link to the latest response; it says "stopped"
only if no continuation comes.

## What Changed

- `response-run-state.ts`: `responseRunColumns` adds
`continuesAutomatically` (the existing `continuesAutomaticallySql`),
read in the same statements as the rest of the run state.
- `response-execution.ts`: `awaitsAutomaticContinuation(run,
latestRun)`: the failed run continues automatically, is still the task's
latest run, and ended under 30 minutes ago
(`GITHUB_CONTINUATION_WAIT_MS`). While true the outcome is `waiting`,
and the result carries `awaitingContinuation`.
- `terminal-response-work.ts`: such a request is not parked, so the
sweep reads it again on later passes.
- `chat-github-response-comments.ts`: `failRun` defers with a conflict
while the continuation is awaited; once a newer run exists it is refused
as before and the sweep settles the request.

## Verification

- New test `waits for the automatic continuation of a failed GitHub
request run` (recent): fails on master (the thread says "stopped"),
passes here: `failRun` defers, the sweep keeps "Working on this…", then
the continuation and a newer response settle it with the link. Second
case (failure 31 minutes old) still settles "stopped".
- Updated `reconciles a GitHub working comment when execution stops
without a publication` to a failure older than the wait window, which is
what it tests.
- GitHub chat integration suites (response maintenance, finding threads,
workflow, retry and recovery, publications): 140 passed. Server
typecheck is clean.

## Risks

- A failed run's thread now shows "Working on this…" for up to 30
minutes while a continuation is expected, instead of "stopped" at once.
- Waiting requests are re-read on each sweep pass (bounded by the
30-minute window).

## Model Used

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

## Checklist

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

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 15:09:48 +00:00
DottaandPaperclip c49e80da6c fix(voice): exclude voice transport from tool health sweep and clarify Speko callback opt-in (#23116)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Speko voice connections create a channel-scoped tool connection with
`transport: "voice"` so the assigned agent can call the responsible
person through `call_my_phone`.
> - The background tool-connection health sweep excluded `chat_sdk` and
`runtime_auth` transports, but omitted `voice`.
> - Every 15 minutes, the sweep called `checkConnectionHealth` on active
Speko connections, hit `unsupportedToolConnectionTransport()`, and
overwrote their health state to `error`.
> - In addition, when `call_my_phone` was not present in an agent's
tools for a task, the Speko skill did not explain how to help the user
check Call my phone opt-in, tool access, or task eligibility.
> - This pull request replaces the duplicated negative transport filters
with a single positive `HEALTH_SWEEP_TRANSPORTS` allowlist, repairs
already-corrupted active Speko voice connections in bounded atomic
batches (while preserving real errors), handles `transport: "voice"`
safely in manual `checkConnectionHealth`, and updates the Speko skill
guidance.
> - The benefit is that active Speko voice connections self-heal and
stay healthy instead of degrading into false errors every 15 minutes,
and agents give accurate troubleshooting guidance when `call_my_phone`
is absent.

## Linked Issues or Issue Description

Refs #23052

**Describe the bug**
Active Speko voice connections (`transport: "voice"`) are picked up by
the scheduled tool-connection health sweep after 15 minutes and marked
`healthStatus: "error"` with `"This connection has no supported tool
integration. Add a supported account or MCP connection from
Connectors."`.

**Steps to reproduce**
1. Connect and activate a Speko voice endpoint.
2. Wait 15 minutes for the scheduled tool-connection health sweep (or
call `sweepConnectionHealth({ staleAfterMs: 0 })` /
`scheduledHealth.load(companyId)`).
3. Inspect the Speko `tool_connections` row.

**Expected behavior**
Voice channel connections (`transport: "voice"`) are excluded from the
generic tool-connection health sweep via a shared positive transport
allowlist, previously corrupted active Speko voice rows self-heal
without clearing real errors, and manual health checks do not overwrite
them to `error`.

## What Changed

- Export `UNSUPPORTED_TOOL_CONNECTION_TRANSPORT_MESSAGE` from
`server/src/services/tool-access/catalog/failures.ts`.
- Export `HEALTH_SWEEP_TRANSPORTS`, `healthSweepConnectionWhere()`, and
`repairUnsupportedVoiceConnectionHealth()` in
`server/src/services/tool-access/catalog/health.ts`; use the shared
allowlist in both `sweepConnectionHealth` and
`connectionHealthSchedule.load`.
- Repair active Speko voice connections previously marked with
`UNSUPPORTED_TOOL_CONNECTION_TRANSPORT_MESSAGE` (only when the paired
active Speko endpoint has `last_error IS NULL`), registering health/chat
notifications before the batch update, running once per
`connectionHealthSchedule` instance, and handling `transport: "voice"`
safely in `checkConnectionHealth`.
- Update `server/src/services/voice/speko-skill.ts` so agents check task
eligibility, tool access, and the `Call my phone` (`Allow this agent to
call me about my tasks`) setting when `call_my_phone` is absent.
- Add red-green regression tests in
`server/src/__tests__/tool-access-service.test.ts` (including
`scheduledHealth.load`, `sweepConnectionHealth`, `checkHealth`,
multi-batch repair, and real-error preservation) and
`server/src/__tests__/voice-session-store.integration.test.ts`.

## Verification

- `pnpm --filter @paperclipai/server exec vitest run -t "sweeps enabled
active connection health|repairs active Speko voice connections|delivers
Speko guidance to existing agents"
src/__tests__/tool-access-service.test.ts
src/__tests__/voice-session-store.integration.test.ts` (3 passed)
- `pnpm --filter @paperclipai/server typecheck` (passed, 0 errors across
`below`, `cycle`, `above`, `tests`, `test-tree-0`, `test-tree-1`,
`test-tree-2`)

## Risks

- Low risk: excludes non-tool transports from the generic MCP/REST
health sweep via an explicit allowlist of the four supported transports
(`mcp_remote`, `rest_api`, `local_stdio`, `plugin`), repairs only rows
matching the exact unsupported-transport error message on active Speko
endpoints with `last_error IS NULL`, and refines one sentence of Speko
skill text. No schema migrations or breaking API changes.

## Model Used

- Google Gemini (Antigravity agentic coding assistant with extended
reasoning, tool use, and local command execution)

## Checklist

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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-27 14:47:15 +00:00
DottaandClaude Opus 5.5 f78a6f5ae3 fix(github): a run that ends without its own reply links the latest response (#23111)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Each GitHub request to a review bot gets a comment that must end in
a real reply or an honest, useful notice
> - #22798 made the terminal sweep link the latest response on the same
pull request when a request's own run did not reply
> - A second path settles the same comments: when a run finishes without
a GitHub reply, the publication transport calls `failRun` with a fixed
notice
> - That path never looked for a newer response, so a thread could say
"ended without publishing" while the PR already showed a fresh review
> - This pull request gives `failRun` the same latest-response link
> - The benefit is that both settle paths agree, and readers are pointed
at the review instead of a dead-end notice

## Linked Issues or Issue Description

Refs #22798, #22672

**Describe the bug**
On a pull request the author replied "Fixed in …" on a review bot's
inline finding. The bot re-reviewed and updated the PR's main review
comment to 5/5, then a second run said no new review was needed. The
inline thread settled to "This turn ended without publishing a final
response. See the Paperclip task for details." instead of linking the
updated review.

**Steps to reproduce**
1. An inline request is answered by a run that publishes nothing on
GitHub.
2. A response for the same task and PR was published after the request
arrived.
3. The publication transport settles the run through `failRun` with the
fixed notice.

**Expected behavior**
The thread says "See the latest response" with a link to it.

## What Changed

- `server/src/services/chat-github-response-comments.ts`: for each
request of the run, `failRun` looks up the latest response published for
the task on the same pull request or issue since the request arrived
(`githubLatestTaskResponseUrl`, scoped by base thread) and links it;
otherwise it keeps the given notice.
- New test in `github-review-response-maintenance.integration.test.ts`:
an inline request whose run ends without a reply, with a newer
assessment on the same PR, settles with the link.

## Verification

- New test fails on master ("ended without publishing") and passes here.
- `github-review-response-maintenance`, `github-review-workflow`,
`github-retry-and-recovery` integration suites and the response-comment
unit tests: 99 passed. Server typecheck is clean.

## Risks

- One indexed lookup per request when a run settles without a reply; it
reuses the same query and index as the terminal sweep.

## Model Used

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

## Checklist

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

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 14:31:51 +00:00
DottaandClaude Opus 5.5 7d850ad65e fix(github): a superseded automatic review finishes instead of asking a person (#23064)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - GitHub review bots run automatic reviews for a specific pull request
head
> - When the head has moved on, the review tools refuse the stale review
and explain why
> - That explanation said "an authorized person can request a manual
review", so an agent can read it as a blocker owned by a person
> - On staging, a review task recovered for an already-merged PR did
exactly that: it marked itself blocked and asked the PR author to
request a review
> - This pull request makes the refusal say the review is no longer
needed and that the task should finish as done
> - The benefit is that stale or merged-PR reviews close cleanly instead
of waiting on a person

## Linked Issues or Issue Description

Refs #23049

**Describe the bug**
A review-bot task for a PR merged three days earlier was continued by
the lost-wait recovery (#23049). Its automatic review targeted the PR's
old head. The review tool refused with "no newer automatic review is
queued for it. An authorized person can request a manual review", and
the agent blocked the task, naming the PR author or a maintainer as
owner.

**Steps to reproduce**
1. An automatic review request targets head A of a pull request.
2. The pull request moves to head B (or is merged) with no newer
automatic review queued.
3. The agent calls a review tool; the refusal tells it a person can
request a manual review, and the agent blocks the task.

**Expected behavior**
The agent finishes the task as done; a merged or closed pull request
needs no review, and nothing waits on a person.

## What Changed

- `server/src/services/chat-github-reviews.ts`:
`supersededAutomaticReview` receives the pull request. For a closed or
merged PR the refusal says no review is needed; otherwise it says the
review is no longer needed (or that a newer automatic review is queued).
In every case it tells the agent to finish the task as done and not to
block it or ask anyone to request a review. The error details add
`pullRequestClosed`.
- Test in `github-review-publications.integration.test.ts` for a closed
and an open pull request whose head moved.

## Verification

- New test (`tells a superseded automatic review to finish instead of
waiting on a person`, closed and open): fails on master (the old message
asks for a person), passes here.
- `github-review-publications` and `github-review-workflow` integration
suites: 39 passed. Server typecheck is clean.
- After deploy: a recovered review for a merged PR should finish as done
instead of blocking.

## Risks

- Wording change for one refusal; the reason code and retryability are
unchanged.

## Model Used

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

## Checklist

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

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 12:56:25 +00:00
DottaandPaperclip 2caedfe7b0 feat(voice): support outbound call messages, issue transcripts, and optional setup test for Speko (#23052)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The Speko voice connection lets agents call a person's saved phone
number via `call_my_phone` and receive inbound phone calls that create
or continue tasks.
> - Outbound `call_my_phone` took no parameters, so the agent could not
speak a specific update or question when the person picked up, and
outbound call transcripts were not projected onto the bound issue.
> - Setup also blocked activation behind a mandatory two-turn browser
microphone test and failed with HTTP 400 when a Speko persona used a
cascade-only voice on `runMode: "s2s"`.
> - This pull request adds an optional `message` parameter to
`call_my_phone`, projects outbound and inbound phone call transcripts
onto the bound issue, derives inbound task titles from the caller's
request, falls back to a supported S2S voice on 400, and lets verified
Speko setups finish without a browser microphone test.
> - The benefit is that both agent-initiated phone updates (with
responses recorded in the issue) and inbound phone tasks work end-to-end
with reliable setup and full issue transcript visibility.

## Linked Issues or Issue Description

**What existing behavior does this improve?**
Speko voice connection setup (`POST
/api/chat-endpoints/:endpointId/finish`, `ChatEndpointSetup`), outbound
agent phone callbacks (`call_my_phone`), outbound/inbound phone
transcript projection (`voiceCallReports`), and incoming low-trust task
creation (`voiceInboundService`).

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

**Current behavior**
- `call_my_phone` accepts no arguments (`properties: {}`) and always
opens with `"Hi, this is your Paperclip agent calling as requested. Is
now a good time?"`.
- Outbound `call.pre_call` sets `idleRePrompts` to `"I'm still working
on it."` every 10 seconds.
- `voiceCallReports.projectTranscript` only writes the transcript
document onto issues for `guest_intake` sessions, omitting authenticated
outbound and inbound phone calls.
- Incoming `guest_intake` tasks always use the generic title `"Incoming
phone conversation"`.
- Activating a Speko connection requires completing a two-turn browser
microphone conversation before **Call my phone** and **Incoming calls**
settings become accessible.
- `configureVoiceDefaults` fails with HTTP 400 if the selected Speko
persona uses a cascade-only voice when switching to `runMode: "s2s"`.

**Proposed behavior**
- `call_my_phone` accepts an optional `message` string (1–2000 chars)
while still strictly rejecting recipient/phone arguments. Speko speaks
`message` immediately as `firstMessage` and instructs the voice model to
submit caller replies via `submit_request`.
- Outbound `call.pre_call` uses a 25-second conversational check-in
re-prompt instead of `"I'm still working on it."`.
- `voiceCallReports.projectTranscript` writes `"Outbound phone call
transcript"` / `"Phone conversation transcript"` onto the bound issue
for all phone calls (`outbound_phone` and `inbound_phone`), preserving
quarantine guards for `guest_intake`.
- Incoming `guest_intake` tasks derive a readable title from the
caller's first spoken request.
- Verified Speko connections can finish setup via `POST
/api/chat-endpoints/:endpointId/finish` (**Skip test & finish**) without
requiring a browser microphone test.
- `configureVoiceDefaults` falls back to S2S voice `"marin"` if Speko
returns HTTP 400 on `runMode: "s2s"`.

**Reason and benefit**
Makes both core phone workflows usable in production: agents can call an
opted-in person to deliver a concrete update and capture their spoken
response in the issue, callers can phone an agent to start a titled
task, and operators can complete Speko setup without a microphone or
cascade-voice failure.

**Breaking changes**
None. `message` is optional on `call_my_phone` so `{}` callers remain
compatible; existing recipient restrictions (`additionalProperties:
false`) and quarantine boundaries are preserved.

## What Changed

- Added optional `message` parameter to `call_my_phone` in
`server/src/services/voice/speko-agent-tools.ts`, threaded
`openingMessage` into `voice-session-service.ts`, `voice-prompts.ts`
(`buildOutboundPhoneVoicePrompt`), and `speko-provider.ts`
(`createPhoneSession`), and updated `speko-skill.ts`.
- Extended `voiceCallReports.projectTranscript` in
`server/src/services/voice/voice-call-reports.ts` to project phone call
transcripts onto the bound issue for `outbound_phone` and
`inbound_phone` sessions while keeping `guest_intake` quarantine
enforcement intact.
- Derived readable issue titles from the first `submit_request` text for
incoming `guest_intake` calls and refined outbound `call.pre_call`
`idleRePrompts` in `server/src/services/voice/voice-inbound-service.ts`.
- Added S2S voice fallback (`voice: "marin"`) on HTTP 400 in
`speko-provider.ts` (`configureVoiceDefaults`).
- Enabled optional test skip (`POST
/api/chat-endpoints/:endpointId/finish`) for verified Speko endpoints in
`server/src/services/chat-channels/setup-probes.ts` and added a **Skip
test & finish** button in
`ui/src/pages/apps/chat/ChatEndpointSetup.tsx`.
- Updated `packages/shared/src/app-definitions/speko.json` guidance
copy.
- Added unit and real-Postgres integration regressions in
`server/src/__tests__/speko-provider.test.ts` and
`server/src/__tests__/voice-session-store.integration.test.ts`.

## Verification

- `pnpm --filter @paperclipai/shared build && pnpm --filter
@paperclipai/server typecheck && pnpm --filter @paperclipai/ui
typecheck` — passed (0 errors across server layers and UI).
- `pnpm exec vitest run server/src/__tests__/speko-provider.test.ts
server/src/__tests__/speko-protocol.test.ts
server/src/__tests__/speko-call-report.test.ts
server/src/routes/voice-sessions.auth.test.ts` — 53/53 passed.
- `pnpm exec vitest run
server/src/__tests__/voice-session-store.integration.test.ts` — 133/133
passed (including new `call_my_phone` message + outbound transcript
projection, derived inbound title, and Speko finish-without-test
regressions).
- `pnpm exec vitest run ui/src/api/voiceSessions.test.ts
ui/src/components/voice/ ui/src/lib/voice-call-attempt.test.ts
ui/src/lib/voice-session-controller.test.ts
ui/src/lib/voice-transcript.test.ts
server/src/__tests__/chat-channels/slack-setup-and-registration.integration.test.ts`
— 161/161 passed.
- `pnpm run check:token-gates` — all 4 gates clean.
- Live local verification against Speko API + webhook-only Cloudflare
quick tunnel: verified Speko setup + `/finish` activation, live
`claude_local` MCP discovery of `call_my_phone` with `message`, live
Speko session create/inspect/end + signed `call.status`/`call.report`
callbacks through tunnel, and inbound `call.pre_call` + `submit_request`
creating a titled task.

## Risks

- Low risk. Additive optional schema field on `call_my_phone` (still
rejects unknown keys such as `to`). No database migrations required.
Transcript projection for authenticated calls writes only to the
session's bound issue under the existing per-session advisory lock. Live
PSTN audio still requires real-phone end-to-end confirmation after
staging rollout.

## Model Used

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

## Checklist

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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-27 06:52:33 -06:00
635ed5a364 fix(skills): start skill package transfer deadlines after the I/O queue admits them (#22615)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Before a run starts, Paperclip copies each selected skill version
from skill package storage into a local cache.
> - Skill package reads share small I/O queues for each process. Each
queue has 2 active permits and 32 waiting slots.
> - Each read started its 180-second deadline before it waited for a
permit. A read that waited behind other transfers used up its deadline
in the queue.
> - On a busy host, a run then failed before its agent started with
"Failed to materialize the selected skill version: The operation was
aborted due to timeout". The next run did the same cold read and failed
the same way.
> - This pull request starts each transfer deadline when the queue
grants the permit.
> - The benefit is that a cold skill read under load waits for its turn
and then gets its full transfer deadline.

## Linked Issues or Issue Description

**What happened?**
A staging host had a burst of 21 run failures in 15 minutes. All runs
were in one company, and each failed with "Failed to materialize the
selected skill version: The operation was aborted due to timeout". The
runs woke at the same time after a provider usage limit reset. The skill
cache was cold.

**Expected behavior**
A run that waits for a skill package I/O permit gets the full 180-second
deadline for its own transfer. Time spent in the queue must not count
against that deadline.

**Steps to reproduce**
1. Make the skill package cache cold for three companies.
2. Stall the archive reads of two companies, so that they hold both
storage permits.
3. Resolve the runtime skills of the third company. Its reads now wait
in the queue.
4. Wait longer than the transfer deadline, then release the stalled
reads.
5. On `master`, the third company's skill resolves as missing with the
timeout message. Its own transfer would take milliseconds.

**Paperclip version or commit**
`master` at 7a2ee0da1c.

## What Changed

- `withPackageIo` now creates the transfer deadline after it grants the
permit, and gives the action that signal. A queued wait stops only when
the caller cancels.
- Manifest loads, isolated package reads, warm package materialization,
durable verification, cached version reads and single-file reads no
longer start a deadline before they queue. Each transfer still has the
same 180-second deadline.
- The cold-response permit gets no deadline of its own. That permit only
bounds decoded responses until cleanup. The storage transfer inside it
still has its deadline.
- An isolated read now gives its consumer the transfer signal. The
cached file reads inside that consumer use it.
- Package uploads (`prepare`) are not changed.
- Added the regression test `starts package transfer deadlines after
queued storage waits`.

## Verification

- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/skill-package-store.test.ts -t "starts package transfer
deadlines"`
  - With this change: passes.
- With `master`'s `skill-package-store.ts`: fails. The skill resolves as
missing with "Failed to materialize the selected skill version: The
operation was aborted due to timeout".
- Related suites: `skill-package-store`, `skill-package-upload`,
`skill-version-cache`, `skill-version-retention`, `runtime-skill-cache`,
`company-skills-runtime-concurrency`,
`company-skills-runtime-selection`, `managed-skill-content`,
`skill-repository-package`, `skill-version-cache-lock`,
`skill-package-work`, `skill-package-storage-migration`,
`skill-package-storage-migration-postgres` and `skill-package-recovery`.
235 of 236 tests pass.
- The only failure is `bounds and validates archives, binaries, paths,
executable modes, and corruption`. It also fails on unchanged `master`
in the same sandbox, because the sandbox `umask` is `077`. It is not
related to this change.
- A timing probe with 20 concurrent cold resolves in one company and 4
other cold companies failed on `master` and passed with this change.

## Risks

- A queued read can now wait longer before it fails. The wait is still
bounded, because each queue has at most 32 waiting reads and every
active transfer has its own deadline. A full queue still returns "Skill
package storage is busy; retry shortly." immediately.
- After a cold fill is published, cache trimming is no longer bounded by
the fill's deadline. Trimming keeps its own 10-second limit, and each
storage check inside it has its own transfer deadline.
- If a manifest read times out, the store now tries the saved legacy
contents or the restore recipe before it fails. Before, the timeout
stopped it before those fallbacks. Both fallbacks are already
authoritative sources for the same manifest.
- Low risk otherwise. The change is limited to `skill-package-store.ts`.

## Model Used

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

## Checklist

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

Related: #22310 changes `skill-package-runtime.ts` and the same test
file. It does not change these deadlines.

🤖 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-11-27 07:08:10 +00:00
DottaandClaude Opus 5.5 1480f716c9 test(recovery): pin the 7-day window for chat setup failures; reattach listSuspects docs (#23063)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The assigned-work sweep now continues a blocked chat-channel task
whose latest run failed in setup before provider work (#23059)
> - Review on #23059 left three non-blocking points: the 7-day run-age
limit had no test, the `listSuspects` doc comment was separated from its
function, and the rule has SQL and TypeScript twins
> - This pull request adds the missing boundary test and restores the
doc placement
> - The benefit is that widening or removing the age limit now fails a
test, and the code reads as it did

## Linked Issues or Issue Description

Refs #23059, #23051

**Describe the bug**
Review follow-up, no user-visible bug. The 7-day limit on how old a
setup failure may be for a chat task to continue automatically had no
test, so a regression that widened or removed it would pass. The
`listSuspects` doc comment was split from `listSuspects` by a new
helper.

**Steps to reproduce**
1. Remove the run-age condition from `latestRunFailedBeforeProviderWork`
and `chatFailedBeforeProviderWork`.
2. The existing tests still pass.

**Expected behavior**
A test fails when the 7-day limit is removed.

## What Changed

- `assigned-work-invariant.test.ts`: a recently blocked chat task whose
setup failure ended 8 days ago is not a sweep suspect and is judged a
conversation wait. The test helper takes an optional `blockedAgoMs` so
the block can be recent while the run is old.
- `assigned-work-sweep.ts`: the `listSuspects` pre-filter doc comment
sits directly on `listSuspects` again; the SQL predicate's comment names
its TypeScript twin and the test that covers both.

## Verification

- `assigned-work-invariant.test.ts`: 35/35 pass. With the age condition
removed from both twins, the chat setup-failure test fails (checked),
then passes again with it restored.
- Server typecheck is clean.

## Risks

- Test and comment changes only; no behavior change.

## Model Used

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

## Checklist

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

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 17:21:06 +00:00
DottaandClaude Opus 5.5 4a9ecd3aca fix(recovery): continue blocked chat tasks whose run failed before provider work (#23059)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The assigned-work sweep continues open agent tasks that have nothing
running and do not wait on a person
> - #23051 made a setup failure before provider work continue
automatically. Two review tasks on staging stayed blocked after it was
deployed.
> - Both tasks come from a chat channel (GitHub review bots). The sweep
treats every chat-channel task as "waiting on a person's next message".
It leaves these tasks out of its suspect list and gives them the
`conversation` waiting reason.
> - The agent never got the message, because its only run failed in
setup before provider work. So the task waits on the system, not on a
person.
> - This pull request lets the sweep judge a blocked chat-channel task
like any other task when its latest run failed in setup before provider
work.
> - The benefit is that these review tasks continue without a Retry, and
so do the two tasks on staging.

## Linked Issues or Issue Description

Refs #23051

**What happened?**
After #23051 was deployed to staging, two GitHub review tasks stayed
`blocked` with no new run. The sweeps ran, and other blocked tasks were
continued. Each task's only run was legacy, failed with `setup_failed`
during environment lease acquisition, and recorded `executionRecovery: {
kind: "bootstrap", providerWorkStarted: false }` about 43 hours earlier.
The tasks have `originKind: "chat_channel"`.

**Expected behavior**
The sweep continues a blocked task whose run failed before provider
work, with bounded backoff, also when the task comes from a chat
channel.

**Steps to reproduce**
1. Create a chat-channel task assigned to an agent. Its only run fails
with `setup_failed` before provider work. Block the task, with or
without a board recovery hold.
2. Run the assigned-work sweep.
3. Before this change, `listSuspects` does not return the task.
`evaluateAssignedWork` returns `waiting: conversation`, and no
continuation is queued.

## What Changed

- `server/src/services/recovery/assigned-work-sweep.ts`:
- The suspect pre-filter still leaves chat-channel tasks out, except a
blocked one whose latest run (by its assignee) failed in setup before
provider work within the last 7 days
(`latestRunFailedBeforeProviderWork`).
- The facts loader no longer marks such a task as a conversation
(`chatFailedBeforeProviderWork`, the TS twin). The latest-run read now
also carries `executionRecovery`.
- Agent chat conversations (`conversationAgentId`) are unchanged. Chat
tasks whose agent may have started work still wait for their
conversation.
- Retry limits do not change. The per-task continuation allowance, the
process-wide repair budget, and the company-wide automatic run brake
apply as for every other sweep continuation.

## Verification

- New red/green test in
`server/src/__tests__/assigned-work-invariant.test.ts`: "continues a
chat-channel task blocked by a legacy setup failure before provider
work, with or without a hold". It uses the staging run shape: legacy,
`setup_failed`, the same `resultJson` keys, the only run, about 43 hours
old. Before the fix it failed (the tasks were not sweep suspects). After
the fix, both the held task and the unheld task are continued. A chat
task whose provider work may have started still waits (`conversation`),
and an in-progress chat task is not a suspect.
- In the same test, with the real heartbeat wake queue, the continuation
of a held chat task is admitted as a new `issue_continuation_needed`
run.
- `npx vitest run src/__tests__/assigned-work-invariant.test.ts`: 35/35
pass.
- `tsc --noEmit` for `server` passes.

## Risks

- The sweep now acts on some chat-channel tasks. The scope is narrow:
the task is blocked, its latest run is its assignee's and failed in
setup before provider work, and the run ended in the last 7 days.
Retries stay bounded by the existing per-task allowance and the
company-wide brake.
- After deploy, chat tasks blocked this way in the last 7 days are
continued. The repair budget and the brake pace them.

## Model Used

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

## Checklist

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

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

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 17:05:39 +00:00