Commit Graph
4803 Commits
Author SHA1 Message Date
7bd424d50f fix(issues): preserve PATCH result when unblock wake fails (#20425)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The issue API commits status changes before it sends some follow-up
notifications.
> - A blocked transition can therefore commit before the control plane
wakes the named unblock owner.
> - A wake failure currently escapes the route and changes the HTTP
response to 500.
> - The client then sees a failure even though the issue is already
blocked.
> - This pull request contains failures from that post-commit
notification path.
> - The benefit is an HTTP result that stays consistent with the
committed issue update.

## Linked Issues or Issue Description

Refs #3824

Related pull request: #19209

The related pull request maps a routine-slot constraint to HTTP 409.
This change covers a different boundary. The target issue update has
already committed when the unblock notification starts. The route must
not replace that successful result with a notification error.

## What Changed

- Catch wake and delivery-marker failures in the unblock notification
helper.
- Log the post-commit notification failure at the route boundary.
- Persist `blockedOwnerNotifiedAt` only after the wake succeeds.
- Keep the marker empty when delivery fails so a later attempt can use
the same idempotency key.
- Add regression tests for wake failures and marker failures.

## Verification

- Before the service change, the two new failure tests rejected with
their injected errors.
- `HOST=127.0.0.1 node_modules/.bin/vitest run
server/src/__tests__/routable-blocked.test.ts` passes 5 tests.
- `HOST=127.0.0.1 node_modules/.bin/vitest run
server/src/__tests__/routable-blocked.test.ts
server/src/__tests__/issue-agent-mutation-ownership-routes.test.ts`
passes 233 tests. This includes HTTP PATCH regressions for wake and
marker-write failures.
- `pnpm --filter @paperclipai/plugin-sdk build` passes.
- `git diff --check` passes.

## Risks

- Risk is low. This change does not add a migration or change the issue
transaction.
- A failed notification no longer changes the PATCH result. The route
emits a warning with the issue and owner context.
- A failed notification keeps `blockedOwnerNotifiedAt` empty. The
existing idempotency key limits duplicate wake delivery during a later
attempt.

> This is a focused bug fix. It does not duplicate planned roadmap work.

## Model Used

- OpenAI Codex with GPT-5, extended reasoning, tool use, and code
execution. The context window size was not exposed to the agent.

## 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 (no
documentation change is needed for this internal error path)
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green (59 checks on `21ad144`: 56
success, 3 skipped, 0 failures; `ci / verify`, `ci / e2e`, and `review`
passed)
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
(`Greptile Review` success on `21ad144`; 0 open review threads)
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Builder <builder@nublo.net>
Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-12-05 03:58:35 -08:00
HisarWebandClaude Opus 5.5 cfabfc8ff4 fix(adapters): bound external adapter loading at startup (#20131)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - External adapters are npm packages that the server imports at
startup through `buildExternalAdapters` in the plugin loader
> - Startup recovery waits for the full external adapter load pass
before the server reports healthy
> - If the import of one package never settles, for example because of a
top-level `await` that never resolves, the pass never returns
> - Then startup recovery stays in the `recovering` phase for the life
of the process, and `/health` keeps reporting `starting`
> - This pull request gives each package a wall-clock load budget and
skips a package that goes over it
> - The benefit is that one broken adapter package cannot keep the whole
server from becoming healthy

## Linked Issues or Issue Description

No issue exists.

**What happened?**
After installing an external adapter package whose import never settled,
the server stayed in `starting` on `/health` and never finished startup
recovery.

**What did you expect?**
The server skips the package with a warning and finishes startup.

**Steps to reproduce**
1. Install an external adapter package whose entry module has a
top-level `await new Promise(() => {})`.
2. Start the server.
3. `/health` keeps reporting `starting`.

**Paperclip version**
`master` at the time of this PR.

## What Changed

- `server/src/adapters/plugin-loader.ts`:
- `DEFAULT_EXTERNAL_ADAPTER_LOAD_TIMEOUT_MS` (10 s) and an
`ExternalAdapterLoadTimeoutError`.
- `loadFromRecord` races the package import against the budget. A
package that goes over the budget is skipped with a warning, and the
pass continues with the next package.
- A late failure of a skipped import is consumed, so it does not become
an unhandled rejection.
- A skipped import that finishes later does not write its UI parser to
the cache, so it cannot replace a parser that was loaded or reloaded in
the meantime.
- `buildExternalAdapters` takes an optional `{ timeoutMs }`. The
cloud-managed early return does not change.
- `server/src/__tests__/external-adapter-load-timeout.test.ts`: a
healthy package still loads, the pass returns when a package import
never resolves, and an import that finishes after the budget leaves no
UI parser in the cache.

## Verification

- `cd server && npx vitest run
src/__tests__/external-adapter-load-timeout.test.ts
src/__tests__/plugin-loader-error-retry.test.ts`: passes.
- `pnpm --filter @paperclipai/server typecheck`: passes.

## Risks

- A package that needs more than 10 s to import is now skipped at
startup. That is very slow for an import; a caller can pass a larger
`timeoutMs`.
- The import that went over the budget keeps running in the background,
because a dynamic import cannot be cancelled. Its result, including its
UI parser, is ignored.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use
(shell, git, test runs). Extended reasoning on.

## Checklist

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

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 03:56:32 -08:00
HisarWebandClaude Opus 5.5 f7c1bf1797 fix(issues): reject a monitor sent with a status that forbids it (#20124)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - An issue can have a monitor in its execution policy, and only some
statuses allow a monitor
> - `PATCH /api/issues/:id` checks this through
`monitorExplicitlyUpdated`: when the body explicitly sets a monitor and
the new status does not allow one, the route returns 422
> - The route counted the monitor as explicit only when it differed from
the stored monitor
> - A body with a status change and the same monitor as stored was
accepted, and the transition dropped the monitor without an error
> - This pull request counts a monitor that is present in the body as an
explicit monitor update, also when the value did not change
> - The benefit is that the client gets a 422 instead of losing the
monitor without notice

## Linked Issues or Issue Description

No issue exists. Related, but a different case: #12149 (monitors on
provider-quota holds).

**What happened?**
A PATCH with `status: "todo"` and an `executionPolicy.monitor` equal to
the stored monitor returned 200, and the issue lost its monitor.

**What did you expect?**
A 422 with "Monitor can only be scheduled ...", as for a monitor that
differs from the stored one.

**Steps to reproduce**
1. Create an issue in `in_review` with a monitor in its execution
policy.
2. Send `PATCH /api/issues/:id` with `status: "todo"` and the same
monitor in `executionPolicy`.
3. The response is 200 and the monitor is gone.

**Paperclip version**
`master` at the time of this PR.

## What Changed

- `server/src/routes/issues.ts`: a new `monitorPresentInBody` is true
when the body has an `executionPolicy` whose normalized form has a
monitor. `monitorExplicitlyUpdated` is now `monitorPresentInBody ||
monitorChanged`.
- `server/src/__tests__/issue-execution-policy-routes.test.ts`: a new
test sends a status change with an unchanged monitor and expects a 422
and no update.

## Verification

- `cd server && npx vitest run
src/__tests__/issue-execution-policy-routes.test.ts`: passes, including
the new test.
- `pnpm --filter @paperclipai/server typecheck`: passes.

## Risks

- A client that sends the full execution policy with a status change to
a status that does not allow a monitor now gets a 422 where it got a 200
before. In that case the monitor was dropped before, so the 422 shows a
real conflict. The client can remove the monitor from the body or send a
status that allows it.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use
(shell, git, test runs). Extended reasoning on.

## Checklist

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

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

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 03:54:43 -08:00
HisarWebandClaude Opus 5.5 f5ed369805 fix(issues): give a reason when a route cancels a run (#20123)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Issue routes can cancel a heartbeat run as a side effect, for
example when a comment supersedes a scheduled retry or when the issue is
set to `cancelled`
> - Other cancel paths pass a reason, an error code and a run event to
`heartbeat.cancelRun`
> - These two route paths called `cancelRun` without a reason, so the
run showed `cancelled` with no error code and no run event that says why
> - An operator who looks at the run, or a recovery path that reads the
error code, cannot tell these cancels apart from other cancels
> - This pull request passes a reason, an error code, an event message
and the issue id to both calls
> - The benefit is that every route-driven cancel explains itself in the
run record and the run events

## Linked Issues or Issue Description

No issue exists.

**What happened?**
A run that was cancelled because a comment superseded its scheduled
retry, or because its issue was set to `cancelled`, had no `error`, no
`errorCode` and no run event with a cancel reason.

**What did you expect?**
The run record and the run events say why the run was cancelled, like
other cancel paths do.

**Steps to reproduce**
1. Let a run fail so that it gets a scheduled retry (`scheduled_retry`).
2. Post a comment on the issue before the retry starts.
3. Open the cancelled retry run. It has no error code and no event that
explains the cancel.
4. Do the same with a running issue that you set to `cancelled`.

**Paperclip version**
`master` at the time of this PR.

## What Changed

- `server/src/routes/issues.ts`:
- The scheduled-retry cancel passes `"Cancelled because a comment
superseded the scheduled retry"`, `errorCode:
"scheduled_retry_superseded"`, an event message and `eventPayload: {
issueId }`. The `expectedStatus: "scheduled_retry"` guard does not
change.
- The cancel on a status change to `cancelled` passes `"Cancelled
because the issue was set to cancelled"`, `errorCode:
"issue_cancelled"`, an event message and `eventPayload: { issueId }`.
- `server/src/__tests__/issue-comment-reopen-routes.test.ts`: six
expectations now check the reason, the error code, the event message and
the event payload.

## Verification

- `cd server && npx vitest run
src/__tests__/issue-comment-reopen-routes.test.ts`: passes.
- `pnpm --filter @paperclipai/server typecheck`: passes.

## Risks

- Low risk. Only the arguments of two existing `cancelRun` calls change.
The cancel decision, the expected status guard and the activity log
entries do not change.
- The two error codes are new values. Code that matches on known cancel
error codes sees them as unknown codes, as before when the code was
empty.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use
(shell, git, test runs). Extended reasoning on.

## Checklist

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

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 03:52:57 -08:00
Alex Castillo González 5fb030f59f fix(heartbeat): keep the newest comments when a wake window is cut (#19969)
Fixes #19198

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - A heartbeat builds a wake payload so the agent can read the latest
issue comments
> - The inline window holds at most 8 comments and 12000 characters of
comment text
> - The builder walked comments from the oldest and stopped when a cap
was reached
> - The newest comment, which the prompt asks the agent to acknowledge,
was left out
> - This pull request keeps the newest comments that fit and names the
older ones that were cut
> - The benefit is that a busy agent answers the comment that woke it

## Linked Issues or Issue Description

Fixes: #19198

No open pull request mentions this issue.

## What Changed

- `buildPaperclipWakePayload` fills the inline comment window from the
newest comment back. The caps stay the same: 8 comments, 4000 characters
per body, and 12000 characters in total. The kept comments still render
oldest first.
- The payload records `commentWindow.cutCount`, `cutCommentIds` (at most
20, oldest first), and `cutAttachmentCount`.
- Attachments keep the newest 20. When nothing is cut, their order stays
oldest first. A count query runs only when more than 20 attachments
match.
- The wake prompt prints one `cut comments` line, and one `cut
attachments` line when needed, after `latest comment id`. A wake that
cuts nothing renders the same prompt as before.
- A generic wake still tells the agent to read the cut comments with
`GET /api/issues/<id>/comments`. A native external-chat turn that
already requires `read_current_wake_comments` and zero other Paperclip
API calls names that reader in the cut line instead. That reader pages
every comment id accepted for the run. The full-thread GET stays out of
that prompt.
- The redaction test that checks an exact comment window now expects the
new fields at zero when nothing is cut.

## Verification

Run this command in `server`:

`pnpm exec vitest run
src/services/heartbeat/run-preparation.wake-window.test.ts --testTimeout
60000`

Before this change, all 7 tests failed. An 11-comment wake listed
comments 1–8 and omitted comment 11. Five comments of 4000 characters
kept the first three and dropped the two newest. After this change, all
7 tests pass. The seventh checks that a native external-chat cut names
`read_current_wake_comments` and does not name a `GET`, while the same
payload without the native reader still names the thread `GET`.

The test fixture now derives its row type from the builder input and
uses the schema-valid `comment` origin. Attachment assertions validate
the array shape before reading ids.

`pnpm exec tsc --noEmit -p .` in `server` reports no errors in the new
test file or the changed source files.

## Risks

A wake that already fits in the caps keeps the same prompt text.

A wake that used to cut now shows the newest comments instead of the
oldest ones. The cut line names the omitted comment ids. A generic wake
tells the agent to read `GET /api/issues/<id>/comments`. A native
external-chat wake tells the agent to read those same ids with
`read_current_wake_comments`.

An attachment list longer than 20 now keeps the newest 20 instead of the
oldest 20.

## Model Used

xAI Grok 4.7, with tool use, prepared the original change and test
evidence. OpenAI GPT-6 (Codex), with repository and shell tools,
corrected the test fixture types. Context window size was not exposed to
the agent.

## 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 `#<number>` /
`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

This change was prepared with the assistance of an AI coding agent.
2026-12-05 03:46:55 -08:00
brendanmatthewjones-cmykandPaperclip f78519ebb8 Clarify unavailable run context for issue writes (#19788)
## Thinking Path

> - Paperclip manages AI agents and their work.
> - The issue API attributes agent writes to a heartbeat run.
> - A valid run with no source issue and an unavailable run are
different denial cases.
> - The old response used one code and could tell an agent to resend a
header that was already present.
> - This pull request gives an unavailable or mismatched run its own
denial code.
> - The response tells the agent to inspect the run and stop affected
writes.
> - The benefit is a clear audit boundary and a useful recovery
instruction.

## Linked Issues or Issue Description

Refs #18450. Related PRs #18743 and #18275 address run context copy and
checkout binding.

**What happened?**

An agent issue write with a supplied run ID can fail when the run row is
absent, in another company, or owned by another agent. The API returned
the same denial as a run without a source issue. The response could tell
the agent to resend a header it already sent.

**Expected behavior**

The API returns a distinct 403 denial for an unavailable or mismatched
run. The response tells the agent to check the run lookup, stop affected
writes, and report the result. A run with no source issue keeps its
separate denial.

**Steps to reproduce**

1. Send an agent issue write with a run ID that has no matching run row
for that agent and company.
2. Observe the denial code and response text before and after this
change.
3. Send a write from a registered run with no source issue and confirm
that it keeps the separate run-context-required code.

**Paperclip version or commit**

Base behavior: `a708a133363a73bd6ad0491cf38dbddfd54c180e`. This PR is
based on a newer `master` commit with unchanged base blobs in the four
affected files.

**Deployment mode**

Agent issue writes in local and self-hosted deployments. No live
installation was tested.

## What Changed

- Add `issue_write_run_context_unavailable` to the shared denial
contract.
- Return that code when the supplied run is absent, belongs to another
company, or belongs to another agent.
- Clarify the separate denial text for a run that has no source issue.
- Add focused shared and server regression tests.

## Verification

- The reviewed four-file patch has SHA256
`d90722aef44d211d57a728e40d435ea4d2b5b15fa9271d9aceab6f254a18e4c7` as a
binary Git diff against its original base.
- Each changed blob in this PR matches the reviewed local commit byte
for byte. The newer base has the same four pre-change blobs.
- `pnpm --filter @paperclipai/shared exec vitest run
src/issue-write-denial.test.ts` passed locally.
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/cross-issue-influence-limit.test.ts` passed locally.
- `pnpm --filter @paperclipai/shared typecheck` passed locally.
- `git diff --check` passed. Node 22.23.1 emitted an engine warning
because the repository requests Node 24.11.0 or newer.
- Full CI and Greptile review are pending. No live runtime verification
was performed.

## Risks

- Clients that branch on denial codes will see a new code for
unavailable or mismatched runs.
- The status remains 403. This change does not grant issue write scope
or alter the cross-issue limit.
- A run lookup may return 403 or 404 for reasons other than missing
registration. The response does not treat that result as proof that the
run is absent.
- Rollback: revert this commit. No database migration or configuration
change is required.

## Model Used

- OpenAI GPT-6 Codex assisted with source acceptance and PR preparation.
The exact serving model ID and context window were not exposed in this
run. Reasoning, shell, and GitHub tools were used.
- The reviewed source candidate was AI assisted. Its original model ID
was not recorded with the review evidence.

## Checklist

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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-12-05 03:45:03 -08:00
Kostyantyn KryokaandClaude Opus 5.5 eb7546d913 fix(wake-queue): do not queue a second run for a new assignee that already has one (#19437)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The wake queue lets one run hold a task, and other wakes for the
task wait as `deferred_issue_execution`
> - #19354 lets the release of a run that was stopped for a reassignment
promote the new assignee's waiting wake
> - Before the drain, the release looks for a live successor run, but
only for the stopped run's agent
> - The new assignee can already have a queued run for the task, because
enqueue sets `executionRunId` only at dispatch
> - Then the release promotes another wake and queues a second run for
the same agent and task
> - This pull request adds the new assignee to that successor check,
only for a handoff release
> - The benefit is that a reassigned task gets one run for its new
owner, not two

## Linked Issues or Issue Description

Follow-up to #19354. Supersedes the duplicate-run part of #19032.

- Greptile found this case on #19032 (P1, "New owner gets duplicate
runs"). #19354 merged a general version of the #19032 handoff, so #19032
is closed as superseded. This pull request keeps only the duplicate-run
fix, on the `handoffAssigneeAgentId` path from #19354.
- #16019 also changes this successor check, for a stale queued run of
the releasing agent. The two changes touch the same query. #16019 checks
ownership for the releasing agent, so with this change it must check the
agent of each queued run. Otherwise the new assignee's queued run stops
counting, and the new `queued` test case fails. I will rebase after
whichever merges first.

**What happened?**

Agent A runs a task, and agent B has a deferred mention wake for it. The
task is reassigned to B. A's run is already `cancelled` by the Stop, but
its release has not run yet. So the assignment wake for B finds no live
lock holder and queues a run for B. It does not adopt the mention wake.
If B is busy, the run stays queued, and `executionRunId` stays empty.
Then the release of A's run takes the #19354 handoff path. The successor
check looks only for runs of A, so the drain promotes B's mention wake
into a second run. Both runs can do the same work.

**Expected behavior**

When the new assignee already has a `queued`, `running` or
`scheduled_retry` run for the task, the release promotes nothing. The
deferred wake stays for that run. This is the same rule that the release
already uses for a successor of the stopped agent.

**Steps to reproduce**

1. Seed a native run of agent A that holds the task lock, cancelled with
an acknowledged reassignment Stop (`reassignmentStopRequested`).
2. Assign the task to agent B. Seed a queued run of B for the task and a
deferred `issue_comment_mentioned` wake of B.
3. Release A's run.
4. The release returns `promoted` and queues a second run for B.

The new embedded-PostgreSQL test does these steps.

**Paperclip version or commit**

master 4d49a3128.

## What Changed

- `wake-queue/adapters/postgres.ts` (`withIssueExecutionLock`): when
`handoffAssigneeAgentId` is set, the successor check before the drain
looks for live runs of the stopped run's agent and of the new assignee.
For all other releases, the check does not change.
- No documentation change. The handoff in `doc/execution-semantics.md`
still applies. A live run of the new assignee now counts as a successor,
as a live run of the stopped agent already does.

## Verification

- New embedded-PostgreSQL test in `adapters/postgres.test.ts`, for a
`queued`, `running` and `scheduled_retry` run of the new assignee. It
does the steps above. It expects `released` with no effects, only the
seeded run for the new assignee, and the mention wake still
`deferred_issue_execution`.
- Without the fix (`postgres.ts` as on master), all 3 cases fail: the
release returns `promoted` with a `run_queued` effect for the new
assignee. With the fix, all 3 pass.
- The #19354 handoff test ("runs the new assignee's parked wake when a
reassignment committed while the native Stop was settling") still
passes.
- `vitest run src/modules/wake-queue`: 10 files, 300 tests pass.
- The test files that #19354 changed
(`issue-agent-mutation-ownership-routes`, `heartbeat/run-state`,
`wake-queue/adapters/postgres`): 331 tests pass.
- `pnpm --filter @paperclipai/server typecheck` passes. `node
scripts/check-module-boundaries.mjs` passes. `git diff --check` is
clean.

## Risks

- Low risk. The change applies only to a handoff release
(`handoffAssigneeAgentId` is set). Other releases do not change. The
stranded-queue sweep already checks the live runs of all agents.
- In this case the new assignee's deferred wake now waits for the
release of its live run, not for this release. That is the current
behavior for a successor of the stopped agent.

> 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), 1M-token context window, adaptive
thinking
- Provider: Anthropic. Harness: Claude Code CLI, with tool use (shell,
file edits), code execution and embedded PostgreSQL tests

## Checklist

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

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

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 03:43:16 -08:00
Jegor1 1afac2fd30 fix(recovery): do not abort startup recovery on one bad blocking pair (#19193)
<!-- Write all pull request text in Simplified Technical English
(ASD-STE100): short sentences, one instruction per sentence, simple
approved vocabulary, and the active voice. -->

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - At startup, the recovery service reconciles the active recovery
actions
> - When a source issue has healthy child issues, recovery adds the
children to the blocked-by list of the source issue
> - If a child already blocks its source issue, this creates a cycle and
`issuesSvc.update` throws an error
> - The error stops the whole sweep, so recovery does not reach any
later issue
> - This pull request catches the error for one source issue, logs a
warning, and goes on with the next action
> - The benefit is that one bad pair of issues no longer stops startup
recovery for all other issues

## Linked Issues or Issue Description

Refs #11853

**What happened?**

During startup recovery, one bad pair of a source issue and a child
blocker created a cycle. The update threw an error. The error stopped
the recovery sweep for all remaining issues.

**What did you expect to happen?**

One bad pair must not stop startup recovery for every issue. The sweep
must skip the bad pair and continue.

## What Changed

- `reconcileActiveRecoveryActions` wraps the `issuesSvc.update` call
that blocks a source issue on its healthy children in a `try`/`catch`.
- On failure, it logs a warning and counts the action as skipped. It
also reports a retry time 5 minutes later, through
`blockerStallRetryAt`, so the recovery worker schedules another pass.
The sweep continues with the next action.
- A new test seeds two source issues with a healthy child each. The
first source issue also blocks its own child, so blocking it on that
child creates a cycle. The test checks that the first action stays
active, is counted as skipped, and sets a retry time. It also checks
that the second source issue becomes blocked and its action resolves.

## Verification

- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/startup-recovery-update-failure.test.ts` (embedded
PostgreSQL, 2 tests pass).
- `pnpm --filter @paperclipai/server typecheck` passes.

## Risks

- The `catch` handles any error from `issuesSvc.update`. If the cause is
a real data or permission problem, the action is skipped and the warning
log is the only signal.
- A skipped action stays active. The retry time makes the worker try it
again after 5 minutes. If the cycle still exists, the warning repeats
every 5 minutes.

> 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

- Provider and model: Anthropic Claude Opus 5.5 (model ID
`claude-opus-5-5`)
- Context window: 1M tokens (128K maximum output)
- Capabilities: adaptive thinking, tool use, and code execution, used
through 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
- [ ] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
2026-12-05 03:41:22 -08:00
Chaitanya Meesalaandcommitperclip[bot] 7612e79215 fix(heartbeat): tell a non-owner addressee to answer the card, not take the task (#18907)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Agents ask each other questions with issue thread interactions
(cards). A card can name an `addresseeAgentId`.
> - When an agent creates a card for another agent, Paperclip wakes the
addressee with the `interaction_pending` reason. The issue still belongs
to the asker.
> - The addressee's wake prompt says "Use this wake to continue the
task". The task markdown ends with "Use this task context as the current
assignment."
> - The addressee follows the normal heartbeat procedure and checks the
issue out. The checkout returns `409` because the asker owns the issue.
The addressee stops, the card stays pending, and the asker waits.
> - This pull request gives the addressee a correct instruction: answer
the named card through its answer route, and do not check out, change
status or continue the task.
> - The benefit is that agent-to-agent questions get answers. This
matters as soon as the run-dispatch fixes for the cancelled addressee
wake (#15991, #16914, #17643) land.

## Linked Issues or Issue Description

Fixes #16563

Refs #17643, #15991, #16914 (run-dispatch fixes that stop the addressee
wake from being cancelled; this pull request fixes the instruction that
the wake then gets). Refs #16409, #11932, #13518.

## What Changed

- `buildPaperclipWakePayload` adds an `addressedInteraction` block when
all of these are true: the wake reason is `interaction_pending`; the
interaction is pending, in the same company and issue, and addressed to
the woken agent; and the woken agent does not own the issue. The block
holds the interaction id, kind, a prompt excerpt (1,000 characters
maximum), the read path and the answer paths for the kind (`respond`,
`accept`/`reject` or `verdicts`). The server reads the interaction from
the database; it does not trust the run snapshot.
- `renderPaperclipWakePrompt` renders a "Question addressed to you"
section for that block, on fresh and resumed sessions. The section names
the card and its answer route, and forbids checkout, status changes,
progress comments and task work. The generic "continue the task" line
changes to "answer the question card addressed to you".
- The prompt renderer accepts the block only when every answer path is
an interaction path of the same issue and card. Other values are
ignored.
- For that wake, `buildPaperclipTaskMarkdown` opens with an "Addressed
question directive", keeps the issue, description and plan as reference
only, and omits every owner-work directive (task question guidance,
clarification, quality review, title, chat, ask, planning and skill test
mode, accepted and rejected plan). It ends with "This task belongs to
another agent. Use this context only to answer the question card ...
addressed to you; it is not your assignment." for that wake, in place of
"Use this task context as the current assignment."
- Other wakes do not change. The owner of the issue, a resolved card, a
card addressed to another agent and a card with no addressee all get the
existing prompt.

## Verification

- New PostgreSQL integration test
`server/src/__tests__/heartbeat-addressed-interaction-wake.test.ts` (7
tests). It covers a pending question to a non-owner, a confirmation card
(accept and reject paths), the wake payload, and the cases that must add
nothing: an answered card, a card addressed to another agent, a card
with no addressee, an addressee that owns the issue, another wake reason
and another company.
- New tests in `packages/adapter-utils/src/server-utils.test.ts` (fresh
and resumed prompts, the ordinary prompt, and tampered answer paths) and
in `server/src/services/heartbeat/task-markdown.test.ts` (the addressee
gets no owner-work directive in planning, accepted plan, rejected plan,
ask, skill test, chat and native-runner review combinations; the owner
still does).
- With the source changes removed, all new tests fail. With them, they
pass.
- Regression runs: `packages/adapter-utils/src/server-utils.test.ts`
(139 passed); in `server/`, `heartbeat-task-context`, `run-preparation`,
`run-preparation.review-path`, `task-markdown`,
`heartbeat-context-summary`, `heartbeat-agent-session-message`,
`heartbeat-reviewed-chat-binding.integration`, `agent-conversations`,
`native-runtime/current-wake-comments` and the new integration test (10
files, 173 passed).
- Typecheck: `packages/adapter-utils` has no errors. In `server/`, `tsc
--noEmit` reports the same 250 errors as unchanged `master` in my local
environment, from workspace packages that I could not build locally
(`@paperclipai/paperclip-runner`). None is in a changed file. CI runs
the full typecheck.
- To check by hand: assign an issue to agent A. As A, create an
`ask_user_questions` interaction with `addresseeAgentId` set to agent B.
With a run-dispatch fix from the issues above applied, read B's rendered
prompt. It names the card and the `respond` route and does not tell B to
continue the task.

## Risks

- Low risk. The change adds one database read per `interaction_pending`
wake, by primary key, and it is limited to the company and issue of the
wake.
- Without a run-dispatch fix, the addressee wake is still cancelled
before it runs, so this change has no visible effect until one of
#15991, #16914 or #17643 lands. The two changes do not touch the same
code.
- An adapter that builds its own prompt without
`renderPaperclipWakePrompt` does not get the new section. The payload
carries the block for those adapters.

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

## Model Used

- Anthropic Claude Opus 5.5 (`claude-opus-5-5`), through the OpenCode
agent harness with tool use and code execution. The model wrote the
change, the tests and this description. The account owner requested the
change and reviewed the result.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes (no
documentation describes this prompt text)
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green (53 passed; the external Snyk
status has not reported)
- [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: commitperclip[bot] <284812584+commitperclip[bot]@users.noreply.github.com>
2026-12-05 03:18:32 -08:00
Paul BéglinandPaperclip 8f6cf8b0d7 fix(auth): ignore comment-only Codex project settings (#18559)
## Thinking Path

> - Paperclip lets agents use managed AI connections.
> - The server checks project files for conflicting authentication
settings.
> - Codex stores project settings in TOML.
> - A full-line TOML comment can contain an example authentication
setting.
> - The current text check rejects that comment as an active override.
> - This pull request excludes full comment lines in local and remote
checks.
> - Active overrides and file-read errors still block execution.

## Linked Issues or Issue Description

**What happened?**

A project or scanned ancestor `.codex/config.toml` containing only `#
model_provider = "example"` can cause `ai_connection_incompatible`. The
worker is rejected before provider execution.

**Expected behavior**

Ignore full TOML comment lines, including indented comments. Continue to
reject active authentication and provider overrides.

**Steps to reproduce**

1. Create a disposable project and a `.codex/config.toml` in its scanned
ancestry.
2. Add `# model_provider = "example"` without an active provider
override.
3. Call the managed OpenAI project-auth guard for that project.
4. The original guard rejects the comment. The new tests reproduce both
local and shell-backed remote checks.

**Paperclip version or commit**

Originally checked against upstream
`e1224783685405eb7d987ece2446962920ee0cf5`. Before publication, rebased
cleanly onto `c0550e7010b5b733b745f60433788db3e6fd2e2e`. The two
intervening commits do not change either fix's source or regression
files.

**Deployment mode**

Source checkout on macOS arm64. Node 24.21.0 and pnpm 9.15.4. Disposable
filesystem fixtures and a real local POSIX shell stand in for remote
transport. No provider call or live remote host was used.

Refs #17421. That open PR changes the scanned project boundary and probe
preparation. This patch handles full-line comments inside the existing
scan. The shared guard will need reconciliation if that PR lands first.
A public search found no separate comment-filtering repair.

## What Changed

- Exclude full comment lines before applying the existing local TOML
conflict pattern.
- Use a POSIX awk check for remote Codex TOML, preserving conflict and
read-error exit codes.
- Leave Claude JSON checking and explicit argument rejection in place.
- Add 23 filesystem and shell regression cases. Cover LF/CRLF, active
overrides, ancestor checks, read failures, argument rejection and Claude
settings. Skip POSIX-only checks on Windows and permission-denial checks
when running as root.

## Verification

- Publication recheck on the rebased branch: auth filesystem/shell and
Codex environment checks passed, **31 tests with one existing skip**.
Full workspace build/typecheck and broader-suite results below were
recorded before that rebase, at the original base. They were not rerun
after the two intervening upstream changes.

- Focused filesystem/shell and existing Codex environment tests: **31
passed, one existing Windows-only skip**.
- Complete connection, routing and hiring test files: **263 passed**.
Combined focused evidence: **294 passed and one conditional skip in five
files**.

```sh
pnpm exec vitest run --project @paperclipai/server server/src/__tests__/ai-connection-project-auth.test.ts server/src/__tests__/codex-local-adapter-environment.test.ts --maxWorkers=1
pnpm exec vitest run --project @paperclipai/server server/src/__tests__/ai-connections.test.ts server/src/__tests__/ai-connection-router.test.ts server/src/__tests__/agent-hire-ai-connections.test.ts --maxWorkers=1
```

- Full workspace typecheck passed: `pnpm -r --workspace-concurrency=1
typecheck`.
- Full workspace build passed: `pnpm build`.
- Module-boundary, runtime Git-push guard and diff-whitespace checks
passed.
- Initial pre-fix regressions: 4 failed and 19 passed cases. All four
failures were comment-only settings. The original failures were
retained.
- **Broader run:** all six chat shards and 22 of 24 general server
shards executed, selecting 1,229 general files (including
platform-conditional skips). Results: **27,547 passed, one failed**,
plus 180 conditional skips outside chat. Completed chat evidence was
reused unchanged when switching from the serial path to the standard
24-shard modes. The inventory check verified the full planned cover;
this partial execution is not a complete pass. The final two general
shards, five native suites, 20 workspace projects and 164 serialized
suites did not run after the failure.
- The failed Git-scan load case observed 126 joins instead of 498. The
identical failure reproduced in the focused case on unchanged upstream
at the stated base. Refs #17536 for the existing host-dependent fixture
repair. No load-test assertion was changed here.
- An initial incomplete dependency installation omitted the embedded
PostgreSQL library symlinks. Running its existing install hook restored
PostgreSQL 18.1 startup and the focused integration tests. This also
cleared the earlier misleading chat-discovery failure. Original failure
logs were retained.
- One parallel server group left a Node child beyond 30 seconds after a
successful test exit. It was stopped. The identical 59 files later
passed all 1,238 cases and drained normally on unchanged upstream. The
original orphan remains unattributed; a clean overall lifecycle run is
not claimed.
- Remote tests run a real POSIX shell locally with transport replaced.
No real remote host, live provider turn or installed production service
was qualified. Upstream CI, Greptile and merge readiness remain pending.

## Risks

This is a limited correction to the existing text guard, not a TOML
parser rewrite. It ignores only full comment lines. It does not change
project scanning boundaries or credentials. Remote checks require POSIX
awk and retain bounded subprocess timeouts. Windows was not exercised.
PR #17421 touches the same guard and can require rebasing.

## Model Used

OpenAI `gpt-6.1-sol` through Codex. Saved session metadata identifies
medium reasoning for the upstream adaptation and verification.
Capabilities used: source inspection, shell tools, patch editing,
regression testing, and build verification. The session-reported context
window is 475,000 tokens. This is the recorded model ID; no unrecorded
build version or nominal model maximum is asserted.

The local-tests, CI and Greptile completion boxes remain unchecked
because a complete repository pass is not claimed.

## 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

Additional local test limitation: final cleanup found a detached
sibling-directory HTTP fixture from `workspace-runtime.test.ts`. Its
ownership was verified from its temporary-root cwd and exact fixture
command; it was stopped individually. This separate observation remains
outside the proposed changes.

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-12-05 03:12:04 -08:00
Josh CoxandReview 0110436ab6 fix(server): keep an existing grant scope when re-ensuring without one (#18116)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Permission grants can carry a scope that narrows what the grant
allows
> - One function re-ensures a grant: it creates the grant when missing
and updates it when present
> - The scope parameter defaults to null, and the update path writes it
unconditionally
> - Most callers omit scope because they only mean to ensure the grant
is enabled
> - Each such call therefore clears a previously stored scope, including
on every server boot through the built-in-agent grant pass
> - This pull request makes scope optional: an omitted scope leaves the
stored scope alone
> - The benefit is that re-ensuring a grant no longer silently widens or
narrows it

## Linked Issues or Issue Description

Fixes #17992

## What Changed

- `server/src/services/access.ts`: `setPrincipalPermission` now takes
`scope?` instead of defaulting it to null. The update path writes scope
only when the caller provided one. The insert path still writes null for
a new grant without a scope.
- `server/src/__tests__/access-service.test.ts`: new test grants a
scope, re-ensures without one and expects the scope kept, then clears
with an explicit null and expects null.

## Verification

- The access-service suite loads and registers the new test, but the
embedded-Postgres suite self-skips in this sandbox because Postgres
refuses to run as root. The new test therefore has not run locally. CI
is the arbiter for it.
- Caller audit, done by reading every call site: the six scope-omitting
callers (built-in-agent defaults, both agent-copy paths, both invitation
acceptances, the permissions tab, and the default task-assign grant) all
intend "ensure enabled" and gain the keep behavior. The two
scope-passing callers are unchanged: the portability copy passes the
source scope or an explicit null, and the bulk grant setter passes an
explicit null, so both keep their clear semantics.

## Risks

- Low risk. The only behavior change is for update calls that omit
scope, which previously reset it to null. No caller was found that
relies on that reset. A caller that wants to clear a scope still can, by
passing null explicitly.

## Model Used

Meta Muse Spark 1.3, 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)
- [ ] 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
- [ ] 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

Signed-off-by: Josh Cox <joshuacox@users.noreply.github.com>
Co-authored-by: Review <review@local>
2026-12-05 02:49:25 -08:00
brianCodesandClaude Opus 5.5 0da786fdc3 fix(issues): clear the compact issue-list cache when an issue changes (#17828)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The board reads task lists through `GET
/api/companies/:companyId/issues?view=compact`
> - The server keeps compact list responses in a short in-memory cache
(`ISSUE_LIST_SERVER_CACHE_TTL_MS = 2000`), keyed by actor and query, to
absorb request storms (#9190)
> - The board refetches its issue lists when it receives an
`activity.logged` live event for an issue
> - But a create, update or delete does not clear the cache, so the
refetch gets the cached list from before the change. The board shows the
old value for up to two seconds, and a quick edit seems to snap back
> - This pull request clears the cached compact lists of a company when
the server publishes an `activity.logged` event for an issue in that
company
> - The benefit is that a list fetched after a change shows the change,
and the cache still absorbs request storms between changes

## Linked Issues or Issue Description

**What happened?**
I changed the title of a task, and the board refetched the task list
immediately. The response had the old title and the header
`x-paperclip-request-cache: hit`. The list showed the old title until
the board fetched the list again more than two seconds later. The same
thing happens for other changes that the compact list shows, for example
status, priority and assignee.

**Expected behavior**
A compact list request that the server receives after a change returns
the changed values. The cache can answer repeated requests only while no
issue in the company changes.

**Steps to reproduce**
1. Start Paperclip with a company and one task.
2. Send `GET /api/companies/<companyId>/issues?view=compact`.
3. Within two seconds, send `PATCH /api/issues/<issueId>` with
`{"title":"After"}`.
4. Within two seconds of step 2, send the request from step 2 again.
5. Before this change, the response has the old title and
`x-paperclip-request-cache: hit`.

**Paperclip version or commit**
`master` at 835966dec8.

**Deployment mode**
Local development server (`pnpm dev`) with embedded PostgreSQL. The
cache is in-process, so the deployment mode does not change the
behavior.

Refs #9190, which added the cache. I did not find an open issue or pull
request for this problem.

## What Changed

- `server/src/routes/issues.ts`: each cache entry and each in-flight
list computation now records its company.
- `server/src/routes/issues.ts`: the issue routes subscribe once,
through `subscribeAllCompanyLiveEvents`, to company live events. On an
`activity.logged` event with `entityType: "issue"`, the server removes
the cached compact lists of that company. It also removes the in-flight
computations of that company from the coalescing map, so a new request
does not join a computation that started before the change.
- `server/src/routes/issues.ts`: a computation that was in flight during
the change does not store its result in the cache.
- `server/src/__tests__/issue-list-assignee-filter-routes.test.ts`: two
embedded PostgreSQL route tests. The first test lists, sends `PATCH
/api/issues/:id`, and lists again within the cache lifetime. It expects
the new values and a cache `miss`. The second test holds a list
computation after it reads the old title. It sends the `PATCH`, and
expects that a fresh request does not coalesce with the old computation
and caches the new title. Then it releases the old computation, which
returns the old title, and expects that the next request is a cache
`hit` with the new title. This checks that a stale in-flight result does
not replace the fresh cache entry. To hold the computation after its
read, the test file wraps `issueService().list` with `vi.mock`.

I put the invalidation on the `activity.logged` event because it is the
existing signal that an issue changed. Mutations must log activity. Most
routes that use a transaction publish the event after the commit. The
board already uses this event to refetch its issue lists. One
subscription covers every route and service that changes an issue:
create, `PATCH`, delete, checkout and release, comments, read marks, and
changes that heartbeat runs make. A call in each route would miss some
of these paths. The change stays in `routes/issues.ts`, which owns the
cache, and it adds no shared contract. The invalidation is event-driven,
so it adds no polling.

## Verification

- Run `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/issue-list-assignee-filter-routes.test.ts`. All 39 tests
pass.
- Without the change in `issues.ts`, the first new test fails. It gets
`hit` instead of `miss`.
- With only the `!inflightEntry.invalidated` guard removed, the second
new test fails. The old computation writes its stale result over the
fresh cache entry, so the next request gets `Before` instead of `After`.
The other 38 tests pass.
- The existing cache tests still pass: a repeated request without a
change still gets `hit`, simultaneous requests still coalesce, cache
keys stay separate per user, and the cache stays bounded.
- Run `pnpm --filter @paperclipai/server exec tsc --noEmit`. It passes.
- The design assumes that each change to an issue publishes
`activity.logged` before the next list request. The first new test
checks this with a real `PATCH` on embedded PostgreSQL, not a mock.
- Locally, I ran only this test file and `tsc --noEmit`, on Windows. I
did not run `pnpm -r typecheck`, `pnpm test:run` or `pnpm build`, and I
left them to CI. On Windows, the `typecheck` script of the server stops
in `prepare:runner-vendor` with `ERR_UNSUPPORTED_ESM_URL_SCHEME`, with
or without this change. A wider local run did not finish in 50 minutes.
- That wider run showed failures in `server-startup-feedback-export`,
`external-chat-wait.integration` and `workspace-recovery`. These files
fail in the same way without this change. `muse-control` failed once and
then passed except for one test, which also fails without this change.
These files do not test the issue-list cache.
- No documentation describes this cache, so this change does not update
documentation.
- To check by hand, follow the steps to reproduce above. After this
change, the response in step 4 has the new title and
`x-paperclip-request-cache: miss`.

## Risks

- Low risk. The change affects only the compact list TTL cache and
in-flight coalescing. The `index` and `rows` views do not use the TTL
cache, but they get the coalescing change.
- The cache absorbs fewer requests while a company has many issue
changes, because each change clears the cached lists of that company.
Each change already makes the board refetch its lists, so the extra work
is one computation per list after each change. Coalescing between
changes is the same as before.
- If many requests from one client are in flight, the server can answer
with a stale cache entry. After a change, that stale entry is gone, so
the server answers with its existing retry response instead of old data.
- The invalidation is per process. A deployment with more than one
server process can still serve a list that is up to two seconds old from
another process. This is the same as before this change.
- Each issue change scans the cache once to find the entries of the
company. The cache holds at most 256 entries
(`ISSUE_LIST_SERVER_CACHE_MAX_ENTRIES`), so this cost stays small.
- Some services log issue activity inside a transaction and publish the
event before the commit. A list request in that short window can cache
the old values. The board's own refetch has the same race.
- Changes that do not log issue activity, for example a label rename, do
not clear the cache. The board does not refetch issue lists for these
changes either.

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

## Model Used

- Anthropic Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with
tool use and code execution. It wrote the change, the tests and this
description. A human reviews the change before submission.

## Checklist

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

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 02:39:21 -08:00
Andrii VasylievandClaude d61877761a fix(docker): install lsof for listener ownership checks (#17770)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Paperclip can start and supervise local runtime services for a
workspace
> - `local-service-supervisor` finds the process that listens on a
service port with `lsof -nP -iTCP:<port> -sTCP:LISTEN -t`
> - The Docker image is based on `node:24-trixie-slim`, which does not
include `lsof`, and the Dockerfile does not install it
> - In the container, the lookup always fails and
`readLocalServicePortOwner` returns `null`
> - It also runs `ps -o command= -p <pid>` and `ps -o pgid= -p <pid>`
for its command and process-group checks, and the slim image has no `ps`
either
> - This pull request installs `lsof` and `procps` in the base stage of
the image
> - The benefit is that port-owner adoption, command matching and stop
checks have process evidence in Docker deployments too

## Linked Issues or Issue Description

No public issue exists for this. I searched open and closed issues and
pull requests for `lsof`, "listener" and changes to `Dockerfile`. I
found no related change.

**What happened?**

In the Docker image, `readLocalServicePortOwner` always returns `null`,
because `lsof` is not installed and the call fails with `ENOENT`, which
the function catches. Callers then act without listener evidence:
- `findLocalServiceRegistryRecordByRuntimeServiceId` removes a registry
record whose original PID is gone, even when another process of the
service still listens on the port.
- `adoptLocalServiceFromPortOwner` cannot adopt a running listener.
- The stop path (`targetIsGone`) treats the port as free when the target
PID is gone, even if a child process still listens on it.

The same applies to `ps`, which comes from `procps` on Debian:
`isLikelyMatchingCommand` catches the `ENOENT` and treats any live PID
as the recorded service, and `readLocalServiceProcessGroupId` returns
`null`, so `isLocalServiceProcessOwnedBy` cannot confirm group
ownership.

**Expected behavior**

The image contains the tools that the server calls at runtime. The
port-owner lookup returns the listening PID in Docker as it does on a
host with `lsof`.

**Steps to reproduce**

1. Run `docker run --rm node:24-trixie-slim sh -c 'command -v lsof ||
echo missing; command -v ps || echo missing'`. Both print `missing`.
2. The Dockerfile `base` stage installs `ca-certificates gosu curl gh
git wget ripgrep python3 tini` and no `lsof`. The `production` stage
starts from `base`.
3. In a container with `lsof` installed, start a listener on a port and
run `lsof -nP -iTCP:<port> -sTCP:LISTEN -t`. It prints the listener PID.

**Paperclip version or commit**

Seen on v2026.1023.0. The patch base is current `master` (`a52f622be8`).

**Deployment mode**

Docker image.

## What Changed

- Add `lsof` and `procps` to the `apt-get install` list in the `base`
stage of `Dockerfile`. The `production` stage starts from `base`.
- `container-init-reaping.test.ts` asserts that the `base` stage
installs both packages.

`procps` was suggested in review.

## Verification

- `node:24-trixie-slim` has no `lsof`. After `apt-get install lsof` in
that image, `lsof -nP -iTCP:43117 -sTCP:LISTEN -t` printed the PID of a
Node listener on port 43117.
- In `node:24-trixie-slim` with every package that the current `master`
Dockerfile installs (`base` and `production` stage apt lists), `ps` and
`lsof` are both missing and `procps` is not installed. After adding
`lsof procps`, `ps -o command= -p <pid>` and `ps -o pgid= -p <pid>` work
as the unprivileged `node` user.
- `npx vitest run src/__tests__/container-init-reaping.test.ts` in
`server`: 16 tests passed. With `procps` removed from the Dockerfile,
the new `procps` case fails.
- I did not build the full image locally, because the build includes the
Rust runner stages. The CI Docker jobs cover the build.

## Risks

- Low risk. Two small Debian packages in the base stage. The image grows
by the size of `lsof`, `procps` and their dependencies.

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

## Model Used

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

## Checklist

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

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

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-12-05 02:25:43 -08:00
20ffa6b0a3 fix(prompt): reference the exact plan revision on resumed turns (#17769)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Each heartbeat run gives the agent task Markdown, and a task can
have a revisioned plan document
> - A resumed session gets a compact variant of that Markdown, because
the session already received the assignment brief
> - The compact variant already leaves out the issue description, but it
still repeats the full plan body on every resumed wake
> - A long plan therefore grows every resumed prompt, although the
session already has the plan
> - This pull request keeps the exact plan document and revision pointer
in the compact variant and drops the body
> - The benefit is smaller resumed prompts without a weaker plan
contract: the agent reads that exact revision when it does not have it

## Linked Issues or Issue Description

No public issue exists for this. I searched open and closed issues and
pull requests for the task plan in resumed prompts and for changes to
`server/src/services/heartbeat/task-markdown.ts` and `task-context.ts`.
Related prompt-size work: #17584 (skip static notes on resumed ACPX
sessions), #17342 and #16645 (bound the execution continuation).

**What existing behavior does this improve?**

`buildPaperclipTaskMarkdown` with `includeDescription: false` builds the
compact task Markdown for resumed sessions. It still writes the full
`Task plan document …` body in a fenced block on every resumed wake.

**Subsystem affected**

Heartbeat task context
(`server/src/services/heartbeat/task-markdown.ts`,
`server/src/services/heartbeat/task-context.ts`).

**Current behavior**

Every resumed wake repeats the full plan body, even when the plan did
not change and the session already holds it.

**Proposed behavior**

The compact variants keep the line `Task plan document <id>, revision
<n> (<revisionId>):` and the work-mode rule. In place of the body, they
tell the agent to read that exact revision through `GET
/api/issues/{id}/documents/plan` (or its `/revisions` list) when the
session does not have it, and not to use a later draft or infer
approval. The full variants do not change.

**Reason and benefit**

Resumed prompts stay smaller. A changed plan still shows a new revision
id, so the agent can see that it must read the new revision.

## What Changed

- `buildPaperclipTaskMarkdown` accepts `includePlanBody`. When it is
`false`, the plan section keeps the document and revision pointer and
replaces the fenced body with the read instruction.
- `prepareHeartbeatTaskContext` passes `includePlanBody: false` only for
`paperclipTaskMarkdownCompact` and
`paperclipTaskMarkdownAssignmentCompact`. Fresh attempts and
assignment-shaped wakes use the full variants and still get the body.
- A quarantined low-trust plan seen by a higher-trust agent keeps its
withheld-body notice in the compact variants instead of the read
instruction, because the issue document routes return the stored body
without the quarantine filter.
- Add unit tests for the compact plan section in all work modes, for a
changed revision and for rejected-plan rules.
- Add a database-backed test that runs a real heartbeat with a plan
document and checks all four task Markdown variants. Another one checks
all four variants for a quarantined plan.

## Verification

On the head rebased onto `master` `7e8901aa60` (the later rebase onto
`7cd5558e41` did not change any file this PR touches):

- `npx vitest run src/__tests__/heartbeat-context-summary.test.ts
src/__tests__/heartbeat-task-context.test.ts` in `server`: 2 files, 70
tests passed (with embedded PostgreSQL).
- Without the source change, the two new plan tests fail (checked before
the rebase). Without the quarantine change, the quarantined-plan test
fails.
- `pnpm --filter @paperclipai/server typecheck` (all layers, including
the test trees): no errors. `pnpm check:tokens` and `pnpm
check:module-boundaries` pass.

## Risks

- A resumed session that lost the plan from its context must call the
API to read it. The prompt names the exact endpoint and revision.
- Approval and work-mode rules do not change. The rejected-plan text
stays in the compact variant.

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

## Model Used

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

## Checklist

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

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

---------

Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: a-vasyliev <1255946+a-vasyliev@users.noreply.github.com>
2026-12-05 02:24:03 -08:00
Rick Glenn bfbe2e3a7f fix(issues): refuse execution policy stage removal by non-board actors (#17503)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Issues carry an execution policy with review and approval stages
> - `PATCH /api/issues/:id` replaces the policy, and the assigned agent
can send `{ stages: [] }` or `null`
> - The stages go away, a pending review is dissolved, and the issue can
then go `done` unreviewed
> - #16431 locks a policy that has a user participant. It does not cover
a policy with only agent stages.
> - This pull request refuses stage removal by non-board actors for any
staged policy
> - The benefit is that an agent cannot remove the gate that exists to
check its work

## Linked Issues or Issue Description

Fixes #17301
Refs #16431

This change extends the #16431 lock to the agent-only gap that #16431
does not cover. Both PRs add a check at the same place in the PATCH
handler. The PR that merges second needs a small rebase.

## What Changed

- `server/src/routes/issues.ts`: a non-board PATCH that sends
`executionPolicy` gets `403 { code: "execution_stage_removal_locked" }`
if a stage id in the current policy is not in the new policy. This
includes `null` and `{ stages: [] }`. Board actors are not affected.
- `server/src/__tests__/issue-execution-policy-routes.test.ts`: four
tests. An agent that removes an agent-only stage is refused. An agent
that sets the policy to `null` is refused. A board user can remove
stages. An agent can change only the monitor when it sends the stages
again.

## Verification

- `pnpm exec vitest run
server/src/__tests__/issue-execution-policy-routes.test.ts`: 41 pass (37
existing and 4 new).
- Without the route change, the two refusal tests fail.
- The 13 route test files that send agent PATCHes with
`executionPolicy`: 500 pass.
- `tsc --noEmit` in `server` reports no errors in the changed files.

## Risks

- An agent that sends only `{ monitor }` on an issue with stages now
gets 403. Before this change, that request removed the stages without a
warning. The 403 message tells the agent to send every current stage
with its id together with the monitor.
- The check compares stage ids only. An agent can still change the
participants of a stage and keep its id. #16431 covers this for user
participants.

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

## Model Used

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

## Checklist

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

> - Paperclip is the open source app people use to manage AI agents for
work
> - The tool gateway routes in server/src/routes/tool-gateway.ts serve
the board API and the public MCP protocol at POST
/mcp/gateways/:gatewayPublicId
> - Those routes use their own sendGatewayError helper instead of the
global error handler
> - for any error that isn't an HttpError it sent err.message back to
the caller, so a database failure leaks drizzle's Failed query text with
the SQL and its params
> - The public MCP route only needs a bearer header to reach that path,
so even a caller with a bad token can get that text
> - This pull request makes the helper answer with a fixed Internal
server error and log the real error on the server, same as the global
handler does
> - The benefit is no more SQL or param values in 500 responses from
these routes

## Linked Issues or Issue Description

Fixes #16783

## What Changed

- sendGatewayError in server/src/routes/tool-gateway.ts now logs unknown
errors with logger.error and returns { error: "Internal server error" }
with status 500.
- HttpError and ToolGatewayHttpError responses are not changed, they
still send their own message and details.
- Added server/src/__tests__/tool-gateway-error-response.test.ts. It
mounts mcpGatewayProtocolRoutes with a gateway that throws a drizzle
style error and checks the 500 body has no SQL or params. Same for a
thrown string.

## Verification

- Ran the new test on master first and both cases fail, the response
body has the full Failed query text and the param value. With the fix
both pass.
- tool-gateway.test.ts, tool-gateway-discovery-http.test.ts,
tool-grant-scope.test.ts and prompt-injection-gateway.test.ts still
pass.
- Typecheck on the changed files is clean and check:node-version,
check:module-boundaries, check:tokens and the no git push check pass.

```
cd server && npx vitest run src/__tests__/tool-gateway-error-response.test.ts src/__tests__/tool-gateway.test.ts
```

## Risks

- Low risk. Only the fallback branch for unexpected errors changes.
- If some client was reading the raw message from a 500 it will now just
see Internal server error. The full error is still in the server log so
nothing gets lost for whoever runs the instance.
- btw tool-gateway.ts was already over 1000 lines before this, the
change adds one import line.

## Model Used

Grok Bot (an AI assistant) helped trace the root cause and draft the fix
and the test. I reviewed the change and ran the tests locally.

## Checklist

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

> - Paperclip helps people manage AI agents for work.
> - Task watchdogs reuse review issues when a watched subtree stops
again.
> - A finished review can still have a user assignee.
> - Reopening that review for an agent retains the user and fails the
single-assignee check.
> - One failed watchdog also rejects a whole reconciliation batch, so
other watchdogs in that batch are not evaluated.
> - This change clears the prior user, isolates each watchdog failure,
and keeps a failed watchdog as recovery retry debt.

## Linked Issues or Issue Description

**What happened?**

A new stopped fingerprint causes a done, user-assigned watchdog issue to
reopen. The update sets assigneeAgentId but leaves assigneeUserId set.
The issue service returns 422, "Issue can only have one assignee".
Reconciliation rejects, and the remaining watchdogs in the same batch or
ancestor chain are not evaluated. On the reported release this rejection
also aborted startup recovery.

**Expected behavior**

Reopen the reusable issue with only its configured agent assigned. Log a
failed watchdog, continue the other watchdogs, and retry the failed one
through the task-watchdog recovery work.

**Steps to reproduce**

1. Configure a task watchdog and let it create a review issue.
2. Complete the review and assign that completed issue to a user.
3. Change a watched leaf to produce a new stopped fingerprint.
4. Reconcile task watchdogs. Before this change, the operation rejects
with 422.

**Paperclip version or commit**

Reproduced on upstream master at `2cd6eb27c`. The reopen path is
unchanged on current master `629281b1e8a4bae014d682a99aa6cd790508414d`.
Current merge candidate: `66d9c624cd86101e8bf65d05cabc3ed449255e5c`,
integrating that master with the previously published branch head
`681955f972c79a827c5bf2aa3e138fe4b2df69f9`.

Related PRs: #11855 addresses reviewed fingerprint reset, #15063
addresses incomplete subtree scans, and #15067 fences reviews by
configuration revision. #18402 replaced the startup and periodic
recovery sweep with per-watchdog recovery work. This branch now builds
on that design instead of changing server startup. #21670 moved
subsystem notes out of `doc/DEVELOPING.md`, so the recovery note now
lives in `doc/TASK-WATCHDOG.md`. #22831 deleted
`task-watchdogs-scheduler.test.ts` and
`issue-recovery-work-lifecycle.test.ts`, so this branch's regression
tests now live in two focused files.

## What Changed

- Clear assigneeUserId in the existing issue-service update when
reopening for an agent.
- Catch individual watchdog errors in both batch and ancestor
reconciliation. Log identifiers and the error, and return a failed
count.
- Reject the task-watchdog recovery-work check when a watchdog reports
`failed`, as it already does for `incomplete`. The coordinator keeps
that watchdog as retry debt instead of treating the swallowed error as
settled.
- Update the route no-op service and the recovery-work owner type to
match the result contract.
- Add database-backed reassignment, isolation, and reevaluation tests in
`task-watchdogs-reconciliation.test.ts`, and a recovery-work test for
failed-watchdog retry in `task-watchdog-recovery-retry.test.ts`.
- Document the recovery behavior in `doc/TASK-WATCHDOG.md`, under "How a
scan works".
- No server startup changes. The earlier startup and periodic catch
blocks were dropped with the sweep that #18402 removed.

## Verification

Current merge revision (29 November):

- The only conflicts were the two test files that #22831 deleted. This
branch accepts the deletions and moves its four regression tests,
unchanged, into `task-watchdogs-reconciliation.test.ts` (with the
minimal database harness from the deleted suite) and
`task-watchdog-recovery-retry.test.ts` (with the trimmed recovery-work
fixture). The added and removed non-test lines are identical to the 16
November revision.
- Frozen install with declared pnpm 9.15.4 succeeds. The plugin SDK was
rebuilt first; a stale SDK build otherwise fails test collection.
- New suites: **4 passed**. With upstream versions of the four changed
server files, all 4 fail: the reopen rejects with 422 "Issue can only
have one assignee", both reconcile paths reject on the malformed
watchdog, and the recovery check sets no retry wake.
- Related suites `issue-watchdogs-routes` and
`task-watchdogs-incident-fixture`: **14 passed**.
- Server TypeScript: failed with 395 diagnostics, none in changed files.
With upstream versions of the changed files on the same tree and
dependencies, the same 395 diagnostics reproduce exactly. This is
baseline reproduction, not a passing typecheck.
- `git diff --check` passed. Full workspace checks were not repeated;
the historical incomplete-suite and missing-Cargo limitations remain.
- CI and Greptile results from the prior published head do not accept
this revision. Fresh checks are required after publication.

Earlier merge revision (16 November, `681955f9`): 210 focused tests and
20 database-backed recovery tests passed; 370 TypeScript diagnostics
reproduced exactly on the upstream parent.

Earlier merge revision (1 November, `cd37b848`): 192 focused tests and
18 database-backed recovery tests passed. The failed-watchdog retry test
failed without the recovery-work change (1 failed, 12 passed) and passed
with it. 208 TypeScript diagnostics reproduced exactly on the upstream
parent.

Earlier merge revision (27 October, `03cd5fc9`): 89 focused tests passed
in independent QA. 48 TypeScript diagnostics reproduced exactly on the
upstream parent.

Historical initial revision evidence:

- New database regressions on unmodified service: 3 failed, 19 passed.
Failures were the dual-assignee 422 and uncaught assignment validation
failures in both reconciliation entry points.
- New startup regression on unmodified startup code: failed because
startServer rejected. The other 39 tests passed.
- Initial focused suite: 82 passed, 0 skipped: `TMPDIR=/tmp pnpm exec
vitest run server/src/__tests__/task-watchdogs-scheduler.test.ts
server/src/__tests__/server-startup-feedback-export.test.ts
server/src/__tests__/task-watchdogs-classifier.test.ts`.
- Initial server TypeScript passed: `TMPDIR=/tmp pnpm --filter
@paperclipai/server exec tsc --noEmit`.
- `git diff --check` passed.
- Full workspace typecheck and build were attempted. Both stop because
cargo is absent. They are not green.
- Full test suites ended without terminal summaries. They are
incomplete, not green.
- Initial local setup failures: missing plugin-sdk build, missing
embedded PostgreSQL library symlinks, and an overlong tsx IPC temporary
path. Built the workspace dependencies, ran the platform package install
step, and shortened TMPDIR before the successful focused run. These
tests used real PostgreSQL with synthetic data on macOS arm64 and Node
24.22.1.

## Risks

- Watchdog errors no longer abort a reconciliation batch. Operators must
use the error logs, failed count, and recovery-work retry errors to find
an invalid configuration.
- No migration, timer, new privilege, startup change, or live
installation change.
- Existing partial-write delivery behavior is unchanged: a failure after
issue creation/reopening can leave an open same-fingerprint issue that
suppresses a later enqueue. Later reevaluation does not guarantee every
failed delivery retries. The regression proves retry after a pre-write
assignment failure.
- Independent QA reviewed this exact revision before publication. Full
checks remain incomplete; fresh CI is pending publication.

## Model Used

Initial fix and 27 October merge: OpenAI Codex, GPT-6, with reasoning,
shell tools, code editing, and test execution; exact backend model ID
and context window not exposed. 1, 16 and 29 November merges: Claude
Opus 5.5 (`claude-opus-5-5`) in Claude Code, with shell tools, code
editing, and test execution. Independent QA reviews each exact revision
before publication.

## 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
- [x] My branch name describes the change and contains no internal
ticket id or instance-derived details
- [ ] I have run tests locally and they pass — focused tests pass; full
suites ended without terminal summaries
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
Co-authored-by: Paperclip <paperclip@localhost>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 00:14:53 -08:00
Luke AbellandLuke Abell 26cff7ebf4 fix(plugins): record webhook deliveries whose body holds NUL (#16985)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Plugins receive inbound webhooks on `POST
/api/plugins/:pluginId/webhooks/:endpointKey`
> - The route records each delivery in `plugin_webhook_deliveries`
before it calls the worker
> - The row keeps the parsed body and the headers in jsonb columns
> - PostgreSQL refuses a jsonb value that holds U+0000 or an unpaired
UTF-16 surrogate (22P05 "unsupported Unicode escape sequence")
> - So a delivery whose body has a NUL fails at the insert. No row is
written, the worker is not called, and the sender gets a 500 and retries
into the same failure
> - This pull request stores a jsonb-safe copy of the body and headers,
and gives the worker the request as sent
> - The benefit is that such a delivery is recorded and handled

## Linked Issues or Issue Description

**What happened?**
A plugin webhook delivery whose JSON body held `\^@` failed with
`PostgresError: unsupported Unicode escape sequence` (code 22P05) at
`insert into "plugin_webhook_deliveries"`. The route answered 500 and
did not call the worker. A provider that retries on 5xx sent the same
delivery again, and it failed again.

**Expected behavior**
The route records the delivery, calls the worker with the body as sent,
and answers 200.

**Steps to reproduce**
1. Install a plugin that has the `webhooks.receive` capability and
declares a webhook endpoint.
2. Send `{"text":"a\^@b"}` with `Content-Type: application/json` to
`POST /api/plugins/<pluginId>/webhooks/<endpointKey>`.
3. The answer is 500, and `plugin_webhook_deliveries` has no row for the
delivery.

**Paperclip version or commit**
`master` at efcc8a7d8. `server/src/routes/plugins.ts` is the same on the
current `master`.

Refs #16918 (the same 22P05 error class on run status writes; this pull
request uses its rule: drop NUL, turn an unpaired surrogate into U+FFFD)
Refs #16782 (what the delivery row stores)

## What Changed

- `server/src/routes/plugins.ts`: add the exported helper
`pluginWebhookJsonbValue()`. It reads the `JSON.stringify` text that the
driver sends. It drops each real `\^@` escape. It replaces each `\udXXX`
escape (the form `JSON.stringify` gives an unpaired surrogate) with `�`.
This applies to keys and values. An escaped backslash before a literal
`u0000` stays unchanged. A clean value comes back unchanged (the same
object).
- The delivery insert stores `pluginWebhookJsonbValue(payload)` and
`pluginWebhookJsonbValue(rawHeaders)`. The worker call does not change:
it still gets `rawBody` and `parsedBody` as sent, so a signature check
on the raw body does not change.
- `server/src/__tests__/plugin-webhook-unicode.test.ts`: unit tests for
the helper, and a route test on embedded Postgres that posts a body with
a NUL and an unpaired surrogate.

## Verification

- `cd server && npx vitest run
src/__tests__/plugin-webhook-unicode.test.ts`: 3 passed (embedded
Postgres included).
- With the change to `plugins.ts` reverted, the route test fails with
`expected 500 to be 200`, which is the reported error.
- `tsc --noEmit` in `server/`: no errors in the changed files.

## Risks

- Low risk. The stored copy is different only when the body or headers
hold a NUL or an unpaired surrogate. PostgreSQL refuses those values
today, so no such row exists now.
- A reader of `plugin_webhook_deliveries.payload` sees the NUL dropped.
The worker and the signature check see the request as sent.

> 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

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

## Checklist

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

> - Paperclip is the open source app people use to manage AI agents for
work
> - Plugins can declare managed agents. The server creates them in
`server/src/services/plugin-managed-agents.ts`.
> - A company can require board approval for new agents. A new agent
then starts as `pending_approval`. A `hire_agent` approval must appear
in the board inbox.
> - A managed agent can declare `instructions`. The host writes those
files and updates the agent `adapterConfig`.
> - That update runs on a `pending_approval` agent. The agent update
path refuses it with HTTP 409 (`pending_approval_agent_config_frozen`).
> - The error stops `createManagedAgent` before it creates the approval
and the plugin binding. The agent is stuck. The board has nothing to
approve.
> - This pull request passes `allowPendingApprovalConfigUpdate: true`
for that one update. Other instruction and skill materialization paths
already do this.
> - The benefit is that a managed agent with declared instructions gets
its approval and its binding when the company requires board approval.

## Linked Issues or Issue Description

Refs #11635. That pull request fixed the same root cause. Its author is
@StartupMill. A triage bot closed it as stale on 2026-10-14. It was
never merged. The defect is still present on `master` at cde944e. This
pull request has a smaller scope. See "What Changed" for the difference.

No separate issue exists. This section describes the bug.

**What happened?**

A plugin declares a managed agent that has an `instructions` block. The
company has `requireBoardApprovalForNewAgents` turned on. The host
creates the agent as `pending_approval`. Then it materializes the
declared instructions and updates the agent `adapterConfig`. The update
fails with HTTP 409: "Pending approval agent configuration cannot be
changed before board approval".

The error stops `createManagedAgent` before the `hire_agent` approval
and the plugin binding exist. The agent stays `pending_approval`. No
approval exists for a board user to click. The `adapterConfig` has no
instruction bundle keys. A second reconcile relinks the agent by its
managed marker. It does not create the approval.

**Expected behavior**

The instructions are written. The `hire_agent` approval is created with
the final `adapterConfig` in its payload. The binding is saved. The
board can approve the agent.

**Steps to reproduce**

1. Turn on "require board approval for new agents" for a company.
2. Install a plugin with the `agents.managed` capability and a managed
agent declaration that has `instructions` (`entryFile` and `content`).
The LLM Wiki plugin Wiki Maintainer is one example.
3. Run `managedReconcile` for that agent key (for example, through the
plugin bootstrap).
4. The call fails with 409. The agent list shows the agent as
`pending_approval`. The approvals list has no matching `hire_agent`
entry.

**Paperclip version or commit**

`master` at cde944e.

## What Changed

- `materializeDeclaredInstructions` in
`server/src/services/plugin-managed-agents.ts` passes
`allowPendingApprovalConfigUpdate: true` to `agentSvc.update`. The
approval payload is built from the updated agent, so it carries the
final `adapterConfig`.
- New test in `server/src/__tests__/plugin-managed-agents.test.ts`:
"materializes declared instructions and creates the hire approval when
board approval is required". It checks the agent status, the instruction
file on disk, the approval payload, and that a second reconcile adds no
second approval.

Difference from #11635: that pull request also added a backfill. The
backfill creates a missing hire approval for managed agents that are
already stuck. This pull request does not include it, on purpose.
Greptile found that the backfill is a lookup followed by an insert, so
two overlapping reconciles can create two open approvals for one agent.
The fix for that needs a change in the approvals service or schema. That
is a separate change. I can do it as a follow-up if the maintainers want
it. Also, `master` changed since #11635, so the backfill would need a
rewrite.

## Verification

- `cd server && npx vitest run
src/__tests__/plugin-managed-agents.test.ts --maxWorkers=1` - 23 of 23
tests pass.
- With the one-line fix removed, the new test fails with the 409 message
above.
- Not run: the rest of the server test suite and a repo-wide typecheck.

## Risks

- Low risk. The flag lifts the freeze only for the plugin's own
instruction materialization. This is the same flag that the other
instruction and skill materialization paths already pass. Config changes
on pending agents from any other path stay refused.
- Agents that are already stuck are not repaired by this change. The
Wiki plugin has to create them again, or a follow-up has to add the
backfill.
- No schema change and no migration.

## Model Used

Claude Opus 5.5 (Anthropic) via Claude Code, with tool use (shell, file
edits, test execution). A human reviewed the diagnosis and the diff.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes (no
docs describe this internal flow)
- [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: tomRumi <tomRumi@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 00:01:27 -08:00
9f4562f076 fix(claude-local): list Claude Haiku 5.5 in the model catalog (#16708)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The `claude_local` adapter owns the Claude Code model list that `GET
/api/companies/{companyId}/adapters/claude_local/models` returns.
> - That list includes Claude Opus 5.5 and Claude Sonnet 5.5, but the
newest Haiku entry is still Claude Haiku 4.5.
> - Claude Code 2.1.293 added `claude-haiku-5-5`. Operators on a current
CLI cannot select it in the agent model picker.
> - This pull request adds Claude Haiku 5.5 to the direct catalog and to
the Bedrock catalog, in the same family order as the other 5.5 models.
> - Haiku 5.5 needs Claude Code 2.1.293 or later. Haiku models still do
not take a reasoning effort.
> - The benefit is that the model picker can offer Claude Haiku 5.5
without a catalog redesign.

## Linked Issues or Issue Description

Fixes #16637

Refs #16660. That open pull request also inserts this model ID, but it
replaces the hardcoded catalog with an operator-editable catalog. This
pull request only adds the missing model to the catalog that ships
today.

Refs #14038. Haiku models still return no reasoning-effort choices. This
change does not alter that behavior.

## What Changed

- Added `claude-haiku-5-5` ("Claude Haiku 5.5") to the `claude_local`
model list, after Sonnet 5.5. Moved `claude-haiku-4-5` into the older
Haiku group.
- Added the dateless Bedrock ID `us.anthropic.claude-haiku-5-5`
("Bedrock Haiku 5.5"). The Anthropic Bedrock model ID is
`anthropic.claude-haiku-5-5`.
- Required Claude Code 2.1.293 or later before a CLI run or environment
test uses Haiku 5.5. Documented that minimum in the adapter
configuration notes.
- Left reasoning effort empty for Haiku 5.5, matching Haiku 4.5.

## Verification

- `pnpm exec vitest run --config vitest.config.ts src/index.test.ts
src/server/model-order.test.ts src/server/execute.remote.test.ts
src/server/test.remote.test.ts src/server/test.probe.test.ts` in
`packages/adapters/claude-local` (72 passed).
- `pnpm exec vitest run --config vitest.config.ts
src/__tests__/adapter-models.test.ts` in `server` (28 passed).
- `pnpm exec vitest run --config vitest.config.ts
src/lib/agent-setup-fields.test.ts
src/components/task-chat/composer-run-settings.test.ts` in `ui` (6
passed).
- With no Anthropic API key, the `claude_local` model list includes `{
id: "claude-haiku-5-5", label: "Claude Haiku 5.5" }` ahead of
`claude-haiku-4-5`.
- In Bedrock mode, the list includes `us.anthropic.claude-haiku-5-5` and
does not include the direct ID `claude-haiku-5-5`.

## Risks

Low risk. The new ID is additive. Existing Haiku 4.5 agents keep that
model. A CLI older than 2.1.293 fails the existing version check before
launch when Haiku 5.5 is selected. `ROADMAP.md` does not plan this
catalog entry.

## Model Used

Grok 4.7 from SpaceXAI. Tool use for repository search, tests, and the
pull request.

## 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: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
Co-authored-by: commitperclip[bot] <284812584+commitperclip[bot]@users.noreply.github.com>
2026-12-04 23:50:33 -08:00
Daniel McSheehy 957565529c fix(server): detach open conversations before deleting an agent (#16706)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - A board member can delete an agent through `DELETE /api/agents/:id`.
> - Deletion clears the assignee and the creator on the agent's issues
before it clears the conversation.
> - An open conversation must keep the same agent in the assignee field
and the conversation field.
> - The database check fails, the transaction rolls back, and the caller
receives HTTP 500.
> - This pull request clears the conversation and the assignee in one
update, then clears the other issue links.
> - The agent row can be deleted. The conversation issue remains as a
normal task.

## Linked Issues or Issue Description

Fixes #16703.

I searched open and merged pull requests for this delete path. No pull
request already changes conversation identity during agent deletion.

Refs #9186. Refs #3878. Those issues fail on `cost_events`, not on the
conversation check. This pull request does not change that path.

**What happened?**

`DELETE /api/agents/:id` returns HTTP 500 when the agent still has an
open conversation. The agent and the conversation remain.

**Expected behavior**

The delete removes the agent. The open conversation is detached first,
so the conversation check stays valid.

**Steps to reproduce**

1. Create an agent and start a chat, so the agent has a conversation
issue.
2. Pause the agent and wait until nothing is running.
3. Terminate the agent, then call `DELETE /api/agents/{agentId}` as
board.

**Paperclip version**

Reproduced from the report on 2026.1001.0 and 2026.1005.0. The same
check is present on current `master`.

**Deployment mode**

Local.

## What Changed

- Clear `conversationAgentId`, `conversationUserId`,
`conversationState`, and `assigneeAgentId` together when the
conversation belongs to the agent being deleted.
- Keep the later update that clears assignee and creator on every other
issue for that agent.
- Add a lifecycle test for an open conversation and a normal assigned
task.
- No documentation change. The public delete route stays the same.

## Verification

- Command: `pnpm exec vitest run --config vitest.config.ts
src/modules/agent-lifecycle/__tests__/lifecycle.test.ts`
- Result: 50 passed.
- The new test fails on the previous update with
`issues_conversation_identity_check`.
- With this change, the agent row is gone and both issues remain with a
null assignee and a null conversation identity.

## Risks

Low risk. The new update runs only for issues whose conversation agent
is the agent being deleted. Issue status does not change. Cost-event
delete failures in #9186 and #3878 remain open.

> 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

Grok 4.7 from SpaceXAI. The model used tool calls to read the
repository, run the lifecycle tests, and write this patch.

## Checklist

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

> - Paperclip is the open source app people use to manage AI agents for
work
> - When an owner's run ends without a recorded disposition, Paperclip
sends a disposition-repair wake with an instruction
> - The legacy instruction only asks the owner to record a disposition,
and owners tend to read it as "recovery only, do no work"
> - They then end the repair run with the issue unchanged, the repair
attempts run out, and the issue escalates to the board even though the
work could simply continue
> - This pull request adds one sentence: continue unfinished, unblocked
work in the run, then record the disposition
> - The benefit is fewer escalations and fewer empty repair runs

## Linked Issues or Issue Description

**What happened?**
Owners woken by a disposition-repair wake did no work, ended with the
same state, and exhausted the repair attempts, so the issue escalated to
the board.

**Expected behavior**
An owner with unfinished work and no blocker continues the work in the
repair run, then records a disposition.

**Steps to reproduce**
1. Let an owner run end `in_progress` without a disposition while work
remains.
2. Observe the disposition-repair wake and its instruction.
3. The owner records nothing new; after the attempts run out, the issue
escalates.

**Paperclip version or commit**
`master`; also v2026.1012.0.

Refs #16388. That change addresses original-owner repair instructions.
This change clarifies continuation during disposition repair.

## What Changed

- Keep the existing continuation instruction. The current review has no
code findings.
- Refresh the contribution template and repeat the focused instruction
checks.

## Verification

- Focused tests: **2 passed**.
- Run `pnpm --filter @paperclipai/server exec vitest run
src/services/recovery/legacy-continuation-instruction.test.ts
--maxWorkers 1`.
- Worker verification used Node 24 and local workspace source aliases.
- Full repository typecheck, tests, and build were not run. The remote
build host was unavailable.
- CI and Greptile must verify the updated head after the push.

## Risks

- The instruction can affect how an agent interprets a repair wake.
- The runtime authorization and issue state rules remain unchanged.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`, 1M context) in Claude Code, with
tool use (code search, shell, test runs).
- Review fixes: OpenAI Codex, `gpt-6.1-sol`, with code search, shell
execution, and test execution.
- The review adapter does not expose its 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
- [ ] 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: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-authored-by: Owner·paperclip <owner-paperclip@users.noreply.github.com>
Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-12-04 23:47:04 -08:00
Joly0 599867caac fix(recovery): wake the target when a quota monitor's retry is exhausted (#16199)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Recovery arms an "AI provider quota" monitor when a run fails with
`provider_quota`
> - The monitor fires at the reset time, or when a board user clicks
"Check now"
> - It asks for another bounded retry of the failed source run, but that
run used its retries before the monitor was armed
> - The dispatcher then queues nothing and still logs
`issue.monitor_triggered`, and recovery arms the same monitor again
> - This pull request makes an exhausted quota retry fall back to a
normal monitor wake
> - The benefit is that a task waiting on a provider quota resumes at
the reset without manual help

## Linked Issues or Issue Description

Fixes: #16198
Refs #10374, #15613, #17015 (an automated fix for the same issue)

## What Changed

- `server/src/services/heartbeat/scheduling.ts`: in
`dispatchClaimedIssueMonitor`, a quota monitor whose bounded retry
returns `retry_exhausted` now calls `enqueueWakeup` like every other
monitor. The existing deferred-wake handling applies to it.
- Tests: one database test in `issue-monitor-scheduler.test.ts`
(conversation-continuation source run with `scheduledRetryAttempt: 2`).

Rebased onto `master` on 2026-11-21. The earlier reset-parser change is
dropped: `master` now parses reset times in `provider-quota-reset.ts`,
whose `(?![\d:])` lookahead already stops an ISO year being read as an
hour.

## Verification

- `npx vitest run src/__tests__/issue-monitor-scheduler.test.ts` in
`server`, after the rebase: 21 passed, 2 failed.
- The new test fails with the source change reverted and passes with it.
- The two failures (`lets the board check a scheduled monitor on an
in_progress task` and `... on an blocked task`) fail identically with
the source change reverted, so they are not caused by it.
- The same change runs as a local patch on a self-hosted instance: a
stuck task resumed after a manual wake, and the patched build starts
cleanly.

## Risks

Low. Only the `retry_exhausted` outcome of the quota branch changes. If
the quota is still spent, the woken run fails again and recovery arms a
new monitor at the next reset, so the loop is bounded by the provider
reset times. Runs that need reconciliation still go to
`terminalizeLegacyExecution` first, and native source runs are still
refused before the retry is scheduled.

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

## Model Used

- Anthropic Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with
tool use (shell, file edits) and extended thinking. It traced the bug,
wrote the change and the tests, rebased the branch, and ran them. A
human reviewed and approved the change.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [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 (pending on the rebased push)
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
(pending on the rebased push)
- [x] I will address all Greptile and reviewer comments before
requesting merge
2026-12-04 23:42:00 -08:00
DottaandPaperclip eb35831f05 Add first-class SpreadJam and Okara remote MCP connectors (#23859)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The Apps catalog ships first-class connectors for external services
so teams can connect tools with verified endpoints, brand icons,
permission reviews, and guided sign-in
> - SpreadJam and Okara both publish official hosted remote MCP servers
with OAuth discovery and dynamic client registration, so users currently
fall back to unverified custom MCP entries without brand assets, scope
defaults, or reviewed risk policies
> - Adding catalog definitions with conservative risk classification,
drift quarantine, and Ask-first defaults lets users discover both apps
in the gallery and connect safely without unreviewed write/destructive
actions auto-enabling
> - This pull request adds first-class remote MCP connectors for
SpreadJam (`https://api.spreadjam.com/mcp`) and Okara
(`https://okara.ai/api/mcp`) with official brand SVGs, reviewed
permission entries, reviewed tool risk + drift policies, Ask-first
defaults for write/destructive actions, unit + fresh-OAuth server tests,
and refreshed SDK public inputs
> - The benefit is a guided connection flow with official branding,
safer default OAuth scopes for Okara, optional project pinning and
API-key support for SpreadJam, Ask-first approval on write/destructive
tools, drift quarantine on catalog refresh, and automatic BYO URL
recognition

## Linked Issues or Issue Description

**Subsystem affected**
Cross-cutting (packages/shared, server, ui, doc/connections)

**Problem or motivation**
Users connecting SpreadJam (`https://api.spreadjam.com/mcp`) or Okara
(`https://okara.ai/api/mcp`) must configure them as unverified custom
MCP servers. They get no official brand icon, no catalog entry, no
curated permission review, no Okara default scope restriction
(`mcp:read`, `mcp:write`), no SpreadJam `X-Jam-Project` or workspace API
key setup guidance, and no reviewed risk classification or drift
quarantine.

**Proposed solution**
Add both SpreadJam and Okara as first-class Track A remote MCP
connectors in the Paperclip Apps catalog:
- Register `spreadjam` with DCR OAuth (`dcr`) and workspace API key
(`customer`, `Authorization: Bearer sk_...`) methods, optional
`projectId` header pinning (`X-Jam-Project`), default agent
instructions, verified `reviewedTools` (against
`https://api.spreadjam.com/openapi.json`) with `quarantineNewEntries:
true`, and official SVG branding.
- Register `okara` with DCR OAuth (`dcr`) requesting `mcp:read` and
`mcp:write` by default (omitting `mcp:publish` and `mcp:spend`),
conservative `okaraRisk` classification with `quarantineNewEntries:
true` in `connectorToolPolicy`, and official light and dark SVG
branding.
- Require Ask-first approval by default for `write` and `destructive`
actions on fresh SpreadJam and Okara connections via
`recommendedDefaultsForApp`, keeping read tools immediately usable.
- Register permission reviews, manifest entries, generated catalog
output, shared/server tests, and `source-sdk-public-inputs.json`.

**Alternatives considered**
Leaving both servers as custom BYO MCP connections was considered.
Custom connections work after #23846, but they cannot provide curated
brand assets, verified gallery placement, Okara's read/draft scope
guardrails, reviewed tool risk + Ask-first defaults, or SpreadJam's
`X-Jam-Project` pinning and API-key flow.

**Roadmap alignment**
Extends the existing declarative Track A remote MCP Apps catalog
(`packages/shared/src/app-definitions/`) and connector risk policy
registry (`server/src/services/connectors/`). Does not duplicate or
alter planned core architecture in `ROADMAP.md`.

**Additional context**
Follows up on #23846, which improved custom remote MCP discovery and
recovery.

## What Changed

- Added SpreadJam connector override and generated definition
(`scripts/app-definition-overrides/spreadjam.json`,
`packages/shared/src/app-definitions/spreadjam.json`) for
`https://api.spreadjam.com/mcp` with `mcp-oauth` (`dcr`), `mcp-api-key`
(`customer`, Bearer `sk_...`), optional `X-Jam-Project` tenant header
pinning, `spreadjam-default-v1` agent instructions, and `reviewedTools`
(42 verified `GET` reads, 26 verified
delete/publish/PR/credit-spending/billing-allocation destructive ops,
`unlisted: "write"`, `quarantineNewEntries: true`).
- Added Okara connector override and generated definition
(`scripts/app-definition-overrides/okara.json`,
`packages/shared/src/app-definitions/okara.json`) for
`https://okara.ai/api/mcp` with `mcp-oauth` (`dcr`) and default
`scopesHint: ["mcp:read", "mcp:write"]` (`Read and draft` capability
profile, withholding `mcp:publish` and `mcp:spend`).
- Added `server/src/services/connectors/okara/risk.ts` and registered
`okara` in `server/src/services/connectors/tool-policy.ts` with
`quarantineNewEntries: true` and fail-closed risk classification (only
explicit `readOnlyHint: true` without destructive/write hints or verbs
classifies as `read`; publish/spend/delete/launch verbs classify as
`destructive`; unlisted/unannotated fail closed to `write`).
- Updated `recommendedDefaultsForApp` in
`packages/shared/src/app-definitions.ts` so new SpreadJam and Okara
connections default to `askFirstRiskLevels: ["write", "destructive"]`
while leaving read tools immediately usable.
- Added verbatim official brand SVGs
(`ui/public/brands/apps/spreadjam.svg`,
`ui/public/brands/apps/okara.svg`,
`ui/public/brands/apps/okara-dark.svg`) and registered both identities
in `ui/public/brands/apps/manifest.json` without colliding with
`jam-dev`'s existing `"jam"` alias.
- Added reviewed method entries for `spreadjam/mcp-oauth`,
`spreadjam/mcp-api-key`, and `okara/mcp-oauth` in
`doc/connections/tool-method-permission-reviews.json`.
- Added `"okara"` and `"spreadjam"` to `CONNECTABLE_APP_SLUGS` in
`packages/shared/src/app-definitions.ts` and regenerated
`packages/shared/src/app-definitions.generated.ts`.
- Added unit and embedded-Postgres integration tests in
`packages/shared/src/app-definitions.test.ts` and
`server/src/__tests__/connector-tool-policy.test.ts` covering
definitions, risk classification, fresh OAuth Ask-first policy creation,
and drift quarantine on catalog refresh.
- Refreshed `tests/runner-e2e/source-sdk-public-inputs.json` to match
the updated shared exports.

## Verification

- Brand, asset, and override validation:
- `node scripts/check-app-brand-assets.mjs` (pass: 117 brand identities
validated)
- `node --test scripts/app-definition-overrides.test.mjs
scripts/app-brand-validation.test.mjs` (pass: 16/16)
- Build, typecheck, and Vitest suites:
- `pnpm --filter @paperclipai/shared build && pnpm --filter
@paperclipai/shared typecheck` (pass)
  - `pnpm --filter @paperclipai/server typecheck` (pass)
  - `pnpm --filter @paperclipai/ui typecheck` (pass)
- `pnpm exec vitest run packages/shared/src/app-definitions.test.ts
server/src/services/tool-access/oauth/client-settings.test.ts
server/src/__tests__/connector-tool-policy.test.ts
ui/src/pages/apps/AppsConnect.test.tsx` (pass: 4 files, 97/97 tests)
- `node tests/runner-e2e/source-sdk-public-inputs.mjs $(git rev-parse
HEAD) --check` (pass: `changed: false`)
- Live non-registering preflight against local Paperclip dev server:
- `GET /api/companies/:id/tools/apps/spreadjam/preflight` →
`endpointReachable: true` (`401 application/json`),
`oauth.metadataFound: true`, `oauth.registrationAdvertised: true`
- `GET /api/companies/:id/tools/apps/okara/preflight` →
`endpointReachable: true` (`401 application/json`),
`oauth.metadataFound: true`, `oauth.registrationAdvertised: true`,
`oauth.clientIdMetadataDocumentSupported: true`
- Local browser verification against isolated dev server:
- Verified both tiles render in the Apps gallery with official SVG logos
(dark and light theme contrast verified for Okara's light/dark icons).
- Verified `/apps/connect?source=spreadjam` shows no unverified badge,
default agent instructions, OAuth + API key methods, and optional `Pin
to project ID` field.
- Verified `/apps/connect?source=okara` shows no unverified badge and
clean one-click OAuth flow.
- Verified BYO URL recognition (`/apps/byo?link=...`) detects and
suggests guided setup for both `https://api.spreadjam.com/mcp` and
`https://okara.ai/api/mcp`.

### Production Validation Matrix

| Check | SpreadJam | Okara |
| --- | --- | --- |
| Public docs & live OAuth metadata discovery | Passed | Passed |
| Non-registering Paperclip preflight endpoint | Passed | Passed |
| Deterministic unit, server OAuth policy, typecheck, and brand asset
checks | Passed | Passed |
| Local UI gallery, connect flow, light/dark logos, and BYO recognition
| Passed | Passed |
| Live account-bound OAuth sign-in / tool call execution | Not run (no
live user credentials provided) | Not run (no live user credentials
provided) |

## Risks

- Low risk: additive declarative catalog definitions, static brand SVGs,
connector risk policy, tests, and generated metadata only; no database
schema, migration, or generic OAuth runtime changes.
- Live account-bound OAuth consent, token exchange, and post-connect MCP
tool invocation were not executed in this verification pass because no
live SpreadJam or Okara account credentials were used.
- SpreadJam OAuth and workspace API keys inherit the signed-in user's
workspace role; new connections mitigate accidental side effects by
starting write and destructive actions on Ask first and quarantining
newly added tools on catalog refresh.

## Model Used

- Google Antigravity (`gemini-3-pro`, 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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-12-05 01:19:42 -06:00
Dotta 266eccc524 fix(connections): improve custom remote MCP OAuth draft setup, auto-detection, and recovery UX (#23846)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - People connect external tools to agents through custom remote MCP
servers in `/apps/byo` and manage them on `/apps/:id/permissions`
> - Unauthenticated custom MCP OAuth drafts failed catalog reads with
`oauth_refresh_missing`, displayed as `Paused`, and left operators on a
dead-end `Retry` error screen with no sign-in, auth-method switch, or
remove controls
> - The `/apps/byo` setup flow also lacked upfront read-only auth
detection, display-name editing, custom draft resume, and detached-tab
OAuth completion polling
> - Custom remote MCP servers must work smoothly out of the box without
dead ends or manual trial-and-error
> - This pull request fixes backend OAuth draft/catalog truthfulness,
adds a read-only custom MCP auto-detection probe, adds dedicated draft
setup and error recovery on `AppDetail`, and improves `/apps/byo`
auto-detection, resume, and OAuth waiting UX
> - The benefit is that operators can connect and recover any
standards-compliant remote MCP server cleanly without hitting false
expired-credential dead ends

## Linked Issues or Issue Description

**What happened?**
Opening an unauthenticated custom remote MCP OAuth draft at
`/apps/:id/permissions` triggered a live remote catalog refresh that
threw `422 oauth_refresh_missing` (`"OAuth credentials have expired and
need to be reconnected."`), overwrote stored health to `failed`,
displayed status `Paused`, and replaced the Permissions tab with a
looping `Retry` box. Operators had no way to start sign-in, change the
sign-in method, see OAuth callback failure details, or remove the
connection. In `/apps/byo`, pasting a URL did not detect auth upfront,
did not allow editing the display name, failed to resume custom MCP
drafts via `?resume=<id>`, duplicated the `Unverified server` badge, and
stopped polling when opening sign-in in a new tab.

**Expected behavior**
Unauthenticated OAuth drafts should remain readable without failing
catalog reads or reporting expired credentials, show `Setup incomplete`
with clear `Sign in`, `Change sign-in method`, `Remove`, and `Connection
details` controls, surface OAuth callback errors inline, and keep
recovery actions visible when catalog loading fails. `/apps/byo` should
detect auth upfront in a read-only probe, allow naming the connection,
resume custom MCP drafts cleanly, and detect OAuth completion even when
sign-in opens in a new tab.

**Steps to reproduce**
1. Create a custom remote MCP OAuth draft via `/apps/byo` or `POST
/api/companies/:companyId/tools/apps/connect` without completing browser
OAuth consent.
2. Open `/<prefix>/apps/<connectionId>/permissions`.
3. Observe `Paused` and `"Couldn't load tools for this app / OAuth
credentials have expired and need to be reconnected. [Retry]"` with no
sign-in or recovery controls.

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

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

## What Changed

- **Backend OAuth draft & catalog truthfulness**
- Export `isConnectionAwaitingFirstSignIn` in
`server/src/services/tool-access/connections/first-sign-in.ts` and skip
remote `refreshCatalog()` in
`server/src/services/tool-access/catalog/reader.ts` when an
unauthenticated OAuth draft has an empty catalog.
- Distinguish never-authorized OAuth connections/grants (`422
oauth_challenge`: `"This app needs you to sign in."`) from genuinely
expired tokens missing a refresh token (`422 oauth_refresh_missing`) in
`server/src/services/tool-access/oauth/grant-refresh.ts` and
`server/src/services/tool-access/oauth/connection-refresh.ts`.
- Annotate `firstSignInPending` on `getConnection` in
`server/src/services/tool-access.ts` to match `listConnections`.
- **Read-only custom MCP auto-detection probe**
- Add `probeGenericMcpSchema` and `GenericMcpProbeResult` in
`packages/shared`, capture optional `resource_name` in
`server/src/services/tool-access/oauth/discovery.ts`, implement
read-only `createGenericMcpProbe` in
`server/src/services/tool-access/connections/probe-mcp.ts`, expose `POST
/api/companies/:companyId/tools/apps/probe-mcp` in
`server/src/routes/tool-access.ts`, and add `toolsApi.probeGenericMcp`
in `ui/src/api/tools.ts`.
- Refresh `tests/runner-e2e/source-sdk-public-inputs.json` for the
shared schema and type additions.
- **App detail setup, recovery, and management UI**
- Show `Setup incomplete` for draft connections in
`ui/src/pages/apps/AppDetail.tsx` and
`ui/src/pages/apps/Connections.tsx`.
- Add `FinishSetupCard` in `AppDetail.tsx` with `Sign in` (shared,
personal, and agent policies), `Change sign-in method`, inline OAuth
return error recovery (`?oauth=failed|denied`), live completion polling,
`Remove`, and `Connection details`.
- Scope catalog fetch errors to the Actions area so `IdentitiesSection`,
`ReconnectCard`, and custom MCP management (`AdvancedPanel`) stay
accessible.
- **BYO setup, resume, and OAuth waiting UX**
- Run background read-only probing on `/apps/byo` Step 2 in
`ConnectionSetupFlow.tsx` and `GenericMcpConnectStep.tsx`, add an
editable Display name input, use `Server URL · Connect` for the BYO
stepper, and support resuming/reconnecting custom MCP drafts via
`?resume=<id>&editAuth=1`.
- Remove the duplicate `Unverified server` badge and stuck disabled
`Opening …` button on `OAuthConnectStateScreen`, use non-workspace copy
for custom MCP servers, and keep polling connection activation after
clicking `Open sign-in in a new tab`.

## Verification

- Ran server and UI regression tests (183/183 passing):
- `pnpm vitest run server/src/__tests__/generic-mcp-connection.test.ts
server/src/__tests__/tool-access-cancelled-first-sign-in.integration.test.ts
ui/src/pages/apps/AppDetail.test.tsx
ui/src/features/connections/ConnectionSetupFlow.generic-mcp.test.tsx
ui/src/features/connections/GenericMcpConnectStep.machine.test.tsx
ui/src/pages/apps/generic-mcp-connect.test.ts`
- Ran package typechecks and UI checks:
  - `pnpm --filter @paperclipai/shared typecheck`
  - `pnpm --filter @paperclipai/server typecheck`
  - `pnpm --filter @paperclipai/ui typecheck`
  - `node scripts/check-query-error-rendering.mjs` (0 findings)
  - `pnpm run check:token-gates` (0 violations in changed files)
- Verified end-to-end locally in an isolated worktree dev server against
live remote OAuth MCP endpoints for draft setup, `Change sign-in method`
resume, upfront read-only auto-detection, and OAuth waiting screen.

## Risks

- Low risk: existing active and expired OAuth connections keep
`oauth_refresh_missing` behavior unchanged (covered by explicit
regression tests).
- The new `/probe-mcp` route uses the same company/management
authorization guards, SSRF/private-network checks, self-loop protection,
and OAuth endpoint policy as `/apps/connect`, performs zero database
writes, and makes zero DCR `POST` requests.
- `packages/shared` exports changed, so
`tests/runner-e2e/source-sdk-public-inputs.json` was regenerated for CI.

## Model Used

- Google Antigravity (`gemini-3-pro`, 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
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
2026-12-05 00:41:30 -06:00
1dcab931a6 fix(recovery): do not cap new runs at the legacy disposition-repair allowance (#15923)
## Thinking Path
> - The execution-semantics spec gives `deliberate_wait_without_target`
recovery five disposition-repair attempts, with delays 0, 60, 120, 240,
and 480 seconds.
> - The disposition-repair module implements that schedule. A separate
legacy-episode helper also exists, to protect pre-upgrade episodes that
already spent attempts under an older, tighter allowance.
> - The helper never answered "not a legacy episode". A run with an
entirely empty context snapshot — clearly not a pre-upgrade episode —
still got a legacy episode capped at 2 attempts (1 for handoff and
old-recovery runs).
> - The common continuation path passes that episode unconditionally, so
the documented five-attempt fallback next to it was dead code for every
non-native run.
> - The fix makes the helper return no episode when a run has no legacy
markers and has consumed no attempts. Marked or partly spent pre-upgrade
runs keep the legacy cap, so no spent budget is resurrected.

## Linked Issues

Fixes #15776

## What Changed

- `server/src/services/recovery/legacy-continuation.ts`:
`legacyDispositionEpisode` now gives a run with no legacy markers (no
persisted episode record, no handoff or old-recovery markers, no repair
fingerprint, no liveness-continuation source) and no consumed attempts
the documented budget, `DISPOSITION_REPAIR_MAX_ATTEMPTS` (5), instead of
the legacy cap. The episode object still exists for every run, so repair
dispatch keeps its persisted binding, issue state guard, and
source-identity semantics. Marked or partly spent runs still derive
their capped episodes, unchanged.
- `server/src/services/recovery/legacy-continuation.ts`: the
persisted-record branch no longer clamps every episode to the legacy
cap. A record keeps the budget it was written with: records written
under the legacy scheme carry at most the legacy cap and keep it, and
records written under the documented scheme keep theirs. Without this, a
new episode was re-capped at 2 from its second attempt on.
- Tests in `legacy-continuation.test.ts`: marker-less runs derive the
five-attempt budget; persisted records keep their written budget (2
stays 2, 5 stays 5); fingerprinted, liveness-sourced, and partly spent
runs still derive their capped episodes.
- Test updates in `legacy-continuation-authority.test.ts` and
`heartbeat-process-recovery.test.ts`: expectations that pinned the old
cap for marker-less runs now expect `maxAttempts: 5`; the exhaustion
tests (ACCT-02, ACCT-04, and the bounded-episode test) stamp a genuine
pre-upgrade episode on their source runs so they keep pinning the legacy
bound. No production behavior outside the budget derivation changed for
those tests.

## Verification

- `vitest run server/src/services/recovery/legacy-continuation.test.ts`
— 28 of 28 pass, including the existing "does not resurrect an exhausted
pre-upgrade budget" cases.
- CI on the final head: all checks pass (55 of 55), including the suites
that pin the surrounding semantics — `legacy-continuation-authority`,
`heartbeat-process-recovery`, `heartbeat-stale-queue-invalidation`,
`heartbeat-slack-invitation`, `heartbeat-issue-liveness-escalation`, and
the chat integration suites.
- An earlier revision of this PR returned `undefined` for marker-less
runs; CI showed that episode presence also drives the state guard and
dispatch identity checks, so the fix was reworked to change only the
budget derivation. The PR comments carry the full history.

## Risks

- A run whose only history is a positive generic continuation counter
stays on the legacy cap. That matches this repo's existing test
expectation that a run with `continuationAttempt: 2` is an exhausted
pre-upgrade episode; the counters cannot distinguish schemes, so the
conservative reading wins.
- Note for sequencing: open PR #15658 also touches the recovery area
(owner continuation after partial work) but does not change the attempt
cap, so the two changes are independent.

## Model Used

- **Provider / Model ID:** Meta, Muse Spark 1.3
- **Context window:** 1M+ tokens (exact limit not disclosed);
large-repository tasks with long tool transcripts
- **Capabilities:** agentic coding with tool use — file editing, shell
execution, test execution, browser and API access, multi-step planning

## Checklist

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

---------

Signed-off-by: Josh Cox <joshuacox@users.noreply.github.com>
Co-authored-by: Review <review@local>
Co-authored-by: commitperclip[bot] <284812584+commitperclip[bot]@users.noreply.github.com>
2026-12-04 21:38:49 -08:00
Josh CoxandReview 587de9420f fix(native-runtime): stamp attribution on cancel_continuations run cancellations (#15922)
## Thinking Path
> - Native status decisions can cancel an issue's continuations. The
`cancel_continuations` effect cancels queued wakes and pending
interactions, then terminalises the heartbeat run.
> - That run write set only `status`, `finishedAt`, and `updatedAt`.
Every other run-cancellation write in the codebase also stamps an
`errorCode`, a `resultJson` marker, or both.
> - Recovery treats a cancelled run with no attribution as possible
agent stranding. It can re-wake an agent that a status decision
deliberately stopped, and there was no activity row recording the run's
cancellation.
> - The committer already writes an issue-level activity row for the
decision itself, with actor `system` / `native-status-committer`. The
fix stamps the run in the same terms and adds a run-level activity row
in the same transaction.

## Linked Issues

Fixes #15767

## What Changed

- `server/src/services/native-runtime/status-decision-committer.ts`: the
`cancel_continuations` branch now
- sets `errorCode: "native_cancelled_continuations"` and an `error`
message on the run,
- merges a `resultJson` marker into the run's existing result
(`stopReason`, `cancelledByActorType: "system"`, `cancelledByActorId:
"native-status-committer"`, and the cancelled wake-request and
interaction ids),
- writes a `heartbeat.cancelled` activity row for the run inside the
same transaction, using the file's existing `persistActivity` helper and
the same system actor the decision row uses.
- New embedded-Postgres test
`server/src/__tests__/native-cancel-continuations-attribution.test.ts`:
seeds the native finalization graph (company, agent, issue, run,
contract, result, assessment, coordinator), commits an issue-scope
cancellation decision, and asserts the run's status, errorCode, error,
merged resultJson, and the single `heartbeat.cancelled` activity row.

## Verification

- The new test runs against embedded Postgres. The sandbox I used runs
as root, and embedded Postgres refuses to start as root, so the suite
self-skips there and runs in CI.
- Type check: a full server `tsc` run does not fit in the memory of the
sandbox I used. I ran a scoped program over the changed files instead;
its errors are confined to pre-existing scoped-program artifacts in
unrelated files, with none in the changed files.
- The fix follows the exact field conventions of the sibling
cancellation writes enumerated in the issue (the board route's
`heartbeat.cancelled` activity action and the `cancelledByActorType`
result marker), with the actor recorded as the system committer because
no user or agent actor reaches this path.

## Risks

- `cancelledByActorType: "system"` does not trip the operator stand-down
in recovery, which is keyed to `user`/`board`. That is deliberate: this
path is a system status decision, not an operator action, and claiming a
user actor would be false attribution. The run now carries a distinct
errorCode, so it no longer groups with unexplained cancellations.
- The resultJson merge reads the run's current resultJson inside the
same transaction before the update, so existing markers (for example
native cancellation receipts) are preserved.

## Model Used

- **Provider / Model ID:** Meta, Muse Spark 1.3
- **Context window:** 1M+ tokens (exact limit not disclosed);
large-repository tasks with long tool transcripts
- **Capabilities:** agentic coding with tool use — file editing, shell
execution, test execution, browser and API access, multi-step planning

## Checklist

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

---------

Signed-off-by: Josh Cox <joshuacox@users.noreply.github.com>
Co-authored-by: Review <review@local>
2026-12-04 21:37:12 -08:00
Mohamed AamirandClaude Opus 5.5 81547e803e fix(server): do not re-create closed plugin session rows on run finalization (#15860)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Plugins can open agent sessions with `ctx.agents.sessions.create`,
send messages to them, and end them with `ctx.agents.sessions.close`.
> - Each plugin session is one `agent_task_sessions` row with the task
key `plugin:<pluginKey>:session:<uuid>`. `close` deletes this row.
> - The host publishes the terminal run event (`heartbeat.run.status`
and the plugin `agent.run.*` event) before run finalization saves the
session state. Finalization calls `upsertTaskSession`, and that function
inserts a new row when no row exists.
> - Thus a plugin that closes its session on the terminal event gets the
row back a few milliseconds later. The closed session becomes a leaked
row that nobody owns.
> - This pull request makes `upsertTaskSession` update an existing
plugin session row and never insert one. Only `agentSessions.create`
creates these rows.
> - The benefit is that `close` is final. Plugins do not need delays or
cleanup jobs to remove leaked session rows.

## Linked Issues or Issue Description

Refs #14143 (we found this bug while we built a Boardroom plugin for
this feature request).

Related: #9977 (open) adds general task-session tombstones and atomic
finalization. That change is much larger and does not cover the plugin
`close` path. This pull request is a small, separate fix for plugin
sessions only.

**What happened?**
A plugin called `ctx.agents.sessions.close` when it received the
terminal event of a session run. The `agent_task_sessions` row for that
session came back after the delete. On a real instance, the row was
re-created 5 ms after the plugin closed the session. That run was
cancelled, but a "done" (succeeded) run has the same race.

**Expected behavior**
After `ctx.agents.sessions.close` returns, the session row stays
deleted. A run that finalizes after the close does not create the row
again.

**Steps to reproduce**
1. Install a plugin that has the `agent.sessions.create`,
`agent.sessions.send`, and `agent.sessions.close` capabilities.
2. In the plugin, create a session and send a message with
`ctx.agents.sessions.sendMessage`.
3. In the `onEvent` callback, call `ctx.agents.sessions.close` when the
event type is `done` or `error`.
4. Wait for the run to finish (or cancel it).
5. Query `agent_task_sessions` for the task key
`plugin:<pluginKey>:session:%`. The closed session row is there again,
with `last_run_id` set to the finished run.

**Paperclip version**
`master` at 7e10dbe65 (server 0.3.1).

**Deployment mode**
Local trusted, self-hosted, with the embedded database.

## What Changed

- `server/src/services/heartbeat/run-state.ts`: `upsertTaskSession`
returns `null` and does not insert when the task key is a plugin session
key (`plugin:<pluginKey>:session:...`) and no row exists. It still
updates an existing row. The guard is next to the existing fence for
agent chat conversation sessions (added in #13284).
- `server/src/services/heartbeat/run-state.test.ts`: a new PostgreSQL
test. It creates a session with the real `agentSessions.create`, saves
session state for a run (the row is updated), closes the session with
the real `agentSessions.close`, and then runs a late finalization write.
The test expects `null` and no row for that task key.
- No documentation change is necessary. The public plugin API does not
change.

## Verification

- The branch is rebased on `master` at eedf25655. Full repository check,
on this branch and on a clean `master` eedf25655 checkout on the same
machine:
- `pnpm -r typecheck` and `pnpm -r build`: 33 of 35 packages pass.
`@paperclipai/paperclip-runner` and `@paperclipai/server` fail with
`cargo: command not found` (no Rust toolchain on the local machine).
`master` has the same two failures. The checks that do not need Rust
pass: the runner `typecheck:typescript`, `cd server && pnpm exec tsc
--noEmit` (no errors), and the server build without the Rust runner
step.
- `pnpm test:run`: the script stops after the first group that has a
failure, so I ran every group of `scripts/run-vitest-stable.mjs`
(general server, workspaces A and B, serialized). No test fails on this
branch that does not also fail on `master` in the same conditions. The
failures on both are environment failures on this machine (git
credential helper, GitHub launcher, CLI install store, timeouts). Tests
that failed only once under load passed when I ran them again alone, on
this branch and on `master`.
- `cd server && pnpm exec vitest run
src/services/heartbeat/run-state.test.ts
src/__tests__/plugin-agent-sessions.test.ts
src/services/heartbeat/run-completion.test.ts
src/__tests__/heartbeat-task-session-reset.test.ts`: 4 files, 36 tests
pass. In the full run, the server test count is one higher than on
`master`, and the new test passes.
- Without the change in `run-state.ts`, the new test fails.
`upsertTaskSession` returns a re-created row with `sessionDisplayId:
"late-finalization"` instead of `null`.
- Manual check on a production build (`pnpm build`, then
`NODE_ENV=production node server/dist/index.js`, embedded PostgreSQL),
with a plugin that creates a session per run and closes it when the run
ends (`claude_local` agent). I started a session run, cancelled it
during the run with `POST /api/heartbeat-runs/:id/cancel`, and let the
run finish. The plugin closed the session when it received the cancel:
- With this change: no `agent_task_sessions` row is left for the
`plugin:<pluginKey>:session:...` task key.
- On `master` with the same steps: the host inserted a new row for that
task key after the plugin closed the session, and the row stayed.

## Risks

- Low risk. The change applies only to task keys that start with
`plugin:` and contain `:session:`. Issue sessions, conversation
sessions, and other task keys keep the old behavior.
- A plugin session row matches on agent, adapter type, and task key. If
an operator changes the adapter type of an agent while a plugin session
is open, the run of the new adapter does not save its session state for
that session (before, it inserted a second row). The plugin can close
the session and create a new one. We think this is the correct behavior,
because `close` deletes only the original row.
- A plugin that sets its own `taskKey` in `agentSessions.create` is not
affected, because `list`, `sendMessage`, and `close` do not find such
rows either.

## Model Used

- Provider and model: Anthropic Claude Opus 5.5
- Model ID: `claude-opus-5-5`
- Context window: not stated by the tool
- Use: through Claude Code, with tool use, subagents, 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 (not
applicable: the public plugin API and documented behavior do not change)
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 21:30:00 -08:00
Devin FoleyandPaperclip f4a6cacb3d test(server): seed prior heartbeat for watchdog timer test (#23856)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Agent timers use the last checked heartbeat to set their next
deadline.
> - The watchdog settles a run whose source task has completed.
> - Settlement advances an existing heartbeat but preserves a missing
first heartbeat.
> - The timer test expected an advanced heartbeat without seeding an
existing one.
> - This pull request seeds that timestamp from the fixture clock.
> - The test can then verify that the fold advances the deadline and
reschedules the coordinator.

## Linked Issues or Issue Description

**What happened?**

[Master source verification
47480088300](https://github.com/paperclipai/paperclip/actions/runs/47480088300/job/145548865209),
on `3ecc2dffffebf5ad7af54c02ce2a96b90f141e09`, failed in
`agent-timer-deadlines.test.ts`. The watchdog rescheduling case
dereferenced a null `lastHeartbeatAt`. The other 87 files passed, with
1,395 tests passed. This cancelled [image run
47480088316](https://github.com/paperclipai/paperclip/actions/runs/47480088316).

The fixture creates an agent with no recorded heartbeat. Watchdog
settlement uses `settledHeartbeat`, which preserves null until a real
heartbeat occurs. The fixture therefore did not meet the precondition
for its deadline assertion.

The earlier [image run
47465426560](https://github.com/paperclipai/paperclip/actions/runs/47465426560)
had separate SSH fixture and human-blocker corpus failures. Those are
fixed on master by #23830 and #23853. This PR addresses the remaining
timer fixture failure.

**Expected behavior**

The case that checks an advanced heartbeat deadline must start with an
existing heartbeat. It must still assert a succeeded run, a later
deadline, and the coordinator's rescheduled wake. Settlement must
preserve the first-heartbeat behavior.

**Steps to reproduce**

On master `c8ca682bf28e43d03e836de53b466809cbafb806`, run
`PAPERCLIP_VITEST_RETRY=0 pnpm exec vitest run
server/src/__tests__/agent-timer-deadlines.test.ts -t 'reschedules after
the watchdog folds a completed source run' --maxWorkers=1`. Before this
change, the test failed locally with the same null `getTime` error as
CI.

## What Changed

- Seed this case's prior heartbeat with the fixture's `now` before
creating and folding its active run.
- Retain the run settlement, later-deadline, and coordinator wake
assertions.

## Verification

- Red: the targeted test failed locally with retries disabled and the
same null timestamp error as CI.
- Green: `PAPERCLIP_VITEST_RETRY=0 pnpm exec vitest run
server/src/__tests__/agent-timer-deadlines.test.ts --maxWorkers=1`
passed all 54 tests with no skips. Environment: macOS, Node v25.6.1,
embedded PostgreSQL.
- `pnpm exec tsc --noEmit -p server/tsconfig.json` passed.
- The test budget check and `git diff --check` passed.
- [Greptile rated head `ef9329c36cfbbdfdcb811762e63f5896beed7f25`
5/5](https://github.com/paperclipai/paperclip/pull/23856#issuecomment-7432554160),
with no actionable feedback or review threads. Final checks: 64 passed,
seven skipped, no pending or failed checks. The [CI verification
gate](https://github.com/paperclipai/paperclip/actions/runs/47483205676/job/145559933620)
passed. GitHub reports no merge conflicts.
- This suite is registered in `scripts/ci/nightly-only-suites.json`. It
runs in master readiness and full verification, and ordinary PR CI omits
it. The full local owner suite supplies direct coverage for this fixture
change; required CI will supply the applicable typecheck, build, and
regression coverage.
- Final local head: `ef9329c36cfbbdfdcb811762e63f5896beed7f25`. No full
local repository suite was run.
- The subsequent [master verification
attempt](https://github.com/paperclipai/paperclip/actions/runs/47482391206/job/145556677801)
also failed in the same watchdog deadline case. That image publication
attempt was cancelled. Post-merge master verification and image
publication still need confirmation; no gate was bypassed.

## Risks

- Low risk. One test fixture gains a prior-heartbeat timestamp.
- The fixture uses its seeded clock, so it does not depend on the
wall-clock date.
- No application contract or documentation change is needed.

## 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>
2026-12-04 21:27:58 -08:00
Josh CoxandReview 511c9cc5f7 fix(runs): honor offset when listing company heartbeat runs (#15669)
<!-- Write all pull request text in Simplified Technical English
(ASD-STE100): short sentences, one instruction per sentence, simple
approved vocabulary, and the active voice. -->

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The board and external tools read agent runs through the REST API
> - The company heartbeat runs endpoint returns the run history for a
company
> - The endpoint accepted a limit value, but it ignored the offset value
> - A caller that paged through the runs received the first page again
and again, and tools that count runs or tokens silently over-counted
> - This pull request adds offset support to the route, to the run list
service, and to the OpenAPI entry
> - The benefit is correct paging through the full run history of a
company

## Linked Issues or Issue Description

Fixes #15318

## What Changed

- The `GET /api/companies/:companyId/heartbeat-runs` route now reads the
`offset` query parameter, clamps it at zero, and passes it to the
heartbeat run list
- `listRuns` in the heartbeat run state service accepts `options.offset`
and applies it in the database query; an absent or zero offset keeps the
current behavior
- `listRuns` now orders by `createdAt` descending and then by `id`
descending, so page boundaries stay stable when runs share a timestamp
- The OpenAPI entry for the endpoint now documents the `agentId`,
`limit`, `offset`, and `summary` query parameters
- Tests: a mock-level test proves the offset reaches the query only when
one is set, and an embedded-Postgres test proves limit and offset page
in newest-first order

## Verification

- `vitest run server/src/services/heartbeat/run-state.test.ts` — 4
passed, 6 skipped in my sandbox. The PostgreSQL suite self-skips when
the tests run as root; the new paging test is in that suite and runs in
CI. The mock-level offset test runs everywhere
- Negative control: with the source change stashed, the new offset test
fails on the unmodified code
- `tsc --noEmit -p server/tsconfig.json` passes

## Risks

- Low risk. The default behavior does not change when a caller sends no
offset
- Rows with equal `createdAt` values now have a deterministic order. The
old order for equal timestamps was not specified, so no caller could
rely on it

## Model Used

- Provider: Meta
- Model: Muse Spark 1.3 (Muse model family)
- Capabilities: tool use, code execution, extended reasoning

## Checklist

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

---------

Signed-off-by: Josh Cox <joshuacox@users.noreply.github.com>
Co-authored-by: Review <review@local>
2026-12-04 21:25:00 -08:00
Arthurandmnazirp-finity 2eea950c2e fix(heartbeat): stop carrying the in_review wait into later summaries (#15544)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - After each run, Paperclip refreshes the issue's continuation
summary. In review, its Next Action says to wait for reviewer feedback
> - Later refreshes copy that line into in-progress issues, so the
dispatcher cancels the queued continuation
> - This pull request stops that copy

## Linked Issues or Issue Description

Refs #14424. Agents on an issue that came back from review get their
queued continuation runs cancelled with
`issue_continuation_waiting_on_review`. Builds on the repro and check
from @mnazirp-finity. Related: #11614.

## What Changed

- `inferNextAction` no longer carries the Next Action it writes for an
in_review issue into another status.
- Tests: the issue's repro, a kept waiting Next Action, and a Postgres
test for the queued continuation.

## Verification

- `pnpm exec vitest run issue-continuation-summary.test.ts
run-dispatch/adapters/postgres.test.ts`

## Risks

Low. Stored summaries with the wait line change after the next run.

## Model Used

The AI assistance note is at the end.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [ ] I have specified the model used (with version and capability
details)
- [x] ROADMAP.md lists no planned core work that overlaps this PR
- [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

Assisted by Claude/Codex.

Co-authored-by: mnazirp-finity
<317764857+mnazirp-finity@users.noreply.github.com>

Co-authored-by: mnazirp-finity <317764857+mnazirp-finity@users.noreply.github.com>
2026-12-04 21:23:21 -08:00
crownlayerappandcrownlayerapp 6520046f35 fix(recovery): admit a legacy conversation turn cancelled before dispatch (#15383)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - A chat task runs each user message as a legacy conversation turn,
and a turn must prepare before it dispatches a provider
> - An operator can press Stop during that preparation window, so the
run ends with no provider process and no stop receipt
> - Admission then asks for proof that the previous process stopped, and
a process that never started can never supply that proof
> - So every later message on the thread defers forever behind
`process_identity_missing`, and the chat goes silent with no error
> - The same missing proof stalls `agentExecutionsHaveStopped()`, so a
pause or terminate waiting on that run never completes either
> - This pull request adds a narrow proof that such a run never reached
dispatch, and retires its reconciliation hold on the same evidence
> - The benefit is that a chat thread recovers by itself after an
interrupted preparation, explicit Retry works on a thread that is
already stuck, and a pause stops hanging

## Linked Issues or Issue Description

Refs #18147 — the pause hang on a historical conversation-adapter run
cancelled before spawn. #20384 fixed the verified resource-wait case of
that issue (`workspace_busy` / `ai_connection_*` with a matching
`executionRecovery` receipt) and its description says it does not claim
to repair every run shape reported there. This PR covers the shape most
of its reporters describe: an operator Stop during preparation on a
conversation adapter, `errorCode: cancelled`, with no resource-wait
receipt because none applies. The two changes are disjoint:
`isPreDispatchResourceWait()` requires a wait receipt that an operator
Stop never writes, and `legacyBeforeDispatch` requires the
conversation-adapter claim and the `preparing` stage that a resource
wait at `settled` does not have.

Refs #14300 — the same permanent hold. `master` already covers the
triggers reported there: the stale-queued-run gate row through
`isPreDispatchReviewWait`, and the historical Paperclip Runner
preparation row through `historicalBeforeSelection` (#15020, #15022).
The conversation-adapter trigger that @MatrixCODEBreak [reported on 29
September](https://github.com/paperclipai/paperclip/issues/14300#issuecomment-5899252500)
is still uncovered, and this PR covers it. Our own diagnosis of the same
shape is
[here](https://github.com/paperclipai/paperclip/issues/14300#issuecomment-5981260379).

Refs #13640 — the same "no operator path out" family. Related merged
work: #19276 (system-cancelled unclaimed workspace retry) and #19466
(Retry after a refused automatic attempt) both reference this PR as the
adjacent case they do not cover.

**What happened**

A board operator pressed Stop 1.1 s into a `codex_local` chat turn on
`v2026.1001.0`. The run never dispatched a provider. The chat then went
silent for a day and a half: every message was saved, and every wake was
re-deferred as `deferred_issue_execution` while
`admitExplicitNativeContinuation` returned `process_identity_missing`.

**Expected behavior**

A turn cancelled before dispatch started no process, so there is nothing
to stop. A new user message should start a fresh turn.

**Steps to reproduce**

1. Open a chat task that is assigned to an agent on a conversation
adapter.
2. Send a message, and press Stop on the board while the run is still
`preparing` — before any `adapter.invoke` or process-start event.
3. Let the controller lease on that run expire (a restart also does it).
4. Send another message. It is saved, and it never starts a run.

One of the two terminal rows that produced the hold for us — the first
occurrence, with the fence retained:

```json
{
  "status": "cancelled", "error_code": "cancelled",
  "runtime_mode": "legacy", "runtime_mode_resolved_at": null,
  "execution_stage": "preparing",
  "process_pid": null, "process_group_id": null, "process_started_at": null,
  "native_session_id": null, "native_issue_id": null, "session_id_after": null,
  "controller_boot_id": "<the boot that prepared it>",
  "controller_lease_expires_at": "<in the past>",
  "runner_profile_json": { "adapterDispatch": { "adapterType": "codex_local" } },
  "result_json": {
    "stopReason": "cancelled", "cancelledByActorType": "user",
    "startupCancellation": { "requestedAt": "...", "beforeNativeSelection": false }
  }
}
```

`historicalBeforeSelection` does not admit it, because that proof
requires `claimedAdapterType(run) === "paperclip_runner"` and `errorCode
=== "operator_interrupted"`. It also accepts only an absent result or
`beforeNativeSelection === true`; here the cancel arrived after runtime
selection but before dispatch, so the fence records `false`.

**It recurs, and the shape varies.** The same thread stranded a second
time two days later, on `claude_local`, from a cancel 31 s into
preparation. That row has `runtime_mode_resolved_at` **set** and **no**
`startupCancellation` at all — `Stop` only writes that fence while the
runtime is unresolved. A proof keyed on the fence, or on an unresolved
runtime, therefore misses the second occurrence while fixing the first.
So this proof keys on the stage instead.

**Why the stage is positive evidence, not an absence.** `execution_stage
= 'preparing'` is written by core in `legacyControllerClaim()`, in the
same UPDATE that claims the queued run. The only writer that advances it
is `renewLegacyControllerLeaseInTransaction(..., "dispatching")`,
reached through `assertOwned("dispatching")`, which the executor calls
ahead of the provider handoff, and which succeeds only while the run is
`running` under the same controller boot. A terminal run still at
`preparing` therefore provably never dispatched. This is the same kind
of evidence `historicalBeforeSelection` already accepts for
`paperclip_runner` rows, and the same `preparing` stage that master's
`legacy-preparation-settlement.v1` receipt records as
`adapterDispatched: false` for failed preparations. The run shape this
PR admits differs from those only in adapter family and error code.

**Why the current Stop path cannot write the receipt this hold waits
for.** `conversationRecoveryActionPredicate()` retires a cancelled run's
hold only on `executionCancellation.state = 'acknowledged'`. Stop
records `state: 'requested'` for every run, and advances it to
`acknowledged` for a legacy run in exactly two places: when a running
child process with a PID or process group was stopped, and in
`acknowledgeRemoteStop()` when a remote lease has a termination receipt.
A local conversation turn cancelled before its child spawned matches
neither, so its `executionCancellation` stays `requested` and the hold
cannot retire by itself. That is why the SQL arm is needed alongside the
TypeScript proof, and why the data shape reported on #18147 by eleven
other operators keeps appearing on `2026.1023.0` and `2026.1106.0`.

**The earlier-boot requirement.** The elapsed controller lease must come
from an **earlier boot**, as `historicalBeforeSelection` also requires.
That is what proves the preparer is gone rather than merely unable to
renew. It costs no coverage: an executor that reaches its own cleanup
commits `execution_stage = 'settled'` *and* `controller_lease_expires_at
= null` in a single write gated on the current boot id, so a cleanly
settled run of this boot retains no lease deadline for the proof to
match, and the proof already requires one. The runs that reach this
proof are exactly those whose executor never finished — and a
current-boot executor that has not finished may still be inside an
uninterruptible provider call. See the resolved review thread on
`cancelled-native-startup.ts` for the race this closes.

**A second symptom, independently reported.** @naeemakhtar110 [reported
on 18
October](https://github.com/paperclipai/paperclip/pull/15383#issuecomment-6247286188)
that on `2026.1012.1-beta.0` several agents stayed in lifecycle
`pausing` for good, because `agentExecutionsHaveStopped()` was waiting
on a run of exactly this shape, and that applying the TypeScript arm
alone cleared it. That path reaches the same proof through the
`runtime_mode = 'legacy'` branch of `agent-execution-stop.ts`, which
needs no change. This PR carries a regression test for it. #18147 then
collected the same report from eleven more operators between 29 October
and 9 November, on `claude_local`, `codex_local`, `opencode_local` and
`grok_local`, on `2026.1023.0` and `2026.1106.0`.

**Paperclip version or commit** — `v2026.1001.0`; merged with `master`
at `629281b1e8a4bae014d682a99aa6cd790508414d`.

**Deployment mode** — Self-hosted server. **Database mode** — Embedded
Postgres. **Access context** — Board (human operator).

**Agent adapter(s) involved** — Not adapter-specific (core bug).
Observed on `codex_local` and `claude_local`; the gate is
adapter-family-level.

## What Changed

- `server/src/services/cancelled-native-startup.ts`: a new
`legacyBeforeDispatch` proof inside `isCancelledNativeStartup`. No gate
is relaxed and no new bypass is added — the `cancelledStartup` branch in
`admitExplicitNativeContinuation` already guards the
`process_identity_missing` block, so the proof belongs in the proof
function. That also makes explicit Retry work on a thread that is
already stuck, and lets a pause or terminate waiting on such a run
complete.
- The same file: `legacyBeforeDispatch` joins
`historicalBeforeSelection` in the "no environment lease rows"
condition, because this fixture settles without a
`startupPreparationSettledAt` marker. It carries the same earlier-boot
requirement, which is what makes that exemption safe. The live-lease
check, the `pendingCleanupInFlight` check and the shared
`nativeStartupHasExecutionEvidence()` contradiction check all still
apply to it unchanged.
- `server/src/services/conversation-continuation.ts`:
`conversationRecoveryActionPredicate()` gains a matching arm. It
previously retired a cancelled run's hold only on
`result_json.executionCancellation.state = 'acknowledged'`, which a run
that never dispatched can never record. The SQL mirrors the TypeScript
proof field for field, including the earlier-boot requirement, and
reuses the shared `executionStartedEventPredicate()` for the
contradictory-event exclusion rather than carrying its own event list.
This arm is what lets the thread recover without waiting for a user
message.
- `server/src/services/explicit-native-continuation.test.ts`: one
positive fixture in both observed shapes (fence present with the runtime
unresolved, and no fence with the runtime resolved) × explicit message
and Retry, plus 17 negative kinds in both shapes.
- `server/src/modules/agent-lifecycle/__tests__/lifecycle.test.ts`: one
case for the pause symptom — `agentExecutionsHaveStopped()` returns
`true` for a turn cancelled at `preparing`, and still `false` once the
same row reaches `dispatching`.
- Per `CONTRIBUTING.md` this revision carries no code comments; the
rationale that earlier revisions kept inline is in this description.

The proof requires **all** of:

- `status = cancelled` with `finished_at` set, `runtime_mode = legacy`,
and `execution_stage = preparing`
- `process_pid`, `process_group_id`, `process_started_at`,
`native_session_id`, `native_issue_id` and `session_id_after` all null,
and no finalization coordinator row
- the claimed adapter is a conversation adapter — the immutable claim on
the run, never the agent's current adapter
- `controller_boot_id` set and **not equal to this boot's id**, with
`controller_lease_expires_at` in the past
- every environment lease released with no cleanup in flight, or an
exact remote termination receipt. The SQL arm is stricter: it retires
the hold only when every lease is a cleanly released local lease, so a
remote lease always leaves the hold to the TypeScript proof, which
checks the receipt
- **no** contradictory run event, as defined by the shared
`executionStartedEventPredicate()`

The pid-alive, process-group-alive and environment-lease gates are
untouched, and `getConversationOwnershipBlocker` is unchanged.

**Two splits remain on offer**, either of which I will carry out on
request:

1. TypeScript proof first, SQL arm as a follow-up. The proof alone fixes
explicit Retry and the pause hang; @naeemakhtar110 has run that split in
the field.
2. A forward-looking receipt instead of, or ahead of, the historical
proof: have Stop write the `legacy-preparation-settlement.v1` style
not-dispatched receipt when it cancels a `preparing` conversation turn,
and let both `agentExecutionsHaveStopped()` and the recovery predicate
accept it. That gives new runs a positive receipt in core's existing
shape. It does not help the rows already on disk, which is what the
eleven reports on #18147 are about, so this PR keeps the historical
proof as `historicalBeforeSelection` does.

## Verification

Run against this head, merged with `master` at `629281b1e`, Node
24.20.0, embedded Postgres, after `pnpm run preflight:workspace-links &&
pnpm --filter @paperclipai/plugin-sdk ensure-build-deps` as CI does:

- `pnpm --filter @paperclipai/server exec vitest run
src/services/explicit-native-continuation.test.ts` — **whole file
passes** on head `8af8e699d` (474 cases with the lifecycle file: 550 of
551 together; the one failure, `restores hidden setup values when a
native Codex record uses the Codex onboarding choice`, needs a Codex
runner and fails the same way with stock `master` test files). The new
cases are `recovers a conversation turn cancelled before dispatch
through an explicit message|retry (fence: true|false)` and `holds a
conversation turn cancelled before dispatch with contradictory or
incomplete <kind> evidence (fence: true|false)` for `dispatching`,
`no_stage`, `native_mode`, `process_adapter`, `runner_adapter`,
`no_adapter`, `missing_boot`, `current_boot`, `missing_lease`,
`live_lease`, `session`, `launch`, `invoked`, `coordinator`, `cleanup`,
`remote` and `remote_released`.
- `pnpm --filter @paperclipai/server exec vitest run
src/modules/agent-lifecycle/__tests__/lifecycle.test.ts -t "cancelled
before dispatch"` — **passes**, and ****fails `expected false to be
true` with master's stock `cancelled-native-startup.ts` swapped in**
(negative control re-run on this master)**. That is the negative control
for the pause symptom: restoring the stock proof file reproduces the
hang.
- `pnpm --filter @paperclipai/server exec tsc --noEmit -p tsconfig.json`
— **306 errors on stock `master` and 306 on this branch, sorted error
lists identical** — all pre-existing, stale generated declarations in
packages this PR does not touch; zero added and zero in the five changed
files.
- Earlier revisions on `master` `0cb3fc7db`: 320/320 on the same file;
the negative control for the earlier-boot requirement — removing
`run.controllerBootId !== legacyControllerBootId` from
`legacyBeforeDispatch` alone fails both `current_boot` cases with
`expected true to be false`; the patched proof run against the recorded
fields of **both** real stranded runs admitted both and rejected 23
relaxations.

**Remaining limits.** We have not run the full suite or the e2e jobs
locally, only the two affected files plus the server typecheck; CI
covers the rest. The previous head (`a2a1721`) was green on all 56
checks; CI on `5da10435d` was green on every Paperclip gate; CI on
`8af8e699d` is running at the time of writing and the checklist below
will be updated when it reports.

## Risks

- Medium, and concentrated in the SQL predicate. If that arm is wrong it
could retire a hold too early. It is bounded: it adds one `and(...)` arm
to an `or(...)` that is already scoped to `cause =
'legacy_execution_requires_reconciliation'`, and it keeps process
liveness and lease cleanup with `getConversationOwnershipBlocker`. It is
covered by the positive and the 34 negative cases above. Reviewers may
still prefer to take the TypeScript proof alone first and the SQL arm in
a follow-up; that alone fixes the user-visible hold on the next message
and the pause hang.
- Low for the TypeScript proof. It narrows to a shape a dispatching run
cannot reach: a terminal `legacy` row that stopped at `preparing`, with
no identity of any kind, an elapsed controller lease from an earlier
boot, and no dispatch event. One deliberate difference from
`historicalBeforeSelection` remains and is worth a reviewer's attention:
it does not require the `startupCancellation` fence or an unresolved
runtime, because neither exists on the second occurrence above.
- **A known residual, inherited rather than introduced.** The
earlier-boot requirement proves a dead preparer only in a single-process
deployment. With replicas, another boot's executor can still be inside
an uninterruptible provider acquisition while this one evaluates
recovery, and the sandbox and plugin drivers insert the lease row only
after the provider answers — so an empty lease list is not proof that
none is coming. That window applies equally to
`historicalBeforeSelection` on `master` today. The durable fix belongs
at the insert rather than in any proof: reject an environment lease
insert whose run is already terminal, inside the transaction, as
`assertCompanyBinding` already re-reads the company binding there,
letting the existing `cleanUpRejectedOrphanSandbox` path tear down the
provisioned resource. Deliberately not bundled here, because it touches
the shared acquisition path for every driver; happy to send it as its
own PR.
- No migration. No schema change. No behavior change for any run that
reached dispatch.

## Model Used

Claude Opus 5 (`claude-opus-5`, Anthropic) for the original change;
Claude Fable 5.1 (`claude-fable-5-1`, Anthropic) for this rebase. Both
with extended thinking and tool use, driven through Paperclip's
`claude_local` adapter.

## 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 — the two affected test
files and the server typecheck; see Verification for what is still unrun
- [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 — running on this head; the
previous head (`a2a1721`) was 56/56
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups —
re-review pending on this head; the previous head was 5/5 with both P1
threads resolved
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: crownlayerapp <323182007+crownlayerapp@users.noreply.github.com>
2026-12-04 21:21:42 -08:00
Andrii Furmanets dbfcbb532b fix: key dashboard task cards by the native issue id (#15032)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The dashboard draws one task card per issue
> - `selectDashboardRunIds` reads only `contextSnapshot.issueId`
> - A native run stores the task on `nativeIssueId`
> - Older runs store it on `contextSnapshot.taskId`
> - The same task is then drawn as two cards
> - This pull request coalesces the bound issue id, then native issue
id, then context issue id, then task id
> - The benefit is that one task has one dashboard card

## Linked Issues or Issue Description

No open issue covers this. I searched open and closed issues and pull
requests.

**What happened?**

Dashboard task cards ignore the bound and native issue ids.
`selectDashboardRunIds` uses only `contextSnapshot.issueId`. Recovery
already reads `nativeIssueId`, then the context issue id, then `taskId`.
A native or bound run and a context run for the same task both take a
card slot.

**Expected behavior**

Use `coalesce(issueId, nativeIssueId, contextSnapshot.issueId,
contextSnapshot.taskId)` for the card key. Two runs for the same task
collapse to one card.

**Steps to reproduce**

1. Insert two runs for one company with the same `nativeIssueId`.
2. Give them different `contextSnapshot.issueId` values, or omit
`issueId` and set `taskId`.
3. Call `selectDashboardRunIds` with a small limit.
4. Observe that both runs are selected.

**Paperclip version or commit**

master at 215586d127

**Deployment mode**

Local dev (pnpm dev)

## What Changed

- Add `dashboardTaskIssueId`: the bound `issue_id` column first, then
the recovery coalesce order.
- Use it in `selectDashboardRunIds`.
- Add a test that collapses a native pair and a task-id pair, and keeps
a different context issue separate.
- Add a test that collapses a run bound to an issue with a context run
for the same issue.
- After merging master, the live-runs route keeps master's `issueId`
column (the bound `issue_id`), since the run read check uses it.

## Verification

- `pnpm exec vitest run src/__tests__/dashboard-service.test.ts --config
vitest.config.ts` in `server`
- Result: 1 file passed, 6 tests passed

## Risks

- Only card selection changes. The live-runs response and its read check
are unchanged from master.

## Model Used

- No model runtime is part of this change.

## Checklist

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

> - The health endpoint reports database backup status.
> - Backup directories and marker files may live on slow storage.
> - Synchronous filesystem reads hold Node's event loop during each
check.
> - Other requests wait behind that filesystem work.
> - Await filesystem operations and preserve the existing health
response.

## Linked Issues or Issue Description

**What happened?** A backup-health check scans and reads files
synchronously on the HTTP event loop.

**Expected behavior:**
Filesystem work yields so unrelated timers and requests can proceed.

**Steps to reproduce:**
Enable database backup health with a slow backup directory, request
`/api/health`, and observe unrelated event-loop work waiting for
synchronous filesystem calls. The regression deterministically holds an
asynchronous directory read and verifies another timer can run before it
completes.

**Paperclip version or commit:**
`master` at `a027f76a7`.

**Deployment mode:**
Built from source; tested using temporary backup files and controlled
filesystem responses.

Related PRs #13308 (empty archive health) and #10736 (backup retention)
address different backup behavior. This change leaves archive validation
and retention policy alone; those branches may need small textual
reconciliations if merged first.

## What Changed

- Use `node:fs/promises` for directory enumeration, file metadata and
failure markers.
- Scan archive metadata in batches of at most four reads to bound
filesystem work while allowing parallel I/O.
- Await the result in the health route.
- Treat only missing files as absent, including files removed by
retention during enumeration.
- Preserve warnings for actual filesystem failures and existing
newest-file/marker behavior.
- Add coverage for freshness, missing directories, marker text, read
errors, retention races, bounded scan concurrency and event-loop
progress.

## Verification

- Backup-health and health route suites (4 files): 35 passed.
- The event-loop regression fails with the original synchronous service.
- The archive-only concurrency regression also fails against the
sequential scan; optional marker reads cannot mask that failure.
- `pnpm --filter @paperclipai/server typecheck`: passed.
- `git diff --check`: passed.
- Refreshed with upstream `master` at
`7d59de6113caf5219d34d65e1fb5f0c1a7fbdc2a`, which includes the Runner
qualified-command fixture fix. The fresh branch diff remains limited to
this fix and its tests.
- Re-ran all four focused suites on
`8e96930537774ac4623cd493ba065b8a6f5d3269`: 35 passed. The first
[refreshed CI
run](https://github.com/paperclipai/paperclip/actions/runs/37038481259)
passed every test gate except the touch-picker browser shard. The
failure screenshot shows the last option already visible at the scroll
boundary. The source-identical retry at
`eeaeb752a36e0acd5129b6c6bce40e24fdefe1bd` [passed all
CI](https://github.com/paperclipai/paperclip/actions/runs/37040261790),
including the touch-picker shard, both Runner shards, build, typecheck,
server suites, canary dry run and the final aggregate.
- Greptile is 5/5 and all review threads are resolved.

## Risks

The internal inspection helper now returns a Promise; its route caller
awaits it. The response schema and freshness threshold are unchanged. No
database migration or cache is introduced.

## Model Used

OpenAI GPT-6 through Codex, with reasoning, Git and code execution
tools. The exact deployment identifier and context-window size are 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, including the available 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
- [x] I have described the issue using the bug report fields
- [x] I have not referenced internal/instance-local Paperclip issues or
links
- [x] My branch name describes the change and contains no internal
ticket ID
- [x] I have run tests locally and they pass
- [x] I have added a regression test
- [x] I have documented the affected request behavior and risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open findings
- [x] I will address reviewer comments before requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-12-04 20:56:21 -08:00
paperclipbugbotandClaude Opus 5.5 3ecc2dffff test(native-runtime): cite a saved request in the human-owned blocker corpus case (#23853)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 04:42:40 +00:00
Dotta 3befcd245b feat(connections): add LinkedIn REST connector (v1 personal posting) (#23388)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - App connectors let agents call external APIs under company/user
grants, risk classification, and audit governance
> - LinkedIn does not publish an official remote MCP server, and its
public API separates self-serve personal posting (`Share on LinkedIn`)
from vetted commercial Company Page management (`Community Management
API`)
> - Users want a governed native LinkedIn connector without waiting
weeks for commercial review or relying on ToS-violating scrapers
> - This pull request adds a reviewed native LinkedIn REST adapter
(`server/src/services/connectors/linkedin/`) registered in
`rest-registry.ts`, extracts a shared governed REST transport
(`server/src/services/connectors/rest-transport.ts`) used by LinkedIn,
Vercel, and Supabase, and wires managed Paperclip Cloud OAuth
(`linkedin.share`) plus customer-owned OAuth fallback
> - The benefit is governed personal LinkedIn publishing
(`linkedin_get_profile`, `linkedin_create_post`, `linkedin_delete_post`)
with S4 destructive classification, shared transport security
guarantees, and clean expansion room for v2 Company Page support

## Linked Issues or Issue Description

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

**Problem or motivation**
Paperclip has no native LinkedIn connector. LinkedIn does not publish an
official remote MCP server, and standard self-serve OAuth requires a
pre-registered LinkedIn Developer App with exact callback URIs and
explicit governance for public broadcasts.

**Proposed solution**
Add a reviewed native LinkedIn REST adapter
(`server/src/services/connectors/linkedin/`) in `rest-registry.ts`
supporting v1 self-serve OIDC Sign In + Share on LinkedIn (`openid`,
`profile`, `email`, `w_member_social`), backed by a shared governed REST
transport (`server/src/services/connectors/rest-transport.ts`) shared
across LinkedIn, Vercel, and Supabase, paired with the `linkedin.share`
managed OAuth profile in `paperclip-cloud` and a customer-owned OAuth
fallback.

**Alternatives considered**
- Remote MCP: ruled out because LinkedIn has no official MCP server.
- Waiting for Community Management API review before v1: deferred to v2
so personal posting ships now without blocking on commercial app review.

## What Changed

- Extracted shared governed REST transport
(`server/src/services/connectors/rest-transport.ts` and
`rest-transport.test.ts`) owning pre-`Headers` Bearer validation, token
redaction in strings and object keys, origin/prefix pinning, `redirect:
"error"`, deadline racing with forged-504 rejection, input/output byte
caps with reader cancellation, and unified write uncertain-outcome
(`408`/`5xx`/unparseable 2xx) handling; converged LinkedIn, Vercel, and
Supabase adapters onto it.
- Added reviewed LinkedIn REST adapter
(`server/src/services/connectors/linkedin/catalog.ts`, `index.ts`,
`index.test.ts`) using `LinkedIn-Version: 202611` and registered it in
`server/src/services/connectors/rest-registry.ts`:
- `linkedin_get_profile` (`read`, also powers `probe()` via `GET
/v2/userinfo`)
- `linkedin_create_post` (`destructive`, S4; derives `author` URN from
authenticated grant via `POST /rest/posts`)
- `linkedin_delete_post` (`destructive`, S4; validates post URN via
`DELETE /rest/posts/{encoded_urn}`)
- Added `packages/shared/src/linkedin-connectors.ts` (`linkedin.share`
profile & scopes) and exported from `packages/shared/src/index.ts`.
- Wired `linkedin` / `linkedin.share` into
`server/src/services/paperclip-cloud-connector.ts`,
`server/src/services/tool-access/oauth/client-settings.ts` (with
exhaustive `managedConnectorIssuer` mapping), and
`server/src/services/tool-access/oauth/authorization-start.ts`.
- Added official sanitized LinkedIn SVG
(`ui/public/brands/apps/linkedin.svg`) and registered it in
`ui/public/brands/apps/manifest.json`.
- Added reviewed catalog override
(`scripts/app-definition-overrides/linkedin.json`), regenerated
`packages/shared/src/app-definitions/linkedin.json` and
`app-definitions.generated.ts`, added `"linkedin"` to
`CONNECTABLE_APP_SLUGS`, and added permission reviews in
`doc/connections/tool-method-permission-reviews.json`.
- Added `doc/connections/LINKEDIN.md` and indexed it in
`doc/connections/README.md`.
- Merged `master` and resynced
`tests/runner-e2e/source-sdk-public-inputs.json`.

## Verification

- `node scripts/check-app-brand-assets.mjs` — passed (115 brand
identities validated)
- `node tests/runner-e2e/source-sdk-public-inputs.mjs $(git rev-parse
HEAD) --check` — passed (`changed: false`)
- `pnpm --filter @paperclipai/shared typecheck && pnpm --filter
@paperclipai/server typecheck && pnpm --filter @paperclipai/ui
typecheck` — passed
- `pnpm exec vitest run
server/src/services/connectors/rest-transport.test.ts
server/src/services/connectors/linkedin/index.test.ts
server/src/services/connectors/vercel/index.test.ts
server/src/services/connectors/supabase/index.test.ts
server/src/services/tool-access/oauth/client-settings.test.ts
server/src/services/paperclip-cloud-connector.test.ts
server/src/__tests__/connector-tool-policy.test.ts
packages/shared/src/app-definitions.test.ts` — passed (8 files, 248/248
tests)
- `pnpm exec vitest run ui/src/lib/app-brand-assets.test.ts --project
@paperclipai/ui` — passed (7/7)
- `pnpm verify --explain` — exit 2 (global CI input
`doc/connections/tool-method-permission-reviews.json` changed; full CI
`ci / verify` and `ci / e2e` running on current head `cc7e3a8184`)
- **Live-provider proof (human-gated — pending):** Registering
Paperclip's LinkedIn Developer App + AWS Secrets Manager credentials on
`paperclip-cloud` (companion PR) and completing an interactive OAuth
sign-in on a real LinkedIn account are required before live-account
acceptance.

## Risks

- LinkedIn posts are public external broadcasts (S4); both
`linkedin_create_post` and `linkedin_delete_post` are classified
`destructive`, and `author` is always derived from the authenticated
grant rather than caller input.
- Standard self-serve LinkedIn tokens expire every 60 days without a
refresh token; UI copy and docs state this explicitly.
- Extracting `rest-transport.ts` touches Vercel and Supabase adapters
alongside LinkedIn; all three adapters' unit suites (80 tests combined)
plus dedicated `rest-transport.test.ts` pass and preserve existing
status/error codes while extending unified write
`408`/`5xx`/unparseable-2xx uncertain-outcome protection.
- Deploy the companion `paperclip-cloud` PR (`feat/linkedin-connector`)
and configure LinkedIn client credentials before enabling `managed`
sign-in on Cloud stacks.

## Model Used

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

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
2026-12-05 03:07:21 +00:00
DottaandPaperclip 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>
2026-12-04 20:38:15 -06:00
Dotta 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
2026-12-04 20:37:16 -06:00
Nicky Leach 238e4779af Keep answered chat turns settled across later status changes (#23815) 2026-12-04 18:33:25 -08:00
Dotta 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
2026-12-04 20:08:57 -06:00
Dotta 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
2026-12-04 20:05:31 -06:00
Dotta b85e189408 perf(runner,native-runtime): silence AJV format warnings, cache validators, and retain released catalogs (#23812)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The server and Runner validate assigned MCP tool input schemas with
AJV and project shared frozen tool catalogs into native sessions
> - Today, AJV runs with `validateFormats: true` and no registered
formats, so every tool schema with `format` keywords (such as `uuid` or
`date-time`) emits two synchronous `console.warn` lines per property
while still ignoring those formats
> - Each call to `admitToolInputSchema` also recompiles identical
schemas from scratch, `resolveAssignedCatalog` evicts a shared catalog
as soon as its last active session closes (so back-to-back runs rebuild
the catalog every time), and `createAssignedMcpTools` logs the
over-budget and uncompilable schema warnings on every run even on a
cache hit
> - Together these issues produce heavy synchronous stderr/log churn and
repeat CPU and allocation work on sequential runs
> - This pull request disables AJV format lookup in
`tool-input-schema.ts`, adds a bounded compiled-validator LRU cache with
isolated error state, retains explicitly closed assigned catalogs in a
bounded short-TTL warm LRU, and deduplicates catalog schema warnings per
`(gatewayPublicId, catalogKey)`
> - The benefit is zero `unknown format` stderr warnings, up to ~27x
faster repeat schema admission, sequential catalog cache reuse across
back-to-back runs, and one warning per distinct gateway and catalog
instead of per-run log floods

## Linked Issues or Issue Description

Refs #21274, #21482. No separate public GitHub issue exists; the bug is
described below using the bug report template.

**What happened?**

During native agent runs that use assigned MCP tools with JSON Schema
`format` annotations (such as `"format": "uuid"` and `"format":
"date-time"`) or tool catalogs over the 768 KiB compile budget:
1. `admitToolInputSchema` in
`packages/paperclip-runner/src/drivers/tool-input-schema.ts` creates
`Ajv`, `Ajv2019`, and `Ajv2020` with `{ allErrors: true, strict: false,
addUsedSchema: false }`, leaving `validateFormats` at its default
(`true`) without registering any formats. AJV still ignores unknown
formats because `strict: false`, but writes two synchronous `unknown
format "..." ignored in schema at path "..."` `console.warn` lines per
property on every compilation.
2. Repeated calls to `admitToolInputSchema` for identical schemas re-run
AJV compilation (`new Function`) each time.
3. `resolveAssignedCatalog` in
`server/src/services/native-runtime/assigned-mcp-tools.ts` evicts the
shared catalog immediately when `holder.holders === 0`, so sequential
runs for the same company and unchanged tool listing never reuse the
frozen catalog.
4. `createAssignedMcpTools` logs `assigned MCP tools whose input schema
is over the compile budget are offered only through assigned-tool
search` and `assigned MCP tools whose input schema the Runner cannot
validate are not offered` unconditionally on every call, including cache
hits.

**Expected behavior**

1. `admitToolInputSchema` preserves exact validation behavior (ignoring
unregistered format annotations while still rejecting invalid non-string
`format` values via meta-schema validation) with zero `unknown format`
warnings.
2. Identical schemas reuse cached compiled validators in a bounded LRU
without sharing mutable `.errors` state or allowing mutation of the
cached schema.
3. Explicitly closed assigned tool catalogs stay warm in a bounded
short-TTL LRU so sequential runs reuse the frozen catalog when the fresh
gateway listing is unchanged, while expired or changed catalogs rebuild
cleanly and idle processes hold no background polling timers.
4. Catalog schema warnings log once per distinct `(gatewayPublicId,
catalogKey)` within a bounded deduplication window instead of flooding
logs on every run.

**Steps to reproduce**

1. Call `admitToolInputSchema` on 50 schemas containing `format:
"uuid"`, `format: "date-time"`, and `format: "email"` across 20
iterations (1,000 admissions) and count `console.warn` lines matching
`unknown format`.
2. Call `createAssignedMcpTools` 20 times sequentially (`close()` after
each call) for the same `companyId` and `gatewayPublicId` with an
unchanged listing over the 768 KiB compile budget and with an
under-budget listing, counting `logger.warn` lines and schema object
reuse across runs.

**Paperclip version or commit**

Reproduced on `master` at `306437a2a5`.

**Deployment mode**

Self-hosted server / Local dev (`pnpm dev`).

## What Changed

- `packages/paperclip-runner/src/drivers/tool-input-schema.ts`:
- Pass `validateFormats: false` to `Ajv`, `Ajv2019`, and `Ajv2020`
compilers.
- Add a bounded compiled-validator LRU cache
(`TOOL_INPUT_SCHEMA_CACHE_MAX_ENTRIES = 512`,
`TOOL_INPUT_SCHEMA_CACHE_MAX_BYTES = 16 MiB` serialized schema bytes)
keyed by canonical dialect and SHA-256 of the normalized schema JSON,
including caching `uncompilable` outcomes and skipping `$async` schemas.
- Deep-freeze cached compiled schemas after `forgetCompiledSchema` and
wrap cached `ValidateFunction` instances in `isolatedValidator` so each
caller has independent `.errors` state and cached validators retain no
prior error arrays.
- Export `toolInputSchemaCacheStats`,
`TOOL_INPUT_SCHEMA_CACHE_MAX_ENTRIES`, and
`TOOL_INPUT_SCHEMA_CACHE_MAX_BYTES` for verification.
- `packages/paperclip-runner/src/drivers/tool-input-schema.test.ts`:
- Add tests covering zero `unknown format` warnings across all three
dialects while preserving validation and rejecting invalid non-string
`format` values.
- Add tests covering validator cache reuse (including `$schema` fragment
normalization, `uncompilable` caching, and uncached `$async` schemas),
isolated `.errors` state, frozen `validate.schema`, independent
`admission.schema`, and cache bounds.
- Give each `reserved $id` iteration a unique `title` so every iteration
still compiles fresh on the compiler.
- `server/src/services/native-runtime/assigned-mcp-tools.ts`:
- Retain explicitly closed shared catalogs in a bounded warm LRU
(`ASSIGNED_CATALOG_RETAIN_ENTRIES = 64`, `ASSIGNED_CATALOG_RETAIN_BYTES
= 32 MiB`, `ASSIGNED_CATALOG_RETAIN_TTL_MS = 60_000`) promoted back to
active `sharedCatalogs` on sequential hits and invalidated automatically
whenever the fresh gateway listing changes `identity`.
- Unregister the `collectedCatalogs` `FinalizationRegistry` token
(`catalog`) in `forgetSharedCatalog` and before re-registering in
`shareAssignedCatalog` so repeated sequential warm reuses never
accumulate live registrations.
- Keep `FinalizationRegistry` GC drop callbacks (`drop` from
`createSessionRelease`) in a separate lexical scope with no reference to
`assigned` or `catalog`, releasing holds without retaining abandoned
sessions.
- Manage warm TTL expiry with lazy pruning on lookup/insert plus one
per-entry `.unref()` `setTimeout` cleared in `forgetRetainedCatalog` on
hit, eviction, or expiry. Keep `assignedRetainedCatalogCacheStats()`
read-only.
- Deduplicate `unavailable` and `unchecked` `logger.warn` emissions per
`(gatewayPublicId, catalogKey)` in a bounded LRU
(`ASSIGNED_CATALOG_WARNING_CACHE_ENTRIES = 512`,
`ASSIGNED_CATALOG_WARNING_DEDUP_MS = 10 * 60_000`).
- `server/src/services/native-runtime/assigned-mcp-tools.test.ts` and
`server/src/services/native-runtime/assigned-mcp-tools-cache.test.ts`:
- Split `describe("shared assigned tool catalogs")` into
`assigned-mcp-tools-cache.test.ts` (353 lines), reducing
`assigned-mcp-tools.test.ts` from 980 to 808 lines.
- Add fake-timer tests verifying timer-driven and lazy warm catalog TTL
expiration, invalidation on listing changes, bounded
`FinalizationRegistry` registrations across 50 sequential warm reuses,
and per-`(gatewayPublicId, catalogKey)` warning deduplication and window
expiry.

## Verification

### Local Before vs After Benchmark

Measured in the worktree against `306437a2a5` (before) and `2b3757ad58`
(after):

| Workload | Metric | Before | After |
| --- | --- | ---: | ---: |
| `admitToolInputSchema` (50 schemas w/ 4 format fields × 20 calls) |
`unknown format` warnings (cold 50 / total 1,000) | 400 / 8,000 | **0 /
0** |
| `admitToolInputSchema` (950 repeat admissions) | Total wall time |
144.44 ms | **5.28 ms** (27.4× faster) |
| `createAssignedMcpTools` over-budget (120 tools × ~6.7 KiB, 20
sequential runs) | `unknown format` warnings | 672 | **0** |
| `createAssignedMcpTools` over-budget (20 sequential runs) |
Compile-budget `logger.warn` count | 20 | **1** |
| `createAssignedMcpTools` over-budget (runs 2–20) | Median / total time
| 1.35 ms / 29.07 ms | **1.18 ms / 23.52 ms** |
| `createAssignedMcpTools` under-budget (50 tools × ~1 KiB, 20
sequential runs) | Sequential catalog cache hits | 0 / 19 | **19 / 19**
|
| `createAssignedMcpTools` under-budget (runs 2–20) | Median / total
time | 0.34 ms / 6.81 ms | **0.29 ms / 5.66 ms** |

Memory benchmark (`NODE_OPTIONS="--expose-gc" npx tsx
scripts/benchmark-assigned-mcp-tools-memory.ts --tools 80 --schema-bytes
2048 --sessions 50 --turns 10`):
- `sharedAcrossTurns: true`, `retainedBytesPerSession: 10052`,
`bytesStillHeldAfterRelease: 321248` (unclosed sessions released on GC
without entering warm retention).

### Automated Tests & Checks (on head `687fe283be`)

- `pnpm --filter @paperclipai/paperclip-runner exec vitest run
src/drivers/tool-input-schema.test.ts
src/drivers/runner-tool-bridge.schemas.test.ts`: 2 files, 26 passed.
- `pnpm --filter @paperclipai/server exec vitest run
src/services/native-runtime/assigned-mcp-tools.test.ts
src/services/native-runtime/assigned-mcp-tools-cache.test.ts`: 2 files,
80 passed.
- `pnpm --filter @paperclipai/paperclip-runner run
typecheck:typescript`: passed.
- `pnpm --filter @paperclipai/server exec tsc --noEmit`: passed.
- `pnpm check:module-boundaries`: passed.
- `node scripts/check-test-budget.mjs --base origin/master`: passed (`2
test file(s) checked`).
- `node tests/runner-e2e/source-sdk-public-inputs.mjs "$(git rev-parse
HEAD)" --check`: passed (`changed: false`).

### Operational Assumptions & Sleep Safety

- **Format validation parity:** `tool-input-schema.ts` never registered
`ajv-formats` and ran with `strict: false`, so format keywords were
never enforced before this change. Verified with real `Ajv`, `Ajv2019`,
and `Ajv2020` instances across all shared fixtures plus explicit format
tests.
- **Warm retention lifecycle (`sleep-aware-background-work`):** Trigger
is explicit `assigned.close()` releasing the last active holder
(`holders === 0`). Source of truth for tool grants remains the fresh
gateway listing on every `createAssignedMcpTools` call. Pending-work
predicate is `retainedCatalogs.size > 0`, with one `.unref()`
`setTimeout` per retained entry (at most 64 entries, 60s TTL), cleared
immediately in `forgetRetainedCatalog` on hit, eviction, or expiry. When
all retained entries expire or are promoted back to active, zero timers,
SQL queries, or network requests remain.
- **Remaining coverage:** Full repository test suites and build gates
run in CI on this revision.

## Risks

- **Frozen `validate.schema` in `tool-input-schema.ts`:** Cached
compiled schemas are deep-frozen before reuse so callers cannot corrupt
shared cache entries. All in-repo consumers (`admitToolInput`,
`toolInputError`, `RepeatedToolInputRejectionGuard`) only read
`validate.schema`, and `admission.schema` remains a fresh unfrozen
clone. Any future consumer attempting to mutate `validate.schema` will
get a `TypeError` instead of silent cross-caller corruption.
- **Validator cache byte accounting:**
`TOOL_INPUT_SCHEMA_CACHE_MAX_BYTES` (16 MiB) accounts for serialized
schema JSON bytes rather than V8 compiled closure heap, and is paired
with a 512-entry cap so total validator memory stays bounded.
- **Warm catalog memory bound:** Released catalogs are held strongly for
up to 60 seconds, capped strictly at 64 entries and 32 MiB accounted
bytes, and cleared by per-entry `.unref()` expiry timers. Abandoned
sessions dropped without `close()` are never retained, and
`collectedCatalogs` unregisters tokens on release and re-share.
- **Warning deduplication window:** Repeated warnings for an unchanged
`(gatewayPublicId, catalogKey)` are suppressed for 10 minutes (bounded
at 512 entries). Changes to the tool listing or gateway ID log
immediately, and unchanged warnings re-log after the 10-minute window.
- **No database schema changes or migrations.**

> 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
2026-12-04 20:05:03 -06:00
DottaandPaperclip 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>
2026-12-04 20:04:57 -06:00
Dotta 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
2026-12-04 20:04:50 -06:00
Devin FoleyandPaperclip 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>
2026-12-04 17:56:22 -08:00
DottaandClaude Opus 5.5 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>
2026-12-04 19:52:12 -06:00
Eduardo Vasconcelosandcommitperclip[bot] 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 0f14d2612.

## What Changed

- `claude_local`: adds each mounted skill source to `managedPaths` as
`ro`.
- `codex_local`: mounts, read-only, the Paperclip source of each desired
skill. It does not mount what a `CODEX_HOME/skills/<name>` link resolves
to, because `CODEX_HOME` is writable in the sandbox and that target is
agent-controlled. When injection keeps a live link that resolves
elsewhere, the run logs a warning naming the skill.
- Tests in `claude-local-execute.test.ts` and
`codex-local-execute.test.ts` use a fake `bwrap` that records its argv
and check that each link target has a `--ro-bind`.
- A Bubblewrap confinement test reads the Claude bundle link from inside
a real sandbox. Like the adapter-utils sandbox integration test, it runs
when `PAPERCLIP_TEST_BWRAP` is set.
- `codex-local-execute.test.ts` checks the `bwrap` argv: a preserved
link to a host directory is not bound, a warning is logged, and the
Paperclip source is still bound. It runs in CI.

## Verification

- `cd server && npx vitest run
src/__tests__/claude-local-execute.test.ts
src/__tests__/codex-local-execute.test.ts
src/__tests__/codex-local-skill-injection.test.ts` passes (57 tests, 1
skipped without `PAPERCLIP_TEST_BWRAP`). With `PAPERCLIP_TEST_BWRAP`
set, all 58 pass.
- The argv test fails without the change (the host directory got a
`--ro-bind`). The Claude confinement test fails when the source mount is
removed.
- `tsc --noEmit` is clean for both adapter packages.
- Manual: on Ubuntu with bwrap, Claude and Codex agents loaded their
skills after I added the same paths through `filesystemExtraPaths`. This
change mounts those paths automatically.

## Risks

- Low risk. The mounts are read-only, and they contain only the skills
that the agent already gets through the links.
- Runs without a sandbox do not change.
- A custom link that an operator keeps in `CODEX_HOME/skills` and that
points outside the Paperclip skill sources is not readable inside a
workspace sandbox. The run logs a warning; add the directory through
`filesystemExtraPaths` if that link must work.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`, Anthropic), in Claude Code with
tool use (shell, file edit). A human reviewed the change.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [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: commitperclip[bot] <284812584+commitperclip[bot]@users.noreply.github.com>
2026-12-04 17:48:01 -08:00
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>
2026-12-05 01:44:29 +00:00
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>
2026-12-04 17:37:31 -08:00
馨冉and馨冉 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>
2026-12-04 17:35:55 -08:00