Commit Graph
8992 Commits
Author SHA1 Message Date
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
Tambria Kemp 66b97fb490 fix(plugin-sdk): do not stamp a finished invocation on a worker-to-host call (#17797)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Plugins run in a worker process. The host issues an invocation for
each request or event it delivers, and the SDK stamps that invocation id
on every worker-to-host call so the host can resolve the call's company.
> - Node propagates the ambient AsyncLocalStorage context into a timer
callback. A `setTimeout` or `setInterval` armed inside a handler
therefore still sees the invocation after the handler returned.
> - The SDK stamped it anyway. The host looked the id up, missed it, and
refused the call as "a missing, expired, or unknown invocation scope".
> - The host resolves a call that carries no id by the company the call
names. So a call that claimed nothing would have been allowed. A call
that claimed a dead invocation was not.
> - The symptom is quiet. The plugin's feature still works, but every
host call from its timer fails, and the work arrives late or not at all.
> - This pull request stops the stamp at the moment the handler returns.
The worker is the only side that knows when that happened.
> - The benefit is that a plugin author does not have to discover this
trap. Scheduled and deferred work in a plugin now behaves as the
specification describes.

## Linked Issues or Issue Description

Fixes: #17532

Related issues, each a different cause behind the same error string.
This change does not fix them:

- Refs #15765 — the host-side mirror. There the call carries **no** id,
and the `activeInvocations.size > 0` rule refuses it. Here the call
carries a **dead** id, and the lookup refuses it. Each fix leaves the
other bug standing.
- Refs #8633 — a polling loop started in `setup()`, which has no
invocation to inherit.
- Refs #9310 — `runJob` carries no scope.
- Refs #7897 — an SDK version that never echoes the id.

Related pull requests. I read all three before writing this one:

- Refs #10580 — the opt-in form of this fix. It adds
`ctx.runtime.runProactively(cb)` so an author can detach deliberately.
The two compose: that API lets an author drop the stamp *inside* a live
handler, and this change drops it only after the handler returned. This
one needs no plugin change, which matters because the trap is invisible
to the author.
- Refs #15925 — retires an event invocation scope when the worker
handlers settle. It is complementary, and it makes this fix more
necessary. Today a notification registers its scope with the maximum RPC
timeout and clears it only if the send throws, so a timer armed in an
event handler is admitted for up to 15 minutes. #15925 closes that
window. The dead-stamp refusal then appears on the event path too, and
this change is what prevents it. The two also work together in code:
this change marks the invocation finished before the notification
settles, so the settlement notification that #15925 sends goes out
unstamped and carries its id in the parameters, as it already does.
- Refs #8159 — a 5 second grace period after a scoped RPC settles. It
answers a different question. That window covers a nested request
already in flight when the response lands. It does not cover a timer
that fires seconds or minutes later. It also carries an unrelated
transaction change in `server/src/services/environments.ts`, and it has
conflicted since June.

## What Changed

- `packages/plugins/sdk/src/worker-rpc-host.ts`: a `WeakSet` of finished
invocation contexts, plus `liveInvocation()` at the two stamp sites and
`runInInvocationScope()` at the two scope-entry sites.
- The guard is keyed on the invocation context object, not on the id
string. Each delivery deserializes its own object. A second delivery
that carries the same id keeps its own stamp while its own handler runs.
- Both scope-entry sites are guarded. A host-to-worker notification also
runs its handler inside the invocation scope, and an event handler is a
normal place to arm a timer.
- `doc/plugins/PLUGIN_SPEC.md` gains §12.3.1. The contract said that a
call with no invocation is attributed by the company it names. It never
said which calls have no invocation, and not being able to tell is the
whole trap.
- No host change. No manifest change. No new dependency.

## Verification

```bash
cd packages/plugins/sdk
pnpm vitest run                 # 178 passed, 14 files
pnpm tsc --noEmit -p tsconfig.json   # clean
```

Red before green, which is the part worth checking:

- With the three new tests in place and `src/worker-rpc-host.ts`
restored to `master`, **two of the three fail**. The in-handler call
keeps its stamp and the timer's call keeps it too, which is the bug.
- The third test passes either way by design. It asserts that a live
invocation still stamps, and it is there to prove the guard does not
over-reach.
- The tests drive a real worker over a pair of pipes. The host side
answers every worker-to-host request and records the id on each
`state.get` request and each `execute.log` notification. One case enters
through a request, one through an event notification, and one runs two
deliveries that share an id.

## Risks

Low.

- The behaviour change is narrow. A worker-to-host call made after its
handler returned now goes out with no invocation id, where before it
went out with a finished one.
- The host already handles a call with no id. It resolves the company
the call names against the plugin's proactive company scopes, and it
refuses the call when that company is not configured. So a call that was
refused for a missing scope can now succeed, but only where the operator
already authorized that company. Where the operator did not, the call is
still refused. The line that refuses it changes; the answer does not.
- A call made inside a handler is unaffected. The stamp is dropped only
after the handler settles.
- The `WeakSet` holds no strong reference, so a finished invocation
context is still collected.

## Model Used

Claude Opus 5 (`claude-opus-5`), with extended thinking and tool use.
The model wrote the change and the tests, ran the verification above,
and read the three related pull requests before positioning this one. A
human reviewed all of it.

## 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
canary/v2026.1205.0-canary.899100
2026-12-05 02:27:22 -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
Dana63301 6a62ccdba5 fix(hermes): allow keyless local inference endpoints (#17477)
## Thinking Path

> - Paperclip is an open-source application for managing AI agents.
> - Paperclip uses adapters to connect to agent runtimes.
> - The Hermes adapter checks the local Hermes configuration.
> - Hermes can use Ollama on a local HTTP endpoint without a cloud API
key.
> - The adapter reports `hermes_no_api_keys` even when this local
configuration is valid.
> - This warning can mislead users during environment validation.
> - This pull request recognizes configured loopback inference
endpoints.
> - The change reduces false warnings and keeps warnings for remote
endpoints.

## Linked Issues or Issue Description
### Related pull requests

No existing public issue has been identified for this specific bug.

The following pull requests cover related Paperclip capabilities:

- #4654 — Related Hermes local-script functionality.
- #10260 — Native Ollama adapter support.
- #15565 — Model gateway documentation.
- #14154 — Hermes home-directory resolution.

These pull requests provide related context. None is a confirmed
duplicate of this fix.

This PR addresses the Hermes adapter's API-key validation for local
inference endpoints.

I reviewed `ROADMAP.md`. The roadmap lists Hermes as a supported
adapter, but it does not identify planned work for local inference
API-key validation.

**What happened?**

The Hermes adapter reports `hermes_no_api_keys` when Hermes uses a local
Ollama inference endpoint without cloud API credentials.

The warning appears during Paperclip's Hermes environment validation.

**Expected behavior**

Paperclip should not report missing cloud API keys when the requested
model uses a configured loopback inference endpoint.

Paperclip should continue to warn when the endpoint is remote or the
requested model does not match the detected model.

**Steps to reproduce**

1. Configure Hermes to use Ollama at `http://127.0.0.1:11434/v1`.
2. Configure Hermes to use a locally available model.
3. Do not configure cloud LLM API keys.
4. Run the Hermes adapter environment validation in Paperclip.
5. Observe the `hermes_no_api_keys` warning.

**Paperclip version or commit**

The bug was identified in the upstream Hermes adapter.

The fix is based on the upstream `master` branch and is available in
commit `cc34b2119`.

The exact upstream base commit has not been recorded in this
description.

**Deployment mode**

Local development.

**Agent adapter(s) involved**

Hermes.

**Database mode**

Not database-related.

**Relevant logs or output**

Before the fix: `hermes_no_api_keys`.

After the fix: `hermes_local_endpoint_no_api_key`.

**Relevant config (if applicable)**

The affected configuration uses:

- Inference provider: Ollama
- Inference endpoint: `http://127.0.0.1:11434/v1`
- Model: A locally available Ollama model
- Cloud LLM API keys: Not configured

The endpoint is a loopback address. Ollama serves the model locally.
This configuration does not require a cloud inference API key.

## What Changed

- Added exact loopback hostname checks for `localhost`, `127.0.0.1`, and
`[::1]`.
- Limited accepted endpoint schemes to HTTP and HTTPS.
- Added an informational validation result for matching local model
configurations.
- Preserved existing cloud API-key checks.
- Preserved warnings for remote endpoints and model mismatches.
- Added eight regression tests for valid and invalid endpoint
configurations.

## Verification

- Hermes adapter targeted tests: 15/15 passed.
- Hermes adapter TypeScript typecheck: passed.
- Repository-wide typecheck (`pnpm typecheck`): passed across all 35
participating workspace projects.
- Rust runner compilation: passed with non-blocking compiler warnings.
- Database migration safety checks: passed.
- `git diff --check`: passed.
- Repository-wide tests: server test failures occurred outside the
changed Hermes files. Their causes are not yet confirmed.

The targeted Hermes adapter tests and repository-wide typecheck passed.
The repository-wide test suite did not fully pass.

## Risks

Low risk. The change affects only Hermes environment validation.

The adapter accepts a configured loopback endpoint without requiring a
cloud API key. It does not verify that the endpoint is reachable or that
the inference server accepts requests without authentication.

The change does not modify model execution, credentials, or database
state.

## Model Used

Local inference using Tiel-Coder-35B-A3B-GGUF-MTP through LM Studio,
integrated with Cline in VS Code. The model assisted with code changes
and regression tests.

ChatGPT (GPT-6) assisted with review, test planning, and pull request
preparation.

## 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 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
Paperclip ticket id
- [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-05 02:06:50 -08:00
Jetandjet ed82614fae fix(pi): settle the run when the adapter fails before the provider (#17416)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Every agent run settles when it has a usage receipt, or when it
carries the proof that the provider was never reached
> - The Pi adapter can fail before it reaches the provider. Two
examples: the command is not resolvable, or the configured model is not
in `pi --list-models`
> - In that case the adapter throws. The server receives no result. The
terminal run then has no receipt and no proof of "no provider work".
> - The cost accounting sweeper skips such a run. The run never settles.
The budget gate counts it as unsettled spend and hard-stops the scope.
The agent cannot run again.
> - This pull request returns the bootstrap proof for that failure path.
> - The benefit is that a pre-provider failure settles at zero cost and
the agent keeps working.

## Linked Issues or Issue Description

Refs #15649

Related work and duplicates found in the pre-PR search:

- #17265 fixes the same failure class for the hermes adapter. This PR is
the Pi equivalent. It does not touch hermes.
- #15986 handles a cancelled run with partial usage. This is a different
case: the provider was reached there.

## What Changed

- Wrap the pre-flight checks in
`packages/adapters/pi-local/src/server/execute.ts` in one try/catch
block. The block covers command resolution and model availability.
- Return `executionRecovery: { kind: "bootstrap", providerWorkStarted:
false }` when a pre-flight check fails. Do not rethrow.
- Add `packages/adapters/pi-local/src/server/execute.bootstrap.test.ts`.
The test forces the model check to fail and asserts the bootstrap proof,
the exit code, and the log line.

## Verification

- Run `vitest run` in `packages/adapters/pi-local`. Result: 7 test
files, 63 tests, all pass.
- Run `tsc --noEmit` in the same package. Result: no errors.
- Manual reproduction on a self-hosted 2026.1023.0 instance, Pi adapter,
model not present in `pi --list-models`:
- Before the change: the run ends as `adapter_failed` with
`cost_accounting_pending = true`. `retry-accounting` returns
`{"accounted": false}` on every call. The scope stays paused.
- The same run row, with `usage_json.accountingProviderWorkStarted =
false` present, settles at zero cost. `retry-accounting` returns
`{"accounted": true}` and the scope resumes on the next wake.

## Risks

Low risk. The change touches only the code path before the provider
starts. Runs that reach the provider keep the current behaviour.

One behaviour change: a pre-flight failure now returns a result instead
of an exception. The run message becomes `Pi cannot start: <reason>`
instead of a bare `adapter_failed`. This message is the same shape the
hermes adapter uses.

## Model Used

- Provider: DeepSeek
- Model ID: `deepseek-flash`
- Reasoning: enabled
- Context window: 1M tokens

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

Co-authored-by: jet <jet@users.noreply.github.com>
canary/v2026.1205.0-canary.898600
2026-12-05 02:03:47 -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>
canary/v2026.1205.0-canary.898500
2026-12-05 00:20:57 -08:00
kaluli123123andkaluli123123 68533743a2 fix(ui): settle Files reports and preserve sidebar navigation (#17296)
## Thinking Path

> - Paperclip shows workspace files next to an agent task.
> - The Files browser reports its current folder and search to the task
panel.
> - New callback identities repeatedly report identical state and
rerender the panel.
> - A stale task callback can also replace a new sidebar destination.
> - This pull request fixes notification identity and stale-path
navigation together.
> - Files can stay open without trapping navigation on the task.

## Linked Issues or Issue Description

Fixes: #15620

Thanks to @nunobarrosmir for the local-build diagnosis of both
mechanisms in this Issue. Related merged #17068 stabilizes tab widths,
not this synchronization boundary.

## What Changed

- Use the existing callback-ref pattern so callback identity changes do
not report unchanged browse state. Real state changes reach the latest
callback.
- Reject viewer URL updates from an obsolete pathname. Migrate both
provider and task-panel guard callers.
- Add browser/provider and real TaskSidePanel regression coverage, and
update the development guide.

## Verification

- RED: 4 failed, 88 passed across the three focused files. Failures
included the real panel/browser update loop and stale-path navigation.
- GREEN: from ui, `pnpm exec vitest run
src/components/WorkspaceFileBrowser.test.tsx
src/context/FileViewerContext.test.ts
src/components/task-side-panel/TaskSidePanel.test.tsx` — 92 passed.
- `pnpm check:token-gates` — passed.
- Real Chromium smoke mounted the actual WorkspaceFileBrowser and
FileViewerProvider against local empty-workspace API fixtures. The
inline state-updating parent settled with one report. After clicking
Dashboard, invoking the previous task's saved browse callback left the
browser on Dashboard with no task-path replacement. Temporary fixture
files were removed. This was a focused component/provider surface, not a
complete authenticated task installation.
- Independent read-only review checked latest-callback ordering and all
guard callers; no concrete blockers.
- UI `tsc --noEmit` failed on missing SDK/generated Storybook artifacts
and dependency errors outside the changed files. It did not pass.
- Same-base full checks in the independent SSH-fix worktree hit
test/typecheck deadlines and ENOSPC during build. They are not passes
for this branch and were not repeated here.
- `git diff --check` passed before commit.

## Risks

- The pathname guard intentionally discards late task-state reports
after navigation.
- Same-task folder changes, current search, and close behavior retain
regression coverage.
- Full validation, CI, and Greptile remain gates. Draft, not
merge-ready.

## Model Used

OpenAI `openai-codex/gpt-6.1-sol`, tool use and code execution;
context-window size is not exposed by the harness. TypeSafe `jev-1.14.0`
supplied advisory approach selection.

## 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 linked the existing public Issue
- [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
- [ ] 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


## Append-only follow-up verification

- Appended commit `b14ebe622` without rewriting history. The existing
markdown-file-link fixture mocked a task pathname while jsdom remained
on `/`; it now models the actual browser pathname and restores the
original URL. This fixes the dependent regression without weakening the
stale-path guard.
- Four focused files now pass **102 tests**, including all 10
markdown-availability cases and the existing same-task/stale-path
navigation coverage.
- Original CI UI shard: 4,987 passed / 1 failed (the corrected fixture).
Server shard: 1,803 passed / 1 failed / 13 skipped, with
`login-cleanup-work.test.ts:119` observing active=1 instead of 0. E2E
shard: 15 passed / 1 failed / 1 skipped; `cases-read-only.spec.ts:130`
expected Done but saw All statuses, with an announcement handler also
active. The latter two are unchanged-area failures, not established
baseline failures, and remain gates.
- Replacement CI is pending. Prior UI typecheck/full-build limitations
remain. Draft, not merge-ready.

---------

Co-authored-by: kaluli123123 <295758798+kaluli123123@users.noreply.github.com>
2026-12-05 00:16:33 -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
Zhou rui 23ff8e8be6 fix(hermes): settle the run when the skills cannot be reconciled (#17265)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Every run has an accounting state, and the budget gate reads the
pending runs
> - A run settles when it has a usage receipt, or when it carries the
proof that the provider was never reached
> - The server writes that proof on every failure path that happens
before the adapter is entered
> - The Hermes adapter can also fail before it reaches the provider,
when it cannot reconcile the Paperclip-managed skills
> - The adapter threw that error, so the server received no proof and
the run stayed pending for ever
> - The budget gate then counts the run as unsettled spend, and it
hard-stops the agent, so the agent can never run again
> - This pull request reports the failure with the bootstrap result that
the server already understands, so the run settles

## Linked Issues or Issue Description

There is no public GitHub issue for this defect. The description below
follows `.github/ISSUE_TEMPLATE/bug_report.yml`.

**Pre-submission checklist**

- [x] I have searched existing open and closed issues and this is not a
duplicate. The repository was searched for the error text, for the
accounting states, and for the recovery record of the bootstrap. The
related items are listed at the end of this section. None of them covers
this case.
- [x] I am on the latest released version of Paperclip (or can reproduce
on `master`). The change is based on `master` at
`043f2514e67c50320433a0013fb228a75a51325c`. The new test fails on that
revision.
- [x] I have confirmed the error originates in Paperclip itself — not in
my agent adapter, API provider, or local configuration. The Hermes
adapter is part of this repository, not an external plugin. The defect
is in `packages/adapters/hermes/src/server/execute.ts`. The new test
fails on unmodified `master` and passes with the fix.

**What happened?**

The Hermes adapter failed during its bootstrap, before it called the
provider. The adapter threw the error, so the server received no proof
that the provider was never reached. The run stayed in the pending
accounting state for ever. The budget gate then hard-stopped the agent,
and the agent could not run again. The run could not be settled, and the
agent could not be resumed past the budget hold.

**Expected behavior**

A run that fails before the provider is reached must settle. The agent
must stay able to run after such a failure.

**Steps to reproduce**

1. Give an agent a Hermes adapter with a Paperclip-managed skill.
2. Make the reconciliation of that skill fail. One way is to let a real
directory occupy the runtime name of the skill in the skills home.
3. Start a run of the agent.
4. The adapter throws `Cannot reconcile Hermes skill "<key>" because
<target> is occupied by another installation.`
5. The run stays in the pending accounting state. The budget gate
hard-stops the agent.

**Paperclip version or commit**

`master` at `043f2514e67c50320433a0013fb228a75a51325c`.

**Deployment mode**

Self-hosted server.

**Installation method**

Built from source.

**Agent adapter(s) involved**

Hermes. The change is in `packages/adapters/hermes`, so no other adapter
changes.

**Database mode**

Not database-related.

**Node.js version**

v24.22.1 on the author's own host, where the tests ran before the push.

**Operating system**

Linux on the author's own host, where the tests ran before the push.

**Relevant logs or output**

The error in the step list above is the complete error from the adapter.
The run log then shows that the run never settled.

**Additional context**

Related pull requests and issues in this repository. This change does
not overlap with them.

- Refs #15649. That issue reports runs that stay in
`waiting_for_receipt` and that block the budget resume. It is the same
symptom. The cause there is a missing acknowledgement for the
`opencode_local` adapter. This change covers the Hermes adapter, which
fails before it reaches the provider.
- Refs #13807. That issue reports that a bundled skill release drift
throws and hard-fails every run. That throw happens in the run
preparation of the server. The server already records the proof on that
path. This change covers the adapter path.
- Refs #14234. That pull request stops the regeneration of holds for
settled runs that failed before the launch. It is server-side work on
the same area.

**Privacy checklist**

- [x] I have reviewed all pasted output for PII (usernames, file paths,
API keys, tokens, company names) and redacted where necessary. The
pasted output has no API key, no token, no company name, and no user
name. The company id, the skill key, the runtime name, and the temporary
folder name are replaced with placeholders.

## What Changed

- `packages/adapters/hermes/src/server/execute.ts`: a failure of the
managed-skills reconciliation no longer throws. The adapter returns a
result with `exitCode: 1` and the recovery record `executionRecovery: {
kind: "bootstrap", providerWorkStarted: false }`.
- `packages/adapters/hermes/src/server/execute.ts`: the error message
still goes to the log stream for stderr. The returned result carries the
text `Hermes cannot start: <reason>`.
- `packages/adapters/hermes/src/server/execute.skills.test.ts`: new test
file with one case. The case lets a real directory occupy the runtime
name of a managed skill, so the reconciliation fails. The test checks
that the adapter returns the no-provider-work proof instead of throwing,
and that the provider was never started - the promise the server settles
the run on. The mock of the child process would succeed silently if it
were called, so the test asserts on the mock itself.
- No code comments are added. The upstream contributing guide asks that
a pull request carries none, so the explanation of the failure mode
lives in this description.

## Verification

The commands below ran on the author's own Linux host, before the push.
They did not run on CI. The host used Node.js v24.22.1 and pnpm 12.14.0.
The tree was the upstream `master` revision
`043f2514e67c50320433a0013fb228a75a51325c`.

```sh
pnpm --filter @paperclipai/hermes-paperclip-adapter exec vitest run src/server/execute.skills.test.ts
```

Before the change, the new case failed. The failure was the production
error itself.

```
FAIL  src/server/execute.skills.test.ts > hermes-local adapter: the skills cannot be reconciled > reports the failure with the no-provider-work proof instead of throwing
Error: Cannot reconcile Hermes skill "<company-id>/<skill-key>" because <skills-home>/<runtime-name> is occupied by another installation.
 ❯ reconcileHermesPaperclipSkills src/server/skills.ts:242:13
 ❯ Module.execute src/server/execute.ts:370:30

 Test Files  1 failed (1)
```

The company id, the skill key, the runtime name, and the temporary
folder name are replaced with placeholders. The test uses fixed values
for them.

After the change, the file passes.

```
 Test Files  1 passed (1)
      Tests  1 passed (1)
```

The whole package was run in the state of this branch, and it is green.

```
 Test Files  11 passed (11)
      Tests  174 passed (174)
```

That run was repeated on the same host after the review, on Node.js
v24.16.0 with vitest 5.0.3, against the branch tree with the cost test
of the other pull request moved aside - that test belongs to a different
branch. The package copy was placed next to the original so that the
workspace links resolve the same way, and the instance that serves the
drill was not touched.

The assertion on the child process was checked to have teeth: with the
assertion inverted, the same file fails with `expected "vi.fn()" to be
called at least once`, so the mock really records the calls.

The wider suites of the two packages were not re-run for this pull
request. A recorded run of them shows failures that also exist on
unmodified `master` in the same environment. They concern the workspace
sync and the sandbox provisioning.

### The pull request carries no code comments

The contributing guide asks that a pull request adds no code comments,
so the explanatory blocks of this change were removed and the reasoning
moved into this description. The tree of the branch was rebuilt from the
branch content alone, and the whole package suite was run again on that
tree.

```
 Test Files  11 passed (11)
      Tests  174 passed (174)
```

The type check of the package passes as well.

```
cd packages/adapters/hermes
./node_modules/.bin/tsc --noEmit
```

## Risks

- The change is local to the Hermes adapter. No other adapter and no
server code changes.
- The adapter now reports the failure instead of throwing it. The run
still fails, and the agent still does not do the work. Only the
accounting state changes, because the run can now settle.
- The fix is in the adapter on purpose. A fix in the core would have to
guess whether an adapter that threw had already spent money. A wrong
guess under-bills. Only the Hermes adapter has this failure, and only
the adapter knows that the provider was never reached.
- If the server does not understand the bootstrap result, the run would
stay pending. The server already handles a result with `kind:
"bootstrap"` and `providerWorkStarted: false` on the failure paths that
happen before the adapter is entered.
- The upstream contributing guide asks that a pull request carries no
code comments, so this change adds none. The explanation that the code
would have carried lives in this description instead: the failure mode
is not obvious from the diff, so a reviewer has to read the description
above to follow the change.

## Model Used

- Provider: MiniMax
- Model id: `minimax-M3.1-Flash`
- Context window: not published in this environment. The size is
unknown.
- Reasoning mode: the environment does not expose a reasoning or
thinking mode for this model.
- Capabilities used: tool use, code execution, shell, file editing.

## 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 00:12:11 -08:00
43a3b12bd7 fix(claude-local): classify auth from provider evidence (#17229)
## Thinking Path

> - Paperclip manages work performed by AI agents.
> - The Claude CLI adapter converts provider output into run errors.
> - Ordinary transcript text can contain words such as `unauthorized` or
`login required`.
> - A max-turns result can also contain the model's last answer.
> - These words can mark a valid Claude connection as needing
reauthentication.
> - This change limits auth classification to failure evidence and
excludes max-turns summary prose.
> - Cleanup finalization and retry policy stay with their existing
owners.

## Linked Issues or Issue Description

Refs #5534, #15441, #15660, #14089, #13647, #17865.
Related cleanup work: Refs #15774, #14611, #13322, #13028.

**What happened?**

A successful Claude result followed by process cleanup at exit 143
received `claude_auth_required` because an unrelated tool transcript
contained `unauthorized`. A max-turns result can produce the same false
label when its summary quotes login or token-failure text.

**Expected behavior**

Use provider authentication evidence to decide whether Claude needs a
new login. Preserve a max-turns stop when only its summary mentions
auth. Preserve real provider auth errors. Leave cleanup outcome,
notification detection, and retry policy unchanged.

**Steps to reproduce**

Feed the adapter a successful result, transcript auth prose, and a
cleanup receipt. It must not report `claude_auth_required`. Feed it an
`error_max_turns` result whose summary says "The page says login
required for guests." or quotes an invalid bearer token. It must retain
`max_turns_exhausted`. The fixtures require no provider credentials.

**Paperclip version or commit**

The original reproduction used `def4726be`. The branch includes upstream
master `1ca90d2d6f`; the latest auth correction is `ae586d060d`.

**Deployment mode**

Local source-checkout verification with synthetic process receipts.

### Related PR boundaries

- #15660 overlaps the auth parser change. This alternative also excludes
max-turns summary text from both auth scans, ignores stderr after a
successful result, filters JSON records from eligible diagnostic
streams, and retains explicit terminal HTTP 401. Maintainers should
select or consolidate one parser implementation.
- #14089 adds an execution-level failure gate. It does not by itself
prevent transcript words from misclassifying a run that failed for
another reason.
- #17865 addresses max-turns classification and connection repair. This
PR excludes model summary prose while retaining separate provider auth
evidence. It does not change connection repair.
- #15774 owns a proposed cleanup success rule. This PR adds no cleanup
error code and no success promotion. It defines no new retryability
rule.
- #13322/#13028 concern synthetic task-notification results. This PR
does not change result selection or the cleanup trigger and does not
claim to fix that case.

## What Changed

- Match login markers against failed terminal fields and plain
failed-run stderr. Before a result exists, also accept plain startup
stdout. Exclude JSON transcript records from those diagnostic streams.
- Ignore successful answer text and successful-run stderr.
- Exclude max-turns `result` prose from both login-prompt and
token-failure scans. Reuse the existing structured max-turns detector.
- Retain explicit provider `error`/`errors`, terminal HTTP 401, and
plain CLI login diagnostics.
- Add parser and adapter regressions for summary prose, provider errors,
startup diagnostics, and cleanup receipts with exit 143, SIGTERM, or
SIGKILL.
- Incorporate [Bart Rozycki's
follow-up](https://github.com/TheJohnzo/paperclip/pull/1), including 33
synthetic scenarios and 76 detector/execution tests. Ignore stdout lines
beginning with `{` after trimming when no terminal result exists, so a
partial JSON tool event cannot become a login diagnostic. Stderr
continues to discard only valid JSON; malformed JSON-looking login
prompts there and in terminal results remain recognized.
- Keep upstream's deletion of the obsolete execution-semantics document
and upstream's shared CLI startup budget. The re-home fixture retains
only a workload explanation comment.

The Claude adapter owns this parsing. No shared contract or
orchestration change is needed. `execute.ts` matches upstream. Existing
exit codes, signals, and nested cleanup evidence remain intact.

## Verification

- At `ae586d060d`, `pnpm --filter @paperclipai/adapter-claude-local exec
vitest run src/server` passed: **489 tests passed, two skipped**, across
23 passing files and one skipped file. This includes all 76 new auth
classification tests.
- Red/green: removing only the stdout partial-JSON filter reproduced
exactly the two M3 failures (detector and `execute()`), with the other
74 new tests passing. Restoring the filter passed the full server suite.
- Adapter `typecheck`, adapter `build`, and staged diff whitespace
checks passed.
- Prior-head [CI run
44106433610](https://github.com/paperclipai/paperclip/actions/runs/44106433610)
at `4ccb4ddfa5` had 58 successful checks and three skipped. Prior-head
Greptile was 5/5 with no actionable findings. These results do not
qualify the new head.
- New-head CI and Greptile review are pending after the push; their live
state is shown in this PR's checks. No repository-wide local suite, live
provider run, or deployment was performed for this correction.
- The previously reported CI timing failures and local
dependency/native-library setup failures were resolved before the prior
green CI run; no dependency or native-library change is included in this
correction.

## Risks

The new regression inputs are synthetic, not captured provider output. A
genuine login diagnostic emitted only on a JSON-looking stdout line is
excluded; stderr and failed terminal fields remain eligible.
Edge/Cloudflare HTML 403 handling remains outside scope (see #21351).

Plain diagnostic text remains a compatibility fallback. A new CLI output
format may need a focused fixture and parser update. A genuine auth
failure represented only as max-turns summary prose will retain the
budget-stop classification; explicit provider fields, HTTP 401, and
plain CLI login diagnostics remain recognized.

Cleanup success/failure, retry eligibility, and synthetic notification
handling need their own coordinated work.

## Squash merge attribution

When squash-merging, retain the following trailer in the final commit
message, separated from the body by a blank line. This uses [Bart's
verified commit
email](https://github.com/paperclipai/paperclip/pull/17229#issuecomment-7105332696),
superseding the bot's suggested noreply address:

```text
Co-authored-by: Bart Rozycki <contact@bartrozycki.com>
```

## Model Used

OpenAI Codex, GPT-6 family, with reasoning, repository inspection, code
editing, and local test execution. The exact serving snapshot 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 (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change and contains no internal
Paperclip ticket id or instance-derived details
- [ ] I have run tests locally and they pass — focused and adapter
suites pass; repository-wide checks remain unqualified
- [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 for `ae586d060d`
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups —
pending for `ae586d060d`; prior head was 5/5
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
Co-authored-by: Bart Rozycki <bmrozycki@gmail.com>
Co-authored-by: Bart Rozycki <contact@bartrozycki.com>
nightly/v2026.1205.0-nightly.1 canary/v2026.1205.0-canary.898100
2026-12-05 00:10:30 -08:00
797680a5ff fix(opencode-local): keep global instructions and skill paths stable across runs (#17209)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The `opencode_local` adapter runs each heartbeat with a runtime
OpenCode config. It copies the user OpenCode config directory into a new
`mkdtemp` directory for every run.
> - OpenCode writes the path of the global `AGENTS.md` ("Instructions
from: <path>") and the location of each config skill into the system
prompt.
> - Because the directory name is random, the system prompt is different
in every run, at about token 2,000.
> - Provider prompt caching matches a prompt prefix only. Each run
therefore pays for the full prompt again, and the model waits longer
before it answers.
> - This pull request loads the global `AGENTS.md` and the config skill
folders from the source config directory instead of copying them into
the per-run directory.
> - The benefit is a stable system prompt across runs, so providers can
reuse cached prompt tokens.

## Linked Issues or Issue Description

Refs #16678
Refs #15440

I found no issue or pull request for this problem. #16678 and #15440
also change how this adapter builds the runtime OpenCode config
(run-scoped MCP servers). They do not change the copy of `AGENTS.md` or
skills.

**What happened?**

Every `opencode_local` run with a global `~/.config/opencode/AGENTS.md`
sent a different system prompt. With OpenRouter and
`deepseek/deepseek-v4.1-flash-1017`, each run read only 1,792–2,048
cached tokens of about 48,000 prompt tokens. A short message ("halo")
took 9–20 seconds, depending on the model, and the full prompt was
billed every time.

**Expected behavior**

Two runs of the same agent with the same OpenCode config send the same
system prompt. Prompt caching then covers the system prompt.

**Steps to reproduce**

1. Put an `AGENTS.md` (and optionally a `skills/<name>/SKILL.md`) in
`~/.config/opencode`.
2. Create an agent with the `opencode_local` adapter and an OpenRouter
model that supports implicit prompt caching.
3. Run the agent twice with a short prompt.
4. Compare `cachedInputTokens` in the usage of the two runs. It stays at
about 2,000 tokens.
5. Run `XDG_CONFIG_HOME=<per-run dir> opencode debug skill` for two
per-run directories. The skill `location` contains the random
`paperclip-opencode-config-*` directory.

**Agent adapter(s) involved**

`opencode_local` (OpenCode 1.18.34; the same config keys exist in
1.19.3).

**Relevant logs or output**

System prompt layout that OpenCode sends, captured with an OpenCode
plugin that records `experimental.chat.system.transform`:

| Characters | Content | Same in each run? |
|---|---|---|
| 0–8,740 | OpenCode base prompt | Yes |
| about 8,970 | `Instructions from:
/tmp/paperclip-opencode-config-<random>/opencode/AGENTS.md` | No |
| about 13,000 to end | `<available_skills>`, with the `location` of
config skills under the same random directory | No |

## What Changed

- `packages/adapters/opencode-local/src/server/runtime-config.ts`: after
the adapter copies the source config directory, it removes the copied
`AGENTS.md` and the copied `skill`/`skills` folders from the per-run
directory. It adds the source `AGENTS.md` path to `instructions` and the
source skill folders to `skills.paths` in the runtime `opencode.json`.
Existing `instructions`, `skills.paths` and `skills.urls` values stay in
the config. The adapter adds a note to the run when it does this.
- `packages/adapters/opencode-local/src/server/runtime-config.test.ts`:
a test for two runs from the same source config: different per-run
directories, no copied `AGENTS.md` or `skills`, the same `instructions`
and `skills` values, and existing user entries kept. A test for a source
config without `AGENTS.md` or skills: the adapter does not add
`instructions` or `skills`.

## Verification

- `pnpm --filter @paperclipai/adapter-opencode-local exec vitest run`
passes (84 tests).
- `pnpm --filter @paperclipai/adapter-opencode-local exec tsc --noEmit`
passes.
- `opencode debug skill` and `opencode debug config` with a per-run
directory from this change: all 26 skills load, the config skill
`location` is the source path, and no `paperclip-opencode-config-*` path
is in the output.
- Direct `opencode run` test (DeepSeek through OpenRouter, "halo"): with
a new random config directory for each run, 0 of 6 runs read cached
tokens past 2,000. With a fixed config directory, the system prompt was
the same byte for byte in three runs.
- Self-hosted instance (Linux, systemd user unit, embedded Postgres),
one `opencode_local` agent with `deepseek/deepseek-v4.1-flash-1017`,
before and after this change:

| Run | Cached input tokens before | Cached input tokens after |
|---|---|---|
| First message of a new session | 1,792 | 1,536–1,792 |
| Second message in the same session | 1,792 | 7,680–29,978 |

The first message of a new session still reads about 1,800 cached
tokens. OpenRouter sends requests for this model to many providers, and
each provider keeps its own cache.

## Risks

- Low. Remote execution targets do not use this code path. Configs
without a global `AGENTS.md` or config skills do not change.
- Behavior shift: OpenCode now loads the global `AGENTS.md` through
`instructions`. It is the first entry, before other configured
instructions. The text in the prompt is the same. Only the path in
"Instructions from" changes to the source path.
- The run reads `AGENTS.md` and the config skills from the source
directory, not from a copy. The adapter does not change these files.
- `skills.paths` must be a supported OpenCode config key. OpenCode
1.18.34 and 1.19.3 support it.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), via Claude Code CLI, with tool
use (file edits, shell, test runs) and extended reasoning. A human
reviewed 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
- [ ] 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 <noreply@anthropic.com>
Co-authored-by: commitperclip[bot] <284812584+commitperclip[bot]@users.noreply.github.com>
2026-12-05 00:08:54 -08:00
d1cdd217a2 fix(adapter-utils): give hermes_local real session-rotation thresholds (#17199)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - It keeps a session for each agent. Some agents use the same session
for many runs.
> - The session compaction feature rotates a session when it grows too
large.
> - The rotation function asks the adapter registry for a limit for each
adapter type.
> - The registry gave hermes_local a policy where all limits were 0.
> - The function read those 0 values and decided that no limit exists.
It never rotates.
> - So a new hermes agent starts with no rotation limit unless someone
adds a manual override.
> - hermes does not compress its own context well on large sessions. Its
compression stops.
> - A stalled compression uses half of the run budget and the run then
fails.
> - This pull request gives hermes_local its own rotation policy with
real limits.
> - The benefit is that every new hermes agent is protected by default.

## Linked Issues or Issue Description

No public GitHub issue exists for this defect. This is the defect
report.

**What happened?**

The registry marks `hermes_local` as `nativeContextManagement:
"confirmed"`. It gives the type `ADAPTER_MANAGED_SESSION_POLICY`. Every
limit in that policy is 0. The function
`hasSessionCompactionThresholds()` returns false for it. The server then
never rotates the session.

**Expected behavior**

A new `hermes_local` agent should start with working rotation limits. A
developer should not need to add
`runtimeConfig.heartbeat.sessionCompaction` to each agent by hand.

**Steps to reproduce**

1. Create an agent with adapter `hermes_local`. Do not set any session
policy.
2. Call `resolveSessionCompactionPolicy("hermes_local", undefined)`.
3. Read `hasSessionCompactionThresholds(result.policy)`.
4. The result is `false`. The server returns `rotate: false` on every
wake.

**Agent adapter(s) involved**

`hermes_local`. The change does not affect `claude_local`,
`codex_local`, or `acpx_local`.

**Relevant logs or output**

hermes reports this in its own log:

```
run_agent: Context compression made no progress for 300.0s (total wait 300.0s, ceiling 600.0s); continuing without compression
```

The session row records the same event:

```
compression_failure_error: backoff:stall_interrupted:strategy=lean:msgs=1297:tokens=346650
```

On one measured fleet, 52 unarchived hermes sessions reached 400 or more
messages. They hold 33,894 messages and 854,572,069 cumulative input
tokens.

**Additional context**

On that fleet, agents that have a manual override rotate correctly
today. This change only protects agents that are created after it lands.

## What Changed

- Add `HERMES_SESSION_COMPACTION_POLICY` to
`packages/adapter-utils/src/session-compaction.ts`.
- Point
`ADAPTER_SESSION_MANAGEMENT.hermes_local.defaultSessionCompaction` at
that policy.
- Add a test file with four cases. It covers the default, the other
adapters, an agent override, and a full opt out.

The new policy is:

```ts
const HERMES_SESSION_COMPACTION_POLICY: SessionCompactionPolicy = {
  enabled: true,
  maxSessionRuns: 12,
  maxRawInputTokens: 500_000,
  maxSessionAgeHours: 168,
};
```

`maxSessionRuns` and `maxSessionAgeHours` work together across cadences.
An agent that runs about four times a day reaches 12 runs in about three
days. A daily agent reaches the 168 hour limit first.

`maxRawInputTokens` compares only the latest run. For hermes it is a
backstop. `maxSessionRuns` is the limit that acts first.

## Verification

Run these commands from the repository root.

```bash
pnpm install --frozen-lockfile
pnpm --filter @paperclipai/plugin-sdk build
npx tsc --noEmit -p packages/adapter-utils
npx vitest run packages/adapter-utils/src/__tests__/session-compaction.test.ts \
  packages/shared/src/validators/adapter-registry.test.ts \
  server/src/__tests__/adapter-registry.test.ts
```

Results on master at commit `043f2514e`:

| Check | Result |
| --- | --- |
| `tsc --noEmit` in `packages/adapter-utils` | clean |
| `packages/adapter-utils/src/__tests__/session-compaction.test.ts` | 4
passed |
| `server/src/__tests__/adapter-registry.test.ts` | 33 passed |
| `packages/shared/src/validators/adapter-registry.test.ts` | 4 passed |

CI runs the full suite. It uses `pnpm test:run:general`, the serialized
server shards, `typecheck:build-gaps`, `build`, and the end to end
tests.

One test fails in the sandbox. It is
`heartbeat-workspace-session.test.ts` →
`assertGitWorktreeBaseWorkspaceReady` → `marks a proven non-Git local
path as an owner configuration conflict without changing the failure`.
The same test fails on unmodified master. It does not relate to this
change.

## Risks

The change is low risk. It does not alter a shared default.

- Only `hermes_local` changes. The shared
`ADAPTER_MANAGED_SESSION_POLICY` is unchanged.
- A hermes agent that runs about four times a day rotates after about
three days. Its context is then rebuilt from a handoff note.
- Any agent can still set `runtimeConfig.heartbeat.sessionCompaction`
and override the policy.
- Any agent can set `enabled: false` and stop rotation.
- There is no migration. No stored data changes.

Reviewers should compare this change with PR 3905. That PR is open. It
sets limits for `codex_local`. It edits the same file. The two changes
touch different adapter keys.

## Model Used

The original fix was written with Anthropic Claude Opus 4.8. It used a
1M context window.

The change was later moved onto current master by an OpenClaw agent
runtime. That runtime used the model `minimax-portal/MiniMax-M3`. It
used shell access, git, the GitHub API, and the test runner. It did not
use a separate reasoning mode.

## Related and Prior Work

- PR 3905 is open. It sets limits for `codex_local`. This change does
the same job for `hermes_local`.
- PR 7902 is closed. It tried to stop unbounded session growth in the
shared policy. That approach would rotate adapters that compress
correctly. This change gives hermes its own policy instead.

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

---------

Co-authored-by: ruai-engineering-lead <engineering-lead@ruah.innovations>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: Head of Engineering <engineering@ruah-innovations.local>
2026-12-05 00:06:22 -08:00
d9ce549dd2 docs: fix OpenClaw onboarding to use the invite-prompt CLI (#17178)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Operators connect outside agents, such as OpenClaw, through the
`openclaw_gateway` adapter
> - `doc/OPENCLAW_ONBOARDING.md` is the checklist for that setup
> - Step 4 tells the reader to click "Generate OpenClaw Invite Prompt"
in company settings
> - That control does not exist in the current UI, so the checklist
cannot be completed as written
> - The `openclaw/invite-prompt` route and the `paperclipai openclaw
invite-prompt` command still work
> - This pull request moves the checklist to the CLI command and the
route
> - The benefit is that an operator can complete the OpenClaw setup by
following the document

## Linked Issues or Issue Description

**Issue type**

Outdated documentation

**Where is the issue?**

`doc/OPENCLAW_ONBOARDING.md`, steps 3 and 4.

**What's wrong?**

Step 4 says to click `Generate OpenClaw Invite Prompt` in the Invites
section of `/CLA/company/settings`. Company settings has no Invites
section. The Invites tab on the access page creates human invites only
(`allowedJoinTypes: "human"` in `InvitesSection.tsx`).
`createOpenClawInvitePrompt` in `ui/src/api/access.ts` has no caller
outside a test mock. The new-agent picker hides `openclaw_gateway`
(`comingSoon: true` in `adapter-display-registry.ts`). A reader who
follows the document cannot create the invite.

**Suggested fix**

Create the invite with `paperclipai openclaw invite-prompt`, or call the
route directly.

## What Changed

- Replace step 3 (open company settings) with a command that lists
company ids
- Replace the button steps in step 4 with the `paperclipai openclaw
invite-prompt` command and the equivalent route
- Say where the prompt text is: `onboardingTextUrl`, or `inviteMessage`
when it is set

## Verification

I ran each step against a local instance on current `master`
(`043f251`):

- `pnpm paperclipai company list --json` returns the company id
- `pnpm paperclipai openclaw invite-prompt --company-id <id>
--payload-json '{}' --json` returns an invite with `allowedJoinTypes:
"agent"`, `onboardingTextUrl` and `inviteMessage`
- `onboardingTextUrl` returns the agent onboarding text
- In the browser, company settings and the access page have no OpenClaw
invite control, and `openclaw_gateway` is absent from the new-agent
adapter list

This is a documentation-only change. I ran no automated tests.

## Risks

Low risk. One Markdown file changes. No code, API or UI behavior
changes.

## Model Used

- Provider: Anthropic
- Model: Claude Sonnet 5.5 (`claude-sonnet-5-5`)
- Tool use and code execution through Claude Code. A human directed and
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
- [ ] I have run tests locally and they pass
- [ ] 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: RouterGlock <RouterGlock@users.noreply.github.com>
Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-05 00:04:46 -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
75b22e264d fix(ui): honor Project visibility on Kanban cards (#16714)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - People use task collections to track work across projects.
> - The collection has a Project visibility setting and a Kanban view.
> - The list reads that setting, but board cards receive neither the
setting nor the project metadata.
> - This pull request passes the existing preference and project map to
the board and its drag preview.
> - The benefit is that people see each known project's name and color
on the board when they enable Project.

## Linked Issues or Issue Description

Related prior work: #3686 by @levineam and #7243 by @cassioln. Both PRs
are closed without a merge. Thank you to both authors for the earlier
work on project metadata in board cards. I searched open and closed PRs
and issues before starting this focused follow-up.

**What happened?**

In the task board, enabling Project in the Columns menu does not show
the project on any card. The collection reads the saved preference for
list rows, but does not pass it or its existing project map to
`KanbanBoard`.

**Expected behavior**

A card shows its known project's name and color when Project is enabled.
Disabling Project hides the badge. Regular cards, compact cards, and the
drag preview use the same setting. A long name stays inside the card and
keeps its full text in the title. A task with no known project has no
badge.

**Steps to reproduce**

1. Create a project and a task in that project.
2. Open the Tasks collection and select board view.
3. Open Columns and enable Project.
4. Check the task card. On `master`, it still shows no project.

## What Changed

- Pass the saved Project visibility setting and the existing project map
from the collection to the board. Both the streamlined and the legacy
collection do this.
- Show a token-styled badge with the project color, a truncated name,
and the full name in its title. Use it in regular cards, compact cards,
and the drag preview.
- Cover saved enabled and disabled preferences in both collections,
badge color, unknown or unset projects, neutral color fallback, long
names, and drag-preview visibility in component tests.
- Add three Storybook fixture states.

Scope update (2026-11-11): the branch is rebuilt as one commit on
current `master` (`14cb692`). Earlier revisions also carried shared CI
repairs (CLI startup deadline, legacy heartbeat cleanup handoff, and a
scheduled-retry test wait). Those changes are not part of this fix and
are removed from this PR. The feature-map paragraph is removed too,
because routine fixes leave the maps unchanged.
`doc/SPEC-implementation.md` no longer exists on `master` (#20565), so
the spec paragraph is removed too.

## Verification

Run in a clean Node 24.22 container with `pnpm install
--frozen-lockfile`, on `9d3d138`. The current head `ed05687` only
removes the feature-map paragraph from that revision:

- `cd ui && vitest run src/components/KanbanBoard.test.tsx
src/components/IssuesList.test.tsx src/components/IssueColumns.test.tsx
--maxWorkers=1` — 3 files, 103 tests passed.
- `pnpm --filter @paperclipai/ui typecheck` — passed.
- `pnpm check:token-gates`, `node scripts/check-maps.mjs`, `node
scripts/storybook-catalog.mjs --check`, and `git diff --check` — passed.
The feature map is unchanged on the current head, per
`rules/feature-map-scope.mdc`.
- Storybook states: `product-kanban-projects--project-enabled`,
`product-kanban-projects--compact-cards`, and
`product-kanban-projects--project-disabled`. These use fixtures and do
not prove live API access or navigation.
- Earlier revisions recorded a red-before-fix run: the component suites
failed on missing project badges and missing board props before the
implementation.
- Full GitHub CI passed on head `ed05687`.

## Risks

- Low risk. The change adds an optional badge row to each board card.
- Long names truncate. The badge uses the existing neutral badge tokens.
Missing project metadata produces no badge.
- The API, stored preferences, task mutations, and drag target logic
stay the same.

## Model Used

- Original change: OpenAI Codex, GPT-based agent, with repository
search, code editing, and code execution. The runtime did not expose the
exact model ID.
- Rebase onto current `master`, scope cleanup, and the legacy-collection
follow-up: Anthropic Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code,
with tool use and code execution.

## Merge Attribution

If squash-merging, retain these trailers in the squash commit body:

```text
Co-Authored-By: Codex <codex@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
```

## 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 (head ed05687)
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
(reviewed ed05687)
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Codex <codex@users.noreply.github.com>
Co-authored-by: a-vasyliev <1255946+a-vasyliev@users.noreply.github.com>
2026-12-04 23:58:50 -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>
canary/v2026.1205.0-canary.897400
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
Ethereal49 2e99edf825 fix(adapter-utils): allow summary slot callbacks from sandboxes (#16535)
## Thinking Path

> - Paperclip manages work for companies of AI agents.
> - Remote agents use the sandbox callback bridge to reach the
controller.
> - The built-in Summarizer reads and writes summary slots through that
bridge.
> - The server and bundled skill already provide these routes.
> - The default bridge allowlist rejects all three documented requests.
> - This change admits the exact methods and paths, so remote summaries
can reach the existing server checks.

## Linked Issues or Issue Description

- Fixes:
[#16481](https://github.com/paperclipai/paperclip/issues/16481).
- Related: [#16534](https://github.com/paperclipai/paperclip/pull/16534)
adds a labels read route in the same allowlist.
[#14533](https://github.com/paperclipai/paperclip/pull/14533) changes
SSH attachment queue reads. Neither adds summary-slot routes.
- Related: [#11682](https://github.com/paperclipai/paperclip/pull/11682)
adds routine refresh behavior on the server. This change does not
include that work.

## What Changed

- Add only GET slot, GET slot revisions, and PUT slot to the shared
default allowlist. Each pattern matches the full path.
- Test all three requests through the file queue. Check that the method,
path, query, and JSON body reach the handler. Check that a controller
403 response stays a 403 response.
- Add allowlist checks for both transports and rejection checks for
wrong methods, missing or extra path segments, similar resource names,
and the board-only generate action.

## Verification

- On base `185483e0909246b4609980a0e6e7ad3b8dbad1ba`, the new
regressions fail: all three queue requests return 403 instead of 200.
The allowlist assertion also fails (4 failed).
- PASS: `pnpm exec vitest run
packages/adapter-utils/src/sandbox-callback-bridge.test.ts
packages/adapter-utils/src/http2-bridge-server.test.ts
packages/adapter-utils/src/sandbox-callback-bridge-body.test.ts
packages/adapter-utils/src/execution-target.test.ts` (162 passed).
- PASS: `PAPERCLIP_ENABLE_DARWIN_SSH_ENV_LAB=1 pnpm exec vitest run
packages/adapter-utils/src/ssh-fixture.test.ts` (25 passed, no skips).
- PASS: `pnpm exec vitest run
server/src/__tests__/summary-slot-routes.test.ts
server/src/__tests__/summary-slots.test.ts` (31 passed, no skips). These
tests use the existing routes and an isolated PostgreSQL database. They
cover company access, board write denial, non-Summarizer denial, and
generation task/run checks.
- PASS: `pnpm --filter @paperclipai/adapter-utils typecheck`, `pnpm
--filter @paperclipai/adapter-utils build`, and `git diff --check`.
- Local environment: macOS ARM64, Node 26.11.1, pnpm 9.15.4. The first
server test attempt could not load the plugin SDK. Building the existing
shared/plugin SDK packages resolved that setup failure. One new
mock-call assertion also needed correction because the handler receives
a second context argument; the tests then passed.
- BLOCKED: `pnpm -r typecheck` stops at missing Node types in an
uninstalled workspace. `pnpm test:run` and `pnpm build` stop in
preflight because the CLI workspace's `tsx` is not installed. Their full
test/build bodies did not run. Only the server dependency closure was
installed in this isolated worktree. Disk space was limited and
Rust/cargo was unavailable.
- NOT_RUN: a model-driven SSH Summarizer run against a real Paperclip
instance, full repository gates, PR CI, and Greptile. The queue
handler's test 403 proves response forwarding; it does not prove
controller authorization. The server tests provide separate
authorization evidence.

## Risks

- The bridge now admits three existing summary-slot operations. Server
company access, the summaries feature flag, and the Summarizer task/run
write checks remain in force.
- No schema or request contract changes. POST generate and unrelated
routes stay denied. A real SSH Summarizer run and full CI remain
acceptance limits.

## Model Used

- OpenAI Codex, `gpt-6.1-sol`, `xhigh` reasoning, for implementation and
validation. Read-only assistants used OpenAI `gpt-6-luna` with `max`
reasoning for upstream checks, source inspection, and independent
review. A browser assistant used OpenAI `gpt-6.1-sol` with `medium`
reasoning to prepare the review page. Tools included shell execution,
Git/GitHub APIs, Vitest, TypeScript, and browser interaction. The
context window size is not exposed by this session.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either linked existing issues or described the issue in-PR
- [x] I have not referenced internal/instance-local Paperclip issues or
links
- [x] My branch name describes the change and contains no internal
Paperclip ticket id
- [x] I have run the listed targeted tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have checked the existing API/skill documentation; no request
contract changed
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
2026-12-04 23:45:21 -08:00
Josh CoxandReview a072b17067 fix(cli): warn when run list stops at the server page cap (#16533)
## Thinking Path
> - Bounding run history gave `GET
/api/companies/:companyId/heartbeat-runs` a default page of 200 runs and
a ceiling of 1,000, with no offset parameter and no truncation signal in
the response.
> - `paperclipai run list` sends `limit` only when `--limit` is passed,
makes one request, and the HTTP client returns only the parsed body. So
the command prints the newest 200 runs and stops, with no notice — and
`--limit 5000` silently stops at 1,000 the same way.
> - The issue's expected behavior is that the command either returns
every run or says that it did not.
> - Returning every run needs server work that is already scoped in open
issue #14958 (an `offset` parameter plus `X-Result-Truncated` /
`X-Total-Count` headers, and a client that surfaces headers). That is
not this PR.
> - What the CLI can do today: tell the truth. State the default and the
ceiling in the help text, and when a page comes back exactly full — the
only truncation sign the current route gives — say on stderr that more
runs may exist.

## Linked Issues

Fixes #16413

Refs #14958

## What Changed

- `cli/src/commands/client/run.ts`: the `run list` `--limit` help now
reads "Maximum runs to return (server default 200, max 1000)", using the
shared `HEARTBEAT_RUN_LIST_DEFAULT_LIMIT` /
`HEARTBEAT_RUN_LIST_MAX_LIMIT` constants so the text cannot drift from
the server values.
- Same file: after printing, when the returned row count reaches the
effective limit (the requested limit clamped to the server ceiling, or
the 200 default), the command prints a notice on stderr: how many runs
are shown, the cap that applied, that more runs may exist, and to raise
`--limit` to see more. stderr keeps `--json` output on stdout clean and
machine-readable.
- Tests in `cli/src/__tests__/run.test.ts`: a full 200-row default page
triggers exactly one stderr notice and sends no `limit` parameter; a
partial page under `--limit 25` stays quiet.

## Verification

- `vitest run src/__tests__/run.test.ts` — 5 of 5 pass, including the
pre-existing run command tests (request shapes unchanged: no `limit` is
sent unless `--limit` is passed).
- Disclosure: the CLI package typecheck did not complete in my sandbox
(the checker process is very slow against the shared package surface
here and was cut off); CI runs the CLI typecheck and is the arbiter. The
change uses two constants that are exported from `@paperclipai/shared`
today and already imported the same way elsewhere.

## Risks

- A company with exactly 200 (or exactly `--limit`) runs gets the notice
even though nothing was hidden. The wording says more runs *may* exist,
which is the strongest claim the current route supports; #14958's
headers will let a later change make it exact.
- This PR deliberately does not page or raise the default page size: the
server bound exists to keep run-history reads cheap, and silently
requesting 1,000 by default would change the command's cost profile for
every user. Full retrieval lands with #14958.

## 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 23:43:38 -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>
canary/v2026.1205.0-canary.896800
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
canary/v2026.1205.0-canary.896700
2026-12-05 00:41:30 -06:00
Josh CoxandReview 4b5000fae0 fix(hermes): state the enforced timeoutSec default (1800) in local adapter docs (#15936)
## Thinking Path

> - Paperclip is a control plane for AI-agent companies.
> - The Hermes local adapter has a `timeoutSec` run limit.
> - The code sets the default in `DEFAULT_TIMEOUT_SEC`. The value is
1800.
> - The UI config builder also floors `timeoutSec` at that default. A
user cannot build a lower value in the UI.
> - Two doc tables still state the default as 300. The README example
config also uses 300.
> - A user who copies the documented value gets runs killed at a wall
the docs implied was normal.
> - This pull request makes the three doc spots state 1800. It changes
no code behavior.

## Linked Issues

Fixes #15903

## What Changed

- `packages/adapters/hermes/README.md`: the Core Configuration table now
states the `timeoutSec` default as `1800`. The example agent config now
uses `"timeoutSec": 1800`, so the example no longer shows a value the UI
builder cannot produce.
- `packages/adapters/hermes/src/index.ts`: the local variant doc table
now states the `timeoutSec` default as 1800.
- The gateway variant docs are not touched. They state 600, and the
gateway code default is 600, so they agree.

## Verification

- Text check: all three local-variant spots now read 1800, and
`DEFAULT_TIMEOUT_SEC` in
`packages/adapters/hermes/src/shared/constants.ts` is 1800.
- The Hermes entrypoint test suite passes: 8 tests, including a new
guard that fails if the doc table and `DEFAULT_TIMEOUT_SEC` drift apart
again.
- Docs-only change; no runtime code was modified.

## Risks

- None for runtime behavior. The only risk is doc drift in the other
direction if the code default changes later; the constant stays the
single source of truth in code.

## Model Used

- **Model:** Meta Muse Spark 1.3

## 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
- [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:40:29 -08: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>
canary/v2026.1205.0-canary.896300
2026-12-04 21:30:00 -08:00
LakshmananandPaperclip 560201c683 fix(codex-local): prevent quoted auth errors from invalidating connections (#15832)
## Thinking Path

> - Paperclip manages AI agents and their work.
> - The Codex adapter reports provider failures to connection recovery.
> - Connection recovery requests a new login after a refresh-token
failure.
> - The classifier searched the full CLI transcript, including command
output and agent messages.
> - A source review can quote an application error such as "expired
refresh token" before an unrelated provider failure.
> - This pull request limits structured stdout classification to
protocol errors.
> - A quoted application error can no longer invalidate the selected AI
connection.

## Linked Issues or Issue Description

**What happened?**

A Codex CLI agent read application source containing "Invalid or expired
refresh token". Its turn then failed for a separate provider safeguard
reason. Paperclip reported `refresh_token_expired` and asked users of
the shared connection to sign in again.

**Expected behavior**

Keep the original provider failure. Do not invalidate credentials
because command output or an agent message contains an authentication
error. Continue to detect genuine refresh-token failures.

**Steps to reproduce**

1. Include an `item.completed` command result that quotes "Invalid or
expired refresh token" in a Codex JSONL transcript.
2. End the transcript with an `error` and `turn.failed` event for an
unrelated provider failure.
3. Call `classifyCodexAuthRefreshFailure` with the transcript and the
parsed provider error.
4. The previous implementation returns `refresh_token_expired`. The
fixed implementation returns `null` and preserves the provider failure.

The regression tests use synthetic protocol events. No live credentials
or private task logs are included.

**Paperclip version or commit**

Reproduced on `b1ebe3de3c17610573de3e849fc245e2aace7742`. The branch is
based on upstream `master` at
`9ba5569030cc4f37e53906d19e13778c81c99ecc`.

**Deployment mode**

Local development from source, `local_trusted`, Windows, Node.js
24.18.0. The classifier fix applies to Codex CLI execution on other
platforms too.

**Additional context**

I searched public issues and open and closed pull requests for Codex
authentication, quoted output, logout, and refresh classification. I
found no matching report or duplicate implementation. This fix does not
change provider safeguards or token-refresh behavior.

## What Changed

- Reuse the existing JSONL parser to classify the last protocol error
instead of the full structured transcript.
- Retain plain stdout support for failures before protocol startup and
retain process stderr diagnostics.
- Add regressions for quoted errors, real protocol authentication
errors, a later unrelated failure, a process crash, and real stderr
authentication failures.
- Document why quoted application errors do not request a new connection
login.

## Verification

- `pnpm exec vitest run
packages/adapters/codex-local/src/server/parse.test.ts
packages/adapters/codex-local/src/server/execute.auth.test.ts`: 40 tests
passed on this branch.
- `pnpm exec vitest run
packages/adapters/codex-local/src/server/acp.test.ts -t 'classifies ACP
refresh-token auth failures'`: one selected test passed; 45 tests were
not selected.
- `pnpm --filter @paperclipai/adapter-codex-local typecheck`: passed.
- `pnpm --filter @paperclipai/adapter-codex-local build`: passed using
Git Bash for Unix build commands on Windows.
- `git diff --check`: passed.
- Full checks were attempted. `pnpm test:run` stops at `spawnSync pnpm
ENOENT` in the Windows test launcher. `pnpm -r typecheck` and `pnpm
build` stop in unchanged native-runner generated-file checks in this
Windows checkout. The first typecheck also hit a patch-byte hash
mismatch from checkout line endings. Restoring canonical bytes moved it
to the generated-file check. No generated files or patch changes are
included in this PR.
- Greptile reviewed head `10be54bcba8df2f68068daf4bb583c42ae6282ca` and
gave it 5/5 with no findings. All 53 check runs for that head completed
without failures. Linux CI passed full typecheck, build, test shards,
release-registry, native-runner, and browser checks. This PR is ready
for review.

## Risks

- Authentication recovery is sensitive. The tests retain real protocol,
stderr, and pre-protocol stdout failure detection.
- CLI execution still returns the actual failure. The fix does not
suppress a provider refusal or retry around a safeguard.
- No schema, migration, API, permission, credential storage, or
telemetry changes.

## Model Used

OpenAI Codex, a GPT-6-based assistant. The exact runtime model ID,
reasoning setting, and context-window size are not exposed in this
session, so they are not inferred from the separately configured
Paperclip agents. Capabilities used: repository analysis, code editing,
shell execution, and test execution.

## Checklist

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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-12-04 21:28:15 -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
77b28108d4 fix(codex-local): extract retry time from subscription usage-limit wording (#15671)
<!-- 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 Codex adapter runs agents on Codex subscriptions, and a run that
hits the usage limit must wait for the provider reset time
> - Codex prints the reset time in the local time of the host
> - The adapter reads the reset time from the error text and stores it,
and recovery prefers the stored value
> - Subscription plans, for example ChatGPT Plus, get a different error
wording, and the adapter pattern does not match that wording
> - No reset time is stored, so recovery uses a generic parser, and the
generic parser reads a clock with no zone as UTC
> - On a host outside UTC, the retry waits for the wrong hour, and then
rolls to the next day
> - This pull request teaches the Codex adapter to read the subscription
wording, so the stored reset time is correct at the source
> - The benefit is a correct provider-quota retry time for subscription
runs in every time zone

## Linked Issues or Issue Description

Fixes #15613

## What Changed

- A new pattern in the Codex adapter matches the subscription
usage-limit wording: "You've hit your usage limit. Upgrade to Pro (...),
visit ... to purchase more credits or try again at 8:13 PM."
- `extractCodexRetryNotBefore` now tries the new pattern after the model
pattern, and both patterns use the existing `parseLocalClockTime` path:
a clock with no zone is local time, and an explicit zone hint keeps its
current meaning
- The change is only in the Codex adapter. The generic recovery parser
keeps its current rule for a clock with no zone (UTC), because a test
covers that rule and other providers also use that parser
- Tests: the reported wording extracts the correct local time, a past
clock rolls to the next local day, an explicit zone hint still works,
and the wording with no clock returns no retry time

## Verification

- `vitest run packages/adapters/codex-local/src/server/parse.test.ts` —
28 passed
- `vitest run
packages/adapters/codex-local/src/server/acp.quota.test.ts` — 19 passed
- `vitest run
server/src/services/recovery/provider-failure-classification.test.ts` —
24 passed; the server parser is not changed
- `tsc --noEmit` for `@paperclipai/adapter-codex-local` passes
- Negative control: with the parser change stashed, the three new
extraction tests fail on the unmodified code
- Note: three tests in `codex-auth-copyback.test.ts` fail in my sandbox
with and without this change. The sandbox runs tests as root, and those
tests use read-only directories. The failure is not related to this
change

## Risks

- Low risk. The new pattern needs the exact usage-limit sentence and a
"try again at" clause on the same line, so unrelated error text does not
match
- The model wording path does not change, and the recovery parser does
not change

## 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: commitperclip[bot] <284812584+commitperclip[bot]@users.noreply.github.com>
Co-authored-by: Review <review@local>
2026-12-04 21:26:37 -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
Steven Nance c8ca682bf2 fix(ui): remount the composer takeover card per pending input (#15121)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Agents ask people for decisions through cards in the task chat
> - The composer shows one pending card at a time in a takeover slot
> - The checkbox card and the suggested-tasks card keep the selection,
the reason and the page in local React state
> - The takeover slot renders each pending card in the same position
without a React `key`, so React reuses one card instance for the next
pending card
> - The next card then starts with the state of the card before it
> - This pull request adds a `key` for each pending input, so each card
mounts with its own state
> - The benefit is that each card shows and sends only its own options

## Linked Issues or Issue Description

No public issue exists for this bug. The description follows the bug
report template.

**What happened?**

A task had two pending cards of the same kind. I answered the first
card. The takeover slot then showed the second card, but the second card
kept the selection state of the first card. The default ticks of the
second card did not show. The card also wrote the selection of the first
card into the saved draft of the second card. When I confirmed the
second checkbox card, it sent option ids that belong to the first card.
The server refused the request with `Unknown checkbox confirmation
optionId`.

**Expected behavior**

Each pending card starts with its own default selection. Each card sends
only its own option ids. Each card saves only its own draft.

**Steps to reproduce**

1. Create two pending `request_checkbox_confirmation` interactions on
one task. Give them different option ids and different
`defaultSelectedOptionIds`.
2. Open the task. The composer takeover shows one of the cards.
3. Change the ticks on that card, then confirm it.
4. Look at the next card in the takeover slot. Its default ticks do not
show.
5. Confirm the next card. The request fails with `Unknown checkbox
confirmation optionId`.

The same fault occurs with two pending `suggest_tasks` cards.

**Paperclip version or commit**

`master` at `1c07b5903b1b11139b1e1ce052a3cd4885865d90`.

**Deployment mode**

Self-hosted server. The bug is in the UI and does not depend on the
deployment mode.

Related work: a search of issues and pull requests found no report and
no fix for this bug. #14613 and #9290 change the same cards, but they do
not change how the takeover slot mounts a card.

## What Changed

- `ui/src/components/TaskChatThread.tsx`: the takeover
`TaskChatProtocolCard` and `TaskChatInteractionCard` now have
`key={selectedPendingInput.key}`. React mounts a new card when the
pending input changes.
- `ui/src/components/TaskChatThread.test.tsx`: two new tests. One test
covers two pending checkbox cards. One test covers two pending
suggested-tasks cards. Each test answers the first card and then checks
the ticks, the submitted ids and the saved draft of the second card.
- The branch has two commits. The first commit adds only the tests. The
second commit adds the fix.

## Verification

Run these commands from the repository root:

- `pnpm exec vitest run --project @paperclipai/ui
ui/src/components/TaskChatThread.test.tsx`
- On the tests-only commit: 2 failed, 195 passed. The two failures are
the new tests.
  - On the head commit: 197 passed.
- `pnpm exec vitest run --project @paperclipai/ui`: 679 test files
passed, 7316 tests passed.
- `pnpm --filter @paperclipai/ui typecheck`: no errors.
- `pnpm check:token-gates`: all gates clean.
- `pnpm check:tokens`: no forbidden tokens.

Manual check: on a self-hosted build that has the same two-line change,
two pending checkbox cards on one task were accepted one after the
other. Each request sent the option ids of its own card. This build was
not the head commit of this branch.

I did not run `pnpm -r typecheck`, the full `pnpm test:run`, `pnpm
build` or the browser suites. The change touches only the two UI files
above.

## Risks

Low risk. A card in the takeover slot now mounts again when the selected
pending input changes. Unsaved local state of the card that leaves the
slot is not kept in memory. Selections and reasons stay in the saved
draft for each card, as before. The card does not mount again while the
same pending input stays selected, because the key is stable for one
pending input.

## Model Used

Claude Opus 5.5 (`claude-opus-5-5`) from Anthropic, run as a coding
agent with tool use (shell, file edit, test runs). The context window
size of the run was not recorded. A person reviews the change before the
pull request opens.

## 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: no documentation describes this behavior)
- [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 21:09:46 -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
Can H. Tartanoglu 6c6e978725 fix(build): preserve UI errors before service worker output exists (#14444)
## Thinking Path

> - Paperclip serves a web UI with a service worker.
> - The UI build stamps the worker with the entry bundle ID.
> - Vite also calls `closeBundle` after a failed build.
> - A failed build can leave the worker file absent.
> - Reading that file replaces the useful build error with an `ENOENT`
error.
> - This change stamps the worker in `writeBundle`, after the output
exists.

## Linked Issues or Issue Description

**What happened?**

An unresolved UI import reports a missing `dist/sw.js` file instead of
the missing module. The stamping plugin reads the worker from
`closeBundle`, including after a failed bundle.

**Expected behavior**

The build should report the original module error. A successful build
should still stamp the copied worker with its entry bundle ID.

**Steps to reproduce**

1. Create a minimal Vite project with an HTML entry and `public/sw.js`
containing the build-ID placeholder.
2. Enable `serviceWorkerBuildIdPlugin()`.
3. Make the entry import `./missing.js`.
4. Run the build. The current plugin reports `ENOENT` for `dist/sw.js`.

**Paperclip version or commit**

Reproduced on `3447609d2247e75e55d91493dda91a608364f672`.

**Deployment mode**

Other: production UI build.

**Installation method**

Built from source.

**Database mode**

Not database-related.

**Operating system**

NixOS, x86_64 Linux. Node 24.19.0.

**Additional context**

Searches of open and closed issues and PRs for `closeBundle` and
`writeBundle` found no matching contribution.

## What Changed

- Move file stamping to `writeBundle`.
- Add real Vite build tests for a failed import and a successful stamped
output.
- Compare the complete stamped worker content against the entry-derived
build ID.

## Verification

### Current exact-source hosted qualification — 2026-10-09

Published head: `d0b95c377e43a06a2b5ba740dd6df9cb23fd3335`. The
externally published reconciliation preserves the prior proposal and
exactly matches its recorded tree merged with target
`9b624a110e281badc54cbdf37ddb792cdc1690ff`; no proposal behavior was
changed. Required **`ci / verify` and `ci / e2e` succeed** in [run
37864533960/1](https://github.com/paperclipai/paperclip/actions/runs/37864533960).
Actual checkout logs bind this exact candidate to this exact current
target. All original regression repairs and historical findings remain
retained.

GitHub verifies the reconciliation signature. Local signature
verification cannot check it because the signer public key is absent; no
key, signing setting or commit identity was changed. Local worktrees
were fast-forwarded to the existing public heads without creating or
rewriting commits.

Successful complete native Codex code review and applicable maintainer
approvals remain outstanding; [the source-bound review
request](https://github.com/paperclipai/paperclip/pull/14444#issuecomment-6072822720)
is not acceptance. After qualification, mark the draft ready and use the
protected exact-head merge. The authenticated operator currently has
READ-only upstream access.


<!-- preserving-source-refresh-20261009:start -->
### Preserving upstream refresh — 2026-10-09

Published signed head: `d0b95c377e43a06a2b5ba740dd6df9cb23fd3335`.

This head contains observed upstream
`9b624a110e281badc54cbdf37ddb792cdc1690ff`, previous published head
`eda06f1c0a8eaf0a8c9c3a352ba02dea88bb0b95`, and preserved prepared head
`cde0ef5321f48d75593738afd3310d901986a16e`. The publication used one
atomic, non-force push. Remote branch and PR readback match the signed
head. The lockfile and database migrations have no delta from this
upstream.

Exact-head hosted CI:
https://github.com/paperclipai/paperclip/actions/runs/37864533960.
Qualification is pending. Earlier results remain historical evidence and
do not qualify this refreshed head. Acceptance requires mandatory
attempt-1 GREEN results, zero mandatory failures, errors, skips or
retries, SHA-256-bound receipts, and provider retention of at least
2592000 seconds.

Refresh assistance: OpenAI `openai/gpt-6.1-sol`, with repository
inspection, Git tooling and evidence verification. The harness does not
expose a context-window size.
<!-- preserving-source-refresh-20261009:end -->

### Published reconciliation — 2026-10-08

Published candidate `eda06f1c0a8eaf0a8c9c3a352ba02dea88bb0b95` includes
the target `71cd0a2621615182274a977d6cc969b9ab920b92`. Frozen dependency
installation and all **9** stamping unit/integration tests passed on
that exact candidate, with zero skipped. Changing only `writeBundle`
back to `closeBundle` reproduced the masked missing-import diagnostic.
Restoring the candidate passed the full focused file again.

```sh
corepack pnpm --filter @paperclipai/ui exec vitest run src/lib/vite-sw-build-id.test.ts src/lib/vite-sw-build-id.integration.test.ts
```

The source comparison merges without conflict against the live `master`
observed at `9f4acc8f14f5baf77b54b040d156a1b094d8d366`. The exact
candidate was normal-pushed to this PR branch. The focused results are
not full qualification of the newer target/composite tree. New hosted CI
and full native code review are pending. Queued, running, skipped or
failed checks do not establish a pass. Applicable maintainer approvals
and protected merge gates remain required.

### Historical qualification — not acceptance of the new comparison

- Before the fix, the failed-import regression reports the unrelated
worker `ENOENT`; the successful-build case passes.
- After the fix, all nine stamping unit/integration tests pass.
- At `375f1cbd9`, all 6,756 UI tests passed across 639 files: `pnpm exec
vitest run --project @paperclipai/ui --exclude '**/dist/**'`.
- `pnpm --filter @paperclipai/ui typecheck` passes.
- `pnpm --filter @paperclipai/ui build` passes, with existing chunk-size
and mixed static/dynamic import warnings.
- `git diff --check` passes.
- `pnpm check:token-gates` passes on the exact published head.
- The assertion-only follow-up
`415c30fe034f7e99b25f12a940776766e9325966` passed all nine focused
stamping tests and UI typecheck. Greptile reviewed that head at 5/5 with
no remaining findings. Full-monorepo qualification and CI remain
pending. This is a draft.
- Added code comment removed per CONTRIBUTING.md; `pnpm exec vitest run
ui/src/lib/vite-sw-build-id` (11 passed) and `pnpm --filter
@paperclipai/ui typecheck` pass on this head and on upstream `820c458`.
- `ci / General tests (server (8/12))` failed once in
`server/src/__tests__/decision-expiry-work.test.ts` (expected timestamps
off by exactly 90000 ms). This PR does not touch server code, and that
file passes locally (20 tests). Treated as unrelated timing flake:
https://github.com/paperclipai/paperclip/actions/runs/40728729442

## Risks

The hook timing changes. Real build tests verify that the copied worker
exists at `writeBundle` and receives the emitted entry ID. Missing or
invalid worker content during a successful build still fails stamping.

## Model Used

OpenAI GPT-6 Astra, exact model ID `gpt-6-astra`, through OpenCode.
Assistance included code, real-build regression tests, and command
execution. The harness did not expose a verified 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
- [ ] 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-04 20:49:00 -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
Can H. Tartanoglu 153b48dea9 fix(db): honor PostgreSQL URI host parameters for Unix sockets (#14442)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Paperclip stores control-plane state in PostgreSQL through
`packages/db`
> - A self-hosted instance can reach a local PostgreSQL service through
a Unix socket
> - libpq URIs select the socket with the `host` query parameter, but
postgres.js sends that parameter as a server setting and uses TCP
> - This pull request maps the URI `host` parameter to the driver host
option in one shared helper
> - The benefit is that app connections, migrations, backups, and
restores use the socket that the URI selects

## Linked Issues or Issue Description

**What happened?**
With
`DATABASE_URL=postgresql://paperclip@localhost:5432/paperclip?host=/run/postgresql`,
Paperclip connected over TCP to `localhost` instead of the socket.

**Expected behavior**
All JavaScript connections use the socket directory in `host`.
Percent-encoded paths also work. TCP URIs do not change.

**Steps to reproduce**
1. Run PostgreSQL with a Unix socket directory.
2. Set `DATABASE_URL` to a URI with `?host=<socket-directory>`.
3. Start Paperclip or run a JavaScript backup.
4. See that the connection uses TCP, not the socket.

**Paperclip version or commit**
upstream master cde944ed7

**Operating system**
Linux, Node 24

## What Changed

- Add `connectPostgres` in `packages/db/src/postgres-connection.ts`. It
moves the URI `host` parameter into the driver `host` option. Explicit
options still win.
- Use it in `createDb`, the utility clients, and `backup-lib.ts`.
- Key the teardown registry by the `host` parameter when it is set.
- Add tests, including a socket backup and restore with an unreachable
TCP hostname.
- Document socket URIs in `doc/DATABASE.md`.

## Verification

Rebased onto upstream `322fa6b65c` (squashed into one commit; conflicts
in `client.ts` and `client-teardown-registry.test.ts` resolved,
`codex-credentials.test.ts` taken from upstream because it already
carries the quorum fixture fix).

- `pnpm exec vitest run packages/db/src/postgres-connection.test.ts
packages/db/src/postgres-uri-host.test.ts
packages/db/src/client-teardown-registry.test.ts
packages/db/src/client.test.ts packages/db/src/backup-lib.test.ts`: 5
files, 47 tests passed.
- `pnpm --filter @paperclipai/db typecheck`: pass.
- The new tests fail when the helper ignores `host`.
- Added code comments removed per CONTRIBUTING.md; the same five test
files and `tsc` re-run after removal: pass.

## Risks

- Low risk. URIs without a `host` query parameter use the old code path.
- A URI with both a hostname and `host` now connects to `host`. This is
the libpq rule.

## Model Used

Original change: OpenAI gpt-6.1-sol via OpenCode. Cleanup and rebase:
Anthropic Claude Opus 5.5 (claude-opus-5-5), 1M context, tool use.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
2026-12-04 20:08:24 -08:00
dependabot[bot] f4fc0ca0bc build(deps): bump @cloudflare/sandbox from 0.7.21 to 0.12.14 in /scripts/typecheck-sandbox-providers (#23827)
Bumps [@cloudflare/sandbox](https://github.com/cloudflare/sandbox-sdk)
from 0.7.21 to 0.12.14.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/cloudflare/sandbox-sdk/releases">@​cloudflare/sandbox's
releases</a>.</em></p>
<blockquote>
<h2><code>@​cloudflare/sandbox</code><a
href="https://github.com/0"><code>@​0</code></a>.12.14</h2>
<h3>Patch Changes</h3>
<ul>
<li><a
href="https://redirect.github.com/cloudflare/sandbox-sdk/pull/1028">#1028</a>
<a
href="https://github.com/cloudflare/sandbox-sdk/commit/2e4e1eb304e2cbbf5569e095e3ead296a5efbc87"><code>2e4e1eb</code></a>
Thanks <a
href="https://github.com/ghostwriternr"><code>@​ghostwriternr</code></a>!
- Update the container runtime to Bun 1.4.4. Bun checks certificates
against its own built-in CA list, and in 1.4.4 that list no longer
trusts the compromised eMudhra intermediates, so the <code>bun</code>
command and <code>createBackup()</code> uploads of 10 MiB or more now
reject their certificates. Bun 1.4.4 also updates Brotli to 1.2.1, which
fixes CVE-2026-111497. The <code>-opencode</code> image ships OpenCode
1.19.4 or later, which also runs on Bun 1.4.4.</li>
</ul>
<h2><code>@​cloudflare/sandbox</code><a
href="https://github.com/0"><code>@​0</code></a>.12.13</h2>
<h3>Patch Changes</h3>
<ul>
<li><a
href="https://redirect.github.com/cloudflare/sandbox-sdk/pull/1023">#1023</a>
<a
href="https://github.com/cloudflare/sandbox-sdk/commit/a4eaa89aada863cda9ea8a7373404029a1a32761"><code>a4eaa89</code></a>
Thanks <a
href="https://github.com/ghostwriternr"><code>@​ghostwriternr</code></a>!
- Stop trusting certificates from the compromised eMudhra intermediate
CAs in the container images. The images now ship the updated Ubuntu and
Alpine CA bundles, Node.js 22.23.4, cloudflared 2026.10.2, and pip
26.2.2 in the <code>-python</code> image. Bun keeps trusting these
certificates until it releases a fix, which affects <code>bun</code>,
opencode, and multipart uploads in <code>createBackup()</code> for
archives of 10 MiB or more. Update the container image to get this fix.
See <a
href="https://blog.cloudflare.com/emudhra-certificate-compromise/">the
eMudhra certificate compromise</a> for details.</li>
</ul>
<h2><code>@​cloudflare/sandbox</code><a
href="https://github.com/0"><code>@​0</code></a>.12.12</h2>
<h3>Patch Changes</h3>
<ul>
<li>
<p><a
href="https://redirect.github.com/cloudflare/sandbox-sdk/pull/1002">#1002</a>
<a
href="https://github.com/cloudflare/sandbox-sdk/commit/8dc216c5c16563d0e3f2044ad14c0657682f3fd9"><code>8dc216c</code></a>
Thanks <a
href="https://github.com/ghostwriternr"><code>@​ghostwriternr</code></a>!
- Fix <code>mountBucket()</code> breaking an existing mount when a
second call for the same mount path fails with &quot;already in
use&quot;. The existing mount now stays mounted and usable.</p>
</li>
<li>
<p><a
href="https://redirect.github.com/cloudflare/sandbox-sdk/pull/1013">#1013</a>
<a
href="https://github.com/cloudflare/sandbox-sdk/commit/98b787b81b5526851af95e6be9ca98da13ae450d"><code>98b787b</code></a>
Thanks <a
href="https://github.com/ghostwriternr"><code>@​ghostwriternr</code></a>!
- Keep streaming <code>exec()</code> alive while a command is quiet, and
enforce its <code>timeout</code>. Quiet commands were cut off after
about four minutes on the HTTP transport and five on WebSocket. The
timeout was ignored on those transports, and on every transport for
commands that run in a session. Requires the matching container
image.</p>
</li>
<li>
<p><a
href="https://redirect.github.com/cloudflare/sandbox-sdk/pull/1008">#1008</a>
<a
href="https://github.com/cloudflare/sandbox-sdk/commit/b2a862cffce187f56bcfae321756c0a9c91b712b"><code>b2a862c</code></a>
Thanks <a
href="https://github.com/ghostwriternr"><code>@​ghostwriternr</code></a>!
- Keep R2 binding and credential-proxy bucket mounts working when the
Sandbox Durable Object restarts while its container keeps running. The
mounts used to stay listed but fail every read and write with
<code>EIO</code> until <code>mountBucket()</code> was called again.</p>
</li>
<li>
<p><a
href="https://redirect.github.com/cloudflare/sandbox-sdk/pull/1003">#1003</a>
<a
href="https://github.com/cloudflare/sandbox-sdk/commit/e8332cd3c6b0a6f958062304f922d93678f6dfed"><code>e8332cd</code></a>
Thanks <a
href="https://github.com/ghostwriternr"><code>@​ghostwriternr</code></a>!
- Fix <code>createOpencodeServer()</code> and
<code>createOpencode()</code> waiting for the full three-minute startup
timeout when <code>OPENCODE_SERVER_PASSWORD</code> is set. When the
password is passed in <code>env</code>, the client returned by
<code>createOpencode()</code> now authenticates with it.</p>
</li>
<li>
<p><a
href="https://redirect.github.com/cloudflare/sandbox-sdk/pull/1016">#1016</a>
<a
href="https://github.com/cloudflare/sandbox-sdk/commit/d62f020d6b1cae787fc676c11b29b7718c40f575"><code>d62f020</code></a>
Thanks <a
href="https://github.com/ghostwriternr"><code>@​ghostwriternr</code></a>!
- Create the s3fs password file for <code>mountBucket()</code> with mode
0600 from the start. The file used to be readable by other users in the
container until a chmod a moment later, long enough for a non-root
process to open it and read the bucket credentials. Upgrade the
container image together with the SDK to close the gap; with an older
image, mounts work as before.</p>
</li>
<li>
<p><a
href="https://redirect.github.com/cloudflare/sandbox-sdk/pull/996">#996</a>
<a
href="https://github.com/cloudflare/sandbox-sdk/commit/da3d7b6c4edde53b071c42180bca22493e864c9a"><code>da3d7b6</code></a>
Thanks <a
href="https://github.com/ghostwriternr"><code>@​ghostwriternr</code></a>!
- Answer a preview request with <code>502</code> when the app's port in
the container fails, for example because nothing listens on it or it
closes the connection, and log the original error. Previously the error
escaped the Sandbox, <code>proxyToSandbox()</code> answered <code>500
Proxy routing error</code>, and the log blamed a platform runtime
update.</p>
</li>
<li>
<p><a
href="https://redirect.github.com/cloudflare/sandbox-sdk/pull/997">#997</a>
<a
href="https://github.com/cloudflare/sandbox-sdk/commit/c79bf1de83e9be4d5c423b0b60fc7d48792418e7"><code>c79bf1d</code></a>
Thanks <a
href="https://github.com/ghostwriternr"><code>@​ghostwriternr</code></a>!
- Forward WebSocket upgrades on preview URLs with <code>Host:
localhost:&lt;port&gt;</code>, like every other preview request. Dev
servers that check the <code>Host</code> header, such as Vite, no longer
reject HMR connections. The public hostname is still in
<code>X-Forwarded-Host</code>.</p>
</li>
<li>
<p><a
href="https://redirect.github.com/cloudflare/sandbox-sdk/pull/1000">#1000</a>
<a
href="https://github.com/cloudflare/sandbox-sdk/commit/c6760770b291531ae9a782e6ddfc2aa32ad8674c"><code>c676077</code></a>
Thanks <a
href="https://github.com/ghostwriternr"><code>@​ghostwriternr</code></a>!
- Keep preview URLs and tunnels working on the RPC transport after the
control connection reconnects. The connection closes after 1 second
without calls, and the next call used to rerun the sandbox's start
handling even though the container was still running. Preview URLs then
returned <code>410 STALE_PREVIEW_URL</code>,
<code>getExposedPorts()</code> returned an empty list, quick tunnels
disappeared from <code>tunnels.list()</code>, and
<code>tunnels.get()</code> could fail with &quot;Tunnel recovery
attempts were exhausted&quot;.</p>
</li>
<li>
<p><a
href="https://redirect.github.com/cloudflare/sandbox-sdk/pull/1010">#1010</a>
<a
href="https://github.com/cloudflare/sandbox-sdk/commit/7866d45fb7c1b83e45d1fac4f5c084d712603bb0"><code>7866d45</code></a>
Thanks <a
href="https://github.com/ghostwriternr"><code>@​ghostwriternr</code></a>!
- Stop the first call on the RPC transport from failing when Cloudflare
can't provide a container right away. The call now keeps waiting for the
container within its retry window.</p>
</li>
<li>
<p><a
href="https://redirect.github.com/cloudflare/sandbox-sdk/pull/995">#995</a>
<a
href="https://github.com/cloudflare/sandbox-sdk/commit/becade1ff2b472d50340c64b12cf1c9208d945f7"><code>becade1</code></a>
Thanks <a
href="https://github.com/ghostwriternr"><code>@​ghostwriternr</code></a>!
- Stop the container server from crashing with <code>ENOENT: no such
file or directory, watch '…/&lt;id&gt;.log.stderr'</code> while commands
run. The crash killed every process in the container. Update the
container image to pick up this fix.</p>
</li>
<li>
<p><a
href="https://redirect.github.com/cloudflare/sandbox-sdk/pull/1007">#1007</a>
<a
href="https://github.com/cloudflare/sandbox-sdk/commit/fa571496cd1276d41c8d23672c3e6da541c4d1d1"><code>fa57149</code></a>
Thanks <a
href="https://github.com/ghostwriternr"><code>@​ghostwriternr</code></a>!
- <code>tunnels.get()</code> on the RPC transport now reports the real
tunnel error, such as <code>cloudflared</code> failing to start or
missing from the image, instead of &quot;Tunnel recovery attempts were
exhausted&quot;. It also no longer leaves a port stuck after giving up:
a <code>cloudflared</code> left running from an earlier attempt is
stopped and replaced. Replacing it needs the matching container
image.</p>
</li>
</ul>
<h2><code>@​cloudflare/sandbox</code><a
href="https://github.com/0"><code>@​0</code></a>.12.11</h2>
<h3>Patch Changes</h3>
<ul>
<li>
<p><a
href="https://redirect.github.com/cloudflare/sandbox-sdk/pull/889">#889</a>
<a
href="https://github.com/cloudflare/sandbox-sdk/commit/119336ef67819feda18cf0f716f10db4e1eece73"><code>119336e</code></a>
Thanks <a href="https://github.com/scuffi"><code>@​scuffi</code></a>! -
Stop backups from dropping whole directories when <code>excludes</code>
or <code>gitignore: true</code> match a nested path. For example,
<code>excludes: ['.cache/foo/*/node_modules']</code> no longer removes
all of <code>.cache</code> from the archive. A multi-component pattern
such as <code>build/output</code> now matches only relative to the
backup directory, while a single-component pattern such as
<code>node_modules</code> still matches at any depth. Because mksquashfs
does not support <code>**</code>, a pattern like
<code>**/node_modules/.cache</code> now excludes only
<code>node_modules/.cache</code> at the root of the backup directory;
add a pattern for each nested location that must stay out of the
backup.</p>
</li>
<li>
<p><a
href="https://redirect.github.com/cloudflare/sandbox-sdk/pull/914">#914</a>
<a
href="https://github.com/cloudflare/sandbox-sdk/commit/66862ff45736e416422736b225da90b5f1dd9cd3"><code>66862ff</code></a>
Thanks <a
href="https://github.com/ghostwriternr"><code>@​ghostwriternr</code></a>!
- Return 404 with <code>workspace_read_not_found</code> from the
bridge's <code>GET /v1/sandbox/:id/file/*</code> when the file doesn't
exist. The route used to return 200 with an empty body, the same
response as an empty file.</p>
</li>
<li>
<p><a
href="https://redirect.github.com/cloudflare/sandbox-sdk/pull/894">#894</a>
<a
href="https://github.com/cloudflare/sandbox-sdk/commit/20d72db671876a3e50ab0881758cae7576ae2b6e"><code>20d72db</code></a>
Thanks <a href="https://github.com/scuffi"><code>@​scuffi</code></a>! -
Fix local bucket mounts for large files and write bursts. On the RPC
transport, objects over 4 MiB now stream into the container instead of
failing with an interrupted runtime connection. Container files stream
back to R2 byte for byte, without loading the whole file into Worker
memory. A file being written uploads once its changes settle, instead of
on every write.</p>
</li>
<li>
<p><a
href="https://redirect.github.com/cloudflare/sandbox-sdk/pull/926">#926</a>
<a
href="https://github.com/cloudflare/sandbox-sdk/commit/6678b1378f4ba61586d26f84ee9616a171e6303c"><code>6678b13</code></a>
Thanks <a
href="https://github.com/ghostwriternr"><code>@​ghostwriternr</code></a>!
- Stop writing command text and output to Sandbox logs. Exec and process
log events now record IDs, exit codes, durations, and output lengths,
and the OpenAI Agents <code>Shell</code> and <code>Editor</code>
adapters no longer log commands, stderr, or patch text, so secrets in
commands, output, or patches no longer reach Workers Logs or container
logs. Command failure messages no longer repeat the command; it remains
available on the error's <code>context.command</code>.</p>
</li>
<li>
<p><a
href="https://redirect.github.com/cloudflare/sandbox-sdk/pull/888">#888</a>
<a
href="https://github.com/cloudflare/sandbox-sdk/commit/6c9edcc4e466390f52540e48dbd3809ca80fcc89"><code>6c9edcc</code></a>
Thanks <a href="https://github.com/scuffi"><code>@​scuffi</code></a>! -
Fix <code>restoreBackup()</code> error reporting for archives of 10 MB
or more. A failed download part now throws a
<code>BackupRestoreError</code> that includes curl's error output and
each part's exit code, instead of a <code>Shell terminated
unexpectedly</code> session error.</p>
</li>
<li>
<p><a
href="https://redirect.github.com/cloudflare/sandbox-sdk/pull/887">#887</a>
<a
href="https://github.com/cloudflare/sandbox-sdk/commit/13f477d6fc1b4a73b61d333de6a222e8876de860"><code>13f477d</code></a>
Thanks <a href="https://github.com/scuffi"><code>@​scuffi</code></a>! -
Sync local bucket mounts outside <code>/workspace</code>, such as
<code>/data</code>, from the container back to R2. <code>watch()</code>
and <code>checkChanges()</code> now accept any absolute path on every
transport, as documented. A local mount whose container rejects the
watch now logs one error instead of retrying forever.</p>
</li>
</ul>
<!-- raw HTML omitted -->
</blockquote>
<p>... (truncated)</p>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/cloudflare/sandbox-sdk/commit/b96de6ea1ca248e11a56a78f1efabc2717d6c7b9"><code>b96de6e</code></a>
Version Packages (<a
href="https://redirect.github.com/cloudflare/sandbox-sdk/issues/1034">#1034</a>)</li>
<li><a
href="https://github.com/cloudflare/sandbox-sdk/commit/2e4e1eb304e2cbbf5569e095e3ead296a5efbc87"><code>2e4e1eb</code></a>
Update the container runtime to Bun 1.4.4 (<a
href="https://redirect.github.com/cloudflare/sandbox-sdk/issues/1028">#1028</a>)</li>
<li><a
href="https://github.com/cloudflare/sandbox-sdk/commit/b3a8566c61c15bdc24d216fadb322fd673bb0aca"><code>b3a8566</code></a>
Promote public refs to 0.12.13 (<a
href="https://redirect.github.com/cloudflare/sandbox-sdk/issues/1027">#1027</a>)</li>
<li><a
href="https://github.com/cloudflare/sandbox-sdk/commit/2538b5540b2f79b56af2a81fa0fa2b353948d667"><code>2538b55</code></a>
Version Packages (<a
href="https://redirect.github.com/cloudflare/sandbox-sdk/issues/1026">#1026</a>)</li>
<li><a
href="https://github.com/cloudflare/sandbox-sdk/commit/a4eaa89aada863cda9ea8a7373404029a1a32761"><code>a4eaa89</code></a>
Stop trusting compromised eMudhra intermediates (<a
href="https://redirect.github.com/cloudflare/sandbox-sdk/issues/1023">#1023</a>)</li>
<li><a
href="https://github.com/cloudflare/sandbox-sdk/commit/7fbb9e5dd3a419570fee79bb98365668b5188984"><code>7fbb9e5</code></a>
Keep polling when a rollout wrangler call fails (<a
href="https://redirect.github.com/cloudflare/sandbox-sdk/issues/1018">#1018</a>)</li>
<li><a
href="https://github.com/cloudflare/sandbox-sdk/commit/e3ebd96707fdb86ac68ce1641963864f5e5e4a81"><code>e3ebd96</code></a>
Promote public references to 0.12.12 (<a
href="https://redirect.github.com/cloudflare/sandbox-sdk/issues/1019">#1019</a>)</li>
<li><a
href="https://github.com/cloudflare/sandbox-sdk/commit/0d96b78f58c9e808688352d621249b673767cedf"><code>0d96b78</code></a>
Version Packages (<a
href="https://redirect.github.com/cloudflare/sandbox-sdk/issues/1004">#1004</a>)</li>
<li><a
href="https://github.com/cloudflare/sandbox-sdk/commit/d62f020d6b1cae787fc676c11b29b7718c40f575"><code>d62f020</code></a>
Create s3fs support files owner-only from the start (<a
href="https://redirect.github.com/cloudflare/sandbox-sdk/issues/1016">#1016</a>)</li>
<li><a
href="https://github.com/cloudflare/sandbox-sdk/commit/98b787b81b5526851af95e6be9ca98da13ae450d"><code>98b787b</code></a>
Stop cutting off quiet exec streams (<a
href="https://redirect.github.com/cloudflare/sandbox-sdk/issues/1013">#1013</a>)</li>
<li>Additional commits viewable in <a
href="https://github.com/cloudflare/sandbox-sdk/compare/@cloudflare/sandbox@0.7.21...@cloudflare/sandbox@0.12.14">compare
view</a></li>
</ul>
</details>
<br />

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-12-04 19:50:26 -08: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 042cb67370 fix(ui): keep Composio connect navigation from closing back to /apps (#23845)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The Plugins page lets users connect third-party apps directly or
through aggregators like Composio and Arcade.
> - When an app offers multiple aggregators, clicking Connect opens
AggregatorConnectDialog so the user can choose a provider.
> - Selecting Composio with no saved Composio gateway, or clicking
Connect new account, called onNavigate and then immediately called
onClose.
> - In Browse, closeAggregatorSetup checked window.location.search for
source=composio, matched the URL that onNavigate had just pushed, and
replaced the route with /apps.
> - This pull request stops in-app dialog navigation from calling
onClose, clears dialog state in Browse's navigation handler, and reads
React Router's location.search instead of window.location.search.
> - The benefit is that choosing Composio or adding a new Composio
account from the connect modal navigates cleanly to /apps/connect while
dismissing the modal still strips ?source=composio.

## Linked Issues or Issue Description

No public GitHub issue exists for this report (searched open and closed
issues and PRs for duplicates).

**What happened?**

When going to Plugins -> Slack -> Connect and clicking Composio without
a saved Composio gateway, the connect modal closed and redirected back
to /apps instead of opening
/apps/connect?source=composio&targetToolkit=slack. The same redirect
happened when opening the modal via
/apps?source=composio&targetToolkit=slack and clicking Connect new
account.

**Expected behavior**

Clicking Composio with no saved Composio gateway navigates to
/apps/connect?source=composio&targetToolkit=slack. Clicking Connect new
account navigates to
/apps/connect?source=composio&targetToolkit=slack&new=1. Dismissing the
modal without navigating still closes it and strips ?source=composio
back to /apps.

**Steps to reproduce**

1. Open Plugins on a Cloud instance where Slack yields to aggregators
and no Composio gateway is saved.
2. Open Slack and click Connect.
3. Click Composio in the Connect Slack dialog.
4. Observe that the dialog closes and the page stays on /apps instead of
navigating to /apps/connect?source=composio&targetToolkit=slack.

**Access context**

Board (human operator)

## What Changed

- Updated `ui/src/pages/apps/AggregatorConnectDialog.tsx` so in-app
navigation handlers (`choose`, `onConnectNew`, and the non-Composio
"Connect a new account" button) call only `onNavigate` without also
invoking `onClose`.
- Updated `ui/src/pages/apps/Browse.tsx` to pass
`navigateFromAggregatorSetup` as `AggregatorConnectDialog`'s
`onNavigate` prop so navigation clears dialog state without triggering
`closeAggregatorSetup`'s `?source=composio` redirect cleanup.
- Switched `Browse.tsx` from `window.location.search` to React Router's
`useLocation().search` for the `?source=...` effect and dismissal
cleanup.
- Added `ui/src/pages/apps/Browse.aggregatorConnect.test.tsx` with real
`BrowserRouter` regression tests covering Plugins -> Slack -> Connect ->
Composio, new-account navigation from `?source=composio`, dismissal
cleanup, and staying on the plugin page when cancelling.

## Verification

- Verified TDD red-before / green-after on
`ui/src/pages/apps/Browse.aggregatorConnect.test.tsx`: before the fix,
both Composio navigation tests failed with `Received: "/PAP/apps"`
instead of `/PAP/apps/connect?source=composio&targetToolkit=slack` and
`...&new=1`.
- Ran `pnpm vitest run
ui/src/pages/apps/Browse.aggregatorConnect.test.tsx
ui/src/pages/apps/Browse.pluginTileState.test.ts
ui/src/pages/apps/AppsConnect.test.tsx
ui/src/lib/analytics/replay-masking.test.tsx` on rebased HEAD
`c605d6358c`: 4 test files, 243 tests passed.
- Ran `pnpm --filter @paperclipai/ui typecheck`: passed with 0 errors.
- CI covers repo-wide typecheck, build, and test suites on the pushed PR
revision.

## Risks

- Low risk. Changes are scoped to `AggregatorConnectDialog` and
`Browse`'s aggregator connect dialog wiring. Dismissal actions (Cancel,
Escape, dialog close, completion, and external management links) still
invoke `closeAggregatorSetup` to invalidate aggregator queries and strip
`?source=composio`.

## Model Used

- Google Gemini 4 (Antigravity agent with extended reasoning and local
tool/test execution).

## Checklist

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

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-12-04 20:56:22 -06:00
dependabot[bot] 2d7bb6392d build(deps): bump actions/checkout from 4.2.2 to 7.0.1 (#19561)
Bumps [actions/checkout](https://github.com/actions/checkout) from 4.2.2
to 7.0.1.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/actions/checkout/releases">actions/checkout's
releases</a>.</em></p>
<blockquote>
<h2>v7.0.1</h2>
<h2>What's Changed</h2>
<ul>
<li>skip running unsafe pr check if input is default by <a
href="https://github.com/aiqiaoy"><code>@​aiqiaoy</code></a> in <a
href="https://redirect.github.com/actions/checkout/pull/2518">actions/checkout#2518</a></li>
<li>trim only ascii whitespace for branch by <a
href="https://github.com/aiqiaoy"><code>@​aiqiaoy</code></a> in <a
href="https://redirect.github.com/actions/checkout/pull/2521">actions/checkout#2521</a></li>
<li>escape values passed to --unset by <a
href="https://github.com/aiqiaoy"><code>@​aiqiaoy</code></a> in <a
href="https://redirect.github.com/actions/checkout/pull/2530">actions/checkout#2530</a></li>
<li>Various dependency updates</li>
</ul>
<p><strong>Full Changelog</strong>: <a
href="https://github.com/actions/checkout/compare/v7...v7.0.1">https://github.com/actions/checkout/compare/v7...v7.0.1</a></p>
<h2>v7.0.0</h2>
<h2>What's Changed</h2>
<ul>
<li>block checking out fork pr for pull_request_target and workflow_run
by <a href="https://github.com/aiqiaoy"><code>@​aiqiaoy</code></a> in <a
href="https://redirect.github.com/actions/checkout/pull/2454">actions/checkout#2454</a></li>
<li>Bump actions/publish-immutable-action from 0.0.3 to 0.0.4 in the
minor-actions-dependencies group across 1 directory by <a
href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot]
in <a
href="https://redirect.github.com/actions/checkout/pull/2458">actions/checkout#2458</a></li>
<li>Bump flatted from 3.3.1 to 3.4.2 by <a
href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot]
in <a
href="https://redirect.github.com/actions/checkout/pull/2460">actions/checkout#2460</a></li>
<li>Bump js-yaml from 4.1.0 to 4.2.0 by <a
href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot]
in <a
href="https://redirect.github.com/actions/checkout/pull/2461">actions/checkout#2461</a></li>
<li>Bump <code>@​actions/core</code> and
<code>@​actions/tool-cache</code> and Remove uuid by <a
href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot]
in <a
href="https://redirect.github.com/actions/checkout/pull/2459">actions/checkout#2459</a></li>
<li>upgrade module to esm and update dependencies by <a
href="https://github.com/aiqiaoy"><code>@​aiqiaoy</code></a> in <a
href="https://redirect.github.com/actions/checkout/pull/2463">actions/checkout#2463</a></li>
<li>Bump the minor-npm-dependencies group across 1 directory with 3
updates by <a
href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot]
in <a
href="https://redirect.github.com/actions/checkout/pull/2462">actions/checkout#2462</a></li>
<li>getting ready for checkout v7 release by <a
href="https://github.com/aiqiaoy"><code>@​aiqiaoy</code></a> in <a
href="https://redirect.github.com/actions/checkout/pull/2464">actions/checkout#2464</a></li>
<li>update error wording by <a
href="https://github.com/aiqiaoy"><code>@​aiqiaoy</code></a> in <a
href="https://redirect.github.com/actions/checkout/pull/2467">actions/checkout#2467</a></li>
</ul>
<h2>New Contributors</h2>
<ul>
<li><a href="https://github.com/aiqiaoy"><code>@​aiqiaoy</code></a> made
their first contribution in <a
href="https://redirect.github.com/actions/checkout/pull/2454">actions/checkout#2454</a></li>
</ul>
<p><strong>Full Changelog</strong>: <a
href="https://github.com/actions/checkout/compare/v6.0.3...v7.0.0">https://github.com/actions/checkout/compare/v6.0.3...v7.0.0</a></p>
<h2>v6.1.0</h2>
<h2>What's Changed</h2>
<ul>
<li><strong>[BREAKING]</strong> backport
<code>allow-unsafe-pr-checkout</code> to v6 by <a
href="https://github.com/aiqiaoy"><code>@​aiqiaoy</code></a> in <a
href="https://redirect.github.com/actions/checkout/pull/2500">actions/checkout#2500</a></li>
<li>backport fixes to releases-v6 by <a
href="https://github.com/aiqiaoy"><code>@​aiqiaoy</code></a> in <a
href="https://redirect.github.com/actions/checkout/pull/2527">actions/checkout#2527</a></li>
</ul>
<p><a
href="https://github.blog/changelog/2026-06-18-safer-pull_request_target-defaults-for-github-actions-checkout/">https://github.blog/changelog/2026-06-18-safer-pull_request_target-defaults-for-github-actions-checkout/</a>
for more details about this breaking change</p>
<p><strong>Full Changelog</strong>: <a
href="https://github.com/actions/checkout/compare/v6.0.3...v6.1.0">https://github.com/actions/checkout/compare/v6.0.3...v6.1.0</a></p>
<h2>v6.0.3</h2>
<h2>What's Changed</h2>
<ul>
<li>Update changelog by <a
href="https://github.com/ericsciple"><code>@​ericsciple</code></a> in <a
href="https://redirect.github.com/actions/checkout/pull/2357">actions/checkout#2357</a></li>
<li>fix: expand merge commit SHA regex and add SHA-256 test cases by <a
href="https://github.com/yaananth"><code>@​yaananth</code></a> in <a
href="https://redirect.github.com/actions/checkout/pull/2414">actions/checkout#2414</a></li>
<li>Fix checkout init for SHA-256 repositories by <a
href="https://github.com/yaananth"><code>@​yaananth</code></a> in <a
href="https://redirect.github.com/actions/checkout/pull/2439">actions/checkout#2439</a></li>
<li>Update changelog for v6.0.3 by <a
href="https://github.com/yaananth"><code>@​yaananth</code></a> in <a
href="https://redirect.github.com/actions/checkout/pull/2446">actions/checkout#2446</a></li>
</ul>
<h2>New Contributors</h2>
<ul>
<li><a href="https://github.com/yaananth"><code>@​yaananth</code></a>
made their first contribution in <a
href="https://redirect.github.com/actions/checkout/pull/2414">actions/checkout#2414</a></li>
</ul>
<p><strong>Full Changelog</strong>: <a
href="https://github.com/actions/checkout/compare/v6...v6.0.3">https://github.com/actions/checkout/compare/v6...v6.0.3</a></p>
<h2>v6.0.2</h2>
<h2>What's Changed</h2>
<ul>
<li>Add orchestration_id to git user-agent when ACTIONS_ORCHESTRATION_ID
is set by <a
href="https://github.com/TingluoHuang"><code>@​TingluoHuang</code></a>
in <a
href="https://redirect.github.com/actions/checkout/pull/2355">actions/checkout#2355</a></li>
</ul>
<!-- raw HTML omitted -->
</blockquote>
<p>... (truncated)</p>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/actions/checkout/commit/3d3c42e5aac5ba805825da76410c181273ba90b1"><code>3d3c42e</code></a>
prep v7.0.1 release (<a
href="https://redirect.github.com/actions/checkout/issues/2531">#2531</a>)</li>
<li><a
href="https://github.com/actions/checkout/commit/28802689a136bfcdb721715abd713740beecbe07"><code>2880268</code></a>
escape values passed to --unset (<a
href="https://redirect.github.com/actions/checkout/issues/2530">#2530</a>)</li>
<li><a
href="https://github.com/actions/checkout/commit/12cd2235efa0937479335606d7c3ac9f6c0973b1"><code>12cd223</code></a>
trim only ascii whitespace for branch (<a
href="https://redirect.github.com/actions/checkout/issues/2521">#2521</a>)</li>
<li><a
href="https://github.com/actions/checkout/commit/62661c4e71a304b2823ed026347b8d34c3eac541"><code>62661c4</code></a>
skip running unsafe pr check if input is default (<a
href="https://redirect.github.com/actions/checkout/issues/2518">#2518</a>)</li>
<li><a
href="https://github.com/actions/checkout/commit/e8d4307400f9427dba7cb98e488d6ab85f1cec5f"><code>e8d4307</code></a>
Bump the minor-actions-dependencies group with 2 updates (<a
href="https://redirect.github.com/actions/checkout/issues/2499">#2499</a>)</li>
<li><a
href="https://github.com/actions/checkout/commit/631c942040754b6e095e929c1677c07e10ed4f87"><code>631c942</code></a>
eslint 9 (<a
href="https://redirect.github.com/actions/checkout/issues/2474">#2474</a>)</li>
<li><a
href="https://github.com/actions/checkout/commit/4f1f4aec02e41874fa0262ea8ff5172d7978ad1e"><code>4f1f4ae</code></a>
Bump actions/upload-artifact from 4 to 7 (<a
href="https://redirect.github.com/actions/checkout/issues/2476">#2476</a>)</li>
<li><a
href="https://github.com/actions/checkout/commit/ba097532fb203f7e88c9c3c0b899b49469908a92"><code>ba09753</code></a>
Bump actions/checkout from 6 to 7 (<a
href="https://redirect.github.com/actions/checkout/issues/2488">#2488</a>)</li>
<li><a
href="https://github.com/actions/checkout/commit/b9e0990d219a03df7633c93f6f005a8fecbcab22"><code>b9e0990</code></a>
Bump docker/login-action from 3.3.0 to 4.2.0 (<a
href="https://redirect.github.com/actions/checkout/issues/2479">#2479</a>)</li>
<li><a
href="https://github.com/actions/checkout/commit/e8cb398be4a550817e382abf69e4c12c76fce1f2"><code>e8cb398</code></a>
Bump docker/build-push-action from 6.5.0 to 7.2.0 (<a
href="https://redirect.github.com/actions/checkout/issues/2478">#2478</a>)</li>
<li>Additional commits viewable in <a
href="https://github.com/actions/checkout/compare/v4.2.2...v7.0.1">compare
view</a></li>
</ul>
</details>
<br />

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-12-05 02:49:47 +00:00
Dotta fd8ad7d5b8 fix(ui): remove environment selector from AI connection setup (#23836)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Users connect AI provider accounts (Claude, OpenAI, Antigravity,
xAI, and GitHub Copilot) through `AiConnectionCredentialStep`
> - AI connections store credentials in Paperclip's secret store and do
not bind the saved connection to an execution environment
> - When a company had more than one active login-capable environment,
the setup form showed a raw environment dropdown (exposing internal
sandbox names and appearing even for API key or hosted OAuth flows)
> - The component already resolves the default login or probe
environment automatically
> - This pull request removes the environment selector dropdowns from
`AiConnectionCredentialStep` while preserving automatic environment
resolution
> - The benefit is a simpler AI connection flow that does not leak
internal execution infrastructure into provider account setup

## Linked Issues or Issue Description

**What existing behavior does this improve?**

The AI provider connection setup screen (`AiConnectionCredentialStep`)
for Anthropic (Claude), OpenAI, Google (Antigravity), xAI (Grok), and
GitHub Copilot.

**Subsystem affected**

`ui/` — React + Vite board UI

**Current behavior**

When a company has more than one active login-capable environment,
`SubscriptionConnectionStep` renders a `Sign-in environment` dropdown
and `ApiKeyConnectionStep` renders a `Copilot execution environment`
dropdown. The dropdown appears even for hosted Google OAuth or when the
user switches to an API key, and it exposes internal sandbox labels such
as `Paperclip Sandbox (Legacy)`.

**Proposed behavior**

Remove both environment dropdowns from `AiConnectionCredentialStep` and
update the GitHub Copilot help text to say verification discovers models
automatically. Continue resolving `environmentId` automatically from the
forced Kubernetes environment, instance default, plugin login target
preferences, or local default environment.

**Reason and benefit**

Saved AI connections are not bound to an execution environment; the
environment is only an internal detail for running a temporary
subscription login PTY or Copilot model probe. Removing the dropdown
eliminates user confusion and keeps internal infrastructure out of the
Apps connect flow.

**Breaking changes**

Users can no longer manually override the temporary login/probe
environment from the standalone AI connection setup form; Paperclip uses
the automatically resolved default environment instead. Agent-scoped
flows that pass `environmentId` explicitly continue to use the supplied
environment.

## What Changed

- Removed the `Sign-in environment` `<Select>` and unused
`chosenEnvironment` state from `SubscriptionConnectionStep` in
`ui/src/components/ai-connections/AiConnectionCredentialStep.tsx`.
- Removed the `Copilot execution environment` `<Select>` and unused
`chosenEnvironment` state from `ApiKeyConnectionStep` in
`ui/src/components/ai-connections/AiConnectionCredentialStep.tsx`, and
updated the Copilot help text to match.
- Added
`ui/src/components/ai-connections/AiConnectionCredentialStep.test.tsx`
to verify that no environment selector renders for Anthropic, OpenAI,
Google, xAI, or GitHub Copilot when multiple environments exist, while
automatic `environmentId` resolution is preserved.

## Verification

- `pnpm --filter @paperclipai/ui exec vitest run
src/components/ai-connections/AiConnectionCredentialStep.test.tsx` — 5/5
tests passed.
- `pnpm --filter @paperclipai/ui typecheck` — passed.
- `pnpm verify` — 270/271 UI test files passed in the combined run (1
unrelated `requestAnimationFrame` timing failure in
`src/components/TaskChatThread.test.tsx`); re-running `pnpm --filter
@paperclipai/ui exec vitest run src/components/TaskChatThread.test.tsx
src/components/ai-connections/AiConnectionCredentialStep.test.tsx`
passed all 444 tests (1 skipped).

## Risks

- Low risk. Self-hosted instances with multiple login-capable
environments now always use the automatically resolved default
environment during standalone AI account sign-in rather than exposing a
per-login override dropdown.

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

## Model Used

- Google Gemini (Antigravity agent, medium reasoning effort, with
repository read/edit, terminal, and browser inspection tools).

## Checklist

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

> - Paperclip manages work performed by AI agents.
> - Task monitors schedule later checks.
> - A saved schedule can remain present during a new run.
> - The UI calls that state a wait even while the agent works.
> - This change gives the current run priority over monitor notices.
> - Users see the monitor again after the run ends.

## Linked Issues or Issue Description

Refs #19519, which added the active-run wait message. This change
removes that message during execution. Searches found no open duplicate,
and the roadmap has no overlapping item. The small SSH fixture repair
below addresses a CI regression introduced on master by #14309.

**What happened?**

A task showed a running agent and a monitor waiting notice at the same
time. The notice said the agent was waiting or saving work, based only
on the presence of a run.

**Expected behavior**

Show the current run without monitor waiting notices. Keep the saved
schedule. Restore both monitor surfaces after execution ends, if the
monitor remains scheduled.

**Steps to reproduce**

1. Schedule a task monitor.
2. Start a run on the same task before its next check.
3. Inspect the task banner and composer while the run works.
4. End the run and confirm the retained monitor appears again.

**Paperclip version or commit**

Reproduced against master at dfe392dada
with mounted production components.

**Deployment mode**

Source checkout on macOS arm64 with Node v25.6.1. Browser checks use
disposable local servers. No deployment is part of this PR.

## What Changed

- Hide the banner and composer monitor notice while a task run is queued
or running. Use the existing live-run state; add no request.
- Restore countdowns, PR review links, and check controls after
execution ends. Keep workspace and usage retry waits visible.
- Add mounted regressions for future, due-now, overdue, review, and
retry states. Update the product and monitor documentation.
- Pass the stdin command envelope to the new dash SSH test from master.
This one-line repair changes only its test input.
- Make the connection-review race fixture drop exactly one initial
interaction snapshot, through either bootstrap or the standalone
endpoint. Preserve all other bootstrap data and keep dropping the live
creation event. Keep the approval assertions, timeouts, and retry
settings unchanged.

## Verification

Current head: `cfdbbb22839`.

- Red-green: four new monitor regression cases failed against the
original implementation, then passed with the fix.
- From ui/: `pnpm exec vitest run
src/components/IssueMonitorBanner.test.tsx
src/lib/issue-monitor.test.tsx
src/pages/IssueDetail.agentChatPanel.test.tsx
src/pages/IssueDetail.mobile.test.tsx` passes: 44 tests in four files,
including after the master merge.
- UI and adapter-utils typechecks pass. `git diff --check` passes.
- The new monitor transition test initially crossed a real countdown
boundary. Its clock is now fixed. The fresh worktree initially lacked
plugin SDK declarations; building them restored the UI typecheck.
- The focused dash regression reproduced CI exit 125 without stdin.
Passing `target.stdinPrefix` makes it pass. No SSH runtime code changed.
- Both stale chat-settings grant/revocation cases pass locally with two
Chromium workers. The original [e2e shard 13
failure](https://github.com/paperclipai/paperclip/actions/runs/47463601089/job/145495043379)
remains unexplained; the same shard passed in the next CI run without a
settings change.
- The connection-review decline journey passes in Chromium with trace
capture: `PAPERCLIP_E2E_PORT=43984 PAPERCLIP_E2E_SKIP_UI_BUILD=1 pnpm
exec playwright test --config tests/e2e/playwright.config.ts
tests/e2e/connection-reviews.spec.ts --grep 'connection review: decline'
--workers=1 --trace=on --reporter=line --output=<scratch>`. E2E
test-project typecheck also passes.
- Before that fixture repair, the local trace shows bootstrap at
02:08:50, an empty first recovery poll at 02:09:11, and the review
arriving on the second poll at 02:09:31. The corrected trace shows
bootstrap at 02:10:29 and the review on the first poll at 02:10:50. The
original fixture was consuming a recovery read rather than the initial
snapshot. The complete decline and continuation assertions pass with the
correction.
- The [first CI
run](https://github.com/paperclipai/paperclip/actions/runs/47463601089)
failed in the SSH fixture and the chat-settings case. The [second run on
e9fced7](https://github.com/paperclipai/paperclip/actions/runs/47464395894)
passed all general tests, build, typecheck, Runner checks, and 15
browser shards. Its [connection-review
failure](https://github.com/paperclipai/paperclip/actions/runs/47464395894/job/145499941920)
is addressed by the fixture correction above. These original failures
remain part of the evidence; later passes do not erase them.
- Greptile scored the current head
cfdbbb2283 at 5/5 with no actionable
findings or open threads. Required CI passes on this head.
- The token scan reports three existing violations: two task-number
strings in transcript-adapter.test.ts and one grid class in
AdapterLoginChrome.tsx. Those files and the scanner match the base
branch. This PR adds no visual values.
- Broad local selection was inspected with `pnpm verify --explain`; that
command did not execute the selected suite. Final CI supplies the
broader coverage. Added lines and PR text were scanned for secrets,
private endpoints, personal data, and run artifacts before push.

Final qualification for cfdbbb2283:

- [Final CI
run](https://github.com/paperclipai/paperclip/actions/runs/47466120239):
80 successful checks and four skipped checks, with no failures or
pending checks. Both required aggregates, ci / verify and ci / e2e,
pass. All 16 browser shards pass, including the repaired
connection-review journey.
- Greptile's completed check and 5/5 summary both name this exact head.
No review comments or unresolved threads remain.
- GitHub reports MERGEABLE and CLEAN against master. The worktree is
clean. This PR is ready to merge; it has not been merged or deployed.

## Risks

Low risk. Delayed live-run query updates can briefly delay notice
transitions. PR review links inside these notices are hidden during
execution and return afterward. The two CI repairs affect test fixtures
only. Schedules, execution admission, ownership, authorization, approval
behavior, and schema stay unchanged. Required CI passes on this head.

## Model Used

OpenAI Codex, gpt-6.1-sol, with xhigh reasoning effort, repository
inspection, code editing, shell tools, and test execution.

## Checklist

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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-12-04 18:35:01 -08:00