Files
PaperClipAI/server/src/modules
DottaandClaude Opus 5.5 426e8a35dc perf(runs): read live runs in a fixed number of statements (#21417)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The board shows the runs that are live now. The sidebar and the
active agents panel read `GET /api/companies/:companyId/live-runs`
> - That route checked read access and built the output-silence summary
one run at a time, with 8 statements per run
> - On a hosted instance this route ran about 6 times per minute with an
average of 2.1 s of server time, and its statements and allocations add
load to a busy main thread
> - This pull request reads the access decisions and the silence state
for all runs of the request in one batch
> - The benefit is a fixed number of statements per request (15 instead
of 8 + 8 per run) and about one quarter of the allocation

## Linked Issues or Issue Description

No public issue exists. This is an enhancement.

**What existing behavior does this improve?**
The live-runs read on the board (`GET
/api/companies/:companyId/live-runs`).

**Subsystem affected**
Server: agent routes, run read authorization, active-run watchdog.

**Current behavior**
For each run, the route calls `canActorReadHeartbeatRun` (task
existence, instance-admin flag, membership, run policy, task privacy)
and `buildRunOutputSilence` (two watchdog decision reads and one
evaluation-task read). The instance-admin and membership reads repeat
the same answer for every run. Measured locally with a statement and
allocation harness:

| Live runs | Statements per request | Allocated per request |
| --- | --- | --- |
| 10 | 88 | 10.0 MB |
| 50 | 408 | 27.9 MB |
| 200 (route returns 50) | 408 | 28.6 MB |

**Proposed behavior**
The route reads every access decision in one batch and every silence
summary in one batch, so the statement count does not grow with the
number of runs.

**Reason and benefit**
Fewer statements and less allocation on a route that the board calls
often.

**Breaking changes**
None. The response is the same.

## What Changed

- `server/src/routes/agents.ts`: the live-runs handler decides reads
with the existing `getHeartbeatRunReadDecisions` (the run history list
already uses it) and builds silence summaries with one
`buildRunOutputSilences` call for the readable runs. Unreadable runs are
still redacted with `redactHeartbeatRunListRow`, and no silence state is
read for them.
- Active-run watchdog Postgres adapter: new `findLatestDecisions` and
`findOpenStaleRunEvaluations` read all runs of one company in one
statement each (`DISTINCT ON`). The single-run `findLatestDecision` and
`findOpenStaleRunEvaluation` now call the batch with one run, so both
paths use the same query.
- Watchdog application: new `createBuildRunOutputSilences` use case
groups runs by company. `createBuildRunOutputSilence` now calls it with
one run, so the single and batch summaries use one rule.
- `recoveryService` and `heartbeatService` expose
`buildRunOutputSilences` as pass-throughs.
- Tests: new `live-runs-batched-reads.test.ts`; updated watchdog
use-case tests and the live-run route unit test.

## Verification

- `cd server && npx vitest run
src/__tests__/live-runs-batched-reads.test.ts` (embedded Postgres):
- The batched read decision equals one `canActorReadHeartbeatRun` call
per run for 24 actor kinds (owner, admin, operator, viewer, member,
board key, cloud tenant, instance admin, local implicit board, board
without membership, agent keys, agent runs on behalf of users, low-trust
agents, agent of another company, unauthenticated). The runs mix open
tasks, private tasks readable by grant, creation or assignment, private
tasks nobody may read, private-project tasks, a hidden task,
company-scoped runs, a run whose task was deleted, runs of another
company, and runs of another company asked for as this company's.
- For every actor that passes the company gate, each live-runs row is
either the full row or exactly `redactHeartbeatRunListRow` of it (field
by field), as one check per run decides.
- Output silence per run equals the single-run reader for: no output
yet, active snooze plus a later continue, expired snooze, dismissed
false positive, recent output, open evaluation task, done evaluation
task, queued run, an evaluation task of another company, and a run that
has no rows at all.
- The statement count is the same with 19 and 49 live runs for 6 actor
kinds. Before the fix this test fails (for example 347 against 107
statements).
- `npx vitest run src/modules/active-run-watchdog
src/__tests__/heartbeat-active-run-output-watchdog.test.ts
src/__tests__/agent-live-run-routes.test.ts
src/__tests__/heartbeat-run-privacy-routes.test.ts`: pass.
- `npx tsc --noEmit -p server/tsconfig.json` and a test-tree typecheck
of the changed tests: pass. `pnpm check:module-boundaries`: pass.
- After the fix, measured with the same harness (embedded Postgres, 400
tasks, 40 agents, 5 requests each):

| Live runs | Statements per request | Allocated per request |
| --- | --- | --- |
| 10 | 15 | 6.4 MB |
| 50 | 15 | 7.3 MB |
| 200 (route returns 50) | 15 | 7.8 MB |

## Risks

- This changes an authorization read path. The route now uses the batch
helper that the run history list and the live events socket already use.
The test compares it with the per-run check for every actor kind in the
visibility fixture.
- If several open evaluation tasks point at the same run, the batch
picks one of them. The single-run read also picked an unordered one
before.
- No schema, migration, locking or transaction change.

## 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>
2026-11-13 11:10:30 -06:00
..

Feature modules

A feature module under server/src/modules/<name>/ uses three layers. Each layer has one rule: which layer below it, it may import from.

adapters  →  application  →  domain
  • domain/ holds pure business rules. A domain file takes plain data in and returns plain data out. A domain file must not import drizzle-orm, @paperclipai/db, a service under server/src/services/, a route under server/src/routes/, or a Node.js I/O module (node:child_process, node:fs, node:net). A domain function must not read the system clock; the caller passes now as an explicit Date value.
  • application/ holds use cases and the ports they need. A use case takes its ports as constructor arguments and calls domain functions for policy decisions. An application file must not import drizzle-orm, a SQL client, a concrete adapter, or the server's HTTP error helpers. The outer service or route translates application errors into transport responses.
  • adapters/ holds the concrete implementations of the ports: Postgres queries, transactions, and process control. An adapter file may import drizzle-orm, @paperclipai/db, and Node.js I/O modules.

A module exposes its commands through index.ts, which composes the adapters and the use cases behind a factory function. Code outside the module imports that entry point, never a file inside domain/, application/, or adapters/ directly.

pnpm check:module-boundaries enforces these rules for production source files. It also checks access to the company deletion entry point below.

Company deletion

The existing company deletion service owns the database transaction and deletion order. A module can expose a separate company-deletion.ts entry point. Only services/company-deletion.ts can import this entry point. The entry point exports an implementation of CompanyDeletionParticipant from lib/company-deletion.ts. Do not export it through the normal module index.

The service must complete external cleanup before it starts the transaction. It must lock the company before it deletes dependent records or calls a module. Creation commands must use the same company lock. The service removes dependent records before it calls the module. The module checks its deletion conditions and deletes the records it owns. Use the supplied transaction. Do not start another transaction or call external systems. Throw an error if deletion cannot proceed. An error must roll back all database changes in the deletion transaction.

Call each module explicitly in dependency order. No module registry is required.

The agent lifecycle module also has a restricted configuration.ts entry point. It saves configuration and invalidates verification in the caller's transaction. The lifecycle guide lists its permitted callers. Ordinary configuration updates use the root lifecycle command.

The agent lifecycle module owns agent creation, pause, resume, and termination. Use its commands for these changes.

The execution admission module owns project task-execution policy and the durable admission records that charge project capacity. Today it exposes only internal policy commands and the deletion guards that project, agent, and company deletion call. Settlement releases active charges but keeps each admission's complete project set for later retained-session resolution. Execution claims still belong to services/heartbeat/queue.ts and native review dispatch. See execution admission accounting.