Commit Graph
9023 Commits
Author SHA1 Message Date
Saurabh Sunghandcommitperclip[bot] 180b99d579 fix(claude-local): ignore host env in ACP billing when managed connection is used (#22422)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The claude_local adapter's ACP lane classifies cost events for the
ledger via resolveClaudeAcpBillingIdentity
> - When an agent runs with a managed AI subscription connection and the
host process happens to have ANTHROPIC_API_KEY in its environment,
resolveClaudeAcpBillingIdentity incorrectly inspected process.env
because considerHostEnv only checked whether target.kind was remote
> - The probe (testClaudeAcpEnvironment) and execution paths in the same
package already check !targetIsRemote && !config.managedAiConnection,
and the CLI lane only inspects the effective run environment
> - This pull request updates considerHostEnv in
resolveClaudeAcpBillingIdentity to also check
!config.managedAiConnection, preventing host environment leaks from
misclassifying subscription runs as metered API spend
> - The benefit is that subscription runs on managed AI connections
correctly file as subscription_included at $0 rather than metered API
spend even if the host environment has an Anthropic key

## Linked Issues or Issue Description

Fixes #22388

Related: #20955

## What Changed

- Updated `resolveClaudeAcpBillingIdentity` in
`packages/adapters/claude-local/src/server/acp.ts` to gate
`considerHostEnv` on `!config.managedAiConnection`, aligning it with
`testClaudeAcpEnvironment` and `testEnvironment`.
- Added unit tests in
`packages/adapters/claude-local/src/server/acp.test.ts` verifying that
`resolveClaudeAcpBillingIdentity` ignores host environment when
`managedAiConnection` is configured, while preserving `api` billing when
`managedAiConnection` is used with `api_key` and config credentials.

## Verification

- Ran `vitest run packages/adapters/claude-local/src/server/acp.test.ts`
(43 passed).
- Built package via `pnpm --filter @paperclipai/adapter-claude-local
build` (0 TypeScript errors).
- Ran all ACP suites in `claude-local` (`acp.auth.test.ts`,
`acp.quota.test.ts`, `acp.test.ts`) (97 passed).

## Risks

- Low risk: Only affects ACP billing identity resolution when
`managedAiConnection` is set. Unmanaged local runs and remote execution
targets maintain their existing behavior.

## Model Used

- Model: Gemini 2.5 Flash
- Reasoning: Chain-of-thought analysis, autonomous codebase
investigation, test-driven reproduction, and verification

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [ ] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] 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: commitperclip[bot] <284812584+commitperclip[bot]@users.noreply.github.com>
2026-12-05 04:55:31 -08:00
Jason e7ecb66d42 fix(server): store JSON null for plugin state values (#22409)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Plugins keep key/value state through the plugin SDK `state.set(key,
value)`, and the server stores it in `plugin_state.value_json`
> - The SDK type allows any JSON value, including `null`, but the column
is `jsonb NOT NULL`
> - `plugin-state-store.ts` passes JS `null` to Drizzle, and Drizzle
writes SQL NULL for it instead of JSON `null`
> - So `state.set(key, null)` fails with `null value in column
"value_json" ... violates not-null constraint`, on insert and on
overwrite
> - This pull request writes the JSON literal `'null'::jsonb` for a null
value on both the insert and the conflict-update paths, and rejects
`undefined` with a clear 400 error
> - The benefit is that plugins can store and clear values with `null`
as the SDK contract says

## Linked Issues or Issue Description

Fixes: #22150

## What Changed

- `server/src/services/plugin-state-store.ts`: a `null` value is written
as `'null'::jsonb` for insert and for upsert update. Other values keep
the current parameterized encoding. A top-level `undefined` value now
gets a 400 `badRequest` and does not change the stored row.
- `server/src/__tests__/plugin-state-store-postgres.test.ts`: new tests
on real embedded Postgres. They cover a null insert, value → null →
value, `get` and `list`, instance and company upserts,
plugin/company/namespace isolation, and `undefined` rejection. They also
check `jsonb_typeof(value_json) = 'null'`, so the row holds JSON null
and not SQL NULL.

## Verification

- Red: before the fix, the Postgres tests fail with `PostgresError: null
value in column "value_json" of relation "plugin_state" violates
not-null constraint` (6 failed).
- Green: `pnpm exec vitest run
server/src/__tests__/plugin-state-store-postgres.test.ts` gives `6
passed (6)`.
- `pnpm --filter @paperclipai/server typecheck` passes.

## Risks

- Low risk. The SQL uses only a fixed `'null'::jsonb` literal. Scope
predicates do not change. No schema or migration changes.
- `undefined` now gets a 400 error. Before, it failed with the same
database constraint error, so no working call changes.
- Not in scope: a stored JSON string `"null"` is read back as `null` by
the current driver/Drizzle decoding. This occurs without this change. I
can open a separate issue for it.

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

## Model Used

- Devin (Cognition AI) autonomous coding agent, with tool use and code
execution (shell, pnpm, vitest, embedded Postgres, git). The agent wrote
the change and the tests. A human (the PR author) reviewed 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
- [ ] 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 04:44:09 -08:00
Mehmet Yağız MaktavandClaude Opus 5.5 513f9522dc fix(hermes-gateway): retry a create request refused during a gateway drain (#22311)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The `hermes_gateway` adapter starts a run with `POST /v1/runs` on a
running Hermes gateway
> - A Hermes gateway that drains for a restart refuses new runs with
HTTP 503 and the code `gateway_draining`. Hermes does not start a run
for that request
> - The adapter reported the refusal as a plain upstream error. It gave
no evidence that provider work did not start
> - So the retry scheduler found no proof of a safe retry. It did not
schedule the bounded transient retry and held the run as
`legacy_execution_requires_reconciliation`. The parent task then blocked
on children that never started
> - This pull request makes the adapter record `executionRecovery: {
kind: "bootstrap", providerWorkStarted: false }` only for that explicit
drain refusal of the create request
> - The benefit is that the existing bounded transient retry runs again
after the drain. Uncertain outcomes keep their reconciliation safeguard

## Linked Issues or Issue Description

Fixes: #15236

Related: #10422 and #10424 (`hermes_local` error classification, a
different path). #17235 was a closed, larger attempt to book Hermes
profile-capacity deferrals as waits. This PR does not touch that path.

## What Changed

- `packages/adapters/hermes/src/gateway/server/execute.ts`: `fetchJson`
marks an error as a drain admission refusal at the request boundary, in
a `WeakSet`. This is the same provenance pattern as
`requestConnectionFailures`. The mark needs all three conditions: status
503, a response that was not redirected, and `error.code ===
"gateway_draining"` in the body. `errorResult`, which only the
create-run path uses, then adds the bootstrap evidence. The error code,
error family, `retryNotBefore` and connection-failure marker do not
change.
- `packages/adapters/hermes/src/gateway/server/execute.test.ts`: tests
for the evidence on a drain refusal. Tests that the outcome stays
unknown for another 503 code, a top-level code, a drain code on 502 or
429, and a redirected response. A test that a drain 503 after an
accepted run gives no evidence. The forged-callback test also covers a
forged drain error.
- `server/src/__tests__/hermes-gateway-drain-admission.test.ts`: runs
the real adapter result through the server classifiers. A drain refusal
takes the transient retry contract and is not held for reconciliation on
the first and second failures. After two charged retries it is held
again. A plain 503 stays held.

## Verification

- `cd packages/adapters/hermes && npx vitest run src/gateway`: 116
passed.
- `cd server && npx vitest run
src/__tests__/hermes-gateway-drain-admission.test.ts`: 2 passed.
- Red check: with only `execute.ts` reverted, the new adapter test fails
(`executionRecovery` is undefined).
- `pnpm --filter @paperclipai/hermes-paperclip-adapter typecheck` and
`cd server && pnpm typecheck` pass.
- I did not run a live Hermes gateway drain. The 503 body and
`Retry-After: 1` header in the tests match Hermes
`gateway/platforms/api_server.py` (`_draining_response`) and its test
`tests/gateway/test_api_server_active_work_drain.py`.

## Risks

- Low risk. The change only affects a direct 503 `gateway_draining`
response to the create request. Every other failure keeps its current
classification.
- The retry budget does not change:
`BOUNDED_TRANSIENT_HEARTBEAT_RETRY_DELAYS_MS` (about 30 s, then 60 s,
with jitter). A drain that lasts longer than these retries still
exhausts them. After that the existing reconciliation hold applies, as
for other exhausted bootstrap failures. A drain-aware wait would need a
scheduler change, which this PR does not make.
- Hermes sends `Retry-After: 1` (seconds). The adapter forwards the raw
header value as before. That value is earlier than the base retry delay,
so the base schedule wins.

## Model Used

- AI-assisted with Claude Code (tool use and local code execution). The
commit carries the matching `Co-Authored-By` trailer.

## 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 (no
documentation change needed)
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

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

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 04:27:12 -08:00
Ludovic Gasc 78848ae785 fix(server): scrub systemd notify env vars at startup (#22117)
## Thinking Path

> - Paperclip manages AI agents from a control-plane server that runs
under a systemd user service on Linux hosts.
> - Systemd sets `NOTIFY_SOCKET`, `LISTEN_FDS`, `LISTEN_PID`, and
`LISTEN_FDNAMES` in the server environment, and the generated unit uses
`Type=notify` and `NotifyAccess=all`.
> - `#11584` strips those variables inside `runChildProcess`, but
`process.env` in the server process still keeps them.
> - Workspace provisioning commands, plugin workers, external adapters,
and container tools such as `podman run` (`conmon` with default
`--sdnotify=container`) still inherit
`NOTIFY_SOCKET` and can send `STOPPING=1` or `MAINPID=` to systemd.
> - When a child process sends `MAINPID=<child_pid>` and then exits
non-zero, systemd stops the entire `paperclipai.service` cgroup with
`SIGTERM` and interrupts every active run.
> - This pull request captures `NOTIFY_SOCKET` once in
`server/src/services/systemd-notify.ts` and removes the four systemd
variables from `process.env` at startup.
> - The benefit is that only `systemd-notify` invocations from the
server receive `NOTIFY_SOCKET`, while all server descendants remain
isolated from the systemd control channel.

## Linked Issues or Issue Description

Fixes: #14657
Refs: #13608, #11584

## What Changed

- Update `server/src/services/systemd-notify.ts` to capture
`NOTIFY_SOCKET` via `consumeSystemdNotifySocket()` at module load and
delete `NOTIFY_SOCKET`, `LISTEN_FDS`, `LISTEN_PID`,
and `LISTEN_FDNAMES` from `process.env`.
- Pass the captured `NOTIFY_SOCKET` only in the `env` option of
`execFile("systemd-notify", ...)` inside `systemdNotify()`.
- Add unit tests in `server/src/__tests__/systemd-notify.test.ts`
covering startup scrubbing, `systemdNotify` env isolation, missing
`NOTIFY_SOCKET`, and error handling.

## Verification

- Ran `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/systemd-notify.test.ts`: 4 tests passed.
- Ran strict TypeScript check (`tsc --noEmit --strict`) on
`server/src/services/systemd-notify.ts` and
`server/src/__tests__/systemd-notify.test.ts`: 0 errors.
- Confirmed in a running systemd user service that spawned child
processes and agent runs no longer inherit `NOTIFY_SOCKET` while
`systemdNotify(["--ready", ...])` still marks the
service active.

## Risks

- Low risk. The change removes only `NOTIFY_SOCKET`, `LISTEN_FDS`,
`LISTEN_PID`, and `LISTEN_FDNAMES` from the server `process.env` after
capturing `NOTIFY_SOCKET` in memory. Any
caller of `systemdNotify()` still works as before, and any future write
to `process.env.NOTIFY_SOCKET` is consumed on the next call.

## Model Used

- Google Gemini (Antigravity CLI, Orchestrator (Argon)) with tool use
and shell execution.

## Checklist

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

> - Paperclip is the open source app people use to manage AI agents for
work
> - The shared ACPX engine keeps each agent session in files that ACPX
names after the session key
> - The session key holds two UUIDs, the task key and a fingerprint, so
its length is not bounded
> - When a file name is longer than the NAME_MAX of the file system, the
session cannot start (`acpx_session_init_failed`, `ENAMETOOLONG`)
> - With ACPX 0.12.0, summary-slot task keys exceeded 255 bytes and
failed on all Linux file systems (#17785). With ACPX 0.22.0 they fit,
but only with 6 bytes to spare
> - On eCryptfs (NAME_MAX 143), a UUID task key also fails. Synology
encrypted shared folders use eCryptfs, and self-hosted users often put
the Paperclip home on an NFS export of such a folder
> - This pull request replaces a key that is too long with a
fixed-length digest of that key
> - The benefit is that every session file name fits in 143 bytes, and
keys that fit now stay the same

## Linked Issues or Issue Description

Refs #17785

The ACPX 0.22.0 upgrade (#20770) removed the `.<pid>.<ms>.tmp` suffix
that made the summary-slot names in #17785 longer than 255 bytes. This
change removes the remaining risk: no session file name can be longer
than 143 bytes, whatever the task key is.

The same failure also occurs on eCryptfs with shorter keys. A
self-hosted instance on Kubernetes has `PAPERCLIP_HOME` on an NFS export
of a Synology encrypted shared folder (`namlen=143` in the mount
options). On release `v2026.1106.0` (ACPX 0.12.0), a heartbeat run
failed in `ensure_session`:

```
ENAMETOOLONG: name too long, open '<home>/companies/<company>/acp-engine/agents/<agent>/sessions/paperclip%3A<company>%3A<agent>%3A__heartbeat__%3A<16-hex>.json.<pid>.<ms>.tmp' (acpx_session_init_failed)
```

That name is 147 bytes. ACPX 0.22.0 (on `master` since #20770) writes
the temporary file in a subdirectory, so the heartbeat name now fits.
But other names are still too long:

| Session file name | Bytes |
|---|---|
| Heartbeat key, `<key>.stream.1024.ndjson` | 141 |
| UUID task key, `<key>.json` | 150 |
| UUID task key, `<key>.stream.1024.ndjson` | 164 |
| Summary-slot task key, `<key>.json` | 235 |
| Summary-slot task key, `<key>.stream.1024.ndjson` | 249 |

## What Changed

- `buildSessionKey` measures the URI-encoded key. If the longest session
file name (`<key>.stream.1024.ndjson`) would be longer than 143 bytes,
it returns `paperclip:sha256:<32 hex>`. The digest is the SHA-256 of the
full key, so a digested key has the same scope as the full key.
- A key that fits is not changed. Thus saved heartbeat and `default`
sessions still resume after an upgrade.
- When a resumed run's session key differs from the saved key, the run
result now reports `sessionReset` with the named code
`acpx_session_identity_changed`. Before, it reported the reset only when
`configFingerprint` changed. `isCompatibleSession` already refuses to
resume when the keys differ, so the notice now covers every key change.
This includes the one-time change from a long key to a digest.
- Added `SESSION_KEY_MAX_ENCODED_LENGTH` and tests in
`execute-identity.test.ts`. The tests check that a heartbeat key does
not change, that issue and summary-slot keys become digests that fit in
143 bytes, and that a digest changes when the company, agent, task or
fingerprint changes.
- Added an old-saved/new-resumed test in `execute.test.ts`. It saves
session params with a long key, as the previous release wrote them, and
resumes them with the new code. The run gets the digest key and reports
`acpx_session_identity_changed`. The next run resumes without a reset.

## Verification

- `pnpm --filter @paperclipai/adapter-utils exec vitest run
src/acpx-engine/`: 22 files and 477 tests pass.
- `pnpm --filter @paperclipai/adapter-utils typecheck` passes.
- Without the `buildSessionKey` change, the new test "digests a key
whose file names would exceed the eCryptfs NAME_MAX" fails.
- Without the `sessionReset` change, the new old-saved/new-resumed test
fails.

## Risks

- Previous-release story: saved session params with a key that fits
carry forward unchanged and resume. Saved params with a key that becomes
a digest are reset on purpose: `isCompatibleSession` compares the saved
`sessionKey` with the new key, so the next run starts a new session and
reports `acpx_session_identity_changed`. The saved files under the old
name are not deleted. On a file system with a small NAME_MAX, these keys
could not write their session files before this change, so nothing is
lost. On ext4, a session with a UUID or summary-slot task key resumed
before this change and starts again one time after it.
- A digested key does not show the company, agent or task in logs. The
session directory path and the run context still show the company and
the agent.
- Low risk in other areas. The key format of short keys does not change,
and the code does not parse session keys.

## Model Used

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

## Checklist

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 04:22:02 -08:00
323be7e2d3 fix(issues): only treat a pending interaction as a covered blocker path when its host can be woken (#21982)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Blocker attention (`listIssueBlockerAttentionMap` in
`server/src/services/issues.ts`) is the "does this blocked card need a
human" signal: for every blocking edge it decides `covered` (something
will resume it on its own) or `needs_attention`
> - One of its coverage sources is `explicitWaitingIssueIds`, built from
any issue with a *pending* `issue_thread_interactions` row — the
assumption being that accepting the interaction will wake the issue's
assignee and move things forward
> - That assumption is never checked. The only place that turns an
accepted interaction into an actual wakeup,
`queueResolvedInteractionContinuationWakeup`
(`server/src/routes/issues.ts`), silently returns early when the host
issue has no `assigneeAgentId`, is already `done`/`cancelled`, or has a
`continuationPolicy` that cannot queue a wakeup (`request_confirmation`
defaults to `"none"`) — so a pending interaction in any of those shapes
is still counted as a live waiting path even though accepting it wakes
nobody
> - This is not a corner case: an issue can be assignee-less by design
(a standing gate/anchor issue with no owner), and `request_confirmation`
interactions default to a continuation policy that never wakes anyone
unless the caller opts in. Every such blocker reads as `covered`
forever, so no human is ever prompted to look at it
> - This pull request makes the interaction-derived half of
`explicitWaitingIssueIds` mirror the same guard: a pending interaction
only counts as a covered waiting path when its host issue currently has
an assignee agent, is not `done`/`cancelled`, and carries a
`continuationPolicy` of `wake_assignee` or `wake_assignee_on_accept`
> - The benefit is that `blockerAttention` stops reporting a
permanently-unreachable pending interaction as a resolved path, so the
board's "needs a human" signal is accurate for this shape of card; every
other interaction-covered case (an assigned, open host issue with a
wake-capable policy) keeps its current `covered` result

## Linked Issues or Issue Description

No public GitHub issue exists for this; describing it here as a bug
report.

**What happened?**
`listIssueBlockerAttentionMap` classified a blocked issue's blocker as
`covered` solely because the blocker had a `pending` row in
`issue_thread_interactions`, even when the blocker issue had no
`assigneeAgentId`, was already `done`/`cancelled`, or the interaction's
own `continuationPolicy` could never queue a wakeup. Accepting that
interaction can never wake anyone in those shapes:
`queueResolvedInteractionContinuationWakeup` in
`server/src/routes/issues.ts` returns early exactly when the host has no
assignee or is closed, and separately a `request_confirmation`
interaction defaults to `continuationPolicy: "none"` (see
`createIssueThreadInteractionSchema`), which the resolver also never
wakes.

**Expected behavior**
A pending interaction should only be treated as a live waiting path when
accepting it could actually reach an agent — i.e. the host issue has an
assignee agent, is not closed, and the interaction's continuation policy
is wake-capable (`wake_assignee` or `wake_assignee_on_accept`).
Otherwise the blocker should classify as `needs_attention`, the same as
any other dead-end path, so a human is prompted to look at it.

**Steps to reproduce**
1. Create a `blocked` parent issue and a blocker issue with
`assigneeAgentId = null` and `status = "todo"`.
2. Create a `pending` `issue_thread_interactions` row (any kind,
`continuationPolicy: "wake_assignee"`) on the blocker issue.
3. Call `listIssueBlockerAttentionMap` (e.g. via `GET` the issues list
with `status=blocked`) for the parent.
4. Observe `blockerAttention.state === "covered"` even though nothing
will ever wake the blocker.
5. Separately: create an assigned, open blocker with a
`request_confirmation` interaction left at its default
`continuationPolicy: "none"` — same false `covered` result.

**Paperclip version**
`master` at the base commit of this PR (see below).

**Deployment mode**
Self-hosted / any deployment — this is a pure server-side classification
bug, not deployment-specific.

## What Changed

- `server/src/services/issues.ts`: inside
`listIssueBlockerAttentionMap`, only add an interaction's host issue id
to `explicitWaitingIssueIds` when that host currently has a non-null
`assigneeAgentId`, a status other than `done`/`cancelled`, and a
`continuationPolicy` of `wake_assignee` or `wake_assignee_on_accept` —
mirroring the guard in `queueResolvedInteractionContinuationWakeup`
(`server/src/routes/issues.ts`) plus the `request_confirmation`
default-policy gap. Approval-, recovery-, and monitor-derived coverage
in the same function are unchanged; this touches only the
`issue_thread_interactions` branch.
- `server/src/__tests__/issue-blocker-attention.test.ts`: added a
`pendingInteraction` fixture helper and cases covering a pending
interaction on an assignee-less/open blocker, on a closed blocker, and
on an assigned/open blocker left at the default `"none"` continuation
policy — all now classify as `needs_attention`/`attention_required`
(previously `covered`/`active_dependency`) — plus a regression guard
that a wake-capable, assigned, open blocker still classifies as
`covered`/`active_dependency`.

## Verification

Ran on this branch (`server/`, local vitest against an embedded Postgres
instance):

```
npx vitest run src/__tests__/issue-blocker-attention.test.ts
# 33 passed (33)
```

`pnpm --filter @paperclipai/server typecheck` passes with no new errors
in either touched file.

This PR was rebased from an earlier attempt (commits originally authored
2026-09-14/15) onto current `master` after a long gap; both commits
applied with only line-offset conflicts (no logic divergence — verified
the touched types/fields,
`IssueBlockerAttentionNode.{assigneeAgentId,status}` and
`issueThreadInteractions.continuationPolicy`, and the
`ISSUE_THREAD_INTERACTION_CONTINUATION_POLICIES` enum, are all unchanged
on current `master`), then re-tested and re-typechecked against the
current tree.

## Risks

Low risk. The change narrows an existing `covered` classification to a
strictly smaller set of cases (a pending interaction now only counts as
a waiting path when its host is assignable, open, and wake-capable); it
cannot newly mark anything as `covered` that wasn't before. The affected
code path is read-only diagnostics (`blockerAttention` on the issues
list/board), so this cannot change any issue's actual status,
assignment, or interaction state — only how a blocker is reported.
Approval-, recovery-, and monitor-derived coverage are untouched.

**Overlapping open PRs — disclosed, not silently duplicated.**
- [#10398](https://github.com/paperclipai/paperclip/pull/10398) (same
author) also touches `listIssueBlockerAttentionMap`'s
`explicitWaitCandidateIds`/`explicitWaitingIssueIds` block, adding
monitor-based coverage and excluding `cancelled` nodes from the
candidate list. Its diff ends exactly where this PR's change begins
(right after the `interactionRows` query) and does not touch the
`interactionRows` loop body itself — adjacent but non-overlapping.
- [#20807](https://github.com/paperclipai/paperclip/pull/20807) also
touches `server/src/services/issues.ts` and
`server/src/__tests__/issue-blocker-attention.test.ts`, inside the same
function (`readIssueBlockerAttentionBatch`), adding agent-liveness-aware
wake coverage before and after the `interactionRows` loop. It does not
modify the `interactionRows` query or loop body this PR changes. Checked
both diffs line-range by line-range to confirm no overlap.

## Model Used

Claude Sonnet 5 (`claude-sonnet-5`), Anthropic. Standard (non-extended)
thinking mode. Tool use (file read/edit, local vitest/tsc execution,
GitHub CLI) via 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 — no
user-facing docs describe this internal classification helper
- [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: AURDVIN Dev Agent <dev@aurdvin.ch>
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-12-05 04:20:13 -08:00
5d85df5da2 fix(server): delete projects that still own cost or finance events (#21723)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Each agent run can record spend. Paperclip stores spend in cost
events and finance events, and it links each event to a company, an
agent, a project, and a task.
> - Operators delete a project when the work is cancelled or complete.
The delete service removes the project row and the project workspace
rows.
> - Two kinds of rows keep a reference to the project and block the
delete: tasks, and cost or finance events. The database rejects the
delete. The route returns `500 {"error":"Internal server error"}`.
> - The message hides the cause. A project delete also has no clear
behaviour for remaining tasks.
> - This pull request adds an explicit result. The service returns `409`
with the code `project_tasks_pending` when tasks remain. The service
clears the project link on cost and finance events, so spend history
survives and the delete completes.
> - The benefit is a predictable delete path, no lost spend history, and
no opaque `500`.

## Linked Issues or Issue Description

Related pull requests: Refs #10817, Refs #9145. Related issue: Refs
#11062 (the same foreign key problem on agent delete).

**What happened?**

`DELETE /api/projects/:id` returns `500 {"error":"Internal server
error"}` in two cases:

1. The project still has tasks. `issues.project_id` has no delete
action, so the database rejects the delete of the project row.
2. The project has cost events or finance events.
`cost_events.project_id` and `finance_events.project_id` have no delete
action, so the database rejects the same delete.

The server log shows the raw Drizzle error `update or delete on table
"projects" violates foreign key constraint`. The API client only sees
the generic `500`.

**Expected behavior**

The delete returns a result that names the blocking state:

- Tasks remain: `409` with a message that tells the operator to move or
delete the tasks.
- Cost or finance events remain: the delete completes. The spend rows
stay, and their project link becomes `null`.

**Steps to reproduce**

1. Create a project.
2. Create one task in the project.
3. Call `DELETE /api/projects/<id>`. Result: `500 Internal server
error`.
4. Delete the task, then call `DELETE /api/projects/<id>` again. Result:
`200`.
5. Create a second project. Record one cost event for it, then call
`DELETE /api/projects/<id>`. Result: `500 Internal server error`.

**Paperclip version or commit**

2026.1106.0 (self-hosted). The same code is on `master` at the time of
this pull request.

**Deployment mode**

Self-hosted, local, single operator.

**Installation method**

`npm install -g paperclipai`.

**Agent adapter(s) involved**

Not adapter-specific (core bug).

**Database mode**

External PostgreSQL 17 in Docker.

## What Changed

- `projectService.remove` clears `cost_events.project_id` and
`finance_events.project_id` before it deletes the project row.
- `projectService.remove` returns `409` with the code
`project_tasks_pending` when the project still has tasks.
- New test file `server/src/__tests__/project-delete-references.test.ts`
covers both cases.

## Verification

- `pnpm --filter @paperclipai/plugin-sdk build`
- `cd server && ./node_modules/.bin/vitest run
src/__tests__/project-delete-references.test.ts`
- The first test adds one cost event and one finance event to a project.
It deletes the project, then confirms that both rows still exist with a
`null` project link, and that the project row is gone.
- The second test adds a task to a project. It checks that the delete
returns `409`, and that the project row stays.
- Manual check on a self-hosted instance (2026.1106.0): project with 58
cost events returned `500` before the change. After the same query that
the service now runs, the delete returned `200`.

## Risks

- Behaviour change: a project delete with remaining tasks returns `409`
instead of `500`. The project row stays.
- Cost and finance rows keep their amounts and their company link. They
lose only the project attribution. No spend rows are deleted.
- No migration. No schema change. No data change outside the delete
path.

## Model Used

- Harness: Hermes Agent (Nous Research)
- Provider: opencode-go
- Model: `deepseek-v4.1-flash`
- Capabilities used: tool use, code execution, file edits, browser
- Context window: provider default. The task used a small part 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
- [ ] 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: hungpt99-dev <hungpt99-dev@users.noreply.github.com>
Co-authored-by: commitperclip[bot] <284812584+commitperclip[bot]@users.noreply.github.com>
2026-12-05 04:18:25 -08:00
2bd225ac0f fix(workspaces): keep a run going when a retired recovered copy cannot be removed (#21509)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - With remote (sandbox) execution, preparation can attach saved work
of an interrupted run under `.paperclip-recovered/<operation>`. After a
run that was shown that copy succeeds, the next preparation retires the
copy and removes it from the sandbox (#19979).
> - The removal is only a save-size cleanup. A retired copy is never
shown to an agent again.
> - When the sandbox refuses the removal (the proof file changed, the
path is not a plain directory, or a file cannot be deleted), the whole
run preparation fails with `remote_workspace_operation_failed:
operation=recovery_attachment exit=1`. The sandbox script drops its own
reason, so the failure tells nobody why.
> - Each later preparation that restores the same save meets the same
copy and fails the same way. The task cannot start.
> - This pull request makes a refused removal of a retired copy
non-fatal and makes the sandbox report a closed reason.
> - The benefit is that the run continues with the copy left in place,
and the log names why the sandbox refused.

## Linked Issues or Issue Description

Refs #19979

**What happened?**
On hosted staging, four runs of four different tasks failed in setup
with `remote_workspace_operation_failed: operation=recovery_attachment
exit=1`. The stack goes through `retainRemoteRecoveryAttachments` and
`removeRemoteRecoveryAttachment`. The run stopped before any provider
work. The error has no reason, because the sandbox script writes only
`remote_workspace_recovery_attachment_invalid` and the server accepts no
cause for this operation.

**Expected behavior**
A retired recovered copy that the sandbox will not remove stays in
place. The run continues. The log names a closed reason for the refusal.
Timeouts and provider transport failures still stop the run.

**Steps to reproduce**
1. Record a retired recovered copy in the workspace metadata
(`remoteWorkspaceRecoveredFiles` with `retired: true`).
2. In the sandbox, put a different `provenance.json` in
`.paperclip-recovered/<operation>`, or replace that directory with a
symlink.
3. Start the next run in that workspace. Preparation calls
`retainRemoteRecoveryAttachments`.
4. Preparation fails with `remote_workspace_operation_failed:
operation=recovery_attachment exit=1`.

**Relevant logs or output**
`RemoteWorkspaceOperationError: remote_workspace_operation_failed:
operation=recovery_attachment exit=1` at `realizeForRun` ->
`prepareRemoteWorkspace` -> `retainRemoteRecoveryAttachments` ->
`removeRemoteRecoveryAttachment`.

## What Changed

- The recovered-copy sandbox script now writes
`remote_workspace_recovery_attachment_invalid: reason=<closed reason>[
code=<errno>]`. The reasons are `invalid_attachment`,
`unsafe_attachment`, `missing_workspace`, `attachment_proof_changed`, or
`filesystem`. It never writes a path or file text.
- `command()` accepts only that exact grammar as the cause for the
`recovery_attachment` operation. Any other output is still dropped.
- New `isRemoteRecoveryAttachmentRefusal()` identifies a refusal that
the sandbox reported with an exit status. Timeouts and provider
transport errors do not match.
- `retainRemoteRecoveryAttachments` catches only that refusal when it
removes a retired copy. It logs a warning with code
`remote_workspace_retired_copy_kept` and the closed cause. The files
stay in place. The retired record stays, so the copy is never shown
again, and the next preparation tries the removal again.
- New `remote-workspace-recovery-attachments.test.ts` runs the real
sandbox script.

## Verification

- `cd server && npx vitest run
src/services/remote-workspace-recovery-attachments.test.ts`
- Before the fix: 4 of 6 fail. The retain test fails with the production
message `remote_workspace_operation_failed:
operation=recovery_attachment exit=1`.
  - After the fix: 6 of 6 pass.
- Safety cases in the same file:
  - A retired copy with its exact proof is still removed.
- A changed proof or a symlinked directory leaves every file in place,
also outside the workspace.
  - A provider failure (the runner throws) still fails preparation.
- `npx vitest run src/services/remote-workspace-transport.test.ts`: all
recovery-attachment cases pass. On this machine, three unrelated Git and
restore-lock cases fail with and without this change, because of the
local environment.
- `npx vitest run src/services/workspace-recovery-preparation.test.ts`:
81 of 81 pass.
- `tsc --noEmit -p server`: no errors in the changed files.

## Risks

- Low risk. Only the cleanup of an already-retired copy becomes
tolerant. Live recovered copies, attachment import, and the
`hasRemoteRecoveryAttachment` check keep their current behavior.
- A copy that cannot be removed stays in the saved workspace. Saves are
bigger for that workspace, which is the behavior from before #19979. The
warning makes this visible.
- The sandbox now writes a short closed reason to stderr. The server
accepts only the exact grammar, so no paths or file contents reach the
record.

## Model Used

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

## Checklist

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

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: paperclipbugbot <356415228+paperclipbugbot@users.noreply.github.com>
Co-authored-by: paperclipbugbot <bots+paperclipbugbot@paperclip.ing>
2026-12-05 04:16:35 -08:00
DottaandPaperclip b4cef7c8c8 fix(runner): load assigned skills by their granted runtime name (#21445)
## Thinking Path

> - Paperclip manages AI agents and their assigned skills.
> - Runner copies each assigned skill into a private provider home.
> - Paperclip gives company skills a unique runtime name.
> - OpenCode reads the name from the skill document.
> - The copied document kept the source name, so the assigned name
failed to load.
> - This change aligns the copied name with the granted name.
> - Agents can then find the skill under the name in their assignment.

## Linked Issues or Issue Description

**What happened?**

OpenCode rejected an assigned review skill name with a generated suffix.
It listed the source name instead. The agent made another lookup before
the review continued. See the [Braintrust
pattern](https://www.braintrust.dev/app/Paperclip/p/Paperclip%20Staging/patterns/27ff1ec9-4579-4ea1-ab6b-caae8d2a833d).

**Deployment mode**

Local Linux Runner with OpenCode 1.18.34. Staging recovery is not
tested.

**Expected behavior**

The provider discovers each assigned skill under its granted runtime
name.

**Steps to reproduce**

1. Assign a company skill whose source document has `name: review`.
2. Give it the runtime name `review--abc123`.
3. Copy it into the provider home through
`materializeNativeRuntimeSkills`.
4. Run OpenCode skill discovery in that home. Before this fix, it lists
`review`.

**Paperclip version or commit**

The baseline snapshot was inspected at
`43bdd773e901391e298415c5d039b2fc6a975bf7`. The current fix includes
master `89e65754189a3d73832562cbd28b90edf6ff52b8`.

Related-work search found no other repair for this name mismatch. PR
#14427 changes gateway hints and does not repair this skill projection.

## What Changed

- Align the top-level `name:` value in the disposable provider snapshot
before its existing read-only seal.
- Keep the admitted source, asset digest, runtime naming, collision
checks, and access controls unchanged.
- Support CRLF line endings, root mapping indentation, and complete
literal or folded name values.
- Cover unchanged source, bundled skill bytes, and documents without
frontmatter.

## Hypothesis and thesis for a fix

**Hypothesis:** Paperclip advertises the granted name, but OpenCode
indexes the original frontmatter name. The raw trace and actual local
OpenCode discovery confirm the mismatch.

**Thesis for a fix:** The shared native skill materializer owns the
provider copy. Align its name before sealing the copy. OpenCode, Codex,
and ACPX use this boundary. Legacy direct adapters use other paths and
are outside this change.

Saved source assets carry forward without migration. New provider copies
receive the aligned name. No saved session schema or authority contract
changes.

## Verification

- Added CRLF, literal, and folded regression cases. All three failed on
the earlier implementation; the LF case passed.
- `pnpm --filter @paperclipai/paperclip-runner exec vitest run
src/drivers/runtime-context-skill-name.test.ts
src/drivers/runtime-context-materializer.test.ts`: 24 tests pass.
- `pnpm --filter @paperclipai/paperclip-runner exec tsc -p tsconfig.json
--noEmit`: passes.
- Actual installed OpenCode `debug skill --pure`, with an isolated HOME
and XDG paths: without alignment it lists `review` and the granted-name
assertion fails. With this fix it lists `review--abc123`. The source
bytes stay unchanged.
- `git diff --check`: passes.
- ACPX and Copilot runtime-host suites: 84 tests pass. Total focused
checks: 108 tests pass.
- `pnpm verify` returned exit 2: the new test is outside the resolved
dependency graphs. Required CI supplies broad coverage.
- At `72b55119`, Greptile reached 5/5 with no unresolved threads.
Typecheck, build, Runner suites and E2E passed. General server shard
9/12 exposed an outdated remote-staging assertion; two other shards were
interrupted by runner shutdown.
- Updated remote-staging assertions for the granted nested name and
unchanged source. Reproduced the old assertion failure locally; all 35
remote-staging tests pass with standard umask 022. The default
restrictive mask caused a separate exact-mode assertion failure on the
initial local run.
- Current head `059e7b26`: aggregate CI verify, typecheck, build, all
server/Runner suites, E2E, Canary Dry Run, and Runner support pass.
Greptile is 5/5 with all threads resolved; Snyk succeeds. No pending or
failed checks. Superagent is neutral after a scan-workflow error, so no
security scan pass is claimed.

## Risks

The change affects native providers that share this materializer.
Existing symlink, overlap, unsafe-name, and read-only controls still
apply. The tests check those existing paths.

The local proof runs real provider discovery and checks the staged file.
It does not run a model or a staging agent task. Staging recovery
remains unverified. No merge or deployment is included.

## Model Used

OpenAI Codex, GPT-6, with tool use and code execution. Earlier work used
Codex; its exact model ID is not retained in the task evidence.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes:` / `Closes:`
/ `Refs:` OR (b) described the issue in-PR following the relevant issue
template
- [x] I have not referenced internal/instance-local Paperclip issues or
links
- [ ] My branch name describes the change and contains no internal
ticket id (the existing branch is retained for continuity)
- [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 (this
report describes the internal 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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-12-05 04:14:46 -08:00
OscarandClaude Opus 5.5 c8f363ef47 fix: treat an empty .git directory as no repository in the workspace source proof (#21409)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Before each heartbeat run, Paperclip proves the Git source of the
task workspace (`readWorkspaceGitSourceRoots`)
> - A workspace can contain an empty `.git` directory that is not a
repository. The Codex sandbox creates it as a mount point to protect
`.git` in a non-repository workspace (openai/codex#33813,
openai/codex#32872). When the run stops early (task reassignment,
cancel, quota failure), the empty directory stays
> - The proof treats the empty `.git` as a broken repository and throws
`workspace_git_source_unproven`. Every later run on that task fails at
setup, and the task cannot recover without manual cleanup
> - The proof already treats a `.git` that holds only `info/exclude` as
"no repository". An empty `.git` holds even less Git state
> - This pull request treats an empty `.git` directory as "no
repository" in the same way
> - The benefit is that interrupted runs no longer block all later runs
on the same task

## Linked Issues or Issue Description

Refs #20805

This change answers question B in the triage comment on #20805 for the
empty-placeholder case. We saw the failure on a self-hosted instance
many times on one day. Each time, the trigger was a task reassignment
while a `codex_local` run was active on that task. Inside one minute of
the reassignment, an empty `.git` directory appeared in the task's
isolated workspace. All later runs on the task failed at setup with
`workspace_git_source_unproven`. After `rmdir` of only the empty `.git`,
the next run passed setup. The concurrent-write case and the capacity
limits in #20805 are separate and this PR does not change them.

Related Codex issues (the source of the empty directory):
openai/codex#33813, openai/codex#32872, openai/codex#33450.

## What Changed

- `readWorkspaceGitSourceRoots` returns `null` (no repository) when the
`.git` marker is a real, empty directory. It still rejects symlinks and
every non-empty partial Git state.
- The existing ignore-only test now also covers an empty `.git`, both
directly and through ancestor lookup.

## Verification

- `pnpm vitest run
server/src/services/workspace-git-source-roots.test.ts`
- Manual: on an instance that showed the failure, removing the empty
`.git` made the next run pass setup. With this change, the proof returns
"no repository" for that state, so the removal is not necessary.

## Risks

- Low risk. An empty directory cannot hold objects, refs or a `gitdir`
pointer, so no Git source can hide behind it.
- `readNestedWorkspaceGitSourceRoots` keeps its current behavior: a
nested `.git` that is not a repository still fails that scan, the same
as the existing ignore-only case.

## Model Used

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

## Checklist

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

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

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 04:11:51 -08:00
045cf74081 fix(heartbeat): promote wakes deferred behind a queued run the claim gate withdraws (#20859)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The heartbeat wake queue parks a wake in `deferred_issue_execution`
while another run holds the task's execution lock. Only the holder's
release drain promotes the parked wake
> - A queued run can hold that lock before it starts. Wake admission
adopts a queued run on the task when the lock column is empty, and
deferred-wake promotion stamps the lock only for the assignee
> - When the claim-time execution gate withdraws that queued run as
stale (for example `issue_assignee_changed`), `claimQueuedRun` clears
the lock and returns. It does not run the release drain
> - The parked wake then waits until an unrelated event, such as a new
comment, arrives. The other pre-start cancellations in the same claim
(the mention gate and the daily cap) already release the task
> - This pull request releases the task after a gate withdrawal, with
the same call that the mention gate uses
> - The benefit is that a parked wake starts as soon as the run it
waited behind is withdrawn

## Linked Issues or Issue Description

No issue describes this exact path, so I describe it here.

**What happened?**

1. Agent A is the assignee of a task. A asks agent B a question on the
task. B's wake is deferred behind A's live run.
2. A's run ends. The release drain promotes B's wake into a run. B is
busy elsewhere, so that run stays `queued`. Promotion does not write the
task lock, because B is not the assignee.
3. B answers the question from another run. The answer wakes A.
Admission finds the lock column empty, adopts B's queued run as the
holder, and parks A's wake in `deferred_issue_execution`.
4. B gets capacity. The claim-time gate withdraws B's queued run
(`issue_assignee_changed`, `startedAt: null`), because the question is
no longer pending. The gate clears the lock.
5. Nothing promotes A's wake. It stays deferred until a new comment
arrives. We saw waits of more than 40 minutes.

**Expected behavior**

When the run that a wake waits behind ends in any state, including a
cancellation before start, the oldest eligible deferred wake is
promoted.

**Steps to reproduce**

The new test
`server/src/__tests__/heartbeat-deferred-wake-after-stale-queued-cancel.test.ts`
reproduces it with the real `heartbeatService` on embedded Postgres. It
covers a plain non-assignee queued run and the answered-question shape
above.

**Related**

- Refs #18838 and #15483. #18838 exempts a never-started gate
cancellation from reconciliation. Without #18838 the release drain
refused to run for the withdrawn run, and the periodic stranded-queue
sweep could not promote the wake either. This pull request adds the
missing release call after that fix.
- Refs #20256: the deferral of an addressee's wake behind a live run. It
is the same adoption path seen from the other agent's side. This pull
request does not change the deferral.
- Refs #16202: a periodic pass that force-releases stale locks held by a
former assignee's non-running run. It is a different mechanism and does
not cover the claim gate.
- Refs #14082, #14879, #1269, #10270: other paths that leave a deferred
wake without a drain.

## What Changed

- `server/src/services/heartbeat/queue.ts`: after `cancelStaleQueuedRun`
returns `cancelled`, `claimQueuedRun` calls
`releaseIssueExecutionAndPromote(run, { suppressImmediateRecovery: true,
deferredPostCommitEffects })`. This is the same call that the
mention-gate cancellation makes in the same function, under the same
agent start lock. A refusal with `execution_reconciliation_required`
does not release, because its saved wakes belong to the existing
execution hold, and the wake-queue drain does not check execution holds.
- Add the regression test
`server/src/__tests__/heartbeat-deferred-wake-after-stale-queued-cancel.test.ts`.
- Add one paragraph to `doc/execution-semantics.md`.

## Verification

From `server/`, with Node 24:

- `npx vitest run
src/__tests__/heartbeat-deferred-wake-after-stale-queued-cancel.test.ts`:
both cases pass. Without the change in `queue.ts`, both cases fail: the
wake stays `deferred_issue_execution` and no run is created for it. With
the change, the promoted run runs to `succeeded`.
- Related suites, one file or module at a time:
`heartbeat-stale-queue-invalidation`,
`heartbeat-lock-release-on-reassignment`,
`satisfied-connection-intents`, `legacy-continuation-authority`,
`heartbeat-undispatched-execution-wait`,
`heartbeat-task-drain-admission-release`,
`heartbeat-dependency-scheduling`, `heartbeat-retry-scheduling`,
`durable-chat-wakeup`, `heartbeat-responsible-user-invariant`,
`agent-conversation-delivery`, `src/modules/run-dispatch` and
`src/modules/wake-queue`: 882 tests pass. A single run of about 76
related files did not finish within 55 minutes on this host, so I ran
them one at a time.
- `npx tsc --noEmit`: 318 errors on this host, the same count as
unmodified `master`, none in the changed files. The host has no `cargo`,
so the runner vendor files do not build.

I did not run `pnpm build`, the full `pnpm test:run` or the browser
suites, because the build needs `cargo`.

## Risks

- Low risk. A withdrawn queued holder now drains the deferred queue, as
a finishing holder already does. A promoted wake still passes every
admission and claim gate (ownership, pause holds, budget, approvals,
dependencies). If it is also stale, the same gate withdraws it.
- The release runs inside the claim, under the agent start lock, like
the mention-gate path. Post-commit effects are collected in
`deferredPostCommitEffects` when the caller supplies it.

## Model Used

- Claude Opus 5.5 (Anthropic), model ID `claude-opus-5-5`, used as a
coding agent in Claude Code with tool use (shell, file edit) and
extended reasoning. A human owner approved sending this change upstream.

## Checklist

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

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

---------

Co-authored-by: LiterallyBlah <22526586+LiterallyBlah@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 04:10:07 -08:00
NevyshaandClaude Opus 5.5 1cd359408d fix(chat): keep a turn's progress messages apart in the conversation view (#20818)
# Branch

Nevysha:fix/task-chat-progress-message-breaks → paperclipai:master

# Body

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The task chat shows an agent's live run, including the short
progress messages that the agent writes between tool calls
> - The paperclip runner streams a whole provider turn under one
assistant item, so all progress messages in a turn have the same
`itemId`
> - For a run that started before the page opened, the task page loads
the conversation event view (#17593). This view returns only the text
deltas, without the tool calls that normally separate the messages
> - The transcript adapter joins consecutive deltas with the same
`itemId`, so the whole turn becomes one block with no space between
sentences
> - This pull request starts a new paragraph when a delta comes from a
different provider message than the delta just before it
> - The benefit is that the live task chat stays readable for runs that
started before the page opened

## Linked Issues or Issue Description

Fixes #20812
Refs #17593

## What Changed

- `nativeRunEventsToTranscript()` reads the provider message id of each
assistant delta (`providerItemId`, at the top level or in `update`).
- When a delta continues the same item directly after the previous
assistant delta, but comes from a different provider message, the delta
text starts with a paragraph break (`\n\n`).
- The change does not apply when another entry (for example a tool call)
is between the two deltas. The adapter already shows those messages as
separate rows.
- The change does not apply when the delta has no provider message id.
Those deltas join as before.
- Added three tests to `native-run-events.test.ts`: the
conversation-only case, the case with a tool call between the messages,
and deltas without a provider message id.

## Verification

- `cd ui && npx vitest run
src/components/transcript/native-run-events.test.ts`: 86 tests pass. The
new conversation-only test fails without the fix.
- `cd ui && npx vitest run src/components/transcript/
src/components/task-chat/ src/lib/issue-chat-messages.test.ts
src/components/TaskChatThread`: 76 files, 1618 tests pass, 1 skipped.
- `cd ui && pnpm typecheck` passes.
- I ran the projection on the events of a real run (paperclip_runner
with Claude Code, about 35 progress messages in one turn):
- Conversation view: before the fix, 1 message with no breaks. After the
fix, 1 message with the progress messages as separate paragraphs.
- Full event list: 36 message rows before and after the fix. No row
starts with a line break.
- I did not run the full `pnpm -r typecheck`, `pnpm test:run` and `pnpm
build`. The CI gates run them.

## Risks

- Low risk. The change applies only to assistant deltas that continue
the same item and come from a different provider message.
- The first delta of each new message now starts with `\n\n`. Markdown
shows this as a new paragraph. `flattenSelfTalk()` changes it to one
space.
- Runners and adapters that do not send a provider message id keep the
current behavior.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`, Anthropic), in Claude Code with
tool use (shell commands, file reads and edits). It found the cause,
wrote the change and the tests, and ran the checks. A human reviewed the
change.

## Checklist

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

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 04:08:17 -08:00
james8814andPaperclip 65614fa87e fix(issues): tell a reviewer to decide again when a reply to it is queued (#20745)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Execution policies route an issue through review and approval
stages, and agents can be stage participants
> - The issue update route refuses an agent handoff to review while a
human reply to that agent is still queued
(`interaction_response_queued`)
> - The refusal protects the reply: if the issue gets a new assignee
first, the dispatcher cancels the queued continuation with
`issue_assignee_changed` and the reply is never delivered
> - A reviewer agent that approves an intermediate stage also hits this
refusal, because the policy moves the issue to the next participant and
keeps it `in_review`
> - The error tells the reviewer to "keep the current assignee". The
reviewer did not choose the assignee, and the error does not say that
the decision was dropped
> - This pull request keeps the refusal and gives stage decisions a
message the reviewer can act on: the decision was not saved, read the
reply in the next run, then decide again

## Linked Issues or Issue Description

No issue exists for this bug. I searched issues and PRs for
`interaction_response_queued`, "queued response stage approval", "review
stage approve 409 queued" and "queued interaction response handoff".

- Refs #19376. That closed PR changed which queued receipts count as
delivered. It did not change this check.
- Refs #20264. That open PR reworks stage decisions into explicit
operations. Its description does not mention this check. If it lands
first, this change needs a rebase onto its decision path.

**What happened?**
A two-stage policy has a review stage (agent A) and an approval stage
(agent B). Agent A is the active reviewer and the assignee. A human
reply to agent A is queued, for example an answer to a question that
agent A asked. Agent A sends `PATCH /api/issues/:id` with `status:
"done"` and an approval comment. The policy turns this into an approval
of the review stage, which would set `status: "in_review"` and assign
agent B. The route returns 409 `interaction_response_queued`: "Keep the
current assignee so the queued response can continue after this run".
The update, the decision row and the comment are not saved, and the
message does not say so.

**Expected behavior**
The reply still reaches agent A, so the refusal stays. The error tells
agent A that the decision was not saved and that it should read the
reply in its next run and submit the decision again.

I first tried to let the decision through. That loses the reply: the
queued continuation for agent A is a resolved-interaction continuation,
and `decideQueuedRunStaleness` cancels it with `issue_assignee_changed`
once agent B is the assignee
(`server/src/modules/run-dispatch/domain/policy.ts:538-556`). The human
input would also not inform the decision. So this change keeps the
refusal.

**Steps to reproduce**
1. Configure an execution policy with a review stage (agent A) and an
approval stage (agent B).
2. Move the issue into the review stage with agent A as the current
participant and assignee.
3. Queue a resolved interaction response for agent A on the issue.
4. As agent A, send `PATCH /api/issues/:id` with `{ "status": "done",
"comment": "Approved." }`.
5. The response is 409 with the generic "keep the current assignee"
message.

**Paperclip version or commit**
`master` at 8b3348c6b. The check is at
`server/src/routes/issues.ts:15483-15489`.

## What Changed

- `server/src/routes/issues.ts`: when the execution policy returns a
stage decision, the `interaction_response_queued` error now says: "The
user already responded to you. This stage decision was not saved. Read
the queued response in your next run on this issue, then submit the
decision again." The condition and the error code do not change. Other
handoffs keep the old message.
- `server/src/__tests__/issue-execution-policy-routes.test.ts`:
- The `hasQueuedInteractionResponse` mock is now a shared handle, so a
test can make it return `true`. The mocked transaction also supports
`insert`, so a test can see the decision row.
- New test: a reviewer approves the review stage with no reply queued.
The issue moves to agent B and an `approved` decision row is written.
- New test: the same approval with a reply to the reviewer queued. The
response is 409 with the new message. There is no update, no comment and
no decision row, so the reviewer stays the assignee.
- New test: an agent submits its own work for review with a reply
queued. The response is 409 with the old message and no update.
- `server/src/modules/run-dispatch/domain/policy.test.ts`: new test for
the delivery rule this refusal depends on. A queued response to a
reviewer runs while the reviewer is still the assignee, and is cancelled
with `issue_assignee_changed` after a handoff.

## Verification

- `cd server && npx vitest run
src/__tests__/issue-execution-policy-routes.test.ts
src/modules/run-dispatch/domain/policy.test.ts`
- Route file from `master`: 1 failed, 111 passed. The queued-reply
approval test fails on the message.
- Route file that lets stage decisions skip the check: 1 failed, 111
passed. The same test fails with 200 instead of 409.
  - With this change: 112 passed.
- With this change, also
`src/__tests__/issue-agent-mutation-ownership-routes.test.ts` and
`src/__tests__/issue-comment-reopen-routes.test.ts`: 4 files, 446 passed
in total.
- The new policy test passes on `master` too. It documents the existing
dispatcher rule. It does not test a change.
- Not run locally: `issue-queued-comments-routes.test.ts`. It needs
embedded Postgres, which my environment cannot start. No end-to-end test
with a real queue was run.

## Risks

- Behavior: no change to which requests are refused. Only the message
text for stage decisions changes. Clients that match on the error code
are not affected.
- Not covered by this PR: a change request (`in_progress`) and a final
approval (`done`) do not end in `in_review`, so they pass this check
today. If a change request moves the issue back to the executor while a
reply to the reviewer is queued, the dispatcher cancels that reply in
the same way. I found this by reading `policy.ts` and did not reproduce
it on a running instance. It needs a separate decision.
- #20264 changes the same route area. Whichever PR lands second needs a
rebase.

## Model Used

Claude Opus 5.5 (claude-opus-5-5), agentic coding with 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
- [ ] 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: Paperclip <noreply@paperclip.ing>
2026-12-05 04:03:07 -08:00
7bd424d50f fix(issues): preserve PATCH result when unblock wake fails (#20425)
## Thinking Path

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

## Linked Issues or Issue Description

Refs #3824

Related pull request: #19209

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

## What Changed

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

## Verification

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

## Risks

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

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

## Model Used

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

## Checklist

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

---------

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

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

## Linked Issues or Issue Description

No issue exists.

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

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

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

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

## What Changed

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

## Verification

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

## Risks

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

## Model Used

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

## Checklist

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

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

---------

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

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

## Linked Issues or Issue Description

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

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

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

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

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

## What Changed

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

## Verification

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

## Risks

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

## Model Used

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

## Checklist

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

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

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

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

## Linked Issues or Issue Description

No issue exists.

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

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

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

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

## What Changed

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

## Verification

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

## Risks

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

## Model Used

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

## Checklist

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

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 03:52:57 -08:00
KiaanKothari a2abe16e50 docs(skills): fix typos in fix-slow-queries skill (#20093)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Agents use skills in `.agents/skills/` as working instructions
> - The `fix-slow-queries` skill has three spelling and grammar errors
on lines 175 to 177
> - Errors in instructions make the text harder to read for people and
agents
> - This pull request corrects the three errors
> - The benefit is clearer instructions with no change to their meaning

## Linked Issues or Issue Description

**Issue type**
Typo or grammar error.

**Where is the issue?**
`.agents/skills/fix-slow-queries/SKILL.md`, lines 175 to 177.

**What's wrong?**
Line 175 has "non starter". Line 176 has "dont'". Line 177 has "a sense
on the time".

**Suggested fix**
Change them to "non-starter", "don't" and "a sense of the time".

## What Changed

- Corrected three spelling and grammar errors in
`.agents/skills/fix-slow-queries/SKILL.md`.

## Verification

- Read lines 175 to 177. Each sentence has the same meaning as before.
- This change touches one Markdown file only. No code changes.

## Risks

- Low risk. Text-only change to one Markdown file.

## Model Used

- Claude (Anthropic), model ID `claude-opus-5-5`, with tool use. The
model found the errors with a spell-check scan and suggested the fixes.
A human made and reviewed the edit.

## 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-05 03:51:10 -08:00
Alex Castillo González 5fb030f59f fix(heartbeat): keep the newest comments when a wake window is cut (#19969)
Fixes #19198

## Thinking Path

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

## Linked Issues or Issue Description

Fixes: #19198

No open pull request mentions this issue.

## What Changed

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

## Verification

Run this command in `server`:

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

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

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

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

## Risks

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

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

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

## Model Used

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

## Checklist

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

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

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

## Linked Issues or Issue Description

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

**What happened?**

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

**Expected behavior**

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

**Steps to reproduce**

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

**Paperclip version or commit**

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

**Deployment mode**

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

## What Changed

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

## Verification

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

## Risks

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

## Model Used

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

## Checklist

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

---------

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

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

## Linked Issues or Issue Description

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

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

**What happened?**

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

**Expected behavior**

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

**Steps to reproduce**

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

The new embedded-PostgreSQL test does these steps.

**Paperclip version or commit**

master 4d49a3128.

## What Changed

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

## Verification

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

## Risks

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

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

## Model Used

- Claude Opus 5.5 (claude-opus-5-5), 1M-token context window, adaptive
thinking
- Provider: Anthropic. Harness: Claude Code CLI, with tool use (shell,
file edits), code execution and embedded PostgreSQL tests

## Checklist

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

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

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

## Thinking Path

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

## Linked Issues or Issue Description

Refs #11853

**What happened?**

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

**What did you expect to happen?**

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

## What Changed

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

## Verification

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

## Risks

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

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

## Model Used

- Provider and model: Anthropic Claude Opus 5.5 (model ID
`claude-opus-5-5`)
- Context window: 1M tokens (128K maximum output)
- Capabilities: adaptive thinking, tool use, and code execution, used
through Claude Code

## Checklist

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

> - Paperclip is the open source app people use to manage AI agents for
work
> - The `hermes_local` adapter runs the Hermes CLI and reads its stdout
> - The adapter uses the stdout before `session_id:` as the run result.
Paperclip posts this result as an auto-comment when the agent does not
post its own comment.
> - The Hermes gateway client prints the inline diff of each edit behind
a `│` gutter. It does this also in quiet mode (`-Q`) and with
`display.inline_diffs: false`.
> - `cleanResponse()` does not remove these lines. The run summary and
the auto-comment then contain only code diffs, cut at 2,000 characters.
> - The live issue chat uses `parseHermesStdoutLine()`. This parser
shows the same lines as assistant text, so the agent appears to "speak"
diffs.
> - This pull request removes the gutter lines from the result and
classifies them as stdout in both UI parsers (TypeScript and
`ui-parser.cjs`).
> - The benefit is that auto-comments and the issue chat show what the
agent wrote, not raw diffs.

## Linked Issues or Issue Description

No issue exists. I searched open and closed issues and PRs for "hermes
diff", "hermes cleanResponse" and Hermes adapter PRs. I found no
duplicate.

**What happened?**
An agent on `hermes_local` ran through the Hermes gateway client. When a
run ended without an agent comment (timeout or interrupted run),
Paperclip posted an auto-comment (`authorizationReason:
internal_agent_write`). The comment contained only diff lines such as `│
apps/web/... │`, `│ @@ -1,2 +1,3 @@`, `│ +...`. The live issue chat
showed the same lines as assistant messages.

**Expected behavior**
The auto-comment contains the agent's final text only. The issue chat
shows diff lines as tool output, not as assistant speech.

**Steps to reproduce**
1. Configure an agent with `hermes_local` and a Hermes setup that uses
the gateway client.
2. Give the agent a task that edits files.
3. Let the run end without an agent comment (for example, a timeout).
4. Look at the auto-comment and at the live issue chat during the run.

**Agent adapter(s) involved**
Hermes

## What Changed

- `packages/adapters/hermes/src/server/execute.ts`: `cleanResponse()`
removes lines that start with `│` after ANSI codes are removed.
- `packages/adapters/hermes/src/ui/parse-stdout.ts`:
`parseHermesStdoutLine()` returns `stdout` for lines that start with
`│`. Before, they became `assistant`.
- `packages/adapters/hermes/ui-parser.cjs`: the same rule for the CJS
parser. Externally installed adapters load this file.
- New test `src/ui/ui-parser-cjs.test.ts`: tests the exported
`parseStdoutLine` from `ui-parser.cjs`.
- New test `src/server/execute.response.test.ts`: runs `execute()` with
Hermes stdout that has gutter diff lines. It checks `summary` and
`resultJson.result`.
- New tests in `src/ui/parse-stdout.test.ts` for plain and colored
gutter lines.

## Verification

- `pnpm --filter @paperclipai/hermes-paperclip-adapter test`: 12 files,
180 tests pass.
- `pnpm --filter @paperclipai/hermes-paperclip-adapter typecheck`: pass.
- The five new parser and execute tests fail without the source change
and pass with it.
- Manual: I applied the same change to the built adapter on a live
instance (2026.1023.0). After a restart, auto-comments from a Hermes
agent contained the final text only. The issue chat stopped showing diff
lines as assistant text.

## Risks

- Low risk. The change affects only lines whose first visible character
is `│` (U+2502).
- If an agent writes a final answer line that starts with `│`, the
adapter now removes that line from the result. This is unlikely in
normal prose. The `┊` (U+250A) tool lines are not affected.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use
(shell, file edits, test runs). The model found the cause, wrote the
change and the tests, and wrote this description. A human reviewed and
approved the work.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [ ] I have updated relevant documentation to reflect my changes (not
applicable: no documented behavior 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: Thomas Venturini <4708070+tjventurini@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 03:23:32 -08:00
Chaitanya Meesalaandcommitperclip[bot] 7612e79215 fix(heartbeat): tell a non-owner addressee to answer the card, not take the task (#18907)
## Thinking Path

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

## Linked Issues or Issue Description

Fixes #16563

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

## What Changed

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

## Verification

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

## Risks

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

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

## Model Used

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

## Checklist

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

---------

Co-authored-by: commitperclip[bot] <284812584+commitperclip[bot]@users.noreply.github.com>
2026-12-05 03:18:32 -08:00
viwe-monai 960ed4b3ae docs: document multiple Hermes profiles via /p/<profile> base URLs (#18732)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The subsystem is the Hermes gateway adapter onboarding doc
(`doc/HERMES_GATEWAY_ONBOARDING.md`)
> - The doc does not mention Hermes profiles at all
> - Users who run one Hermes profile per role (coder, reviewer,
researcher) cannot see that one Paperclip agent per profile is possible
> - This pull request adds a "Multiple Hermes Profiles" section to the
onboarding doc
> - It documents the `/p/<profile>` base-URL route, the shared-listener
auth rule, and the dashboard-port gotcha
> - The benefit is that users can wire one Paperclip agent per Hermes
profile from the doc alone

## Linked Issues or Issue Description

- Fixes: #18697 (docs: document routing to a specific Hermes profile via
the `/p/<profile>` base URL)

## What Changed

- Add a "Multiple Hermes Profiles" section to
`doc/HERMES_GATEWAY_ONBOARDING.md`.
- The section covers the four points from #18697: enable
`gateway.multiplex_profiles`, one agent per profile with `apiBaseUrl`
set to `<gateway>/p/<profile>`, the API key rule, and the port `9119`
path-rewrite gotcha.
- The section also documents the two routing outcomes: unknown prefix
returns `404`, no prefix runs as the default profile.

## Verification

- The `/p/<profile>` route contract is verified against the Hermes
gateway source (`gateway/platforms/api_server.py`: the module docstring
lists `GET /p/<profile>/v1/models`; `_resolve_request_profile` returns
the reject sentinel for unknown profiles; the profile-prefix middleware
answers `404 {"error": "Unknown or unconfigured profile"}`).
- The base-URL claim is verified against
`packages/adapters/hermes/src/gateway/server/execute.ts`: `apiUrl()`
appends `/v1/runs...` to the configured URL and keeps its path;
`normalizeBaseUrl()` rewrites the path to `/api` only when the port is
the Hermes dashboard port.
- One correction to #18697: the issue says each multiplexed profile has
its own `API_SERVER_KEY`. The source shows one listener with one key
(`self._api_key` is set once in the api_server platform init from
`API_SERVER_KEY`). The profile prefix scopes the request home; it does
not change the auth key. The doc text follows the source. Please correct
me if a per-profile key path exists that I missed.
- The issue asks for a maintainer smoke test (a full Paperclip run
against a `/p/` URL) before documenting. I did not run that smoke test.
The doc describes static source behavior only. If you prefer, switch the
link to `Refs: #18697` and run `doc/HERMES_GATEWAY_SMOKE.md` first.
- Docs-only change. No tests apply. No code paths change.

## Risks

Low risk. Docs only. The new section is additive and isolated.

## Model Used

- Hermes Agent (Nous Research) with mimo-v2.6-pro (Xiaomi), 2026-11-03
- Tool-assisted: `gh` CLI for API reads; local Hermes source
(`/usr/local/lib/hermes-agent`) for the verification above

## 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 (open PRs scanned; none touches profile routing docs)
- [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 (`docs/hermes-profiles`)
- [x] I have run tests locally and they pass (docs-only; no test suite
applies)
- [x] I have added or updated tests where applicable (no tests apply to
markdown docs)
2026-12-05 03:16:38 -08:00
Paul BéglinandPaperclip 8f6cf8b0d7 fix(auth): ignore comment-only Codex project settings (#18559)
## Thinking Path

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

## Linked Issues or Issue Description

**What happened?**

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

**Expected behavior**

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

**Steps to reproduce**

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

**Paperclip version or commit**

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

**Deployment mode**

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

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

## What Changed

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

## Verification

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

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

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

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

## Risks

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

## Model Used

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

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

## Checklist

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

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

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-12-05 03:12:04 -08:00
Chen Yufeiyang ed262f2e9a fix(adapter-utils): protect nested clone .git directories during workspace copy-back (#18534)
## Thinking Path

> - Paperclip runs agents in local, SSH and sandbox environments.
> - A remote run uploads the agent workspace to the execution host. At
the end the adapter copies the workspace back.
> - The upload excludes Git metadata with the `.git` archive exclude
list.
> - The copy-back uses the same list to decide what it may delete. The
list only matched the top-level `.git` directory.
> - The upload left out nested clones' `.git` data. The copy-back
treated that data as deleted in the sandbox.
> - The copy-back then removed `repo/.git` on the host. Unpushed commits
and branches were lost.
> - This pull request adds the nested patterns that the heavy-directory
excludes already use.
> - The benefit is that a copy-back never deletes Git data that the
upload left out.

## Linked Issues or Issue Description

Fixes: #18299

Refs: #15959 (the same exclude list inconsistency for SSH workspaces)

## What Changed

- Add `*/.git` and `*/.git/*` to `GIT_ARCHIVE_EXCLUDES`. The restore
baseline exclude now matches a nested `.git` at any depth, like the tar
upload already does.
- Add a regression test. The test captures a baseline that contains
`repo/.git` and asserts that the nested `.git` is excluded.

## Verification

- `pnpm vitest run
packages/adapter-utils/src/workspace-restore-merge.test.ts` -> the new
test passes; 47 passed.
- Before the change, the same test fails with `expected true to be
false` because the baseline contained `repo/.git/config`.
- `pnpm --filter @paperclipai/adapter-utils exec tsc --noEmit` -> pass.
- `pnpm vitest run
packages/adapter-utils/src/remote-managed-runtime.test.ts` -> 7 passed.
- `git-workspace-sync.test.ts` and `sandbox-managed-runtime.test.ts`
show the same environment failures with and without the change (8 and
40; local Node 23.11 `node:sqlite` `Incomplete workspace manifest`).
This change adds no failure.
- A live sandbox copy-back is not available locally. After merge, run
one sandbox run with a nested clone in the workspace and confirm that
`repo/.git` stays on the host.

## Risks

- The copy-back no longer removes nested `.git` data. This is intended:
the upload does not send that data to the sandbox.
- The tar upload now names the nested patterns explicitly. The tar
behavior does not change because the old `.git` pattern already matched
at any depth.
- `workspaceFileMode: "all"` keeps the old behavior; it does not use
these excludes.

## Model Used

- DeepSeek V4.1 Flash (model id: `deepseek-v4.1-flash`). Provider:
DeepSeek.
- Capabilities: extended reasoning, tool use, shell command execution,
file edits and test execution.
- No other AI model was used for 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
- [x] My branch name describes the change
(`fix/sandbox-nested-git-exclude`) and contains no internal 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 — no
docs page describes this internal exclude list
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green — CI starts after this PR
- [ ] Greptile is 5/5 with no open P2s — review starts after this PR
- [x] I will address all Greptile and reviewer comments before
requesting merge
2026-12-05 03:08:54 -08:00
emme1t 32e80f80fe fix(codex-local): accept newer prerelease CLI versions (#18508)
## Thinking Path

> - Paperclip manages AI agents and checks their execution environment.
> - The Codex adapter checks the installed CLI against the selected
model's minimum version.
> - The parser rejects prerelease builds shipped with Codex Desktop,
including builds newer than that minimum.
> - This stops the hello probe and can leave an approved agent in
verification.
> - This change accepts valid prerelease versions and compares their
release numbers with the stable minimum.
> - A prerelease of the minimum release stays below the minimum.

## Linked Issues or Issue Description

Fixes: #18498

Refs #15399, which introduced the version check, and #15053, which
reports the original model compatibility problem. Related open #15534
adds model catalog discovery; this change addresses version parsing.

## What Changed

- Parse one stable or prerelease `codex-cli` version line. Keep
malformed and ambiguous output invalid.
- Accept `0.164.0-alpha.11.1` against `0.157.0`. Keep `0.157.0-alpha.1`
below `0.157.0`.
- Cover the parser, stable minimum comparison, CLI hello-probe
admission, and ACP environment check.
- Document this version rule in the Codex adapter guide. The change
stays in the adapter that owns this rule.

## Verification

Tested source commit `d8e2e2e` on Windows x64, Node 24.16.0 and pnpm
9.15.4, with isolated test homes.

- Seven affected assertions fail with the original production code and
pass with this change. The three affected test files report 58 passed
and one existing Windows path-separator failure. The same path failure
occurs on the original source.
- The real `checkCodexCliVersionForModel` launches the installed
`codex.exe --version`, which reports `0.165.0-alpha.1.2`. Checks for
`gpt-6-luna`, `gpt-6-sol`, and `gpt-6.1-sol` fail on the original source
and pass after this change. This probe makes no model request.
- `pnpm --filter @paperclipai/adapter-codex-local typecheck` passes. The
package build passes with Git Bash as the script shell.
- The complete Codex adapter suite reports 530 passed, 65 failed, and
one skipped. All 65 failure names also fail on the original production
source. That comparison reports 522 passed and 73 failed: seven failures
are this regression, and one independent auth-lock timing test changes
result between runs. Existing failures include Windows symlink
permissions, POSIX file modes/signals, and path expectations.
- Full workspace checks remain incomplete on this host. `pnpm -r
typecheck` stops at the unchanged Grok launcher digest check in the CRLF
checkout. `pnpm test:run` stops at `spawnSync pnpm ENOENT`. `pnpm build`
stops at the shared package's POSIX shell command under Windows cmd.
Initial install/preflight symlink errors were resolved for local
workspace links with directory junctions; those earlier failures remain
recorded.
- `git diff --check` passes. Greptile reports 5/5 on this commit, and
Codex code review completed with no findings. On November 20, GitHub
reported 55 passing checks and three skipped checks for this commit.

To run the focused tests:

```sh
pnpm exec vitest run --config packages/adapters/codex-local/vitest.config.ts packages/adapters/codex-local/src/index.test.ts packages/adapters/codex-local/src/server/test.remote.test.ts packages/adapters/codex-local/src/server/acp.cli-version.test.ts
```

The hello responses in the adapter tests use transport fixtures. Live
model execution, lifecycle completion, and native Runner qualification
were not exercised.

## Risks

The check now admits prereleases whose release numbers exceed a verified
stable floor. The hello probe still checks the selected model after
version admission. Equal-release prereleases, invalid versions, and
ambiguous output stay incompatible. The verified model floors are
unchanged.

## Model Used

OpenAI GPT-6 through Codex, with reasoning, tool use, and local code
execution. This session does not expose its exact deployment model ID or
context-window limit.

## Checklist

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

With assistance from Astra.
2026-12-05 03:05:52 -08:00
Josh CoxandReview 0110436ab6 fix(server): keep an existing grant scope when re-ensuring without one (#18116)
## Thinking Path

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

## Linked Issues or Issue Description

Fixes #17992

## What Changed

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

## Verification

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

## Risks

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

## Model Used

Meta Muse Spark 1.3, with tool use and code execution.

## Checklist

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

Signed-off-by: Josh Cox <joshuacox@users.noreply.github.com>
Co-authored-by: Review <review@local>
canary/v2026.1205.0-canary.899500
2026-12-05 02:49:25 -08:00
Josh CoxandReview e31445b43a fix(claude-local): recognise hyphenated 5-hour limit wording as provider quota (#18110)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The claude_local adapter classifies Claude CLI failures as provider
quota, transient upstream, or other errors
> - Provider quota classification arms the quota monitor and schedules a
retry at the reset time
> - The quota regexes use `(?:\w+\s+)?limit` for the limit name
> - `\w` stops at a hyphen, so "You've hit your 5-hour limit" does not
match
> - The run then records as transient upstream, spends its bounded
retries, and parks the issue blocked with no retry at the reset
> - This pull request allows a hyphen in the limit name in both regexes
> - The benefit is that 5-hour limit messages classify as provider quota
and resume after the reset

## Linked Issues or Issue Description

Fixes #18057
Refs #16785 (the same regex family misses the "org's monthly spend
limit" wording; that wording needs multi-word names and stays a separate
issue)
Refs #15797 (other quota wordings this regex family misses)

## What Changed

- `packages/adapters/claude-local/src/server/parse.ts`:
`CLAUDE_PROVIDER_QUOTA_RE` and `CLAUDE_EXTRA_USAGE_RESET_RE` now use
`(?:[\w-]+\s+)?limit` for the limit name.
- `packages/adapters/claude-local/src/server/parse.test.ts`: new test
classifies the exact reported message as provider quota, not transient,
and extracts the 16:30Z retry time.

## Verification

- `packages/adapters/claude-local`: `vitest run
src/server/parse.test.ts` passes 49/49.
- Negative control: with only the `parse.ts` change stashed, the new
test fails; with the change restored, it passes.
- Full server typecheck and CI are the arbiters for anything beyond this
package. They were not run locally in this sandbox.

## Risks

- Low risk. The change widens one character class in two match patterns.
A limit name with a hyphen now matches where it did not match before. No
other wording changes classification: the existing suite passes
unchanged.

## Model Used

Meta Muse Spark 1.3, with tool use and code execution.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [ ] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [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-05 02:47:41 -08:00
DottaandPaperclip c1c2f7e73d fix(cli): check the effective database target in doctor (#17847)
<!-- entire-trail-link-start -->
https://entire.com/gh/paperclipai/-/trails/51/changes/paperclip/51
<!-- entire-trail-link-end -->

## Thinking Path

> - Paperclip runs with embedded or external PostgreSQL.
> - The CLI checks the database before it starts the server.
> - The server uses `DATABASE_URL` before the saved connection string.
> - Doctor checked only the saved database configuration.
> - A valid environment-only setup could fail before startup.
> - This change probes the effective server target instead.
> - Operators can keep database credentials in the environment.

## Linked Issues or Issue Description

Fixes: #11598

Refs: #11612. That predecessor is closed and unmerged. The defect
remains on current master at `0cb3fc7db5`. This PR adds current
precedence coverage, including a saved embedded mode and explicitly
empty environment values.

## What Changed

- Resolve the effective URL with the same nullish environment-first rule
as the server.
- Probe external PostgreSQL when the environment selects it, even if the
saved mode is embedded.
- Keep an explicitly empty environment value distinct from an unset
value. Do not trim or replace the selected URL.
- Add eight mocked transport regressions. Keep the three embedded
storage checks.

## Verification

- `node node_modules/vitest/vitest.mjs run --config cli/vitest.config.ts
cli/src/__tests__/database-check.test.ts` — 11 passed.
- Six new cases failed before the original fix.
- Review exposed one ambient worktree-mode failure in the new embedded
fallback test. That test now sets its worktree flag explicitly.
- Both `env -u PAPERCLIP_IN_WORKTREE node node_modules/vitest/vitest.mjs
run --config cli/vitest.config.ts
cli/src/__tests__/database-check.test.ts` and
`PAPERCLIP_IN_WORKTREE=true node node_modules/vitest/vitest.mjs run
--config cli/vitest.config.ts cli/src/__tests__/database-check.test.ts`
pass all 11 cases.
- Tests cover environment-only configuration, environment precedence,
embedded override, saved fallback, empty values, unchanged URL
forwarding, and a failed effective-target probe.
- The database factory and transport are mocked. No database is started
or contacted.
- PR CI passed full typecheck, build, and broad tests on the exact
reviewed head. Broad local checks were not repeated while a separate
live qualification run owned local resources.

- Fresh Greptile review is 5/5 at
`a042fb4a28f2e1574972798ed80de2e616daf9fc`. All review threads are
resolved. All 55 successful checks for this exact head are green. Two
conditional checks are skipped, and one review check is neutral. No
checks are pending or failed.

## Risks

- Doctor now probes the database that server startup will use, instead
of an ignored saved target.
- Empty `DATABASE_URL` follows the existing server rule. It masks a
saved URL in Postgres mode and leaves embedded mode selected when no
effective URL exists.
- No schema, migration, startup resolver, or provider behavior changes.
Existing environment support is already documented in the implementation
spec and developing guide.

## Model Used

OpenAI `gpt-6.1-sol`, with repository inspection, code editing, and
offline test tools. No model or provider call was used in the
regression.

## 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.899300
2026-12-05 02:41:54 -08:00
brianCodesandClaude Opus 5.5 0da786fdc3 fix(issues): clear the compact issue-list cache when an issue changes (#17828)
## Thinking Path

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

## Linked Issues or Issue Description

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

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

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

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

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

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

## What Changed

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

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

## Verification

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

## Risks

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

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

## Model Used

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

## Checklist

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

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 02:39:21 -08:00
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