mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-16 03:31:44 +01:00
3244780bd03294c860e8cedea3bf8ea29e03cd1f
8098
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
3244780bd0 |
fix(queue): keep a message a starting run's first turn took out of the queue (#21747)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - A message posted while a run is starting goes into that run's first turn, and the task page shows it as sent > - The page shows it as sent only while the live queue lists it as a first-turn message > - When that queue closes, for example after a later Steer, the page has no lasting record of the delivery > - It then infers that the message is queued and shows it again with a Steer button > - This pull request reports each run's own first-turn receipt in the run list, and the page places those messages in that run > - The benefit is that a sent message stays sent ## Linked Issues or Issue Description Follow-up to #21661, found while I verified that change on staging. **What happened?** With a Codex runner, two messages were posted while the run was starting. The first turn took them and the agent acted on both. Then a third message was steered into the running turn. After the Steer, the first two messages came back into the queue with Steer buttons. The server queue was empty. **Expected behavior** Messages that a run's first turn took stay in the conversation as delivered. **Steps to reproduce** 1. Start a task with a Paperclip runner agent. 2. While the runner is starting, post one or two messages. 3. After the turn starts, post another message and click Steer. ## What Changed - `activityService.runsForIssue` returns `firstTurnCommentIds` from the run's `firstTurnQueuedInput` receipt. The field is set only when the receipt names this run, because a retry copies its predecessor's context. - `IssueDetail` adds those ids to the run's start inputs, so the messages are placed in that run and are not inferred as queued. - `RunForIssue` type gets the new optional field. ## Verification Red/green tests. Each failed before the fix and passes after it: - `server/src/__tests__/activity-service.test.ts`: "reports the queued messages a run's own first turn took, not a predecessor's". 33/33 pass. - `ui/src/pages/IssueDetail.test.tsx`: "keeps a message the running turn already took out of the queue after the live queue closes". The IssueDetail, queue helper, and task-chat suites pass (69 files, 1298 tests). UI typecheck passes. Staging, after #21661 deployed, Codex runner: two messages posted while the run started were taken into the first turn and acted on. No Interrupt, error banner, or composer wait was shown. A mid-turn Steer was accepted in seconds. This PR fixes the one defect that the check found. ## Risks - Low. One new read-only field on the run list. A run that took messages and then failed before its provider accepted the turn now shows those messages in that run. The next run still delivers them, and the queue still lists them while they wait. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use and code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>canary/v2026.1115.0-canary.12 |
||
|
|
e7f31705da |
perf(release): stage the verified host release daemon instead of compiling it in publish_canary (#21555)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Every master push runs a canary, and only one canary runs at a time, so its duration sets how often merged work ships > - `publish_canary` takes about 30 min. 8 min of it is `pnpm build`, and 4 min 40 s of that is an uncached `cargo build --release` of `paperclip-runnerd` > - The release then replaces that binary with the exact-source daemons that `release_runner_binaries` already built and verified for all four targets > - This pull request stages the verified daemon for the publisher's own target during a release, instead of compiling it > - The benefit is about 4.5 min less per canary, with the same verified bytes published ## Linked Issues or Issue Description **What happened?** In canary run 43487884481 (2026-11-13), the `Publish canary` step took 28.6 min. Its `pnpm build` ran 19:42-19:50. The `packages/paperclip-runner build` took 5.3 min, and its `cargo build` reported `Finished release profile ... in 4m 40s`. Every other package waited for it. `release.sh` then runs `assemble-daemons`, which overwrites `dist/bin` with the four exact-source release daemons. **Expected behavior** A release does not compile a binary that it discards. The Runner build stamp stays valid, so the server build still reuses the Runner build. Refs #21554 (the other canary speed-up) ## What Changed - `packages/paperclip-runner/scripts/build-runner-binary.mjs` (new): when `PAPERCLIP_RELEASE_RUNNER_ARTIFACTS_DIR` is set, it checks the release daemons with the existing `releaseDaemonManifest` (source revision equal to `HEAD`, digest, architecture, build metadata) and stages the host target's daemon at `dist/bin` with the existing `stageRunnerBinary`. Otherwise it runs `pnpm run build:binary` as before. - The Runner `build` chain calls this script in place of `pnpm run build:binary`. `build:binary` itself and the image build are unchanged. - `stage-release-runner-binaries.mjs` exports `metadataContract`. - Tests: `stage-runner-binary.test.mjs` (staging per target, wrong source, bad digest, missing target, non-release fallback); `runner-image-identity.test.ts` step list. - `doc/RELEASING.md` describes the behavior. ## Verification - `node --test packages/paperclip-runner/scripts/stage-runner-binary.test.mjs`: 9 of 9 pass. - `server`: `vitest run src/__tests__/runner-image-identity.test.ts`: 42 of 42 pass. - With the real daemon artifacts of canary run 43487884481 (receipts pointed at this commit): `PAPERCLIP_RELEASE_RUNNER_ARTIFACTS_DIR=... pnpm run build` in `packages/paperclip-runner` finished in 15 s with no `cargo` line. The build stamp was recorded, and `server/scripts/prepare-runner-vendor.mjs` then reported `action:reuse,reason:inputs_unchanged`. The staged daemon runs. - After merge: the next canary's `packages/paperclip-runner build` log shows "Staged the verified exact-source linux-x64 release daemon" and no `Compiling` lines. ## Risks - Low. A release still fails closed: a daemon with the wrong source, digest, architecture or metadata stops the build, and `assemble-daemons` checks all four again afterwards. - Local, Docker and CI builds without the variable are unchanged. - On macOS, staging re-signs the binary, as it does for a compiled one. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, in Claude Code with tool use and code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [ ] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>canary/v2026.1115.0-canary.11 |
||
|
|
8cd2d6a73d |
docs(skills): add aggregate-bound, lost-runner, and bug-class lessons to fix-failed-paperclip-run (#21745)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The `fix-failed-paperclip-run` skill guides agents that repair failed or stuck runs > - A recent repair series made automatic recovery more aggressive, and three lessons came out of it > - The aggregate number of automatic run starts was not bounded, so an outage produced many failing starts > - CI jobs lost to runner shutdowns and tests broken on master held merges > - Review rounds kept finding new instances of one bug class, one at a time > - This pull request adds those three lessons to the skill in eight lines > - The benefit is fewer repair rounds and safer recovery changes ## Linked Issues or Issue Description **What happened?** Recovery repairs bounded attempts per task but not the total number of automatic run starts across a company. During an outage that total was large and every start failed. CI jobs lost to runner shutdowns held merges. Review found one instance of a bug class per round. **Expected behavior** The skill tells agents to state the aggregate bound for recovery changes, to re-run lost CI jobs, and to check a whole bug class after one instance. **Steps to reproduce** 1. Read `.agents/skills/fix-failed-paperclip-run/SKILL.md` on master. 2. Observe that none of the three points is covered. Refs #21443, #21561, #21394. ## What Changed - Section 4: a repair that makes recovery start more runs states its worst-case company-wide start rate during an outage and what bounds it. - Section 6: re-run CI jobs lost to a runner shutdown; re-run an unrelated failing test once, then check master and tell its owner; after one instance of a bug class, check every entry point or counter of that class. ## Verification - `git diff --check`: no errors. - Documentation only; no code or tests changed. ## Risks Low risk. The change adds eight lines of guidance to one skill. ## Model Used Claude Opus 5.5 (`claude-opus-5-5`), in Claude Code, 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 - [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> |
||
|
|
c17ef9249d |
fix(comments): keep saved authorization cards from blocking replies (#21744)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - People use task comments to ask for help with pending requests. > - Saving a comment also checks whether it replaces any pending requests. > - A stored request that fails today's payload schema can abort that comment write. > - The connection gateway could write such a request without validating its generated target. > - This change validates new authorization cards, reads older custom identities, and keeps malformed requests from blocking comments. > - Comments remain available while authorization and review gates retain their authority. ## Linked Issues or Issue Description **What happened?** A connection authorization card can contain a generated custom target key longer than 120 characters. The gateway writes the card directly. Later, the interaction reader rejects it. Both the task interaction list and comment submission then return a validation error. Other malformed saved requests can also abort a comment write. **Expected behavior** People can ask questions on a task while authorization is pending. New cards meet the shared schema. Older generated identities remain readable. A malformed request never becomes approval because a person posted a comment. **Steps to reproduce** 1. Use a personal connection with a long UID and no grant for the current user. 2. Invoke a tool. The gateway saves an authorization request with the long UID in its target key. 3. Open the task or post a comment. Reading the saved payload fails the key length limit. Related PR searches found no existing repair for this defect. This is a focused bug fix, with no roadmap feature overlap. ## What Changed - Validate generated connection authorization payloads before either insert or update. Use a stable SHA-256 target identity from the existing connection/user idempotency key. Bound its display label. - Read older confirmation custom keys and labels without the new-input length limits. Preserve their exact identities. Keep target types, URLs, document revisions, and resolver checks strict. New requests still use the strict shared schema. - During current and historical comment supersession, keep an invalid saved request pending, report its ID and schema locations, and continue with valid siblings. Database and other unexpected errors still propagate. - Keep this behavior in the gateway writer and interaction owner. The two existing source files exceed 1,000 lines; the additions extend their existing write/hydration boundaries rather than introduce another ownership path. ## Verification - Reproduced the deployed failure through the browser: comment POST and interaction GET both returned HTTP 400 for `target.key` exceeding 120 characters. The person's draft was restored. - Ran the new regressions before the repair: four expected failures and one short-identity control pass. Failures came from real payload parsing and real PostgreSQL comment writes, not fixture setup. - After repair, all 257 tests passed in the complete affected suites: `issue-thread-interactions-service.test.ts`, `tool-gateway.test.ts`, and `issue-thread-interactions.test.ts`. - Safety cases cover fresh and reused authorization cards, repeated missing-grant calls, refusing another user's credentials, two persisted follow-ups, strict new-input limits, wrong-company resolution, unsafe URLs, invalid document revisions, malformed question and confirmation payloads, and valid sibling supersession. - Local browser acceptance used an isolated, credential-free source instance on macOS arm64 with embedded PostgreSQL and Chrome. A card shaped like an older saved long-key authorization request remained visible. Two comments saved through Send, including a second after reload. The original comment persisted and the authorization request remained pending. No model execution was configured. - Browser acceptance was repeated on final commit `58b57dfe104b2ab421c7f24c89db4c29fcfda8ec` after rebase. The server health and ownership check confirmed that exact serving revision. Both comments persisted and the authorization stayed pending. Both owned instances were then stopped. All 257 affected tests passed again after rebase. The final fixture typing correction passed its six affected PostgreSQL cases. Greptile reviewed final head `58b57dfe104b2ab421c7f24c89db4c29fcfda8ec` at 5/5, with zero review threads or open findings. Required CI is green on that head: aggregate `ci / verify` and `ci / e2e` both passed. The repository CI run is https://github.com/paperclipai/paperclip/actions/runs/43710675824 . All 55 completed checks passed; four inapplicable checks were skipped. The non-required Superagent Security Scan remains in progress at 35%, with no annotations or reported findings. This external scan is still unverified; it was not retried or marked as passed. - `git diff --check` and the module boundary check pass. All seven local server typecheck layers pass on the final fixture revision. An earlier run found fixture typing errors; those were corrected and rerun successfully. Full repo tests, release qualification, and deployment were not run. ## Risks - Stored custom keys and labels may exceed current input limits. Only those length limits change for saved confirmation payloads; unsafe links and invalid document targets still fail validation. - A malformed request stays pending and still needs repair. It does not receive consent, disappear, or block a comment. Its read or resolution can still return a validation error. - This PR does not deploy the fix or recover a remote task. The original environment remains affected until rollout. ## Model Used OpenAI GPT-6-based Codex, with code editing, shell execution, browser tools, and PostgreSQL-backed tests. The host does not expose a more specific model version or context size. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes (behavior and limits are recorded in this PR) - [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> |
||
|
|
689d62661d |
fix(server): wake a delivery task unscoped when it cannot apply settled hints (#21686)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The delivery work coordinator wakes background tasks when a database work topic settles, and passes the settled scope hints to the task's `onSettled` > - The coordinator calls `onSettled(hints)` before `wake()` > - If `onSettled` throws on a hint that it does not recognise, the task is not woken. Only a generic listener warning is logged > - Hints now cross server processes (#21681), so a hint shape from another server version can arrive during a deploy overlap > - This pull request makes the coordinator log a warning, apply the settlement unscoped once, and always wake the task > - The benefit is that a hint that a task cannot read never makes the task miss committed work ## Linked Issues or Issue Description Follow-up to #21681 (merged). This branch is based on master. **What existing behavior does this improve?** How the delivery work coordinator handles an `onSettled` callback that throws. **Subsystem affected** `server/src/services/delivery-work-coordinator.ts`. **Current behavior** `subscribeDatabaseWork` calls the coordinator listener, which calls `task.onSettled?.(hints)` and then `wake()`. If `onSettled` throws, `wake()` does not run. The work-signal publisher catches the error and logs "Database work listener failed". The task stays asleep until a different event or deadline wakes it. **Proposed behavior** If `onSettled(hints)` throws, the coordinator logs a warning and calls `onSettled(undefined)` once, which is the unscoped settlement. If that also throws, it logs a second warning. In all cases it then wakes the task. **Reason and benefit** A settled event means committed work can be ready. A task must never miss it because a hint could not be applied. **Breaking changes** None. ## What Changed - `delivery-work-coordinator.ts`: a settled event goes through `applySettled(hints)`. It tries `onSettled(hints)`. If that throws and hints were given, it tries `onSettled(undefined)` one time. Each failure logs `Delivery settlement could not be applied for <queue>` with `process.emitWarning`. Then `wake()` runs. - Unscoped means `onSettled(undefined)`. Each registered task already defines what that means. For example, scoped deadline queues, dispatch work, muse maintenance and the revocation index mark `*` dirty. Counter-style tasks set their request flag. `chat-action-work` does nothing. The fallback is bounded: it calls `onSettled` at most twice per event, it does not recurse, and it does not schedule another settlement. So it cannot loop. - `work-signals.test.ts`: a new test pins one rule of #21681 for the local path and the remote path. An unhinted `signalDatabaseWork` in the same transaction as a hinted one gives a settlement that is scoped to the hinted set. The owner of `work-signals.ts` confirmed that this is deliberate. The repository does not allow code comments in pull requests, so this sentence and the test document it. ## Verification - `cd server && npx vitest run src/__tests__/delivery-work-coordinator.test.ts`: 31 pass. New tests: - An `onSettled` that throws on an unknown hint shape: the task gets `[hint]` and then the unscoped settlement, it is woken once, and one warning is logged. `onError` is not called. - An `onSettled` that always throws: the task gets 2 calls and is woken once, with 2 warnings. A later unscoped event gives 1 call, 1 wake and 1 warning. No more runs happen after 60 seconds, so there is no loop. - A normal `onSettled`: it gets the hints once, the task is woken once, and no warning is logged. - Red/green: with the coordinator from master, the 2 throwing tests fail. `onSettled` is called only with the hints, and there is no unscoped settlement and no wake. With this branch, all tests pass. - `cd packages/db && npx vitest run src/work-signals.test.ts -t alongside`: passes on real PostgreSQL. The local listener and the receiving process both get `["company-1"]`. ## Risks - Low risk. The change applies only when `onSettled` throws. Before, that path skipped the wake. Now it wakes with an unscoped settlement. For scoped deadline queues an unscoped settlement is a `*` reload. That is the existing safe fallback, and the reconstruction interval of the queue still throttles it. - A task whose `onSettled` throws on every event now runs on every settled event and logs a warning each time. Before, it did not run. The warning makes such a defect visible. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude Code with tool use (shell, file edit, test execution). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
fb3b09aaef |
refactor: split the runner-e2e and restart-chaos READMEs into a runbook and a catalog (#21743)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - `tests/runner-e2e` is the paid Product E2E harness and `tests/restart-chaos` is the restart chaos harness > - A README is the first file a person or an agent opens in a directory > - These two READMEs grew to 3,805 and 2,277 lines. Most of each is a catalog with one section per suite or per fault scenario, and almost none of it is ever trimmed > - This pull request splits each README into a runbook and a catalog file > - The benefit is a README that can be read in full, and a clear place for the next suite or scenario note ## Linked Issues or Issue Description Refs #21670 and #21700 (the same cleanup for `doc/DEVELOPING.md` and `doc/DATABASE.md`). **Issue type** Outdated or confusing documentation. **Where is the issue?** `tests/runner-e2e/README.md` and `tests/restart-chaos/README.md` **What's wrong?** In the last 60 days, `tests/runner-e2e/README.md` gained 3,476 lines and lost 182. `tests/restart-chaos/README.md` gained 2,411 and lost 134. The setup, evidence, and CI sections sit between suite notes. The first 225 lines of the runner-e2e README are suite notes with no heading. **Suggested fix** Keep how to run the harness in the README. Move the per-suite and per-scenario sections to a catalog file in the same directory. ## What Changed - `tests/runner-e2e/README.md` is now 767 lines: credentials, local commands, the Daytona image, evidence and cleanup, billing, the dashboard, GitHub Actions, and the report preview. - New `tests/runner-e2e/SUITES.md` (3,055 lines) holds every per-suite section. The two blocks of suite notes that had no heading now have one. - `tests/restart-chaos/README.md` is now 592 lines: run, fault timing, Daytona mode, hosted mode, universal checks, grading notes, pieces, output, and the crash-point suite. - New `tests/restart-chaos/SCENARIOS.md` (1,694 lines) holds every workload and fault scenario section. - All text is moved without wording changes. Nothing is deleted. The only edits are three "(below)" references in the restart-chaos README, which are now links. - Repointed 22 anchor links and 3 plain links in `doc/evals.md` and `maps/feature-map/cases.md`. - Updated seven code comments in `tests/restart-chaos/` that name a moved section, and two skills that list the runner-e2e docs to read. ## Verification - The split script asserts that each source line is kept or moved exactly one time, and checks the first line of each range. - A link check on the four files and on every file that links into them found 0 missing files and 0 missing anchors. - `tests/runner-e2e/daytona-image.test.ts` reads the README for a Docker build recipe. The recipe is still in the README. I did not run that test locally. - `node scripts/check-maps.mjs` passes. - `node --test .github/scripts/tests/*.test.mjs`: 808 pass, 0 fail. - `pnpm verify` was not run. This worktree has no installed dependencies. ## Risks - Low risk. The change is documentation and comments only. - A link to a moved section from outside this repository lands on the top of the README. - The catalog files are still long. This change moves them off the first-read path. It does not prune them. ## Model Used - Claude Fable 5.2 (`claude-fable-5-2`), Claude Code desktop, 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 - [x] 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 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com> |
||
|
|
066c8244b5 |
perf(release): build canary daemons during source verification and keep their dependency cache (#21554)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Every master push runs a canary that publishes npm packages and reaches staging > - Only one canary runs at a time, so a canary's duration sets how often merged work ships > - A canary takes about 70 min. Two parts of it are avoidable waiting: the Runner daemons build only after the source proof, and darwin-x64 often rebuilds every dependency crate > - This pull request starts the daemon builds with the canary and keeps their dependency cache across Runner changes > - The benefit is about 15-25 min less per canary, with no change to what must pass before publication ## Linked Issues or Issue Description **What happened?** In successful canaries on 2026-11-13 the critical path was: `Reuse exact-source verification` 11-14 min, then `Release daemon (darwin-x64)` 10-28 min (9 runs: 10, 16, 18, 20, 20, 21, 24, 24, 28), then `publish_canary` 27-37 min. The daemon builds waited for the source proof, although they only build and upload artifacts. The darwin-x64 build was 16.4 min with a cache miss and 3.9 min with a hit. The native cache key included a hash of `packages/paperclip-runner/src/**`, `protocol/**` and `*.json`, but the cache holds dependency crates only (`cache-workspace-crates: false`). So every Runner change caused a full dependency rebuild. **Expected behavior** Daemons build in parallel with the source wait. The dependency cache changes only when dependencies, Cargo configuration, host or target change. Refs #21399, #16028 ## What Changed - `release.yml`: `release_runner_source` no longer needs `verify_canary`. On a canonical master push it starts at once. `publish_canary` still requires `verify_canary.result == 'success'`, so nothing publishes from unverified source. - `release-verify.yml`: the native Rust cache `shared-key` drops the Runner source hash. It keeps the Cargo manifest and configuration, host and target. - `release-verify-workflow.test.mjs`: tests that a canonical master push selects the source without the proof, that a fork, other ref or other event does not, that `publish_canary` still needs the proof, and that the cache key contains no source globs. - `doc/RELEASING.md`: describes both behaviors. ## Verification - `node --test scripts/__tests__/release-verify-workflow.test.mjs`: 73 of 73 pass. - Red: the same tests against master's `release.yml` and `release-verify.yml` fail 2 tests (the source selection and the cache key). - After merge: the next canary shows `Release daemon (*)` starting at the same time as `Reuse exact-source verification`, and darwin-x64 restores its cache. ## Risks - Low. If verification fails, that commit's daemon builds are wasted macOS minutes. Verification failures on master are now rare. - The first canary after merge saves a new cache entry, so it is not faster for darwin-x64. Later canaries are. - Stable, beta and nightly still select their source through their own gates, unchanged. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, in Claude Code with tool use and code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [ ] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
83541e89ad |
perf(recovery): re-check only changed tasks between hourly full backstop passes (#21729)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The server runs issue recovery queues on one Node main thread. `stranded-assignments` and `assigned-work-invariant` find assigned tasks that have no live run and restart them. > - #21552 scoped run hints to the run's task graph and kept a company "backstop" pass to catch a missed hint. Any graph hint arms the backstop, and the backstop runs at most every 5 minutes after the last full pass. > - The backstop reloads and re-checks every open assigned task of the company. With any trickle of activity it runs every 5 minutes. On the hosted staging instance that is about 850 tasks every 5 minutes, about 2.8 checks per second at idle, close to the measured 3.2 per second. That is work proportional to history, not to activity. > - This pull request makes the 5-minute backstop re-check only tasks whose own rows changed since the previous look, with one set-based query. A full company pass runs at most once an hour, still armed only by activity. > - The benefit is no re-checks between hourly passes when nothing changed: idle statements drop from 59 per second to 5.5 per second in a staging-shaped fixture. A task whose own state changed without a hint is still recovered within 5 minutes. ## Linked Issues or Issue Description No issue exists. This describes the problem with the fields of `.github/ISSUE_TEMPLATE/enhancement.yml`. **What existing behavior does this improve?** The missed-hint backstop of the `stranded-assignments` and `assigned-work-invariant` recovery queues (`server/src/services/recovery/work.ts`). **Subsystem affected** Server: issue recovery background work. **Current behavior** Each graph hint arms a `{companyId, backstop: true}` scope. When it opens (5 minutes after the last full pass), the queue loads every open assigned task of the company and checks each one again: about 22 statements per task for the stranded check. With a hint at least every 5 minutes, this repeats every 5 minutes, whatever changed. **Proposed behavior** Between full passes, the backstop loads only the tasks whose own rows changed since the previous look (minus a 5-minute overlap for late commits): the task row, its runs, its recovery actions, its wake requests, its thread interactions, its comments, or its assignee agent. A full company pass runs when the last one is an hour old. A real change still sends its own hint and gets an immediate targeted check. **Reason and benefit** On staging at idle, the stranded check runs about 3.2 times per second with zero runs. A fixture with staging's population shape attributes all of it to the backstop. ## What Changed - `server/src/services/recovery/work.ts`: - `fullPasses()` keeps the time of the last full pass and of the last changed-tasks pass per company. The backstop gate is 5 minutes after the later of the two. - A backstop scan decides on its first page: a full load when the last full pass is at least `ISSUE_RECOVERY_FULL_BACKSTOP_MS` (1 hour) old, otherwise a changed-tasks load since the previous look minus `ISSUE_RECOVERY_BACKSTOP_MS`. All pages of one scan use the same decision. - Each scan records its start time on its first page. A completed scan advances the saved full or changed time only to that start, so a change behind the cursor of a slow scan falls in the next window. - The stranded queue adds `changedTaskCondition(since)` to its load query. The assigned-work queue passes `changedSince` to `listSuspects`. Both return `keepUnseen: true` for a changed-tasks load. - A new `fullBackstopMs` option. When a caller sets only `backstopMs` (tests), every backstop stays a full pass, as before. - With `PAPERCLIP_DEBUG_WORK_SIGNALS=stranded-assignments`, each `check` event now names why the task was loaded: `deadline`, `reload` (unscoped reconstruction), `backstop`, `company` (company-wide hint) or `hint` (task or graph hint). - `server/src/services/recovery/changed-tasks.ts` (new): the set-based "changed since" condition. Each part uses an existing index: `issues (company_id, updated_at)`, runs by `(company_id, context issueId)`, wakes by `(company_id, payload issueId)`, interactions and comments by `(company_id, issue_id)`. - `server/src/services/scoped-deadline-work.ts`: a load result may set `keepUnseen`. Then a completed scan does not drop the pending entries it did not load, so their saved deadlines stay. - `server/src/services/recovery/assigned-work-sweep.ts`: `listSuspects` accepts `changedSince`. - `server/src/services/issue-recovery-notifications.ts`: `ISSUE_RECOVERY_FULL_BACKSTOP_MS = 60 * 60_000`. - Tests: - `server/src/__tests__/issue-recovery-idle-backstop.test.ts` (new): the staging-shaped fixture, see Verification. - The staging-shaped population helper and the fixture's statement meter come from #21724, now merged into this branch. - `server/src/__tests__/issue-recovery-work-debug-attribution.test.ts`: the check event now names its load reason (`hint` or, when the backstop loaded the task last, `backstop`) instead of `load`. - `server/src/__tests__/issue-recovery-deadlines.test.ts`: the backlog helper writes its rows with the test's fake clock, as production writes use the server clock. Without it, rows stamped with the database clock look older than the fake-clock window. ## Verification - Fixture (`issue-recovery-idle-backstop.test.ts`, embedded PostgreSQL, the real recovery, dispatch and retry-cancellation workers, fake clock, statement meter, `PAPERCLIP_DEBUG_WORK_SIGNALS=stranded-assignments:1`): one company, 50 agents, 780 in-review tasks with succeeded native runs and no execution state, 40 in-progress and 30 to-do tasks of a paused agent, 12 tasks with an active agent-owned recovery action, 3 tasks of a terminated agent. After boot, one unrelated graph hint per minute stands in for idle activity. - Wake reasons on master over 30 idle minutes with that trickle: 5,100 stranded checks, all `backstop`; 0 from hints, 0 from company hints, 0 from deadlines. That is 2.83 checks per second and 106,632 statements (59.2 per second). With no hint at all after boot, master still made one backstop pass (850 checks) in 30 minutes, armed by boot activity. - This branch, same fixture: | | master | this branch | | --- | --- | --- | | Stranded checks, first 30 idle minutes | 5,100 | 0 | | Statements, first 30 idle minutes | 106,632 | 1,044 | | Stranded checks, one idle hour (one full pass) | about 10,200 | 850 | | Statements per second over that hour | 59.2 | 5.5 | - Missed hint: a task inserted with no hint is checked and gets a run within 5 minutes plus one pass (`ISSUE_RECOVERY_BACKSTOP_MS + 2 min` asserted). - A change outside the task's own rows (its agent resumed by a raw update that sets no `updated_at`, with no hint) is not seen by the 5-minute pass. It is checked and gets a run after more than 10 minutes and within 62 minutes, through the hourly full pass. - Prompt pickup with the backstop closed: a finished run (`notifyNativeStatusReassessment`), a user comment, a hold release (`pause_lifted`, which a budget raise and an agent resume send) and an agent resume each get a check of the affected task within 60 seconds. The company-wide events re-check the whole company at 25 tasks per pass, as before. - Two regression tests in `issue-recovery-deadlines.test.ts`, red on |
||
|
|
07d5a6ee17 |
perf(db): carry scope hints in cross-process work notifications (#21681)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - Server processes share durable queues and wake each other with a
commit-bound PostgreSQL NOTIFY
> - The NOTIFY payload carries only `{version, origin, topic}`, so the
receiver gets an unscoped "settled" event
> - In `scoped-deadline-work.ts` an unscoped settle becomes `*`, which
reloads every candidate of that queue on the whole instance
> - On a large instance one cross-process notification can re-check
about 850 open tasks, at about 22 statements each
> - This blocks more than one server process per stack, and it costs
work during every deploy overlap
> - This pull request puts the topic's hints in the NOTIFY payload, so
the receiver reloads only the hinted scopes
> - The benefit is that a scoped commit in one process costs the same
scoped reload in every other process
## Linked Issues or Issue Description
**What existing behavior does this improve?**
Cross-process work notifications between server processes on one
database.
**Subsystem affected**
`packages/db` work signals (`work-signals.ts`) and their consumers, such
as `server/src/services/scoped-deadline-work.ts`.
**Current behavior**
`receiveDatabaseWorkNotification` publishes "settled" with no hints. A
scoped deadline queue then reloads all of its candidates, throttled only
by its reconstruction interval.
**Proposed behavior**
The NOTIFY payload carries the deduplicated hints of its topic. The
receiving process publishes "settled" with the same hints that a local
commit publishes. Overflow and malformed input fall back to the old
unscoped behavior.
**Reason and benefit**
A scoped commit no longer causes an instance-wide reload in other
processes. This is necessary before a stack runs more than one server
process.
**Breaking changes**
None. Old and new processes interoperate in both directions (see Risks).
## What Changed
- `packages/db/src/work-signals.ts`: the per-level pending notifications
are now a map of topic to `{ hints, unscoped }`. Savepoint merge and
rollback keep the same rules as before.
- The hints follow the local "settled" semantics: the union of the hints
from `signalDatabaseWork` and `publishDatabaseWorkSettled`. An unhinted
`publishDatabaseWorkSettled`, `notifyDatabaseWorkOnCommit`, or a topic
with no hints sends the unscoped payload.
- A hinted payload is `{version: 1, origin, topic, hints: [...]}`. The
field is additive and the version stays 1.
- Each payload is at most 1,024 bytes
(`DATABASE_WORK_NOTIFICATION_MAX_BYTES`), because current receivers drop
any payload longer than 1,024 characters before they parse it. Many
hints split into several payloads. The payloads of one topic are at most
7,000 bytes in total (`DATABASE_WORK_TOPIC_NOTIFICATIONS_MAX_BYTES`). If
a topic exceeds this cap, or one hint alone does not fit, the topic
sends one unscoped payload.
- All payloads still go in the one batched `select pg_notify(...) from
jsonb_array_elements_text(...)` statement at commit. There are no added
statements or awaits on the commit path.
- `receiveDatabaseWorkNotification` accepts payloads up to 8,000
characters (the PostgreSQL limit). It keeps the drop of own-origin
payloads and of payloads without a usable origin or topic. A missing,
malformed, or empty hint list, or a version other than 1, gives an
unscoped wake. It never throws.
- The `remote_notification` debug event now logs the received hints
(`hints`: a JSON array, or `null` when unscoped).
- Tests: new payload, compatibility and fallback tests in
`packages/db/src/work-signals.test.ts`, and a new two-process test on
real PostgreSQL in
`server/src/__tests__/scoped-deadline-work-notifications.test.ts`.
## Verification
- `cd server && npx vitest run
src/__tests__/scoped-deadline-work-notifications.test.ts`: two pools on
one embedded PostgreSQL database. Process A commits work. Process B runs
a real delivery coordinator with `registerScopedDeadlineWork` over 800
candidate rows in 20 companies.
- Master (red): a commit hinted with one company makes B load `*`: 1
load, 801 rows.
- This branch (green): B loads only `company-7`: 1 load, 41 rows. A
commit with two hints loads only those two companies (80 rows). An
unscoped commit still loads all 801 rows.
- `cd packages/db && npx vitest run src/work-signals.test.ts` (32 tests,
real PostgreSQL). New tests:
- deduplicated hints per topic, including a released savepoint and a
rolled-back savepoint
- split into payloads of at most 1,024 bytes, at most 7,000 bytes in
total, and the union of hints is complete
- overflow and one oversized hint fall back to one unscoped payload
- malformed hint lists and unknown versions wake unscoped; unusable
payloads do not wake; own-origin payloads are dropped; nothing throws
- an old-format payload `{version, origin, topic}` gives an unscoped
wake
- every new payload passes a copy of the receiver from master, which
reads it as an unscoped wake for the correct topic
- the debug event logs the received hints
- With master's `work-signals.ts`, 5 of these tests fail (red). With
this branch, all pass.
- Also run: `scoped-deadline-work.test.ts`,
`delivery-work-coordinator.test.ts`, `deployment-notifications.test.ts`,
`run-start-handover.test.ts`, `heartbeat-run-start-handover.test.ts`,
`heartbeat-run-event-atomic-append.test.ts` (111 tests pass),
`work-signal-debug.test.ts` (12 pass), and `tsc --noEmit` for
`packages/db`.
## Risks
- Mixed deploys, new sender to old receiver: every payload is version 1
and at most 1,024 bytes. The old receiver ignores the `hints` field and
wakes unscoped, as today. A commit with many hints sends several
payloads, so an old receiver can get up to about 7 unscoped wakes for
one commit. The coordinator merges them into one `*` reload.
- The sender bounds bytes, and old receivers compare `.length` in UTF-16
code units. A string never has more UTF-16 code units than UTF-8 bytes,
so a payload of at most 1,024 bytes always passes the old check.
- PostgreSQL collapses identical NOTIFY payloads in one transaction. The
chunks of one topic always carry different hints, so PostgreSQL drops
none of them.
- Mixed deploys, old sender to new receiver: the old payload has no
`hints`, so the new receiver wakes unscoped, as today.
- I did not use one large payload of about 7 KB: current receivers drop
any payload over 1,024 characters before they parse it, so they would
miss the wake during a deploy overlap.
- Consumers that read hints (for example `chat-action-work`,
`approval-queue-seeding-work`) now get the same hints from another
process that they already get from a local commit. Before, they got no
hints from another process.
- The receiver accepts hint strings from the database channel. Consumers
decode them in the same way as local hints. `scoped-deadline-work`
already turns a decode failure into a `*` retry.
> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.
## Model Used
- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude
Code with tool use (shell, file edit, test execution).
## Checklist
- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
|
||
|
|
819f61f1fd |
fix(evals): repair four cohort-15 chat cases and prefix board links in completion feedback (#21682)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - The chat-feature eval catalog runs real chat journeys. It grades saved state, rendered links and run ledgers. > - Chat-eval cohort 15 (OpenCode with `openrouter/deepseek/deepseek-v4.1-flash-1017`, master `36101ebcb9`) failed four cases where the agent did the right thing or where our own server text misled it. > - One failure was a harness race introduced by #21667. Two failures came from graders that read free-form text with keyword regexes. One failure came from an unprefixed approval link in the server's completion feedback, plus a grader that required a literal prefix. > - This pull request fixes the harness step, replaces the free-form graders with saved-state and clicked-link checks, and makes the server emit company-prefixed board links. > - The benefit is that these cases measure the feature again. The retained correct outcomes pass, and the relevant broken outcomes still fail. ## Linked Issues or Issue Description Refs #21667 **What happened?** In chat-eval cohort 15, four cases failed: - `projects.share-project`: the harness followed the agent's ID-based project link. The app then rewrote the URL to the project slug and redrew the page. The owner step timed out because Riley's option in the people picker was "detached from the DOM". #21667 introduced this path. - `skills.author-skill`: the saved skill was a correct, richer checklist. Per-sentence keyword regexes rejected it. For example, "ignore the mouse" tripped the forbidden word "ignore". - `inbox-search.show-decisions`: the reply linked the right approval and tasks and said the question was "addressed to a different teammate". A regex required the word "Riley". - `agents.hire-needs-approval`: both replies linked `/approvals/<id>` without the company prefix. The agent copied that link from `server/src/services/native-runtime/native-completion-feedback.ts`. The grader required a literal `/<prefix>/approvals/<id>`, although the board redirects the unprefixed route. **Expected behavior** Correct agent behaviour passes. Grading uses saved state, setup literals and rendered or clicked links, not free-form wording. The server gives agents canonical company-prefixed board links. **Steps to reproduce** 1. Use the retained cohort-15 evidence for the four cases. 2. Run the old graders on the retained skill markdown and decisions reply. Both fail. 3. For share-project, open a project configuration page by ID while the app rewrites the route after a delay, then use the access picker before the rewrite completes. 4. For hire-needs-approval, finish a task with a pending linked approval. The feedback links `/approvals/<id>`. **Paperclip version or commit** master `36101ebcb9` (cohort 15); fixed on top of current master. ## What Changed - `projects.share-project` (`internal-privacy.ts`, `runtime-support.ts`): after the harness follows the agent's link, it waits until the URL settles on the project's canonical route key. This reuses the #21667 approach for agent profiles: `settleAgentProfileRoute` now calls a shared `settleRouteKey`, and `projectRouteKey` follows the app's `projectRouteRef`. The owner's picker selection (`addProjectAccessMember`) now retries as one unit. If the dialog or picker closes, or an option detaches, it reopens them, searches again and selects again. It continues only when the picker shows the person and Add is enabled. - `skills.author-skill` (`integrator-skills.ts`): removed the keyword-regex checklist grader, the waiver regexes, and the reply regexes for "global activation" and "attached to me" claims. The saved-state checks stay: one agent-created writable skill, its current revision authored by the responding agent, the same bytes on the skill and the revision, the Skills/Studio inspection with reload, and assignment scope from saved assignments and audit rows. The checklist check now requires the setup literals `375`, `WCAG` and `AA` as whole tokens in the saved SKILL.md and in the rendered editor. Whether the skill still asks for keyboard-only navigation and visible labels, and whether it waives a check, is left to human review. Oracle version `skill-authoring.v10`. - `inbox-search.show-decisions` (`internal-decision-search.ts`): removed all reply regexes, including the `Riley` requirement and the wording-based separation checks. The grade now uses saved state (pending decisions unchanged, answered history unchanged, each person's own attention queue and resolver) and rendered links to the exact approval, the question's task and the history task. Oracle version `decision-search.v3`. - Product (`native-completion-feedback.ts`): the completion feedback now links `/<prefix>/approvals/<id>` and `/<prefix>/issues/<identifier>`. This fixes the approval link and the four sibling task links in the same file. - `agents.hire-needs-approval` (`runtime-hiring.ts`): the harness now clicks each reply's rendered link to its approval and records where the UI lands. The grade accepts a prefixed link, or an unprefixed link that the board redirect lands on `/<prefix>/approvals/<id>` with the proposed hire visible. Without such a link, the harness still opens the approval directly so later phases keep their evidence, and the grade fails. Oracle version `runtime-hiring.v4`. - No eval YAML changed, so the TestOps manifest does not change. `chat-catalog-descriptors.json` records the three oracle version bumps. ## Verification - Red/green tests (each new test fails on the old code and passes on the new code): - `internal-privacy-share-route.test.ts` (real Chromium): the project page rewrites its route after 0, 400 and 1500 ms, and one case closes the picker while its first results render. With the old flow, the 400 ms rewrite and the closed picker both time out on the option click (the cohort-15 failure). With the fix, Riley is added on the settled route in all cases. - `integrator-skills.test.ts`: the retained cohort-15 SKILL.md passes. The old grader rejects it. A stale skill body, another author, and a lost 375 width still fail. - `internal-decision-search.test.ts`: the retained cohort-15 reply and a reworded reply pass. The old grader rejects the retained reply. A missing or wrong approval, question-task or history-task link fails. - `native-completion-feedback.test.ts`: a pending linked approval produces `[the pending approval](/<prefix>/approvals/<id>)`, and a pending review stage produces a prefixed task link. The old code produces `/approvals/<id>`. - `runtime-hiring.test.ts`: unprefixed links that the redirect lands on the right approval pass. The old grader rejects them. A link that did not land, landed on another approval, was not clicked, or is another href still fails. - `npx vitest run --config tests/runner-e2e/vitest.config.ts chat-catalog`: all passed (one negative control in `internal.test.ts` changed from a reply wording to "approved while listing"). - `pnpm test:e2e:runner:typecheck` and `server` `tsc --noEmit`: passed. - `server` vitest for `native-completion-feedback`, `native-current-wake-completion-feedback` and `heartbeat/run-completion`: 201 tests passed. - Narrow paid run of the four full case ids on this branch: run 43657390762 (results are added in a comment). ## Risks - Low risk. The product change only adds the company prefix to links in agent feedback text. It adds one indexed company read, and only on the branches that return a link. - Less is graded automatically, by design. `skills.author-skill` no longer checks that the skill keeps the keyboard-only and visible-label checks or that it does not waive a check. `inbox-search.show-decisions` no longer checks how the reply names resolvers or separates the person's decision from others' and from history. `skills.author-skill` no longer checks whether the reply describes the assignment scope truthfully. A person reviews this meaning. Saved state and links still catch the plausible broken outcomes listed above. - `agents.hire-needs-approval` now needs a reply link that really opens the approval. A reply without a link to its approval fails as before. ## Model Used - Claude, model ID `claude-opus-5-5` (Claude Code agent with tool use and code execution). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [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> |
||
|
|
ca23330c69 |
fix(recovery): continue a task on its own when its saved files are permanently lost (#21541)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - When a run stops early, Paperclip recovers its saved files and then continues the task automatically > - Sometimes the sandbox is gone. Then saved-work recovery ends with `source_unavailable` (use another strategy) > - In that state the task showed Retry. Retry worked, because it continues in a fresh workspace. But nothing continued the task automatically > - A task must never need a person's Retry for a system failure. The target is 0% > - This pull request lets the system take the same fresh-workspace step that Retry takes, when the saved files are permanently lost > - The benefit is that these tasks continue on their own, and the sweep reports them correctly ## Linked Issues or Issue Description Refs #21478 **What happened?** A legacy run on a remote sandbox failed in setup. Its unsaved files were held for saved-work recovery. The sandbox was gone, so the recovery ended `source_unavailable` / `use_alternative_strategy`. The task then showed Retry. For about 2 hours, the assigned-work sweep logged `retry_offered` with outcome `not_started` every 15 minutes. A person had to press Retry. **Root cause** The fresh-continuation fallback returned `person_owned` / `retry_needed`. It does this when a later run of the task was withheld at dispatch (here, a scheduled retry that the hold blocked) and the source run does not continue automatically. The source was a person's earlier Retry that failed with `setup_failed`, so it was not an automatic recovery run and not a restart-class failure. Without the withheld run, the same task already continued automatically. Restore-hold ownership (`isOwnedReconciliationHold`) and the legacy refusal in `inspectFallback` were not the blocker. **Expected behavior** When saved-work recovery proves that the files are permanently gone, the system continues the task in a fresh workspace on its own. This is the same path that Retry takes. ## What Changed - `fresh-continuation-fallback.ts`: the eligibility rule (`interruptionEligibility`, which the fallback and the backlog pass share) also accepts a system-owned source run when a hold of that run has saved-work recovery `exhausted` with a permanent unverifiable-source failure (`UNVERIFIABLE_SOURCE_CODES` × `PERMANENT_SOURCE_RETRY_CLASSES`). - `recovery/assigned-work-sweep.ts`: admission can settle the hold and coalesce the sweep's wake into a pending fresh continuation. The sweep now reports this as `repaired` / `queued` (`continuedFromSavedWork`). Before, it reported `enqueue_refused` / `not_started`. - `legacy-execution-recovery.ts`: the stranded sweep calls `terminalizeLegacyExecution` for the same failed run on every pass. Its restore-hold branch rewrote the hold every time, with a new `automaticRecovery.recordedAt`, a new `updatedAt`, and `continuationDelivery: "invalidated"`. The branch now returns early when the hold already records the same no-replay decision for this run, or when a fresh continuation took the hold over. Finding: a continuation that was already recorded was not clobbered, because the existing `executionReconciliation.runId` guard returned early. But a hold with a `coalesced` delivery state would have been reset, and the churn kept bumping `updatedAt`. - New regression test `legacy-source-unavailable-continuation.test.ts`. The existing `assigned-work-invariant` test now expects the corrected sweep outcome. ## Verification - Red/green: `legacy-source-unavailable-continuation.test.ts` uses `failedRemotePreparation()` with a `destroyed` termination receipt, `recoverRetainedWorkspace`, a withheld scheduled retry, and a source that was a person's Retry. Then it runs `assignedWorkSweep(...).checkIssue` with the real `heartbeatService(db).wakeup`. - Without the fix: outcome `enqueue_refused`, and the fallback returns `person_owned` / `retry_needed`. - With the fix: outcome `repaired`. A stranded pass keeps `continuationDelivery: "pending"`. `deliverReconciledExecutions` starts the successor run. The task no longer shows Retry. There is no `not_started` entry. - Red/green: the "revisits" test fails without the `terminalizeLegacyExecution` guard, because the hold evidence changes. It passes with the guard. - Locally passing: `fresh-continuation-fallback`, `fresh-continuation-move-forward-offer`, `fresh-continuation-retry-delivery`, `legacy-execution-recovery`, both `assigned-work-invariant` suites, `assigned-work-stalled-queued-run`, `assigned-work-sweep-round-trips`, `saved-work-recovery-overdue`, and the new test file (10 files, 225 tests). `tsc --noEmit` passes for `server`. - Not run locally: the full suite. CI covers it. ## Risks - Behavior shift: a task whose source failure is system-owned now continues automatically after its saved files are proven permanently gone, even when an earlier wake was withheld. The new run does not replay the old run. It starts in a fresh workspace, with the same notes and quarantine that Retry uses. Person-owned failure codes still wait for a person. - The new hold guard can skip a rewrite. It skips only when the hold is already resolved with the same no-replay decision and the same restore-recovery data. A changed decision is still written; the test covers this. - No schema changes. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use (shell, file edits, local Vitest against embedded Postgres). ## 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>canary/v2026.1115.0-canary.10 |
||
|
|
68f641ba0b |
fix(recovery): continue a native run cut off by a sandbox client timeout (#21736)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The native runtime runs an agent's provider turn in a sandbox (for example Daytona) and records each failure on the run and its native coordinator > - A Daytona SDK request can hit its client-side deadline during a provider turn. The run then fails with `native_session_interrupted` in an ambiguous state, because the turn started and its outcome is unknown > - That failure blocks the task under a board-owned watchdog hold. No recovery owner selected the hold, because its cause is not an execution-reconciliation cause. The task never ran again, and only a person's Retry could continue it > - Recovery from an infrastructure fault must work automatically, without a person > - This pull request lets the execution-disposition pass hand that hold to the existing fresh-continuation fallback > - The benefit is that the task continues once, in an isolated fresh run, and the cut-off turn is never replayed ## Linked Issues or Issue Description **What happened?** A native run on a Daytona execution environment (native runtime, an OpenRouter model) started its provider turn. A Daytona request then failed with `HTTP request timed out after 300000ms waiting for a response. This is a client-side deadline (DaytonaConfig.requestTimeoutMs, or the per-call operation/execution timeout); any operation already started on the server may still be running.` The run failed with `native_session_interrupted`. The task had no further run: no automatic retry and no continuation. **Expected behavior** The task continues automatically, exactly once, in a fresh run from its saved work. The cut-off provider turn is not replayed. **Steps to reproduce** 1. Start a native run for an assigned task. Let its provider turn start (a `turn.started` event is saved). 2. Make a sandbox request in that turn fail with the Daytona client-side timeout error. 3. The executor saves the coordinator as `terminal_failure` with `recoveryMode: ambiguous_state`, blocks the task, and writes an active board hold with cause `native_session_interrupted`. 4. Run the execution-disposition worker (`settleUnrecoverableExecutions`). Before this change, nothing happens and the task stays blocked. **Paperclip version or commit** `master` atcanary/v2026.1115.0-canary.9 |
||
|
|
01c1e708e9 |
fix(runner): stop a turn that keeps resending a refused tool call and continue fresh (#21734)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - Native agent runs call Paperclip tools, and
`RepeatedToolFailureGuard` refuses an exact repeat of a call that
already failed validation twice
> - The refusals are not counted and never end the turn, so a model
whose host drops an argument can resend the same refused call until the
run's wall clock
> - In a recorded restart-chaos wave, an opencode/DeepSeek agent sent
the same `PATCH /api/issues/{id}` through `call_api` 431 times in 40
minutes without `body`; 427 were refused. The run held an agent slot and
delayed other tasks
> - The system knows the next step (stop the turn and continue on a
fresh session), so the harness must own it, with no Retry banner
> - This pull request counts refusals, stops the provider turn after a
bounded number with the classified cause `agent_tool_call_loop`, and
queues an automatic fresh-session continuation that tells the model to
use a dedicated tool
> - It also records the declared argument names that each opencode tool
call delivered, so we can tell whether the bridge or the model drops
`body`
> - The benefit is that a looping agent frees its slot in seconds
instead of 40 minutes, and the task continues by itself
## Linked Issues or Issue Description
**What happened?**
An opencode agent on DeepSeek created two subtasks and then tried to set
their descriptions with `call_api` `PATCH /api/issues/{id}`. Every call
arrived with `operationId`, `pathParams`, `query` and `responseText`,
but without `body`. The guard refused each repeat. The model said "I
need to include body" more than 20 times and kept sending the same call:
431 calls, 427 refused, over 40 minutes. The run stayed active and its
agent slot delayed other queued work.
**Expected behavior**
After a small, bounded number of refusals, Paperclip stops the provider
turn and continues the task automatically on a fresh session, with a
hint to use a dedicated Paperclip tool. The board shows no Retry banner
because the system owns this recovery.
**Steps to reproduce**
1. Run a native agent whose model resends one tool call with a missing
required argument.
2. The guard refuses the third and later identical calls.
3. On master, the refusals never end the turn.
**Paperclip version or commit**
`master` at
canary/v2026.1115.0-canary.8
|
||
|
|
c7efca1eaf |
perf(recovery): read an agent's own reporting chain and each pass's review waits once (#21724)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The server runs its background recovery queues on one Node main thread. Each database statement and each byte returned costs main-thread time. The target is 1,000 concurrent agents per server. > - On the idle hosted staging instance, the stranded-task check is the top remaining cost. Each check read the full agent row (with its configuration blobs) and then every agent of the company, only to decide whether this one agent can run. Per check it also opened a repeatable-read budget transaction for the same company and agent. > - The org-chain evaluation only looks at the agent's own managers. Reading the whole company is work proportional to the size of the company, for an answer that depends on a few rows. > - The same check also read the external review wait of each in-review task one task at a time. > - This pull request reads only the agent's reporting chain (one recursive query up `reports_to`), gives the stranded check a lean agent read, and reads the review waits of a pass's tasks in one call. > - The benefit is half the bytes per check (17.2 KB to 8.6 KB), 87 percent fewer rows, and no per-task review-wait chain for tasks that wait, with the same answers. ## Linked Issues or Issue Description No issue exists. This describes the problem with the fields of `.github/ISSUE_TEMPLATE/enhancement.yml`. **What existing behavior does this improve?** The per-task reads of the stranded-task recovery check (`reconcileStrandedAssignedIssues`) and of every caller of `evaluateAgentInvokabilityFromDb` and `agentService.getById`. **Subsystem affected** Server: issue recovery and agent invokability. **Current behavior** `evaluateAgentInvokabilityFromDb` reads `id, company_id, name, reports_to, status` for every agent of the company on each call. `getById` does the same for `orgChainHealth`. The stranded check calls it once per task, after a full-row agent read with the configuration blobs. On staging at idle these are the `agents where company_id = $1` read at 4.7/s and the full `agents where id = $1` read at 4.2/s. The check also calls `listExternalReviewWaits` for one task at a time (the `chat_message_links` / `chat_github_reviews` reads at about 3/s on staging). **Proposed behavior** Read only the agent's managers, with the same cycle, missing-manager, cross-company and terminated rules. Read nothing when the agent has no manager or when its own status already decides the answer. Read the stranded check's agent with only the fields it uses. Read the review waits of all tasks of a pass in one call, and use that answer only to skip a task that waits. **Reason and benefit** At idle, the average result size on staging is about 17 KB per statement. The stranded check is about 22 statements and 17 KB per task, and it runs about 3 times per second there. ## What Changed - `server/src/lib/agent-reporting-chain.ts` (new): `readAgentReportingChain` reads the agent's managers with one recursive CTE up `reports_to`, limited to the agent's company. `UNION` stops the walk at a cycle. A root agent costs no statement. - `server/src/services/agent-invokability.ts`: `evaluateAgentInvokabilityFromDb` evaluates against the chain, not the company list. It reads nothing when the agent's own status is not invokable, because the status then decides the answer and the chain is not part of it. Every caller benefits with no change: wake enqueue, queued-run claim, retries, run dispatch, wake-queue promotion, continuation delivery, task watchdogs, thread interactions, native completion feedback, native session resumption, native review participants, agent conversations and recovery. - `server/src/lib/agent-records.ts`: `getById` computes `orgChainHealth` from the chain, not from the company list. - `server/src/services/recovery/service.ts`, stranded check: - The agent read selects only `id, company_id, name, reports_to, status, lifecycle_state, lifecycle_holds`, not the full row. - `hasPersistedDurableWaitPath` takes the pass. When the task is in the pass, the first in-review task reads the external review waits of every task of the pass with one `listExternalReviewWaits` call. A task in that answer waits and is skipped. A task not in that answer is read again alone, exactly as before, so a missing answer never lets a check go further than a fresh read would. - A company-wide call without a pass gets a pass of its in-review candidates. - `server/src/services/scoped-deadline-work.ts`: an optional `beforeChecks(entries)` hook gets the entries of the batch before their checks run. - `server/src/services/recovery/pass-reads.ts` (new) and `server/src/services/recovery/work.ts`: the task queues build a pass from the batch in `beforeChecks` and give it to each check of that batch. - Tests: - `server/src/__tests__/agent-reporting-chain.test.ts` (new): property test, see Verification. - `server/src/__tests__/issue-recovery-pass-reads.test.ts` (new): statements and bytes per check, per pass and per full worker drain. - `server/src/__tests__/issue-recovery-review-wait-pass.test.ts` (new): review-wait answers and reads, see Verification. - `server/src/__tests__/monthly-spend-service.test.ts`: the select-sequence stub no longer serves a company agent list to `getById`. - `server/src/__tests__/helpers/recovery-population.ts` (new): seeds a company with an org chart, review tasks with succeeded native runs, and optional paused, terminated and recovery-action tasks. - `server/src/__tests__/issue-recovery.test-fixture.ts`: an optional statement meter, installed before the first connection. - `server/src/__tests__/agent-record-read-projections.test.ts`: `getById` now makes one typed `agents` select; the chain is a raw query. ### Why the shared review-wait read cannot start or escalate work that a fresh read would not - A pass is one coordinator batch: at most 25 checks, one after the other. Its read is never older than the start of the batch. Nothing is kept across batches. - Only the positive answer is used: "this task waits on an external review or reply", which leads to a skip. A skip only delays the task to its next check, and the end of a wait sends its own hint. - A negative answer is not used. The task is read again alone, so every decision that goes further (an enqueue or an escalation) uses a fresh read, as today. - A first version also kept the agent's invokability and the budget answer for the pass. Review found that a kept permissive answer can reach an escalation, which does not re-check those facts the way an enqueue does. That reuse is removed: those reads stay per task. No authorization, pause, approval or budget check is removed or reordered. ## Verification - Equality proof (`agent-reporting-chain.test.ts`, embedded PostgreSQL): - 60 generated org charts, 2 companies each, up to 45 agents. Shapes: deep chains (depth 44), trees, full cycles and mixed graphs. - Managers are missing (inserted with foreign keys off), in another company, terminated, paused or pending approval at random depths. Agent statuses include an unknown value. - For each agent, the test compares the old list-based result with the new result. `evaluateAgentInvokabilityFromDb` deep-equals `evaluateAgentInvokability(agent, companyRows)`. `getAgentWorkEligibility` on the chain deep-equals it on the company list (this is the `getById` path). The test also asserts that every block reason and every chain-health reason occurred. - The list-based evaluation has no depth cap (`reporting_chain_too_deep` is declared but never returned), so the chain read has none either. A cycle ends the walk in both. - Mutation check: when the recursive step does not walk up, both tests fail. - Review-wait equality (`issue-recovery-review-wait-pass.test.ts`, embedded PostgreSQL): two tasks with a direct chat reply wait, one task with an inherited GitHub review wait, one task with none, and one task with an inherited GitHub review wait in another company. One call for all of them gives the same per-task answer as one call per task, for both companies. - Review-wait reads per pass (same file): the pass makes 2 bound-run message reads (one shared, one for the task whose candidate is not a wait) where per-task reads make 3, and 89 statements instead of 91. The check results are identical. On master the pass is ignored, so the test fails (3 is not less than 3). - Statements and bytes (`issue-recovery-pass-reads.test.ts`, 50 agents, 200 review tasks with succeeded native runs and no review waits, embedded PostgreSQL, statement meter on the client sockets): | | master | this branch | | --- | --- | --- | | One check: statements | 22 | 22 | | One check: bytes received | 17,170 | 8,617 | | One check: rows | 57 | 8 | | 25 checks: bytes | 429,331 | 215,505 | | Real worker, full company drain (200 checks): statements | 4,414 | 4,422 | | Real worker, full company drain: bytes | 3,455,957 | 1,749,701 | | Real worker, full company drain: rows | 11,600 | 1,800 | | Company agent-list reads per drain | 200 | 0 | Here no task waits, so each batch pays one extra review-wait statement (8 per drain). Where tasks wait, the shared read replaces the per-task review, publication and authorization reads. - Regression after the review change, embedded PostgreSQL (664 tests): scoped-deadline-work, heartbeat-process-recovery, issue-recovery-deadlines, assigned-work-invariant, recovery-deadline-acceptance, heartbeat-issue-liveness-escalation, slack-conversation-lifecycle. Also issue-list-review-wait-authorization, external-review-wait, monthly-spend-service. - Regression of the first version, embedded PostgreSQL (757 tests): issue-assignee-invokability-routes, agent-record-read-projections, issue-graph-liveness-equivalence, heartbeat-paused-assignee-new-task, heartbeat-process-recovery, heartbeat-issue-liveness-escalation, assigned-work-invariant, recovery-deadline-acceptance, issue-recovery-actions, heartbeat-refused-assignment-wake, failed-continuation-continues-again, agent-invokability, agent-cross-tenant-authz-routes, heartbeat-stop-queued-task, issue-tree-pause-resume-run. - `tsc --noEmit -p server/tsconfig.json` passes. ## Risks - A test double that gives `evaluateAgentInvokabilityFromDb` an object with only `select` now needs `execute`, and a select-sequence stub of `getById` gets one select fewer. CI found one (`monthly-spend-service`), fixed here. - A batch with no waiting task pays one extra cheap review-wait statement. - This branch and #21729 both touch `server/src/services/recovery/work.ts` in nearby lines. The second one to merge may need a small rebase. - `server/src/services/recovery/service.ts` was already past 1,000 lines. This change adds about 25 lines to it, beside the check it changes. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, via Claude Code with tool use (shell, file edits, local PostgreSQL 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 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
7c0c116edf |
test(e2e): accept every dependency wake producer for the one automatic resume (#21732)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - When a blocker task is completed, Paperclip wakes the blocked dependent task automatically > - Two producers emit that `issue_blockers_resolved` wake: the issue update route and the issue-graph liveness backstop (plus workspace finalize); they share one idempotency key and coalesce into one wake run > - The QA task-dependency-resume journey requires the run's `contextSnapshot.source` to be exactly `issue.blockers_resolved` > - On QA both producers emitted 43 ms apart; the run was created once, but the later backstop wake recorded its source on the run, so the journey failed a resume that happened exactly once > - This pull request accepts any of the three producers and keeps every other resume condition > - The benefit is that the journey tests the user-visible promise (one automatic resume caused by this blocker) instead of which internal producer won a race ## Linked Issues or Issue Description **What happened?** QA run (launch 3937) failed task-dependency-resume on `dependency_one_automatic_resume`. The dependent's activity log shows `issue.blockers_resolved_wake_emitted` from `issue_update` at 06:59:39.973 and from `issue_graph_liveness_backstop` at 06:59:40.016 with the same idempotency key and the same wake run. Exactly one run executed, started after the blocker completed, and succeeded. **Expected behavior** The journey accepts one automatic, blocker-caused resume regardless of which producer's label the coalesced run kept. **Steps to reproduce** Grade the retained evidence with `contextSnapshot.source = "issue_graph_liveness.backstop"`: `dependency-one-automatic-resume` fails although every other condition holds. ## What Changed - `task-dependency-resume-evidence.ts`: the wake source must be one of `issue.blockers_resolved`, `issue_graph_liveness.backstop`, `workspace.finalize` (the producers of this wake reason in `server/src`). - Still required: one dependent run, `invocationSource` automation / `triggerDetail` system, wake reason `issue_blockers_resolved`, the resolved blocker id, start after blocker completion, committed native run, no leftover checkout. ## Verification - Red/green: new cases "accepts the same automatic resume when the issue_graph_liveness.backstop / workspace.finalize dependency wake recorded its source" fail before and pass after. - Existing mutants still fail: "mutation name used as wake source" (`issue.blocker_done`) and "missing saved wake source". - `tests/runner-e2e` task-dependency tests: 3 files, 108 tests pass. ## Risks - Low risk: journey grading only. Separate note: the coalesced run keeps the last producer's source label; whether it should keep the first is a provenance question, not addressed here. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use and code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [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> |
||
|
|
41a3520a2f |
fix(issues): count a blocker covered when its wake already created a queued run (#21731)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - A blocked parent task shows "covered" when its blockers have work
that will start by itself, and "needs attention" when a person must act
> - The blocker-attention read counts a blocker as active only through
its current execution run, or through a waiting wake that has not
created a run yet
> - A child whose wake already created a queued run that has not started
matches neither, so the parent shows "needs attention" and lands in the
blocked inbox
> - That work starts by itself when an agent slot frees, so the
attention is false and asks a person to act for no reason
> - This pull request also counts a blocker as active when its waiting
wake points at a queued or running run
> - The benefit is that the board and the blocked inbox stop showing
false attention while queued child work waits for a slot
## Linked Issues or Issue Description
**What happened?**
A parent task was blocked by two child tasks. Each child had a queued
run that a wake had created, and the runs waited for agent slots. The
parent showed `needs_attention` / `attention_required` and appeared in
the blocked inbox. The children started about 25 minutes later and the
parent then finished without a person.
**Expected behavior**
The parent shows `covered` with reason `active_child` while a child's
queued run waits to start.
**Steps to reproduce**
1. Create a blocked parent task with one child blocker that is assigned
to an agent.
2. Insert a queued wake for the child whose `runId` points at a queued
`heartbeat_runs` row, and leave the child's `executionRunId` empty.
3. List blocked tasks. The parent shows `needs_attention`.
**Paperclip version or commit**
`master` at
|
||
|
|
9ebc276b42 |
test(restart-chaos): let R5 wait out a slow model request and stop calling held wakes undispatched (#21730)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The restart-chaos harness (`tests/restart-chaos`) grades each task of a chaos wave with rules R1–R6 > - R5 fails a run that stays `running` with no new evidence for more than 3 minutes (`silent_dead_run`) > - In wave w-20261115T044649-s7106, task t028 failed R5. Its run was quiet for 303.6 s (05:22:13.005 to 05:27:16.647) because one DeepSeek request through OpenRouter was slow. Every sample showed an active provider turn and no tool running. The run then finished normally. > - A slow model request is not a dead run. False failures hide real failures and make the wave number wrong. > - This pull request lets R5 wait up to 10 minutes while a provider turn is active and no tool runs. It also stops the release-swap grade from calling queued wakes "never dispatched" while a live run holds them. > - The benefit is a wave grade that counts only real dead runs and real lost wakes. ## Linked Issues or Issue Description **Bug description** R5 reports `silent_dead_run` for a run that waits on one slow model request. The samples show `providerTurnActive=true` and no tool in flight for the whole gap. The run then finishes normally. Separately, the release-swap grade detail says "2 queued wake(s) never dispatched" for a task whose run was still running. Those wakes wait behind the active run by design. **Steps to reproduce** Grade the t028 samples of wave w-20261115T044649-s7106 with `gradeR5`. The result is `fail: silent_dead_run 7b51b352… 182s`. Grade a release-swap task that has a stale running run and queued wakes. The detail contains "never dispatched". **Expected behavior** R5 passes a quiet run while a provider turn is active and no tool runs, up to 10 minutes. R5 still fails a quiet run with no active provider turn after 3 minutes, and a provider turn quiet for more than 10 minutes. The grade does not call wakes undispatched while a queued or running run holds them. ## What Changed - `grader.ts`: add `PROVIDER_TURN_LIMIT_MS` (10 minutes). `deadRunningRun` uses this limit instead of the 3-minute `STALL_LIMIT_MS` when the run sample has `providerTurnActive`. A run with a tool in flight or a live process is still skipped as before. - Why 10 minutes: the observed slow request took 303.6 s. Common provider HTTP clients (the OpenAI and Anthropic SDKs) time out a request at 10 minutes. After 10 minutes the provider client has given up, so continued quiet means the run is dead, not slow. A turn whose process died also keeps `providerTurnActive` set, so the bound still catches it. - `release-swap-grade.ts`: omit the "N queued wake(s) never dispatched" note while the task has a queued, running or scheduled-retry run. The stale-run note stays. - New fixture `fixtures/t028-slow-provider-turn.json`: the real t028 samples from 05:21:30 to the run's end (116 samples). - `README.md`: document the provider-turn bound for R5 and the queued-wake rule. ## Verification - Red on `origin/master`, green with this change: - `triggers.test.ts` › R5 live evidence › "does not flag a slow model request while the provider turn is active with no tool running (w-20261115T044649-s7106/t028)" - `triggers.test.ts` › R5 live evidence › "still fails a silent run with no active provider turn, and a provider turn silent past the provider-latency bound" (guards: 4 min quiet with no provider turn fails; 9.5 min quiet with a provider turn passes; 10.5 min quiet with a provider turn fails) - `release-swap-grade.test.ts` › "does not report queued wakes as never dispatched while a run holds them (w-20261115T044649-s7106/t019)" (also checks that wakes with no live run still get the note) - `npx vitest run --config tests/restart-chaos/vitest.config.ts`: 71 files, 826 tests pass. - `npx tsc -p tests/restart-chaos/tsconfig.json --noEmit`: clean. - No wave was run. ## Risks - Low risk. The change touches only the test harness grader. - A run whose provider turn is active but whose process is truly dead now fails R5 after 10 minutes instead of 3. The fault is still caught, but later. > 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 and code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>canary/v2026.1115.0-canary.7 nightly/v2026.1115.0-nightly.0 |
||
|
|
6400698a8e |
test(e2e): find the native Plan chip in the Coordinator chat thread (#21727)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - The QA Cloud plan-revise-accept journey checks that a person can
revise and approve an agent's Plan
> - It first checks that the saved Plan chip is visible, scoped to a
settled `task-chat-turn` so a live "Writing plan" chip cannot count
> - The Coordinator workspace renders the Plan chip directly in the chat
thread; there is no `task-chat-turn` element and no `data-settled`
attribute
> - So the journey never finds the chip and fails before the person
reviews the plan
> - This pull request also accepts the chip in the chat thread
> - The benefit is that the plan journey reaches the revision and
approval steps it exists to test
## Linked Issues or Issue Description
**What happened?**
On QA Cloud (build
|
||
|
|
61c315ebab |
perf(chat): keep GitHub review check deadlines on company-wide rebuilds (#21725)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The GitHub chat channel shows a check run on each pull request it reviews. The review-check sweep (`review-check-work.ts`) keeps one `github_review_check` action per check. It republishes the check when its status changes (queued, running, completed) and polls the pull request head on a saved deadline. > - Each time the sweep loads its checks, it computes the current check status of every `received` check (`githubReviewCheckState`: 3–5 statements) to see whether the status changed. > - Run lifecycle changes anywhere in a company send a company-wide hint. So the sweep rebuilds every company's checks every 30 s and recomputes the status of every waiting check, even when nothing about those checks changed. > - This pull request keeps the saved poll deadline on a company-wide rebuild and reads the status only on targeted hints, at startup, and in `check()`. > - The benefit is that an idle company with many waiting checks costs one page read per rebuild instead of 3–5 statements per check. ## Linked Issues or Issue Description Refs #21705, #21711 (the same class of idle reload in the GitHub response sweeps). No issue exists. This describes the problem with the fields of `.github/ISSUE_TEMPLATE/bug_report.yml`. **What happened?** On paperclip.staging atcanary/v2026.1115.0-canary.6 |
||
|
|
5acf27bc3b |
perf(server): read the instance role and membership once per GET request in authorization (#21716)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - Every board request goes through authorization, and the server runs
all requests on one Node main thread
> - The cost on that thread is per database statement
> - One `GET /api/issues/:id` makes several authorization decisions (the
issue, its project, mentioned projects, related task edges), and each
decision reads `instance_user_roles` and `company_memberships` again
> - On a task with a blocker and a project mention, that is 4 role reads
and 4 membership reads in the authorization service for one request, all
with the same answer
> - This pull request shares those two reads among the decisions of one
GET or HEAD request
> - The benefit is fewer statements on every polled board read, with no
authorization cache across requests
## Linked Issues or Issue Description
**What existing behavior does this improve?**
`authorizationService.isInstanceAdmin` and `getActiveMembership` read
the database for each decision in a request.
**Subsystem affected**
Server: authorization service and app middleware.
**Current behavior**
`GET /api/issues/:id` for a plain task sends 3 `instance_user_roles`
reads and 3 `company_memberships` reads (1 each in the session
middleware, 2 each in authorization). A richer task sends 5 and 5.
**Proposed behavior**
A new middleware, `authorizationReadScope`, opens a per-request memo for
GET and HEAD requests. For a session actor, it seeds the instance admin
answer that the session middleware read at the start of the same
request. Inside the scope, `isInstanceAdmin`, `getActiveMembership`,
`issueReadSqlCondition` and `projectReadSqlCondition` read each key
once. The plain task now sends 1 role read (the session middleware) and
2 membership reads (1 in the session middleware, 1 in authorization).
The issue list and summaries routes also drop their extra role reads.
Other methods, background work and other callers keep the old reads. The
memo ends with the request, so a revoked membership takes effect on the
very next request.
**Reason and benefit**
Fewer statements per polled read, with the same decisions.
**Breaking changes**
None.
## Memo lifetime rule
- The memo exists only for GET and HEAD requests.
- It wraps `res.writeHead`, `res.flushHeaders` and `res.write` once and
never reassigns them, so hooks that later middleware installs on the
response stay in place.
- It closes at the first of: `res.writeHead`, `res.flushHeaders`,
`res.write`, `finish` or `close`. After it closes, every read goes to
the database. A stream, a long poll, a download or a callback that runs
after the response therefore never uses the memo.
- Each entry is used for at most 2 seconds
(`AUTHORIZATION_READ_MAX_AGE_MS`), then read again. Correctness does not
depend on a list of routes.
- A rejected read is removed from the memo, so the next decision reads
again.
- Nothing is kept across requests.
Long-lived and streaming routes that I checked:
- `GET /plugins/:pluginId/bridge/stream/:channel` (SSE): authorizes once
at connect with `assertBoardOrgAccess` and `assertCompanyAccess` on
`req.actor`. It does not re-authorize per event. The memo closes at
`writeHead`.
- Streaming downloads (`object.stream.pipe(res)` in assets, access and
issue attachments): they authorize before the stream starts. The memo
closes at the first write.
- `POST /board/chat/stream` and `POST
/companies/:companyId/skill-sources/discover` (NDJSON): POST, so no
memo.
- Live events, plugin API, runner and terminal WebSockets: they use
`server.on("upgrade")`, so they do not pass through Express middleware.
## What Changed
- New `server/src/services/authorization-read-scope.ts`:
`authorizationReadScope` (an AsyncLocalStorage scope for GET and HEAD)
and `readOncePerRequest`.
- `authorizationService.isInstanceAdmin` and `getActiveMembership` use
`readOncePerRequest`. The existing batch snapshot memo still comes
first.
- `issueReadSqlCondition` and `projectReadSqlCondition` use the same
`admin:<userId>` key for their instance admin check.
- For `source: "session"` board actors, the scope seeds `admin:<userId>`
with `req.actor.isInstanceAdmin`, which the session middleware read from
`instance_user_roles` in the same request.
- `createApp` mounts `authorizationReadScope` after the actor and Cloud
control middleware.
- `authorizationReadScope` closes the memo when the response starts or
ends, ignores entries older than 2 seconds, and drops rejected reads.
- New exported `readInstanceAdmin(db, userId)`: the one predicate for
`isInstanceAdmin`, `issueReadSqlCondition` and
`projectReadSqlCondition`.
- New test `authorization-request-reads.test.ts`: one role read and one
membership read in authorization per issue read, and a removed
membership gives 404 on the next request.
## Verification
- Red: without the scope, the issue read sends 3 `instance_user_roles`
statements (`expected ... to have a length of 2 but got 3`).
- Green: with the scope, it sends 1 role read and 2 membership reads.
The issue list plus the summaries request send 1 role read each.
- Revocation: delete the membership row, and the next GET returns 404.
HEAD returns 200, then 404 after the revoke.
- Stream: a GET that flushes headers, then re-reads the membership after
it is deleted mid-stream, sees the deletion.
- Background callback: a callback scheduled in a GET that runs after the
response and after a revoke reads again and sees the deletion.
- Age bound: an entry older than 2 seconds is read again. A rejected
read is not kept.
- Seed predicate: for users with an `instance_admin` row, another role
row, and no row, the session middleware value equals
`readInstanceAdmin`.
- Other actors: an agent key, a board key and a cloud tenant actor get
no seeded value.
- Response hooks: a later middleware that wraps `res.writeHead` and
`res.write` keeps working for JSON and streamed responses. This test
fails with a version that restores the original methods.
- Red: with the previous implementation, the stream, callback, age and
rejection tests fail.
- `pnpm exec vitest run` on `access-routes-hidden-floor`,
`access-routes-permissions-upgrade`, `access-service`,
`agent-auth-middleware`, `authorization-privacy-query`,
`authorization-request-reads`, `authorization-run-context`,
`authorization-service`: 8 files, 177 tests pass. Also
`inbox-mine-candidates`, `issue-read-filter-batching`,
`attention-summary-counts`, `issues-unread-inbox`,
`live-runs-batched-reads`, `privacy-production-review`,
`activity-routes`, `authorization-privacy-query`,
`muse-native-visibility`: 224 tests pass (one
`privacy-production-review` test failed once under machine load and
passed on two reruns).
- `pnpm --filter @paperclipai/server typecheck` passes.
## Risks
- This changes where authorization gets two facts inside one request, so
it needs a human review before merge.
- A GET route that changes a membership or an instance role and then
authorizes again before its response starts, within 2 seconds, would see
the earlier value. GET routes do not change memberships or roles. POST,
PATCH, PUT and DELETE requests do not use the memo.
- A board actor built by the session middleware still carries its own
connect-time `memberships` and `isInstanceAdmin` for the life of a
stream. That is the existing behavior, and this change does not affect
it.
- Nothing is cached across requests.
> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.
## Model Used
- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used 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>
canary/v2026.1115.0-canary.5
|
||
|
|
f33db357f7 |
fix(ui): let Request changes on a plan always take a revision note (#21721)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - In planning work, an agent saves a Plan document and asks the person to confirm it with a request_confirmation card > - The card offers "Request changes"; it opens a revision note only when the request sets rejectRequiresReason, allowDeclineReason or declineReasonPlaceholder > - Paperclip's own plan confirmations (runner plan approval) always set rejectRequiresReason, but an agent that writes its own confirmation may not > - Then "Request changes" rejects the plan at once and the person cannot say what should change > - This pull request makes plan confirmations always open the revision note; the note stays optional unless required > - The benefit is that a plan can always be sent back with a reason, and the QA plan journey can complete ## Linked Issues or Issue Description **What happened?** On the QA Cloud stack the plan-revise-accept journey failed. The agent saved a correct two-step Plan and a confirmation bound to the latest revision, with labels "Confirm" / "Request changes" and `rejectRequiresReason: false`. Clicking "Request changes" rejected the plan immediately; no revision note opened. **Steps to reproduce** 1. Create a request_confirmation that targets the issue's `plan` document without `rejectRequiresReason`. 2. Open the task chat and click "Request changes". 3. The plan is rejected with no note. **Expected behavior** "Request changes" opens the revision note so the person can describe the change, as for Paperclip's own plan approvals. ## What Changed - `TaskChatCompactInteractionCard`: `collectsRejectReason` is true for any plan confirmation (issue_document target with key `plan`). The note label shows "(optional)" when a reason is not required, and the reject button stays enabled with an empty note. ## Verification - Red/green: new `TaskChatInteractionCard.test.tsx` case "opens the revision note for a plan even when the request does not require a reason" fails on master (the click rejects) and passes with the change. - `ui` vitest for `src/components/task-chat` and `IssueThreadInteractionCard`: 68 files, 1119 tests pass. UI typecheck clean. - QA Cloud: the plan journey failed at this step in run 43671188287 (the only failing product step in a 22/24 run). It will be rerun after deploy. ## Risks - Low risk. Only plan confirmations change: one extra step (the note box) before a plan rejection. Non-plan confirmations are unchanged. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use and code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [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> |
||
|
|
a78be8b601 |
feat(native): send launch preparation and run digests to plugin task prepare (#21717)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Environment plugins can run a native Runner as a plugin task, and a warm session keeps that Runner between turns > - On each warm turn Core sends the plugin a `prepare` operation with the full launch requirements for the new run > - The requirements' `requirementsDigest` covers the run identity, and the run identity changes on every turn > - So a plugin cannot tell that only the run moved, and it must redo its whole preparation every warm turn > - This pull request gives the plugin two digests: one that stays the same while its preparation stays valid, and one that names the run > - The benefit is that a plugin can transfer only the run identity when nothing it reconciles changed ## Linked Issues or Issue Description **What existing behavior does this improve?** The `prepare` operation that Core sends to an environment plugin for a plugin Runner task, on cold starts and on warm attaches. **Subsystem affected** Native runtime, plugin Runner tasks, the Runner launch contract, and the plugin SDK environment task contract. **Current behavior** A warm attach sends the full requirements. The only digest available, `requirementsDigest`, includes `runId`, `turnId` and `itemId`, so it changes on every turn even when the launch is otherwise the same. **Proposed behavior** Core computes two digests for every `prepare`: - `preparationDigest`: the launch requirements an environment reconciles when it prepares a Runner: - the runner, lease and session identity; - provider, model and settings; - the prompt and instruction text; - the runtime context's instruction and skill bundles, working copy and connection instructions. It leaves out the `runId`, `turnId` and `itemId`, and the runtime context's MCP assignment and binding (with `aggregateDigest`, which hashes the assignment). MCP reaches the Runner through Core's tool authority on every run attachment, never through files the environment publishes. Core already continues a warm session across an MCP-only change (`nativeRuntimeContextsMatch` with tool refresh). The binding is also named per run (`native-mcp:<runId>`). So the digest stays the same across warm turns of one Runner, lease and session, including when the agent's MCP access changes. - `runDigest`: `preparationDigest` plus everything it leaves out: `runId`, `turnId`, `itemId`, and the MCP assignment and binding. It is unique to one run's launch. A plugin that advertises `launchDigestVersion: 1` in its task description gets both fields on `prepare`. **Reason and benefit** A plugin can compare `preparationDigest` with its saved preparation and transfer only the run identity when they match, instead of a full preparation. **Breaking changes** None. Plugins without `launchDigestVersion` get no new fields. ## What Changed - `packages/paperclip-runner/src/live/runner-provider-launch.ts`: add `runnerLaunchPreparationDigest` and `runnerLaunchRunDigest`. The preparation digest drops the MCP assignment and binding; the run digest takes the full requirements and includes them. Both use the same canonical JSON as `runnerLaunchRequirementsDigest`, with their own schema tags so the three digests never collide. Export them from the package and the server's vendored runner shim. - `packages/plugins/sdk/src/environment-tasks.ts`: add optional `preparationDigest` and `runDigest` to the `prepare` operation, and optional `launchDigestVersion: 1` to the task description. The capability gates both digests. - `server/src/services/native-runtime/plugin-runner-task.ts` and `native-session-executor.ts`: send both digests on `prepare` when the description advertises `launchDigestVersion: 1`. - `server/src/services/environment-task-runtime.ts`: recompute both digests from the requirements, and refuse a `prepare` whose digests are missing in part or do not match. - `tests/runner-e2e/source-sdk-public-inputs.json`: refresh the SDK public source pin. - Tests: - the preparation digest is stable across runs and changes when the runner, lease, session, instructions, model, approval policy or settings change; - with a runtime context, an MCP-only change (the run's binding, no binding, a changed access set) keeps the preparation digest and changes the run digest; - a change to the instruction bundle, instruction entry, a skill bundle, the skill set, the working copy or the connection instructions changes the preparation digest; - the run digest changes per run; - Core sends the digests only when advertised; - the runtime refuses forged or partial digests before it calls the plugin. ## Verification - `npx vitest run src/live/runner-launch-preparation.test.ts` in `packages/paperclip-runner`: 26 passed. - `npx vitest run src/services/native-runtime/plugin-runner-task.test.ts src/__tests__/environment-task-runtime.test.ts` in `server`: 160 passed. - `npx vitest run source-sdk-public-inputs.test.mjs source-sdk-evidence.test.ts source-sdk-public-type.test.ts` in `tests/runner-e2e`: 59 passed. - `pnpm typecheck` in `server` and in `packages/paperclip-runner`: clean. - Not run locally: the full suite. CI covers it. ## Risks Low risk. The digests are new optional fields behind a plugin capability version. Core computes them and checks them again before it calls the plugin, so a plugin can rely on them. They prove only that the launch requirements are unchanged. A plugin that skips work on a match must still check its own state, such as files it published into the sandbox. If the runtime context carries values that change per run, the preparation digest changes too, so a plugin does its full preparation. That is safe, but the plugin saves nothing. The MCP binding is the one such value Core sets per run today, and MCP is excluded entirely. A plugin that does publish MCP configuration into its sandbox must not rely on this digest for it. Values outside the requirements are not covered at all: the account identity and credentials, the GitHub broker, project IDs, and the plugin's own runtime revision. A plugin must keep checking those itself. A match lets a plugin skip publishing its launch configuration, not computing the descriptor: `prepare` must still return a launch whose `requirementsDigest` matches the current requirements, which carry the current MCP assignment and binding. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use (shell, code search). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
b1e70ab6dd |
fix(db): recover prepared statements that a pooler or schema change invalidates (#21718)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work.
> - The server runs every database statement from one Node main thread.
With `prepare: true`, postgres.js sends a statement in one round trip
instead of two, and the CPU cost of each statement is about half
(benchmark from #21707).
> - `DATABASE_PREPARED_STATEMENTS=true` turns on preparation for ORM
queries (#17673). Hosted instances connect through a transaction-mode
pooler (PgBouncer 1.22 or later, Neon `-pooler` hosts), which supports
protocol-level prepared statements.
> - I tested the flag locally through PgBouncer 1.26.1 in transaction
mode. Evictions, server connection churn, `RECONNECT`, transactions,
pipelining, `SET LOCAL`, advisory transaction locks and savepoints all
work. One failure is not acceptable: after a migration changes a column
type, every prepared statement that reads that column fails, for every
client and for every new process.
> - PgBouncer shares one server-side prepared statement by SQL text.
PostgreSQL never repairs a named statement whose result type changed, so
it fails with `cached plan must not change result type` until PgBouncer
drops it. The postgres.js retry prepares the same text again, and
PgBouncer gives it the same broken statement. postgres.js also caches
the failed statement without columns, so the connection throws
`TypeError: Cannot read properties of undefined (reading 'length')` for
that text even after the schema is correct again.
> - This pull request makes the client recover. When a prepared
statement fails with a prepared-statement error, the client stops
preparing that text, retries once without preparation where that is
safe, and counts it. It also caps the number of prepared texts.
> - The benefit is that the flag can be turned on behind a pooler
without a deploy migration that breaks reads. Behavior with the flag
unset or `false` does not change.
## Linked Issues or Issue Description
Refs #17673 (the opt-in), #10795 (the flag), #21707 (the CPU benchmark).
**What happened?**
With `DATABASE_PREPARED_STATEMENTS=true` behind PgBouncer 1.26.1 in
transaction mode (`max_prepared_statements=5`, local PostgreSQL 17), a
change of a column type made every later execution of an affected
statement fail. A new client process failed in the same way. Measured
with the local probe, 20 executions after the change and 10 from a new
process:
| Change | Before: failures | After: failures |
| --- | --- | --- |
| `int` to `bigint`, ORM read outside a transaction | 20/20, new process
10/10 (0A000) | 0/20, 0/10 |
| `varchar` length change, ORM read | 20/20, 10/10 | 0/20, 0/10 |
| Add column, `select *` | 20/20, 10/10 | 0/20, 0/10 |
| `int` to `bigint`, first statement of a transaction | 20/20, 10/10 |
0/20, 0/10 |
| `int` to `bigint`, second statement of a transaction | 20/20, 10/10 |
1/20, 1/10 |
| Table recreated with its original shape, same client | 10/10
(TypeError in `DataRow`) | 0/10 |
| Add column, explicit-column ORM read | 0/20 | 0/20 |
**Expected behavior**
A statement whose pooled prepared statement is stale or lost runs
anyway, and the failure does not reach the caller.
**Steps to reproduce**
1. Run PostgreSQL behind PgBouncer 1.22 or later with `pool_mode =
transaction` and `max_prepared_statements` above 0.
2. Start Paperclip with `DATABASE_PREPARED_STATEMENTS=true` and run a
read of a table a few times.
3. Change the type of a column that the read returns, for example `alter
table ... alter column n type bigint`.
4. Run the read again from the same process or from a new process: it
fails with `cached plan must not change result type`.
## What Changed
- `packages/db/src/prepared-queries.ts`:
- The prepare decision for each `unsafe` query is made when the driver
builds the query, not when the caller creates it, so a query that waits
on a busy connection sees a text that was demoted after it was queued.
- A failure with 26000 (`prepared statement does not exist`), 42P05
(duplicate statement name), or 0A000 `cached plan must not change result
type` demotes the text: the client does not prepare it again in that
process.
- A pooled statement that fails in that way is retried once with
`prepare: false`. Statements in a reserved connection, cursors,
`forEach`, `describe` and queries with `onexecute` are not retried.
- When the failed statement is the first statement that the transaction
ran (only `SET TRANSACTION` before it), the client restarts the
transaction on the same connection: `ROLLBACK`, `BEGIN` with the same
options, the same `SET TRANSACTION` statements, then the statement
unprepared. The callback runs once and receives the result. Tagged
statements and statements in savepoints count toward the execution
order. The client does not restart when another statement of the
transaction is queued, and it never restarts inside a savepoint.
- At most 1,000 distinct texts are prepared for each client and its
private pools. Texts longer than 8 KB are not prepared. Explicit
per-query `prepare` options, simple queries and the flag-off paths are
unchanged.
- `packages/db/src/client.ts`, `packages/db/src/index.ts`: a client and
its dedicated, liveness, checkpoint, file-storage and listener pools
share one state. `preparedStatementStats(db)` returns the prepared,
unprepared, demoted and retried counts.
- `packages/db/src/prepared-queries-postgres.test.ts`: nine tests
against embedded PostgreSQL: restart after a stale plan and after a lost
statement (the callback runs once and its later work commits),
`repeatable read read only` kept after a restart for driver and ORM
transactions, no restart after a later statement, after a tagged first
statement, or for an out-of-order await, a savepoint whose first
statement fails while the outer transaction continues once, the pooled
retry with `.values()`, and the cap.
- `doc/DATABASE.md`, `docs/deploy/database.md`: the cap and the
recovery.
## Verification
- Red/green, `pnpm --filter @paperclipai/db exec vitest run
src/prepared-queries-postgres.test.ts`. With the old
`prepared-queries.ts` (stub stats exports only), the five new tests
fail: two transactions fail with the stale-plan and the
missing-statement errors, the ORM read fails with 42P05, the invalidated
text is prepared again, and 5 texts are prepared where the cap is 2.
With this change, 23/23 pass.
- `pnpm --filter @paperclipai/db exec vitest run` on
`prepared-queries-postgres`, `client-options`, `client`,
`dedicated-connection-pool`, `dedicated-connection-admission`,
`response-capture-postgres`, `lazy-transaction-queries`,
`client-disconnect-replay`: 91/91 pass on the final revision. `tsc
--noEmit -p packages/db` passes.
- 31 server test files with `DATABASE_PREPARED_STATEMENTS=true`
(services, routes, inbox, recovery, heartbeat events, agent auth,
prepared-statement helpers): 829/830 pass. The one failure
(`execution-workspaces-service`, a git-scan timing test) passes alone
with the flag on and off. The machine load average was 9 to 20.
- Local PgBouncer probe (not in CI, because CI has no PgBouncer):
PgBouncer 1.26.1, PostgreSQL 17, postgres.js 3.4.9 (patched), Node 26.4.
The results in the table above, plus 0 failures for 4,800 statements
over 60 distinct texts with `max_prepared_statements=5`, 0 failures with
`pg_terminate_backend` and `RECONNECT` every 25 statements, and 0
failures for transactions with `SET LOCAL`, pipelines of 20 statements,
`pg_advisory_xact_lock` and savepoint rollback.
- Through PgBouncer 1.26.1 (transaction mode,
`max_prepared_statements=5`, 4 server connections) and PostgreSQL 17, at
head
|
||
|
|
89de6cbe3e |
perf(server): list skills without a folder transaction when bundled folders exist (#21715)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The board UI polls `GET /api/companies/:companyId/skills`, and the server runs all requests on one Node main thread > - The cost on that thread is per database statement, so a polled read must stay small > - Each skills list read reconciles the bundled skill folders, and that opened two transactions with a company advisory lock, even when all folders already existed > - A write-path guard must not run a lock and a transaction on every poll > - This pull request checks the current folders with a plain read first and takes the lock only when a folder must change > - The benefit is a skills list read with no transaction and no advisory lock, and 13 fewer statements (58 to 45) ## Linked Issues or Issue Description **What existing behavior does this improve?** `folderService.ensureBundledCategory` and `pruneEmptyBundledCategories` always open a transaction and take `pg_advisory_xact_lock` for the company folders. **Subsystem affected** Server: skill folders service, used by the company skills list. **Current behavior** Every `GET /api/companies/:companyId/skills` sends 58 statements, including 2 transactions (BEGIN, lock, reads, COMMIT), even when nothing changes. **Proposed behavior** `ensureBundledCategory` reads the company skill folders once. When the bundled root exists and the category folder exists with the expected name, it returns that folder. `pruneEmptyBundledCategories` computes the empty categories with plain reads and returns when there is nothing to delete. In all other cases, both functions take the lock and run the old code, which reads the folders again under the lock. The same request sends 45 statements with no transaction. **Reason and benefit** The polled read stops taking a company lock, and it sends fewer statements. **Breaking changes** None. ## What Changed - `ensureBundledCategory`: a plain read fast path when the category folder and the bundled root exist and the name matches. Create and rename still run under the company folder lock. - `pruneEmptyBundledCategories`: a plain read pre-check. The delete still runs under the lock, and it computes the empty set again under the lock. - New test `company-skills-list-statements.test.ts`: a warm skills list read has no transaction and no advisory lock and at most 45 statements; two concurrent first ensures create exactly one folder; two concurrent first list requests create no duplicate folder; a renamed category is repaired and an empty category is pruned through the locked path. ## Verification - Red: before the change, the warm read had 2 transactions (`expected 2 to be +0`) and 58 statements. - Green: after the change, the warm read has 0 transactions, no `pg_advisory` statement, and 45 statements. The response body is equal to the first read. - Concurrency: two `ensureBundledCategory` calls at once return the same folder, and there is exactly one row for the system key. - `pnpm exec vitest run` on `company-skills-list-statements`, `company-skills-service`, `company-skills-routes`, `company-skills-runtime-concurrency`, `company-skills-catalog-service`, `company-skills` and the folder tests: 215 tests pass. Two `company-skills.test.ts` tests in "project workspace skill discovery" fail on my machine with and without this change. They test file system discovery and do not use the folders service. - `pnpm --filter @paperclipai/server typecheck` passes. ## Risks - Low risk. The fast path returns only when the locked path would return the same folder without a write. Every write still happens under the lock, after a fresh read. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used 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>canary/v2026.1115.0-canary.4 |
||
|
|
30c4d2f4a1 |
perf(server): read the issue detail with fewer database statements (#21713)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - The board UI loads the task page through `GET /api/issues/:id`, and
the server runs all requests on one Node main thread
> - A CPU profile of the server shows that the cost is per database
statement: SQL building, parameter encoding, result parsing and one
socket write each
> - The issue detail read sent 73 statements for a task with two
ancestors, one blocker and a project mention
> - Several of those statements read the issue row again, only to get
values that the route already loaded
> - This pull request passes the loaded issue to those reads, walks the
ancestor chain in one query, and skips reads whose result the response
does not use
> - The benefit is 9 fewer statements on each task page load (73 to 64),
plus one fewer statement for each extra ancestor level, with a
byte-identical response
## Linked Issues or Issue Description
**What existing behavior does this improve?**
`GET /api/issues/:id` reads the same issue row several times in one
request, and walks the ancestor chain with one statement for each level.
**Subsystem affected**
Server: issue routes and the issue, issue reference and project
services.
**Current behavior**
The route loads the issue, then `getRelationSummaries`,
`getCurrentScheduledRetry`, `findMentionedProjectIds`,
`listIssueReferenceSummary` and `getAncestors` each read the issue row
again. `getAncestors` sends one statement for each ancestor. The inbox
archive fields read two activity aggregates even when the issue has no
archive row. The project embed reads the workspace provider catalog, but
the compact embed does not return it. The test fixture request sends 73
statements.
**Proposed behavior**
The route passes the values it already has. The ancestor walk is one
recursive query. The activity aggregates run only when an archive row
exists. The project embed skips the provider catalog. The same fixture
request sends 64 statements, and the JSON response is the same.
**Reason and benefit**
Fewer statements per request means less CPU on the main thread for every
open task page.
**Breaking changes**
None. Other callers of the changed service functions keep the old
behavior, because the new arguments are optional.
## What Changed
- `issueService.getRelationSummaries` and `getCurrentScheduledRetry`
accept an optional known `companyId` and then skip the issue read.
- `issueService.findMentionedProjectIds` accepts the loaded issue
(`companyId`, `title`, `description`).
- `issueService.getAncestors` accepts the known `parentId` and walks the
chain in one recursive query. It keeps the order (nearest first), the
limit of 50, and the stop at a cycle or at a task that is its own
parent.
- `issueService.getActiveInboxArchiveFields` reads the archive row first
and reads the activity aggregates only when an archive row exists.
- `issueReferenceService.listIssueReferenceSummary` accepts an optional
known `companyId`.
- `issueThreadInteractionService.listForIssue` accepts the loaded issue
(`status`, `companyId`, `executionWorkspaceId`). `GET
/api/issues/:id/interactions`, which the board polls, passes it (11 to
10 statements).
- `projectService.getById` accepts `{ workspaceProvider: false }`. The
issue detail route uses it, because `compactIssueProject` never returns
`workspaceProvider`.
- Test helpers: `createStatementCensus` (statements per request, grouped
by statement shape with the server callers), and a board route fixture
with the real session actor middleware. `meterDatabaseStatements` can
record a call stack for each statement.
- New tests: `issue-detail-statements.test.ts` (statement budget,
byte-identical normalized JSON against a fixture file, access rules,
membership removal on the next request, ancestor walk with a cycle) plus
an interactions poll test, and `board-route-statement-census.test.ts`
(census of the polled and page-load board routes).
## Verification
- Red: before the change, the fixture request sent 73 statements, and
the budget test failed (`expected 73 to be less than or equal to 64`).
- Green: after the change, the request sends 64 statements. The
normalized JSON is byte-identical to the fixture file that I wrote
before the change.
- Access: another company's user gets 404, a missing issue gets 404, an
anonymous request gets 404, a hidden issue stays readable for a member,
and a removed membership gets 404 on the very next request.
- `pnpm exec vitest run` on `issue-detail-statements`,
`board-route-statement-census`, `issues-goal-context-routes`,
`issues-service`, `issue-references-service`, `inbox-archive-routes`,
`heartbeat-task-context`, `project-workspace-provider.integration`,
`workspace-provider-failure`, `issue-telemetry-routes`,
`issue-thread-interaction-routes`, `issue-document-restore-routes`,
`heartbeat-referenced-projects`, `project-environments`: 14 files, 414
tests pass.
- `pnpm --filter @paperclipai/server typecheck` passes.
- Interactions: the polled route sends 10 statements instead of 11, with
a response equal to the service result without the known issue.
- Census: `PAPERCLIP_STATEMENT_CENSUS=/tmp/census.txt pnpm exec vitest
run src/__tests__/board-route-statement-census.test.ts` writes
statements per request and the top statement shapes for each board
route.
## Risks
- Low risk. The new arguments are optional, so other callers keep the
old reads.
- When the route passes a known `companyId`, a concurrent delete of the
issue no longer gives a 404 from these sub-reads. The route already
loaded and authorized the issue in the same request, so the response is
the same in practice.
- The JSON fixture file fails when someone changes the issue detail
response. Regenerate it with `PAPERCLIP_WRITE_ISSUE_DETAIL_GOLDEN=1` and
review the diff.
> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.
## Model Used
- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used 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>
|
||
|
|
f4f4902707 |
perf(chat): read the run state of a GitHub response sweep page in one batch (#21711)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - The GitHub chat channel has two sweeps for request response
comments: the acknowledgement sweep (`acknowledgement-work.ts`) and the
terminal-response sweep (`terminal-response-work.ts`). Each reads pages
of up to 100 requests.
> - For each loaded request, both sweeps call `readGitHubResponseRun`
one row at a time. That is one latest-run statement, plus the run
identity context read and the message link read of
`chatRunSourceMessageId`. A page of 100 requests costs about 300
statements.
> - On paperclip.staging, those two provenance reads ran at about 13/s
each. #21705 stops the idle backlog from being reloaded. This PR makes
the reads that remain cost a constant number of statements per page.
> - The per-row read also had a failure mode. A 403 from one run's
provenance check aborted the acknowledgement sweep's whole page, so no
request of that company was acknowledged until the 403 went away.
> - This pull request adds a batched `readGitHubResponseRuns` and uses
it once per page in both sweeps.
> - The benefit is a constant number of statements per page, and a
provenance failure that affects only its own request.
## Linked Issues or Issue Description
Refs #21705 (the same sweeps; that PR stops reloading requests that
cannot progress).
No issue exists. This describes the problem with the fields of
`.github/ISSUE_TEMPLATE/bug_report.yml`.
**What happened?**
On paperclip.staging (2026-11-15, about 01:45–02:25Z),
`provenanceReads.context` (`select … from run_identity_contexts where id
= $1 and run_id = $2 and company_id = $3 and status = $4 limit $5`) ran
at 13.37/s, and `provenanceReads.link` (`select
chat_conversations.issue_id, chat_endpoints.provider from
chat_message_links join … where chat_message_links.company_id = $3 and
comment_id = $4 …`) ran at 13.20/s. Both GitHub response sweeps reach
them through `readGitHubResponseRun` → `chatRunSourceMessageId(db, run,
{ provider: "github" })`, once for each loaded row. `load()` costs one
page read plus three statements per row. `check()` read the run state
twice for each due request (before and after the acknowledgement).
In the acknowledgement sweep, a 403 from `chatRunSourceMessageId` (for
example, a run whose identity context is no longer accepted) threw out
of `entry()` and aborted the whole page. The terminal sweep already kept
such a row due, so the acknowledgement owner could revoke it.
**Expected behavior**
A page of requests costs a constant number of statements. A failure for
one run affects only the requests of that run.
**Steps to reproduce**
1. Create 120 GitHub response requests on 30 tasks. Give each task an
ended run with an accepted identity context.
2. Register the terminal-response sweep. On master, the first pass costs
one page read plus three statements per row.
3. Mark the requests `received`, revoke one run's identity context, and
register the acknowledgement sweep. On master, the load fails with a
403, and none of the 150 requests is acknowledged.
**Paperclip version or commit**
master at
|
||
|
|
8cc26221af |
perf(native): accept a plugin's in-preparation project-auth check on warm attach (#21710)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Environment plugins can run a native Runner as a plugin task, and a warm session keeps that Runner between turns > - On a warm turn Core attaches the kept Runner to the new run: the plugin prepares the new run, then Core checks managed project authentication > - A warm attach has no submit step, so Core sends a separate `check_project_auth` operation after `prepare` > - That separate operation is one more plugin dispatch and Launcher round trip on every warm turn, about 0.12–0.18 s, and it is serial > - This pull request lets the plugin do the check inside `prepare` and say so, so Core does not send the second operation > - The benefit is a faster warm turn with the same proof and the same failure behavior ## Linked Issues or Issue Description **What existing behavior does this improve?** The warm attach of a plugin Runner task (`plugin-runner-task.ts` `prepareLaunch`). When `launched` is true, Core always calls `checkProjectAuth` after `prepare`. **Subsystem affected** Native runtime, plugin Runner tasks, and the plugin SDK environment task contract. **Current behavior** Cold starts fold the check into submit (`projectAuthCheckAtSubmit`). Warm attaches send `prepare`, then a separate `check_project_auth`. Measured on a plugin sandbox, the separate operation costs 0.12–0.18 s on each warm turn. **Proposed behavior** The `prepared` result has a new optional flag, `projectAuthChecked`. A plugin sets it only when it ran the managed project-authentication check inside this preparation, for this launch's configuration, provider and projects, and the check allowed them. Core then records the same lease proof that an allowed `check_project_auth` records, and skips the separate check. **Reason and benefit** One fewer serial round trip on every warm turn. The plugin already runs the check for this task; this removes a dispatch, not a check. **Breaking changes** None. The flag is optional. A plugin that does not set it, or that saw a refusal, gets the current behavior. Plugins detect the flag with the SDK schema before they send it. ## What Changed - `packages/plugins/sdk/src/environment-tasks.ts`: add optional `projectAuthChecked: true` to the `prepared` result, with a doc comment that defines it. - `server/src/services/environment-task-runtime.ts`: when a `prepared` result has `projectAuthChecked`, record `runnerTaskProjectAuthValidation` for the launch's configuration, provider and projects, without `atSubmit`. This is the proof that `submit` and `read_file` require. - `server/src/services/native-runtime/plugin-runner-task.ts`: do not send `check_project_auth` when the prepared result has `projectAuthChecked`. - Tests: a warm attach with the flag makes only `prepare`; without it, `prepare` then `check_project_auth`. The runtime test covers all four combinations of `projectAuthCheckAtSubmit` and `projectAuthChecked`. ## Verification - `npx vitest run src/services/native-runtime/plugin-runner-task.test.ts src/__tests__/environment-task-runtime.test.ts` in `server/`: 157 passed. - Not run locally: full typecheck and full suite. CI covers them. ## Risks Low risk. Core trusts the flag the same way it trusts a plugin's `check_project_auth` answer and `projectAuthCheckAtSubmit` today. A refusal still goes through Core's own check, so the conflict error is unchanged. The plugin side ships separately and sends the flag only when its SDK accepts it. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use (shell, code search, tracing queries). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
b5ba548112 |
feat(server): add an instance-admin server metrics endpoint for the scale ramp (#21708)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The scaling plan (`doc/plans/2026-11-13-thousand-concurrent-agents.md`) has a finish line that a real-agent ramp harness checks (#21695) > - Four finish-line criteria need numbers from inside each server process: main-thread CPU, run event lateness, agent API time before the handler, and missed lease renewals > - The server had no way to give them, so every harness run was at best "incomplete" > - This pull request adds one instance-admin endpoint that returns those numbers per process over a short sliding window, off by default, and connects the harness to it > - The benefit is that a ramp run can measure every server criterion it can see, with near-zero cost when on and no cost when off ## Linked Issues or Issue Description Refs #21695 **Subsystem affected** Server (instance routes, run event append, native lease renewal), database client (statement counter), and the scale-ramp harness in `scripts/scale-ramp/`. **Problem or motivation** The scale-ramp harness reads `PAPERCLIP_SCALE_METRICS_URL`, but the server has no endpoint for it. The criteria `main_thread_cpu`, `run_event_lateness_p99`, `agent_api_pre_handler_p99` and `lease_renewals_missed_zero` are therefore always "not measured", and no run can pass. **Proposed solution** Add `GET /api/instance/server-metrics`. It returns a JSON snapshot of one server process over the last 50 to 60 s. Only an instance admin can read it. The env flag `PAPERCLIP_SERVER_METRICS` (read once at start, default off) turns on collection and the route. Off, the path answers 404 and no collector starts. **Alternatives considered** - The postgres.js `debug` option for the statement counter: rejected, because it captures a stack (`new Error()`) for every query. - Process CPU from `process.cpuUsage()` as `mainThreadCpu`: rejected, because it includes GC and libuv threads. It is returned as `processCpu` instead, and `mainThreadCpu` reads the main thread from `/proc` (Linux only, null elsewhere). - Default on: the measured cost is negligible (numbers below), but the event-loop monitor wakes the process every 20 ms when idle, and this is a new instance-wide surface. It stays off; the runbook says how to turn it on for a ramp run. ## What Changed - `server/src/services/server-metrics.ts`: a per-process collector. It uses `performance.eventLoopUtilization()`, `monitorEventLoopDelay` (20 ms), `process.cpuUsage()`, the main thread's `/proc/self/task/<pid>/stat` on Linux, and six 10 s buckets of native `perf_hooks` histograms. One unref'd timer rotates the buckets. Nothing on the hot path awaits, allocates per call or does I/O. - `server/src/routes/instance-server-metrics.ts`: `GET /api/instance/server-metrics`, guarded by the existing `assertInstanceAdmin` (the check that `/instance/database-backups` and other instance routes use). It returns numbers, a random per-process `processId`, `uptimeSec`, `buildRevision` and `windowMs`. It returns no SQL, names, IDs or hostnames. - `server/src/app.ts`: when the flag is on, two middlewares time agent API requests from arrival to the API router, the route is mounted, and shutdown stops the collector. When the flag is off, nothing is mounted. - The snapshot also carries `dedicatedConnections` from `dedicatedDbConnectionStats()` (#21693): `limit`, `inUse`, `waiting` at request time and `peakInUse`, `queued`, `overLimit`, `nestedOverLimit` since start. The harness ignores it today; it shows dedicated-connection queueing in a restart burst. - `packages/db/src/statement-count.ts` and `lazy-transaction-queries.ts`: a Drizzle logger that increments one counter per statement replaces Drizzle's no-op logger. No edit to `client.ts`. - `paperclip-control-plane-port.ts`: one call records runner `emittedAt` to committed row for each committed (not duplicate) runner event. - `native-execution-lease.ts`: one call counts a lease whose renewal deadline passed. - Harness: missed lease renewals are summed per `processId` (several processes, or a restart, no longer cancel out). A metrics URL on the target origin gets the board token in the `Authorization` header; `PAPERCLIP_SCALE_METRICS_TOKEN` still overrides it, and another origin gets no token. - Contract: `scripts/scale-ramp/server-metrics.fixture.json` is the serializer's own output. A server test asserts the serializer produces exactly this file, and a harness test parses it and checks every field. - `rules/company-scope-exceptions.mdc`: adds the snapshot as an instance-wide exception with its reason. The runbook in the plan doc documents the path, the flag, the credential and each field. | Field | Provided | Source | | --- | --- | --- | | `mainThreadCpu` | yes (Linux; null elsewhere) | `/proc/self/task/<pid>/stat` utime+stime | | `eventLoopUtilization` | yes | `performance.eventLoopUtilization()` | | `eventLoopDelayP99Ms` | yes | `monitorEventLoopDelay`, highest 10 s p99 in the window | | `statementsPerSecond` | yes | Drizzle logger counter (not BEGIN/COMMIT or raw driver calls) | | `poolWaitP99Ms` | absent | postgres.js has no cheap hook for queue time | | `runEventLatenessP99Ms` | yes (null with no events) | runner event append | | `agentApiPreHandlerP99Ms` | yes (null with no agent requests) | arrival and router-entry middlewares | | `leaseRenewalsMissed` | yes, counter since process start | native lease deadline timer | ## Verification - `cd server && npx vitest run src/__tests__/instance-server-metrics-routes.test.ts src/__tests__/server-metrics.test.ts`: through `createApp` on the embedded test database. 200 with the exact field set for an instance admin; 403 for a company owner who is not an instance admin, for an agent key, and unauthenticated; 404 and no collector when the flag is off; values move after agent requests, statements, a late run event and a missed renewal; the body has no IDs, keys or SQL. - `cd server && npx vitest run src/services/native-runtime/native-execution-lease.test.ts src/services/native-runtime/paperclip-control-plane-port.test.ts src/__tests__/api-server-timing.test.ts`: the lease and run-event hooks (red/green checked for the lease hook by removing the call). - `cd packages/db && npx vitest run src/lazy-transaction-queries.test.ts src/client-options.test.ts`: the counter counts statements inside transactions and savepoints. - `node --test scripts/scale-ramp/scale-ramp.test.ts` and `tsc -p scripts/scale-ramp/tsconfig.json`: 38 pass, including the fixture contract and the board-token header. - `node server/scripts/typecheck-layers.mjs` and `tsc --noEmit` in `packages/db`: pass. Overhead, measured on a shared, loaded laptop (load average 8 to 20), median with min and max: | Measure | Off | On | | --- | --- | --- | | Logger call per statement (5M calls x 7) | 0.28 ns (0.24 to 0.97) | 3.36 ns (3.32 to 6.16) | | CPU per `select 1` statement, embedded Postgres (3,000 x 10) | 28.7 us (20.3 to 42.4) | 32.3 us (20.7 to 45.5) | | CPU per HTTP request, client and server in one process (2,000 x 6) | 67.0 us (40.4 to 107.4) | 64.2 us (40.9 to 83.3) | | Idle process CPU, 5 s x 3 | 0.01% of a core (0.00 to 2.21) | 0.08% (0.05 to 0.09) | | Record one run event (Date.parse + histogram) | - | 148 ns (135 to 188) | | One snapshot | - | 55 us | The statement and request differences are inside the run-to-run spread. The direct cost is about 3 ns per statement, against about 30 us of CPU per statement. ## Risks - Low risk. Off by default; off, only the statement counter runs, and it costs one increment more than Drizzle's no-op logger. - `mainThreadCpu` assumes Linux USER_HZ of 100 and is null on other platforms. The harness then uses `eventLoopUtilization`. - Run event lateness compares the runner's clock with the server's clock, so clock skew adds to it. Negative values count as zero. - With several processes, each request reaches one process. The harness keeps the highest gauge and sums counter growth per process, but a process it never samples is not seen. - The statement counter does not count BEGIN/COMMIT or raw postgres.js calls. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, in Claude Code with tool use (shell, file edits, local 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 - [ ] 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> |
||
|
|
554e6d415c |
fix(restart-chaos): credit a follow-up only to a run that started a provider turn, and post a missed follow-up after the run ends (#21692)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The restart-chaos harness runs staging-mix waves across server swaps and grades each task for duplicate side effects, extra turns and follow-up delivery > - In one wave, the grader reported two false failures > - Task t005: the grader credited a follow-up to a run that failed before its provider turn. It then counted the run that really served the follow-up as a duplicate completion and an extra turn > - Task t009: the agent finished before the follow-up window opened. The harness never posted the follow-up, but the grader still required the post > - False failures hide real regressions, so the grader must match what the product did > - This pull request credits a follow-up only to a run that started a provider turn, and posts a missed follow-up after the run ends > - The benefit is that both false failures go away, and the t009 case still tests the product: the product must answer the late follow-up ## Linked Issues or Issue Description Refs #21598 **What happened?** In wave `w-20261114T231451-s7110`, two tasks failed on harness defects, not product defects. - t005 (`T:completion_once`, a duplicate side effect and an extra turn): run 76f30f70 was woken for follow-up comment 3f6a9eb9. It failed before any provider turn, so the agent never received the comment. Recovery run fdf1f793 served the comment. It added the FOLLOWUP line and did not post DONE again (DONE comments = 1). The grader credited 76f30f70 with the answer and flagged fdf1f793 as a second completion and an extra turn. - t009 (`T:follow_up_posted`): the follow-up was due at 23:25:19. The harness posts only during a swap overlap (opened 23:28:02.7) or at the 85% point (about 23:29:15). The agent finished at 23:27:56.0, so the harness never posted. The grader still required the post. **Expected behavior** - t005 grades one completer (60bdd4dc) and no extra turn. fdf1f793 is the run that answered the follow-up. - t009 gets its follow-up after the run ends. The grade then requires the product to answer it. **Steps to reproduce** 1. Build wake evidence with three runs: a done run, a run woken by a follow-up comment that has no provider turn, and a recovery run that re-completes. 2. Grade with `gradeStagingMix`, `completedAtAnchor` and `runsAfterDone`. 3. Drive `stagingMixStep` with the t009 timings: the run ends before the overlap and before the 85% point. ## What Changed - `tests/restart-chaos/wake-evidence.ts`: record `providerTurnStarted` for each run. It is true when the run has a `turn.submitted`, `turn.accepted` or `turn.started` run event. - `tests/restart-chaos/follow-up-delivery.ts`: a run with `providerTurnStarted: false` does not receive its comments. The comments carry to the next run that starts a provider turn. That run is the answering run. Add `undeliveredFollowUpRuns`. Evidence without the field keeps the old behavior. - `tests/restart-chaos/staging-mix-retry.ts`: `runsAfterDone` does not list a run that failed before it could deliver a follow-up as an extra turn. - `tests/restart-chaos/staging-mix.ts`: when no run is active after the hold or the 85% point, `stagingMixStep` posts the follow-up after the run ended. It records the post as an after-end follow-up, so `after_end_follow_ups_served` requires an agent reply and the ledger line. The `follow_up_posted` detail says "after the run ended". - `tests/restart-chaos/observer.ts`: a staging-mix task with an unposted follow-up does not finish yet. - Tests and `tests/restart-chaos/README.md`. ## Verification - Red on master, green with the fix: - `a follow-up whose run failed before any provider turn (w-20261114T231451-s7110 t005) > credits the follow-up to the run that served it, with one completer and no extra turn` - `... > lets only the serving run re-complete, and still fails a later recovery run that answers nothing` - `staging-mix board step > posts a follow-up the run finished before as an after-end follow-up the product must answer (w-20261114T231451-s7110 t009)` - `staging-mix board step > does not post an after-end follow-up between runs before the during-run window closes, or while a run is queued` - `TaskObserver > does not finish a staging-mix task whose run ended before its planned follow-up was posted` - Guards that still grade as failures on master and with the fix: - `... t005 > still fails a recovery re-completion when the run that received the follow-up started its provider turn` - `a done the server rejected as incomplete > keeps a run woken by recovery after a real completion as an extra turn and a duplicate completion (G5c t004)` (#21598) - `completion_once truth table: a later completion that answers nothing` - `wake evidence against real PostgreSQL` now checks `providerTurnStarted` false, then true after a `turn.started` event. - `npx vitest run --config tests/restart-chaos/vitest.config.ts --maxWorkers=3`: 71 files, 823 tests pass. - `tsc -p tests/restart-chaos/tsconfig.json --noEmit`: clean. - Not run: a new wave. The wave's database is gone, so the real t005 evidence cannot get `providerTurnStarted` from the new query. The tests use the real t005 and t009 values. ## Risks - Low risk. The change affects only the restart-chaos harness. - A run that failed after `turn.submitted` but before the provider read the input counts as a delivery. This keeps the grader strict: it can report a false duplicate, but it cannot hide a real one. - A staging-mix task with a planned follow-up that cannot be posted now waits until its deadline instead of resting. The grade still reports the post errors. ## Model Used - Anthropic Claude Opus 5.5 (`claude-opus-5-5`), via Claude Code with tool use and code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
45125f7748 |
test(server): stop the accounting identity child from timing out on loaded runners (#21712)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The server CI runs the general test suite in 12 shards on shared runners > - One accounting test fails at random on unrelated pull requests and passes on re-run > - Each failure costs a full re-run of the shard and the `verify` job, and it teaches people to re-run instead of read > - The test spawns two helper processes that load about 1,400 TypeScript modules under a 5 second kill timer > - This pull request makes the helper processes plain `node` processes, so they do not load the server module graph > - The benefit is that the test no longer depends on runner load, and it still uses real exited processes ## Linked Issues or Issue Description **What happened?** `server/src/services/run-cost-accounting.test.ts > run cost accounting work > normal accounting Retry reconstructs an uncommitted legacy receipt after its real controller and child exited` failed in "General tests (server (5/12))" three times on 2026-11-15 (UTC), each with the retry also failing: - PR #21687, head `2172a5b26a`, job 132643921517 - PR #21687, head `6a1d2fb0ef`, job 132650244103 - PR #21678, head `fc0e96f23c`, job 132663296537 Every failure has the same assertion: `AssertionError: {"exitCode":null,"signal":"SIGTERM","timedOut":true,...,"stderrTail":"accounting-identity:program-entered\naccounting-identity:module-imported\n"}: expected null to be +0` In five of the six failed attempts, the child stopped after `module-imported` and before `birth-read`. In one attempt, the child printed its result but the 5 second timer fired before it exited. **Expected behavior** The test passes on a loaded runner. The helper processes are not under test. Only the accounting Retry decision is under test. **Steps to reproduce** 1. Slow each module load in the child by 8 ms with an `--import` hook in `NODE_OPTIONS`. The test passes `NODE_OPTIONS` to the child. This simulates a loaded runner. 2. Run `npx vitest run src/services/run-cost-accounting.test.ts -t "normal accounting Retry"` in `server/`. 3. On `master` the test fails with the same `timedOut: true` assertion as CI. **Root cause** The child ran `node --import tsx/esm -e "await import('controller-process-identity.ts'); await currentProcessStartedAtMs(); ..."`. That import pulls in `@paperclipai/shared` and `@paperclipai/db` source through tsx, which is 737 modules. On Linux, `readProcessStartedAt` also dynamically imports the full runner package shim (`server/src/vendor/paperclip-runner/index.ts`) to call the 30-line `/proc` reader. That adds 652 more modules. tsx transpiles all of them in a cold process under a 5 second `timeoutSec`. On a shared CI runner this crosses 5 seconds. **Production impact** None. In the built server, the runner package is already loaded at boot, and `currentProcessStartedAtMs()` on Linux reads `/proc` once per process and caches the result. The cost exists only in a fresh tsx process that imports source. ## What Changed - The accounting identity helper child is now `node -e` with no tsx loader and no module imports. It installs a `SIGUSR2` handler, prints `ready`, and waits. - When the test sees `ready`, it reads the child start time with the product function `observedProcessStartedAt(pid)` and then sends `SIGUSR2`. The child exits with code 0. - The test builds the recorded `ControllerProcess` (random boot id, child pid, `currentProcessSpaceHash()`, observed start time). These are the same values the child computed for itself before. The child process is still real, has its own process group, and has exited before the Retry checks run. - No retries, skips or timeout changes. The 5 second guard now covers a plain `node` start, which takes about 40 ms. ## Verification - Red on `master` with the slow-load hook: `Tests 1 failed`, `timedOut: true`, the same assertion as CI. - Green with this change and the same hook: `Tests 1 passed`. - Full file without the hook: `npx vitest run src/services/run-cost-accounting.test.ts` passes 34/34. - Helper loop, 30 runs per variant, macOS, 18 cores with 36 busy-loop processes (load average about 56): - old child (macOS path): 29/30 exited in 5 s, p50 2,020 ms, p90 2,234 ms, max 5,172 ms - old child plus the runner import (as on Linux CI): 29/30, p50 3,663 ms, p90 4,411 ms, max 5,023 ms - new child: 30/30, p50 38 ms, p90 43 ms, max 46 ms - The full test under the same stress: 6/6 before and 6/6 after on macOS. macOS uses the `ps` path and does not load the runner package, so this loop does not show the Linux failure. The helper loop and the slow-load repro do show it. - `npx tsc --noEmit -p server/tsconfig.json` passes. - Other tests with the same pattern: `native-controller-source-digest.test.ts` also spawns a tsx child, but with a 60 second timeout. It is not the same cause, so this pull request does not change it. ## Risks - Low risk. Only one test changes. No product code changes. - The test no longer checks that a separate process computes its own identity stamp. That was not the purpose of this test. Other tests cover `currentControllerProcessStamp()`. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude Code with tool use (shell, file edit, GitHub CLI). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
92308f839d |
test(e2e): use the Coordinator task panel, inbox and plan controls in QA journeys (#21701)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The QA Cloud product journeys check real user paths on a hosted test stack > - #19360 (2026-11-05) made the Coordinator workspace standard; its task side panel starts with no tabs, and the header control opens a tab chooser > - The journeys were written for the classic panel, which opened straight on Properties, and for older inbox and plan controls > - On QA the smoke suite passed 8 of 24 journeys; 13 failures trace to these out-of-date journey steps > - This pull request updates the journeys to use the shipped Coordinator controls the way a person does > - The benefit is that the QA journeys test the product again instead of failing on removed controls ## Linked Issues or Issue Description **What happened?** The QA staging smoke suite passed 8 of 24 journeys. 13 failures come from journey steps that target the classic UI: - Task side panel: the journeys click "Show properties" and expect property rows. In Coordinator the click opens a tab chooser ("Open a side panel tab"), and the user picks Properties or Artifacts. The product's own e2e tests (`tests/e2e/artifact-tab-arrival.spec.ts`, `artifact-uploads.spec.ts`, `disconnect-resilience.spec.ts`) and the chat-catalog runtime cases already use the chooser. - Inbox: desktop Coordinator inbox rows show unread state as a bold title and have no per-row "Mark as read" button (`doc/plans/2026-11-06-chat-contacts-pins.md`). The `r` shortcut marks the hovered row read on the Mine view. - Plan: the Coordinator Plan chip is named "Open Plan revision N in task sidebar", not "Open Plan revision N". **Steps to reproduce** 1. Run `pnpm test:e2e:runner -- --target-config <managed local config>` with task-properties, task-edit-lifecycle, task-document-persistence and project-task-context. 2. See 0/4 pass on master; each stops at the tab chooser. **Expected behavior** The journeys reach the same saved-state checks as before through the shipped controls. ## What Changed - New `product-journeys/task-panel.ts` helper: opens the side panel and selects a tab (Properties or Artifacts) from the chooser, an open tab, or the "Open a new tab" button. It waits for the page instead of a single non-waiting visibility check, and does not close an already open panel. - task-properties, task-edit-lifecycle, task-dependency-resume, project-task-context and task-document-persistence (and routine/agent journeys that reuse `openDocumentAuthoring`) use the helper. task-properties reopens the panel after reload before it checks "You". - inbox-triage: when the row has no visible "Mark as read" button, open the Mine view, blur search, hover the row and press `r` (as `tests/e2e/coordinator-inbox-views.spec.ts` does). - Plan journey: `planPreviewLabel()` accepts the optional " in task sidebar" suffix and still requires the exact revision. - No product code changes. An earlier revision of this PR changed "Show properties" to select Properties; it is reverted because the product e2e suite asserts the chooser is the intended design. All saved-state assertions are unchanged: assignment, labels, status, documents, read state and plan revision are still read back through the API, so a broken feature still fails. ## Verification - Real browser journeys on a managed local instance against unmodified master UI: 4/4 pass (task-edit-lifecycle, task-properties, task-document-persistence, project-task-context); 0/4 before. - Inbox fallback checked by hand on a local instance: an unread task on the Mine view became `isUnreadForMe=false` after blur + hover + `r`. - `tests/runner-e2e` unit tests for product-journeys and plan-revision: 47 files, 1240 tests pass. The task-properties contract test now models the chooser and asserts the opener and the Properties option are used before assignment and after reload. New `planPreviewLabel` test covers revision 12 vs 1 and a missing revision. - QA Cloud rerun follows once the QA harness pin moves to a master commit that contains this change. ## Risks - Low risk: test code only. If the chooser changes again, the helper fails visibly at the panel step. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use and code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [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> |
||
|
|
8adf0a463a |
perf(db): build the agent request authentication statements once per client (#21707)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work.
> - One Node process controls every run of a workspace. At 1,000
concurrent agents, main-thread CPU for each database statement is the
scarce resource.
> - A CPU profile of the hosted server shows the cost is per statement:
building SQL text in Drizzle costs about as much as parsing the result
in postgres.js.
> - Every authenticated agent API request (about 0.3 per agent per
second, plus tool calls) runs three fixed statements in
`actorMiddleware`: the agent row, the run authentication projection, and
the responsible user's company memberships. The server built the SQL
text of all three again for every request.
> - A local micro-benchmark shows that building the text is 15 to 40 µs
of CPU per statement for these shapes, and that a reused prepared query
costs the same as a raw driver call. Drizzle's `tracing.ts` wrapper is a
no-op (0.1 µs).
> - This pull request prepares the three statements once per database
client with placeholders, and executes them with the request's values.
The driver receives the same SQL text and parameters as before.
> - The benefit is about 40% less main-thread CPU for each authenticated
agent request in a local benchmark.
## Linked Issues or Issue Description
**What existing behavior does this improve?**
The CPU cost of agent JWT and agent key authentication on every agent
API request.
**Subsystem affected**
Server request authentication (`server/src/middleware/auth.ts`,
`server/src/middleware/agent-run-authentication.ts`).
**Current behavior**
For every agent request, `actorMiddleware` builds three Drizzle queries
from scratch: `agents` by id, the `heartbeat_runs` authentication
projection (with `jsonb_build_object` and two `run_identity_contexts`
subqueries), and the `company_memberships` read with an `exists` on
`auth_users`. Building and preparing them costs 14, 38 and 40 µs of CPU
(median of 7 passes of 5,000 builds).
**Proposed behavior**
Build each statement one time for each database client, with
`sql.placeholder` values. Execute the prepared query with the request's
values. The SQL text, the parameters, and the returned rows stay the
same.
**Reason and benefit**
At 1,000 agents, agent API traffic is several hundred authenticated
requests per second on one main thread. Measured CPU per authenticated
request (local, embedded PostgreSQL, `process.cpuUsage()`, 2,000
requests per pass):
| Run (interleaved) | Before: median (min–max) µs | After: median
(min–max) µs | Load average |
| --- | --- | --- | --- |
| 1 | 436 (363–599) | 200 (183–224) | 10.8 / 10.1 |
| 2 | 489 (430–535) | 312 (212–392) | 11.6 / 13.4 |
| 3 | 461 (442–562) | 281 (247–409) | 13.1 / 12.9 |
| separate | 383 (322–810), 301 (268–476) | 169 (156–439), 193 (174–215)
| 9.5 / 9.0 |
The machine is shared (18 cores), so the spread is wide. Every pair
shows the after run lower. The drop is larger than the build cost alone,
because the request also allocates less (fewer builder objects to
collect).
**Breaking changes**
None. The statements, their parameters and the result shapes do not
change.
**Additional context**
Per-statement cost attribution from the new
`packages/db/scripts/benchmark-statement-cpu.ts` (CPU µs per statement,
median of 5 passes of 2,000, two runs, concurrency 1, load average
20–26):
| Statement | Drizzle builder | Build only (`toSQL`) | Drizzle
`.prepare()` reused | `unsafe(text, params)` | `unsafe(..., {prepare:
true})` |
| --- | --- | --- | --- | --- | --- |
| `issues` parent by id | 105 / 122 | 17 / 18 | 59 / 75 | 57 / 63 | 30 /
33 |
| `issues` full row by id | 277 / 326 | 136 / 153 | 96 / 81 | 97 / 77 |
48 / 33 |
| `company_memberships` by principal | 128 / 103 | 35 / 33 | 71 / 66 |
80 / 63 | 37 / 32 |
| join with an in-list of 10 | 169 / 173 | 57 / 57 | 83 / 88 | 109 / 80
| 42 / 40 |
| update by id | 110 / 106 | 25 / 26 | 75 / 80 | 76 / 73 | 39 / 40 |
| insert `activity_log` | 116 / 125 | 34 / 35 | 65 / 57 | 64 / 55 | 41 /
30 |
Drizzle's no-op tracer (`startActiveSpan`) measured 0.1 µs per call.
## What Changed
- `server/src/services/prepared-statements.ts`: add
`preparedStatement(prepare)`, the single-statement form of the existing
`preparedStatements` helper (one prepared query for each `Db`, held in a
`WeakMap`).
- `server/src/middleware/agent-run-authentication.ts`: split the query
into `agentRunAuthenticationQuery(db, binding)`;
`loadAgentRunAuthentication` executes the query prepared once with
placeholders.
- `server/src/middleware/auth.ts`: add `agentAuthenticationQuery` and
`responsibleUserMembershipsQuery`; the JWT path, the agent key path and
`loadResponsibleUserMemberships` execute their prepared forms.
- `server/src/__tests__/agent-auth-prepared-statements.test.ts` (new):
proves that each prepared statement sends the same SQL text and
parameters and returns strictly equal rows, and that repeated agent
requests do not build the statements again.
- `server/src/__tests__/agent-auth-middleware.test.ts`: the test
double's select chain now supports `.prepare().execute()`.
- `server/src/__tests__/prepared-statements.test.ts`: covers
`preparedStatement`.
- `packages/db/scripts/benchmark-statement-cpu.ts` (new): CPU per
statement for the builder, build only, a reused prepared query, `unsafe`
with and without `prepare: true`, and the no-op tracer. Run with `cd
packages/db && ITERATIONS=2000 PASSES=5 node --import tsx
scripts/benchmark-statement-cpu.ts` (`CONCURRENCY`, `ONLY`, `VARIANTS`
are optional).
- `scripts/benchmark-agent-request-auth-cpu.ts` (new): CPU per
authenticated agent JWT request through `actorMiddleware`. Run with
`pnpm --filter @paperclipai/server exec tsx
../scripts/benchmark-agent-request-auth-cpu.ts`.
Both benchmarks start their own embedded PostgreSQL in a temporary
directory.
## Verification
- Red/green: the "builds the request authentication statements once per
database client" test failed on `origin/master` (`select` called 12
times in 3 requests) and passes with this change.
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/agent-auth-prepared-statements.test.ts
src/__tests__/prepared-statements.test.ts
src/__tests__/agent-auth-middleware.test.ts
src/__tests__/agent-run-authentication.test.ts
src/__tests__/agent-jwt-request-authentication.test.ts
src/__tests__/auth-session-route.test.ts
src/middleware/cloud-tenant-actor.test.ts
src/__tests__/local-agent-process-boundary.test.ts
src/__tests__/liveness.test.ts src/__tests__/inbox-mine-routes.test.ts
src/__tests__/board-bootstrap-routes.test.ts
src/__tests__/agent-auth-identity-transfer.test.ts
src/__tests__/prepared-statements-driver.test.ts
src/services/fresh-continuation-fallback.test.ts`: all pass.
- CPU before and after: the tables above.
## Risks
- Low risk. The prepared query uses Drizzle's own `PgPreparedQuery`, the
same execute path that the builder uses. The test pins the SQL text, the
parameters and the rows against the builder.
- Drizzle's `.prepare(name)` on postgres.js does not send a statement
name to the database (see #21201). With `DATABASE_PREPARED_STATEMENTS`
unset, the driver sends the same unnamed statement as before, so
connection poolers see no change.
- A test double for `Db` must now support `.prepare().execute()` on
these selects. One test double changed.
> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.
## Model Used
- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, in Claude Code with
tool use (shell, file edits, local test and benchmark 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>
canary/v2026.1115.0-canary.3
|
||
|
|
ea8c734cb9 |
fix(chat): park GitHub terminal responses that wait for a newer run or task change (#21705)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - The GitHub chat channel posts one App-owned response comment per
accepted request. The terminal-response sweep
(`terminal-response-work.ts`) finds processed, non-final responses whose
task's latest run has ended, and asks the acknowledgement owner to post
the final text.
> - On paperclip.staging, 1,557 processed `github_response_comment` rows
are not final. None changed in the last 5 minutes, and the oldest dates
from 2026-10-28. The sweep reads all of them again on each company-wide
rebuild (every 30 s per company), with one page read plus three
statements per row. Two of those statements run at about 13/s each in
`pg_stat_statements`.
> - The sweep cannot make progress on these rows. Their task's latest
run ended without owning the request (a later request started it), or
the pause is already shown. Nothing that the decision reads changes
until a new run starts, the task status changes, or the row changes.
> - This pull request records that wait on the row and skips it on broad
rebuilds until one of those inputs changes.
> - The benefit is that an idle backlog costs one page read per rebuild
instead of about three statements per row, and no request loses a path
to settle.
## Linked Issues or Issue Description
No issue exists. This describes the problem with the fields of
`.github/ISSUE_TEMPLATE/bug_report.yml`.
**What happened?**
On paperclip.staging (2026-11-15, about 01:45–02:25Z), two single-row
statements ran at nearly the same rate:
- `select id, run_id, company_id, status, responsible_user_id,
message_id, parent_context_id from run_identity_contexts where id = $1
and run_id = $2 and company_id = $3 and status = $4 limit $5` at
13.37/s.
- `select chat_conversations.issue_id, chat_endpoints.provider from
chat_message_links join chat_conversations … join chat_endpoints … where
chat_message_links.company_id = $3 and comment_id = $4 …` at 13.20/s.
They are `provenanceReads.context` and `provenanceReads.link` in
`run-origin.ts`. The terminal-response sweep reaches them through
`readGitHubResponseRun` for each row it loads.
The backlog of `github_response_comment` actions on staging:
- `processed`, `delivery_id` set, `result.final` not `true`: 1,557 rows
(the terminal sweep's set). None updated in the last 5 minutes. The
oldest `updated_at` is 2026-10-28.
- `result.code` of those rows: null 1,387, `acknowledgement_unconfirmed`
150, `acknowledgement_superseded` 20.
- The acknowledgement set (`received`, or `failed` and retryable) is
empty.
- Other rows: processed and final 6,645, failed and not retryable 265,
cancelled 116.
**Root cause**
`entry()` returns `null` ("nothing to post now") when
`githubResponseExecution` has no body. That happens when the task's
latest run has ended but does not own the request and the task is not
blocked. It also happens when the task is blocked and the row already
shows this pause (`pausedVersion` matches). The page query still selects
these rows, because the latest run has ended (or the task is blocked)
and the row is not final. Nothing records the decision, so each
company-wide rebuild reads every row again: `readGitHubResponseRun` (one
statement) plus `chatRunSourceMessageId` (the context and link reads)
for each row. The codes do not matter. `acknowledgement_unconfirmed` is
a retry code that a later successful acknowledgement keeps, and
`acknowledgement_superseded` marks a request whose shared PR comment has
a newer version. All three groups wait for the same thing: a newer run
that owns the request, or a task status change.
**Expected behavior**
A response that cannot progress costs nothing until the run, the task or
the response changes. A response that can progress settles as before.
**Steps to reproduce**
1. Create a GitHub endpoint and a task with several processed, non-final
response comments (codes null, `acknowledgement_unconfirmed`,
`acknowledgement_superseded`).
2. Give the task a newer ended run whose identity context names a later
request, so the run does not own the older requests.
3. Register the terminal-response sweep and send a company-wide hint
every 30 s.
4. On master, each rebuild reads every row again with about three
statements per row and writes nothing.
**Paperclip version or commit**
master at
|
||
|
|
82b243ab07 |
perf(server): bound dedicated database connections with a fair queue (#21693)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - The server holds long advisory-lock transactions on dedicated
database connections (`withDedicatedDbConnection`): workspace source and
lifecycle locks, the skill cache lock, agent-directory operations,
status cards and others
> - `withDedicatedDbConnection` kept at most 4 idle connections, but it
had no limit on connections in use. A run start can hold two at once,
because the source lock nests the lifecycle lock
> - After a restart or deploy, a burst of run starts can open hundreds
of connections. That can exceed the database's `max_connections` at the
moment recovery needs the database most. The documented per-process
total (`DATABASE_POOL_MAX` + 2) was also wrong
> - This pull request bounds the dedicated connections in use with a
fair queue, keeps nested and in-transaction callers deadlock-free, and
states the real connection budget
> - The benefit is that a restart burst of 200 or 1,000 run starts
completes within the limit (at most 48 in use with the default limit of
24), where before most of the starts failed with "too many clients"
## Linked Issues or Issue Description
**What existing behavior does this improve?**
`withDedicatedDbConnection`, which gives long advisory-lock transactions
a connection outside the main pool.
**Subsystem affected**
Database client (`packages/db/src/client.ts`) and the connection-sizing
documentation.
**Current behavior**
Nothing bounds the dedicated connections in use; only 4 idle ones are
kept. A run start can hold two at once (the source lock nests the
lifecycle lock). A burst of run starts after a restart can open hundreds
of connections and exceed `max_connections`. The documented per-process
total (`DATABASE_POOL_MAX` + 2) is wrong.
**Proposed behavior**
A per-process limit on dedicated connections in use
(`DATABASE_DEDICATED_CONNECTION_MAX`, default 24) with a first-in,
first-out queue. A caller that already holds a dedicated connection, or
runs inside an open transaction, never waits, because its wait could
deadlock with the holder that blocks it. After
`DATABASE_DEDICATED_CONNECTION_WAIT_MS` (default 30 s), a queued caller
gets a connection over the limit, so a lock cycle that PostgreSQL cannot
see ends in a delay, not a hang. The documentation states the real
per-process budget.
**Reason and benefit**
At 50 agents, staging showed about 9 new connections per second from
this function. At 1,000 agents, a restart burst can take the database
down when recovery needs it most. With the default limit of 24, a burst
of 200 or 1,000 starts completes with at most 48 dedicated connections
in use.
**Additional context**
Refs the 1,000-concurrent-agents plan
(`doc/plans/2026-11-13-thousand-concurrent-agents.md`). Reusing the
outer session for a nested lock was considered. The locks are
transaction-level advisory locks (`pg_advisory_xact_lock`), so a nested
lock in the outer transaction would be held until the outer transaction
ends, which changes lock lifetimes and order.
## What Changed
- `packages/db/src/client.ts`: `withDedicatedDbConnection` admits
callers against a per-owner limit (`DATABASE_DEDICATED_CONNECTION_MAX`,
option `dedicatedConnectionMax`, default 24) with a first-in, first-out
queue. The slot is released after the connection is returned or closed.
- Nested callers (an active dedicated hold of the same owner in the
async context) and callers inside an open transaction of a client from
this process are admitted without a wait. The transaction marker is an
`AsyncLocalStorage` scope that ends when the transaction callback ends.
- A queued caller is admitted over the limit after
`DATABASE_DEDICATED_CONNECTION_WAIT_MS` (option
`dedicatedConnectionWaitMs`, default 30000).
- `dedicatedDbConnectionStats(db)` reports the limit, in-use, peak,
waiting, queued, over-limit and nested-over-limit counts.
- `PRIVATE_POOL_MAX_CONNECTIONS` names the private pool sizes that were
literals, and `databaseConnectionBudget()` returns the per-process worst
case: main pool + 9 private + 2 listeners + 2 x limit + 4 idle dedicated
= 73 with the defaults.
- `server/src/services/skill-package-store.ts`: an isolated package read
takes its package I/O permit before its dedicated connection, and takes
a second dedicated connection only for the cache trim after a publish.
Before, each of up to 32 queued readers held a dedicated connection
while it waited for one of 2 permits. `skillPackageStorageIoDepth()`
reports the queue for the store's test.
- `withDedicatedDbConnection(db, action, { admitWithoutWaiting: true })`
admits a caller at once. The skill package store passes it for the
dedicated connections it takes while it holds a package permit, so a
permit holder never waits for a slot that a cache-lock owner holds while
that owner waits for the permit. The overshoot is bounded by the permits
(2 storage, 2 response).
- `doc/DATABASE.md` and `docs/deploy/database.md`: document the
admission rules, the two new variables and the real connection budget,
which replaces "`DATABASE_POOL_MAX` + 2".
## Verification
- New `packages/db/src/dedicated-connection-admission.test.ts` (embedded
PostgreSQL, `max_connections` 100). A restart burst with the default
limit: each start holds a source advisory lock on a dedicated connection
and nests a lifecycle lock on a second one, 40 ms in all.
- Before (same burst, scratch test on master): 200 starts gave 151
failures ("sorry, too many clients already") and 99 dedicated sessions
open. 1,000 starts gave 823 failures and 99 sessions.
- After: 200 starts gave 0 failures, 45 sessions, peak in use 48, queue
wait p50 541 ms / p99 815 ms. 1,000 starts gave 0 failures, 40 sessions,
peak in use 48, wait p50 1,767 ms / p99 3,422 ms. The wait is the queue
of this synthetic burst of 40 ms holds. Before, the same callers waited
about as long for connection setup, and most then failed.
- Steady state: 20 concurrent holders under the limit are never queued
(`queued: 0`).
- Nested acquisition: with a limit of 2, two holders each take a nested
connection while a third caller is queued. All finish (no deadlock); the
queued caller runs after them.
- In-transaction caller: with a limit of 1, a pooled transaction holds a
row lock and then asks for a dedicated connection, while the one
dedicated holder waits for that row lock. The caller is admitted at once
and both finish. A hard limit would deadlock here.
- Resource holder: with a limit of 1, the slot holder waits for a
resource that a second caller holds. The second caller, with
`admitWithoutWaiting`, is admitted at once and both finish.
- Wait bound: with a limit of 1 and a 100 ms bound, a queued caller is
admitted over the limit after the bound.
- Budget: the sum of the actual `max` of every private pool equals
`databaseConnectionBudget().privatePools`, and the default total is 73.
- `skill-package-store.test.ts` ("does not load queued legacy bodies for
files reads"): 32 readers queue for package I/O while only the 2 active
readers hold dedicated connections, and the 33rd reader still gets
"busy" at once. With the old order and a limit of 24, CI showed only 22
readers reaching that queue. `skill-package-store`,
`skill-version-cache`, `company-skills-empty-runtime`,
`runtime-skill-preservation`, `company-skills-runtime-concurrency` and
`company-skills-service` pass locally. Two `company-skills.test.ts`
workspace-discovery tests fail locally on master too (same result with
this change), so they are not caused by it.
- `packages/db`: client, lazy-transaction, prepared-query,
response-capture, work-signal and dedicated-pool suites, 134 passed.
- `server`: skill-version-cache, status-card-evaluation-work,
git-workspace-expiration, execution-workspace-runtime-control-conflict,
agent-instruction-working-copies, company-skills-empty-runtime and
decisions-service suites: 413 passed. In one combined run under machine
load, git-workspace-expiration failed at file level with all its tests
passing; alone it passed 96 of 96.
- `npx tsc --noEmit` in `packages/db`: passes.
## Risks
- A caller that holds an application-level lock (for example a
filesystem lock) and then waits in the queue can block a dedicated
holder that needs that lock. The 30 s wait bound ends such a cycle with
a delay. The over-limit counter shows it.
- Nested and in-transaction callers do not wait, so the in-use count can
reach twice the limit with one level of nesting. The documented budget
counts this.
- In a large restart burst, run starts now queue for a slot instead of
opening new connections. Steady state (about 10 to 20 dedicated
connections at 1,000 runs) stays under the default limit of 24, so a
run's first turn does not wait there.
- The checkpoint pool (3 connections) can limit throughput at 1,000 runs
on a hosted database. This pull request does not change it; it needs an
owner decision on the hosted connection budget.
> 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`), Claude Code agent with tool use
and code execution.
## Checklist
- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [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>
|
||
|
|
9c230ace94 |
fix(heartbeat): settle deferred chat wakes that can never resume instead of retrying every pass (#21678)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - The heartbeat deferred-receipt worker resumes wakes that waited
behind a running task execution
> - A chat message that arrives while its task runs is saved as a
deferred chat wake
> - When the task finishes (done or cancelled) first, the saved wake can
never resume, but the sweep retried it forever and touched `updated_at`
on every pass
> - An idle instance did one write and one failed resume about 4 times a
second, and the log line did not say why
> - This pull request gives each such wake one recorded outcome, and
makes every other failure wait on a stored, spaced, bounded next attempt
> - The benefit is an idle database stays idle, and a person sees the
existing "not started" result instead of silence
## Linked Issues or Issue Description
**What happened?**
The stranded deferred-queue sweep in
`server/src/services/heartbeat/queue.ts` selects
`deferred_issue_execution` chat-inbound wakes. On every pass it runs
`update agent_wakeup_requests set updated_at = now()` for each wake.
Then `resumeDeferredChatWake` fails because the task is done or
cancelled, so the chat authority denies the work start
(`task_assignment`). Nothing records the failure, so the next pass
repeats it.
**Steps to reproduce**
1. Save a chat message on a task while a run is active, so the message
becomes a deferred chat wake.
2. Let the run finish and mark the task done.
3. Leave the instance idle. The log shows "saved chat source could not
resume after recovery" again and again for the same request ids.
**Expected behavior**
A wake that can never resume gets one terminal outcome with a stored
reason. A wake that can resume later waits on a stored time. An idle
instance runs no statements for these wakes.
**Paperclip version or commit**
master at
|
||
|
|
11b09b7234 |
refactor: remove doc/execution-semantics.md and its references (#21699)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Contributors and agents read the docs under `doc/` for background on run execution > - `doc/execution-semantics.md` grew to 6,310 lines of per-PR notes > - It was hard to read and it drifted from the code > - The code and tests are the source of truth for execution behavior > - This pull request removes the file and every reference to it > - The benefit is one less stale document that readers can mistake for a requirement ## Linked Issues or Issue Description **Issue type** Outdated or unclear documentation. **Where is the issue?** `doc/execution-semantics.md`, and the docs, rules, skills, maps, code comments and log text that link to it. **What's wrong?** The file is 6,310 lines of notes added one PR at a time. Much of it repeats or contradicts the code. Readers and agents treat it as a contract, but the code and tests decide the behavior. **Suggested fix** Delete the file. Remove each link to it. Keep the documents that link to it. Point at code where a pointer is still useful. Do not move the content to another doc. Refs #10664 (an open docs PR that edits this file; it becomes obsolete). ## What Changed - Delete `doc/execution-semantics.md`. - Remove links and pointers in `doc/PRODUCT.md`, `doc/LOW-TRUST-PRESETS.md`, `doc/TASK-WATCHDOG.md`, `doc/composer-stop.md`, `doc/native-workspace-finalization-recovery.md`, `doc/run-log-events.md`, `doc/runner-internals.md` and `doc/workspace-repositories.md`. - `doc/TASK-WATCHDOG.md` now points at `server/src/modules/active-run-watchdog/` for the silent active-run watchdog. - Remove the link in `rules/upgrade-safe-run-state.mdc` and `maps/feature-map/recovery.md`. - Update the skills `diagnose-why-work-stopped`, `fix-failed-paperclip-run` and `terminal-bench-loop`. The `fix-failed-paperclip-run` skill now points at `server/src/services/heartbeat/` and `server/src/services/recovery/`. - Remove the file from the source anchors in `.devin/wiki.json`. - Remove the doc name from four code comments in `server/` and `ui/`. - The failed-attachment log message no longer ends with a link to the removed doc. Two tests now check the message text instead of the link. - Leave two dated plan files under `doc/plans/` unchanged. They are history. ## Verification - `git grep -i execution-semantics` finds no hits outside `doc/plans/`. - Every relative Markdown link in the changed files resolves. - `node scripts/check-maps.mjs` passes. - `node --test .github/scripts/tests/*.test.mjs` passes (808 tests). - `pnpm verify` was not run locally. The worktree has no `node_modules`. CI runs the changed Vitest files. ## Risks - Low risk. Most changes are docs and comments. - One runtime log line is shorter. It no longer has a link. No logic changes. - Open PRs that edit the deleted file, such as #10664, will conflict. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use and shell access. ## 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> |
||
|
|
adc3356ad3 |
fix(native): retry a coordinator claim that loses a deadlock instead of failing the run (#21703)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - A native (Paperclip Runner) run claims its `native_run_finalizations` coordinator before it starts any provider work. The claim is one transaction. It locks the coordinator row, then the run row. > - A writer that holds the run row and then waits for the coordinator row closes a lock cycle. PostgreSQL then aborts the claim with a deadlock (`40P01`), because the claim waited first. > - The aborted claim rolls back whole and starts no provider work. But the raw database error failed the run before its first turn. > - The failure path then preserved the prepared workspace. That stamped the unclaimed coordinator `native_continuation_requires_reconciliation`, and `failRun` used it as the run's error code. The task waited for reconciliation. > - A transient database fault must never end a run like this. The target rate of runs that need Retry is 0%. > - This pull request retries the claim transaction on transient lock contention with the shared bounded helper. > - The benefit is that a fresh run that loses a lock race at its claim continues to its provider turn by itself. ## Linked Issues or Issue Description **What happened?** On a hosted QA stack, a fresh native assignment run (not a retry) failed after about 50 s. The run status was `failed`. The error code was `native_continuation_requires_reconciliation`. The error text was `Database query failed (40P01)`. The stderr was empty. The task needed reconciliation. **Steps to reproduce** 1. Prepare a native run with an unclaimed coordinator (`observed`, attempt 0), as runtime selection leaves it. 2. In another transaction, lock the run row. 3. Start the native session. Its claim locks the coordinator and waits for the run row. 4. In the other transaction, lock the coordinator row. 5. PostgreSQL aborts the claim with `40P01`, and `executePaperclipNativeSession` rejects with that error. **Expected behavior** The claim retries after the competing transaction commits. The run reaches its provider turn. **Paperclip version or commit** `master` at |
||
|
|
c38a471042 |
perf(server): download stale agent files before the agent row lock (#21694)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Durable agent files live in object storage. Each server keeps a local copy (the projection), marked with the head generation it matches > - When the projection is stale, the next locked read or write restores it: it downloads every file from object storage. This happens for the first run of each agent on a new server (every deploy on hosted ephemeral servers) and after another server wrote > - The download ran inside the transaction that holds the `agents` row lock (`FOR UPDATE`), on the main pool for the run-start read (`readCommittedForRuntime`) and on the 2-connection file-storage pool for the store. A download can take up to 30 s > - After a deploy at 1,000 agents, this is one long row lock and one pinned connection per agent, all at once, and every writer of that agent waits behind it > - This pull request downloads the files outside the transaction and takes the lock again only to swap them in > - The benefit is that the row lock is held for milliseconds instead of the download time (0 ms observed instead of 321 ms with a 300 ms download in the test), and writers do not wait for a download ## Linked Issues or Issue Description **What existing behavior does this improve?** The restore of a stale local copy of an agent's durable files (the first run of each agent on a new server, or after another server wrote). **Subsystem affected** Server: durable agent files (`agent-file-durability.ts`, `agent-file-store.ts`, `agent-instruction-revisions.ts`). **Current behavior** The restore downloads every file from object storage inside the transaction that holds the `agents` row lock (`FOR UPDATE`) and a pooled connection. A download can take up to 30 s, and every writer of that agent waits behind it. **Proposed behavior** Under the lock, detect that a download is needed and roll back. Download the head's files, verified by digest, into a private staging directory with no lock. Run the transaction again, and swap the staged files in only when the head generation is unchanged. After two changed heads, restore under the lock as before. **Reason and benefit** After a deploy at 1,000 agents, every agent's first run restores at once. The row lock and connection are now held for milliseconds instead of the download time, and writers do not wait for a download. **Additional context** Refs the 1,000-concurrent-agents plan (`doc/plans/2026-11-13-thousand-concurrent-agents.md`). The save path had the same problem for uploads and was fixed earlier with uploads before the lock (`uploadAgentFilesBeforeCommit`); this is the restore side. Reading the head before every transaction was considered; it adds a query to every call, while the deferral costs nothing when the projection is current. ## What Changed - `agent-file-durability.ts`: the download loop moves into `downloadAgentFiles`, unchanged. `withAgentFilesRestoredBeforeLock(work)` runs `work` in a scope. Inside the scope, the first restore of an attempt that needs a download throws a private deferral error, which rolls back the transaction. The wrapper stages the download in `.agent-files-<uuid>` next to the root and runs `work` again. `restoreDurableAgentFiles` uses a staged directory only when its generation equals the head it reads under the lock. Staged directories are removed when the scope ends. - Only the first restore of each attempt can defer, so nested restores of other agents keep their old behavior. Outside the scope, the behavior is unchanged. - `agent-file-store.ts` (`locked`, so every store read, write, apply and working-copy preparation) and `agent-instruction-revisions.ts` (`readCommittedForRuntime`, `readCurrent`, `materializeCurrent`) run their transactions in the scope. ## Verification - New test `server/src/__tests__/agent-file-restore-locking.test.ts` on embedded PostgreSQL, with an object-storage fixture: - Hold time, with a 300 ms download, through `readCommittedForRuntime` (the run-start read). Before: the download ran with the agent row locked, and the row was locked 321 ms of 322 ms. After: the download ran with the row unlocked, and a sampler saw the row locked for 0 ms. - Concurrency: a board write of the same file runs while the reader's download is blocked. Before: the writer waited for the reader's download (5 s timeout). After: the writer commits a new head during the download. The reader then discards its stale staged copy and returns the writer's content. The projection is marked at the writer's generation, and no staging directory is left. - Failure: when object storage fails, the read fails once with the storage error, after one attempt made without the row lock, and leaves no staging directory. - Progress: when the head generation changes during each of two downloads, the third attempt restores under the lock as before (3 downloads), and the projection matches the final head. - `npx vitest run` for agent-file-checkpoint-locking, agent-file-checkpoints, agent-file-durability, agent-file-restore-locking, agent-instruction-revisions, agent-instruction-working-copies, agent-instructions-service, agent-directory-working-copies and agent-instructions-routes: 287 passed, 1 skipped. - `npx tsc --noEmit -p server/tsconfig.json`: passes. ## Risks - A deferred attempt runs the transaction body again. The deferral happens at the first restore, before the body writes files, and the transaction rollback undoes database work, so the second attempt starts from the same state. - A staged download uses disk next to the agent root until the scope ends, the same as the temporary directory of the old download. - If the head changes during every download, the third attempt downloads under the lock as before. > 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`), Claude Code agent with tool use and code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [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> |
||
|
|
cb9fe3f72d |
perf(server): capture a remote agent-file checkpoint before the directory lock (#21690)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - A warm remote run saves its agent files at the end of every turn (`checkpointWarm`) > - On hosted (ephemeral) servers, this save holds the cross-controller `agent-directory` advisory lock in an open transaction on a dedicated database connection > - The lock was held across the full remote capture: an asset upload, the checkpoint script, the download and the scratch cleanup in the sandbox. Each step is a sandbox round trip of hundreds of milliseconds or more > - At 1,000 concurrent agents, connection-seconds are the scarce resource, and this hold occurs on every turn of every warm remote run. The lock is per agent, so a second run of the same agent got "Agent directory operation is already active" for the whole capture > - This pull request captures the remote files before the lock, and takes the lock only to commit > - The benefit is that the lock and its connection are held for the commit only (85 ms instead of 2.5 s in the test with a 200 ms sandbox), and no sandbox call runs under the lock ## Linked Issues or Issue Description **What existing behavior does this improve?** The per-turn save of agent files for a warm remote run (`checkpointWarm`) on hosted servers. **Subsystem affected** Server: agent directory working copies (`server/src/services/agent-directory-working-copies.ts`). **Current behavior** The save holds the per-agent `agent-directory` advisory lock, an open transaction and a dedicated database connection across every sandbox round trip of the remote capture. A second run of the same agent gets "Agent directory operation is already active" for that whole time. **Proposed behavior** Capture the remote files with no lock. Under the lock, use that capture only when the working-copy row is unchanged. Otherwise discard it and capture again under the lock, as before. **Reason and benefit** At 1,000 concurrent agents, connection-seconds are the scarce resource, and this hold occurs on every turn of every warm remote run. The lock is now held for the commit only. **Additional context** Refs the 1,000-concurrent-agents plan (`doc/plans/2026-11-13-thousand-concurrent-agents.md`). A lease row in place of the advisory lock was considered; it is a larger change, and the optimistic capture removes the slow part without a new protocol. ## What Changed - `agent-directory-working-copies.ts`: `checkpointWarm` captures the remote checkpoint before `serial()` for a disposable remote copy (hosted servers only), with the same inputs that the locked capture uses. - Under the lock, `checkpoint()` reuses that capture on its first attempt only when the current row equals the row the capture used (`adoptionAuthority`, which excludes only `updatedAt` and `nextAttemptAt`) and the target is the same. If the row changed, it captures again under the lock, as before. - If the early capture fails, the code logs a warning and captures under the lock, as before. The early capture's scratch is removed after the lock is released. - Local copies and non-hosted servers are unchanged. ## Verification - New test `server/src/__tests__/agent-directory-remote-checkpoint-lock.test.ts` on embedded PostgreSQL, with the real checkpoint transport and a fixture sandbox runner that takes 200 ms per call: - Before: 11 of 11 sandbox calls ran while the `agent-directory` advisory lock was held. The lock was held 2,482 ms of a 2,515 ms checkpoint. - After: 0 of 11 sandbox calls ran under the lock. The lock was held 85 ms of 2,863 ms. - Concurrency: a competing collector (`collectStopped` from a second service instance) runs while the early capture is blocked in the sandbox. Before: the collector failed with "Agent directory operation is already active". After: the collector saves and releases the copy, and the checkpoint discards its early capture and returns the collector's row unchanged. The canonical file has the final turn's content once, and no scratch directory is left. - `npx vitest run src/__tests__/agent-directory-working-copies.test.ts src/__tests__/agent-file-checkpoint-locking.test.ts src/__tests__/heartbeat-agent-directory-busy.test.ts src/__tests__/agent-directory-lock-crash-point.test.ts src/__tests__/agent-instruction-working-copies.test.ts`: 189 passed, 1 skipped. - `npx tsc --noEmit -p server/tsconfig.json`: passes. ## Risks - The capture now runs while another controller can operate on the same copy. The capture only reads the remote directory into private scratch. The commit uses it only when the row is unchanged, so the result is the same as one of the orders the lock allowed before: the checkpoint first, or the other operation first and then the old locked checkpoint. - The agent can change remote files between the capture and the commit. That was also true before, because the agent is not frozen during a checkpoint. - Changed bytes are still uploaded to object storage inside the lock (before the agent row lock). Moving that upload out is a possible follow-up. > 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`), Claude Code agent with tool use and code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [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> |
||
|
|
328a954cc1 |
test(scaling): add a real-agent ramp harness for hosted instances (#21695)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The control plane must run 1,000 agents at once on one workspace (`doc/plans/2026-11-13-thousand-concurrent-agents.md`) > - Above about 50 agents, the evidence is a load model only. Nobody has run 200 or 1,000 real agents > - Phase 3 of the plan proves the finish line with real runs on hosted instances, in a fixed order > - This pull request adds the harness for those runs. It does not run it against any real instance > - The benefit is that each proof step is one command with a written cost estimate, explicit pass/fail criteria, and a guaranteed cleanup ## Linked Issues or Issue Description **What problem does this solve?** The 1,000-agent plan needs real runs at 50, 200, 500 and 1,000 agents. No tool exists that creates real agents and tasks on a hosted instance, ramps concurrency, measures the control plane, and judges the plan's finish line. **Proposed solution** A script under `scripts/` that ramps real agents through the product API, stops at the first failed criterion, writes a machine-readable result, and always cleans up what it created. **Alternatives considered** Extend the restart-chaos hosted mode. That mode grades release swaps at up to 30 concurrent tasks. The ramp reuses its target guard and its cleanup order, but it has a different workload, different measures and a different stop rule. ## What Changed - `scripts/scale-agents-ramp.ts` and `scripts/scale-ramp/`: the harness. It reads the base URL from a flag or the environment and the credentials from the environment only. It creates or reuses a company, then creates agents, tasks, a project and an optional provider secret. It ramps concurrency in steps (default 10, 50, 100, 200, 500, 1,000) and keeps each agent on one small deterministic task at a time. - It measures per step: tasks started, finished, failed and needing Retry; failed runs; peak running agents; queue wait; time to first token and first activity (from sampled run events); run duration; board GET latency. An optional metrics endpoint supplies event-loop, statement and pool figures. A missing source is reported as "not measured", never as zero. - It evaluates the criteria from the plan's finish line plus harness criteria, writes them into `result.json` and `SUMMARY.md`, and stops at the first failure. - Cleanup runs in a `finally`: pause agents, cancel live runs, archive tasks, terminate and delete agents, delete the stored secret, archive the project and the created company, and wait for sandbox leases. `--cleanup-only <run id>` finishes a cleanup after a crash. `--dry-run` prints the plan and the estimate and makes no request. - Target guard: `--target-kind` is required and must match the host. Shared staging and production hosts need a second explicit flag. The script asks for the host name before it starts unless `--yes` is given. A run above the spend threshold needs `--confirm-spend <max USD>`. - `scripts/scale-ramp/scale-ramp.test.ts`: 28 tests against an in-process fake API with a virtual clock. They cover ramp logic, stop on failure, criteria evaluation, cleanup after a mid-run crash and an interrupt, `--cleanup-only` with and without a state file, dry run, the production-host guard, the spend gate, and that credentials never appear in output or files. - `scripts/scale-ramp/tsconfig.json` is added to the test programs that CI typechecks. The test file joins the `test:release-registry` node test list, which CI runs. - `doc/plans/2026-11-13-thousand-concurrent-agents.md`: a Phase 3 runbook with commands, cost, criteria, proof order, target prerequisites and open risks. ## Verification - `node scripts/ci-profile/node-test.mjs scripts/scale-ramp/scale-ramp.test.ts scripts/typecheck-test-programs.test.mjs`: 47 tests pass. - `node node_modules/typescript/bin/tsc -p scripts/scale-ramp/tsconfig.json`: no errors. - `node cli/node_modules/tsx/dist/cli.mjs scripts/scale-agents-ramp.ts --base-url https://scale1.test.paperclip.app --target-kind test-stack --steps 50 --hold-minutes 30 --dry-run` prints the plan, the estimate and the criteria, and makes no request. - The harness was not run against any real instance. That needs the owner's go-ahead. ## Risks - Low risk for the product: the change adds a script, tests and docs only. No server code changes. - A real run creates real agents, tasks and sandboxes and spends money. The guard, the typed confirmation, the spend gate, the task cap and the recorded-spend stop limit this. The runbook lists the open risks. - The cost defaults are assumptions until a first real run records actual spend. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, via Claude Code with tool use (shell, file edits). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] 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> |
||
|
|
d6acbf50e6 |
refactor: cut DATABASE.md to setup and schema-change rules (#21700)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - `AGENTS.md` tells every contributor and agent to read `doc/DATABASE.md` before a schema or migration change > - That file grew to 2,611 lines. About 1,950 of them were notes on the tables of one feature, added one pull request at a time > - The setup steps and the migration rules started at line 792, below those notes > - This pull request cuts `doc/DATABASE.md` to 377 lines: setup, and the rules that apply to every schema change > - The benefit is a guide that a person or an agent can read in full before a schema change ## Linked Issues or Issue Description Refs #21670 (the same cleanup for `doc/DEVELOPING.md`). **Issue type** Outdated or confusing documentation. **Where is the issue?** `doc/DATABASE.md` **What's wrong?** The file was 2,611 lines. It opened with a Better Auth upgrade note and 492 lines on task query performance. The schema change workflow started at line 1367. **Suggested fix** Keep database setup and the general rules in `doc/DATABASE.md`. Remove the notes on individual tables. The schema and its tests describe those. ## What Changed - `doc/DATABASE.md` is now 377 lines. It keeps the three database modes, client tuning, the schema change workflow, migration compatibility, the migration authoring checklist, migration snapshots, the rule for retries after a lost connection, transaction-aware work signals, plugin namespaces, and backups. The wording of the kept text is unchanged. - New `doc/database-client-internals.md` holds the response-size diagnostic, the notes on the postgres.js patch, and the transaction memory note. The text is moved without wording changes. - "Experimental remote workspace snapshots" moved to `doc/workspace-storage.md`, which links to it. - "Execution admission accounting" moved to `server/src/modules/README.md`, which links to it. - Deleted about 1,950 lines of notes on one feature each. No other file linked to them. The deleted sections are: Better Auth 1.7.16 upgrade, Durable native provider backups, Workspace cohort admission proofs, Original local Git sources for archived workspaces, Proactive agent chat messages, Persistent case handoffs, Task query performance, Tool profile reads, Execution identity row locks, Remote workspace row locks, Managed adapter settings, Cloud configuration migration receipt, Cloud runtime identity singleton, Unclaimed Cloud warm standby, Native finalization history and idle sleep, Feedback history and idle sleep, Resource membership tables, Decision training snapshot retention, Decision queues and triage provenance, Native runner persistence, Chat communication snapshots, Telegram private draft identities, Attachment upload provenance, Question-response delivery receipts, Secret storage, Persistent agent conversations, Resource lifecycle events, Legacy controller ownership, Agent file persistence and legacy revisions, Large API response snapshots, Runner API response reservations, Internal agent commentary, Agent identity keys and backups, Slack app registration, Slack manager workspace grants, Installed skill packages, Project repository skill synchronization, Task workspace records, Execution recovery query performance, Agent runtime synchronization journal, Retired Pipelines storage, Prompt injection classification, Deferred conversation requests, GitHub inherited review-wait reads, Sandbox creation ownership, Object-backed run evidence, Cloud runtime configuration singleton, Independent accounting and budget evaluation, Standard workspace and Classic opt-in, Project environment rolling compatibility. - Also deleted from kept sections: the subscription-table note and the issue-reference backfill note in the embedded mode section, the HTTP access log note and the per-endpoint retry notes in the connection loss section, and the notes on migrations `0355`, `0313`, and `0314` in the authoring checklist. - `AGENTS.md` now states what `doc/DATABASE.md` is for. ## Verification - A script built the new files by line range from the old file. It asserts the old line count and the first line of each range. - A link check on every changed Markdown file, and on the four files that link to a `DATABASE.md` anchor, found 0 missing files and 0 missing anchors. - `node scripts/check-maps.mjs` passes. - `node --test .github/scripts/tests/*.test.mjs`: 808 pass, 0 fail. - `pnpm verify` was not run. This worktree has no installed dependencies, and the change has no runtime code. ## Risks - The deleted notes were not all read in full before deletion. The decision was by section: a section about one feature's tables, with no inbound link, was deleted. The text stays in git history. - Two deleted sections describe procedures for an operator: the duplicate-account check before the Better Auth 1.7.16 migration, and the secret storage tables. Restore them into a focused doc if operators still need them. - No runtime behavior changes. ## Model Used - Claude Fable 5.2 (`claude-fable-5-2`), Claude Code desktop, 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 - [x] 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 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>canary/v2026.1115.0-canary.2 |
||
|
|
958eda6f16 |
fix(native): wait for a live outgoing server before resuming its warm session in a deploy overlap (#21697)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - A deploy swaps servers with an overlap. The outgoing server still serves while the incoming server starts new runs. > - A warm agent session stays with the server that ran its last turn. That server closes the session about 1 s after it leaves new run starts to the replacement (#21627). > - A follow-up that started within about 1 s of its predecessor's finish read the session as suspended, while the outgoing server was still closing it. The follow-up did not wait. It started a second Runner with the wrong OpenCode launch files, and the Runner refused the launch. > - The same-run retry then went to the outgoing server, which had already left run starts. The run failed, and a blocked parent showed a Retry during its scheduled resume. > - This pull request makes the follow-up wait for the live outgoing server, rebuilds the admitted launch files on the new Runner, keeps same-run retries on the replacement, and shows the scheduled resume for a blocked parent. > - The benefit is that a follow-up during a deploy overlap finishes without a failed run or a Retry banner. ## Linked Issues or Issue Description Refs #21627 **What happened?** A zero-downtime release-swap test (Gate B, wave B1 on master |
||
|
|
54cde3353b |
perf(recovery): back off assigned-work re-checks that find the same refused state (#21691)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - The assigned-work sweep checks every open task assigned to an agent
(`todo`, `in_progress`, `blocked`). When a task has nothing running,
nothing pending and no one else's move, it claims one automatic
continuation and asks the wake queue to start it.
> - When the wake queue refuses that continuation, the claim is recorded
as "not started" and the task is checked again 90 seconds later. The
per-task spacing (2, 4, 8, then 15 minutes) lets it claim again. The
refusal is not counted toward the hourly cap, so this never ends.
> - Each cycle reads all of the task's facts, writes an activity entry
and saves a skipped wake row. For 10 such tasks this is about 5,000
statements and 50 claims per hour, forever, on an idle server.
> - This pull request stores a fingerprint of the task's facts with each
refused continuation. A later check that finds the same facts waits,
with reads only, on a backoff that doubles to a 6-hour ceiling.
> - The benefit is that a task that cannot progress costs almost nothing
while idle, and any real change on the task is still picked up within
seconds.
## Linked Issues or Issue Description
No issue exists. This describes the problem with the fields of
`.github/ISSUE_TEMPLATE/bug_report.yml`.
**What happened?**
`act` in `server/src/services/recovery/assigned-work-sweep.ts` repairs a
`no_pending_path` or `retry_offered` task with `deps.enqueueWakeup`.
When admission refuses (for example the assignee has `wakeOnDemand:
false`), `act` returns `enqueue_refused` with `retryAt` 90 seconds
later. The next check claims again as soon as `continuationAllowance`
allows: 2, 4, 8, then 15 minutes. Refused claims do not count toward
`CONTINUATION_CAP`, so the task is re-claimed forever. Each claim writes
an `issue.assigned_work_continued` activity entry ("could not start yet.
It will try again shortly."), and each wake attempt saves a skipped wake
row.
Census on a staging-shaped fixture (real PostgreSQL, real report): 60
tasks in review, 10 running, 5 assigned to a paused agent and 10 whose
continuation is refused. Only the 10 refused tasks are violations
(`retry_offered`). Tasks in review are not in the sweep's scope at all,
and a paused assignee is an "agent paused" wait. So on a hosted instance
where most open tasks are in review, only the tasks whose continuation
is refused pay this cost. One claim check costs 102 statements. A
backed-off re-check costs 34 statements and writes nothing.
**Expected behavior**
A re-check that finds the same state as the last refused continuation
stores nothing and backs off. A real change on the task (a run finishes,
a status change, an assignment, a budget or pause change, a new wake)
re-checks it promptly.
**Steps to reproduce**
1. Create 10 tasks in `in_progress`, assigned to an agent with
`runtimeConfig.heartbeat = { enabled: false, wakeOnDemand: false }`,
each with a failed run.
2. Start the issue-state recovery work (it registers the assigned-work
sweep).
3. Leave the instance idle. The sweep claims and is refused about every
2 to 15 minutes per task, forever.
**Paperclip version or commit**
master at
|
||
|
|
f4e025a1cf |
perf(recovery): wait for an assignee that cannot run instead of retrying its continuation every pass (#21687)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - When a run stops and recovery decides to continue the task in a
fresh run, it records a pending continuation. The execution-continuation
worker delivers it with `heartbeat.wakeup`.
> - When the task's assignee cannot take work (paused, terminated,
waiting for hire approval, or an invalid reporting chain), the wake
refuses. The worker recorded only an "attempted at" time and tried again
on the next 15-second pass, forever.
> - Each refused wake also saved a new skipped wake row. An idle server
with one such task did about 13,000 statements and 390 wake attempts
every 2 hours.
> - This pull request makes delivery check the assignee with the same
rule the wake uses. When the assignee cannot run, the continuation waits
on a stored retry time and is re-admitted at once when the assignee can
run again.
> - The benefit is that an idle server does almost no work for these
tasks, and a resumed agent still gets its continuation within seconds.
## Linked Issues or Issue Description
No issue exists. This describes the problem with the fields of
`.github/ISSUE_TEMPLATE/bug_report.yml`.
**What happened?**
`deliverReconciledExecutions`
(`server/src/services/execution-recovery-resolution.ts`) offers each
pending continuation (`continuationDelivery: "pending"`) to
`heartbeat.wakeup`. When the assignee is not invokable, the wake throws
"Agent is not invokable in its current state" and saves a skipped
`agent_wakeup_requests` row. The worker catches the refusal, records
`continuationDeliveryAttemptedAt`, and the continuation schedule
(`executionControlSchedule.continuation`) asks for another pass in 15
seconds because a pending row exists. Nothing ever changes, so the loop
never ends.
Measured on real PostgreSQL with the real coordinator and the real wake,
on a fake clock, for one pending continuation over 2 idle hours:
| Assignee status | Wake attempts (master) | Statements (master) |
| --- | --- | --- |
| paused | 380 | about 12,980 |
| terminated | 376 | about 12,820 |
| pending_approval | 395 | about 13,000 |
An agent in `error` is not affected: it is invokable, and the wake
delivers the continuation on the first pass. Only the statuses and
conditions that make an agent not invokable cause the loop.
**Expected behavior**
A continuation that cannot be delivered because its assignee cannot run
does not try again every pass. It waits for a real event (the agent can
run again) or a spaced backstop time.
**Steps to reproduce**
1. Create a task in `in_progress` assigned to an agent, with a failed
run.
2. Record a pending continuation for that run, as the fresh-continuation
fallback does.
3. Pause, terminate or un-approve the agent.
4. Run the execution-continuation worker. It calls the wake about every
18 seconds and saves a skipped wake row each time.
**Paperclip version or commit**
master at
|
||
|
|
c66530da63 |
fix(server): release settled native run process identity at graceful shutdown (#21689)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - A server process records the local process of each native run in
`heartbeat_runs` (`process_pid`, `process_group_id`,
`process_started_at`, `process_host_hash`)
> - Only a server in the same PID space can prove that such a process
stopped. `proveLocalOwnerGone` does not accept a recorded process group
from another container
> - Each deploy replaces the server process. Settled native runs that
the old server ran keep their process fields, and no later server can
release them. Recovery sweeps had to learn to skip these rows one by one
> - The stopping server is the one process that can check its own PID
space. After its graceful drain, it can see that a settled run's process
exited
> - This pull request adds a graceful-shutdown step that releases the
process identity of those runs, with the same rules that the running
server already uses, in one candidate read and one update
> - The benefit is that a deploy no longer adds stranded process records
for the runs that the stopping server could prove stopped, and a
successor on the same host has nothing to release at startup
## Linked Issues or Issue Description
Refs #21590
**What happened?**
After a graceful shutdown, settled native runs (`failed`, `cancelled`,
`timed_out`, `interrupted`) that the stopping server ran keep
`process_pid` and `process_group_id`. The successor runs in a new
container with a different `process_host_hash`. It cannot prove that the
recorded process stopped, so the rows stay forever. A successor on the
same host releases them at startup with about 10 statements for each
run.
**Expected behavior**
The server that ran the process knows that the process exited. A
graceful shutdown should release these records before the server stops.
An abrupt stop should keep today's behavior.
**Steps to reproduce**
1. Run native work so that some runs settle while the server runs, or
settle during the shutdown drain.
2. Send SIGTERM to the server.
3. Count settled native runs with `process_pid` or `process_group_id`
set: the count does not go down after the deploy.
**Paperclip version or commit**
master at
|
||
|
|
3eabdd6d10 |
perf(server): size run-log uploads and object journal IO from open run logs (#21685)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - One server process controls every run of a workspace, and the target
is 1,000 concurrent agents on one server
> - Each native run writes its run log to object storage. The server
batches a run's log lines and uploads one batch per run each second
> - The server allowed only 4 log uploads and 8 object storage
operations at a time, for the whole process. These numbers were set when
50 agents was a lot
> - At 200 runs, the run logs fell about 8 seconds behind. At 1,000
runs, pending log bytes grow toward the 64 MiB process cap. Past that
cap, run events wait and log appends can fail
> - This pull request sizes the log upload slots and the object storage
operation slots from the number of open run logs, between the old floor
and a ceiling that comes from the storage client's socket budget
> - The benefit is that run logs stay about one flush interval behind at
200 runs, and fall 7.7 seconds behind instead of 44 seconds at 1,000
runs (p50), without more sockets than the storage client allows
## Linked Issues or Issue Description
Refs plan item 1g in
`doc/plans/2026-11-13-thousand-concurrent-agents.md` ("Size the shared
limiters ... from the active run count").
**What existing behavior does this improve?**
The shared run-log upload limiter and the shared object journal
operation limiter.
**Subsystem affected**
Server: object storage run logs (`object-run-log-store.ts`,
`object-byte-journal.ts`) and the S3 storage client.
**Current behavior**
The process allows 4 run-log uploads and 8 object journal operations at
a time, for any number of runs. Each upload is 3 to 4 sequential object
writes. At 200 runs and 50 ms per write, the run logs commit with a p50
delay of 8.0 s, and only 55% of the log lines offered in a 20 s window
commit inside it.
**Proposed behavior**
The upload slots are one per 10 open run logs, at least 4 and at most
21. The operation slots are the upload slots plus 4 for reads, at most
25. That is half of the 50 sockets that the S3 client may open, so
downloads and other storage calls keep the other half. The S3 client now
sets its 50-socket limit explicitly, from the same constant.
**Reason and benefit**
With the change, 200 runs commit their logs at the flush interval (p50
1.1 s), and 1,000 runs commit with a p50 delay of 7.7 s instead of 43.8
s. Fewer pending bytes stay in memory, so the 64 MiB pending cap and its
admission failure are farther away.
**Breaking changes**
None. With 40 or fewer open run logs the limits are the same as before
(4 uploads, 8 operations).
## What Changed
- `server/src/lib/active-run-slots.ts`: a small helper that gives a slot
count from an active run count, clamped between a floor and a ceiling.
- `server/src/storage/s3-client-limits.ts` and `s3-provider.ts`: the S3
client sets `maxSockets` to 50 (the SDK default) from a named constant,
so the budget is explicit.
- `object-byte-journal.ts`: the object operation limit is the upload
slots plus a read reserve of 4, from the number of open run-log writers.
Open writers are counted with `trackObjectJournalWriter()`. When the
limit grows, waiting operations start at once. When it shrinks, running
operations finish and no new ones start until the count is below the
limit.
- `object-byte-journal.ts` also owns the upload limiter
(`acquireObjectJournalUpload`), process-wide, next to the writer count.
When a run log opens, waiting uploads start at once. When run logs
close, running uploads finish and no new upload starts until the running
count is below the new limit.
- `object-run-log-store.ts`: uses the shared upload limiter. A run log
registers when it begins and releases when it is finalized. The waiting
queue stays first in, first out, and each run has at most one upload in
flight, so one run cannot starve another.
- Review fix: the first revision kept the upload limiter per store, so a
run log opened by another store did not wake uploads waiting in this one
(a lost wakeup on growth). The shared limiter fixes it; a new test
covers growth and shrinkage with queued work.
- Tests: limit growth with uploads waiting and shrinkage with uploads
running; helper bounds; the storage socket budget; 200 open runs upload
at least 20 logs at once (4 before); 1,000 open runs stay at the ceiling
and every upload finishes.
## Verification
- `cd server && npx vitest run src/lib/active-run-slots.test.ts
src/services/object-run-log-store.test.ts
src/services/object-byte-journal.test.ts`: all pass.
- Red/green: with the slot count forced back to the fixed floor of 4,
the two new scale tests fail (4 uploads in flight); with the change they
pass.
- Simulation (in-memory object store with 50 ms per write, each run
appends 1.5 KB at 0.7 records/s, the recorded native event rate, 20 s
window, flush every 1 s). Counts are stable on a loaded machine because
the latency is simulated:
| Runs | Build | Peak concurrent writes | Writes/s | Log lines committed
in window / offered | Commit delay p50 / p99 |
| --- | --- | --- | --- | --- | --- |
| 200 | before | 4 | 74 | 1,473 / 2,669 | 8.0 s / 13.5 s |
| 200 | after | 20 | 211 | 2,646 / 2,790 | 1.1 s / 1.3 s |
| 1,000 | before | 4 | 75 | 1,229 / 13,499 | 43.8 s / 62.3 s |
| 1,000 | after | 21 | 392 | 7,789 / 13,667 | 7.7 s / 12.6 s |
## Risks
- More object storage writes per second at high run counts (at 1,000
runs and 50 ms per write, about 390/s instead of about 75/s). This
raises object storage request cost in proportion. The ceiling bounds it.
- The S3 client now states its socket limit. The value is the SDK
default, so behavior does not change.
- The open-writer count is process-wide. A run log that is never
finalized keeps its count, as it already keeps its writer entry. The
ceiling bounds the effect.
## 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>
|
||
|
|
fad8f051ca |
fix(ui): keep a saved task when its plan, run or work-product read answers 404 (#21684)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - #21671 saves the first chat frame of recently opened tasks in the browser's read cache, so a hard load shows the chat before any response. > - It also removes a task's saved data at once when a read of the task or its chat is refused (401, 403 or 404). > - A task without a plan answers 404 on `GET /issues/:id/documents/plan`. That is a normal answer, but a reader that does not catch it records a query error. > - The cache treated that 404 as "the task is gone" and removed the task and its saved chat. On staging, a task without a plan was therefore never saved, so it never opened from the saved chat. > - This pull request revokes on a 404 only for the task record and its comments. 401 and 403 still revoke on every chat read. > - The benefit is that tasks without a plan (most tasks) open from the saved chat as intended. ## Linked Issues or Issue Description **Describe the bug** After #21671, a task without a plan is not kept in the saved read cache. The first chat frame is not shown from the saved cache for that task. **Steps to reproduce** 1. Open a task that has no plan document (for example PAP-4463 on staging). 2. Look at the saved read cache (`paperclip:query-cache:v1:*` in local storage) after the page settles. 3. The task's record and chat are missing. The page shows `GET /api/issues/:id/documents/plan` answering 404. **Expected behavior** A 404 for a missing plan, active run or work products keeps the task. Only a refusal of the task itself (its record or comments, or any 401/403) removes it. **Actual behavior** Any 404 on a saved chat read removes the task and its saved chat from memory and storage. Refs #21671. ## What Changed - `ui/src/lib/persisted-query-cache.ts`: a chat read revokes the task on 401 or 403, or on 404 only for the recent comments. The task record keeps revoking on 401, 403 and 404. - `ui/src/lib/saved-task-chat.test.ts`: a 404 for a missing plan, active run or work products keeps the task and its saved chat. - `doc/ui-internals.md`: the read-cache rules state which 404s revoke. ## Verification - `cd ui && npx vitest run src/lib/saved-task-chat.test.ts`: 24 passed. With the change in `persisted-query-cache.ts` reverted, the 3 new cases fail. The existing 401/403/404 revocation cases on recent comments still pass. - `src/lib/persisted-query-cache.test.ts` and `src/lib/restored-task-chat-bootstrap.test.ts` pass (90 tests across the three files). `pnpm --filter @paperclipai/ui typecheck` passes. - Staging evidence (build `fc9e4cbbb`, PAP-4463): the only 4xx during the load was `GET /api/issues/:id/documents/plan` 404, and the saved record did not hold the task. ## Risks - Low risk. A 404 on a plan, run or work-product read no longer revokes the task. A task that was deleted or made unreadable still answers 404 or 403 on its record and comments, and that removes it. Any 401 or 403 still removes it. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude Code with tool use (shell, file edits, browser automation). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>canary/v2026.1115.0-canary.1 |
||
|
|
28761f9c25 |
perf(workspaces): read a downloaded snapshot archive once, in the encrypt pass (#21683)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Remote agents work in sandboxes, and the server saves each sandbox workspace as an encrypted snapshot in object storage > - One Node main thread on the server controls every run, so per-agent byte work on that thread limits how many agents one server can hold > - The save path read every downloaded archive twice: a main-thread SHA-256 re-hash after the download, then a full read in the off-thread encrypt pass that already computes the same digest > - This pull request removes the main-thread re-hash and checks the encrypt pass's digest and size against the sandbox receipt instead > - The benefit is one full archive read per save instead of two, and no archive hashing on the main thread, with the same integrity guarantee ## Linked Issues or Issue Description Refs the 1,000-concurrent-agents plan in `doc/plans/2026-11-13-thousand-concurrent-agents.md` (Phase 1, "Workspace snapshot" row). **What existing behavior does this improve?** Saving a remote workspace snapshot after a run. **Subsystem affected** Server: remote workspace snapshot save (`remote-workspace-transport.ts`, `remote-workspace-snapshot-storage.ts`, `remote-workspaces.ts`). **Current behavior** `captureSandboxWorkspaceArchive` streams the whole downloaded archive through `createHash` on the main thread to compare it with the sandbox receipt. Then `uploadWorkspaceSnapshot` reads the whole archive again on a worker thread to encrypt it, and computes the same plaintext digest. **Proposed behavior** After the download, the server checks only the file size against the receipt. The encrypt pass compares its plaintext digest and size with the receipt. A mismatch fails with the same `remote_workspace_capture_transfer_mismatch` error before the upload attempt is recorded and before any object is stored. **Reason and benefit** One full read and one SHA-256 of each archive leave the server's main thread (about 0.36 ms of main-thread time per MB on a loaded dev machine; 37 ms for a 100 MB archive, at event-loop utilization 1.0 for that time). ## What Changed - `captureSandboxWorkspaceArchive` no longer re-hashes the downloaded archive. It checks with `lstat` that the download is a file with the receipt's byte size, and fails with `remote_workspace_capture_transfer_mismatch` when it is not. - `uploadWorkspaceSnapshot` accepts an optional `expectedArchive` (`sha256`, `byteSize`). After the encrypt pass, it compares the sealed plaintext digest and size with it. A mismatch throws `remote_workspace_capture_transfer_mismatch` before the attempt enters `metadata.uploads` and before `putFile`. The scratch ciphertext is removed as before. - `saveRemoteWorkspace` passes the sandbox receipt as `expectedArchive` when it captured an archive. - The save-level `verifyMs` timing field is removed, because that step no longer exists. The storage-level `verifyMs` stays. - `doc/run-log-events.md` says that the encrypt step is the only full read and where a mismatch fails. Callers that relied on the early hash keep their behavior: - Unchanged-snapshot reuse (`findUnchangedWorkspaceSnapshot`) compares the sandbox receipt, not the local hash. When it reuses the parent, the local copy is used only to list directories, and `readRemoteWorkspaceArchiveDirectories` verifies the manifest digest. - Reuse of an earlier upload attempt or an already uploaded snapshot does not read the archive. Those objects were verified when they were stored. - The read-only disk-full fallback builds its archive on the server, so its receipt always matches. Its behavior does not change. - The error message and the failure path do not change, so the save failure code, retry and fallback stay the same. ## Verification - Red/green: `remote-workspace-transport.test.ts` "leaves the downloaded archive's single full read to the encrypting upload" counts main-thread read streams of the downloaded archive during capture. On master it is 1 (fails). With this change it is 0 (passes). The encrypt pass is the one remaining read. - New: digest mismatch and size mismatch in `uploadWorkspaceSnapshot` reject with the transfer-mismatch error, do not call `putFile`, and leave the row `pending` with no recorded attempt. A retry with the right receipt saves. - New: an end-to-end `saveRemoteWorkspace` with a transfer that flips one byte (same size) fails with the transfer-mismatch error, stores nothing, keeps the writer and the previous snapshot, and a retry saves and restores the right content. - New: a download whose size differs from the receipt fails in capture. - `cd server && npx vitest run src/services/remote-workspace-snapshot-storage.test.ts src/services/remote-workspace-transport.test.ts src/services/remote-workspaces.integration.test.ts src/services/remote-workspace-transfer-timeout.test.ts src/services/remote-workspace-readonly-capture-budget.test.ts src/services/sandbox-disk-full-fault.test.ts` passes: 6 files, 360 tests. `src/services/remote-workspace-snapshot-reuse.test.ts` passes: 32 tests. - `npx tsc --noEmit -p server/tsconfig.json` passes. ## Risks - Low risk. A same-size corrupt download is now detected in the encrypt pass instead of right after the download. It is still detected before any attempt is recorded or any object is stored. - When the sandbox reports an unchanged workspace, a corrupt local copy no longer fails the save. The save reuses the verified parent snapshot, which matches the sandbox's content. The local copy is used only for its manifest, and the manifest digest is verified. - The save-level `saveTiming.verifyMs` field is gone. No code reads it. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, via 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> |
||
|
|
cf2a4221e3 |
perf(server): skip the per-request stale instance-admin purge when no row exists (#21680)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Cloud-hosted instances authenticate each request through trusted Cloud headers in the actor middleware > - That path deletes stale `instance_admin` rows for the user on every request, static files and live-events upgrades included > - On an idle hosted instance this delete ran about 1.2 times a second, which is a write on an instance-wide table for each request > - Almost always there is no row to delete, so the statement is wasted work and a database round trip > - This pull request finds out if a stale row exists inside the membership read that the request already does, and deletes only when a row exists > - The benefit is one read and no write for each unchanged authenticated request, with the same purge on the very next request when a stale row appears ## Linked Issues or Issue Description **What existing behavior does this improve?** Cloud trusted-header authentication in the actor middleware. **Subsystem affected** Server authentication (`server/src/middleware/auth.ts`). **Current behavior** `resolveCloudTenantActor` in `server/src/middleware/auth.ts` sends `delete from instance_user_roles where user_id = $1 and role = 'instance_admin'` for every trusted-header request. The actor middleware runs before the static UI, so asset requests run it too. Each live-events WebSocket upgrade runs it again through `resolveCloudActor`. The retry wrapper runs it again after a transient connection error. **Proposed behavior** An unchanged request sends no write. A stale `instance_admin` row is still removed on the next request after it appears. **Reason and benefit** Idle hosted instances send about one delete for each request. This costs a round trip and a write statement on the main database for no change. **Breaking changes** None. The resolved actor and the authorization decisions do not change. ## What Changed - The Cloud trusted-header path reads the user's active memberships together with an `exists` check for an `instance_admin` row, in one statement. - The purge runs only when that check finds a row, when the user has no active membership row yet (first request), or when the read fails. - The session path and the Cloud path share one membership filter function, so both still resolve the same access set. - New test `server/src/__tests__/cloud-tenant-actor-statements.test.ts` meters the statements of one authenticated request on the embedded test database. ## Verification - `cd server && npx vitest run src/__tests__/cloud-tenant-actor-statements.test.ts src/middleware/cloud-tenant-actor.test.ts src/__tests__/cloud-tenant-actor-round-trips.test.ts`: 41 passed. - Red/green: with the `origin/master` version of `auth.ts`, the new test fails. An unchanged member request sends 2 statements, and one of them is the delete. With this change it sends 1 read and 0 writes. - The test inserts a stale `instance_admin` row between two requests. The next request deletes it, and the request after that sends no write again. - The test changes the stack role from member to admin and back. The membership role and the experimental-settings access change on the very next request each time. ## Risks - Low risk. The actor that the middleware returns is the same. Authorization decisions do not change. - The purge now runs after the membership read, not before the tenant sync. The sync does not touch `instance_user_roles`, so the order does not matter. The request still waits for the purge before it continues. - A race between the read and a new row insert existed before too (delete, then insert). The next request removes such a row. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use and code execution in Claude Code. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
dcba9628c7 |
perf(recovery): keep a finished task's settled attention settled and halve graph hint fan-out (#21676)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - Issue recovery records "recovery actions" on tasks. A sweep resolves
the active action of a task that is already done or cancelled.
> - On an idle hosted instance, a debug-log run (from #21640) named a
ping-pong. A native worker re-surfaces a board attention for 13 finished
tasks. Recovery resolves it as `source_terminal`. The unique "one active
action" index then lets the worker insert it again, about every 26
seconds per task. That built 45,008 rows since 2026-10-21. Each insert
and each resolve also signals run dispatch and the task's recovery
graph, which wakes both sides again.
> - Separately, every task-graph recovery hint is published twice per
task queue: once as the graph hint and once as a `{companyId, backstop:
true}` twin. That is half of all idle signals, for a backstop that is
time-gated anyway.
> - This pull request breaks the ping-pong from the recovery side and
removes the backstop twin.
> - The benefit is that a finished task's settled attention stays
settled and wakes nothing. Each graph hint costs half the signals.
## Linked Issues or Issue Description
No issue exists. This describes the problem with the fields of
`.github/ISSUE_TEMPLATE/bug_report.yml`.
**What happened?**
With zero runs active, recovery and native workers kept re-creating and
re-resolving the same board attention on 13 done or cancelled tasks. The
rows are `active_run_watchdog`, owner `board`, cause
`native_restart_recovery_blocked`. The loop added about one row per task
every ~26 s and about 2.6 work-signal commits per second.
**Expected behavior**
Once recovery settles a finished task's attention, the same attention
identity is not surfaced again, and settling it wakes nothing that a
finished task cannot use.
**Steps to reproduce**
1. Create a cancelled task.
2. Surface the native "controller process space unverified" attention
for it (same cause and fingerprint each time), then run
`reconcileActiveRecoveryActions`.
3. Repeat step 2. On master each cycle inserts a new active row and
resolves it, and each resolve signals the task queues and run dispatch.
**Paperclip version or commit**
master at
|