mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-05 06:03:51 +01:00
27a32e77f53cd4592eff052b80bc7455ff22d813
3462
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
7b46abae38 |
Merge remote-tracking branch 'origin/master' into claude/local-board-operator-capability
* origin/master: (129 commits) feat(connections): add LinkedIn REST connector (v1 personal posting) (#23388) fix(ui): keep Composio connect navigation from closing back to /apps (#23845) build(deps): bump actions/checkout from 4.2.2 to 7.0.1 (#19561) fix(ui): remove environment selector from AI connection setup (#23836) perf(db): add partial indexes for chat_actions run publications and pending work (#23811) fix(slack): align form publication wait backoff with enrollment deadlines (#23819) fix(ui): hide monitor waiting notices during active runs (#23822) Keep answered chat turns settled across later status changes (#23815) test: fix CLI bind races and SSH fixture input (#23830) build(deps-dev): bump @types/node from 24.13.3 to 24.19.2 in /packages/plugins/sandbox-providers/daytona (#19564) fix(telemetry): emit missing server telemetry across native, onboarding, and routine paths (#23297) fix(server): avoid ServerResponse MaxListenersExceededWarning in stream pipelines (#23810) perf(runner,native-runtime): silence AJV format warnings, cache validators, and retain released catalogs (#23812) fix(server): add exponential backoff to MCP cloud sync workers (#23821) perf(github): fix inherited review wait join and batch lookup plan (#23817) Require saved requests for human-owned blockers (#23820) fix(queue): let the person who declined a connection discard its queued notice (#23699) fix(adapters): find Windows ACP commands through PATHEXT (#14441) chore(deps): keep @cloudflare/sandbox on 0.x in Dependabot (#23818) fix(adapters): mount skill sources in the local workspace sandbox (#14340) ... # Conflicts: # tests/runner-e2e/source-sdk-public-inputs.json |
||
|
|
83d80b431b |
perf(db): add partial indexes for chat_actions run publications and pending work (#23811)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - External chat connectors (GitHub, Slack, Telegram, voice) store
webhook ingress, publication receipts, and scheduled background work in
`chat_actions`
> - On large instances (~325k rows in `chat_actions`, mostly processed
`github_webhook_ingress`), two hot query families fall back to full
sequential scans because existing partial indexes do not cover their
predicates
> - `githubRunReplyState` queries `kind = 'github_review_publication'`
across all statuses (including unsettled
`received`/`processing`/`failed` rows), so PostgreSQL cannot use
`chat_actions_github_task_publications_idx` (`WHERE kind =
'github_review_publication' AND status = 'processed'`)
> - Scheduled work polling (`nextChatActionAt`, `dueChatAction`, and
pending GitHub publication/response sweeps) filters active non-terminal
statuses (`received`, `processing`, `queued`, etc.) and retryable
failures across kinds that have no matching partial work index
> - This pull request adds two concurrent, idempotent, online-compatible
partial indexes on `chat_actions`
(`chat_actions_github_run_publications_idx` and
`chat_actions_pending_work_idx`) and adds PostgreSQL `EXPLAIN (ANALYZE,
BUFFERS)` regression coverage
> - The benefit is eliminating repeated full-table sequential scans on
`chat_actions` without locking writes during migration or altering query
semantics
## Linked Issues or Issue Description
**What happened?**
On a PostgreSQL instance with ~325k `chat_actions` rows (mostly
processed `github_webhook_ingress`), `chat_actions` incurred ~103 full
sequential scans per 5 seconds (20.6 scans/s):
- `githubRunReplyState` (`server/src/services/chat-run-publications.ts`)
ran a `Parallel Seq Scan on chat_actions` (218.6 ms, 100,595 shared
buffer hits for 1 row) because
`chat_actions_github_task_publications_idx` restricts `status =
'processed'` while `githubRunReplyState` must also inspect unsettled
rows.
- Scheduled action polling (`nextChatActionAt` and `dueChatAction` in
`server/src/services/chat-action-work.ts`, plus
`nextPendingAt`/`processPending` in
`server/src/services/chat-github-reviews.ts` and
`server/src/services/chat-github-response-comments.ts`) ran full
sequential scans (62.4 ms, 25,212 shared buffer hits) because no partial
work index covered `status IN ('received', 'processing', ...) OR (status
= 'failed' AND result->>'retryable' = 'true')` by `kind`. (Existing
`review-check-work.ts` and `acknowledgement-work.ts` do not include
`'processing'` and already use `chat_actions_github_check_work_idx` and
`chat_actions_github_ack_work_idx`.)
**Expected behavior**
PostgreSQL should resolve `githubRunReplyState` and scheduled
`chat_actions` work polling through small partial indexes in
sub-millisecond time with minimal shared buffer hits and zero full
sequential scans over completed webhook history.
**Steps to reproduce**
1. Populate `chat_actions` with ~10k+ processed `github_webhook_ingress`
and `github_review_publication` rows plus active target rows, then run
`VACUUM ANALYZE chat_actions`.
2. Run `EXPLAIN (ANALYZE, BUFFERS)` on `githubRunReplyState(...)` and on
`nextChatActionAt(db, "github_webhook_ingress")` /
`dueChatAction("github_webhook_ingress")`.
3. Observe full `Seq Scan on chat_actions` scanning all table pages
before this migration.
**Paperclip version or commit**
`master` (`6a5dfc0288`)
**Deployment mode**
Self-hosted server
## What Changed
- Added `chat_actions_github_run_publications_idx` in
`packages/db/src/schema/chat_channels.ts` on `(company_id, endpoint_id,
(payload->'session'->>'issueId'), (payload->'session'->>'runId')) WHERE
kind = 'github_review_publication'`.
- Added `chat_actions_pending_work_idx` in
`packages/db/src/schema/chat_channels.ts` on `(kind, created_at, id)
WHERE status IN ('received', 'processing', 'queued',
'provider_confirmed', 'admitting', 'resolving', 'validating',
'dispatching') OR (kind = 'failed_run_retry' AND status IN ('issued',
'processing')) OR (status = 'failed' AND result->>'retryable' =
'true')`. (Excludes permanently `'issued'` kinds such as
`task_control_authorization` and completed/cancelled/non-retryable
history so the index stays minimal at rest.)
- Generated migration
`packages/db/src/migrations/0516_exotic_spectrum.sql` with idempotent
`CREATE INDEX CONCURRENTLY IF NOT EXISTS`, registered it in
`MIGRATIONS_WITH_TOP_LEVEL_STATEMENTS` in `packages/db/src/client.ts`,
and pruned schema snapshots to the 5 newest (`0512`–`0516`).
- Extended `server/src/__tests__/chat-admission-condition.test.ts` with
embedded PostgreSQL regression coverage verifying result behavior and
`EXPLAIN (ANALYZE, BUFFERS)` partial index usage (zero `Seq Scan` on
`chat_actions`) for `githubRunReplyState`, every `ScheduledChatAction`
in `CHAT_ACTION_QUEUES` (`nextChatActionAt`), `dueChatAction`
(`github_webhook_ingress`, `failed_run_retry`),
`githubChatReviewService.nextPendingAt`/`processPending`,
`githubResponseCommentService.processPending`, and
`speko_voice_reply_push` (`dispatching`).
## Verification
- Local red/green `EXPLAIN (ANALYZE, BUFFERS)` against embedded
PostgreSQL 18 with 10,003 `chat_actions` rows (8,000 processed
`github_webhook_ingress`, 1,000 processed `github_review_publication`,
500 processed `inbound_wakeup`, 500 issued `task_control_authorization`,
3 target rows) with strict result equality verified before and after
applying the concurrent partial-index migration SQL (and verified 2x
idempotent replay + `indisvalid = true`, `indisready = true`, index
sizes 152 kB and 16 kB):
| Query | Before | After (`0516`) |
| --- | --- | --- |
| `githubRunReplyState` | `Seq Scan` (0.900 ms, 2,204 buffer hits) |
`Index Scan(chat_actions_github_run_publications_idx)` (0.018 ms, 7
buffer hits) |
| `nextChatActionAt(github_webhook_ingress)` | `Seq Scan` (1.169 ms,
2,200 buffer hits) | `Bitmap Index Scan(chat_actions_pending_work_idx)`
(0.011 ms, 2 buffer hits) |
| `nextChatActionAt(provider_effect)` | `Seq Scan` (0.891 ms, 2,200
buffer hits) | `Index Scan(chat_actions_pending_work_idx)` (0.005 ms, 1
buffer hit) |
| `nextChatActionAt(failed_run_retry)` | `Index
Scan(chat_actions_company_issue_kind_idx)` (0.028 ms, 11 buffer hits) |
`Index Scan(chat_actions_pending_work_idx)` (0.006 ms, 2 buffer hits) |
| `nextChatActionAt(slash_task_start)` | `Seq Scan` (0.839 ms, 2,200
buffer hits) | `Index Scan(chat_actions_pending_work_idx)` (0.007 ms, 1
buffer hit) |
| `dueChatAction(github_webhook_ingress)` | `Seq Scan` (1.148 ms, 2,200
buffer hits) | `Bitmap Index Scan(chat_actions_pending_work_idx)` (0.010
ms, 2 buffer hits) |
| `chat-github-reviews.nextPendingAt()` | `Seq Scan` (0.807 ms, 2,200
buffer hits) | `Index Scan(chat_actions_pending_work_idx)` (0.004 ms, 2
buffer hits) |
- Verified prepared-statement execution (`PREPARE` + 10 `EXECUTE` runs)
keeps custom partial-index plans on the 10th execution (`0.004–0.010
ms`) and does not regress `githubLatestTaskResponseUrl`
(`chat_actions_github_task_publications_idx`) or `review-check-work`
(`chat_actions_github_check_work_idx`).
- Ran local checks on commit `97f0f7294262aa129dd283072108ce6932f3a447`:
- `pnpm --filter @paperclipai/db build` — PASS
- `pnpm --filter @paperclipai/db check:migrations` — PASS (1 new
migration, `online_compatible`, none blocked)
- `pnpm check:module-boundaries` — PASS
- `node scripts/check-test-budget.mjs --base origin/master` — PASS (113
nightly suites validated, 1 test file checked)
- `pnpm --filter @paperclipai/db typecheck` & `pnpm --filter
@paperclipai/server typecheck` — PASS
- `pnpm exec vitest run packages/db/src/check-migration-safety.test.ts
packages/db/src/migration-compatibility.test.ts
packages/db/src/migration-snapshot-drift.test.ts
server/src/__tests__/chat-admission-condition.test.ts` — 4 files, 149
tests passed
## Risks
- Low risk: purely additive migration creating two partial indexes with
`CREATE INDEX CONCURRENTLY IF NOT EXISTS` in
`MIGRATIONS_WITH_TOP_LEVEL_STATEMENTS`. Writes are not blocked during
index build, existing indexes
(`chat_actions_github_task_publications_idx`,
`chat_actions_github_check_work_idx`,
`chat_actions_github_ack_work_idx`) remain untouched, and previous
releases continue serving safely during rolling deploy.
- Small write-amplification trade-off: active `chat_actions` rows enter
`chat_actions_pending_work_idx` while non-terminal and leave once
settled; `chat_actions_github_run_publications_idx` tracks
`github_review_publication` rows only (excluding high-volume
`github_webhook_ingress` history).
## Model Used
- Gemini 4 Neon (Google DeepMind, XHigh reasoning, 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
- [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>
|
||
|
|
84ca111c78 |
fix(slack): align form publication wait backoff with enrollment deadlines (#23819)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Slack chat channels deliver interactive question forms that depend on Cloud events and form-owner enrollment before Paperclip posts the prompt. > - When enrollment is pending and backed off for 60s to 300s, `createSlackFormPublicationStage` returns a hardcoded `retryAfterMs: 2_000` wait instead of reading the enrollment `nextAttemptAt` deadline. > - That hardcoded 2-second wait makes the publication worker claim leases, run 20 to 30 SQL queries, emit `chat publication failed` warnings every few seconds, and keep `chat_endpoint_leases` hot while blocking idle sleep. > - This pull request derives the publication wait delay from the pending `slackCloudIntent` or `slack_form_owner` deadline (bounded to `[2_000 ms, 300_000 ms]`), clears waiting publication deadlines and notifies `chatPublications` whenever enrollment commits, retires, or enters `attention`, rechecks wait state via a shared predicate inside a savepoint (`FOR SHARE NOWAIT`) in the deferral transaction, and logs pre-send waits at debug level. > - The benefit is cutting a 5-minute enrollment wait from ~100–150 publication/lease cycles to 1 while preserving immediate wake on early enrollment completion or attention settlement. ## Linked Issues or Issue Description **What happened?** A Slack form publication waiting on `form_publication_enrollment_pending` loops every ~2–3 seconds and logs `chat publication failed` warnings continuously while enrollment is backed off for up to 300 seconds. Each tick claims and deletes `chat_endpoint_leases`, writes `chat_publications`, and prevents the worker from going quiet. **Expected behavior** A Slack form publication waiting on pending enrollment schedules its `nextAttemptAt` to match the pending `slackCloudIntent.nextAttemptAt` or `slack_form_owner.result.nextAttemptAt` deadline (with a 2-second floor for past/due deadlines and a 300-second cap), emits a debug log rather than a failure warning, and wakes immediately when enrollment commits early, retires, or transitions to `attention`. **Steps to reproduce** 1. Configure a Slack endpoint with managed Cloud forms and a pending `slackCloudIntent` or staged `slack_form_owner` backed off 60s–300s in the future. 2. Create an `ask_user_questions` interaction with a Slack form prompt (`question_form_open`) on an active Slack conversation. 3. Run the `chatPublications` delivery worker and observe `chat_publications.next_attempt_at` and server logs. **Paperclip version or commit** Reproduced on `master` prior to `0c0cd68c711da5ebdb0cbaf5a2d54bc96faca7c4`. **Deployment mode** Self-hosted server ## What Changed - **`server/src/services/chat-channels/slack/form-publication.ts`**: Extract single-source-of-truth `pendingIntentDeadline` and `pendingOwnerDeadline` helpers used by both the main readiness gate and the `stillWaiting(tx)` recheck. Compute `retryAfterMs` from the actual pending deadline clamped to `[2_000 ms, 300_000 ms]`. Use `FOR SHARE NOWAIT` in `stillWaiting(tx)` so the recheck never blocks on concurrent enrollment updates. - **`server/src/services/chat-channels/publications/preparation.ts` & `publications/failures.ts`**: Extend `ChatPublicationPreparationWait` with an optional platform-agnostic `stillWaiting?: (tx: DbTransaction) => Promise<boolean>` callback. Execute `stillWaiting` inside a PostgreSQL savepoint (`tx.transaction(...)`): if `stillWaiting` returns `false`, commit `nextAttemptAt = null` so an enrollment commit racing deferral wakes immediately; if `stillWaiting` hits lock contention (`NOWAIT`) or a transient error, roll back only the savepoint and commit `state = "retry"` with a `<= 2_000 ms` fallback so a benign pre-send wait can never stay `streaming` and become `delivery_unknown`. Log `waitingBeforeSend` deferrals at `logger.debug(..., "chat publication waiting before send")` instead of `logger.warn(..., "chat publication failed")`. - **`server/src/services/chat-channels/slack/form-owner.ts` & `cloud-enrollment.ts`**: Add `clearWaitingSlackFormPublicationDeadlines(tx, endpoint)` and register `notifyChatPublicationWork(tx)` before writes across every enrollment resolution/retirement/attention transition (`reconcileSlackFormEnrollment`, `stageSlackFormEnrollment` for an already-enrolled owner, `stageSlackFormOwnerConfiguration` deactivation, `reconcilePendingSlackFormWork` permanent `attention`, `stageSlackCloudEnrollmentIntent` inactive/attention staging, and `createSlackCloudEnrollment` `intent_authority_changed` / `attention` / retirement commits). - **Tests & CI timing manifests**: Extended `server/src/__tests__/slack-cloud-forms.test.ts` and `server/src/services/chat-channels/slack/cloud-enrollment.test.ts`, added a focused real embedded-PostgreSQL suite in `server/src/__tests__/chat-channels/slack-form-enrollment-wait.integration.test.ts` (641 lines; keeping `slack-protocol.integration.test.ts` untouched at 726 lines), and registered its measured 8-core CI timing (`12547 ms`) in `scripts/chat-shard-durations.json` and `scripts/general-server-shard-durations.json`. ### Sleep-Aware Background Work Contract - **Trigger**: Shared `DELIVERY_QUEUES.chatPublications` transaction-aware work signals (`notifyChatPublicationWork`) and saved per-row `chat_publications.next_attempt_at` deadlines read by `nextPublicationAt()`. - **Durable source of truth**: `chat_publications` (`state`, `next_attempt_at`, `attempts`, `redacted_error`), `chat_endpoints.setup` (`slackCloudIntent`, `slackCloudForms`), and `chat_actions` (`slack_form_owner`). - **Pending-work predicate**: `publicationEligibility()` selects `chat_publications` in `pending`/`retry` whose `next_attempt_at` is `null` or due (`<= now`) on active/verifying endpoints. - **Next deadline/retry**: `nextAttemptAt` tracks `clamp(2_000, 300_000, enrollmentDeadline - now)` while enrollment is scheduled, is cleared to `null` when enrollment completes, retires, or enters `attention` (or when `stillWaiting(tx)` sees enrollment already settled), and falls back to `<= 2_000 ms` if `stillWaiting` encounters lock contention. - **Quiet condition**: Once waiting publications defer to the enrollment deadline (up to 300s), no publication sweep or lease write runs until either that deadline arrives or an enrollment producer commits a state change; once enrollment resolves, publications publish or settle to `failed`/`cancelled` and `nextPublicationAt()` returns `null`. ## Verification Verified on commit `a75b654d3d75f9b36f860b0793baa94f5811fdac`: - Reproduced pre-fix RED failures before applying the fix: unit tests confirmed hardcoded `2000 ms` waits for 60s/300s deadlines and missing publication wake on `slackCloudIntent` attention; real PostgreSQL tests confirmed 2s `nextAttemptAt` scheduling, `chat publication failed` warn logs, and 5-minute stranding on the concurrent commit race. - `pnpm check:module-boundaries` — PASS. - `node scripts/check-test-budget.mjs --base origin/master` — PASS (113 nightly suites validated, 3 test files checked). - `node --test ./scripts/__tests__/run-vitest-stable-shard.test.mjs ./scripts/__tests__/run-vitest-stable-pr-mode.test.mjs ./scripts/ci/test-selection-pr-timings.test.mjs ./scripts/check-test-budget.test.mjs .github/scripts/tests/ci-dependency-cache.test.mjs` — PASS (79/79 tests). - `pnpm --filter @paperclipai/server typecheck` — PASS (all 7 typecheck layers green; unchanged server sources since `459443a36a`). - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/slack-cloud-forms.test.ts src/services/chat-channels/slack/cloud-enrollment.test.ts src/services/chat-publication-errors.test.ts src/__tests__/chat-channels/slack-form-enrollment-wait.integration.test.ts` — PASS (4 test files, 106/106 tests passed; unchanged server sources since `459443a36a`). - Scope note: Local tests verify worker quiet, durable deadlines, and PostgreSQL reactivation; they do not by themselves prove deployed host suspension or fleet cost reduction. ## Risks - Low risk; no database schema or migration changes are introduced. - Lock ordering stays acyclic (`chat_endpoint_leases` -> `chat_endpoints` -> `chat_actions` -> `chat_publications`), and `stillWaiting(tx)` uses `FOR SHARE NOWAIT` inside a PostgreSQL savepoint so lock contention can neither block nor abort publication finalization. - `clearWaitingSlackFormPublicationDeadlines` only clears `next_attempt_at` on `state = 'retry'` rows with `redacted_error = 'form_publication_enrollment_pending'` for the affected `(company_id, endpoint_id)`, verified by test to leave unrelated provider rate-limit backoffs untouched. - Process-local transaction notifications cover supported application writers; startup reconstruction and the bounded 300s ceiling still recover any external or out-of-band state change. ## Model Used Gemini 4 Neon (Google DeepMind, XHigh reasoning, 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 - [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 |
||
|
|
205482b2c2 |
fix(telemetry): emit missing server telemetry across native, onboarding, and routine paths (#23297)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Paperclip emits first-party product telemetry from server lifecycle transitions so operators and Cloud analytics can measure real agent runs, completions, onboarding, and routines > - A full audit of every `track*` helper in `packages/shared/src/telemetry/events.ts` found several server code paths that perform real product transitions directly in the database without emitting their existing telemetry events: native/reconciliation terminal run failure writers (`agent.task_run`), agent-accepted `native_completion_review` closures (`agent.task_completed`), `active-run-watchdog` overwriting a null `lastHeartbeatAt` (suppressing `agent.first_heartbeat`), `onboarding-seed` creating the first agent and mission goal (`agent.created`, `goal.created`), routine suggestions creating a routine (`routine.created`), and standing check reports recording a routine run (`routine.run`) > - Because those paths bypass the REST routes or `emitTerminalAgentTaskRun` (which skips rows already written to `"failed"`), deployments under-report failed native runs, agent-reviewed completions, onboarding hires, and routine activity > - This pull request wires up the existing telemetry helpers at each missing server-side transition after transaction commit using a shared terminal-failure emitter, passes an explicit root database handle for post-commit operator-containment telemetry, skips non-terminal `retryable_failure` writes while emitting non-blocking telemetry on `retryable_failure -> terminal_failure` / `committed` transitions (including superseded retry retirement), keeps `agent-task-run-telemetry.ts` free of circular imports from `run-failure-report.ts`, updates `packages/shared/src/telemetry/README.md`, and adds embedded-Postgres regression tests covering every restored path > - The benefit is complete, deduplicated, non-blocking server-side telemetry across native runtime, onboarding, and routine flows without changing any telemetry contract schema ## Linked Issues or Issue Description Refs #22963 **What happened?** Several server-side lifecycle paths transitioned database rows directly without emitting their existing first-party telemetry events: 1. `native-session-executor.ts`, `native-restart-recovery.ts`, `native-superseded-retry.ts`, `execution-control-reconciliation.ts`, and `native-failed-run-owner-release.ts` wrote `heartbeat_runs.status = 'failed'` or transitioned `retryable_failure -> terminal_failure` directly (so `heartbeat.ts`'s `emitTerminalAgentTaskRun` later saw `previousStatus === updated.status` and skipped `agent.task_run`). 2. `issue-thread-interactions.ts` allowed an agent reviewer to accept a `native_completion_review` confirmation card and move an `in_review` task to `done` without emitting `agent.task_completed`. 3. `active-run-watchdog/adapters/postgres.ts` set `agents.lastHeartbeatAt = new Date()` unconditionally when folding a silent run instead of using `settledHeartbeat(now)`, suppressing `agent.first_heartbeat` for never-heartbeated agents. 4. `onboarding-seed.ts` created a company's first agent and mission goal without emitting `agent.created` or `goal.created`. 5. `routine-suggestions.ts` created routines from task suggestions without emitting `routine.created`, and `routine-standing-checks.ts` inserted completed `routine_runs` without emitting `routine.run`. **Expected behavior** Each of those committed transitions emits its existing first-party telemetry event once after commit, non-blocking, with accurate company and person scope (`withTelemetryActor` / `withTelemetryCompany`), using an explicit live root DB handle after outer transaction commit, skipping pending native retries (`retryable_failure`), and emitting no duplicates on replay or rollback. **Steps to reproduce** 1. Trigger any of the paths above in embedded Postgres (as exercised in `server/src/__tests__/missing-server-telemetry-emissions.test.ts`). 2. Observe that the database state transitions as expected, while the corresponding telemetry event is missing, dropped on a finished transaction, prematurely emitted on a retryable native failure, or blocking finalization while pending. **Paperclip version or commit** Merged cleanly with `master` at `054b4e1395b7f246e2c18d222b701595daf5522b` (PR head `b4e70c295b78de4bdcec1788e342c421cce1e138`). ## What Changed - `server/src/services/agent-task-run-telemetry.ts` & `server/src/services/run-failure-report.ts`: keep `isRunFailureStatus`, `isPendingNativeRetry`, and `isNewTerminalRunFailure` as pure leaf helpers in `agent-task-run-telemetry.ts` (re-exported by `run-failure-report.ts`) and colocate `emitTerminalRunFailure(db, run, options)` in `run-failure-report.ts` so `agent-task-run-telemetry.ts` never imports `run-failure-report.ts` (avoiding a circular dependency into `status-decision-committer.ts` that broke `vi.mock("../agent-task-run-telemetry.js")` in `native-task-completed-telemetry.test.ts`). Tighten `isNewTerminalRunFailure` so writes into `failed/retryable_failure` return `false` while writes leaving `retryable_failure` into a terminal failure return `true`, guard `emitAgentTaskRun` against `isPendingNativeRetry`, and select `nativePhase` in `emitAgentTaskRunById`. - `server/src/routes/issues.ts`, `server/src/services/execution-recovery-resolution.ts`, and `server/src/services/native-runtime/native-failed-run-owner-release.ts`: require an explicit root `telemetryDb: Db` whenever `controllerContainment` is set (discriminated union type plus runtime guard, removing the `input.telemetryDb ?? input.db` and `release.telemetryDb ?? db` fallbacks) so `afterTransactionCommit` always runs `emitTerminalRunFailure` against the root pool instead of a finished outer transaction, gated on `isNewTerminalRunFailure(run, settledRun)`. - `server/src/services/native-runtime/native-run-finalizer.ts` and `server/src/services/native-runtime/native-run-projection.ts`: emit non-blocking `void emitAgentTaskRun(...)` + `void reportRunFailure(...)` on the `isNewTerminalRunFailure` branch when a native run transitions from `failed/retryable_failure` to `failed/committed`, ensuring telemetry DB lookups never block finalization, projection, review responses, or chat settlement. - `server/src/services/native-runtime/native-superseded-retry.ts`, `server/src/services/native-runtime/native-finalization-reconciler.ts`, and `server/src/services/native-runtime/native-restart-recovery.ts`: return the retired `heartbeatRuns` row from `retireSupersededNativeRetry` so both `claimNativeSessionResumptions` and `claimNativeRestartRecoveries` emit `agent.task_run` and `reportRunFailure` once after commit when retiring a superseded `retryable_failure` run to `terminal_failure`. - `server/src/services/native-runtime/native-session-executor.ts`: select `runtimeMode` and `nativePhase` before the failure write, gate on `isNewTerminalRunFailure(runBeforeWrite, updatedRun)`, and emit via `emitTerminalRunFailure(input.db, terminalRunToReport, { failureReport: { nativeCloseFailure: error } })`. - `server/src/services/native-runtime/native-restart-recovery.ts`: return `updatedRun` from `endNamespaceUnverifiedRun` and call `emitTerminalRunFailure` after commit in both `claimNativeRestartRecoveries` and `boundAwaitingEvidence` (making `boundAwaitingEvidence` consistent with inline unverified-run termination for both telemetry and Sentry failure reporting). - `server/src/services/execution-control-reconciliation.ts`: gate terminal failure detection on `isNewTerminalRunFailure(run, updatedRun)` and emit via `emitTerminalRunFailure(db, terminalRunToReport)`. - `server/src/modules/active-run-watchdog/adapters/postgres.ts`: use `settledHeartbeat(now)` instead of `new Date()` when folding a silent run so a never-heartbeated agent keeps `lastHeartbeatAt = null` until its first real heartbeat. - `server/src/services/issue-thread-interactions.ts`: call `void emitAgentTaskCompleted(committedDb, completedTask)` in the post-commit `publish` hook when an agent reviewer accepts a `native_completion_review` confirmation card and closes the task to `done`. - `server/src/services/onboarding-seed.ts`: emit `trackAgentCreated` (after hire commit) and `trackGoalCreated` (via `afterTransactionCommit`) with `withTelemetryActor` when onboarding seed creates a new first agent or mission goal. - `server/src/services/routine-suggestions.ts`: emit `trackRoutineCreated` with `withTelemetryActor` after both the routine and its trigger are created. - `server/src/services/routine-standing-checks.ts`: emit `trackRoutineRun` (`source: STANDING_CHECK_TRIGGER_KIND` = `"heartbeat"`, `status: "completed"`) with `withTelemetryCompany` after committing a standing-check report. Emitting the raw value follows `packages/shared/src/telemetry/README.md`; the receiving layer and `posthog-direct/enum-fallbacks.generated.ts` normalize unknown `routine.run.source` values to `"other"` until `"heartbeat"` is promoted in the telemetry schema. - `packages/shared/src/telemetry/README.md` & `tests/runner-e2e/source-sdk-public-inputs.json`: document the restored `agent.task_run` and `agent.task_completed` emission paths per `rules/data-paths.mdc`. - `server/src/__tests__/missing-server-telemetry-emissions.test.ts`: add embedded-Postgres TDD regression tests covering every restored path, including `isNewTerminalRunFailure`, the real board containment route (`POST /api/issues/:id/recovery-actions/resolve`) for both `running` and `retryable_failure` runs, `native-session-executor` retryable vs terminal settlement, `native-restart-recovery` inline and `boundAwaitingEvidence` termination, non-blocking `finalizeNativeRun` / `projectCommittedRun` while `emitAgentTaskRun` is pending, superseded-retry retirement telemetry in both `claimNativeRestartRecoveries` and `claimNativeSessionResumptions`, and strict `telemetryDb` enforcement on `validateExecutionReconciliation`. ## Telemetry Contract Exception (`rules/data-paths.mdc`) - **Unchanged generated contract exception:** `packages/shared/src/telemetry/generated/paperclip-telemetry.ts` has no diff in this PR because all six emitted events (`agent.task_run`, `agent.task_completed`, `agent.created`, `goal.created`, `routine.created`, `routine.run`) and all of their dimensions, types, and optionality already exist unchanged in the generated contract. No new event names, dimensions, or enum values were added to the telemetry contract. - **Documentation & privacy review preserved:** `packages/shared/src/telemetry/README.md` is updated in this PR to document the restored emission paths, and privacy review remains requested per `rules/data-paths.mdc` because this PR adds callers to existing helpers in `packages/shared/src/telemetry/events.ts`. ## Verification - **RED (initial review-finding regression proof before fix on `9f10d34af2`):** `pnpm --filter @paperclipai/server exec vitest run src/__tests__/missing-server-telemetry-emissions.test.ts -t "classifies pending native retries|board containment route|retryable native session failures"` — **3/3 failed**. - **RED (targeted P1/CI/review fix pass before `b4e70c295b`):** - `pnpm --filter @paperclipai/server exec vitest run src/services/native-runtime/native-task-completed-telemetry.test.ts` — **3/3 failed** (reproducing CI shard 16 failure caused by the `agent-task-run-telemetry.ts -> run-failure-report.ts` circular import into `status-decision-committer.ts`). - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/missing-server-telemetry-emissions.test.ts -t "without awaiting emitAgentTaskRun|retiring a superseded native retry|requires an explicit root telemetryDb"` — **3/3 failed** (reproducing blocking `await emitAgentTaskRun`, missing `agent.task_run` on superseded retry retirement, and silent `telemetryDb` fallback to `input.db`). - **GREEN (on final head `b4e70c295b78de4bdcec1788e342c421cce1e138`):** - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/missing-server-telemetry-emissions.test.ts` — **1/1 file, 12/12 tests passed**. - `pnpm --filter @paperclipai/server exec vitest run src/services/native-runtime/native-task-completed-telemetry.test.ts src/__tests__/heartbeat-status-preserving-telemetry.test.ts src/__tests__/agent-task-run-telemetry.test.ts` — **3/3 files, 59/59 tests passed** (3 + 1 + 55). - **Test budget:** `node scripts/check-test-budget.mjs --files server/src/__tests__/missing-server-telemetry-emissions.test.ts` — **PASS** (113 nightly suites validated, 1 test file checked). - **Verify scope & local gap:** Local `tsc --noEmit` was skipped to avoid exceeding the container's shared 9.7 GiB cgroup memory limit; GitHub PR CI supplied full typecheck, build, serialized server suites (`ci / verify`), and E2E (`ci / e2e`) verification for head `b4e70c295b78de4bdcec1788e342c421cce1e138`. - **GitHub CI on `b4e70c295b78de4bdcec1788e342c421cce1e138`:** - `ci / verify` — **PASS** (https://github.com/paperclipai/paperclip/actions/runs/47455114528/job/145468380453; includes Typecheck + Release Registry, Build, policy, Runner support/package/native server suites, and all 20 server test shards). - `ci / e2e` — **PASS** (https://github.com/paperclipai/paperclip/actions/runs/47455114528/job/145468199932; all 16 E2E shards). - All 87 status checks completed with zero failures and zero pending checks. - **Automated reviews on `b4e70c295b78de4bdcec1788e342c421cce1e138`:** Greptile **5/5** (`SUCCESS`, unchanged-contract exception recorded), Ponytail **5/5** (`Verdict: ship`), Feynman **4/5** (zero functional defects; structural rationale recorded below and in threads, 17/17 review threads resolved). - **Structural decisions (`rules/pull-request-review.mdc` & `rules/test-budget.mdc`):** - `server/src/services/native-runtime/native-finalization-reconciler.ts` grew from 1,000 lines on `master` to 1,006 lines (+6 net lines) to keep the `retiredSupersededRun` capture, error-clear, and post-commit `void emitTerminalRunFailure` call locally visible inside `claimNativeSessionResumptions` rather than bundling an unrelated reconciler refactor into this telemetry fix. - `server/src/__tests__/missing-server-telemetry-emissions.test.ts` (1,447 lines) keeps all 12 embedded-Postgres telemetry regressions in one shared `beforeAll` suite (grouped by domain `describe` blocks) to avoid multiplying disposable Postgres startup cost across CI shards per `rules/test-budget.mdc`. ## Risks - Low risk. No telemetry schemas, event names, or dimension contracts changed; all new emissions run after transaction commit as best-effort/fire-and-forget and catch errors so telemetry can never block or fail product flows. - `native-restart-recovery.ts`'s `boundAwaitingEvidence` and `retireSupersededNativeRetry` callers now invoke terminal failure telemetry/reporting after commit, matching inline unverified-run termination. - Deployments will see more accurate counts for failed `agent.task_run`, agent-reviewed `agent.task_completed`, `agent.created` / `goal.created` during onboarding, and `routine.created` / `routine.run`, which is the intended fix. - Requesting privacy review per `rules/data-paths.mdc` because this PR adds callers to existing helpers in `packages/shared/src/telemetry/events.ts`. ## Model Used - Google Antigravity (Gemini 4 Neon, High reasoning, 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 (explicit unchanged-contract exception recorded per `rules/data-paths.mdc`) - [x] I will address all Greptile and reviewer comments before requesting merge |
||
|
|
1a20fb1953 |
fix(server): avoid ServerResponse MaxListenersExceededWarning in stream pipelines (#23810)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - The Express server streams HTTP responses through Node's
`stream.pipeline(..., res)` on proxy, avatar, file download, MCP
transfer, and retained UI asset routes
> - Node's `stream.pipeline` attaches 7 internal `close` listeners (and
4 `finish` listeners) to `ServerResponse`
> - Global request middleware (`idleAdmissionMiddleware`, `pino-http`,
`postHogRequestContextMiddleware`, `authorizationReadScope`) and route
cleanup handlers already attach 3 to 5 `close` listeners to `res` before
streaming begins, pushing every request over the default `MaxListeners`
cap of 10
> - Each excess listener emits `MaxListenersExceededWarning`, which
captures a synchronous V8 stack trace and writes to stderr on every
streamed request
> - This pull request collapses the 3 redundant `close` listeners in
`posthog-proxy` into one cleanup listener and routes all
`ServerResponse` stream pipelines through a narrow `pipelineToResponse`
helper that reserves only pipeline's internal listener headroom once per
response
> - The benefit is zero false `MaxListenersExceededWarning` stack traces
on streamed HTTP responses while preserving real listener-leak detection
## Linked Issues or Issue Description
**What happened?**
Streamed HTTP routes that call `stream.pipeline(source, res)` emit
`MaxListenersExceededWarning: Possible EventEmitter memory leak
detected. 11 close listeners added to [ServerResponse]. MaxListeners is
10.` on every request. Each warning runs a synchronous
`Error.captureStackTrace` and writes to stderr. On a hosted server this
occurred 14 to 17 times per minute.
Root cause:
- `stream.pipeline(readable, res)` attaches 7 internal `close` listeners
(`destroyer`, two `eos` pairs of `onlegacyfinish` + `onclose`, `pipe`,
and `Readable.pipe`) and 4 internal `finish` listeners to
`ServerResponse`.
- Any route with 4 or more `close` listeners already registered on `res`
exceeds the default limit of 10:
- `server/src/routes/posthog-proxy.ts`: `idleAdmissionMiddleware` (1) +
3 separate route `close` listeners + `pipeline` (7) = 11.
- `server/src/services/cloud-trial-proxy.ts`: 3 global middleware +
`onClientClose` (1) + `pipeline` (7) = 11.
- `server/src/routes/agent-avatars.ts`: 4 global middleware + `pipeline`
(7) = 11.
- `server/src/routes/agents.ts`: 4 global middleware + `pipeline` (7) =
11.
- `server/src/routes/file-resources.ts`: 4 global middleware +
`abortIfResponseIncomplete` (1) + `pipeline` (7) = 12.
- `server/src/retained-ui-assets.ts`: 4 global middleware + `cancel` (1)
+ `pipeline` (7) = 12.
- `server/src/services/public-mcp/file-transfers.ts`: 3 global
middleware + `pipeline` (7) = 10 (at the limit).
**Expected behavior**
Streamed HTTP responses complete with 0 `MaxListenersExceededWarning`
events under the real middleware chain, while genuine listener leaks
(such as adding listeners in a loop) still trigger
`MaxListenersExceededWarning`.
**Steps to reproduce**
1. Mount `idleAdmissionMiddleware`, `posthogProxyRoutes`,
`createHttpLogger`, `postHogRequestContextMiddleware`,
`authorizationReadScope`, `agentAvatarRoutes`, and `retainedUiAssets` on
an Express app in `app.ts` order.
2. Attach a `process.on("warning", ...)` listener.
3. Send one request each to `POST /_ph/e/`, `GET
/api/agent-avatars/cap-v1/arctic-blue/rest.png`, and `GET
/assets/chunk-test.js`.
4. Observe 3 `MaxListenersExceededWarning` warnings (one per streamed
response).
**Paperclip version or commit**
Reproduced at `306437a2a5` on `master`; fixed on top of `83f10b968d`.
**Deployment mode**
Self-hosted server and hosted server deployments.
**Node.js version**
Reproduced on Node v24 and v26.4.0.
**Relevant logs or output**
```text
(node:2376) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 close listeners added to [ServerResponse]. MaxListeners is 10. Use emitter.setMaxListeners() to increase limit
```
## What Changed
- Added `pipelineToResponse` in `server/src/http/response-pipeline.ts`:
- Shared HTTP-layer primitive owned by `server/src/http/` so routes,
services, and `retained-ui-assets.ts` do not duplicate `EventEmitter`
listener-budget logic or cross module boundaries.
- Reserves at most `stream.pipeline`'s internal `close` (8) and `finish`
(5) headroom once per `ServerResponse` (tracked via
`WeakSet<ServerResponse>`), capped at `currentMax + 8` and never setting
`0` (unlimited) or overwriting an explicit `0`.
- Delegates directly to `node:stream/promises` `pipeline`, preserving
backpressure, error propagation, `AbortSignal` cancellation, and
response headers/status codes.
- Collapsed the 3 separate `res.once("close")` / `res.on("close")`
listeners in `server/src/routes/posthog-proxy.ts` (in-flight slot
decrement, deadline `clearTimeout`, and upstream abort) into one
`res.once("close")` cleanup listener and routed response streaming
through `pipelineToResponse`.
- Updated all 6 remaining `pipeline(..., res)` call sites to use
`pipelineToResponse`:
- `server/src/services/cloud-trial-proxy.ts`
- `server/src/routes/agent-avatars.ts`
- `server/src/routes/agents.ts`
- `server/src/routes/file-resources.ts`
- `server/src/retained-ui-assets.ts`
- `server/src/services/public-mcp/file-transfers.ts`
- Added unit and middleware-chain regression tests in
`server/src/http/response-pipeline.test.ts`,
`server/src/__tests__/cloud-posthog-browser.test.ts`,
`server/src/__tests__/agent-avatars.test.ts`, and
`server/src/__tests__/retained-ui-assets.test.ts`.
## Verification
Before fix (Node v26.4.0, real Express middleware chain for
`posthog-proxy`, `agent-avatars`, `retained-ui-assets`):
```text
Statuses: 200 200 200
Warnings count: 3
{"route":"posthog-proxy","name":"MaxListenersExceededWarning","message":"Possible EventEmitter memory leak detected. 11 close listeners added to [ServerResponse]. MaxListeners is 10. Use emitter.setMaxListeners() to increase limit"}
{"route":"agent-avatars","name":"MaxListenersExceededWarning","message":"Possible EventEmitter memory leak detected. 11 close listeners added to [ServerResponse]. MaxListeners is 10. Use emitter.setMaxListeners() to increase limit"}
{"route":"retained-ui-assets","name":"MaxListenersExceededWarning","message":"Possible EventEmitter memory leak detected. 11 close listeners added to [ServerResponse]. MaxListeners is 10. Use emitter.setMaxListeners() to increase limit"}
```
After fix (same 3 routes + a 15-listener leak probe):
```text
Statuses: 200 200 200 200
Warnings count: 1
{"route":"genuine-leak","name":"MaxListenersExceededWarning","message":"Possible EventEmitter memory leak detected. 13 close listeners added to [ServerResponse]. MaxListeners is 12. Use emitter.setMaxListeners() to increase limit"}
```
Local checks run on rebased revision
`e265a0a2207244f79eeddadf7a5b2958a8c59888`:
- `pnpm check:module-boundaries` — PASS
- `node scripts/check-test-budget.mjs --base origin/master` — PASS (113
nightly suites validated, 4 test files checked)
- `pnpm --filter @paperclipai/server exec vitest run
src/http/response-pipeline.test.ts
src/__tests__/cloud-posthog-browser.test.ts
src/__tests__/agent-avatars.test.ts
src/__tests__/retained-ui-assets.test.ts` — 4 files, 116 tests passed
- `pnpm --filter @paperclipai/server typecheck` — PASS
- Pre-rebase also ran the 5 additional DB-backed affected route suites
(`cloud-trial-inference.test.ts`,
`cloud-trial-proxy-middleware-order.test.ts`, `file-resources.test.ts`,
`agent-instructions-routes.test.ts`, `public-mcp.test.ts`) — 5 files,
172 tests passed; CI will run the full required matrix on this revision.
## Risks
- Low risk. `pipelineToResponse` only adjusts `maxListeners` narrowly
once per `ServerResponse` by the internal headroom `stream.pipeline`
requires (at most `currentMax + 8`), never disables the cap (`0`), and
forwards directly to `node:stream/promises` `pipeline`.
- In `posthog-proxy.ts`, replacing callback `pipeline(upstreamRes, res,
cb)` with `void pipelineToResponse(upstreamRes, res).catch(...)`
preserves identical error destruction and debug logging; the
consolidated `res.once("close")` listener executes the same deadline
cleanup, in-flight accounting, and upstream abort logic.
> 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
- Gemini 4 Neon (Google DeepMind, XHigh reasoning, 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
|
||
|
|
858f021658 |
fix(server): add exponential backoff to MCP cloud sync workers (#23821)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Public MCP cloud sync runs two delivery workers: `mcp-client-mirror` and `mcp-revocation-index` > - Both workers retry every 5 seconds indefinitely when the Cloud connector broker returns HTTP 404/501 or fails repeatedly, and `delivery-work-coordinator` caps error retries at fixed `task.retryMs` > - Each failed tick executes PostgreSQL locks and queries, local secret derivation, Ed25519 request signing, and an HTTPS request while logging full error stacks roughly 20 times per minute > - In `client-mirror-sync`, a failed `begin` also sets `reserveFullRevision = true`, causing extra revision bumps and self-notifications that immediately re-trigger failed runs > - This pull request adds an opt-in `retryAtOnError` hook to `delivery-work-coordinator`, adds bounded exponential backoff to both MCP cloud sync workers, prevents self-wakes from bypassing backoff, and avoids unnecessary `reserveFullRevision` churn on unsupported HTTP 404/501 `begin` rejections > - The benefit is a >94% reduction in repeated failure load during broker outages or unsupported endpoint responses while preserving immediate recovery on broker return and all sleep-safety and revocation invariants ## Linked Issues or Issue Description No matching public GitHub issue or duplicate pull request exists. **What happened?** When the Cloud connector broker returns HTTP 404 (`UNKNOWN_BROKER_ERROR`), HTTP 501, or repeated transient errors, `mcp-client-mirror` (`server/src/services/public-mcp/client-mirror-sync.ts`) and `mcp-revocation-index` (`server/src/services/public-mcp/revocation-index-sync.ts`) retry every 5 seconds without backoff. Both workers log `Delivery reconciliation failed` continuously and repeat PostgreSQL advisory locks, queries, local key derivation, and signed HTTP requests. In `client-mirror-sync`, a failed tick also triggers `prepareMcpClientMutation`, which bumps `mcp_oauth_client_mirror_state.revision` and self-notifies `mcpClientMirror`, immediately re-running the worker and bypassing retry delays. **Expected behavior** Both MCP cloud sync workers must apply bounded exponential backoff on consecutive failures, ramp faster on HTTP 404/501 unsupported broker endpoints, avoid unnecessary revision bumps on unsupported `begin` rejections, ignore self-wakes while backed off, recover cleanly and reset backoff when the broker succeeds, and stay quiet once synchronized. **Steps to reproduce** 1. Configure a managed Paperclip instance with `startMcpClientMirrorSync` and `startMcpRevocationIndexSync` registered on `createDeliveryWorkCoordinator`. 2. Make the Cloud connector broker return HTTP 404 (`PaperclipCloudConnectorError` with status `404` and reason `UNKNOWN_BROKER_ERROR`) or HTTP 503 for 10 minutes. 3. Observe ~121-122 failed ticks per worker in 10 minutes (every 5 seconds, plus immediate self-wake ticks in `client-mirror-sync`) and repeated `Delivery reconciliation failed` errors. **Paperclip version or commit** Reproduced on `master` (`306437a2a5` / rebased on latest `origin/master`). **Deployment mode** Other (managed Cloud connector runtime; reproduced deterministically with unit tests and fake timers). ## What Changed - **`server/src/services/delivery-work-coordinator.ts`** (shared contract update): - Keep `scheduledAt` unmodified if `scheduler.schedule` throws on a non-finite deadline. - Add an opt-in `retryAtOnError?: () => number | null` callback on registered tasks. When `task.run` fails (`runFailed === true`), `input.canRun()` is true, and `task.retryAtOnError()` returns a finite deadline, schedule `Math.max(Date.now(), backoffAt)` directly instead of capping the retry at `task.retryMs`. - Keep `nextRunAtOnError` and all existing consumers (`scoped-deadline-work.ts`, `receiver-work.ts`, `createScheduledBoardPostsWorker`, `createClaimLeaseExpiryWorker`, and all workers without `retryAtOnError`) unchanged on the `task.retryMs` fallback. - Fall back to `task.retryMs` whenever `retryAtOnError` is absent, returns `null`, throws, returns a non-finite value, `!input.canRun()`, `!runFailed`, or `databaseWorkPending(input.owner, queue)` is true. - **`server/src/services/public-mcp/client-mirror-sync.ts`**: - Add bounded exponential backoff on consecutive failures: - Transient errors: `5s -> 10s -> 20s -> 40s -> 80s -> 160s -> 300s` (5-minute cap). - HTTP 404/501 unsupported broker endpoints: `5s -> 20s -> 80s -> 320s -> 900s` (15-minute cap). - Respect finite broker `Retry-After` (`PaperclipCloudConnectorError.retryAt`) up to the active cap. - Register `retryAtOnError: () => retryAt` so the coordinator schedules the computed backoff deadline directly. - Guard `run()` at entry against active `retryAt` so self-notifications from `prepareMcpClientMutation` and mutation bursts during a broker outage do not bypass backoff or execute database/network work early; preserve explicit `worker.wake()` to clear `retryAt` for immediate manual/recovery wake. - Avoid setting `fullRecovery = true; reserveFullRevision = true` when `begin` itself fails with HTTP 404/501 before acceptance; for failures after `begin` or non-404/501 failures, reserve at most one full-recovery revision per failure episode until recovery succeeds. - Reset `consecutiveFailures = 0` and `retryAt = null` immediately upon successful synchronization, disable ACK, or unmanaged/unconfigured state. - **`server/src/services/public-mcp/revocation-index-sync.ts`**: - Add the same bounded exponential backoff (`5s` doubling to `5m` on transient errors, `5s` quadrupling to `15m` on HTTP 404/501, respecting broker `Retry-After`), `retryAtOnError: () => retryAt`, early backoff guard in `run()`, explicit `worker.wake()` bypass, and immediate backoff reset upon grant sync progress or empty/synchronized state. - **Background work lifecycle contract (`rules/sleep-aware-background-work.mdc`)**: - **Trigger**: Startup check plus transaction-aware `notifyDeliveryWork` settlements (`mcp-client-mirror`, `mcp-revocation-index`) and explicit `worker.wake()`. - **Durable source of truth**: `mcp_oauth_client_mirror_state` / `mcp_oauth_clients` / `mcp_oauth_client_changes` / `mcp_oauth_device_requests` for client mirror; `mcp_oauth_grants` and `mcp_oauth_tokens` for revocation index. - **Pending-work predicate**: Unacknowledged revision/deviceStatus/issuer mismatch in `mcp_oauth_client_mirror_state` (`idle-client-mirror.ts` continues to report `blocked: true` until acknowledged); unrevoked grants whose `revocation_index_receipt` revision or `keyId` differs from current `revocation_revision` / `keyId`. - **Next deadline/retry**: `null` when synchronized, disabled, or unmanaged; `Date.now() + 5_000` when a follow-up batch/revision is queued without error; bounded exponential `retryAt` on failure. - **Quiet condition**: Zero scheduled timers, zero SQL queries, and zero network requests once synchronized, unconfigured, or unmanaged; bounded retries only while an unacknowledged obligation remains failed. - **Tests**: - Added `server/src/services/public-mcp/client-mirror-sync.test.ts` (fake timers, real `createDeliveryWorkCoordinator` + `installDatabaseWorkSignals`, covering HTTP 404, HTTP 501, HTTP 503, HTTP 429 `Retry-After`, `reserveFullRevision` churn, self-wake suppression, `readIdleMcpClientMirror` sleep-safety invariants, drain pause/resume, explicit `worker.wake()`, and quiet post-recovery state). - Extended `server/src/services/public-mcp/revocation-index-sync.test.ts` with fake-timer backoff, 404/503/429 coverage, mutation-during-backoff quietness, explicit `worker.wake()`, and post-recovery reset/quietness. - Extended `server/src/__tests__/work-scheduler.test.ts` for coordinator `retryAtOnError` backoff deadlines, `retryMs` fallbacks (`null`, `NaN`, and pending database work), and regression coverage confirming `nextRunAtOnError` remains capped at `retryMs`. ## Verification Tested on commit `c53a4a0bdf2ca3723f6a446e85f54bf2255a3223`: - **Red/green before-vs-after (fake timers over 10 minutes / `600_000 ms`)**: - `mcp-client-mirror` under HTTP 404: **122 failed ticks** before fix (`0, 0, 1, 5001, ...`, with immediate self-wakes and extra revision bump) -> **5 failed ticks** after fix (`0, 5s, 25s, 105s, 425s`, next wake `1_325s`; **95.9% reduction**, zero extra `reserveFullRevision` bumps). - `mcp-revocation-index` under HTTP 404: **121 failed ticks** before fix (`0, 5s, 10s, ..., 600s`) -> **5 failed ticks** after fix (`0, 5s, 25s, 105s, 425s`, next wake `1_325s`; **95.9% reduction**). - Both workers under transient HTTP 503: **121 failed ticks** -> **7 failed ticks** (`0, 5s, 15s, 35s, 75s, 155s, 315s`, next wake `615s`; **94.2% reduction**). - After broker returns HTTP 200: both workers save receipts, reset backoff (`nextWakeAt() === null`), and execute 0 queries and 0 publishes across a subsequent 10-minute idle window. - Commands run (all passed): - `pnpm --filter @paperclipai/server exec vitest run src/services/public-mcp/revocation-index-sync.test.ts src/services/public-mcp/client-mirror-sync.test.ts src/services/public-mcp/client-mirror-ack.test.ts src/__tests__/work-scheduler.test.ts` (4 files, 16 tests passed; full 7-file public-mcp + work-scheduler suite: 33/33 passed) - `pnpm check:module-boundaries` (passed) - `node scripts/check-test-budget.mjs --files server/src/services/public-mcp/client-mirror-sync.test.ts server/src/services/public-mcp/revocation-index-sync.test.ts server/src/__tests__/work-scheduler.test.ts` (passed: 113 nightly suites validated, 3 test files checked) - `pnpm --filter @paperclipai/server typecheck` (all 7 layers passed) - Scope note: Verification uses deterministic fake-timer unit suites and local typecheck/boundary checks; this does not claim live deployed Cloud host suspension or external wake behavior. ## Risks - Low risk. During an active broker outage, new local client or grant mutations wait until the active backoff deadline (capped at 5 minutes for transient errors and 15 minutes for HTTP 404/501) rather than immediately retrying the failing broker, while preserving durable pending state and `idle-client-mirror` sleep blocks until acknowledged. - Existing `delivery-work-coordinator` consumers (including `nextRunAtOnError` callers) keep their exact `retryMs`-capped fallback behavior. Only workers opting into `retryAtOnError` schedule error retries beyond `retryMs`, with `null`, thrown errors, non-finite values, drain/standby states, and pending database transactions still falling back safely to `task.retryMs`. > 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 - Gemini 4 Neon (Google DeepMind, XHigh reasoning, 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> |
||
|
|
74e67231bd |
perf(github): fix inherited review wait join and batch lookup plan (#23817)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - When an agent publishes a GitHub pull request review, the Paperclip task waits in review for the next GitHub reply. Later runs on that task inherit this wait. > - Issue lists and inbox attention call `readInheritedGitHubReviewWaits` to check all waiting runs of a company in one batch (`readInheritedReviewsForKeys`). > - In `readInheritedReviewsForKeys`, the join between `chat_message_links` and `chat_conversations` matched only `conversation_id` and omitted `endpoint_id`, while filtering `comment_id`, `issue_id`, and `agent_id` through three separate `= ANY(...)` arrays and joining every historical `chat_github_reviews` row before `DISTINCT ON`. > - On PostgreSQL with many endpoints and message links, the missing leading `endpoint_id` column caused PostgreSQL to skip-scan `chat_message_links_provider_message_uq (endpoint_id, conversation_id, provider_message_id)` across all endpoints for every matched conversation, reading hundreds of buffers per conversation. Separate `= ANY(...)` arrays also allowed cross-key cartesian matching in SQL, and joining all historical reviews forced extra `heartbeat_runs` lookups and `assessment` JSONB detoasting before `DISTINCT ON` discarded older rows. > - This pull request binds `chat_message_links.endpoint_id = chat_conversations.endpoint_id` in both the single-key and batch queries, replaces the three `= ANY(...)` arrays with deduplicated `(comment_id, issue_id, agent_id)` tuples via `unnest(...)`, and selects only the latest `chat_github_reviews` row per `(endpoint_id, issue_id)` in a lateral subquery before joining `heartbeat_runs` and projecting `assessment->'reviewedCommit'`. > - The benefit is 25x-35x lower query execution time and 34x-50x fewer shared buffer hits on realistic multi-endpoint batches, with exact result equivalence and zero schema changes. ## Linked Issues or Issue Description Refs #20673 Refs #20851 **What happened?** `readInheritedReviewsForKeys` in `server/src/services/chat-channels/github/review-wait.ts` ran slow multi-second queries on hosted multi-tenant PostgreSQL instances when listing in-review issues. `EXPLAIN (ANALYZE, BUFFERS)` showed PostgreSQL skip-scanning `chat_message_links_provider_message_uq` on `conversation_id = chat_conversations.id` without the leading `endpoint_id` column, producing over 200 buffer hits per conversation. The query also used three independent `= ANY(...)` array predicates (allowing cross-key combinations in SQL) and joined all historical `chat_github_reviews` rows to `heartbeat_runs` before `DISTINCT ON` discarded older reviews. **Expected behavior** `readInheritedReviewsForKeys` should look up exact `(comment_id, issue_id, agent_id)` keys using leading-prefix index scans (`chat_message_links_company_comment_idx` or `(endpoint_id, conversation_id)` on `chat_message_links_provider_message_uq`), avoid cross-key matches in SQL, and join `heartbeat_runs` and project `assessment->'reviewedCommit'` only for the latest review per key. **Steps to reproduce** 1. Seed a PostgreSQL database with multiple chat endpoints (across GitHub and other channels), tens of thousands of `chat_message_links`, and 100-250 waiting GitHub PR tasks with 5-20 historical `chat_github_reviews` rows each. 2. Run `VACUUM ANALYZE`. 3. Call `readInheritedGitHubReviewWaits` for 100 or 250 waiting runs and run `EXPLAIN (ANALYZE, BUFFERS)` on the `chat_github_reviews` query. 4. Observe PostgreSQL skip-scanning `chat_message_links_provider_message_uq` across all endpoints (over 100,000 shared buffer hits for 100 keys) and probing `heartbeat_runs` once for every historical review. **Paperclip version or commit** `83f10b968d` (`master`) **Deployment mode** Self-hosted server **Database mode** External Postgres ## What Changed - `server/src/services/chat-channels/github/review-wait.ts`: - Added `eq(chatConversations.endpointId, chatMessageLinks.endpointId)` to both `prepareInheritedReviewQuery` and `readInheritedReviewsForKeys`. - Replaced the three independent `= ANY(...)` array predicates in `readInheritedReviewsForKeys` with deduplicated `(comment_id, issue_id, agent_id)` tuples via `unnest(...)`, matching `chat_message_links.comment_id` with strict equality so `chat_message_links_company_comment_idx` (`WHERE comment_id IS NOT NULL`) is directly eligible and cross-key cartesian matches cannot occur in SQL. - Added `latestGitHubReviewSubquery` (`CROSS JOIN LATERAL ... ORDER BY created_at DESC, id DESC LIMIT 1`) in `readInheritedReviewsForKeys` so `heartbeat_runs` joins and `assessment->'reviewedCommit'` extraction run only on the newest review per `(endpoint_id, issue_id)`, while retaining outer `DISTINCT ON` ordering and shared `inheritedReviewFields` projection with `prepareInheritedReviewQuery`. - `server/src/__tests__/github-review-wait.test.ts`: - Verified batch parity on malformed, null, and valid JSON `assessment` values. - Added regression coverage proving cross-key `(comment_id, issue_id, agent_id)` combinations return zero rows from SQL and mismatched `chat_message_links.endpoint_id` values return `null` in both single and batch reads. - Added an `EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)` regression test over multi-endpoint data confirming `chat_message_links` never skip-scans without `endpoint_id`, `heartbeat_runs` joins only one row per key across multiple historical reviews, and raw wire rows stay under 1,000 bytes. ## Verification - Audited `packages/db/src/schema/chat_channels.ts` and all production write sites of `chat_message_links` (`chat-channels.ts`, `email-channels.ts`, `chat-teams-file-publication.ts`, `interactions/callbacks.ts`, `publications/transport.ts`, `publications/worker.ts`) and `chat_conversations` updates: every insert writes matching `endpointId` for the conversation and no production path mutates `endpointId` on either table. - Ran checks on commit `e76ca43f1714b31fd47fd9149661090dd3a98483`: - `pnpm check:module-boundaries` — passed. - `node scripts/check-test-budget.mjs --base origin/master` — passed (`113 nightly suites validated, 1 test file(s) checked`). - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/github-review-wait.test.ts src/__tests__/github-review-check-state.test.ts src/__tests__/issue-list-review-wait-authorization.integration.test.ts src/services/native-runtime/external-review-wait.test.ts` — 4 test files, 26/26 tests passed. - `pnpm --filter @paperclipai/server typecheck` — passed across all 7 typecheck layers. - Captured apples-to-apples before (`origin/master`) vs. after (`8a7b1939db4d3ee66c6fdfebcac38032c2a2895b`) `EXPLAIN (ANALYZE, BUFFERS)` on embedded PostgreSQL 18.1 with `VACUUM ANALYZE` (253 `chat_endpoints` including 3 GitHub + 20 Slack in the target company and 230 in other companies, 2,980 `chat_conversations`, 89,400 `chat_message_links`, 4,200 `chat_github_reviews` with ~8 KB TOASTed `assessment` JSONB, 4,680 `heartbeat_runs`, 7 warm samples per query, exact result equivalence asserted with `assert.deepEqual`): | Batch | Before (`origin/master`) | After (this PR) | Improvement | | --- | --- | --- | --- | | 100 keys (5 reviews/PR) | 21.85 ms median (21.75-22.03 ms), 109,761 shared buffer hits (`chat_message_links_provider_message_uq` skip-scan: 29,237 searches, 105,656 hits; `heartbeat_runs`: 500 loops, 1,500 hits) | 0.68 ms median (0.63-0.75 ms), 2,208 shared buffer hits (`chat_message_links_company_comment_idx`: 100 searches, 400 hits; `heartbeat_runs`: 100 loops, 300 hits) | 32.1x faster, 49.7x fewer buffers | | 100 keys (20 reviews/PR) | 28.49 ms median (28.02-28.78 ms), 124,939 shared buffer hits (`chat_message_links_provider_message_uq` skip-scan: 30,229 searches, 108,902 hits; `heartbeat_runs`: 2,000 loops, 6,000 hits) | 1.11 ms median (1.09-1.36 ms), 3,619 shared buffer hits (`chat_message_links_company_comment_idx`: 100 searches, 400 hits; `heartbeat_runs`: 100 loops, 300 hits) | 25.7x faster, 34.5x fewer buffers | | 250 keys (5 reviews/PR) | 58.24 ms median (57.77-58.62 ms), 278,373 shared buffer hits (`chat_message_links_provider_message_uq` skip-scan: 73,820 searches, 268,080 hits; `heartbeat_runs`: 1,250 loops, 3,750 hits) | 1.68 ms median (1.59-1.76 ms), 5,525 shared buffer hits (`chat_message_links_company_comment_idx`: 250 searches, 1,000 hits; `heartbeat_runs`: 250 loops, 750 hits) | 34.7x faster, 50.4x fewer buffers | ## Risks - Low risk. No database schema or migration changes. - Adding `chat_conversations.endpoint_id = chat_message_links.endpoint_id` relies on the invariant that every `chat_message_links` row belongs to the same endpoint as its `chat_conversations` row. All production write paths enforce this invariant, and rejecting a mismatched cross-endpoint link is stricter and safer than matching it. - The `CROSS JOIN LATERAL (... ORDER BY created_at DESC, id DESC LIMIT 1)` subquery is mathematically equivalent to the previous `DISTINCT ON` because `heartbeat_runs` is a primary-key `LEFT JOIN` that neither filters nor multiplies rows, and the outer query still applies `DISTINCT ON (comment_id, issue_id, agent_id) ORDER BY ..., created_at DESC, id DESC` across any multiple conversations or endpoints. ## Model Used - Gemini 4 Neon (Google DeepMind, XHigh reasoning, 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 |
||
|
|
69144bcf22 |
Require saved requests for human-owned blockers (#23820)
## Thinking Path > - Paperclip coordinates AI agents and human decisions. > - Native runs report blockers through the completion feedback service. > - A run could name a human owner and stop without saving a question. > - The task then had only a generic blocker card and no answerable choice. > - This change requires a saved request receipt before accepting that blocker. > - The human can answer the request, and the existing continuation flow can resume the work. ## Linked Issues or Issue Description **What happened?** A native run could report a human-owned product decision blocker with no saved question, approval, or decision. The task stopped after publishing the choices only as text. **Expected behavior** The agent must save an answerable request that requires a human response and resumes the task after that response. **Steps to reproduce** 1. Start a native task. 2. Call `paperclip_block` with a human owner, a concrete choice in `unblockAction`, and no request receipt. 3. Before this change, the report was accepted and no answerable request existed. After this change, the agent receives a correction and must save the request first. **Paperclip version or commit** Reproduced against `845ca8506a2a` with an isolated source checkout and embedded PostgreSQL. **Deployment mode** Source tests on macOS arm64 with Node 25.6.1 and pnpm 9.15.4. No hosted deployment was made. Related: #22674 improves the text on generic blocker cards. #20807 changes blocker routing. This change enforces the saved request contract before a native worker can stop. ## What Changed - Require a cited, current human-only interaction with `wake_assignee`, a linked pending approval, or an open decision with `wake_origin_agent`. - Check company, task, creator, recipient, request state, and continuation policy. Reuse active requests from prior runs. Reject historical, dismissed, resolved, expired, and unrelated records. - Give the agent a correction in the same turn when it reports a text-only handoff. Add the request and receipt rules to native task instructions. - Expose `request_human_input` in the closed Muse first-party catalog. It uses the existing task, run, and authorizer checks. Generic API and repository operations stay outside that catalog. - Cover the original failure, request reuse, saved answers and queued response delivery, invalid request states, and approval and decision compatibility. ## Verification - Reproduced the original bug with a failing regression, then confirmed the same test passes after the fix. - Passed 114 tests across `native-human-blocker-feedback`, `native-completion-feedback`, `native-completion-format-feedback`, and `native-execution-input`. The review-fix run passed all 161 tests across these suites and `historical-task-questions`. - Passed the updated 16-test request suite after adding the saved-answer delivery check. - Passed `pnpm --filter @paperclipai/server typecheck` across all server layers. - Passed test-budget validation, `git diff --check`, and the secret/PII scan. - `pnpm verify --explain` selected 2,013 of 2,373 Vitest files. Focused local checks cover this change; required CI must supply broad typecheck, test, build, and runner coverage on the final revision. - Initial verification exposed two TypeScript errors and three tests that expected the old permissive behavior. The type errors and expectations were corrected before the passing runs above. - [The first CI run](https://github.com/paperclipai/paperclip/actions/runs/47462198570/job/145490417452) found two more historical-question tests that expected a human blocker with no saved request to be accepted. Their expectations now match the enforced contract; they still check that historical questions stay answerable and do not gate completion. - Reproduced the Muse review finding with a failing native-profile test. After the catalog fix, all 10 selected Muse tests pass, including the new request test and existing actor, grant, and lock-wait authority checks. - Final revision `7d4928cebe5`: [CI passed](https://github.com/paperclipai/paperclip/actions/runs/47463165222) with 68 successful checks and 6 expected skips. [Greptile scored 5/5](https://github.com/paperclipai/paperclip/pull/23820#issuecomment-7429462031) on this revision. No unresolved review threads remain. GitHub reports a clean, mergeable branch. ## Risks - This tightens native human-owned blocker reports. An older in-flight prompt may receive a correction and must save or cite a request before stopping. - Persisted shapes and identities do not change. Existing questions, approvals, decisions, sessions, and saved results carry forward. No migration is required. - Already committed text-only blockers are not backfilled. They need a new agent turn to create the missing request. - Response delivery is tested through its durable queue. No live provider run or hosted deployment was tested. ## Model Used OpenAI Codex, `gpt-6.1-sol`, with xhigh reasoning effort 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> |
||
|
|
c6a8c3ac06 |
fix(queue): let the person who declined a connection discard its queued notice (#23699)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The task composer shows a queue of messages that wait for the agent's current turn to end > - A saved card response, such as a declined connection, also waits in this queue as a read-only row > - The person cannot remove a "Declined: <service> connection" row. The trash stays disabled, and a forced discard returns 409 > - When the person's own queued messages are in front of it, the row is hidden. When the person trashes the last message, the declined row appears. To the person, the deleted row comes back > - This pull request lets the person who declined the connection discard that notice > - The benefit is that the composer queue no longer keeps a row that the person cannot remove ## Linked Issues or Issue Description **What happened?** A person declined a connection request while the agent's turn was running. A "Declined: Google Sheets connection" row then stayed in the composer queue. The trash button did not remove it. After the person deleted their own queued messages, the declined row showed again. **Expected behavior** The person who declined the connection can remove the declined notice from the queue. After removal, the row does not come back. **Steps to reproduce** 1. Start an agent turn on a task. 2. While the turn runs, queue one or more messages, and decline a connection request from the agent. 3. Trash the queued messages one at a time. 4. The "Declined: <service> connection" row appears. Its trash is disabled, and `DELETE /api/issues/:id/queued-comments/:interactionId` returns 409. ## What Changed - `queued-interaction-response.ts`: a declined `connection_intent` receipt now reports the user who declined it as the one person who can discard it. - Board read path (`queued-comment-board-postgres.ts`): the receipt row sets `canDiscard: true` only for that person. - Mutation lock (`queued-comment-postgres.ts`): a receipt wake now counts as a pending queue, and its snapshot uses the same receipt row and revision as the read path. - Discard use-case: for a saved response, discard cancels the receipt wake and does not delete a comment. The card keeps its Declined outcome. - Discard also marks an unfinished connection delivery as done in the same transaction. A delivery retry after a crash does not send the notice again. - `queuedInteractionEntry` builds the receipt row and its `canDiscard` rule for the read path and the mutation path. - The connection delivery worker counts a wake that a person discarded as delivered. A retry that is already running does not create a new wake. - The read path and the mutation path drop a tool-action outcome the same way, so both compute one queue revision. Edit and reorder refuse every saved-response queue with `queued_comment_not_pending`. - Edit and reorder still return 409 for every saved response. Approvals, answers, accepted connections and tool-action outcomes stay non-discardable. ## Verification - New route tests in `server/src/__tests__/issue-queued-comments-routes.test.ts`: - The person who declined the connection discards the notice. The next read is empty, the wake is `cancelled`, `hasQueuedInteractionResponse` is false, and the card stays `rejected`. Another member gets `canDiscard: false` and cannot discard it. - The notice waits behind two queued messages. Trashing each visible row empties the queue: messages, then the declined notice, then nothing. - The tests failed before the fix (409 on discard) and pass after it. - `npx vitest run src/__tests__/issue-queued-comments-routes.test.ts src/__tests__/issue-queued-comments-dispatch-routes.test.ts src/modules/wake-queue` passes, together with `src/__tests__/connection-intents-service.test.ts`: 19 files, 540 tests. - New tests: a delivery retry that is already running does not send a discarded notice again, and reordering a hidden tool-action outcome returns 409. Both fail without the change. - A route test with an unfinished delivery row checks that discard sets `deliveredAt`. The test fails without the change. - I did not complete a local full `tsc` run. The process ran out of memory on the test machine. CI runs the typecheck. ## Risks - Low risk. The change applies only to declined connection notices. - When the person discards the notice, the agent does not get the decline as a steering message. The agent still sees the Declined card on its next turn. Continuation recovery only redelivers accepted or answered cards, so it does not queue the notice again. - Discard sets `deliveredAt` on an unfinished connection delivery. The delivery worker also treats a discarded wake as delivered, so a retry that is already running does not create a new wake. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use and code execution in a Paperclip agent workspace. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [ ] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [ ] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
3346a95af8 |
fix(adapters): mount skill sources in the local workspace sandbox (#14340)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - `claude_local` and `codex_local` can confine a run with the local
bwrap sandbox (`filesystemScope: "workspace"`)
> - The adapters give the agent its skills as symlinks (in the prompt
bundle, or in `CODEX_HOME/skills`) to the skill source under the
Paperclip instance skills directory
> - The sandbox mounts the bundle and `CODEX_HOME`, but not the link
targets, so every link dangles
> - The agent sees no skill, not even the built-in `paperclip` skill,
and the run gives no warning
> - This pull request mounts each linked skill source read-only in the
sandbox
> - The benefit is that confined agents get the skills that the board
assigned to them
## Linked Issues or Issue Description
No issue exists. Description:
**What happened?**
A `claude_local` agent with `filesystemScope: "workspace"` and assigned
skills ran without skills. Inside the sandbox, `.claude/skills/<skill>`
in the `--add-dir` bundle was a dangling symlink to
`~/.paperclip/instances/default/skills/<company>/__runtime_cache_v1__/…`
(company skills) and to `…/@paperclipai/server/skills` (built-in
skills). `codex_local` had the same problem with `CODEX_HOME/skills`.
**Expected behavior**
The agent reads every desired skill inside the sandbox.
**Steps to reproduce**
1. Create a `claude_local` or `codex_local` agent with `filesystemScope:
"workspace"` and one company skill.
2. Run it and ask it to list its skills, or run `ls -L` on the skills
directory inside the run.
3. The links do not resolve. The workaround is to add both directories
to `filesystemExtraPaths` by hand.
**Paperclip version or commit**
Seen on 2026.916.1, reproduced on `master` at
|
||
|
|
6a5dfc0288 |
feat(recents): store sidebar Recents on the server so every client shares one list (#23706)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The sidebar Recents list shows the tasks from a person's own recent activity > - Each browser kept Recents in `localStorage`. A laptop, a phone, and a second browser each showed a different list > - People expect one list for their account, the same on every client > - This pull request moves Recents to the server. The server keeps one list for each person in each company. The UI shows that list and gets live updates when another client changes it > - The benefit is that every client shows the same Recents in the same order, and a change on one client shows on the others at once ## Linked Issues or Issue Description **Is your feature request related to a problem? Please describe.** Recents is kept in the browser. When I open a task on my laptop, the task does not show in Recents on my phone or in another browser. **Describe the solution you'd like** Keep Recents on the server, so that every client that I sign in to shows the same list. **Additional context** Eligibility (which rows show) does not change. The navigation summaries still decide it (see #23675). ## What Changed - `packages/db`: new `user_recent_tasks` table (company, user, issue, `recorded_at`), unique on company + user + issue. Migration `0515` creates only a new table, so it is `online_compatible`. - `packages/shared`: `RecentTaskRecord`, `RecentTaskList`, `RECENT_TASKS_MAX_ENTRIES` (200), and the `recordRecentTaskSchema` and `importRecentTasksSchema` validators. - `server`: new `recentTaskService` and routes: - `GET /api/companies/:companyId/recent-tasks/me`: the list, newest first. - `POST /api/companies/:companyId/recent-tasks/me` `{ issueId, touch }`: `touch: true` moves the task to the top (server time). `touch: false` adds a missing task below the history and does not move an existing task. - `POST /api/companies/:companyId/recent-tasks/me/import`: imports the list that a browser kept. The later time wins. - `DELETE /api/companies/:companyId/recent-tasks/me/:issueId`. - The server keeps the newest 200 rows for each person. Each change is in the activity log as `recent_tasks.*` with `entityType: "company"` and `details.userId`. The entry does not name the task. Viewers can change their own Recents, like workspace preferences. - Record, import, and list use the normal task read decision. A private or unreadable task gets the same 404 as a missing task. The import skips it, and the list does not return it. - `server/src/realtime/live-events-ws.ts`: sends `recent_tasks.*` events only to the owner's connections, without details. - OpenAPI entries for the four routes. - `ui/src/lib/recent-tasks.ts`: the module is now a client mirror of the server list, not `localStorage`. Optimistic records and removals stay applied until a server list that was requested after the server saved them arrives. This prevents a stale list from hiding a new visit. - `ui/src/hooks/useRecentTasks.ts`: fetches the server list (`queryKeys.recentTasks`). On the first load it imports the old browser list one time and then deletes the browser copy. It does not delete ineligible rows anymore. It hides them, and it requests a new summary batch when new activity occurs on a hidden task. The `awaitingRead` flow is removed because nothing deletes the row while the read is in flight. - `LiveUpdatesProvider`: a `recent_tasks.*` event refreshes Recents. Other company views do not refresh. - A failed save is tried again one time. If it fails again, the client loads the server list again, so an unsaved change does not look saved. - The import reads only the newest browser storage version. - `SidebarRecentTasks`: the "Archive" action removes the task from the server list. - `doc/PRODUCT.md`: describes the shared list. ## Verification - `cd server && npx vitest run src/__tests__/recent-tasks-routes.test.ts` (embedded Postgres): 5 passed. The tests cover: two clients of the same person see the same order; touch and passive seed; personal and company scope (teammate, other company, agent, viewer, suspended member); removal plus activity log plus live events; import, and the 200-row limit. - `cd server && npx vitest run src/__tests__/openapi-routes.test.ts`: 59 passed. - `cd server && npx vitest run src/__tests__/recent-tasks-routes.test.ts src/__tests__/live-events-toast.test.ts`: 21 passed. This includes private-task checks and owner-only socket delivery. - `cd ui && npx vitest run src/lib/recent-tasks.test.ts src/hooks/useRecentTasks.test.tsx src/context/LiveUpdatesProvider.test.ts`: all passed. New tests cover: the same list on a second client, legacy import (success and failure), the record-and-list race, server-time adoption, and live-event scoping. - `packages/db`: `migration-compatibility.ts` classifies `0515` as `online_compatible`. - `packages/shared` typecheck: no errors. `ui` typecheck: no errors in changed files (errors exist only in the ungenerated Storybook feature-map indexes). - `server`: a typecheck of the route, service, and test graph passes. The full `server` typecheck was killed by the local memory limit (exit 137). CI covers it. - `pnpm verify` returned exit 2 (the migration needs broad CI coverage). Required CI supplies that coverage. ## Risks - Medium. This adds a table and changes where Recents is kept. - Each task open now sends one more request and writes one activity row (the same as `issue.read_marked`). The live socket sends the event only to the owner's connections. - Rows that are not eligible stay in the server list (hidden) until they fall out of the newest 200. Before, the client deleted them. - The import reads `paperclip.recentTasks.v3`, `v2`, and the oldest key one time for each browser. If the import fails, the browser copy stays and the next load tries again. - An old tab from the previous release still writes to `localStorage`. The next load of a new tab imports those entries. The later time wins, so this does not reorder newer server entries. > 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`), via Claude Code with tool use (shell, file edit, test runs). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [ ] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [ ] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [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: devinfoley <139239+devinfoley@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
df371acc77 |
fix(recovery): give fresh runs a grace period before the issue-terminal sweep (#13883)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - The control plane keeps issue ownership and run liveness in separate rows, and a recovery sweep reconciles them. > - That sweep can terminalize a `running` heartbeat row on two authorities: a dead process, or a terminal issue above a live row. > - The issue-terminal authority infers orphanhood from the issue status alone. It does not observe the run. > - A reassignment hand-off satisfies that inference while it is healthy: one request sets the issue to `done` and reassigns it, so the receiving agent's run starts while the issue is momentarily terminal and still holds the lock columns. > - The sweep then kills a run that is seconds old and releases the checkout it just acquired. > - This pull request requires the row to have stayed `running` for 60 seconds before the issue-terminal authority applies. > - The benefit is that a reassignment hand-off completes instead of failing with an ownership conflict on a checkout that returned 200. ## Linked Issues or Issue Description No public GitHub issue exists for this bug. Related pull requests: - Refs #13271. That pull request makes a live in-memory executor authoritative over both authorities. It fixes the case where one run sets its own issue terminal and keeps writing. It does not close the window this pull request closes. See "Relationship to #13271" below. **What happened?** An agent set an issue to `done` and reassigned it in the same `PATCH`. The server started the receiving agent's run. The issue was still terminal and still held `checkout_run_id` and `execution_run_id`. The stale-lock sweep read the terminal issue as proof that the new run was orphaned. The sweep marked the run terminal after about 700 ms and cleared the lock columns. The receiving agent had already received `200` from its checkout. Every later status write from that agent failed with an ownership conflict. **Expected behavior** The sweep must not terminalize a run that is seconds old on the strength of the issue status alone. A run that just acquired a checkout must keep it. **Steps to reproduce** 1. Assign an issue to agent A and let its run check the issue out. 2. Send one `PATCH` that sets the issue to `done` and reassigns it to agent B. 3. Let the server start agent B's run. The issue still holds both lock columns. 4. Run the stale issue-lock sweep inside the first seconds of that run. 5. See the sweep mark agent B's run `succeeded` with error code `orphaned_running_run_issue_terminal`. 6. Send a status write from agent B. See the ownership conflict. **Paperclip version or commit** `master` at `60c7c9cd1`. **Deployment mode** Self-hosted server with PostgreSQL. The defect is in the shared run lifecycle. It is not specific to an adapter. ## What Changed - Added `ISSUE_TERMINAL_MIN_RUN_AGE_MS` (60 seconds) to `server/src/services/recovery/service.ts`. - Suppressed the issue-terminal authority in `terminalizeOrphanedRunningRun` while the run row is younger than that age, and logged a warning when the suppression fires. - Left the process-death authority unchanged, so a dead process is still swept immediately at any run age. - Made the two reuse-lease tests seed an aged run row, because an orphan is by definition a row that stayed `running`. - Added a test for the reassignment hand-off. It asserts that the fresh run survives and that both lock columns survive. - Added a test for a fresh run with a dead recorded pid. It asserts that the sweep still terminalizes the run as `interrupted` and still clears the locks. ## Relationship to #13271 #13271 moves the `liveRunExecutions` check to an early return, so it covers both authorities. That is a good change and this pull request composes with it. It does not cover this window, for two reasons. 1. The run row reaches `running` before the execution registers itself. `activeRunExecutions.add(run.id)` runs inside the execution body, after awaited database work. A sweep that fires in that gap sees no live execution. The run also has no recorded pid yet, so the process-death authority stays silent by design. The issue-terminal authority is the only one left, and it fires. 2. `activeRunExecutions` is a module-scope `Set`. It is per server process. A sweep on one process cannot see an execution owned by another. The grace period covers both, because run age is in the row itself. ## Verification - `node scripts/run-vitest-stable.mjs server/src/__tests__/recovery-stale-issue-lock-sweep.test.ts` is the target suite. I could not run it in my environment: the suite needs embedded PostgreSQL, and my sandbox has no host for it. I ask CI to be the check here. Please do not merge on a red run. - I did verify the guard logic directly. I extracted the compiled guard and drove it against seven cases: a 700 ms run under a `done` issue, a 59 s run, a 61 s run, a one-hour run under a `cancelled` issue, a row with no usable timestamp, an ISO string timestamp, and a null issue status. All seven matched the intended outcome, and the warning fired only on the three suppressed cases. - I traced the single call site. `sweepStaleIssueLocks` builds `runRows` with `db.select()` and no projection, so `run.createdAt` is always present at run time. There is no other caller. - Reviewers can reproduce the bug with the six steps above. The new hand-off test fails on `master` and passes with this change. ## Risks Low, and the direction of the failure is the safe one. - A genuinely orphaned run now keeps its lock for up to one extra sweep tick. The sweep is periodic, so the next tick clears it. Nothing is stranded. - The guard fails open. If the row carries no usable timestamp, the sweep behaves as it does today. - The process-death authority is untouched. A hard crash is still reaped at once. - Two existing tests changed their fixture, not their assertions. They still assert that the sweep terminalizes the run and clears the lock. - The 60 second value is a constant, so an operator who needs a different window changes one line. ## Model Used Claude Opus 4.7 (`claude-opus-4-7`) by Anthropic, through Claude Code with tool use 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 - [ ] I have run tests locally and they pass — the suite needs embedded PostgreSQL, which my environment cannot start. See Verification. - [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 — pending the first CI run - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups — pending review - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Builder <builder@nublo.net> Co-authored-by: Claude Opus 5 <noreply@anthropic.com> |
||
|
|
67e6a6aa2a |
fix(plugins): bridge issue.child_created activity to issue.created plugin event (#13728)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Plugins subscribe to core domain events such as `issue.created` through the `events.subscribe` capability > - Issues created through `POST /issues/:id/children` or accepted-plan decompositions only log the `issue.child_created` activity action, and that action was not in the plugin event bridge in `activity-log.ts` > - Subscribers to `issue.created` therefore never observe child issues, so plugin workflows that track every new issue silently miss decompositions > - This pull request maps `issue.child_created` to the `issue.created` plugin event type > - The benefit is that plugin subscribers observe every new issue through one event type, and the bridged payload matches a top-level creation because the activity row already carries `entityType: "issue"` and the new child issue id ## Linked Issues or Issue Description Fixes: #13466 ## What Changed - Added `issue_child_created: "issue.created"` to `ACTIVITY_ACTION_TO_PLUGIN_EVENT` in `server/src/services/activity-log.ts`, with a comment explaining why the bridge is safe (same entity shape as top-level creation) - Added `server/src/__tests__/activity-plugin-event-bridge.test.ts` covering: - `issue.child_created` is bridged to `issue.created` with the child issue id as the event entity - a native `issue.created` action still passes through unchanged - unmapped actions still emit no plugin event ## Verification ```sh ./node_modules/.bin/vitest run server/src/__tests__/activity-plugin-event-bridge.test.ts ``` All 3 tests pass against an embedded Postgres instance. Also ran `git diff --check`. ## Risks Low risk. The change only adds a mapping entry; no existing activity action is remapped or removed. Plugins that already handle `issue.created` will now also receive child creations. The activity details payload carries an extra `parentId` field for child creations, which additive subscribers should tolerate. No migration or schema change. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used OpenAI Codex (GPT-5, coding-agent mode, repository tool use) — assisted with root-cause analysis, the mapping change, and the new test file. ## 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: 馨冉 <xinxincui239@gmail.com> |
||
|
|
845ca8506a |
test(server): drain structured issue route work before teardown (#23813)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Issue routes can wake an assigned agent in the background. > - The structured issue parity suite uses those real routes and a temporary database. > - It could stop that database while route-triggered work was still active. > - The resulting unhandled database error failed source verification after test assertions passed. > - This pull request drains that work after each test and checks quiescence. > - Database teardown now starts only after the suite's background work settles. ## Linked Issues or Issue Description **What happened?** [Cloud readiness run 47456696780, attempt 2](https://github.com/paperclipai/paperclip/actions/runs/47456696780/job/145473729239) reported 1,562 tests passed and three skipped in server shard 13/20, then failed on an unhandled PostgreSQL `read ECONNRESET`. The error came from type discovery and was reported while `canonical-issue-structured-parity.test.ts` was running. This cancelled [image run 47456696824](https://github.com/paperclipai/paperclip/actions/runs/47456696824). **Expected behavior** The fixture must settle route-triggered wakeups and executions before it resets data or stops PostgreSQL. **Steps to reproduce** On master `83f10b968dba1cb0300f216cabce3a5924f5d3c8`, add the quiescence assertion from this diff without the drain. Run `PAPERCLIP_VITEST_RETRY=0 pnpm exec vitest run server/src/__tests__/canonical-issue-structured-parity.test.ts --maxWorkers=1`. The assertion failed locally with three active executions and one pending wake. The old teardown also logged queries against a closed connection. ## What Changed - Await the existing heartbeat drain after each test. - Assert zero active executions and pending wakes before the fixture can continue or stop its database. - Keep the route, channel isolation, schema validation, and authorization checks in place. ## Verification - Red: the cleanup assertion failed with `activeRuns: 3`, `pendingWakes: 1`, and `quiescent: false`. - Green: both tests passed after the drain, with retries disabled and no unhandled errors. - Test budget and `git diff --check` passed. - Final PR head `f4679f12c299ff7718112f5d368fce907d1d0f3a`: 64 checks passed, seven skipped, no pending or failed checks; GitHub reports no merge conflicts. [Greptile rated it 5/5](https://github.com/paperclipai/paperclip/pull/23813#issuecomment-7429108337), with no review threads or follow-ups. - The first server typecheck found stale local Plugin SDK declarations that omitted `runtime_updating`. The value already exists in SDK source. Rebuilt the Plugin SDK and shared package; the final server typecheck passed, and both focused tests passed again with retries disabled. - `pnpm verify --explain` conservatively retained 2,009 of 2,372 test files. Required CI will provide that broad coverage. - Recovery: [exact-source verification attempt 3](https://github.com/paperclipai/paperclip/actions/runs/47456696780/job/145482927885) passed for master `83f10b968dba1cb0300f216cabce3a5924f5d3c8`. [Image attempt 2](https://github.com/paperclipai/paperclip/actions/runs/47456696824/job/145483491486) then published the AMD64/ARM64 manifest as `ghcr.io/paperclipai/paperclip:sha-83f10b9`, digest `sha256:9c23177cbe9744eded163c56bc88904aa0901442fe9932b6ea5cf329f143c66e`. All publication gates remained in place. This establishes operational recovery; resolving the cleanup race requires this change. ## Risks - Low risk. Only test fixture cleanup changes. Production code and database behavior stay as they are. - The drain can settle work that the route started before the HTTP response. A future unfinished execution fails the quiescence assertion instead of leaking into database teardown. - No documentation change is needed because the application contract does not change. ## Model Used - OpenAI `gpt-6.1-sol`, through the Codex harness in T3 Code, with xhigh reasoning effort and shell tools. The context window size is not exposed. ## 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> |
||
|
|
bc526683c2 |
fix(github-chat): fix initial repository import and verify UX states (#23760)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work.
> - The GitHub Code Review Bot setup wizard registers a GitHub App,
discovers its installation repositories, imports initial repository
selections, and verifies access before activation.
> - When a user or agent saves review configuration on a draft before
installing the GitHub App, the wizard skipped initial repository import
because it required `saved.revision === 0`, leaving enabled GitHub
repositories disabled in Paperclip and showing a misleading "Enable at
least one repository from the App installation." error.
> - The wizard also closed initial repository import prematurely when
GitHub returned zero repositories, failed to refresh repositories on
retry, treated removed installations (HTTP 404) as generic 422 failures
and transient repository-sync errors as empty installations, omitted the
direct GitHub App installation link on verification errors, and kept
showing "Checking GitHub access…" while idle on a failed check.
> - This pull request decouples initial repository import from review
configuration revision, recovers verifying endpoints stuck with a
pending initial import, maps removed installations and transient
repository sync errors to structured verification check codes with
validated GitHub URLs, and updates the setup verify screen to show clear
error states, accurate paired links/labels, and active retry feedback.
> - The benefit is that pre-configured GitHub review bots connect
cleanly when the App is installed, and operators get accurate error
diagnostics, direct GitHub installation and Access settings links, and
clear retry feedback when setup checks fail.
## Linked Issues or Issue Description
**What happened?**
During GitHub Code Review Bot setup
(`/apps/chat/connect?provider=github&purpose=chat&resume=...`), the
verify step failed with "Enable at least one repository from the App
installation." even when one repository was already enabled on the
GitHub App installation. The verify screen also kept displaying
"Checking GitHub access…" when idle, did not link to the GitHub App
installation URL, and did not clearly explain whether the problem was on
GitHub or in Paperclip Access settings.
**Expected behavior**
Installing the GitHub App with one or more repositories enabled should
import and enable those repositories during initial setup even if custom
review configuration was saved earlier, while preserving that saved
configuration. When verification genuinely fails for missing
repositories, missing permissions, removed/suspended installations, or
transient GitHub repository sync errors, the screen should stop polling,
replace the checking indicator with a clear error card, pair each GitHub
link with an accurate label, link to Paperclip Access settings, and show
active checking feedback only while a retry or refetch is running.
**Steps to reproduce**
1. Create a GitHub Code Review Bot draft and save custom review
configuration (`PUT /api/chat-endpoints/:id/github/configuration`),
incrementing configuration revision to `1`.
2. Register and install the GitHub App on GitHub with one repository
selected, verify webhook delivery, and link a GitHub identity.
3. Resume
`/apps/chat/connect?provider=github&purpose=chat&resume=<endpointId>`.
4. Observe that `POST /api/chat-endpoints/:id/github/setup` leaves the
repository disabled, marks `initialRepositoriesImported: true` while
leaving `initialRepositoryImportPending: true`, and returns `state:
"verify"` with "Enable at least one repository from the App
installation." and no GitHub installation link.
**Paperclip version or commit**
Reproduced on `master` at commit `e2e2265085`.
**Deployment mode**
Self-hosted server
**Agent adapter(s) involved**
Not adapter-specific (core bug)
## What Changed
- Extract initial GitHub repository import eligibility/transition logic
into `server/src/services/chat-github-initial-import.ts` and decouple
initial repository import in `server/src/services/chat-github-wizard.ts`
from `saved.revision === 0` so pre-saved review configuration no longer
blocks enabling repositories granted during initial App installation,
while keeping `saved.revision === 0` strictly for default review
configuration writes.
- Recover verifying endpoints left in the prior half-state
(`initialRepositoriesImported: true` with
`initialRepositoryImportPending: true` and `repositorySelectionSaved`
unset) without re-enabling repositories after an explicit user save
(`repositorySelectionSaved: true`).
- Keep `initialRepositoryImportPending` open when GitHub returns zero
repositories during initial import
(`server/src/services/chat-github-wizard.ts` and
`server/src/services/chat-channels/resource-reconciliation.ts`), refresh
repository inventory on wizard retry when no enabled available
repository exists, and track transient repository-sync errors so failed
`/installation/repositories` refreshes skip initial import and emit
`repositories_sync_failed` instead of misreporting
`no_installation_repositories`.
- Map HTTP 404 on `/app/installations/:id` in
`server/src/services/chat-github-management.ts` to
`installation_missing` + `managementUrl` (keeping 401/403/5xx and
transient failures separate), and enforce `!permissionsOk` precedence
(`permissions_required`) over cached repository state.
- Preserve `setup.github.managementUrl` and sibling setup fields via
atomic `jsonb_set` in
`server/src/services/chat-channels/github/app-setup.ts`.
- Centralize strict GitHub URL validation
(`safeGitHubInstallationManagementUrl`, `safeGitHubAppInstallUrl`,
`safeGitHubAppUrl`) and structured `GitHubVerificationCheckCode` values
(including `repositories_sync_failed`) in
`packages/shared/src/types/github-app-setup.ts` and
`packages/shared/src/index.ts`, with OpenAPI schema updates in
`server/src/routes/openapi.ts` and UI API types in
`ui/src/api/githubChat.ts`.
- Extract `deriveGitHubVerifyView`, `shouldPollGitHubVerify`, and
`<GitHubVerifyStatus />` into
`ui/src/pages/apps/chat/GitHubVerifyStatus.tsx` and simplify
`ui/src/pages/apps/chat/GitHubChatSetup.tsx` so verification failures
stop 5-second background polling, pair every external GitHub link with
an accurate label (including `installation_missing` fallback to
`managementUrl`), show active checking feedback only while
retrying/refetching, and link to Paperclip Access and Connection
settings.
- Add unit, integration, and UI tests in
`server/src/services/chat-github-initial-import.test.ts`,
`server/src/services/chat-github-management.test.ts`,
`server/src/__tests__/chat-channels/github-setup-and-access.integration.test.ts`,
`ui/src/pages/apps/chat/GitHubVerifyStatus.test.ts`, and
`ui/src/pages/apps/chat/GitHubChatSetup.test.tsx`.
- Update `tests/runner-e2e/source-sdk-public-inputs.json` for the shared
type and helper exports.
## Verification
Tested on Linux through revision `9a5a949098`:
- Red-green TDD proofs:
- Pre-saved review configuration and stuck verifying endpoint recovery
(`server/src/__tests__/chat-channels/github-setup-and-access.integration.test.ts`):
confirmed both failed before the wizard fix (`Received: "verify"`,
`Expected: "connected"`) and passed after.
- Removed installation HTTP 404 (`installation_missing` +
`managementUrl`) and `!permissionsOk` precedence
(`server/src/services/chat-github-management.test.ts` + integration
test): confirmed red before fix, green after.
- Transient `/installation/repositories` 503 failure with empty cache
and valid permissions (`repositories_sync_failed`, followed by
successful retry -> `connected`) and UI `installation_missing` fallback
label (`ui/src/pages/apps/chat/GitHubVerifyStatus.test.ts`,
`GitHubChatSetup.test.tsx`,
`github-setup-and-access.integration.test.ts`): confirmed red before
fix, green after.
- Server unit & OpenAPI tests on `9a5a949098`:
- `pnpm --filter @paperclipai/server exec vitest run
src/services/chat-github-management.test.ts
src/services/chat-github-initial-import.test.ts` (47/47 passed: 39
management + 8 initial-import).
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/openapi-routes.test.ts` (59/59 passed).
- Server integration tests (`c1f234335f`; full suite running in CI on
merged head `9a5a949098`):
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/chat-channels/github-setup-and-access.integration.test.ts
-t "recovers from an empty initial GitHub repository inventory|keeps
explicitly disabled repositories disabled|imports GitHub App
installation repositories even when review configuration was
pre-saved|recovers a verifying endpoint whose
initialRepositoriesImported|returns installation_missing with
managementUrl when the GitHub installation is removed|surfaces a
retryable repositories_sync_failed check"` (6/6 passed).
- UI tests & typecheck on `9a5a949098`:
- `pnpm --filter @paperclipai/ui exec vitest run
src/pages/apps/chat/GitHubChatSetup.test.tsx
src/pages/apps/chat/GitHubVerifyStatus.test.ts
src/pages/apps/chat/chat-ui-contract.test.ts` (27/27 passed) and
`ui/src/lib/analytics/replay-masking.test.tsx` (236/236 passed).
- `pnpm --filter @paperclipai/shared build && pnpm --filter
@paperclipai/shared typecheck && pnpm --filter @paperclipai/ui
typecheck` (passed).
- `node scripts/check-token-gates.mjs` — zero violations in touched
files.
- Release registry check on `9a5a949098`:
- `node tests/runner-e2e/source-sdk-public-inputs.mjs
|
||
|
|
f23af2e079 |
Fix user attribution for agent lifecycle verification (#23800)
## Thinking Path > - Paperclip manages work for AI agents. > - An agent must pass execution checks before it can run work. > - Personal AI accounts require the identity of the responsible user. > - An environment change could start those checks without a user identity. > - The manual connection test still passed because it used the signed-in user. > - This pull request records the configuring user and repairs missing identity on an authorized retry. ## Linked Issues or Issue Description **What happened?** An agent could pass its manual connection test and stay paused after an environment change. Background verification had no responsible user and rejected access to the selected personal AI account. Retry now repeated the same failure. **Expected behavior** Verification started by a configuration change uses the configuring user. An authorized retry can repair an older operation that has no responsible user. Existing account sharing and task access checks still apply. **Steps to reproduce** 1. Use an agent with a personal AI connection and no saved lifecycle user or company default responsible user. 2. Move the agent to an environment that requires setup. 3. Run its manual connection test. The test passes under the signed-in user. 4. Observe failed background verification. Retry now does not repair the missing identity. **Paperclip version or commit** Reproduced on base commit `f0d4f6c3eb2e931f2f7a3e8b426f964aeb54aeee`. **Deployment mode** Authenticated hosted server. The local regression uses disposable PostgreSQL databases on macOS arm64, Node 25.6.1, and pnpm 9.15.4. ## What Changed - Record the authenticated responsible user when a configuration change starts a new lifecycle operation. Include the verified human context for an agent acting on behalf of a user. Keep the prior identity for changes without that context. - Pass the authenticated board identity to the existing retry command. Fill only missing responsibility; preserve an operation's recorded owner. - Start a new operation when repairing a missing identity. Repeat the host check under that identity. A prior attempt cannot complete the replacement operation. - Extend the lifecycle owner suites to cover human and delegated configuration attribution, retry repair, existing owners, active leases, readiness, and request-body spoofing. The existing board, agent, and company access checks remain covered. The lifecycle module owns the repair. Its internal store contract now accepts the authenticated retry identity. The routes supply those values after their existing authorization checks. No new API field, migration, provider policy, or credential permission is added. ## Verification - Before the fix, focused regressions failed in four cases: configuration attribution, board retry attribution, and retry identity repair with and without a lease. - The three owner suites passed all 141 tests after the fix. The final retry suite passed all 27 tests, including rejection of a stale host completion after identity repair. - Server typechecking passed with `node scripts/typecheck-layers.mjs` after the Runner and SDK build prerequisites. An initial test-only type error was corrected with the lifecycle operation type. - `pnpm verify --explain` returned exit 2 because the internal port type lies outside the resolved runtime test graph. Required CI will supply the listed broad typecheck, test, build, and end-to-end coverage. No full local suite pass is claimed. - Test budget, module boundaries, runtime push guard, whitespace, and local secret/PII checks passed. - CI found one stale mocked retry expectation in `agent-cross-tenant-authz-routes.test.ts`. It now checks the authenticated board user as well as the agent ID. All 18 tests in that suite pass locally. The interrupted native-runner CI job was stopped by a runner shutdown; the new revision will rerun CI. - Greptile reviewed the final `e5701b3584a57bbdde269b60439c561acca1f9b1` revision at 5/5. There are no unresolved review threads. - GitHub CI passed on `e5701b3584a57bbdde269b60439c561acca1f9b1`: all 68 reported checks are green, including typecheck, build, native Runner, serialized server, general tests, and end-to-end shards. [CI run](https://github.com/paperclipai/paperclip/actions/runs/47452634326). The initial canceled Runner attempt and stale mock failure are superseded by this successful run. - Hosted acceptance remains pending deployment of the reviewed revision. No live provider call is made by the regression tests. ## Risks - Identity repair does not change credential sharing. Verification still fails if the responsible user lacks access to the selected account. - An identity repair starts a replacement operation and fences any old lease. Existing plugin and host work must pass under that operation before readiness. - No schema or migration changes. Background retry behavior without an explicit user keeps the saved identity. ## Model Used - OpenAI `gpt-6.1-sol`, through the Codex harness in T3 Code, with xhigh reasoning and terminal tool access. The harness does not expose the context-window size. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing> |
||
|
|
1bbf734ce6 |
fix(connections): avoid timeouts when saving agent access (#23790)
## Thinking Path > - Paperclip manages agents and the connections they can use. > - A connection's Permissions page saves its actions and agent audience together. > - The save checks the saved profile, its agent targets, and related accounts. > - Those checks repeat database reads for each target and action. They also expand the same profile for each related account. > - On a large company, the request can time out before it reaches the save transaction. > - This change bounds that work and keeps the existing permission decisions and reauthorization boundaries. ## Linked Issues or Issue Description **What happened?** Adding an agent to an existing connection leaves the page at “Saving…” until the request fails. Refreshing shows the old audience. The browser reproduction ended with HTTP 502 at the five-minute request deadline. **Expected behavior** Save an authorized agent-audience change and return the saved permissions without repeated checks across the full company and catalog. **Steps to reproduce** Use a company with many agents, several accounts under one application, and an existing connection profile with many catalog entries. Add an agent on the connection's Permissions page. The new regression covers 40 additional agents, three accounts, and 50 actions through the assembled server and real PostgreSQL. GitHub searches found no duplicate fix. ## What Changed - Share membership and grant reads inside one authorization check. Retain the existing two-second age limit. Close the scope before the handler runs and start a fresh scope for each reauthorization. - Resolve catalog references and canonical agent target IDs in batches. Keep the ordinary target lookup outside the check scope and for other UUID spellings. Continue to decide permissions for every target. - Keep the already checked profile in each related account's permission scope without expanding that profile again. Continue to check changed profiles, gateway bindings, and the referenced accounts. - Add a save regression with SQL-count bounds and a subsequent grant-revocation refusal. Cover nested, completed, and failed authorization-check scopes. ## Verification - `cd server && pnpm run typecheck` — passed, including the test-tree layers. Repeated successfully after rebasing onto current `master`. - `cd server && pnpm exec vitest run src/__tests__/connection-management.integration.test.ts src/__tests__/connection-management-delegated-policy.integration.test.ts src/__tests__/connection-management-gateway-rules.integration.test.ts src/__tests__/connection-management-delegated-tests.integration.test.ts src/__tests__/connection-management-providers.integration.test.ts src/__tests__/connection-management-gateways.integration.test.ts src/__tests__/authorization-request-reads.test.ts` — 7 files and 110 tests passed. - After rebase, repeated both `connection-management.integration.test.ts` and `authorization-request-reads.test.ts` on head `fc8b3ecf16cc`: 2 files and 31 tests passed. The 110-test run above preceded the rebase. - Red/green: the new HTTP regression first failed on 2,218 membership reads. It now saves the requested audience, retains all 50 actions, meets the query bounds, and refuses the next request after its grant scope is restricted. - Read-only replay of the affected authorization path completed with the fix. No tenant database rows were changed by the replay. - `node scripts/check-test-budget.mjs --files server/src/__tests__/connection-management.integration.test.ts server/src/__tests__/authorization-request-reads.test.ts` — passed. - `git diff --check` and Gitleaks scan of the diff — passed. The diff was also checked for private identifiers and personal data. - `pnpm verify` selected 2,008 test files through the shared authorization dependencies. That broad local run was stopped; it is not a pass. The focused suites and server typecheck above passed. Required CI must supply the broad checks on this revision. - Final head `fc8b3ecf16cc`: [CI run](https://github.com/paperclipai/paperclip/actions/runs/47445309988) passed, including typecheck, build, all general and serialized server shards, native Runner checks, and all end-to-end shards. [Greptile review](https://github.com/paperclipai/paperclip/pull/23790#issuecomment-7426956976) scored 5/5 with no actionable issues or unresolved threads. GitHub reports the branch mergeable with a clean merge state. - The fix has not been deployed. A live browser save and refresh on the new release remain to be verified after deployment. ## Risks No schema, API, or deployment-policy change. Shared authorization code is affected. Reuse is limited to one check with the existing age limit; each pre-write reauthorization reads fresh facts. The related-account checks still include profile IDs in their permission scopes. Existing delegated, scoped-grant, company-isolation, and gateway tests pass. Revert this commit to roll back. ## Model Used OpenAI GPT-6.1 Sol (`gpt-6.1-sol`) through Codex in T3 Code, with xhigh reasoning 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 (the public contract is unchanged; the internal boundaries and validation are recorded above) - [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> |
||
|
|
ab79cb9cdd |
fix(heartbeat): wait for an updating runtime before workspace setup fails (#23779)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Before a run starts its agent, Paperclip prepares the task workspace through a workspace provider plugin > - A hosted agent computer can apply an update. While it updates, it finishes its running tasks and refuses new workspaces > - The provider can only report this refusal as a generic `remote_incomplete` failure. Setup retries that failure two times in about 90 seconds (#23764), but an update can wait for running tasks for an hour > - So each new task on that computer fails setup, reports an error, and stops, although it only had to wait > - This pull request adds the closed provider reason `runtime_updating` and a separate wait lane for it. Setup holds the run and retries the same workspace every 2 minutes for up to 1 hour. The wait does not use the failure retry budget, and Paperclip does not report the run as a failure while the wait continues > - The benefit is that new tasks wait for an updating agent computer and then start, instead of failing ## Linked Issues or Issue Description Refs #23764, #23362 **What happened?** A hosted agent computer refused every new workspace preparation while it applied an update and finished its long running tasks. The provider reported each refusal as `remote_incomplete`. Setup failed each new run. Every retry of the same workspace failed the same way, and each failure was reported to error tracking. On one staging stack this happened 34 times in two hours, for two agents. **Expected behavior** A provider can say that the selected runtime is updating. Setup then holds the run and retries the same workspace after the update. The retry does not spend the failure budget. Paperclip reports the failure only if the wait ends without success. **Steps to reproduce** 1. Start a legacy run whose workspace preparation calls a workspace provider plugin. 2. Have the provider reject preparation because its runtime is updating. Before this change, the only fitting reason is `remote_incomplete`. 3. Setup records `workspace_storage_incomplete` and retries two times (30 s and 60 s). Then the task stops and the failure is reported, while the runtime is still updating. **Paperclip version or commit** `master` at `30334c1f03`. **Deployment mode** Hosted (Paperclip Cloud agent computers). A self-hosted workspace provider can use the same reason. ## What Changed - `packages/plugins/sdk/src/workspace-operation-error.ts`: add the closed reason `runtime_updating` ("the selected runtime is applying an update and refuses new workspaces until it finishes"). - `server/src/services/workspace-provider-failure.ts`: give `runtime_updating` a fixed, retryable message. Map it to the new setup code `workspace_runtime_updating`. Add `WORKSPACE_RUNTIME_UPDATING_RETRY` (reason `runtime_update_wait`, 30 attempts, 2 minutes apart). Add the code to `WORKSPACE_STORAGE_RETRY_CODES`, so the existing deferred error report also covers it. - `server/src/services/heartbeat/run-completion.ts` and `heartbeat/retries.ts`: schedule a failed pre-dispatch `workspace_runtime_updating` run with the wait lane, and use the lane's budget in `failedRunRetryBudgetSpent`. This is the same pattern as `runner_revision_mismatch`. - `server/src/services/execution-recovery-attempt.ts`, `modules/run-dispatch/domain/wake-context.ts`, `task-interruption-presentation.ts`: `runtime_update_wait` is an uncharged preparation wait. An answered interaction keeps its continuation through the wait, and the task shows a wait, not a failure. - `failed-preparation-retry.ts`, `legacy-execution-recovery.ts`, `recovery/service.ts`, `agent-task-run-telemetry.ts`: treat `workspace_runtime_updating` like the other transient workspace preparation codes. - `recovery/stranded-notice.ts`: add a notice for a wait that ended without success ("Agent computer was still updating"). ## Verification - Red before the change (test files only, source reverted): 9 new tests fail in `workspace-provider-failure.test.ts`, `execution-recovery-attempt.test.ts`, `heartbeat/retries.test.ts`, `heartbeat/run-completion.test.ts` and `run-failure-report-sandbox-resume.test.ts`. - `pnpm verify` did not run: its workspace link repair failed for `plugin-orchestration-smoke-example`, before test selection. The SDK change also affects many packages, so CI supplies the broad coverage. - Green after the change: the same 5 files pass (267 tests). Related files also pass: `task-interruption-automatic-path`, `task-interruption-query`, `wake-context`, `stranded-notice-remote-workspace-environment`, `task-interruption-presentation` (181 tests); `agent-task-run-telemetry`, `legacy-continuation-authority`, `heartbeat-retry-scheduling` (179 tests); plugin SDK `workspace-operation-error`, `workspace-provider` (20 tests). - `pnpm --dir server typecheck` and `pnpm --filter @paperclipai/plugin-sdk typecheck`: pass (server typecheck run with `PAPERCLIP_TYPECHECK_LOW_MEMORY=1` because of a local memory limit). - CI supplies the full suite. - Review follow-up (`cf73701742`, `d7540263bd`): update waits keep their count in `executionRetryAccounting` (`runtimeUpdateWaits`) across other retry lanes. An answered interaction whose update wait runs out is escalated like an exhausted storage wait. The pinned SDK input registry is refreshed. The two new tests failed before the fix and pass after it. `execution-recovery-attempt`, `heartbeat/retries`, `workspace-provider-failure` and `run-failure-report-sandbox-resume` pass (83 tests). `heartbeat/run-completion` and `modules/wake-queue` pass (577 tests). `tests/runner-e2e/source-sdk-public-inputs` passes (13 tests). `pnpm --dir server typecheck` passes. ## Risks - Low risk. No schema, migration, API route or wire protocol shape change. The reason set is closed and validated on both sides. An older Core that receives `runtime_updating` treats it as an unknown provider failure, as before. - A provider must not send `runtime_updating` before the new SDK is available to it. The SDK constructor rejects an unknown reason, so a provider update has to follow this change. - The wait is a bounded scheduled retry after a real refusal, not idle polling: at most 30 retries in one hour per waiting run. Each retry is one workspace preparation call. When the wait ends without success, the run is reported and the task shows a named notice with a Retry action. - Only legacy runs that fail before provider dispatch use the lane. Started and native runs keep `setup_failed`. ## Model Used - Anthropic Claude Opus 5.5 (`claude-opus-5-5`), via Claude Code with tool use (code search, file edits, shell, local test execution, 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: paperclipbugbot <356415228+paperclipbugbot@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
14f23fef03 |
fix(plugins): offer direct Buffer setup when Composio has no sign-in link (#23782)
## Thinking Path > - Paperclip helps people manage AI agents for work. > - Plugins lets people connect tools to their agents. > - Some tool connections use the Composio gateway. > - Buffer requires a custom OAuth app in the Composio project that serves the session. > - When that gateway returns no sign-in link, Plugins can help the user open Buffer's own MCP setup. > - This pull request opens the existing connection form with the Buffer name and endpoint filled in. ## Linked Issues or Issue Description **What happened?** Plugins showed a generic error when Composio returned no Buffer sign-in link. **Expected behavior** The user can open the direct Buffer setup from the error. For other apps, the user can open Composio's app settings. **Steps to reproduce** In Plugins, select Buffer and choose a saved Composio gateway without a configured Buffer OAuth app. Select Continue. **Additional context** [Buffer's MCP setup](https://developers.buffer.com/guides/integrations/other-ai-tools.html) accepts a Buffer API key. [Composio's Buffer setup](https://composio.dev/toolkits/buffer) requires a custom OAuth app. [Composio auth configs belong to one project](https://docs.composio.dev/kb/guide/dashboard-auth-configs-navigation). Related prior work: Refs #19408. ## What Changed - Return a machine-readable code when Composio returns no sign-in link. - Offer the direct Buffer MCP form with its official address. Offer a link to Composio app settings for other toolkits. - Clear the old sign-in link when the user requests a new one. Keep the link if the completion check fails. - Document the setup options. Refresh the shared SDK test input pins. ## Verification - Reproduced the missing-link API response with an embedded database and a Composio response fixture. The new test failed on the old server. - Passed 13 focused tests across the Composio route, Plugins setup dialog, and the MCP URL prefill flow. The replacement-link test reproduced the stale link before the fix. A second test checks that the sign-in link stays available after a failed completion check. - Sent an unauthenticated MCP initialize request to Buffer's documented endpoint and confirmed that it requires authentication. A real Buffer consent or API-key test needs a Buffer account with access. ## Risks - Low risk. The new action opens the existing MCP setup page. The user chooses the credentials and access before Paperclip creates the connection. - A valid Composio sign-in link still takes the user through Composio. ## Model Used - OpenAI GPT-6 (Codex), with repository, test, and GitHub 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 described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links - [x] My branch name describes the change - [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> |
||
|
|
039e4c0a57 |
fix(native): stop paperclip_block from reassigning tasks and audit assignee changes (#23780)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Native Paperclip Runner agents report blockers with `paperclip_block`, which includes a descriptive `blocker.owner` field (`kind` and `name`). > - PR #22962 made `paperclip_block` reassign `issue.assigneeAgentId` whenever `blocker.owner` named another company agent, including when the task was only waiting on a durable dependency (`durable_dependency_blocker_bound`). > - That collided directly with Paperclip's own execution prompt (which instructs agents waiting on a child or prerequisite task to call `set_dependencies` and then `paperclip_block` naming the dependency's agent), silently transferred task ownership with no return path, could cross multi-user AI credential boundaries, and omitted the assignee change from the `issue.updated` activity record. > - This pull request stops `paperclip_block` from reassigning tasks at all, preserves the original assignee on dependency-gated blocks, guides agents toward explicit delegation/reassignment tools (`create_task` + `set_dependencies`, `reassign_task`, `handoff_case`) at report time when no dependency exists, and records assignee field changes in native `issue.updated` activity details. > - The benefit is that waiting on a dependency resumes the original owner cleanly, ownership transfers stay explicit and auditable, and native assignee changes (such as configured review stages) appear in task activity receipts. ## Linked Issues or Issue Description Refs #22962, #21265, #22140, #22438. **What happened?** When an agent linked a prerequisite task via `set_dependencies` and followed the execution prompt by calling `paperclip_block` with the prerequisite's agent as `blocker.owner`, `status-arbiter.ts` emitted `handoffAgentId` and `status-decision-committer.ts` permanently overwrote `issue.assigneeAgentId` to that other agent. The same silent reassignment also occurred on non-dependency `current_track` and `task_wide` blocks naming another agent. Because `status-decision-committer.ts` did not record `previousAssigneeAgentId` / `assigneeAgentId` in `issue.updated` details, the assignee change was invisible in task history, and handing a task to an agent bound to another user's unshared AI credential caused repeated `ai_connection_credential_not_shared` wake failures. **Expected behavior** `blocker.owner` in `paperclip_block` is descriptive and never silently reassigns a task: - On dependency-gated blocks (`durable_dependency_blocker_bound`), the reporting agent remains `assigneeAgentId` and `unblockDescriptor.owner` so dependency completion wakes the original owner. - On non-dependency blocks naming another agent, report-time feedback rejects the report with actionable guidance pointing to `create_task` + `set_dependencies`, `reassign_task` (or `handoff_case`), or `blocker.owner.kind: "user"`. If such a report still reaches finalization, it stays blocked for `"board"` without changing `assigneeAgentId` or waking the other agent. - Whenever any committed native status decision changes `assigneeAgentId` or `assigneeUserId` (for example when starting a configured review stage), the `issue.updated` activity row records `previousAssigneeAgentId`, `assigneeAgentId`, `previousAssigneeUserId`, `assigneeUserId`, and `changes`. **Steps to reproduce** 1. Create two agents in one company (Agent A and Agent B), an upstream task assigned to Agent B, and a parent task assigned to Agent A. 2. Link the upstream task as a dependency of the parent task (`blocks`). 3. Have Agent A call `paperclip_block` with `blocker.owner: { kind: "agent", name: "<Agent B>" }`, then finalize Agent A's run. 4. Observe on `master` that the parent task's `assigneeAgentId` is silently overwritten from Agent A to Agent B with no assignee-change fields in the `issue.updated` activity log. ## What Changed - **`server/src/services/native-runtime/status-arbiter.ts`**: - Remove `handoffAgentId`, `blockerHandoffLocked`, and `resolveBlockerHandoff` so `paperclip_block` never reassigns tasks. - On `durable_dependency_blocker_bound`, keep `unblockDescriptor.owner` on `{ agentId: input.agentId }` whenever `blocker.ownerKind === "agent"` (including another agent or an unresolved/deprecated agent label), while preserving named human/board owners (`#22438`). - On non-dependency `task_wide` and `current_track` blocks naming another agent, bind `unblockDescriptor.owner` to `"board"` without reassigning, waking the other agent, or re-waking the reporting agent. - **`server/src/services/native-runtime/native-completion-feedback.ts`**: - Check dependency readiness (memoized per call) before validating `blocker.owner.kind === "agent"`: allow dependency-gated blocks naming the dependency's agent descriptively, and reject non-dependency blocks naming another or unknown agent with actionable guidance pointing to `create_task` + `set_dependencies`, `reassign_task` / `handoff_case`, or `blocker.owner.kind "user"`. - **`server/src/services/native-runtime/native-run-finalizer.ts` & `server/src/services/native-runtime/status-decision-committer.ts`**: - Remove blocker-owner handoff checks and `assigneeAgentId` handoff patching during finalization and commit. - Record `previousAssigneeAgentId`, `assigneeAgentId`, `previousAssigneeUserId`, `assigneeUserId`, and `changes` on native `issue.updated` activity events whenever a committed native status decision changes the task assignee. - **Cleanup**: - Remove unused `server/src/services/native-runtime/blocker-owner-handoff.ts` and `server/src/modules/external-agents/run-authorizer.ts` (and its export from `server/src/modules/external-agents/index.ts`). - **Tests**: - Update `server/src/services/native-runtime/status-arbiter.test.ts` and `server/src/__tests__/native-status-arbiter-corpus.test.ts` to cover dependency-gated owner preservation (including chat-bound tasks and unmatched agent labels) and non-dependency rejection + board fallback without reassignment. - Extend `server/src/services/native-runtime/native-execution-policy-review-stage.test.ts` to verify `issue.updated` activity details record assignee transitions for both human and agent configured review stages. ## Verification - **RED-before-fix (on base `c5a705ce92`)**: - `pnpm --filter @paperclipai/server exec vitest run src/services/native-runtime/status-arbiter.test.ts` -> 3 failed | 31 passed (34) (failed because `handoffAgentId` and `{ agentId: "reviewer" }` were emitted on dependency and non-dependency blocks). - **GREEN after fix**: - `pnpm --filter @paperclipai/server exec vitest run src/services/native-runtime/blocker-owner.test.ts src/services/native-runtime/evidence-classifier.test.ts src/services/native-runtime/status-arbiter.test.ts` -> 48 passed (48). - `pnpm --filter @paperclipai/server exec vitest run --hookTimeout=120000 src/services/native-runtime/native-execution-policy-review-stage.test.ts` -> 16 passed (16). - `pnpm --filter @paperclipai/server exec vitest run --hookTimeout=120000 src/__tests__/native-status-arbiter-corpus.test.ts -t "rejects a non-dependency|keeps accepting a human-owned|preserves the original assignee on a dependency-gated"` -> 5 passed (5 selected; 169 skipped). - `pnpm --filter @paperclipai/server exec vitest run --hookTimeout=120000 src/services/native-runtime/native-agent-blocker.integration.test.ts` -> 17 passed (17). - `pnpm --filter @paperclipai/server typecheck` -> PASS across all 7 layers. - `node scripts/check-module-boundaries.mjs` -> PASS. - `node scripts/check-test-budget.mjs --base origin/master` -> PASS (113 nightly suites validated, 3 test file(s) checked). - `pnpm --filter @paperclipai/server exec vitest run ../tests/runner-e2e/chat-catalog-domains/internal-timeline-native-milestone.test.ts` -> 33 passed (33). - **CI & Reviews on final head `d7c54badca`**: - GitHub Actions PR workflow run [`47436506671`](https://github.com/paperclipai/paperclip/actions/runs/47436506671): `ci / verify` PASS, `ci / e2e` PASS, all 84 checks green/neutral (including Socket Security, Superagent Security Scan, and Snyk). - Greptile Review: `5/5` (zero open comments); Ponytail Paperclip Review: `5/5`; Feynman Nuclear Review: `5/5`. ## Risks - **Intentional behavior change from #22962**: Agents that previously relied on `paperclip_block` naming another agent without a dependency to silently reassign a task will now receive actionable report-time feedback directing them to `create_task` + `set_dependencies` or `reassign_task` (and any already-saved result reaching finalization will fall back to `"board"` without reassigning). - **Upgrade safety**: Existing `chat-control-recovery-stop.ts` read-only ancestry checks for historical `bind_blocker` wakes are preserved. Self-owned blocker continuations (#22140) and named human blocker routing (#22438) are preserved unchanged. - No database schema changes or migrations. ## Model Used - Google Gemini (Antigravity, high reasoning mode with code execution and tool use) ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing> |
||
|
|
c56463e6d1 |
feat(chat): use rich project selector and remove workspace option in GitHub bot settings (#23757)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work.
> - Chat connections let operators set task defaults for new
conversations, including on GitHub review bot settings and repository
access views.
> - Today, task defaults render a plain native `<select>` for projects
and expose a Workspace selector for GitHub review bots.
> - Operators expect the same searchable, rich project selector used in
the task composer, and GitHub review bot tasks should always use
isolated workspaces / project defaults without a separate workspace
override.
> - This pull request replaces the native project select in
`ChatExecutionDefaults` with `InlineEntitySelector`, hides workspace
configuration for GitHub connections and repositories, and strips GitHub
workspace overrides on the server during reads, writes, and task
creation.
> - The benefit is faster, consistent project selection across chat
connections and simpler GitHub review bot settings that enforce isolated
workspace / project defaults.
## Linked Issues or Issue Description
**What existing behavior does this improve?**
Task defaults in chat connection settings (`ChatExecutionDefaults`),
specifically for GitHub review bot connection settings and
per-repository overrides.
**Subsystem affected**
Cross-cutting (`ui/` and `server/`).
**Current behavior**
`ChatExecutionDefaults` renders a plain native `<select>` for the
default project and displays a Workspace configuration selector on
GitHub review bot settings and repository defaults. Legacy workspace
overrides saved on GitHub endpoints or repositories remain visible and
apply during task creation.
**Proposed behavior**
`ChatExecutionDefaults` uses `InlineEntitySelector` with search, recent
projects, project color icons, and private-project indicators (matching
the task composer). For GitHub review bots (`allowWorkspace={false}`),
the Workspace selector is removed, the workspace choices query is
skipped, and the server strips any workspace override on read, write,
and task creation so new tasks always use isolated workspaces / project
defaults.
**Reason and benefit**
Operators can find projects quickly with the same picker they already
know from the task composer, and GitHub review bots no longer expose a
misleading workspace override that conflicts with isolated workspace /
project defaults.
**Breaking changes**
None for non-GitHub providers (Slack, Discord, Telegram, Teams,
iMessage, Email retain their Workspace selector and stored workspace
overrides). For GitHub review bots, any previously saved workspace
override is ignored so new tasks use isolated workspaces / project
defaults; saved project defaults are preserved.
## What Changed
- Updated `ui/src/components/InlineEntitySelector.tsx` to accept
optional `id` (for `<label htmlFor>`) and `contentClassName` (to match
full-width form triggers) without changing existing callers.
- Replaced the native project `<select>` in
`ui/src/pages/apps/chat/ChatExecutionDefaults.tsx` with
`InlineEntitySelector` (searchable by project name and description,
recent project ordering, colored folder icons, private lock badges,
unavailable-project handling, and stable `projectOptions` memoization).
- Added an `allowWorkspace` prop (default `true`) to
`ChatExecutionDefaults` so non-GitHub connections keep their Workspace
selector while GitHub connections
(`ui/src/pages/apps/chat/ChatEndpointDetail.tsx`) and GitHub
repositories (`ui/src/pages/apps/chat/GitHubBotManagement.tsx`) omit
workspace configuration and skip fetching workspace choices.
- Added `normalizeChatExecutionDefaultsForProvider` and provider-aware
stripping in `resolveChatExecutionDefaults`
(`server/src/services/chat-execution-defaults.ts`) and wired it through
endpoint serialization/updates
(`server/src/services/chat-channels/endpoints.ts`), resource
reads/writes
(`server/src/services/chat-channels/resource-reconciliation.ts`,
`server/src/services/chat-channels/github/resources.ts`), and inbound
task creation (`server/src/services/chat-channels.ts`).
- Added unit and realistic-size (400-project linear read budget) tests
in `ui/src/pages/apps/chat/ChatExecutionDefaults.test.tsx`, helper tests
in `server/src/__tests__/chat-execution-defaults.test.ts`, and an
embedded-Postgres integration test in
`server/src/__tests__/chat-channels/github-setup-and-access.integration.test.ts`.
## Verification
- `npx vitest run ui/src/pages/apps/chat/ChatExecutionDefaults.test.tsx`
— passed (5 tests, including 400-project resource-mode search and
recent-ordering linear read budget).
- `npx vitest run ui/src/pages/apps/chat/chat-ui-contract.test.ts` —
passed (12 tests).
- `npx vitest run server/src/__tests__/chat-execution-defaults.test.ts`
— passed (6 tests).
- `npx vitest run
server/src/__tests__/chat-channels/github-setup-and-access.integration.test.ts
-t "strips workspace overrides"` — passed (embedded Postgres integration
test verifying read, write, and inbound task creation).
- `pnpm --filter @paperclipai/ui typecheck && pnpm --filter
@paperclipai/server typecheck` — passed (exit 0).
- `node scripts/check-module-boundaries.mjs && node
scripts/check-test-budget.mjs && node
scripts/check-query-error-rendering.mjs` — passed.
- CI run on final head `d548e20a75`:
https://github.com/paperclipai/paperclip/actions/runs/47394038195 — all
66 checks passed (Build, Typecheck + Release Registry, policy, verify,
general/serialized/runner/e2e suites, security scans).
- Greptile Review on `d548e20a75`: 5/5 confidence score with zero
unresolved comments.
## Risks
- Low risk. Existing GitHub endpoints or repositories with a legacy
`workspace` entry in `executionDefaults` now ignore that entry and use
the project default / isolated workspace behavior instead. Non-GitHub
chat connections keep existing workspace configuration unchanged.
## Model Used
- Google Gemini 4 Neon (High reasoning mode, with tool use and code
execution) via Antigravity.
## Checklist
- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
---------
Co-authored-by: Paperclip <noreply@paperclip.ing>
|
||
|
|
ba1fc8884c |
fix(native-runtime): fix plugin task predecessor resume and confirmed-unavailable retirement (#23772)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - The native runtime executes `per_turn` plugin Runner tasks across remote sandboxes and verifies predecessor lease authority before it reads checkpoints or resumes sessions. > - Three coupled defects in predecessor resolution and retirement caused valid follow-up and retry turns to fail with `Plugin Runner retained session is not authorized (reason: predecessor_candidate_missing)`. > - First, same-run checkpoint reads called `resolvePluginTaskResume` without `inspectCheckpoint: true`, which rejected an unsettled predecessor lease before `read_state` could re-attest its status. > - Second, cross-run checkpoint recovery skipped verified backups and refused to retire a confirmed-unavailable plugin checkpoint when prior verification returned `verified`, leaving the unretired root in place to fail launch resume. > - Third, `admission_rejected` cleared `runnerTaskIdentity` on the rejected lease but kept `runnerTaskResumeFrom`, which disqualified the original predecessor lease on retry; when clearing `runnerTaskResumeFrom`, the attempted predecessor must still be recorded inside `runnerTaskAdmissionRejection` so `materializeNativeResumeRefusedContinuation` preserves automatic fresh-session continuation. > - This pull request fixes all three paths while keeping all stop-proof, scope, and retirement fences intact, and adds red-before-fix regression tests for each case. > - The benefit is that `per_turn` plugin Runner tasks recover, retire confirmed-unavailable checkpoints cleanly, and retry or continue after admission rejection without spurious authorization failures. ## Linked Issues or Issue Description **What happened?** `per_turn` plugin Runner tasks failed on same-run recovery, cross-run confirmed-unavailable checkpoint retirement, and retry after `admission_rejected` with `Plugin Runner retained session is not authorized (reason: predecessor_candidate_missing)`. **Expected behavior** 1. Same-run checkpoint reads pass `inspectCheckpoint: true` to `resolvePluginTaskResume` so `read_state` can re-attest status on the predecessor lease. 2. Cross-run follow-ups inspect verified backups and retire finished `per_turn` plugin owners (including archiving a verified suspended `plugin-runner-state.json` receipt) when the provider confirms the prior checkpoint is stopped and unavailable. 3. `admission_rejected` clears `runnerTaskResumeFrom` alongside `runnerTaskIdentity` so a subsequent retry lease still resolves the original predecessor lease, while recording the attempted `resumeFrom` inside `runnerTaskAdmissionRejection` so `materializeNativeResumeRefusedContinuation` still schedules a fresh-session continuation. **Steps to reproduce** 1. Run a same-run plugin Runner recovery (`resume_dead_runner` or disposition retry) when the predecessor lease has `runnerTaskSessionRetained: false`; `migrateRunnerdStateRoot` calls `resolvePluginTaskResume` without `inspectCheckpoint: true` and fails with `predecessor_candidate_missing`. 2. Run a cross-run `per_turn` plugin Runner follow-up when the prior root verifies via `plugin-runner-state.json` or a verified harness backup and `read_state` confirms `executionStopped: true, sessionStateAvailable: false`; the prior root is not retired and launch resume fails with `predecessor_candidate_missing`. 3. Submit a plugin Runner task on `lease2` with `resumeFrom: "task-1"` that returns `admission_rejected`, release `lease2`, and call `resolvePluginTaskResume` for `lease3` on the same run; stale `runnerTaskResumeFrom` on `lease2` disqualifies `lease1` with `predecessor_candidate_missing`. **Paperclip version or commit** `f4baaa4f48` (`master`) **Deployment mode** Self-hosted server ## What Changed - Pass `inspectCheckpoint: true` to `resolvePluginTaskResume` in `migrateRunnerdStateRoot` (`server/src/services/native-runtime/native-session-executor.ts`) before issuing same-run `read_state`, matching `recoverPluginRunnerCheckpoint` and `environment-task-runtime.ts`. - Inspect plugin checkpoints in `recoverPluginRunnerCheckpoint` when `direct === "absent" && prior === "verified"` (verified harness backup on disk). - Allow `retireFinishedPerTurnRunnerdOwner` in `migrateRunnerdStateRoot` when `pluginCheckpointUnavailableConfirmed && verification === "verified"`, preserving all existing stop-proof, lease, journal, and recovery fences. - Accept a verified suspended `plugin-runner-state.json` receipt in `readSettledRunnerdProjection` when `options.confirmedGonePluginTask` is true, and archive `plugin-runner-state.json` alongside continuity entries in `moveNativeContinuityState` when retiring a confirmed-unavailable plugin owner. - Strip `'runnerTaskResumeFrom'` alongside `'runnerTaskIdentity'` on `admission_rejected` in `executeEnvironmentTask` (`server/src/services/environment-task-runtime.ts`), record the attempted `resumeFrom` inside `runnerTaskAdmissionRejection`, and update `materializeNativeResumeRefusedContinuation` (`server/src/services/native-runtime/native-provider-capacity-retry.ts`) to read `runnerTaskAdmissionRejection.resumeFrom` with fallback to legacy `runnerTaskResumeFrom`. - Add focused red-before-fix regression tests in `server/src/services/native-runtime/native-session-executor.test.ts`, `server/src/__tests__/environment-task-authority.integration.test.ts`, and `server/src/services/native-runtime/native-resume-refused-continuation.integration.test.ts`. ## Verification - Confirmed all 5 new regression test cases failed with `predecessor_candidate_missing` or stale `runnerTaskResumeFrom` before applying the production fixes. - Ran `pnpm --dir server exec vitest run src/services/native-runtime/native-session-executor.test.ts src/services/native-runtime/native-session-root-entries.test.ts src/__tests__/environment-task-authority.integration.test.ts` — 3 test files passed (1591 passed, 7 skipped, 0 failed). - Ran `pnpm --dir server exec vitest run src/services/native-runtime/native-resume-refused-continuation.integration.test.ts` — 1 test file passed (9 passed, 0 failed). - Ran `pnpm --dir server typecheck` — passed cleanly across all layers. ## Risks - Low risk. All existing stop-proof (`remoteExecutionHasStopped`), prior lease end (`priorRemoteSandboxLeasesEnded`), released controller lease, and settled journal fences remain enforced before any confirmed-unavailable plugin checkpoint is retired. - `plugin-runner-state.json` remains in `NATIVE_SESSION_ROOT_HELD_ENTRIES` and is only accepted and archived when `confirmedGonePluginTask` is proven true and `pluginRunnerdAuthorityLifecycle` matches the exact suspended identity with no direct `runner/runner-state.json`. - `materializeNativeResumeRefusedContinuation` falls back to legacy `runnerTaskResumeFrom` for any lease written before this change. - No database schema changes or migrations are included. ## Model Used - Google DeepMind Gemini 4 Neon (Medium reasoning budget) with tool use and code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing> |
||
|
|
244e20a293 |
fix(server): settle prior pending_cleanup leases and recheck stopped ownership on same-run retry (#23770)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The server environment runtime and sandbox creation ownership layer coordinate plugin-task leases across same-run retries and resumptions > - Same-run plugin-task retries can fail with `setup_failed`: `Sandbox creation has already transferred ownership` in two situations > - First, `createOwnedSandbox` has a check-then-read race when the prior lease finishes releasing with a valid termination receipt between `createdSandboxStopped` and `getLeaseById` > - Second, same-run native resumption with `nativeLeaseOwner` (without `nativeRestartRecovery`) leaves `recoverPluginTask` false, and `recoverPluginTask` in `environmentRunOrchestrator` does not retry plain `pending_cleanup` plugin leases before checking `remoteExecutionHasReleased` > - This pull request closes the `createOwnedSandbox` race, enables `recoverPluginTask` for same-run `nativeLeaseOwner` resumptions, and retries prior `pending_cleanup` plugin leases before checking termination receipts > - The benefit is reliable same-run plugin-task recovery without relaxing the invariant that no second sandbox starts without a proven remote termination receipt ## Linked Issues or Issue Description **What happened?** Same-run plugin-task retries and resumptions fail with `setup_failed`: `Failed to acquire lease for environment ... (plugin): Sandbox creation has already transferred ownership`. This occurs either when a prior lease finishes releasing with a stop receipt between `createdSandboxStopped` and `getLeaseById` in `createOwnedSandbox`, or when a prior `pending_cleanup` lease is not settled during same-run recovery. **Expected behavior** When a prior lease has already stopped with a valid termination receipt, `createOwnedSandbox` re-admits the replacement operation cleanly. When a same-run native resumption runs with `nativeLeaseOwner`, `recoverPluginTask` retries prior `pending_cleanup` plugin leases; if teardown succeeds with a stop receipt, the replacement lease acquires cleanly, and if teardown fails, recovery fails closed with `native_plugin_recovery_termination_unconfirmed` without creating a second sandbox. **Steps to reproduce** 1. Run a `paperclip_runner` task on a plugin environment so an `attached` row exists in `sandbox_creation_operations`. 2. Leave the prior lease in `pending_cleanup` (or release it with a valid termination receipt between `createdSandboxStopped` and `getLeaseById`). 3. Resume or retry the same run; before this change, acquisition fails with `Sandbox creation has already transferred ownership` or fails without retrying the `pending_cleanup` teardown. **Paperclip version or commit** `f4baaa4f48` (`master`) ## What Changed - Re-check `createdSandboxStopped(db, operation)` in `server/src/services/sandbox-creation-operations.ts` when `existing && existing.status !== "active"` after `getLeaseById`, and re-admit via `admit(operation)` when the prior sandbox is proven stopped before throwing. - Enable `recoverPluginTask` in `server/src/services/heartbeat/workspace-preparation.ts` for same-run native resumptions with `runOptions.nativeLeaseOwner` when `!restartRecovery`, `!priorVerificationLease`, and `!portablePreparationLeaseId`. - Retry prior `pending_cleanup` plugin leases in `server/src/services/environment-run-orchestrator.ts` (using an atomic `pendingCleanupInFlight` claim, `retryPendingSandboxTeardown`, and `releaseLease`) before checking `remoteExecutionHasReleased`, releasing the in-flight flag on failure and failing closed with `native_plugin_recovery_termination_unconfirmed`. - Add red-before-fix regression tests in `server/src/__tests__/plugin-runner-task.integration.test.ts` and `server/src/services/heartbeat/workspace-preparation.test.ts`. ## Verification - Verified red-before-fix failures before editing production code: - `pnpm --dir server exec vitest run src/__tests__/plugin-runner-task.integration.test.ts -t "pending_cleanup|createOwnedSandbox"` (3 failed: `pending_cleanup` teardown not attempted / `native_plugin_recovery_termination_unconfirmed`, and `createOwnedSandbox` threw `Sandbox creation has already transferred ownership`). - `pnpm --dir server exec vitest run src/services/heartbeat/workspace-preparation.test.ts -t "enables recoverPluginTask"` (1 failed: `recoverPluginTask` was `false`). - Verified green-after-fix: - `pnpm --dir server exec vitest run src/__tests__/plugin-runner-task.integration.test.ts` — 12/12 passed. - `pnpm --dir server exec vitest run src/services/heartbeat/workspace-preparation.test.ts -t "enables recoverPluginTask|retired inherited runner|same-run"` — 4/4 passed. - `pnpm --dir server typecheck` — passed across all layers. ## Risks - Low risk. No database schema or API contract changes. - Preserves the fail-closed termination invariant: no second sandbox is created unless every prior lease has a proven `hasRemoteTerminationReceipt`, and concurrent cleanup attempts are fenced by `pendingCleanupAttemptId` / `pendingCleanupInFlight`. ## Model Used - Google DeepMind Gemini 4 Neon (Medium reasoning budget) with tool use and local code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing> |
||
|
|
f5457565de |
fix(heartbeat): retry setup on retryable remote_incomplete workspace failures (#23764)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Before a run starts its provider, Paperclip prepares the task workspace through a workspace provider plugin using a deterministic `operationId` > - A workspace provider can fail preparation with the closed retryable reason `remote_incomplete` when a remote storage or runtime request does not finish > - Setup recorded `remote_incomplete` as a generic `setup_failed` with no bounded retry, and release recovery immediately marked the task `blocked` without retrying the same workspace or showing the workspace failure reason in the escalation notice body > - This pull request gives a fresh pre-dispatch `remote_incomplete` answer its own transient setup code, `workspace_storage_incomplete`, routes it through the bounded bootstrap retry budget (deferring Sentry reporting until the retry decision), and forwards saved `workspaceProviderFailure` details into immediate execution-path escalation notices > - The benefit is that a task retries the same workspace automatically across transient remote storage/runtime failures instead of immediately blocking for a person ## Linked Issues or Issue Description Refs #23362, #19249 **What happened?** When a workspace provider returned the closed retryable reason `remote_incomplete` (`"Workspace storage operation is incomplete; retry the same workspace"`) during workspace bootstrap (`executionRecovery: { kind: "bootstrap", providerWorkStarted: false }`), `failRunSetup` recorded `errorCode: "setup_failed"` and scheduled no retry. Immediately after, `releaseIssueExecution` treated `setup_failed` as non-retryable continuation failure and marked the task `blocked` with a generic notice that omitted the workspace failure reason. **Expected behavior** When a legacy run fails before provider dispatch with a retryable `remote_incomplete` workspace provider answer, setup must classify it as `workspace_storage_incomplete` and schedule a bounded bootstrap retry of the same workspace (matching `workspace_storage_pending` and `plugin_worker_unavailable`). Sentry must report only when no retry is scheduled or retries are exhausted, and immediate execution-path escalation notices must include the bounded `workspaceProviderFailure` message when present. **Steps to reproduce** 1. Start a legacy run whose workspace preparation calls a workspace provider plugin. 2. Have the provider reject preparation with `PluginWorkspaceOperationError("remote_incomplete")`. 3. Before this fix, `failRunSetup` writes `errorCode: "setup_failed"`, schedules no bounded retry, and `releaseIssueExecution` immediately blocks the task. **Paperclip version or commit** Reproduced on `master` (`01ecbadbf1`). **Deployment mode** Self-hosted server and managed plugin workspace environments (`authenticated` and `local_trusted`). ## What Changed - `server/src/services/workspace-provider-failure.ts`: add `WORKSPACE_STORAGE_INCOMPLETE_CODE` (`workspace_storage_incomplete`) and `findWorkspaceStorageIncompleteFailure` matching `kind === "provider" && reason === "remote_incomplete"`. - `server/src/services/heartbeat/run-completion.ts`: map a fresh pre-dispatch legacy `remote_incomplete` failure (with no native session or runner instance) to `workspace_storage_incomplete`, route it through `scheduleBoundedRetryForRun` (keeping accepted interaction retries owned by the interaction lane), and defer Sentry reporting via `workspaceStorageIncompleteRetry`. - `server/src/services/failed-preparation-retry.ts`, `server/src/services/heartbeat/retries.ts`, `server/src/services/legacy-execution-recovery.ts`, `server/src/services/recovery/service.ts`, `server/src/services/agent-task-run-telemetry.ts`: handle `workspace_storage_incomplete` alongside `workspace_storage_pending`. - `server/src/services/recovery/stranded-notice.ts` & `server/src/services/heartbeat.ts`: add a stranded escalation notice for `workspace_storage_incomplete` and pass `workspaceProviderFailure: readWorkspaceProviderFailure(input.runRow.resultJson)` into `buildImmediateExecutionPathRecoveryNoticeSeed`. - `server/src/services/run-failure-diagnostics.ts` & `server/src/services/run-failure-report.ts`: add `workspaceStorageIncompleteRetry` deferred Sentry reporting handshake. - Add red-then-green regression tests in `run-completion.test.ts`, `workspace-provider-failure.test.ts`, `run-failure-report-sandbox-resume.test.ts`, and `heartbeat-retry-scheduling.test.ts`. ## Verification - Red before the fix: - `pnpm --dir server exec vitest run src/services/heartbeat/run-completion.test.ts -t "incomplete workspace storage"` failed on the `fresh` scenario with `errorCode: "setup_failed"` instead of `"workspace_storage_incomplete"`. - Green after the fix: - Focused `run-completion.test.ts`, `run-failure-report-sandbox-resume.test.ts`, `workspace-provider-failure.test.ts`, `agent-task-run-telemetry.test.ts`, `heartbeat-retry-scheduling.test.ts` (`bootstrap retries across restart`), and `pnpm --dir server typecheck` all pass. ## Risks - Low risk. No database schema, API route, or plugin wire protocol changes. - Retry applies only before provider dispatch on a legacy run with no native session or runner instance, bounded by the existing bootstrap retry budget (2 retries). Started and native runs keep `setup_failed` with no automatic retry. - Every workspace preparation call carries a deterministic `operationId` derived from workspace ID, generation, and operation payload, and `remote_incomplete` is explicitly marked `retryable: true` for the same workspace. ## Model Used - Google DeepMind Gemini 4 Neon (Medium reasoning budget), via Antigravity with tool use (code search, file edits, local test execution, and GitHub CLI). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing> |
||
|
|
73c43fd443 |
test(issues): guard the blockerAttention early-warning against cancelled-child noise (#10375)
## Thinking Path > - Paperclip orchestrates AI agents in companies where no human watches the board continuously. > - `blockerAttention` is the early-warning system for blocked issues: it distinguishes a blocked issue that has a live path from one that is blocked in prose only, with no first-class blocker and therefore no wake path. > - The graph it walks is `explicit blockedBy edges ∪ non-terminal direct children`. > - #7577 correctly made cancelled direct children terminal, because a cancelled child is neither a dependency nor a source of liveness — before that fix a cancelled child pinned its parent to `needs_attention` forever, since a cancelled issue never becomes `done`. > - Two contract branches around that behaviour had no assertion in the suite, so nothing pins the signal's two ends: the pure early-warning case (blocked, zero edges) and the cancelled-child edge count in isolation. > - This PR adds those two guards. It is test-only; no behaviour changes. ## Linked Issues or Issue Description Refs #7578 (the cancelled-child defect fixed by #7577). **Issue this addresses:** the regression test added in #7577 asserts the parent is `covered`, but that parent also has two live explicit blockers holding the state up. If the cancelled-child filter regressed, the counts would change while the *state* could still look plausible in other shapes, and the case the feature exists for — a blocked issue with **no** blocker edges at all — has no assertion anywhere in the file. `unresolvedBlockerCount: 0` appears in no test today. Related PRs found while searching (neither overlaps; both touch blocker relations, not `blockerAttention` classification): #8251 (blocker summaries for legacy child blockers), #10316 (reject `done` while first-class blockers remain open). ## What Changed Two tests in `server/src/__tests__/issue-blocker-attention.test.ts`: - **`flags a blocked issue that has no blocker edges at all`** — a blocked, agent-assigned issue with no relations and no children must report `needs_attention` / `attention_required` with all four counts at 0. This is the text-only-blocked case the signal is built to catch, and it was unasserted. - **`keeps a blocked parent attention-needed when its only child was cancelled`** — a blocked parent whose sole child is `cancelled` must report `unresolvedBlockerCount: 0` and stay `needs_attention`. This pins the cancelled-child edge count on its own, without live explicit blockers masking it. No production code touched. ## Verification - `node_modules/.bin/vitest run server/src/__tests__/issue-blocker-attention.test.ts` on this branch → **26 passed**. - Control run, to prove the guards bite: reverted the #7577 filter in `listIssueBlockerAttentionMap` back to `ne(issues.status, "done")` → **2 failed / 24 passed**, both cancelled-child tests: - `ignores cancelled direct children …`: `unresolvedBlockerCount` 3 instead of 2, state `needs_attention` instead of `covered` - `keeps a blocked parent attention-needed when its only child was cancelled`: `unresolvedBlockerCount` 1 instead of 0 Restored the filter → 26 passed again. - The zero-edge test passes both before and after that revert, as intended: it is the negative control that proves the fix does not blind the detector. ## Risks - Test-only; no runtime behaviour changes, no schema or API surface touched. - The new tests use the file's existing `createCompany` / `insertIssue` helpers and fresh issue prefixes (`PBE`, `PBF`), so they do not interact with sibling cases. ## Model Used - Claude Opus 5 (1M context) via Claude Code CLI, tool-enabled; used for repository inspection, test authoring, and local vitest execution including the revert-based control run. ## 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 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 (not applicable; test-only change) - [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: AURDVIN Dev Agent <juan@rial.ch> Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com> Co-authored-by: commitperclip[bot] <284812584+commitperclip[bot]@users.noreply.github.com> |
||
|
|
def3ac2e7e |
test: cover create-time issue blocker links (#10320)
## Thinking Path > - Paperclip is the control plane people use to coordinate AI-agent work. > - Issue dependencies are first-class board mechanics that must survive issue creation. > - The service layer already persists `blockedByIssueIds` transactionally and decorates create responses after #8901. > - The public create route did not have an end-to-end regression proving that contract. > - Without route-level coverage, a validator or route mapping regression could again return success while silently dropping dependency data. > - This pull request exercises the real HTTP and database path for create-time blockers. > - The benefit is an executable contract that prevents successful creates from silently losing blocker links. ## Linked Issues or Issue Description Refs #8901 Bug regression: - What happened: an issue create request containing `blockedByIssueIds` could report success while its response omitted the requested blocker relation. - Expected behavior: a successful create persists the blocker edge and returns it immediately; a subsequent read returns the same edge. - Steps to verify: create a blocker, create a blocked issue with the blocker's ID, then inspect both the `201` response and a fresh issue read. - Paperclip version/commit: regression coverage added on current `master`. - Deployment mode: local trusted integration-test environment. Related public work: - #8901 implemented create-response relation summaries. - #4099 covers blocker readback shape more broadly. ## What Changed - Added an embedded-Postgres route regression that creates an issue with `blockedByIssueIds`. - Asserted both the `201` create response and a subsequent `GET` contain the persisted blocker summary. ## Verification - `pnpm exec vitest run server/src/__tests__/issue-create-deduplication-routes.test.ts` — 9/9 passed. - `pnpm -r typecheck` — passed. - `pnpm build` — passed. - `pnpm test:run` — 2,823 passed, 1 skipped, 2 unrelated failures in `workspace-runtime.test.ts` caused by local auto-port adoption/collision behavior (`EADDRINUSE`). - `bin/ci` is absent; the repository-documented gates above were used. ## Risks Low risk. This changes test coverage only. The test uses the existing embedded-Postgres harness and does not alter production behavior. > `ROADMAP.md` contains no matching blocker/create-contract work. This is regression coverage for an existing behavior, not a new core feature. ## Model Used OpenAI Codex, GPT-5, with reasoning and repository-aware shell/code execution tools. The serving context-window size is managed by the runtime. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [ ] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] 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: commitperclip[bot] <284812584+commitperclip[bot]@users.noreply.github.com> |
||
|
|
e53cce2257 |
fix: accept nested git worktree folders for local adapters (#7957)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Local adapters such as `codex_local` need workspace validation before launching agent runs. > - The validator became too strict by requiring `.git` metadata directly inside the adapter cwd. > - Git itself treats subdirectories of a repository as valid worktree paths, and Codex can operate from those nested folders. > - Paperclip project folders can be configured as subdirectories inside a larger Git worktree. > - This pull request aligns Paperclip validation with Git's own worktree detection. > - The benefit is fewer false `workspace_validation_failed` errors while still rejecting folders outside any Git worktree. ## Linked Issues or Issue Description - Fixes: #7956 ## What Changed - Replace direct `cwd/.git` metadata checking with `git -C <cwd> rev-parse --is-inside-work-tree`. - Add regression coverage for a workspace-linked issue whose adapter cwd is nested inside a parent Git worktree. - Clean up the temporary Git fixture created by that regression test. - Preserve rejection behavior for folders that are not inside any Git worktree. ## Verification - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/heartbeat-workspace-session.test.ts` - `pnpm --filter @paperclipai/server typecheck` Local validation results: - `heartbeat-workspace-session.test.ts`: 107 tests passed. - Server typecheck passed. ## Risks - Low risk. This changes validation from a stricter direct `.git` file check to Git's own worktree detection. - Requires `git` to be available for git-sensitive local adapter validation. These adapters already require Git-compatible workspaces. - Still fails closed for missing, invalid, or non-git workspace paths. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used Codex, GPT-5.5, with repository inspection, shell execution, local runtime validation, and focused test execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] If this change affects the UI, I have included before/after screenshots - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: zocomputer <help@zocomputer.com> Co-authored-by: commitperclip[bot] <284812584+commitperclip[bot]@users.noreply.github.com> |
||
|
|
0960dd464d |
perf(chat): eliminate activity_log seq scans, chat load waterfalls, and transcript storms (#23750)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Persistent agent chat pages (`/:companyPrefix/chats/:agentRef`) are a primary surface for collaborating with an agent across many tasks and turns. > - Opening an active agent chat page was slow: multiple endpoints scanned the full `activity_log` table, the page bypassed the single-request chat bootstrap, the native transcript hook aborted and retried historical run fetches across multiple waves, and pending task questions triggered N+1 per-task interaction requests. > - These bottlenecks blocked the initial chat reveal for several seconds and saturated server and database capacity during page open. > - This pull request eliminates the `activity_log` sequential scans with index-backed predicates (no schema migrations), batches pending-question interaction hydration, defers completed saved-reply run transcripts in persistent agent chats, stabilizes per-run transcript lifecycles, and enables parallel chat resolution and chat-bootstrap adoption on agent chat pages. > - The benefit is dramatically faster agent chat page loads with far fewer HTTP requests, zero `activity_log` full-table scans on hot chat paths, and no schema migrations. ## Linked Issues or Issue Description Related: #18461, #20355, #21650, #21671. **What happened?** Opening a persistent agent chat page with accumulated history and active tasks took multiple seconds before the conversation became visible and triggered dozens of concurrent API requests: 1. `decisionHistoryService.list` (`handledForBySource`) scanned all rows of `activity_log` because `(details ->> 'handledForUserId') IS NOT NULL` alone did not bind the second key of `activity_log_company_handled_for_created_idx`, and `decisions` used `NOT IN (SELECT id FROM issues ...)` which planned a full-company privacy subquery even when no settled decisions existed. 2. `activityService.forIssue` scanned all rows of `activity_log` because the `project.created` and `company.skill_created` branches omitted `entity_type`, preventing index scans. 3. `attentionService.taskQuestions` executed steady-state write transactions in `decision-retention` and unnecessary plan-document reads on read paths, and `CoordinatorChatPendingQuestion` mounted an `AttentionInteractionResolver` per question that fired one `GET /api/issues/:taskId/interactions` request per pending question. 4. `TaskChatThread` disabled saved-reply transcript deferral in `conversationMode`, fetching `/events` (and legacy `/log` fallbacks) for every historical completed run in the comment window, while `useNativeRunTranscripts` used a single shared `AbortController` that aborted and restarted in-flight sibling reads whenever run membership or live-stream state changed. 5. `AgentChat` waited serially for the agent roster and session before fetching the chat by `:agentRef`, `IssueDetail` skipped `startIssueChatBootstrap` for conversations, and the HTML preload plugin omitted the `AgentChat` chunk on `/chats/:ref` hard loads. **Expected behavior** Opening an agent chat page resolves the conversation and its first-frame data in parallel via `chat-bootstrap`, avoids sequential scans on `activity_log`, avoids fetching completed run transcripts when a saved reply is already visible, avoids aborting sibling in-flight transcript reads, and renders pending task questions without per-task N+1 interaction requests. **Steps to reproduce** 1. Create a company with a persistent agent chat that has 20+ historical replies from completed native runs, several hundred tasks assigned to that agent, pending `ask_user_questions` interactions across multiple tasks, and a large `activity_log` table. 2. Open `/:companyPrefix/chats/:agentRef` directly or from the sidebar and inspect the network waterfall and PostgreSQL query plans for `/activity`, `/decision-receipts`, `/pending-questions`, and `/heartbeat-runs/:id/events`. 3. Observe full-table `Seq Scan` plans on `activity_log`, bypassed `chat-bootstrap`, repeated aborted `/events` requests, and N+1 `/issues/:taskId/interactions` calls. **Paperclip version or commit** Reproduced on `ca21075837` (rebased onto `a3719da3ca`, final head `2995820afe`). ## What Changed - **Eliminate `activity_log` sequential scans (zero migrations)**: - `server/src/services/activity.ts`, `server/src/routes/activity.ts`, `server/src/routes/issues.ts`: Scope `forIssue` secondary branches by their canonical `entity_type` (`project` for `project.created`, `company_skill` for `company.skill_created`) and accept `companyId` from routes so PostgreSQL uses `BitmapOr` index scans instead of a full-table `Seq Scan`. - `server/src/services/decision-history.ts`: Add `(details ->> 'handledForUserId') >= ''` alongside `IS NOT NULL` in `handledForBySource` so PostgreSQL binds the partial index `activity_log_company_handled_for_created_idx`; replace `decision_target_issues.issue_id NOT IN (...)` with correlated `NOT EXISTS (...)`; add a `LIMIT 1` index probe before planning the full `decisions` privacy query when no settled decisions exist. - `server/src/services/conversation-decision-receipts.ts`, `server/src/routes/issues.ts`: Reuse the route's already-authorized conversation record instead of re-querying `source()`. - **Batch pending-question hydration and avoid steady-state retention writes**: - `packages/shared/src/types/attention.ts`, `server/src/services/issue-thread-interactions.ts`, `server/src/services/attention.ts`: Add optional `interaction?: IssueThreadInteraction | null` on `AttentionItem`, batch-hydrate interactions in `issueThreadInteractionService.listByIds` (grouping by `issueId` for acceptance readiness and skipping only `z.ZodError` legacy payloads), restrict `planDocumentMap` to actual plan confirmation interactions, and parallelize `decisionQueueItems` and `decisionTriage` reads in `enrichAttentionItems`. - `server/src/services/decision-retention.ts`: Add a read-only fast path in `syncItems` so steady-state reads skip opening a write transaction when retention rows are already current, while still syncing and bumping versions whenever `activityAt` changes. - `ui/src/components/AttentionInteractionResolver.tsx`, `ui/src/components/coordinator/CoordinatorChatPendingQuestions.tsx`: Accept optional `initialInteraction` so inline pending-question cards render immediately without N+1 `GET /issues/:taskId/interactions` requests while still honoring cache updates after mutations. - **Remove agent chat load waterfalls and transcript abort storms**: - `ui/src/components/TaskChatThread.tsx`, `ui/src/lib/run-answer-visibility.ts`: Defer completed `succeeded` run transcripts that already have a visible saved reply in `conversationMode` while preserving immediate hydration for live, failed, yielded, pending-interaction, and unanswered runs; precompute visible-answer lookups in linear time (`O(comments + runs)`) instead of quadratic scans. - `ui/src/components/transcript/useNativeRunTranscripts.ts`: Manage `AbortController`s and poll timers per run instead of one shared controller so adding sibling runs or transitioning stream health never aborts in-flight reads or refetches already-hydrated terminal runs; clear aborted in-flight tracking cleanly so expanding compact history refetches immediately. - `ui/src/pages/AgentChat.tsx`, `ui/src/pages/IssueDetail.tsx`, `ui/src/lib/vite-issue-detail-preload.ts`: Start `agentChatsApi.get` by `:agentRef` in parallel with roster/session reads on cold loads, enable `startIssueChatBootstrap` for conversations with an existing issue ID, and preload the `AgentChat` chunk alongside `IssueDetail` on `/chats/:ref` hard loads. - **Tests & SDK pin**: - Added/updated tests in `server/src/__tests__/activity-service.test.ts`, `server/src/__tests__/activity-routes.test.ts`, `server/src/__tests__/decision-history.test.ts`, `server/src/__tests__/issue-thread-interaction-routes.test.ts`, `ui/src/components/AttentionInteractionResolver.initial.test.tsx`, `ui/src/components/TaskChatThread.test.tsx`, `ui/src/components/transcript/useNativeRunTranscripts.test.tsx`, `ui/src/components/transcript/useNativeRunTranscripts.streaming.test.tsx`, and `ui/src/lib/vite-issue-detail-preload.test.ts`. - Updated `tests/runner-e2e/source-sdk-public-inputs.json` for `packages/shared/src/types/attention.ts`. ## Verification Local disposable PostgreSQL 18.1 benchmark (`200,000` `activity_log` rows, `455` tasks, `82` interactions, alternating baseline/treatment samples, `ANALYZE` run, positional `.values()` output equality verified on both empty and populated `handledForUserId` sets): | Caller/query | Before median | After median | Samples/spread | Complete output/contract check | Scope | | --- | --- | --- | --- | --- | --- | | `activityService.forIssue(50)` | `53.66 ms` (`50.78 ms` SQL exec, `11,147` buffers, `Seq Scan`) | `1.84 ms` (`0.31 ms` SQL exec, `23` buffers, `BitmapOr` index scans) | 7 alternating samples (before `48.03–62.79 ms`, after `1.34–3.18 ms`, `29.2x` speedup) | Pass (50 positional rows equal) | SQL | | `decisionHistory.handledForBySource` (40 ids, 0 rows) | `13.71 ms` (`11,193` buffers, `Seq Scan`) | `0.73 ms` (`2` buffers, `Bitmap Index Scan` on partial index) | 7 alternating samples (before `11.56–15.45 ms`, after `0.64–0.99 ms`, `18.8x` speedup) | Pass (empty + populated non-empty positional rows equal) | SQL | | `decisionHistory.handledForBySource` (40 ids, 1 matching row) | `40.35 ms` SQL exec (`11,193` buffers, `Seq Scan`) | `0.04 ms` SQL exec (`2` buffers, `Bitmap Index Scan` on partial index) | `EXPLAIN (ANALYZE, BUFFERS)` | Pass (1 positional row equal) | SQL | CI and reviews on final head `2995820afe`: - **GitHub Actions CI (`ci / verify`)**: **PASS** (all 86 check runs completed with 0 failures; `mergeStateStatus: CLEAN`). - **Greptile Review**: **5/5** (`SUCCESS`, 0 unresolved findings). - **Ponytail Paperclip Review**: **5/5** ("No actionable defects found in the reviewed paths. Verdict: Ship."). - **Feynman Nuclear Review**: **4/5** ("no confirmed defect in the new commits"). Tests and builds also verified locally: - `pnpm --filter @paperclipai/shared build` — pass - `cd server && node scripts/typecheck-layers.mjs` — pass (all 7 layers) - `pnpm --filter @paperclipai/ui typecheck` & `pnpm --filter @paperclipai/ui build` — pass - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/approval-queue-seeding-work.test.ts src/__tests__/decision-history.test.ts` — pass (28/28 and 14/14 on real embedded PostgreSQL) - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/activity-service.test.ts src/__tests__/openapi-routes.test.ts` — pass - Focused UI suites (`TaskChatThread.test.tsx`, `useNativeRunTranscripts.test.tsx`, `useNativeRunTranscripts.streaming.test.tsx`, `AttentionInteractionResolver.initial.test.tsx`, `AttentionInteractionResolver.replace.test.ts`, `IssueDetail.agentChatPanel.test.tsx`, `vite-issue-detail-preload.test.ts`) — pass ## Risks - **No schema migrations**: All SQL improvements use existing indexes. - **Completed chat run transcripts**: Persistent agent chats now defer completed `succeeded` runs that already have a visible saved reply, matching compact task behavior. Live, failed, yielded, pending-interaction, placeholder, progress-only, and hash-targeted runs still hydrate immediately. - **Inline interaction hydration**: `AttentionInteractionResolver` uses `initialInteraction` when provided and valid, skipping the mount-time `listInteractions` read; mutations and live updates continue to update/invalidate `queryKeys.issues.interactions(issueId)` and `["issues", "pending-questions"]`. Unparseable legacy interaction rows (`z.ZodError`) are omitted from the batch map and fall back cleanly to the per-issue read. - **Synthetic local proof vs production**: Local PostgreSQL benchmarks prove query plan and buffer reductions on synthetic data (`200k` rows); deployed latency improvements depend on production dataset size and cache warmth. ## Model Used Google Antigravity (Gemini) with tool use, terminal execution, and local embedded PostgreSQL profiling. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing> |
||
|
|
cfe5042378 |
fix(opencode): fix API key env/secret resolution and support Antigravity connector (#23387)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - Agent setup, environment testing, and managed AI connections pass
provider API keys into the OpenCode adapter and Paperclip Runner
> - OpenCode setup failed with `Secret not found` when a user supplied a
direct Gemini API key alongside a stale or auto-selected secret binding,
and the OpenCode runtime reported `GOOGLE_GENERATIVE_AI_API_KEY` missing
because Paperclip only passed `GEMINI_API_KEY` and limited OpenCode to
OpenRouter credentials
> - Users need reliable direct provider API keys and Google/Antigravity
API-key connectors across legacy OpenCode, native Paperclip Runner, and
Plugin Runner environments without exposing raw keys to child tool
shells
> - This pull request strips probe-overridden secret references
(including symmetric Google key aliases) before secret resolution,
prioritizes pasted API keys in setup, routes direct OpenCode provider
credentials through a runner-owned loopback proxy, and enables API-key
AI connections (including the Google / Antigravity connector) for
`opencode_local`
> - The benefit is that OpenCode agents test and run reliably with
direct provider keys or connected Google/Antigravity API keys without
false `Secret not found`, missing `GOOGLE_GENERATIVE_AI_API_KEY` errors,
or raw key leaks into child environments
## Linked Issues or Issue Description
- Fixes: #23359
- Refs #23370 (related community fix by @dev-787 for the initial Gemini
API key issue)
## What Changed
- **Server test-environment secret stripping and inheritance
(`server/src/routes/agents.ts`)**: Strip any credential key supplied in
`testCredentials` (including the symmetric `GEMINI_API_KEY` /
`GOOGLE_GENERATIVE_AI_API_KEY` pair and `hermes_gateway` `apiKey`) from
both `adapterConfig` and resolved environment `envVars` before secret
persistence normalization and runtime resolution. Scope `opencode_local`
inheritable credential groups from `@paperclipai/shared`
(`OPENCODE_PROVIDER_CREDENTIAL_ENV_KEYS`), skip inheritance when the
child supplies any OpenCode credential, and isolate multi-provider
parents to one matching provider group.
- **UI setup credential precedence (`ui/src/lib/provider-credential.ts`,
`ui/src/components/new-agent/NewAgentSetup.tsx`)**: Prefer an explicitly
entered raw API key over an auto-selected organization or personal
secret, and clear stale provider secret bindings and Google alias keys
when switching credentials or providers.
- **OpenCode direct provider keys and Gemini aliasing
(`packages/adapters/opencode-local/`, `packages/adapter-utils/`)**:
Mirror non-empty `GEMINI_API_KEY` into `GOOGLE_GENERATIVE_AI_API_KEY`
during OpenCode runtime config preparation and model discovery while
preserving blank managed isolation. Register `google`, `xai`, `groq`,
and `opencode` API key names in `api-billing-type`.
- **Runner-owned loopback credential proxy and allowlist parity
(`packages/paperclip-runner/`, `packages/plugins/sdk/`,
`packages/shared/`)**: Export canonical
`OPENCODE_PROVIDER_CREDENTIAL_ENV_KEYS` and
`OPENCODE_CREDENTIAL_ENV_KEYS` from `@paperclipai/shared`. Route direct
OpenCode provider API keys (`google`, `anthropic`, `openai`, `xai`,
`groq`, `opencode`) through a runner-owned loopback proxy
(`packages/paperclip-runner/src/drivers/opencode/provider-proxy.ts`)
with per-session bearer tokens, model-pinned endpoint allowlists, native
upstream auth header injection, request secret redaction, and redirect
refusal so raw keys never enter `opencode serve` child environments or
`opencode.json`. Allow direct provider keys across TypeScript, Rust, and
Plugin SDK allowlists, reserve `GOOGLE_API_KEY` and `GROK_API_KEY` in
TS/Rust configured-environment projections, strip ambient provider keys
(including `OPENROUTER_API_KEY`) from sanitized OpenCode runner
environments unless explicitly supplied, and redact provider keys in
output custody.
- **Antigravity / multi-provider API-key AI connections for OpenCode
(`packages/shared/`, `server/src/services/`,
`ui/src/components/ai-connections/`)**: Enable `api_key` AI connections
for `google` (Antigravity catalog slug), `anthropic`, `openai`, and
`xai` on `opencode_local` (keeping OAuth `subscription` methods
excluded), enforce provider-to-model prefix compatibility, mirror
`GEMINI_API_KEY` to `GOOGLE_GENERATIVE_AI_API_KEY` in
`prepareManagedAiRuntime`, isolate project config with
`OPENCODE_DISABLE_PROJECT_CONFIG=true`, and scope child-auth override
detection in `agent-ai-connection-default.ts` to non-empty OpenCode
credentials (supporting plain values, `secret_ref.secretId`, and
`user_secret_ref.key`).
- **Tests and pinned input registry**: Added unit, route, cross-layer
allowlist parity, and pinned `opencode@1.18.34` `bash`-tool credential
isolation tests across `adapter-utils`, `adapter-opencode-local`,
`paperclip-runner`, `server`, and `ui`, and synchronized
`tests/runner-e2e/source-sdk-public-inputs.json`.
## Verification
- `@paperclipai/adapter-utils`: `src/api-billing-type.test.ts` (17/17
tests), `typecheck`, `build` — passed
- `@paperclipai/adapter-opencode-local`:
`src/server/runtime-config.test.ts`, `src/server/models.test.ts`,
`typecheck`, `build` — passed
- `@paperclipai/shared`: full suite (123/123 files, 1426/1426 tests),
`typecheck`, `build` — passed
- `@paperclipai/paperclip-runner`: `typecheck:typescript`,
`build:typescript`, `check:package-boundaries`,
`opencode-server-driver.test.ts` (101/101 including pinned
`opencode@1.18.34` `bash`-tool test), `output-custody.test.ts` (13/13),
`configured-environment.test.ts` (35/35),
`antigravity-credentials.test.ts` (11/11), and
`durable-prp-control-plane.test.ts` — passed
- `@paperclipai/server`: `typecheck` and targeted suites
(`ai-connections.test.ts` 170/170, `agent-hire-ai-connections.test.ts`
84/84, `agent-test-environment-routes.test.ts` 72/72,
`agent-hire-auth-inheritance-routes.test.ts` 29/29,
`plugin-runner-credentials.test.ts` 43/43,
`plugin-runner-credential-names.test.ts` 6/6 cross-layer TS/Rust parity,
`opencode-local-adapter-environment.test.ts` 4/4,
`ai-auth-failure.test.ts` 32/32, `ai-provider-routing.test.ts` 21/21,
`antigravity-runner-credentials.test.ts`) — passed
- `@paperclipai/ui`: `typecheck`, `provider-credential.test.ts`,
`AiConnectionSelect.test.tsx` (20/20 tests) — passed
- `@paperclipai/plugin-sdk`: `build`, `environment-tasks.test.ts`,
`environment-task-release-resume.test.ts` (104/104) — passed on
`03dc341957`
- `@paperclipai/paperclip-runner`: `provider-traffic.test.ts` &
`provider-traffic-proxy.test.ts` alongside OpenCode/Antigravity/custody
suites (169/169) — passed on `03dc341957`
- `node tests/runner-e2e/source-sdk-public-inputs.mjs
|
||
|
|
01ecbadbf1 |
fix(server): stop reporting uploads the client abandoned mid-body (#23756)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - The server accepts file uploads (issue attachments, images, company
imports) through multer
> - A client can close the connection before the upload body ends
(closed tab, lost network, cancelled upload)
> - multer then rejects with a plain `Error: Request aborted` or `Error:
Request closed`
> - The error handler only knew Node's own `aborted`/ECONNRESET
disconnect error, so it reported these as server crashes (500) to Sentry
> - This pull request treats multer's disconnect errors as a client
disconnect when the request stream really stopped early
> - The benefit is that cancelled uploads no longer create false crash
reports, and real server errors stay visible
## Linked Issues or Issue Description
**What happened?**
A hosted production server sent `Error: Request aborted` to Sentry from
`multer/lib/make-middleware.js` (`req.on('aborted')`). The error was
handled, had no code, and came from a client that dropped a multipart
upload.
**Steps to reproduce**
1. Start a multipart upload to a route that uses multer.
2. Send part of the file.
3. Close the connection before the body ends.
**Expected behavior**
The server ends the response with 499 and does not send a crash report.
**Actual behavior**
The error handler calls `reportCrash` and answers 500.
No public issue exists. I searched open and closed PRs for related fixes
and found none. Related earlier work: #19037 (AbortError after client
disconnect).
## What Changed
- `server/src/middleware/error-handler.ts`: add
`isMultipartClientDisconnect`. It matches a plain `Error` with the
message `Request aborted` or `Request closed`, no error code, and
`req.readableAborted === true`. The handler answers 499 and skips the
error sinks for this case.
- `server/src/__tests__/error-handler-client-abort.test.ts`: add a test
with a real multer route. The client sends part of a multipart body and
then drops the connection. Add a test that the same error text from a
connected request is still reported as 500.
## Verification
- `cd server && npx vitest run
src/__tests__/error-handler-client-abort.test.ts
src/__tests__/error-handler.test.ts`: 24 passed.
- Red before the fix: the new abandoned-upload test failed with
`captureException` called once with `Error: Request aborted`, the same
error as the production report.
- Green after the fix. I ran the abort suite 3 more times and it passed
each time.
- I did not run the full server typecheck locally. CI runs it.
## Risks
- Low risk. The match needs the exact multer messages, no error code,
and a request stream that stopped before its end. A route that throws
the same text while the client is still connected is still reported
(covered by a test).
> 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, used as a coding agent
with tool use (shell, 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: paperclipbugbot <356415228+paperclipbugbot@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
|
||
|
|
7d2b1d5362 |
fix(responsibilities): use configured plugin workers for task wakeups (#23705)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Responsibility actions create tasks and wake their assigned agents. > - Plugin execution needs the server's configured plugin worker manager. > - Five responsibility route groups constructed heartbeat services without that manager. > - The task could be created successfully, then fail during environment setup. > - This pull request gives those routes the existing configured heartbeat service so the first run can start. ## Linked Issues or Issue Description **What happened?** Starting a responsibility bar conversation created a task, but its first run failed during sandbox setup. Delegation, dashboard conversations, automation conversations, and status update requests used the same incomplete heartbeat construction. Background recovery could later start the task through a configured service. **Expected behavior** The first wake uses the application's configured plugin workers, so it can acquire the assigned execution environment. **Steps to reproduce** 1. Enable Responsibilities and configure an agent to use a plugin-backed execution environment. 2. Start a responsibility bar conversation with that agent. 3. Observe that task creation succeeds but sandbox setup fails because the heartbeat service has no plugin worker manager. **Paperclip version or commit** Reproduced against master at `0f36a88f41e36e93e50f146196353840e2def341` with an application-level regression test. All five wakeup cases failed before the fix. **Deployment mode** A server with a plugin-backed execution environment. The regression test uses the normal application factory, a disposable local Postgres database, and a configured plugin worker manager. No duplicate public issue or pull request was found in the pre-change search. ## What Changed - Pass the existing worker-enabled heartbeat service to the five responsibility route groups. - Keep the automation route's plugin worker manager for its routine service. - Add application-level coverage for all five wakeup paths and the disabled-feature gate. The tests use the real route registration and database services, and intercept execution before provider work starts. ## Verification - Red: all five application wakeup cases failed on the original route wiring because the worker manager was missing. - Green: 109 tests passed across the application wakeup, responsibilities, bars, dashboard, automation conversations, and status report suites. - Server typecheck: after fixing an optional-input type error in the test fixture, `node scripts/typecheck-layers.mjs` from `server/` passed all source and test layers. The Runner TypeScript build and plugin SDK prerequisites also passed. - `node scripts/check-test-budget.mjs --files server/src/__tests__/responsibility-app-wakeups.test.ts`: passed. - `node scripts/check-module-boundaries.mjs`: passed. - `git diff --cached --check` and a Gitleaks scan of the staged diff: passed. - The first `pnpm verify` selection was invalidated by the fixture type fix. The final `pnpm verify --explain` passed and selected 2,008 test files conservatively for this application change. Local validation used the six focused suites above. Required CI supplies the broader test, typecheck, build, Runner, and E2E coverage. - [Greptile review](https://github.com/paperclipai/paperclip/pull/23705#issuecomment-7402767043): 5/5 on `10035ffae203942ee93a5ee65879cd55a2130d4b`, with no inline comments or unresolved review threads. [CI run 47276399658](https://github.com/paperclipai/paperclip/actions/runs/47276399658) completed successfully on that same commit: typecheck, build, Runner checks, all general and serialized test shards, and all 16 E2E shards passed. Both required checks (`ci / verify` and `ci / e2e`) passed. The branch has no merge conflicts with master. All 71 checks have settled with no blocking results. The external Superagent Security Scan completed with a neutral conclusion; Socket and Snyk checks passed. GitHub reports the pull request as clean and mergeable. ## Risks Low risk. The change reuses a heartbeat service that already has the server's plugin worker manager. Route authorization and feature gates keep their current behavior. No schema migration or configuration change is required. Live provider execution and a Cloud rollout are outside this PR's local verification; the tests verify the application-to-execution dependency boundary. The code and regression tests describe the corrected internal wiring, so no user documentation change is needed. ## Model Used OpenAI Codex, `gpt-6.1-sol`, with xhigh reasoning effort and repository 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> |
||
|
|
c5a705ce92 |
fix(trust): enforce low-trust sourceTrust quarantine on native comments and documents (#23621)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The low-trust review preset isolates untrusted agent runs and marks their raw outputs with `sourceTrust` quarantine metadata so higher-trust agents do not ingest raw output without promotion > - HTTP route writes tagged low-trust comments and documents with `sourceTrust`, but internal native completion replies, finalizer recoveries, continuation summary updates, and non-Muse native runner tool writes (`report_progress`, `write_document`) persisted `sourceTrust: null` > - Higher-trust non-Muse native runner reads (`list_documents`, `read_document`) also bypassed document quarantine redaction > - This pull request resolves `sourceTrust` centrally in `issueService.addComment` and `documentService.upsertIssueDocument` whenever an agent writes without an explicit `sourceTrust` value, removes the `museRuntime` gate on native runner `report_progress` and `write_document` writes, and redacts quarantined documents on higher-trust non-Muse native runner reads > - The benefit is that raw outputs from low-trust native runs retain quarantine metadata across all comment and document write paths and stay redacted from higher-trust agents until promoted ## Linked Issues or Issue Description **What happened?** When an agent running under the `low_trust_review` preset completed a native run or called native runner tools (`report_progress`, `write_document`), its comments and documents were saved with `sourceTrust: null`. Because `sourceTrust` was null, higher-trust agents could read the raw low-trust output directly through ordinary comment and document access without promotion. **Expected behavior** All agent-authored comments and documents produced under `low_trust_review`—including native run completion replies, recovered finalizer replies, continuation summary updates, and non-Muse native runner `report_progress` / `write_document` writes—must persist `sourceTrust` with `preset: "low_trust_review"` and `disposition: "quarantined"`, and higher-trust agents must receive the quarantined redaction placeholder instead of the raw body. **Steps to reproduce** 1. Configure an agent with `trustPreset: "low_trust_review"` and a valid `trustBoundary`. 2. Run a native task on that agent so it writes a completion reply, calls `report_progress` or `write_document`, or refreshes `continuation-summary`. 3. Read the resulting comment or document as a standard-trust agent via `get_task_history`, `list_documents`, `read_document`, or ordinary comment reads. 4. Before this fix, `sourceTrust` is `null` and the raw body is returned unredacted. **Paperclip version or commit** `master` (`ce204a223a`) ## What Changed - **`server/src/services/issues.ts`**: Updated `issueService.addComment` to select `projectId` and `executionPolicy` on the target issue and resolve `sourceTrust` via `resolveActorSourceTrustForIssue` whenever `actor.agentId` is set and `options?.sourceTrust === undefined`. This covers native run completion replies (`run-completion.ts`), recovered finalizer replies (`native-run-finalizer.ts`), status decision committer comments (`status-decision-committer.ts`), and internal agent comment writes. - **`server/src/services/documents.ts`**: Updated `documentService.upsertIssueDocument` to select `projectId` and `executionPolicy` on the target issue and resolve `sourceTrust` via `resolveActorSourceTrustForIssue` whenever `input.createdByAgentId` is set and `input.sourceTrust === undefined`. This covers continuation summary refreshes (`issue-continuation-summary.ts`), native plan writes (`native-session-executor.ts`), and internal agent document writes. - **`server/src/services/native-runtime/paperclip-runner-tool-authority.ts`**: Removed the `this.binding.museRuntime` guard on `resolveActorSourceTrustForIssue` in `report_progress` and `write_document` so all `paperclip_runner` runs tag writes consistently, and added higher-trust quarantine redaction (`redactQuarantinedBodyForHigherTrust`) for non-Muse `list_documents` and `read_document` reads. - **`server/src/__tests__/source-trust.test.ts`**: Added red-green regression tests covering `addComment` without explicit `sourceTrust`, `upsertIssueDocument` without explicit `sourceTrust`, and non-Muse `PaperclipRunnerToolAuthority` `report_progress` / `write_document` writes read by a higher-trust agent via `get_task_history`, `list_documents`, and `read_document`. ## Verification - Confirmed the new regression tests failed before the fix (`sourceTrust` received `null` on `addComment` and `upsertIssueDocument`). - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/source-trust.test.ts` — 10/10 passed. - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/low-trust-red-team-routes.test.ts` — 14/14 passed. - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/issue-continuation-summary.test.ts` — 8/8 passed. - `pnpm --filter @paperclipai/server typecheck` — passed with 0 errors. - `pnpm verify` exited 2 (broad CI coverage required); CI will run the full required check matrix on this PR. ## Risks - Low risk. Standard-trust agent writes continue to resolve to `sourceTrust: null` (unchanged behavior). - Callers that already pass an explicit `sourceTrust` value (such as promotion flows or HTTP routes) keep their explicit value without extra work. - Only newly inserted comments and agent-authored document upserts without an explicit `sourceTrust` perform the policy lookup inside the existing transaction. ## Model Used - Google Gemini (Antigravity agentic coding assistant) with tool use and local code/test execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [ ] I will address all Greptile and reviewer comments before requesting merge |
||
|
|
0f36a88f41 |
fix(notifications): stop toasting "changed the title" on task updates (#23674)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - The board shows live toast notifications when another person or agent changes a task. > - Each title edit makes a toast that says "<actor> changed the title". > - Agents often set or change task titles automatically. These toasts are noise and give no useful information. > - This pull request removes title changes from the toast details on the server and from the toast text in the UI. > - The benefit is fewer unhelpful notifications. Status, priority, assignment, and description changes still show. ## Linked Issues or Issue Description **Describe the bug** Users get toast notifications that only say "<actor> changed the title". **Steps to reproduce** 1. Open the board as a user. 2. Let another user or an agent change the title of a task. 3. See the toast "<actor> changed the title". **Expected behavior** A title change does not show a notification. Other changes in the same update still show. ## What Changed - `server/src/realtime/activity-toast-details.ts`: the projection does not set `titleChanged` any more. This also stops old cached UI bundles from showing the toast. - `ui/src/context/LiveUpdatesProvider.tsx`: `describeIssueUpdate` does not add "changed the title". A title-only update now makes no toast. - Tests: new UI and server tests for title-only and mixed updates. The existing tests now expect no `titleChanged` field. ## Verification - Red-green: the new UI test "does not announce title changes" failed before the fix and passes after it. - `cd ui && npx vitest run src/context/LiveUpdatesProvider.test.ts`: 140 passed. - `cd server && npx vitest run src/realtime/activity-toast-details.test.ts src/__tests__/live-events-toast.test.ts`: 19 passed. ## Risks - Low risk. Title changes do not show a toast any more. The task activity log still records them. ## 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) - [ ] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details (the execution workspace assigned the branch name) - [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 doc describes this toast) - [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: devinfoley <139239+devinfoley@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
bca282e587 |
feat(recents): add tasks from manual routine runs to Recents (#23675)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The sidebar Recents list shows the tasks from a person's own recent activity > - A person can run a routine manually with "Run now", and the run creates a task > - That task does not show in Recents, and opening it does not keep it there, because Recents only admits tasks under the Mine participation rule. This also affects every routine, channel, and agent-created task that a person opens > - The Mine rule keeps these tasks out of Mine on purpose, so we must not change that rule > - This pull request adds a separate Recents eligibility flag. It also admits tasks that the viewer opened and tasks from manual routine runs that the viewer started. The UI records the new task in Recents when the run starts > - The benefit is that people can find the task they just started from the sidebar at once, and Mine stays unchanged ## Linked Issues or Issue Description **Is your feature request related to a problem? Please describe.** When I run a routine manually and it creates a task, the task is not in my Recents list. I must go to the routine or the task list to find it. **Describe the solution you'd like** When I run a routine manually and a task is created, add that task to my Recents list automatically, even if I did not open it. Also, a task that a routine creates does not show in Recents even after I open it. **Additional context** Mine must continue to keep routine tasks out by default, including routines that a person starts manually (see `doc/PRODUCT.md`). ## What Changed - `server/src/services/issue-summaries.ts`: navigation summaries return a new `isRecentEligibleForMe` flag. It is true when one of these conditions is true: - The viewer participates under the Mine rule. - The viewer opened the task. The check is the viewer's `issue_read_states` row, which is unique on company, issue, and user. - The viewer started the manual routine run that created the task. The check is a `routine_runs` row found through the indexed `linked_issue_id`, with `source = 'manual'` and the same ID as the issue's `originRunId`. The issue `createdByUserId` must be the viewer, with no creating agent. `isParticipantForMe`, Mine, and unread state do not change. - `packages/shared`: add `isRecentEligibleForMe` to `IssueSummary`. - `ui/src/hooks/useRecentTasks.ts`: Recents uses `isRecentEligibleForMe` (with a fallback to `isParticipantForMe` for older cached summaries) to show, keep, and prune entries. - `ui/src/lib/recent-tasks.ts`: add `recordStartedRoutineRunTask`. It puts the run's task at the top of Recents. The summary fetch then supplies the title and status and confirms eligibility. - New `useRecordRoutineRunInRecents` hook. All five "Run now" paths call it on success: Routines (both list variants), Routine detail, Execution workspace detail, and the Responsibility screen. - `tests/runner-e2e/source-sdk-public-inputs.json`: refresh the pin for `packages/shared/src/types/issue.ts`. - `doc/PRODUCT.md`: document the Recents behavior. ## Verification - `cd ui && npx vitest run src/hooks/useRecentTasks.test.tsx`: 29 passed. The new test "shows a task from the viewer's manual routine run at the top before it is opened" fails on the old hook (red) and passes with the change (green). Other new tests cover a run that the server does not confirm (for example, a coalesced run) and a repeat run for a task that is already in Recents. - `cd server && npx vitest run src/__tests__/issue-summaries-routes.test.ts` (embedded Postgres): 24 passed. One new test checks that a manual run by the viewer is Recents-eligible but not a Mine participant, and that runs by another person and scheduled runs are not eligible. Another new test checks that a routine task the viewer opened is Recents-eligible, and that a task opened only by another person is not. That test fails on the previous service code (red) and passes with the change (green). - `ui` typecheck: no errors in changed files. (Errors exist only in ungenerated Storybook feature-map indexes, which this change does not touch.) - The full `server` typecheck was killed by the local memory limit. CI covers it. - Manual check: run a routine with "Run now", then look at sidebar Recents. The new task shows at the top before you open it. Mine does not show it. ## Risks - Low risk. No schema change and no migration. - The summaries query adds two `EXISTS` subqueries per requested task. Both use indexes (the read-state unique index and `routine_runs_linked_issue_idx`). The request is bounded by `ISSUE_SUMMARIES_MAX_IDS`. - Behavior change: Recents now keeps tasks that the person opened, also when the task is automatic work. Old local Recents entries for automatic tasks that the person read can come back. - If a manual run coalesces into an existing task that the viewer did not start, the entry is pruned after the summary read. That task does not show in Recents. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), via Claude Code with tool use (shell, file edit, test runs). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [ ] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [ ] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [ ] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: devinfoley <139239+devinfoley@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
3f882fc589 |
fix(native): stage task-description attachments for native agents (#23688)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work.
> - People often create a task with a screenshot in its description and
assign it to a native agent.
> - The native Runner stages wake-comment files into the agent
workspace, so the agent can open an image with its file reader.
> - Files attached to the task description have no comment, so the
Runner never staged them.
> - The agent then said that it could not see the screenshot, or it
guessed from the text.
> - This pull request stages the task's own files on every native wake.
> - The benefit is that an agent can see the screenshot that explains
the task.
## Linked Issues or Issue Description
**What happened?**
A user created a task with the description "This list should probably be
sorted alphabetically" and pasted a screenshot of the list. A Claude
agent on a native sandbox replied that it could not open the screenshot
and asked which list to sort. It found the attachment through the API,
but the run had no staged path and no tool that put the image in its
workspace. When the same image was attached to a comment, the agent
opened it at once.
**Expected behavior**
A native agent can inspect files that are attached to the task
description, the same as files attached to a wake comment.
**Steps to reproduce**
1. Create a task and paste an image into its description.
2. Assign the task to a native `paperclip_runner` agent.
3. Ask the agent what the image shows.
4. The prompt has no "Paperclip native attachment access" entry for the
image, and the agent cannot see it.
**Paperclip version or commit**
`master` at
|
||
|
|
0d867729db |
fix(server): encode non-Latin-1 workspace download filenames (#23683)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Board users can open and download files from a task's workspace through the file-resources route > - The download response builds a raw `Content-Disposition` header from the file name > - Node rejects header values that hold characters outside Latin-1, such as the U+202F narrow no-break space in macOS screenshot names, or CJK text > - The route then fails with `TypeError: Invalid character in header content ["Content-Disposition"]` and returns 500 > - This pull request makes the route use `res.attachment()`, which encodes the name correctly > - The benefit is that users can download workspace files with any name ## Linked Issues or Issue Description Refs #22892. That PR fixes the same defect in the asset and invite-logo routes. This PR fixes the last route that builds the header by hand: the workspace file download. The two PRs change different files and do not conflict. **What happened?** A staging server reported `TypeError: Invalid character in header content ["Content-Disposition"]` from `ServerResponse.setHeader`. A workspace file download with a non-Latin-1 file name returns HTTP 500 for the same reason. **Expected behavior** The download succeeds. The header holds an ASCII `filename` fallback and an RFC 6266 `filename*` parameter with the full UTF-8 name. **Steps to reproduce** 1. Put a file named `Screenshot 10.32.55 PM.png` (with U+202F before `PM`) in a project workspace. 2. Download it through `GET /api/issues/:issueId/file-resources/content?download=1`. 3. The server returns 500. **Relevant logs or output** `TypeError: Invalid character in header content ["Content-Disposition"]` at `ServerResponse.setHeader (node:_http_outgoing)`. ## What Changed - `server/src/routes/file-resources.ts`: the download path now calls `res.attachment(safeAttachmentFilename(title))` instead of writing the raw header. The call comes before `Content-Type`, so the route keeps its own content type. - `server/src/__tests__/file-resources.test.ts`: a new test downloads a file whose name holds U+202F and Japanese text. It checks the status, the content type, the encoded `Content-Disposition`, and the bytes. ## Verification - Red: without the route change, `npx vitest run src/__tests__/file-resources.test.ts -t "not Latin-1"` fails with `expected 500 to be 200`. - Green: with the change, `npx vitest run src/__tests__/file-resources.test.ts` passes (53 of 53). The old `archive.bin` and `index.html` download tests still get `attachment; filename="..."` unchanged. - I also reproduced the Node error directly: `setHeader("Content-Disposition", 'inline; filename="Screenshot 10.32.55 PM.png"')` throws the same message. ## Risks Low risk. ASCII file names produce the same header as before. Non-Latin-1 names now get a `?` fallback in `filename` and the full name in `filename*`, which current browsers use. `res.attachment()` also sets `Content-Type` from the extension, but the route sets its own value right after that call. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), used as an agent with tool use (shell, code edits, test runs). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: paperclipbugbot <356415228+paperclipbugbot@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
ded4c1bf15 |
fix(server): encode Unicode asset response filenames (#22892)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - People open uploaded files and company logos from their browser. > - Two routes put the stored filename directly into an HTTP header. > - Node rejects some valid Unicode names used by screenshot tools and people. > - This change formats both filenames with the same Express API used for issue attachments. ## Linked Issues or Issue Description Fixes: #7493 Thanks to dosthcpp for the report and the earlier proposal in #7494. The issue attachment route already uses Express to format the filename. The asset content and invite logo routes still wrote it directly. Related #8716 and #9570 cover attachment display policy and ZIP downloads. ## What Changed - Format the filename with Express in the asset content and invite logo responses. Keep the current content type and inline or attachment choice. - Exercise a screenshot with a narrow non-breaking space and a logo with Japanese characters. ## Verification - On the preceding master `f1dd9288d`, both Unicode cases returned 500 before the fix. - On `3fbf872d9` with the fix, 57 tests passed across the assets, invite logo, and issue attachment suites. The new checks verify status, Unicode filename encoding, and inline disposition. - Full server typecheck, test budget, and `git diff --check` passed. PR CI is pending. ## Risks - Both routes still set the content type from storage metadata after formatting the filename. The existing disposition, range, and content policy behavior remain covered by the route tests. ## Model Used - OpenAI Codex (GPT-6 family) with terminal and Vitest access. Exact model identifier and context window were not exposed in this 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 - [ ] 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 |
||
|
|
c5f5d3163d |
test: remove recovery and Tailscale readiness races (#23678)
## Thinking Path > - Paperclip requires checks for an exact Core source commit before it publishes images. > - Cloud readiness runs the server integration tests without retries. > - Server shard 18/20 failed in recovery cleanup and Tailscale enrollment. > - The recovery test returned before its status wake reached the heartbeat drain. > - The Tailscale fixture exposed state before it was safe to read or observe. > - This pull request makes those fixtures wait for their actual completion boundaries. ## Linked Issues or Issue Description Refs #23227. Related earlier cleanup fix: #23673. **What happened?** [Docker run 47225196060](https://github.com/paperclipai/paperclip/actions/runs/47225196060) stopped after [Cloud readiness server shard 18/20](https://github.com/paperclipai/paperclip/actions/runs/47225196237/job/144677926140) failed. Staging image preparation then waited for a verified Core image. The previous Runner reattachment cleanup fix passed its protocol lane in that run. The recovery test deleted agents after a late wake inserted a child row. The Tailscale test failed its first connection. On the [next master run](https://github.com/paperclipai/paperclip/actions/runs/47227863572/job/144687185775), the Tailscale blocked-save test timed out while waiting for a callback that startup might never reach. **Expected behavior** Fixture teardown must join the status wake. The fake Tailscale CLI must publish complete state and receive each simulated consent event reliably. Tests must await enrollment completion and fail promptly when connection setup fails. **Steps to reproduce** Run the two changed test files or server shard 18/20 with retries disabled. The unmodified local files reproduced a consent callback failure. The CI links above record the foreign-key and blocked-save failures. The foreign-key failure did not reproduce in the initial local run. **Paperclip version or commit** Failures on `07150650c926d8947ae591f61e4ed854ca284149` and `ba521863f6090e40a37ed3cb6b1ecaf358a11424`. The fix starts from the latter and is rebased onto `86042310917c15eb04be121baf58a6929e52a7d2`, which adds release notes only. **Deployment mode** Source checkout in GitHub Actions. Local checks use macOS arm64, Node 25.6.1, hermetic Tailscale executables, and disposable embedded PostgreSQL. Searched open PRs and issues for the failing files, `ENOTEMPTY`, Runner cleanup, and Tailscale tests. No duplicate fix was found. Issue #23227 describes the startup-dependent expiry window and is also addressed here. ## What Changed - Wait for the accepted recovery status change to persist its wake before the existing heartbeat drain deletes fixture tables. The wake has an asynchronous route prologue that can outlive the HTTP response. - Register a signal handler in the owned fake CLI before exposing the login URL. Publish fixture state atomically, then signal that exact child to simulate consent. This removes the dependency on filesystem notification delivery. - Await the network manager's completion promise instead of a short callback polling window. - Start the expiry test with a valid window, advance the application clock after startup, and submit late consent. Keep real subprocess timers and restore the clock spy in `finally`. - Race blocked-save admission against early connection settlement so startup failures are reported instead of hanging the test. - Only two test files change. Runtime behavior, release gates, and deployment policy do not change. ## Verification - Baseline: the unmodified two-file run failed the consent callback assertion; 129 tests passed. The recovery cleanup passed locally, with its CI failure retained above. - An intermediate expiry check failed its one-second callback wait. A later parallel shard run still lost a filesystem notification. The final fixture uses an explicit consent signal and awaits manager completion. - That eight-worker shard run also timed out in unchanged workspace-trust and runtime-control fixtures while a monolithic typecheck ran concurrently. Those two unchanged files passed in a serial control with the changed fixtures: 186 tests passed across four files. The final shard is run separately with four workers and retries disabled. - `pnpm exec tsc --noEmit -p tsconfig.json` from `server/`: passed. - After the release-notes-only rebase, the Tailscale file passed again: 9 tests, retries disabled. The two fixture file contents are identical to the final shard run. - `PAPERCLIP_VITEST_RETRY=0 PAPERCLIP_VITEST_MAX_WORKERS=4 pnpm test:run:general -- --group general-server-without-chat-or-native-runner --shard-index 17 --shard-count 20`: passed on the final fixture contents. 85 files passed, 3 skipped; 1945 tests passed, 18 skipped. Duration: 160 seconds. - `node scripts/check-test-budget.mjs --files server/src/__tests__/issue-recovery-actions.test.ts server/src/services/connectors/tailscale/device-login-network.test.ts`: passed. - `git diff --check` and local secret/PII review: passed. - [Greptile review](https://github.com/paperclipai/paperclip/pull/23678#issuecomment-7396242983): 5/5 on head `13bf3586bcf3201ce137f674812e8faf778ee77d`, with a successful current-head check and no actionable findings or review threads. The [full PR CI workflow](https://github.com/paperclipai/paperclip/actions/runs/47231990509) passed on attempt 1. All 71 reported checks are clean on this head; GitHub reports `CLEAN` / `MERGEABLE` and there are no unresolved review threads. ## Risks Low risk. The change is limited to fixtures. A missing status wake or failed enrollment still fails the tests. The expiry case now checks actual late-consent rejection without making success depend on process startup time. No schema, API, or runtime changes are required. The tests and PR explain the behavior; no documentation update is needed. A new verified master image is still required before staging can resume. ## Model Used OpenAI `gpt-6.1-sol` through the Codex harness in T3 Code, with xhigh reasoning effort, shell and file tools. The harness does not expose the context window size. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge Co-authored-by: Paperclip <noreply@paperclip.ing> |
||
|
|
c2a8821809 |
fix(agents): keep a prepared agent setup when its configuration changes (#23669)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - A new agent can use a plugin environment that requires an agent. A lifecycle plugin prepares that environment before the agent can work. > - The setup flow creates a draft agent first, so that this preparation can start before the person finishes setup. > - Each change to the draft's harness, model, or sign-in started preparation again. The hire also started it again. > - Verification cannot start until the last preparation is complete. So the early preparation did not decrease the wait after the hire. > - This pull request keeps the preparation when the agent stays on the same environment driver. > - The benefit is that a person who finishes setup waits only for verification. ## Linked Issues or Issue Description I searched the open and closed issues and pull requests. I did not find a duplicate. **What happened?** Create an agent in setup on a plugin environment that declares `requiresAgent: true`. The draft is prepared. Then choose a harness, sign in, and hire the agent. Each of these three steps starts `preparing` again. The agent page shows preparation after the hire, although the environment was ready before the person signed in. **Expected behavior** A change to the harness, model, credentials, or instructions does not change the environment. It must not start preparation again. The hire must go directly to verification. If preparation is in progress, the hire must join it. **Steps to reproduce** 1. Install a lifecycle plugin with an environment driver that declares `requiresAgent: true`. 2. Make that environment the instance default. 3. Create a setup draft and wait until `lifecycleState` is `verifying`. 4. Save a different model on the draft. `lifecycleState` goes back to `preparing`. 5. Hire the draft. `lifecycleState` goes back to `preparing` again. **Paperclip version or commit** `7e025ae65f` **Deployment mode** Self-hosted server with a plugin environment that requires an agent. ## What Changed - A configuration change restarts `preparing` only when the agent moves to an environment that needs setup. The existing environment and driver check makes this decision. - A prepared setup draft stays prepared when its harness, model, credentials, or runtime configuration change. - The hire of a prepared draft goes directly to `verifying` with a new operation. - The hire of a draft that is still `preparing` keeps the operation and its version. Verification starts when that operation is complete. - A hire that moves to an environment that needs setup starts `preparing` again, as before. - A save that changes an environment to another driver of the same plugin now also refuses `preparing` agents, the same as `ready` and `verifying` ones. - A change to instructions alone does not restart verification. The hire writes the managed instruction files immediately after it commits, and verification does not read them. - The hire clears an old lifecycle error on the draft. - These behaviors do not change: - a draft that no longer needs preparation goes to `pausing` - a hire that needs approval, a hire with a hold, and a company hold - an edit to other execution configuration during verification - an edit during `resuming` - `doc/AGENT-LIFECYCLE.md` describes the new rules. ## Verification - `npx vitest run src/modules/agent-lifecycle`: 224 passed. Four new tests cover a prepared draft, a hire from a prepared draft, a hire during preparation, and an instruction change. Three of them failed before the change. The fourth could not run because a test before it left the fixture blocked. - `npx vitest run` on the hire, lifecycle delivery, agent secret, pending approval, secret binding, managed plugin environment, and plugin task tests: all passed. - `npx vitest run` on the two Dot onboarding files: 25 passed. - `pnpm --filter @paperclipai/server typecheck`: passed. - Not done: a live test with a plugin environment. Three existing tests used an agent in `preparing` to test that a configuration change fences verification. They now use `verifying`. ## Risks - A lifecycle plugin that reads the agent's harness or model during `preparing` is not called again when they change. The lifecycle request does not carry them. Verification still tests the final configuration. - A prepared environment can be lost between preparation and hire. Verification then fails and retries, and a pause and resume prepares it again. Before this change, the hire prepared it again. - An edit during `preparing` does not cancel the attempt in progress. A plugin must not fail because the agent's configuration changed during its call. - No migration. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, in Claude Code, with extended thinking, tool use and code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
ba521863f6 |
perf(skills): import environment skills when a setup draft is created (#23672)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - A plugin environment driver can declare `skillKeys`. Core adds those managed skills to each run on the environment. > - Before a run can use a skill, Core imports it into the company's skill library. This occurs once for each company. > - The import occurs when the first task starts. So the first task in a new company waits for it. > - Each missing skill is imported in its own transaction. Each import checks all bundled skills two times, and the transactions do not share that check. > - This pull request starts the import when a person creates a setup draft, and checks the bundled skills once. > - The benefit is that the first task starts sooner. The setup does not wait for the import. ## Linked Issues or Issue Description I searched the open and closed issues and pull requests. I did not find a duplicate. **What happened?** The first task on a plugin environment with four managed skills spent more than ten seconds in skill import. Most of this time was the check and first import of Core's bundled skills. That check ran again for each managed skill. **Expected behavior** The import must start before the first task, while the person completes setup. One import must check the bundled skills once. **Steps to reproduce** 1. Install a plugin with an environment driver that declares several `skillKeys`. 2. Make that environment the instance default. 3. Create a company, set up its first agent, and give it a task. 4. Measure the skill selection part of the first run's preparation. **Paperclip version or commit** `7e025ae65f` **Deployment mode** Self-hosted server with a plugin environment that declares managed skills. ## What Changed - When a person creates a setup draft, the server imports the environment's missing skills in the background. The response does not wait for this import. - A failed background import writes a warning. It does not change the draft. Run admission still installs the skills that are missing. - The background import is counted as active work, so an idle drain waits for it. It runs once and does not poll or retry. - An environment skill import checks the bundled skills once before it installs the missing skills. Before, each skill did this check two times in its own transaction. - `importPackageFiles` reads the library rows after its own inventory check. It no longer does the check a second time. - `doc/skills-and-teams-catalog.md` describes the new behavior. Skill selection, version pins, and the files that a run receives do not change. ## Verification - `npx vitest run src/__tests__/environment-skills.test.ts`: 7 passed. Two tests are new. They fail when I remove the single check and the background import. - `npx vitest run` on the company skill service, managed skill content, company portability, agent adapter validation, and agent lifecycle tests: all passed. - `src/__tests__/ai-connections.test.ts`: 5 of its tests failed in the same local run. The reconnect tests also fail at `7e025ae65f` without this change on the same local database. They do not use this code. - `pnpm --filter @paperclipai/server typecheck`: passed. - Not done: a measurement of the first task with this change. ## Risks - A draft that a person abandons leaves the imported skills in the company library. The same skills are imported for the next agent on that environment. - The background import and a first task can run together. The existing lock for each skill makes the second one wait and use the first result. - The bundled skill check now runs outside the skill's transaction. If the skill import then fails, the bundled skills remain imported. They are imported by other library reads too. - No migration. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, in Claude Code, with extended thinking, tool use and code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
1fb8ddb740 |
feat(trust): allow transient workspace_prepare checkout for low-trust in-boundary projects (#23656)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The low-trust review preset isolates untrusted review agents inside sandboxes with no runtime GitHub tokens and no sandbox network access > - When a low-trust agent is explicitly assigned to a private-repository project with `git.read` enabled, workspace preparation routed the setup-time clone through `resolveGitHubOperationCredentials`, which blocks all low-trust credential export and caused `stage=clone git=auth_failed exit=128` before the agent could start > - Setup-time `prepareRemoteWorkspaceDirectory` runs on the trusted controller path before the agent starts, uses transient `GIT_CONFIG_*` / `PAPERCLIP_GIT_TOKEN` environment variables with `-c core.hooksPath=/dev/null`, and writes zero credentials into `.git/config` > - This pull request adds `resolveGitHubWorkspacePrepareCredentials` for controller-only `workspace_prepare` call sites, allowing transient clone credentials strictly for a repository configured on a project inside `trustBoundary.projectIds` when `git.read` is permitted (preferring an agent-installed GitHub PAT connection when present), while keeping runtime shell credentials (`resolveGitHubOperationCredentials`) strictly denied > - The benefit is that assigning a low-trust agent to a private-repo project works out of the box for local read-only code review without exposing any live GitHub token to the agent runtime ## Linked Issues or Issue Description **What happened?** When an agent configured with `trustPreset: "low_trust_review"` and `allowedToolClasses: ["git.read"]` was assigned a task in a project with a private GitHub repository workspace, workspace preparation failed before the agent started with `remote_workspace_prepare_failed: stage=clone git=auth_failed exit=128 program=git`. **Expected behavior** When a `low_trust_review` run has `git.read` enabled and targets a project explicitly listed in `trustBoundary.projectIds`, the trusted controller should clone that project's configured repository during `workspace_prepare` using transient credentials (preferring an agent-installed GitHub PAT connection if configured, otherwise the run's managed GitHub identity), while leaving zero credentials in `.git/config` and keeping runtime GitHub credential export strictly denied. **Steps to reproduce** 1. Create a project with a private GitHub repository workspace. 2. Configure an agent with `trustPreset: "low_trust_review"`, `projectIds: [projectId]`, and `allowedToolClasses: ["git.read"]`. 3. Run a task in that project on a cloud sandbox environment. 4. Before this fix, `createGitRemoteAuthProvider` falls back to anonymous clone and fails at `stage=clone git=auth_failed exit=128`. **Paperclip version or commit** `master` (`23ca89e376`) ## What Changed - **`server/src/services/github-operation-credentials.ts`**: Added `resolveGitHubWorkspacePrepareCredentials`, `allowsLowTrustWorkspacePrepareCheckout`, and `resolveAgentInstalledGitHubPat`. For `low_trust_review` runs, transient prepare-time clone auth is permitted only when `trust.kind === "low_trust_review"`, `git.read` is in `allowedToolClasses`, the task's project is explicitly in `trustBoundary.projectIds`, and `remoteUrl` matches a configured `project_workspaces.repo_url` on that project. Prefers an active agent-installed GitHub `api_key` (PAT) connection when present and otherwise falls back to `resolveManagedGitHubCredential`. Runtime `resolveGitHubOperationCredentials` remains unchanged and strictly denied for low-trust runs. - **`server/src/services/git-credentials.ts`**: Added optional `purpose?: "workspace_prepare"` to `createGitRemoteAuthProvider` so only controller workspace-preparation call sites invoke `resolveGitHubWorkspacePrepareCredentials`. - **`server/src/services/heartbeat/workspace-preparation.ts`** and **`server/src/services/heartbeat/workspaces.ts`**: Passed `purpose: "workspace_prepare"` at the four controller workspace-preparation call sites. - **`server/src/__tests__/github-operation-credentials.test.ts`**: Added unit, security-boundary, and end-to-end `prepareRemoteWorkspaceDirectory` tests covering managed identity prepare checkout, agent-installed GitHub PAT preference, runtime credential denial, unrelated repo denial, missing `git.read` denial, and zero credentials persisted in `.git/config`. ## Verification - `pnpm --filter @paperclipai/server typecheck` — passed with 0 errors. - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/github-operation-credentials.test.ts` — 30/30 passed (including the 3 new low-trust `workspace_prepare` and local E2E `prepareRemoteWorkspaceDirectory` tests). ## Risks - Low risk. Runtime agent credential endpoints (`/runtime-tools/github/credentials`, native GitHub broker, skill-source fetch) continue calling `resolveGitHubOperationCredentials` and stay strictly denied for `low_trust_review`. - Prepare-time credentials are scoped strictly to repositories already configured in `project_workspaces` for a project explicitly inside `trustBoundary.projectIds` and only when `git.read` is enabled. ## Model Used - Google Gemini (Antigravity agentic coding assistant) with tool use and local code/test execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [ ] I will address all Greptile and reviewer comments before requesting merge |
||
|
|
bba20403ba |
fix(cloud-trial): do not attach Connect OpenRouter repair card on starter-trial auth failures (#23633)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - When a normal agent fails with a provider authentication error, `connectionIntentService.requestForRunAuthFailure` infers the AI provider from the agent's model and attaches a pending `"Connect <Provider>"` interaction card on the issue thread. > - Cloud starter-inference agents (`runtimeConfig.cloudTrialInference: true`, no saved `aiConnection`) run OpenCode with `openrouter/openai/gpt-6-luna` through Paperclip Cloud's server-side proxy instead of a user-saved OpenRouter connection. > - If a starter-inference run ever encounters an OpenRouter 401 failure, `requestForRunAuthFailure` attached a pending `"Connect OpenRouter"` card, causing the agent to keep nagging the user to respond to that card on subsequent turns even after succeeding. > - This pull request skips `requestForRunAuthFailure` for agents using Cloud starter inference without a saved `aiConnection`, leaving `CloudTrialGate` as the single owner of prompting users to connect a model provider. > - The benefit is that starter-inference chats never accumulate stale `"Connect OpenRouter"` cards. ## Linked Issues or Issue Description Refs #23401, #23616 **Summary** Skip creating a `"Connect OpenRouter"` `connection_intent` card in `requestForRunAuthFailure` when the agent runs on Cloud starter inference (`runtimeConfig.cloudTrialInference: true` without a saved `aiConnection`). **Steps to Reproduce** 1. Run an OpenCode agent configured with `runtimeConfig.cloudTrialInference: true` and `adapterConfig.model: "openrouter/openai/gpt-6-luna"` (no `runtimeConfig.aiConnection`). 2. Trigger an OpenRouter HTTP 401 authentication failure on a run. 3. Observe `requestForRunAuthFailure` creating a pending `"Connect OpenRouter"` `issue_thread_interactions` row on the chat issue. **Expected Behavior** `requestForRunAuthFailure` returns `null` and creates no pending `"Connect OpenRouter"` interaction for Cloud starter-inference agents. ## What Changed - `server/src/services/connection-intents.ts`: Returned `null` in `requestForRunAuthFailure` when `!saved && !router && isAgentUsingCloudTrialInference(agent.runtimeConfig)`. - `server/src/__tests__/connection-intents-service.test.ts`: Added a regression test proving that an OpenRouter 401 failure on a Cloud starter-trial agent returns `null` and creates zero `issue_thread_interactions` rows. ## Verification - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/connection-intents-service.test.ts -t "does not create a Connect OpenRouter card|adopts a Copilot account"` — passed (2/2 tests). - `pnpm --filter @paperclipai/server typecheck` — passed (0 errors). ## Risks - Low risk. Narrow 1-line guard scoped strictly to agents with `runtimeConfig.cloudTrialInference === true` and no saved `aiConnection`. Normal agents with or without saved AI connections keep their exact existing auth-repair behavior. ## Model Used - Google Gemini (Antigravity agentic runtime, thinking mode with tool use and local code execution). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [ ] I will address all Greptile and reviewer comments before requesting merge |
||
|
|
63d3354be7 |
fix(runner): keep the session of a stopped run (#23543)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The conversation an agent has on a task is called a session. Each task saves a pointer to its session (the session link), and the next run uses it to continue the conversation > - A run's own record keeps its session id. The task gets its pointer to that session only when the run's result is accepted > - A stopped run has no accepted result, so it saves no pointer. If a task's first run is stopped, the task has no pointer. The next run starts a new session and the agent has forgotten the first run > - A later run can also start a new session, for example after an assignment, a retry or a configuration change. If that run is stopped, the pointer still names the older session. The next message goes back to the older session or starts another one > - Saving the pointer on every stop would be unsafe. The agent's turn might still be open, a request might still be waiting, or the provider might not have kept the session > - This pull request copies the session id from a stopped run to the task only when the records show that the stop was acknowledged, the turn started and then ended with nothing waiting, the provider kept the session, and no newer run has taken over the task. Otherwise, the pointer does not change > - The benefit is that someone can stop a run, send a correction, and continue the same conversation ## Linked Issues or Issue Description No issue exists. **What happened?** A user stopped the first run of a task. The user then sent a message. The agent started a new session and did not remember the first run. The same loss happens when a user stops a later run that started a new session. **Expected behavior** The agent continues the session of the stopped run. **Steps to reproduce** 1. Use an agent whose environment provider runs Runner tasks and keeps their session state. 2. Create a task and wait for the first run to start a turn. 3. Stop the run during the turn. 4. Send a message on the task. 5. See that the new run has a new session. **Paperclip version or commit** `4db307d53c` **Deployment mode** Self-hosted server with a sandbox environment plugin. ## What Changed - A stopped run now links its session after its environment lease is released. - The link needs all of this evidence: - The Stop was delivered and acknowledged. - The provider accepted a turn. The next prompt leaves out messages that the linked run received, so a run whose turn did not start cannot be linked. - The turn ended. No request, background work or goal is waiting. - The controller journal is settled. - The provider reports that the task stopped and that it kept the session state. - No newer run, reset or conversation owns the task. - An existing link is replaced only if its run belongs to the same task and agent and finished before the stopped run started. Accepted results already use this rule. Both paths now share one function. - If any evidence is missing, the link does not change, as before. - If the provider later confirms that the kept state is gone, the next run starts a new session. The acknowledged Stop replaces the committed result in that proof. All other checks in that proof still apply. ## Verification - `npx vitest run` on the publication tests for stopped runs, the publication tests for accepted results, the runtime execution tests and the terminal state reader test: 121 passed. The executor tests ran on an earlier commit, and the executor code has not changed since. - The publication tests use embedded Postgres. They test six saves and 37 refusals. Each refusal checks that the task session row did not change. - The executor tests check that a stopped run retires after a confirmed state loss. They also check that an unacknowledged Stop and a different failure stay refused. - `npx tsc --noEmit` in `server` has no errors. - Saved evidence from two real first-run stops during a turn shows ended turns with no request waiting. The first has a released lease with kept session state. The second failed its lease cleanup, so this change still refuses it. - Saved evidence from two real later-run stops: one kept its session, and the next run resumed it. The other kept no session and had no settled turn, and the next run failed. This change refuses to link the second. - Two of 104 real stops with a cancelled terminal had no accepted turn. The turn check refuses them. - Not done: a live test of this change. CI runs the Runner integration suites. ## Risks - A wrong link could resume an unsafe session. The link uses the same evidence that the resume path checks again, so the resume path still refuses an unsettled session. - A link that turns out to be unusable now replaces an older link instead of no link. The next run then usually fails, and the run after it usually starts a new session, as it does for an unusable link from a finished run. - The change applies only to providers that run Runner tasks and report kept session state. Local Runners and other sandboxes have no equal evidence, so they keep the previous behavior. - A stop while the agent waits for background work is not covered. The Runner holds its terminal event in that state, so the evidence is missing. - The saved link keeps that run's Runner checkpoint, as any other link does. - No migration. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, in Claude Code, with extended thinking, tool use and code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
dc16c47362 |
refactor(runner): remove the unused plugin task source recovery path (#23590)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - An agent run uses a Runner task that an environment plugin provides. When a Runner stops, the next run can need its saved session > - #19134 and #19196 added one way to do this. The next run claims the stopped Runner's task, and then starts that task again under its own control > - Those pull requests added the claim and its checks. They did not add a caller. #19157 was to add the caller, and it did not merge > - Nothing on `master` calls the claim. No lease gets the two records that the claim writes, so every check of those records does nothing > - The unused path still looks active. A reader can change it, and can think that the change fixes a failure > - This pull request removes the claim and all code that only reads its records > - The benefit is that the code shows only the recovery paths that can run ## Linked Issues or Issue Description Refs #19134, #19196 (added the path), #19157 (closed draft that called it). **Issue type** Dead code **What happened?** `claimPluginTaskSourceRecovery` has no caller on `master`. Only the claim writes `runnerTaskSourceConsumer` and `runnerTaskSourceRecovery` to a lease. Six other server files read those records. **Expected behavior** The server contains only recovery code that can run. **Steps to reproduce** 1. Run `git grep claimPluginTaskSourceRecovery master -- server`. 2. See only the definition. 3. Run `git log -G claimPluginTaskSourceRecovery master`. 4. See that the commits added the path, and later removed its tests. No commit added a caller. ## What Changed - Removed the source recovery claim and its checks (`plugin-task-source-recovery.ts`). - Removed the special handling of a claimed source from plugin task dispatch, task resume, checkpoint writes, task ownership, and retained and warm sandbox expiry. - A Runner task owner no longer takes `codexSourceRecoveryVersion`. Nothing set it, so the owner always refused to prepare a predecessor's launch. It still refuses. - The checkpoint writer still locks both runs, and still refuses a late write from a session that moved to another task. - The plugin SDK still accepts `codexSourceRecoveryVersion` and `acpxSourceRecoveryVersion`, so a plugin that sends them does not fail. The guide now says that Core does not use them. - The Runner package does not change. ## Verification - `npx vitest run` on eight test files for the changed code: 319 tests pass. - `npx tsc --noEmit` in `server` has no errors. - The test of a late write to a retired checkpoint used the removed records. It now uses the records of a session that moved to another task. - Not run locally: the suites that start a real Runner. CI runs them. ## Risks - No production code wrote these records, so no saved lease should contain them. A lease that does contain them is no longer held by them. - #19157 depended on this path. It is closed and did not merge. - No migration. No change to the plugin or Runner protocol. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, in Claude Code, with extended thinking, tool use and code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
8e2381a1d1 |
fix(cloud-trial): use stable HMAC-signed proxy tokens across warm OpenCode sessions (#23616)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Cloud starter-inference OpenCode runs in remote Daytona sandboxes reuse warm OpenCode sessions across consecutive chat turns. > - Inside the warm sandbox, `startOpenCodeProviderProxy` stays alive bound to the first run's `PAPERCLIP_OPENROUTER_PROXY_TOKEN`. > - Because `cloud-trial-proxy.ts` generated a random per-run token and deleted it in `cleanup()`, every reused-session turn failed on attempt #1 with HTTP 401 (`Trial proxy token is no longer active on this server instance`) and posted `"The OpenCode run failed before it completed."` into the chat before auto-retry recovered. > - This pull request replaces single-run random tokens with deterministic HMAC-SHA256 signed per-`(companyId, agentId, allowedModel)` tokens (`pctrial_v1.<payload>.<sig>`) that remain valid across warm turns and stack restarts/sleep-wake, while still failing closed on tampering, `work_requires_model`, `$1` exhaustion, disallowed models, and provider migration. > - The benefit is zero spurious 401 failure messages on consecutive chat turns in warm starter-inference sessions. ## Linked Issues or Issue Description Refs #23401, #23559, #23571 **Summary** Use stable HMAC-signed proxy tokens for Cloud starter-inference OpenCode sessions so reused warm sessions succeed on attempt #1. **Steps to Reproduce** 1. Start a Cloud starter-inference (`free_inference_1`) chat with an OpenCode agent in a warm Daytona sandbox. 2. Send a first message and wait for the reply. 3. Send a second message in the same chat (`sessionReused: true`). 4. Observe HTTP 401 (`Trial proxy token is no longer active on this server instance`) and `"The OpenCode run failed before it completed."` before auto-retry starts a fresh process. **Expected Behavior** Consecutive messages on a reused warm OpenCode session authenticate cleanly on attempt #1 with zero 401 failures, while tokens still fail closed on tampering, `work_requires_model`, `$1` exhaustion, disallowed models, or migration to a user provider. ## What Changed - `server/src/services/cloud-trial-proxy.ts`: Replaced single-run random `pctrial_` tokens with deterministic HMAC-SHA256 signed `pctrial_v1.<payload>.<sig>` tokens derived from the stack's stable secret (`PAPERCLIP_CLOUD_CONNECTOR_SIGN_PRIVATE_KEY` / `PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN` / `PAPERCLIP_AGENT_JWT_SECRET` / `BETTER_AUTH_SECRET`, with a per-process random fallback). Kept `cleanup()` probing OpenRouter usage without deleting the token on normal run exit, and added `revokeCompanyTokens(companyId)`. - `server/src/services/cloud-trial-inference.ts`: Called `proxy.revokeCompanyTokens(companyId)` upon `migrateTrialAgents` completion and exposed `revokeCompanyTokens`. - `server/src/__tests__/cloud-trial-inference.test.ts`: Added regression test verifying warm session token reuse after `cleanup()`, survival across a fresh controller restart, HTTP 401 on tampered tokens, and HTTP 401 after `revokeCompanyTokens`. ## Verification - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/cloud-trial-inference.test.ts src/__tests__/cloud-trial-proxy-middleware-order.test.ts` — passed (8/8 tests). - `pnpm --filter @paperclipai/server typecheck` — passed (0 errors). ## Risks - Low risk. Tokens are HMAC-SHA256 verified with `timingSafeEqual`, strictly scoped to `(companyId, agentId, allowedModel)`, never contain the raw OpenRouter key, and fail closed on `work_requires_model`, `$1` budget exhaustion, disallowed models, and company migration. ## Model Used - Google Gemini (Antigravity agentic runtime, thinking mode with tool use and local code execution). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [ ] I will address all Greptile and reviewer comments before requesting merge |
||
|
|
4363be6069 |
fix(workspaces): resolve issue identifiers on task workspace routes (#20658)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Each task can have a task workspace, and the API lets agents and board users inspect and change it > - The routes `GET` and `PUT /api/issues/:id/workspace` and `POST /api/issues/:id/workspace/repositories` are in their own router > - The issues router changes an issue identifier (for example `ABC-12`) to the issue UUID, but that resolver does not apply to this router > - So these routes send the identifier into a UUID comparison, Postgres refuses it, and the API returns 500 > - This pull request makes these routes accept an issue identifier, and return 404 for a value that is not an identifier and not a UUID > - The benefit is that the workspace routes act like the other issue routes, and a bad value gives a clear 4xx, not a 500 ## Linked Issues or Issue Description I searched the open and closed issues and pull requests for this problem. I did not find one. Related issues show the same class of error on other routes: #20356, #13504, #17332. They do not touch these routes. **What happened?** `GET /api/issues/ABC-12/workspace` and `PUT /api/issues/ABC-12/workspace` return `500 {"error":"Internal server error"}`. The server log shows `DrizzleQueryError` caused by `PostgresError: invalid input syntax for type uuid: "ABC-12"`. The same request with the issue UUID returns 200. Other issue routes, for example `GET /api/issues/ABC-12` and `GET /api/issues/ABC-12/comments`, accept the identifier. A value that is not an identifier and not a UUID (for example `not-a-task`) also returns 500. **Expected behavior** The workspace routes accept an issue identifier, as the other issue routes do. The agent skill reference (`skills/paperclip/references/issue-workspaces.md`) writes these routes with `:issueId`, so agents send identifiers. A value that does not identify an issue returns a 4xx. **Steps to reproduce** 1. Create an issue. Note its identifier (for example `ABC-12`). 2. Send `GET /api/issues/ABC-12/workspace` as a board user or as an agent. 3. See `500 Internal server error` and the UUID syntax error in the server log. 4. Send the same request with the issue UUID. See 200. **Paperclip version or commit** Seen on release `2026.1106.0`. The route code is the same on `master` at `4f33bb357`. **Deployment mode** Authenticated, private exposure. Installed from npm. Embedded Postgres. **Agent adapter(s) involved** Not adapter-specific (core bug). An agent found it with the Claude Code adapter. ## What Changed - `server/src/routes/task-workspaces.ts`: the shared `task()` lookup now uses `normalizeIssueIdentifier` and `isUuidLike` from `@paperclipai/shared`. An identifier matches `issues.identifier`. A UUID matches `issues.id`. Any other value returns `404 Task not found` before the query. - The lookup keeps the same read condition (`issueReadSqlCondition`) and the same access checks. An identifier that the actor cannot read gets the same 404 as a UUID that the actor cannot read. - `server/src/__tests__/task-workspace-binding.test.ts`: one new test. It reads and selects a workspace with the identifier (in lower case for the read), and checks 404 for `not-a-task` and for an unknown identifier. - No documentation change. The skill reference already writes these routes with `:issueId`. ## Verification - Red before the fix: `npx vitest run src/__tests__/task-workspace-binding.test.ts -t "resolves an issue identifier"` failed with `expected 500 to be 200`. - Green after the fix: the same command passes. - The three test files that mount these routes pass: `task-workspace-binding.test.ts`, `heartbeat-repository-catalog-recovery.test.ts` and `workspace-preparation-history.test.ts` (117 tests). - `pnpm --filter @paperclipai/server typecheck` passes. - `pnpm verify --base upstream/master` keeps 2,498 test files, because `server/src/app.ts` imports the route. I stopped the local run after 75 minutes, in the first of its 10 jobs. In that part, four files failed: `file-resources-git-scan-load`, `git-restore-point-expiration`, `git-workspace-expiration` and `issue-recovery-assignments`. None of them imports the changed route or `app.ts`. On the base revision, the same four files also stall on this machine: a test database connection stays idle in a transaction, and the cleanup waits for its lock. - The CI checks on this pull request run the full suite. All checks pass. - Manual check on a release `2026.1106.0` instance before the fix: identifier 500, UUID 200, `not-a-task` 500. ## Risks - Low risk. The change touches one lookup in one route file. - A UUID still matches by id, with the same checks. `isUuidLike` accepts UUID versions 1 to 5. Issue ids come from `gen_random_uuid()` (version 4). - A value that is not a UUID and not an identifier now returns 404 instead of 500. No client can depend on the old 500. ## Model Used - Anthropic Claude Opus 5.5 (`claude-opus-5-5`). Capabilities: extended reasoning, tool use and code execution. The harness does not show the context window size. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
917a38efd7 |
fix(server): give the retired task workspace conflict a stable code (#23582)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work.
> - Before a run starts, Paperclip reserves the task's remote workspace.
It refuses a workspace that is archived or whose cleanup failed, with
the message "Workspace ownership changed.".
> - When setup fails, the server sends a run-failure report to Sentry.
Since #23568, the report groups a setup conflict by the stable code in
its details.
> - This conflict has no code. Its reports use the fallback grouping and
share a Sentry group with other uncoded setup conflicts.
> - This pull request gives the conflict the code
`remote_workspace_retired`.
> - The benefit is a separate Sentry group for runs that fail on a
retired task workspace.
## Linked Issues or Issue Description
**What happened**
A task's execution workspace was archived. Automatic recovery then
started new runs for the task. Each run failed setup with "Workspace
ownership changed.". These reports went into a shared Sentry group with
unrelated setup conflicts, because the conflict had no code.
**Expected behavior**
The conflict has a stable code. Its run-failure reports get their own
Sentry group.
**Steps to reproduce**
1. Reserve a remote task workspace, then set its status to `archived` or
`cleanup_failed`.
2. Reserve the workspace again for a new run.
3. The reservation rejects with a 409 conflict that has no
`details.code`.
**Paperclip version or commit**
master at
|
||
|
|
fc09515c7e |
Emit Cloud chat.started when a chat with an agent starts (#23558)
<!-- claude-projects-attribution: {"github_login":"nguyenm7"} -->
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - Paperclip Cloud measures activation with a funnel: account created,
org named, agent named, model connected, chat launched, first agent run
succeeded, first task created
> - `model.connected`, `agent.task_run` and `task.created` come from the
server, but "chat launched" comes only from the browser
(`onboarding_step_completed` with `step=launch`)
> - `task.created` skips chats on purpose, so a person who only chats
with their agent has no server-side step after "first agent run"
> - #23403 added a Cloud-only direct PostHog path
(`trackCloudPostHogEvent`) for onboarding events that must not depend on
the browser
> - This pull request uses that path to emit `chat.started` when the
chat owner's first message or first question-card answer commits
> - The benefit is a server-side "chat started" step that counts a real
action by the person, once per chat, whichever way they reached the chat
## Linked Issues or Issue Description
Refs #23403
**What existing behavior does this improve?**
Server-side activation funnels on Paperclip Cloud.
**Current behavior**
The only "chat launched" signal is the browser `launch` step. Browser
events can be lost (wizard skipped or resumed, navigation, ad blockers
on older builds). On the server, a chat creates an issue but
`emitTaskCreatedAfterCommit` returns early for it, so no event records
that the chat started.
**Proposed behavior**
When the chat owner's first turn commits (their first message, or their
first answer to a question card such as the onboarding welcome card),
the server emits the Cloud-only event `chat.started` with `surface`
(`onboarding_chat` | `agent_chat`) and `agent_id`. Creating or preparing
a chat emits nothing, because onboarding prepares the chat before the
person clicks Launch. The Launch click itself is already relayed
server-side as `onboarding_step_completed` (`step=launch`).
**Reason and benefit**
Funnel steps should come from real product actions that the server
records. With `chat.started`, a funnel can count "chat launched" from
the server and see people who chat but never create a task.
**Breaking changes**
None. The event is new and is Cloud-only.
## What Changed
- `server/src/services/product-telemetry.ts`: add `CHAT_STARTED_EVENT`
and `emitChatStartedIfFirstOwnerTurn`. It runs inside the transaction
that wrote the person's turn and locks the chat's issue row. It checks
that the actor is the chat owner (not an agent, run, or system actor),
and that the owner has no other message and no other answered question
card in the chat. Cancelled or skipped cards do not count. Then it emits
`chat.started` through `trackCloudPostHogEvent` after commit.
- Callers: `addComment` (`issues.ts`), `answerQuestions`
(`issue-thread-interactions.ts`), both headless comment paths
(`headless-comment-group-commit.ts` and the serialized insert in
`routes/headless-channels-schemas.ts`), and the headless one-line
resolve (`headless-events-schedules-interactions.ts`).
- `server/src/__tests__/chat-started-telemetry.test.ts`: unit tests for
the first turn, both surfaces, and every case that must not emit.
- `server/src/__tests__/product-telemetry.test.ts`: embedded-Postgres
tests. Chat creation and system or other-person messages emit nothing.
The owner's first message emits once. A first message after a cancelled
card still emits. A rolled-back first message and a task comment emit
nothing.
- `docs/api/onboarding-telemetry.md`: document the server-emitted
`chat.started` event.
## Verification
- `npx vitest run server/src/__tests__/chat-started-telemetry.test.ts`:
10 passed (helper unit tests).
- `pnpm --filter @paperclipai/server typecheck`: passed.
- The cases in `product-telemetry.test.ts` need embedded Postgres, which
could not start in my environment (it runs as root). CI runs them.
## Risks
- Low. The event is fire-and-forget after commit, inside a `try`. It
does nothing on self-hosted installs, when `PAPERCLIP_POSTHOG_DIRECT=0`,
or when the PostHog environment is not set.
- One event per chat: the check runs under the chat's issue row lock,
and a rolled-back write emits nothing. `/new` in an existing chat does
not emit again.
- Two extra indexed reads run on a person's chat message or answer, and
only on chats.
### Open questions for reviewers
1. **Consent.** Like `model.connected` and the #23403 relay, this server
event is not gated by the browser cookie banner. This PR does not add a
consent check. The only switch is the existing
`PAPERCLIP_POSTHOG_DIRECT=0`. If people who decline cookies must be
excluded from server-side product events, that should be one rule for
all Cloud direct events, not a rule in this PR.
2. **New name or existing name.** This PR adds a new name,
`chat.started`, instead of emitting `onboarding_step_completed`
(`step=launch`) from the server. A new name keeps the browser and server
signals separate, so the two funnels can be compared and the existing
insights do not double count. The other choice is to emit the existing
name with a `source: server` property. Please say which one you prefer.
Not in this PR: "Agent named" has no clean server moment (the setup
agent is saved with a default name before the person names it, and
`agent.created` fires at launch), and `agent.task_run` still does not
say whether a run was a chat reply or a task. That needs a new
registered dimension in the telemetry contract, so it is a follow-up.
## Model Used
Claude Code (Anthropic Claude, agentic coding with tool use and code
execution).
## Checklist
- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [ ] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
https://claude.ai/code/session_01KmUZthscGtSrd1KaWnwzWm
---
_Generated by [Claude Code](https://claude.ai/code)_
---------
Co-authored-by: Claude <noreply@anthropic.com>
|
||
|
|
c852420baf |
fix(server): group setup conflicts by their detail code in run-failure reports (#23568)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work.
> - When an agent run fails, the server sends a run-failure report to
Sentry. The fingerprint of the report sets the Sentry group.
> - Setup failures without a root error code use a fallback fingerprint:
the exception name and the HTTP status.
> - The `conflict()` helper keeps its stable code in `details.code`. The
diagnostics read only `code` and `reasonCode` on the error. They ignore
`details.code`.
> - Thus every coded 409 setup conflict gets the fingerprint
`exception:Error` + `status:409`. Unrelated causes go into one Sentry
group. For example, an unfinished workspace writer and a missing remote
execution environment share one group.
> - This pull request reads a bounded identifier from `details.code`
when the error has no own code.
> - The benefit is one Sentry group for each setup conflict cause. A fix
for one cause no longer shows as a regression of another cause.
## Linked Issues or Issue Description
**What happened**
One Sentry group receives three different setup failures. They are "The
workspace still has an unfinished writer or save operation.", "This
workspace requires a supported remote execution environment." and
"Workspace ownership changed." Each one has a different cause. The first
two have a stable code in `details.code`
(`remote_workspace_writer_pending` and
`remote_workspace_execution_required`). The run-failure diagnostics do
not read that code, so all three get the same fallback fingerprint.
**Expected behavior**
A setup conflict with a stable code gets a fingerprint with that code.
Different causes go into different Sentry groups.
**Steps to reproduce**
1. Make a run fail setup with `conflict(message, { code:
"remote_workspace_writer_pending" })`.
2. Make another run fail setup with `conflict(message, { code:
"remote_workspace_execution_required" })`.
3. Look at the run-failure fingerprints. Both are `[setup_failed,
<adapter>, setup, exception:Error, status:409]`.
**Paperclip version or commit**
master at
|
||
|
|
105b58c96e |
fix(local): allow agent instruction file downloads and load the selected instance's environment in open
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> |