Files
PaperClipAI/server/src/__tests__/instance-settings-routes.test.ts
T
Nicky LeachandClaude Opus 5.5 11ac90e31f fix(build): typecheck server/src/__tests__ and fix every type error (#18739)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The server has about 1,100 test and helper files in
`server/src/__tests__`
> - `server/tsconfig.json` excludes that directory, Vitest does not
check types, and no script runs the tsconfig in that directory
> - So a test can call a function with the wrong arguments and still
pass, and no tool reports it
> - This gap hid 2,168 real type errors, and some of them hid tests that
did not test what they claim
> - This pull request fixes all of these errors and adds the directory
to the server layers from paperclipai/paperclip#18737
> - The benefit is that a type error in a server test now fails the
typecheck, with no baseline and no backlog

## Linked Issues or Issue Description

Refs paperclipai/paperclip#18737, which is merged and added the server
layers. Refs paperclipai/paperclip#18738, which is merged and checks the
test projects outside `pnpm -r`, so it is not a duplicate. Refs
paperclipai/paperclip#18137, which records that this directory has no
check.

**What happened?**

No tool checked the types of 1,074 of the 1,101 files in
`server/src/__tests__`. I searched `package.json`, the workflows, and
all tsconfig files. 27 files are in the program of another tsconfig, and
these 27 have 0 errors. 11 of the 27 are in
`helpers/maintenance/tsconfig.json`. No script ran that project when I
measured this. paperclipai/paperclip#18738 now runs it.

**Expected behavior**

The server typecheck checks these files, and a type error fails the
check.

**Steps to reproduce**

1. On the base commit, run `tsc -p server/src/__tests__/tsconfig.json
--noEmit`. It reports 6,536 errors and needs 12.3 GiB.
2. Add a type error to any file in `server/src/__tests__`.
3. Run `pnpm --filter @paperclipai/server typecheck`. It passes.

**Paperclip version or commit**

I measured the error breakdown below on commit `8dfd632452`, with
TypeScript 7.0.2. The branch now includes master up to
paperclipai/paperclip#18865.

**Deployment mode**

Not applicable. This issue applies to development and CI. No production
source file in the server changes.

### Error breakdown

Each row adds one change to the row above.

| Step | Total errors | Change | Cause |
| --- | --- | --- | --- |
| Config as committed | 6,536 | | |
| Add `src/types/*.d.ts` | 4,447 | -2,089 | Config. The Express request
types were missing. |
| Set `rootDir` to the repository root | 2,436 | -2,011 | Config. |
| Set `allowImportingTsExtensions` | 2,181 | -255 | Config. Vitest
accepts `.ts` imports. |
| Add `ES2024.Promise` to `lib` | 2,138 | -43 | Config. Node 24 has
`Promise.withResolvers`. |
| Set `allowJs` for `.mjs` imports | 2,148 | +10 | Config. It removes 8
`TS7016` errors and shows new real errors. |
| Set `declaration` to false | 2,142 | -6 | Config. Tests emit nothing.
|
| Count only files in `server/src` | 2,058 | -84 | Other packages: 53
Daytona, 29 Runner test, 2 UI. |

So 4,478 of the 6,536 errors (69%) came from config or scope, and 2,058
are real type errors in 314 files. The 29 Runner test errors are also
real, which gives 2,087 errors. Tests that master added after this
measurement had 81 more errors, so this pull request fixes 2,168 errors.

This table classifies the first 2,058 errors.

| Kind of real error | Errors |
| --- | --- |
| Wrong argument or assignment type | 1,023 |
| Stale or partial fixture objects | 525 |
| Property that the type does not have | 317 |
| Missing narrowing of null or unknown | 101 |
| Implicit any | 60 |
| Missing name or module | 16 |
| Other | 16 |

### What the type errors hid

Most errors were stale fixtures and loose mocks. These errors hid real
test problems, and this pull request fixes them:

- **A test that never ran.** `instrumentation.test.ts` required
`sdk-trace-base`, which is not installed. So 3 span tests were skipped.
They now run and pass.
- **Assertions that could not fail.**
- `issue-thread-interactions-service` used a company ID as an issue ID.
- `status-card-evaluation-work` compared `[]` with `[]` in a rollback
check.
- `slack-conversation-lifecycle` read `item.issueId`, which does not
exist.
  - `email-channels` used a permission key that does not exist.
- `heartbeat-project-env` imported `LOW_TRUST_REVIEW_PRESET`, which is
not exported. The value was undefined.
- **Postgres processes that did not stop.** 11 test files called `stop`
on the test database helper. That method does not exist, and the helper
method is `cleanup`.
- **Arguments that the service ignored.**
- `methodKey` is now `connectionMethodKey` in the Daytona, Unikraft,
1Password, and Railway tests.
- 108 calls passed `"owner-user"` to a parameter that expects an options
object.
- 9 chat wizard fixtures passed `managementContext` as `source`, so they
ran `existing_app` and not `manifest`.
  - 2 tests passed a `{ userId }` actor that the function ignores.
- Inserts into `environments` passed a `companyId` column that the table
does not have.
- **Problems in tests that master added during this work.**
- `sandbox-creation-operations` read `database.connectionString` when an
external test database was set. In that mode `database` is undefined, so
the fixture would stop with a TypeError. It now uses the external URL.
- `idle-completed-history` set a Dot operation to `dispatched`. That is
a Muse status, and the Dot type does not have it. The fixture now uses
`admitted`, which is a real in-flight Dot status.

### Possible product problems, not changed

These may be real problems in production code or types. I did not change
them, because this pull request does not change production behavior:

- `decisions-service` `service.create` does not validate the lenient
`cancel_issue_tree` input.
- `createConnection` ignores `input.connectionPurpose`.
- The `createConnection` route schema default stores `{}` for
`transportConfig`.
- `prepareManagedAiRuntime` accepted the invalid value `mode:
"connection"`.
- `createBinding` accepts invalid `projectionClass` strings outside
class 3.
- `ensureManagedProjectWorkspace` forwards an untyped `repoRef` by
spread.
- `routineVariableSchema.label` is optional, but `RoutineVariable.label`
is required.
- `ToolRunContext.projectId` may be too strict.
- `withdrawInteraction` reads `issue.status`, which its type omits.
- `issueService.list` and `reconcileNativeFinalizations` omit fields
that they return at runtime.
- `createGitHubExternalObjectProvider` handles `tokenProvider: null`,
but its type forbids this value.

## What Changed

- Fixed the 2,168 type errors. The diff changes 322 test and helper
files.
- Corrected `server/src/__tests__/tsconfig.json`. Editors and the
typecheck now read the same options and report the same errors.
- Added three `test-tree` layers to
`server/scripts/typecheck-layers.mjs`. They read the server layers as
declarations, and any error fails them. A hash of the path selects the
shard, so a new file does not move other files.
- Added `server/scripts/typecheck-stubs/daytona-sdk.d.ts`. Server tests
reach Daytona plugin source, and the root install does not have
`@daytonaio/sdk`.
- Changed two imports in `ui/src/lib/issue-execution-policy.ts` to use
`.js` extensions, because server tests import this file.
- Made `declarationsConfig` and `--declarations-only` skip the
`test-tree` layers, because these layers emit nothing. Other projects
read only the source layers. Added a test for this.
- Updated `doc/DEVELOPING.md`.

## Verification

Run these commands:

```sh
pnpm --filter @paperclipai/server typecheck
pnpm exec vitest run server/scripts/typecheck-layers.test.mjs
```

Results on macOS (arm64), Node 24, 16 cores. Each check ran after the
merge of paperclipai/paperclip#18738 unless the row says otherwise:

| Check | Commit | Result |
| --- | --- | --- |
| Server typecheck, `PAPERCLIP_TYPECHECK_LOW_MEMORY=1`, all 7 layers |
`6e45a08573` | Exit 0, 0 errors, 62 seconds, peak 3.52 GiB |
| `node scripts/typecheck-test-projects.mjs --low-memory` | `a3306bd13e`
| Exit 0, 0 errors, 42 seconds, peak 3.25 GiB |
| The same script with `--reuse-declarations` | `1b878aabc0` | Exit 0, 0
errors |
| `typecheck-layers.test.mjs` and `live-recovery-work.test.ts` |
`01db5634e4` | 90 passed. These include real compiler runs for a pass, a
type error, and an invalid tsconfig. |
| `tsconfig.declarations.json` after a full server typecheck |
`0fb1e4fb0a` | It references only `below`, `cycle`, and `above`. No
generated config names a `tsconfig.layers.json` file. |
| Owned runtime test in `idle-completed-history` | `e8f2f448ac` |
Passed, with the fix that master later replaced |
| `idle-incoming-wake`, `plugin-idle-manager`, and the changed
`chat-channels` test | `6e45a08573` | 30 passed |
| Runner `native-execution.test.ts` | `eab4dcc1f4` | 114 passed |
| The 19 server test files that changed since `eab4dcc1f4`, and
`typecheck-layers.test.mjs` | `259737b700` | 4,275 of 4,277 passed. The
2 failures are in `chat-channels` and are in the list of 7 below. |

The peak is the largest single process, from `/usr/bin/time -l`. Peaks
for the server typecheck were between 3.42 GiB and 3.56 GiB across 8
runs. Peaks for the test projects were 3.25 GiB and 3.37 GiB across 2
runs. I did not measure a cgroup.

**Runtime check of the fixes.** Types do not prove that a test still
works. So I ran all 309 changed server test files, 11,929 tests, before
the rebase onto paperclipai/paperclip#18737:

| Result | Tests | Detail |
| --- | --- | --- |
| Passed | 11,913 | Includes the 2 tests and the 54 `dot-runner` tests
that passed in a later run, as described below. |
| Failed | 7 | The same 7 tests also fail on the commit before the
fixes. |
| Skipped | 9 | These tests have their own skip conditions: `sentry` 5,
and 1 each in `bundled-plugin-registration`, `customer-success-cloud`,
`onepassword-connection`, and `workspace-runtime-https-live-exercise`. |

The 7 tests that fail with and without this change, on my machine:

- 3 tests in `chat-channels` and `email-channels` stop with `ENOENT` on
a `SKILL.md` file. The path is in the parent checkout, above the git
worktree that I used, so I expect that the worktree is the cause. I did
not prove this.
- `workspace-instance-cleanup` compares `/private/var/...` with
`/var/...`. This is a macOS symlink difference.
- 2 tests in `git-reproducible-managed-checkouts` get
`unknown_base_git_files` and expect `unpushed_managed_checkout`. I did
not find the cause.
- 1 more test in `chat-channels`, `materializes direct external-chat
finals once`, gets `undefined`. I did not find the cause.

CI is the check for these 7 tests. `ci / verify` passed on `eab4dcc1f4`.

Failures during this work:

- My fix to `agent-runtime-connector-access` changed an invalid
permission key in the setup, but not in the assertion. The runtime check
found this. I corrected the assertion, and the file passes.
- `heartbeat-plugin-environment` failed one wait in the full run. It
passed three times alone, so I think that load caused the failure. It
can fail again under load.
- `dot-runner` skipped all 54 tests in the full run because `cargo` was
not on my `PATH`. It then passed 54 of 54 with the toolchain on the
`PATH`.
- My first `lib` value removed the default DOM types, and the error
count went up by 375. I added the DOM libraries.
- My Daytona stub with bare `any` left 48 errors, because generic
helpers then inferred `unknown`. I added shapes that return promises.
- One fix to `agent-secrets-routes` used `class_3_static_lease`, and the
test failed. That class allows only specific paths. I reverted to
`unclassified`.
- `ci / General tests (server (8/12))` failed on `259737b700` because of
the flaky port in `idle-completed-history`. paperclipai/paperclip#18853
fixed this test on master, so this pull request keeps that fix.

**Audit of the diff.** I counted these patterns in added and removed
lines, to find fixes that only hide an error:

| Pattern | Added | Removed |
| --- | --- | --- |
| `@ts-ignore` | 0 | 0 |
| `@ts-expect-error` | 0 | 1 |
| `.skip` | 0 | 0 |
| `as any` | 9 | 9 |
| `: any` | 11 | 2 |
| `as never` | 8 | 2 |
| `as unknown as` | 35 | 4 |
| `Promise<unknown>` | 16 | 5 |
| `expect(` | 128 | 113 |

No hunk removes more `expect(` calls than it adds. Three removals of
test content were intentional, and I checked each one:

- `muse-control` removed `signalToken`. Line 1012 already asserts that
it is absent.
- `merged-pr-confirmation-sweep` removed legacy aliases. Other tests
cover them.
- `heartbeat-workspace-branch-containment` removed a `finalize` branch
that no test row can reach.

Some partial fixtures stay unchecked through `as unknown as` and
`Promise<unknown>`, mostly in `issue-agent-mutation-ownership-routes`
and `issue-comment-reopen-routes`.

**Accuracy of the check.** One program over the tree and the three
shards reported the same errors at the same positions. Memory, as the
peak of the largest process on one thread, was 3.93 GiB for one program
and 2.43 GiB for the largest shard. I measured these two values before
the fixes.

Not run or not proven:

- I did not run the full `pnpm test:run`, or a root `pnpm build`. I
expect CI to run the full suites.
- I did not run the 4 GiB container check, or the full
`scripts/typecheck-low-memory.mjs`. The peaks above come from macOS, so
they are not a Linux cgroup measurement.
- I did not run the UI typecheck after the merges.
- `workspace-runtime-https-live-exercise` is skipped, so its `cleanup`
fix did not run.

## Risks

- **A large diff in test files.** 328 files change. A pull request that
edits the same tests can get merge conflicts. New tests on master can
also add type errors before this merges. Any such error fails this check
and needs a fix here.
- **A higher cost for changes to source types.** A change to a type can
add errors in test files that the author did not touch. The author must
then fix them. This is the purpose of the check, but it is new work.
- **Changed test behavior.** Some tests now run paths that they did not
run before, such as the 9 chat wizard fixtures and the 3 span tests.
They pass here, but they can be more sensitive to timing or to the
environment.
- **The Daytona stub can go stale.** The stub is written by hand. If the
plugin uses a new SDK member, the typecheck reports an error until
someone updates the stub.
- **The release path.** `release-verify.yml` and `scripts/release.sh`
run `pnpm -r typecheck`, so they now run this check.
- **The tsconfig change.** The test transform reads
`server/src/__tests__/tsconfig.json`. The options that I changed are for
type checks, and the runs above passed.
- **A gap that remains.** Tsconfigs in `packages/paperclip-runner` and
in most sandbox provider plugins exclude `*.test.ts`. This check does
not read most of those test files, so they can still drift. That work is
separate from this pull request.

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

## Model Used

Anthropic Claude Opus 5.5 (`claude-opus-5-5`) through Claude Code, with
reasoning, tool use, code execution, and subagents. The runtime does not
show the context window size.

## Checklist

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

1871 lines
83 KiB
TypeScript

import { generateKeyPairSync, randomUUID, sign } from "node:crypto";
import express from "express";
import request from "supertest";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { hoistModuleGraph } from "./helpers/hoist-module-graph.js";
import type { PluginWorkerManager } from "../services/plugin-worker-manager.js";
const mockInstanceSettingsService = vi.hoisted(() => ({
get: vi.fn(),
getGeneral: vi.fn(),
getExperimental: vi.fn(),
update: vi.fn(),
updateGeneral: vi.fn(),
updateExperimental: vi.fn(),
listCompanyIds: vi.fn(),
}));
const mockHeartbeatService = vi.hoisted(() => ({
computeTaskDrain: vi.fn(),
applyTaskDrain: vi.fn(),
stopTaskDrain: vi.fn(),
getTaskDrainStatus: vi.fn(),
readUpgradeReadiness: vi.fn(),
resumeQueuedRunsAfterDrain: vi.fn(),
}));
const mockEnvironmentService = vi.hoisted(() => ({
getById: vi.fn(),
findManagedSandboxEnvironment: vi.fn(),
update: vi.fn(),
}));
const mockCompanyService = vi.hoisted(() => ({
getById: vi.fn(),
update: vi.fn(),
}));
const mockLogActivity = vi.hoisted(() => vi.fn());
const mockPublishActivity = vi.hoisted(() => vi.fn());
const mockReadIdleSleepSafety = vi.hoisted(() => vi.fn());
function registerModuleMocks() {
vi.doMock("../services/idle-sleep-safety.js", () => ({ readIdleSleepSafety: mockReadIdleSleepSafety }));
vi.doMock("../services/index.js", () => ({
companyService: () => mockCompanyService,
heartbeatService: () => mockHeartbeatService,
instanceSettingsService: () => mockInstanceSettingsService,
logActivity: mockLogActivity,
publishActivity: mockPublishActivity,
}));
vi.doMock("../services/environments.js", () => ({
environmentService: () => mockEnvironmentService,
}));
}
// Identity object the mocked db.transaction hands to writers; tests assert
// both the marker clear and the settings update receive THIS same tx.
const TX_SENTINEL = { __tx: true };
// Runs the callback with a sentinel tx and propagates throws, so a failing
// write inside rejects the whole request exactly like a real transaction
// rollback. This is the default mockDb.transaction implementation; a test
// that installs its own mockImplementation loses this default, so
// beforeEach below reinstalls it before every test.
function defaultTransactionImplementation(fn: (tx: unknown) => Promise<unknown>) {
return fn(TX_SENTINEL);
}
// Module-scoped (not rebuilt per createApp call) so a test can assert how
// many times a request opened a transaction — the task-drain audit writes
// for every company must share ONE transaction, not one each.
// Rows the lifecycle read-back's plain `db.select().from(companies)` sees;
// tests assign per case.
let mockCompanyRows: Array<{ id: string; status: string }> = [];
const mockDb = {
transaction: vi.fn(defaultTransactionImplementation),
select: vi.fn(() => ({ from: () => Promise.resolve(mockCompanyRows) })),
};
function localAdminActor() {
return {
type: "board",
userId: "local-board",
source: "local_implicit",
isInstanceAdmin: true,
};
}
describe("instance settings routes", () => {
const routeModules = hoistModuleGraph(registerModuleMocks, async () => {
const [{ errorHandler }, { instanceSettingsRoutes }, { cloudControlMiddleware }, controlIdentity] = await Promise.all([
vi.importActual<typeof import("../middleware/index.js")>("../middleware/index.js"),
vi.importActual<typeof import("../routes/instance-settings.js")>("../routes/instance-settings.js"),
vi.importActual<typeof import("../middleware/cloud-control.js")>("../middleware/cloud-control.js"),
vi.importActual<typeof import("../services/cloud-runtime-identity.js")>("../services/cloud-runtime-identity.js"),
]);
return { errorHandler, instanceSettingsRoutes, cloudControlMiddleware, controlIdentity };
});
function createApp(actor: any, pluginWorkers?: PluginWorkerManager, prepareBackup?: () => Promise<boolean>, verifyControl = false) {
const { errorHandler, instanceSettingsRoutes, cloudControlMiddleware } = routeModules.value;
const app = express();
app.use(express.json());
app.use((req, _res, next) => {
req.actor = actor;
next();
});
if (verifyControl) app.use(cloudControlMiddleware());
app.use("/api", instanceSettingsRoutes(mockDb as any, pluginWorkers, prepareBackup));
app.use(errorHandler);
return app;
}
beforeEach(() => {
vi.clearAllMocks();
mockReadIdleSleepSafety.mockReset();
// vi.clearAllMocks() clears recorded calls only; it does not remove a
// mockImplementation a prior test installed. Reinstall the default here
// so a stateful implementation from one test can never leak into the
// next one.
mockDb.transaction.mockReset();
mockDb.transaction.mockImplementation(defaultTransactionImplementation);
mockInstanceSettingsService.get.mockReset();
mockInstanceSettingsService.getGeneral.mockReset();
mockInstanceSettingsService.getExperimental.mockReset();
mockInstanceSettingsService.update.mockReset();
mockInstanceSettingsService.updateGeneral.mockReset();
mockInstanceSettingsService.updateExperimental.mockReset();
mockInstanceSettingsService.listCompanyIds.mockReset();
mockHeartbeatService.computeTaskDrain.mockReset();
mockHeartbeatService.applyTaskDrain.mockReset();
mockHeartbeatService.stopTaskDrain.mockReset();
mockHeartbeatService.getTaskDrainStatus.mockReset();
mockHeartbeatService.readUpgradeReadiness.mockReset();
mockHeartbeatService.resumeQueuedRunsAfterDrain.mockReset();
mockHeartbeatService.resumeQueuedRunsAfterDrain.mockResolvedValue(undefined);
mockEnvironmentService.getById.mockReset();
mockEnvironmentService.findManagedSandboxEnvironment.mockReset();
mockEnvironmentService.findManagedSandboxEnvironment.mockResolvedValue(null);
mockEnvironmentService.update.mockReset();
mockPublishActivity.mockReset();
mockLogActivity.mockReset();
// Mirrors the real logActivity: push a publication for the transaction
// to publish once it commits, so route-level tests can prove publish
// happens only after every company's write in the same request lands.
mockLogActivity.mockImplementation((_db: unknown, input: { companyId: string }, postCommitPublications?: unknown[]) => {
postCommitPublications?.push({ companyId: input.companyId, payload: input, pluginEvent: null });
return Promise.resolve({ id: `activity-${input.companyId}` });
});
mockInstanceSettingsService.get.mockResolvedValue({
id: "instance-settings-1",
defaultEnvironmentId: null,
general: {
censorUsernameInLogs: false,
feedbackDataSharingPreference: "prompt",
},
experimental: {
enableEnvironments: false,
enableIsolatedWorkspaces: false,
enableIssuePlanDecompositions: false,
enableExperimentalFileViewer: false,
enableExternalObjects: false,
enableBuiltInAgents: false,
enableBetaSkills: false,
enableGoalsSidebarLink: false,
enableServerInfoDebugView: false,
autoRestartDevServerWhenIdle: false,
enableWorkspaceBranchReconcileForward: true,
enableWorkspaceDirtyQuarantineRepair: true,
enableWorktreeRunExecution: false,
worktreeRunExecutionActivatedAt: null,
worktreeRunExecutionActivationInstanceId: null,
},
createdAt: "2026-06-20T00:00:00.000Z",
updatedAt: "2026-06-20T00:00:00.000Z",
});
mockInstanceSettingsService.getGeneral.mockResolvedValue({
censorUsernameInLogs: false,
feedbackDataSharingPreference: "prompt",
});
mockInstanceSettingsService.getExperimental.mockResolvedValue({
enableEnvironments: false,
enableIsolatedWorkspaces: false,
enableIssuePlanDecompositions: false,
enableExperimentalFileViewer: false,
enableExternalObjects: false,
enableBuiltInAgents: false,
enableBetaSkills: false,
enableGoalsSidebarLink: false,
enableServerInfoDebugView: false,
autoRestartDevServerWhenIdle: false,
enableWorkspaceBranchReconcileForward: true,
enableWorkspaceDirtyQuarantineRepair: true,
enableWorktreeRunExecution: false,
worktreeRunExecutionActivatedAt: null,
worktreeRunExecutionActivationInstanceId: null,
});
mockInstanceSettingsService.update.mockResolvedValue({
id: "instance-settings-1",
defaultEnvironmentId: "env-1",
general: {
censorUsernameInLogs: false,
feedbackDataSharingPreference: "prompt",
},
experimental: {
enableEnvironments: true,
enableIsolatedWorkspaces: true,
enableIssuePlanDecompositions: true,
enableExperimentalFileViewer: true,
enableExternalObjects: false,
enableBuiltInAgents: false,
enableBetaSkills: false,
enableGoalsSidebarLink: false,
enableServerInfoDebugView: false,
autoRestartDevServerWhenIdle: false,
enableWorkspaceBranchReconcileForward: true,
enableWorkspaceDirtyQuarantineRepair: true,
enableWorktreeRunExecution: false,
worktreeRunExecutionActivatedAt: null,
worktreeRunExecutionActivationInstanceId: null,
},
createdAt: "2026-06-20T00:00:00.000Z",
updatedAt: "2026-06-20T01:00:00.000Z",
});
mockInstanceSettingsService.updateGeneral.mockResolvedValue({
id: "instance-settings-1",
general: {
censorUsernameInLogs: true,
feedbackDataSharingPreference: "allowed",
},
});
mockInstanceSettingsService.updateExperimental.mockResolvedValue({
id: "instance-settings-1",
experimental: {
enableEnvironments: true,
enableIsolatedWorkspaces: true,
enableIssuePlanDecompositions: true,
enableExperimentalFileViewer: true,
enableExternalObjects: false,
enableBuiltInAgents: true,
enableGoalsSidebarLink: false,
enableServerInfoDebugView: true,
autoRestartDevServerWhenIdle: false,
enableWorkspaceBranchReconcileForward: true,
enableWorkspaceDirtyQuarantineRepair: true,
enableWorktreeRunExecution: false,
worktreeRunExecutionActivatedAt: null,
worktreeRunExecutionActivationInstanceId: null,
},
});
mockInstanceSettingsService.listCompanyIds.mockResolvedValue(["company-1", "company-2"]);
mockEnvironmentService.getById.mockResolvedValue({
id: "env-1",
driver: "local",
status: "active",
config: {},
});
});
it("allows local board users to read and update experimental settings", async () => {
const app = await createApp(localAdminActor());
const getRes = await request(app).get("/api/instance/settings/experimental");
expect(getRes.status).toBe(200);
expect(getRes.body).toEqual({
enableEnvironments: false,
enableIsolatedWorkspaces: false,
enableIssuePlanDecompositions: false,
enableExperimentalFileViewer: false,
enableExternalObjects: false,
enableBuiltInAgents: false,
enableBetaSkills: false,
enableGoalsSidebarLink: false,
enableServerInfoDebugView: false,
autoRestartDevServerWhenIdle: false,
enableWorkspaceBranchReconcileForward: true,
enableWorkspaceDirtyQuarantineRepair: true,
enableWorktreeRunExecution: false,
worktreeRunExecutionActivatedAt: null,
worktreeRunExecutionActivationInstanceId: null,
});
const patchRes = await request(app)
.patch("/api/instance/settings/experimental")
.send({ enableIsolatedWorkspaces: true });
expect(patchRes.status).toBe(200);
expect(mockInstanceSettingsService.updateExperimental).toHaveBeenCalledWith({
enableIsolatedWorkspaces: true,
});
expect(mockLogActivity).toHaveBeenCalledTimes(2);
}, 10_000);
it("does not expose the retired liveness auto-recovery endpoints", async () => {
const app = await createApp(localAdminActor());
await request(app)
.post("/api/instance/settings/experimental/issue-graph-liveness-auto-recovery/preview")
.send({ lookbackHours: 24 })
.expect(404);
await request(app)
.post("/api/instance/settings/experimental/issue-graph-liveness-auto-recovery/run")
.send({ lookbackHours: 24 })
.expect(404);
});
it.each([true, false])("allows only instance admins to change chat connector visibility (%s)", async (isInstanceAdmin) => {
const app = createApp({ type: "board", userId: "user-1", source: "session", isInstanceAdmin, companyIds: ["company-1"] });
const response = await request(app).patch("/api/instance/settings/experimental").send({ enableChatConnectors: true });
expect(response.status).toBe(isInstanceAdmin ? 200 : 403);
if (isInstanceAdmin) {
expect(mockInstanceSettingsService.updateExperimental).toHaveBeenCalledWith({ enableChatConnectors: true });
expect(mockLogActivity).toHaveBeenCalled();
} else {
expect(mockInstanceSettingsService.updateExperimental).not.toHaveBeenCalled();
}
});
it("accepts the instance-wide Streamlined UI preference", async () => {
const app = await createApp(localAdminActor());
await request(app)
.patch("/api/instance/settings/experimental")
.send({ enableStreamlinedUi: false })
.expect(200);
expect(mockInstanceSettingsService.updateExperimental).toHaveBeenCalledWith({
enableStreamlinedUi: false,
});
});
it("strips server-managed worktree run execution fields before updating experimental settings", async () => {
const app = await createApp(localAdminActor());
await request(app)
.patch("/api/instance/settings/experimental")
.send({
enableWorktreeRunExecution: true,
worktreeRunExecutionActivatedAt: "2026-07-10T12:00:00.000Z",
worktreeRunExecutionActivationInstanceId: "copied-instance",
})
.expect(200);
expect(mockInstanceSettingsService.updateExperimental).toHaveBeenCalledWith({
enableWorktreeRunExecution: true,
});
});
it("allows local board users to read and update the instance default environment", async () => {
const app = await createApp(localAdminActor());
const getRes = await request(app).get("/api/instance/settings");
expect(getRes.status).toBe(200);
expect(getRes.body.defaultEnvironmentId).toBeNull();
const patchRes = await request(app)
.patch("/api/instance/settings")
.send({ defaultEnvironmentId: "11111111-1111-4111-8111-111111111111" });
expect(patchRes.status).toBe(200);
expect(mockInstanceSettingsService.update).toHaveBeenCalledWith(
{ defaultEnvironmentId: "11111111-1111-4111-8111-111111111111" },
{ db: TX_SENTINEL },
);
expect(mockLogActivity).toHaveBeenCalledTimes(2);
});
it("clears the managed-default stamp marker on an explicit tenant default write", async () => {
// A tenant write of defaultEnvironmentId reclassifies the default as
// tenant-chosen: the reconciliation stamp marker on the managed
// sandbox row must not survive, or a later managed-sandbox-only
// mode-off pass would mistake the tenant's choice for a stamp.
mockEnvironmentService.findManagedSandboxEnvironment.mockResolvedValue({
id: "managed-env-1",
driver: "sandbox",
status: "active",
config: {},
envVars: {},
metadata: { managedByPaperclip: true, managedDefaultStamped: true },
});
const app = await createApp(localAdminActor());
const patchRes = await request(app)
.patch("/api/instance/settings")
.send({ defaultEnvironmentId: "11111111-1111-4111-8111-111111111111" });
expect(patchRes.status).toBe(200);
expect(mockEnvironmentService.update).toHaveBeenCalledWith(
"managed-env-1",
{ metadata: { managedByPaperclip: true } },
{ db: TX_SENTINEL },
);
// Both writes commit in ONE transaction — each receives the SAME tx —
// so no partial failure can desync the stamp marker from the default
// (neither a stale stamp on a tenant choice, nor a reconciliation
// default that lost its marker and can never revert).
expect(mockInstanceSettingsService.update).toHaveBeenCalledWith(
{ defaultEnvironmentId: "11111111-1111-4111-8111-111111111111" },
{ db: TX_SENTINEL },
);
});
it("aborts the whole request (no committed settings) when the stamp-marker clear fails inside the transaction", async () => {
// The marker clear and the settings write share a transaction, so a
// failure in either rolls the whole thing back — a real DB would
// discard both; here the settings write is never even reached.
mockEnvironmentService.findManagedSandboxEnvironment.mockResolvedValue({
id: "managed-env-1",
driver: "sandbox",
status: "active",
config: {},
envVars: {},
metadata: { managedByPaperclip: true, managedDefaultStamped: true },
});
mockEnvironmentService.update.mockRejectedValue(new Error("metadata write failed"));
const app = await createApp(localAdminActor());
const patchRes = await request(app)
.patch("/api/instance/settings")
.send({ defaultEnvironmentId: "11111111-1111-4111-8111-111111111111" });
expect(patchRes.status).toBeGreaterThanOrEqual(500);
expect(mockInstanceSettingsService.update).not.toHaveBeenCalled();
});
it("rejects unknown defaultEnvironmentId values with 422", async () => {
mockEnvironmentService.getById.mockResolvedValue(null);
const app = await createApp(localAdminActor());
const res = await request(app)
.patch("/api/instance/settings")
.send({ defaultEnvironmentId: "11111111-1111-4111-8111-111111111111" });
expect(res.status).toBe(422);
expect(res.body.error).toContain("Environment not found");
expect(mockInstanceSettingsService.update).not.toHaveBeenCalled();
});
it("allows local board users to update guarded dev-server auto-restart", async () => {
const app = await createApp(localAdminActor());
await request(app)
.patch("/api/instance/settings/experimental")
.send({ autoRestartDevServerWhenIdle: true })
.expect(200);
expect(
mockInstanceSettingsService.updateExperimental.mock.calls.some(
([patch]) => patch?.autoRestartDevServerWhenIdle === true,
),
).toBe(true);
});
it("allows local board users to update external object detection", async () => {
const app = await createApp(localAdminActor());
await request(app)
.patch("/api/instance/settings/experimental")
.send({ enableExternalObjects: true })
.expect(200);
expect(mockInstanceSettingsService.updateExperimental).toHaveBeenCalledWith({
enableExternalObjects: true,
});
});
it("allows local board users to update built-in agents", async () => {
const app = await createApp(localAdminActor());
await request(app)
.patch("/api/instance/settings/experimental")
.send({ enableBuiltInAgents: true })
.expect(200);
expect(mockInstanceSettingsService.updateExperimental).toHaveBeenCalledWith({
enableBuiltInAgents: true,
});
});
it("allows local board users to update the goals sidebar link", async () => {
const app = await createApp(localAdminActor());
await request(app)
.patch("/api/instance/settings/experimental")
.send({ enableGoalsSidebarLink: true })
.expect(200);
expect(mockInstanceSettingsService.updateExperimental).toHaveBeenCalledWith({
enableGoalsSidebarLink: true,
});
});
it("allows local board users to update the server info debug view", async () => {
const app = await createApp(localAdminActor());
await request(app)
.patch("/api/instance/settings/experimental")
.send({ enableServerInfoDebugView: true })
.expect(200);
expect(mockInstanceSettingsService.updateExperimental).toHaveBeenCalledWith({
enableServerInfoDebugView: true,
});
});
it("allows local board users to update environment controls", async () => {
const app = await createApp(localAdminActor());
await request(app)
.patch("/api/instance/settings/experimental")
.send({ enableEnvironments: true })
.expect(200);
expect(mockInstanceSettingsService.updateExperimental).toHaveBeenCalledWith({
enableEnvironments: true,
});
});
it("allows non-admin board users with company access to read but not update experimental settings", async () => {
const app = await createApp({
type: "board",
userId: "user-1",
source: "session",
isInstanceAdmin: false,
companyIds: ["company-1"],
});
await request(app).get("/api/instance/settings/experimental").expect(200);
await request(app)
.patch("/api/instance/settings/experimental")
.send({ enableEnvironments: true })
.expect(403);
expect(mockInstanceSettingsService.updateExperimental).not.toHaveBeenCalled();
});
describe("Cloud stack admin experimental settings access", () => {
afterEach(() => vi.unstubAllEnvs());
const stackAdmin = {
type: "board",
userId: "stack-admin-1",
source: "cloud_tenant",
companyIds: ["company-1"],
isInstanceAdmin: false,
canManageExperimentalSettings: true,
};
it("allows a Cloud stack admin to enable fast responses and audits the change", async () => {
const app = createApp(stackAdmin);
await request(app).patch("/api/instance/settings/experimental")
.send({ enableFastResponses: true }).expect(200);
expect(mockInstanceSettingsService.updateExperimental).toHaveBeenCalledWith({ enableFastResponses: true });
expect(mockLogActivity).toHaveBeenCalledWith(mockDb, expect.objectContaining({
actorId: "stack-admin-1",
action: "instance.settings.experimental_updated",
details: expect.objectContaining({ changedKeys: ["enableFastResponses"] }),
}));
});
it.each([
["patch", "/api/instance/settings", { defaultEnvironmentId: null }],
["patch", "/api/instance/settings/general", { censorUsernameInLogs: true }],
["post", "/api/instance/task-drain", {}],
] as const)("keeps %s %s restricted to instance admins", async (method, path, body) => {
const app = createApp(stackAdmin);
await request(app)[method](path).send(body).expect(403);
});
it.each([
{ ...stackAdmin, source: "session" },
{ ...stackAdmin, source: "mcp_oauth" },
{ ...stackAdmin, type: "agent" },
{ ...stackAdmin, canManageExperimentalSettings: false },
])("rejects actors without trusted Cloud experimental authority (%j)", async (actor) => {
const app = createApp(actor);
await request(app).patch("/api/instance/settings/experimental")
.send({ enableFastResponses: true }).expect(403);
expect(mockInstanceSettingsService.updateExperimental).not.toHaveBeenCalled();
});
it("keeps operator-hidden experimental settings locked for stack admins", async () => {
vi.stubEnv("PAPERCLIP_HIDDEN_SETTINGS", "instance.experimental.enableFastResponses");
const app = createApp(stackAdmin);
await request(app).patch("/api/instance/settings/experimental")
.send({ enableFastResponses: true }).expect(403);
expect(mockInstanceSettingsService.updateExperimental).not.toHaveBeenCalled();
});
});
it("allows local board users to read and update general settings", async () => {
const app = await createApp(localAdminActor());
const getRes = await request(app).get("/api/instance/settings/general");
expect(getRes.status).toBe(200);
expect(getRes.body).toEqual({
censorUsernameInLogs: false,
feedbackDataSharingPreference: "prompt",
});
const patchRes = await request(app)
.patch("/api/instance/settings/general")
.send({
censorUsernameInLogs: true,
feedbackDataSharingPreference: "allowed",
});
expect(patchRes.status).toBe(200);
expect(mockInstanceSettingsService.updateGeneral).toHaveBeenCalledWith({
censorUsernameInLogs: true,
feedbackDataSharingPreference: "allowed",
});
expect(mockLogActivity).toHaveBeenCalledTimes(2);
});
it("allows non-admin board users to read general settings", async () => {
const app = await createApp({
type: "board",
userId: "user-1",
source: "session",
isInstanceAdmin: false,
companyIds: ["company-1"],
});
const res = await request(app).get("/api/instance/settings/general");
expect(res.status).toBe(200);
expect(res.body).toEqual({
censorUsernameInLogs: false,
feedbackDataSharingPreference: "prompt",
});
});
it("rejects signed-in users without company access from reading general settings", async () => {
const app = await createApp({
type: "board",
userId: "user-2",
source: "session",
isInstanceAdmin: false,
companyIds: [],
memberships: [],
});
const res = await request(app).get("/api/instance/settings/general");
expect(res.status).toBe(403);
expect(mockInstanceSettingsService.getGeneral).not.toHaveBeenCalled();
});
it("rejects non-admin board users from updating general settings", async () => {
const app = await createApp({
type: "board",
userId: "user-1",
source: "session",
isInstanceAdmin: false,
companyIds: ["company-1"],
});
const res = await request(app)
.patch("/api/instance/settings/general")
.send({ censorUsernameInLogs: true });
expect(res.status).toBe(403);
expect(mockInstanceSettingsService.updateGeneral).not.toHaveBeenCalled();
});
it("rejects agent callers", async () => {
const app = await createApp({
type: "agent",
agentId: "agent-1",
companyId: "company-1",
source: "agent_key",
});
const res = await request(app)
.patch("/api/instance/settings/general")
.send({ feedbackDataSharingPreference: "not_allowed" });
expect(res.status).toBe(403);
expect(mockInstanceSettingsService.updateGeneral).not.toHaveBeenCalled();
});
describe("executionMode floor on cloud-managed instances", () => {
const adminActor = {
type: "board",
userId: "owner-1",
source: "cloud_tenant",
isInstanceAdmin: true,
companyIds: ["company-1"],
};
beforeEach(() => {
process.env.PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN = "test-server-token";
});
afterEach(() => {
delete process.env.PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN;
});
it("rejects a write that changes executionMode", async () => {
mockInstanceSettingsService.getGeneral.mockResolvedValue({
censorUsernameInLogs: false,
feedbackDataSharingPreference: "prompt",
executionMode: "kubernetes",
});
const app = await createApp(adminActor);
const res = await request(app)
.patch("/api/instance/settings/general")
.send({ executionMode: "any" });
expect(res.status).toBe(403);
expect(res.body.details).toMatchObject({ code: "execution_mode_platform_managed" });
expect(mockInstanceSettingsService.updateGeneral).not.toHaveBeenCalled();
});
it("rejects pinning executionMode when the platform left it unrestricted", async () => {
const app = await createApp(adminActor);
const res = await request(app)
.patch("/api/instance/settings/general")
.send({ executionMode: "kubernetes" });
expect(res.status).toBe(403);
expect(mockInstanceSettingsService.updateGeneral).not.toHaveBeenCalled();
});
it("allows a same-value executionMode echo so full-object settings forms keep working", async () => {
mockInstanceSettingsService.getGeneral.mockResolvedValue({
censorUsernameInLogs: false,
feedbackDataSharingPreference: "prompt",
executionMode: "kubernetes",
});
const app = await createApp(adminActor);
const res = await request(app)
.patch("/api/instance/settings/general")
.send({ executionMode: "kubernetes", censorUsernameInLogs: true });
expect(res.status).toBe(200);
expect(mockInstanceSettingsService.updateGeneral).toHaveBeenCalledWith({
executionMode: "kubernetes",
censorUsernameInLogs: true,
});
});
it("allows general-settings writes that do not touch executionMode", async () => {
const app = await createApp(adminActor);
const res = await request(app)
.patch("/api/instance/settings/general")
.send({ censorUsernameInLogs: true });
expect(res.status).toBe(200);
expect(mockInstanceSettingsService.getGeneral).not.toHaveBeenCalled();
expect(mockInstanceSettingsService.updateGeneral).toHaveBeenCalledWith({ censorUsernameInLogs: true });
});
it("keeps executionMode writable on self-hosted instances", async () => {
delete process.env.PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN;
const app = await createApp({
type: "board",
userId: "admin-1",
source: "session",
isInstanceAdmin: true,
});
const res = await request(app)
.patch("/api/instance/settings/general")
.send({ executionMode: "kubernetes" });
expect(res.status).toBe(200);
expect(mockInstanceSettingsService.updateGeneral).toHaveBeenCalledWith({ executionMode: "kubernetes" });
});
});
describe("operator-hidden settings floor", () => {
const adminActor = {
type: "board",
userId: "admin-1",
source: "session",
isInstanceAdmin: true,
companyIds: ["company-1"],
};
afterEach(() => {
delete process.env.PAPERCLIP_HIDDEN_SETTINGS;
});
it("rejects a write that changes a hidden general field", async () => {
process.env.PAPERCLIP_HIDDEN_SETTINGS = "instance.general.censorUsernameInLogs";
const app = await createApp(adminActor);
const res = await request(app)
.patch("/api/instance/settings/general")
.send({ censorUsernameInLogs: true });
expect(res.status).toBe(403);
expect(res.body.details).toMatchObject({ code: "settings_operator_managed" });
expect(mockInstanceSettingsService.updateGeneral).not.toHaveBeenCalled();
});
it("allows a same-value echo of a hidden general field", async () => {
process.env.PAPERCLIP_HIDDEN_SETTINGS = "instance.general.censorUsernameInLogs";
const app = await createApp(adminActor);
const res = await request(app)
.patch("/api/instance/settings/general")
.send({ censorUsernameInLogs: false, feedbackDataSharingPreference: "allowed" });
expect(res.status).toBe(200);
expect(mockInstanceSettingsService.updateGeneral).toHaveBeenCalledWith({
censorUsernameInLogs: false,
feedbackDataSharingPreference: "allowed",
});
});
it("deep-compares hidden backupRetention echoes instead of rejecting them", async () => {
process.env.PAPERCLIP_HIDDEN_SETTINGS = "instance.general.backupRetention";
mockInstanceSettingsService.getGeneral.mockResolvedValue({
censorUsernameInLogs: false,
feedbackDataSharingPreference: "prompt",
backupRetention: { dailyDays: 7, weeklyWeeks: 4, monthlyMonths: 1 },
});
const app = await createApp(adminActor);
const echo = await request(app)
.patch("/api/instance/settings/general")
.send({ backupRetention: { dailyDays: 7, weeklyWeeks: 4, monthlyMonths: 1 } });
expect(echo.status).toBe(200);
const change = await request(app)
.patch("/api/instance/settings/general")
.send({ backupRetention: { dailyDays: 14, weeklyWeeks: 4, monthlyMonths: 1 } });
expect(change.status).toBe(403);
expect(change.body.details).toMatchObject({ code: "settings_operator_managed" });
});
it("rejects a write that changes a hidden experimental toggle", async () => {
process.env.PAPERCLIP_HIDDEN_SETTINGS = "instance.experimental.enableEnvironments";
const app = await createApp(adminActor);
const res = await request(app)
.patch("/api/instance/settings/experimental")
.send({ enableEnvironments: true });
expect(res.status).toBe(403);
expect(res.body.details).toMatchObject({ code: "settings_operator_managed" });
expect(mockInstanceSettingsService.updateExperimental).not.toHaveBeenCalled();
});
it("enforces a wildcard allowlist at the API and preserves hidden values", async () => {
process.env.PAPERCLIP_HIDDEN_SETTINGS =
"instance.experimental.*,!instance.experimental.enableIsolatedWorkspaces";
const app = await createApp(adminActor);
const rejected = await request(app)
.patch("/api/instance/settings/experimental")
.send({ enableEnvironments: true, enableIsolatedWorkspaces: true });
expect(rejected.status).toBe(403);
expect(rejected.body.details).toMatchObject({ code: "settings_operator_managed" });
expect(mockInstanceSettingsService.updateExperimental).not.toHaveBeenCalled();
// Existing full-form clients may echo hidden values without changing them.
const allowed = await request(app)
.patch("/api/instance/settings/experimental")
.send({ enableEnvironments: false, enableIsolatedWorkspaces: true });
expect(allowed.status).toBe(200);
expect(mockInstanceSettingsService.updateExperimental).toHaveBeenCalledWith({
enableEnvironments: false, enableIsolatedWorkspaces: true,
});
});
it("does not let an allowlist exception bypass an explicit API restriction", async () => {
process.env.PAPERCLIP_HIDDEN_SETTINGS =
"instance.experimental.*,!instance.experimental.enableEnvironments,instance.experimental.enableEnvironments";
const app = await createApp(adminActor);
const res = await request(app)
.patch("/api/instance/settings/experimental")
.send({ enableEnvironments: true });
expect(res.status).toBe(403);
expect(res.body.details).toMatchObject({ code: "settings_operator_managed" });
expect(mockInstanceSettingsService.updateExperimental).not.toHaveBeenCalled();
});
it("allows writes to non-hidden experimental toggles while others are hidden", async () => {
process.env.PAPERCLIP_HIDDEN_SETTINGS =
"instance.experimental.enableEnvironments,instance.experimental.enableServerInfoDebugView";
const app = await createApp(adminActor);
const res = await request(app)
.patch("/api/instance/settings/experimental")
.send({ enableIsolatedWorkspaces: true });
expect(res.status).toBe(200);
expect(mockInstanceSettingsService.updateExperimental).toHaveBeenCalledWith({
enableIsolatedWorkspaces: true,
});
});
it("floors every experimental toggle when the whole Experimental page is hidden", async () => {
process.env.PAPERCLIP_HIDDEN_SETTINGS = "instance.experimental";
const app = await createApp(adminActor);
const res = await request(app)
.patch("/api/instance/settings/experimental")
.send({ enableIsolatedWorkspaces: true });
expect(res.status).toBe(403);
expect(res.body.details).toMatchObject({ code: "settings_operator_managed" });
expect(mockInstanceSettingsService.updateExperimental).not.toHaveBeenCalled();
});
it("keeps every field writable when the env var is unset", async () => {
const app = await createApp(adminActor);
const general = await request(app)
.patch("/api/instance/settings/general")
.send({ censorUsernameInLogs: true });
expect(general.status).toBe(200);
const experimental = await request(app)
.patch("/api/instance/settings/experimental")
.send({ enableEnvironments: true });
expect(experimental.status).toBe(200);
});
});
describe("Cloud staging experiments", () => {
it.each([
["team.staging.paperclip.app", 200],
["team.paperclip.app", 403],
] as const)(
"keeps private Notebook operator-only under the real hidden wildcard on %s",
async (primaryHost, visibleExperimentStatus) => {
vi.stubEnv("PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN", "tenant-token");
vi.stubEnv("PAPERCLIP_PRIMARY_HOST", primaryHost);
vi.stubEnv("PAPERCLIP_HIDDEN_SETTINGS", "instance.experimental.*");
mockInstanceSettingsService.getExperimental.mockResolvedValue({
enablePaperclipNotebook: false, enableChatConnectors: false,
});
const app = createApp({
type: "board", userId: "stack-admin-1", source: "cloud_tenant",
companyIds: ["company-1"], isInstanceAdmin: false, canManageExperimentalSettings: true,
});
const denied = await request(app).patch("/api/instance/settings/experimental")
.send({ enablePaperclipNotebook: true }).expect(403);
expect(denied.body.details).toMatchObject({ code: "settings_operator_managed" });
expect(mockInstanceSettingsService.updateExperimental).not.toHaveBeenCalled();
expect(mockLogActivity).not.toHaveBeenCalled();
await request(app).patch("/api/instance/settings/experimental")
.send({ enableChatConnectors: true }).expect(visibleExperimentStatus);
if (visibleExperimentStatus === 200) {
expect(mockInstanceSettingsService.updateExperimental).toHaveBeenCalledExactlyOnceWith({ enableChatConnectors: true });
} else {
expect(mockInstanceSettingsService.updateExperimental).not.toHaveBeenCalled();
}
},
);
it.each(["team.staging.paperclip.app", "team.paperclip.app"])(
"reads Cloud-enabled isolation and rejects disabling it through the real service on %s",
async (primaryHost) => {
const { instanceSettingsService } = await vi.importActual<typeof import("../services/instance-settings.js")>(
"../services/instance-settings.js",
);
const update = vi.fn();
const db = {
select: () => ({ from: () => ({ where: async () => [{
id: "settings-1",
experimental: { enableIsolatedWorkspaces: false },
}] }) }),
update,
} as unknown as Parameters<typeof instanceSettingsService>[0];
const service = instanceSettingsService(db, { runtimeEnv: {
PAPERCLIP_PRIMARY_HOST: primaryHost,
PAPERCLIP_MANAGED_CONFIG: JSON.stringify({
v: 1, mode: "cloud", catalogVersion: "test",
features: { enableIsolatedWorkspaces: true }, plugins: { autoInstall: [] },
}),
} });
mockInstanceSettingsService.getExperimental.mockImplementation(service.getExperimental);
mockInstanceSettingsService.updateExperimental.mockImplementation(service.updateExperimental);
const app = createApp({
type: "board", userId: "stack-admin-1", source: "cloud_tenant",
companyIds: ["company-1"], isInstanceAdmin: false, canManageExperimentalSettings: true,
});
const current = await request(app).get("/api/instance/settings/experimental").expect(200);
expect(current.body).toMatchObject({
enableIsolatedWorkspaces: true,
managedKeys: { enableIsolatedWorkspaces: { managed: true } },
});
const denied = await request(app).patch("/api/instance/settings/experimental")
.send({ enableIsolatedWorkspaces: false }).expect(403);
expect(denied.body.details).toMatchObject({ code: "settings_operator_managed" });
expect(update).not.toHaveBeenCalled();
expect(mockLogActivity).not.toHaveBeenCalled();
},
);
afterEach(() => vi.unstubAllEnvs());
it.each(["instance.experimental", "instance.experimental.*"])(
"keeps hidden Cloud sandbox policy protected when staging reveals %s",
async (hidden) => {
vi.stubEnv("PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN", "tenant-token");
vi.stubEnv("PAPERCLIP_PRIMARY_HOST", "team.staging.paperclip.app");
vi.stubEnv("PAPERCLIP_HIDDEN_SETTINGS", hidden);
mockInstanceSettingsService.getExperimental.mockResolvedValue({ enableManagedSandboxOnly: true });
const app = createApp(localAdminActor());
await request(app).patch("/api/instance/settings/experimental")
.send({ enableManagedSandboxOnly: false }).expect(403);
expect(mockInstanceSettingsService.updateExperimental).not.toHaveBeenCalled();
},
);
it("lets a staging admin change hidden experiments but keeps general settings locked", async () => {
vi.stubEnv("PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN", "tenant-token");
vi.stubEnv("PAPERCLIP_PRIMARY_HOST", "team.staging.paperclip.app");
vi.stubEnv("PAPERCLIP_HIDDEN_SETTINGS", "instance.experimental,instance.experimental.*,instance.general.censorUsernameInLogs");
const app = createApp({
type: "board", userId: "admin-1", source: "cloud_tenant",
isInstanceAdmin: false, canManageExperimentalSettings: true,
});
await request(app).patch("/api/instance/settings/experimental").send({ enableChatConnectors: true }).expect(200);
expect(mockInstanceSettingsService.updateExperimental).toHaveBeenCalledWith({ enableChatConnectors: true });
await request(app).patch("/api/instance/settings/general").send({ censorUsernameInLogs: true }).expect(403);
expect(mockInstanceSettingsService.updateGeneral).not.toHaveBeenCalled();
});
it("keeps production locked even with a staging request hostname", async () => {
vi.stubEnv("PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN", "tenant-token");
vi.stubEnv("PAPERCLIP_PRIMARY_HOST", "team.paperclip.app");
vi.stubEnv("PAPERCLIP_HIDDEN_SETTINGS", "instance.experimental.*");
const app = createApp(localAdminActor());
await request(app).patch("/api/instance/settings/experimental")
.set("Host", "team.staging.paperclip.app").send({ enableChatConnectors: true }).expect(403);
expect(mockInstanceSettingsService.updateExperimental).not.toHaveBeenCalled();
});
it("still denies ordinary board members on staging", async () => {
vi.stubEnv("PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN", "tenant-token");
vi.stubEnv("PAPERCLIP_PRIMARY_HOST", "team.staging.paperclip.app");
const app = createApp({ type: "board", userId: "member-1", source: "session", isInstanceAdmin: false });
await request(app).patch("/api/instance/settings/experimental").send({ enableChatConnectors: true }).expect(403);
expect(mockInstanceSettingsService.updateExperimental).not.toHaveBeenCalled();
});
});
describe("task drain", () => {
const adminActor = {
type: "board",
userId: "admin-1",
source: "session",
isInstanceAdmin: true,
companyIds: ["company-1"],
};
const nonAdminActor = {
type: "board",
userId: "user-1",
source: "session",
isInstanceAdmin: false,
companyIds: ["company-1"],
};
const idleStatus = {
draining: false,
startedAt: null,
expiresAt: null,
activeRuns: 0,
pendingWakes: 0,
quiescent: true,
};
afterEach(() => {
// A drain the mock left active must not carry over into an unrelated
// test, so every test starts from the idle status again.
mockHeartbeatService.getTaskDrainStatus.mockReset();
mockHeartbeatService.readUpgradeReadiness.mockReset();
mockHeartbeatService.computeTaskDrain.mockReset();
mockHeartbeatService.applyTaskDrain.mockReset();
mockHeartbeatService.stopTaskDrain.mockReset();
});
it("returns the idle status", async () => {
mockHeartbeatService.getTaskDrainStatus.mockReturnValue(idleStatus);
const app = await createApp(nonAdminActor);
const res = await request(app).get("/api/instance/task-drain");
expect(res.status).toBe(200);
expect(res.body).toEqual(idleStatus);
expect(mockHeartbeatService.readUpgradeReadiness).not.toHaveBeenCalled();
expect(mockReadIdleSleepSafety).not.toHaveBeenCalled();
});
it("restricts the on-demand upgrade report to instance operators and does not start a drain", async () => {
mockHeartbeatService.getTaskDrainStatus.mockReturnValue(idleStatus);
mockHeartbeatService.readUpgradeReadiness.mockResolvedValue({ version: 1, ready: true, activeRuns: 1 });
await request(createApp(nonAdminActor)).get("/api/instance/task-drain?upgradeReadiness=1").expect(403);
expect(mockHeartbeatService.readUpgradeReadiness).not.toHaveBeenCalled();
const res = await request(createApp(adminActor)).get("/api/instance/task-drain?upgradeReadiness=1").expect(200);
expect(res.body.upgradeReadiness).toEqual({ version: 1, ready: true, activeRuns: 1 });
expect(mockHeartbeatService.computeTaskDrain).not.toHaveBeenCalled();
expect(mockHeartbeatService.applyTaskDrain).not.toHaveBeenCalled();
});
it("acquires an owned bounded idle hold and forwards its owner for inspection", async () => {
const ownerId = "d0b833f4-4098-42de-8420-1907f3aa4895";
mockHeartbeatService.computeTaskDrain.mockReturnValue({ ownerId, startedAt: new Date(), expiresAt: new Date(Date.now() + 60_000) });
await request(createApp(adminActor)).post("/api/instance/task-drain").send({ purpose: "idle", ttlMs: 60_000 }).expect(200);
expect(mockHeartbeatService.computeTaskDrain).toHaveBeenCalledWith({ purpose: "idle", ttlMs: 60_000 });
await request(createApp(adminActor)).get(`/api/instance/task-drain?idleSleepSafety=1&ownerId=${ownerId}`).expect(200);
expect(mockReadIdleSleepSafety).toHaveBeenLastCalledWith(mockDb, expect.any(Function), Date.now, ownerId, expect.any(Function), undefined, undefined, false, false, { incomingWake: undefined, deadlineCapability: undefined });
});
it.each([{}, { ttlMs: null }, { ttlMs: 1 }, { ttlMs: 300_001 }])("rejects an unbounded or invalid idle TTL: %j", async body => {
await request(createApp(adminActor)).post("/api/instance/task-drain").send({ ...body, purpose: "idle" }).expect(400);
expect(mockHeartbeatService.applyTaskDrain).not.toHaveBeenCalled();
});
it("rejects replacement and ownerless or stale release of an idle hold", async () => {
mockHeartbeatService.getTaskDrainStatus.mockReturnValue({ ...idleStatus, draining: true, ownerId: "current-owner" });
const app = createApp(adminActor);
await request(app).post("/api/instance/task-drain").send({}).expect(409);
await request(app).delete("/api/instance/task-drain").expect(409);
await request(app).delete("/api/instance/task-drain?ownerId=previous-owner").expect(409);
expect(mockHeartbeatService.applyTaskDrain).not.toHaveBeenCalled();
expect(mockHeartbeatService.stopTaskDrain).not.toHaveBeenCalled();
await request(app).delete("/api/instance/task-drain?ownerId=current-owner").expect(200);
expect(mockHeartbeatService.stopTaskDrain).toHaveBeenCalledOnce();
});
it("returns the opt-in instance-wide safety report to an instance admin", async () => {
mockHeartbeatService.getTaskDrainStatus.mockReturnValue(idleStatus);
const report = { version: 1, backgroundWork: "unknown" };
mockReadIdleSleepSafety.mockResolvedValue(report);
const res = await request(createApp(adminActor)).get("/api/instance/task-drain?idleSleepSafety=1");
expect(res.status).toBe(200);
expect(res.body).toEqual({ ...idleStatus, idleSleepSafety: report });
expect(mockReadIdleSleepSafety).toHaveBeenCalledWith(mockDb, expect.any(Function), Date.now, undefined, expect.any(Function), undefined, undefined, false, false, { incomingWake: undefined, deadlineCapability: undefined });
expect(mockReadIdleSleepSafety.mock.calls[0][1]()).toEqual(idleStatus);
});
it("collects fixed-key diagnostics only through the privileged safety report", async () => {
mockHeartbeatService.getTaskDrainStatus.mockReturnValue(idleStatus);
mockReadIdleSleepSafety.mockResolvedValue({ version: 1, backgroundWork: "present",
diagnostics: { version: 1, complete: true, checks: [{ reason: "agent_api_keys", state: "present" }] } });
await request(createApp(adminActor)).get("/api/instance/task-drain?idleSleepDiagnostics=1").expect(200);
expect(mockReadIdleSleepSafety).not.toHaveBeenCalled();
const response = await request(createApp(adminActor))
.get("/api/instance/task-drain?idleSleepSafety=1&idleSleepDiagnostics=1&ownerId=fixture-owner").expect(200);
expect(response.body.idleSleepSafety.diagnostics.checks).toEqual([{ reason: "agent_api_keys", state: "present" }]);
expect(mockReadIdleSleepSafety).toHaveBeenCalledWith(mockDb, expect.any(Function), Date.now,
"fixture-owner", expect.any(Function), undefined, undefined, false, false, { incomingWake: undefined, deadlineCapability: undefined, collectDiagnostics: true });
mockReadIdleSleepSafety.mockClear();
for (const actor of [nonAdminActor, { type: "agent", agentId: "agent-1", companyId: "company-1", source: "api_key" }]) {
await request(createApp(actor))
.get("/api/instance/task-drain?idleSleepSafety=1&idleSleepDiagnostics=1&ownerId=fixture-owner").expect(403);
}
expect(mockReadIdleSleepSafety).not.toHaveBeenCalled();
await request(createApp(adminActor))
.get("/api/instance/task-drain?idleSleepSafety=1&idleSleepDiagnostics=1&scheduledWake=2&ownerId=fixture-owner").expect(403);
expect(mockReadIdleSleepSafety).not.toHaveBeenCalled();
});
it.each(["1", "2"])("reserves scheduling capability %s for verified Cloud control callers", async version => {
mockHeartbeatService.getTaskDrainStatus.mockReturnValue(idleStatus);
for (const source of ["session", "cloud_tenant", "local_implicit"]) {
await request(createApp({ ...adminActor, source }))
.get(`/api/instance/task-drain?idleSleepSafety=1&scheduledWake=${version}&ownerId=fixture-owner`).expect(403);
}
expect(mockReadIdleSleepSafety).not.toHaveBeenCalled();
await request(createApp({ ...adminActor, source: "cloud_control" }))
.get(`/api/instance/task-drain?idleSleepSafety=1&scheduledWake=${version}&ownerId=fixture-owner`).expect(200);
expect(mockReadIdleSleepSafety).toHaveBeenCalledWith(mockDb, expect.any(Function), Date.now,
"fixture-owner", expect.any(Function), undefined, undefined, true, version === "2", { incomingWake: undefined, deadlineCapability: undefined });
});
describe("signed incoming capability handoff", () => {
const createControlApp = (actor: any) => createApp(actor, undefined, undefined, true);
const keyPair = generateKeyPairSync("ed25519");
const publicJwk = { ...keyPair.publicKey.export({ format: "jwk" }), kid: "idle-route-test", alg: "EdDSA", use: "sig" };
const ownerId = "d0b833f4-4098-42de-8420-1907f3aa4895";
const catalog = {
incomingWake: { version: 1, ownerId, generation: "a".repeat(64), apiKeyProof: { version: 1, challenge: "c".repeat(64) }, routes: ["tenant-api-http-v2"] },
deadlineCatalog: "domain_deadlines_v1",
};
const path = `/api/instance/task-drain?idleSleepSafety=1&ownerId=${ownerId}`;
function assertion(claims: Record<string, unknown> = {}) {
const identity = routeModules.value.controlIdentity;
const encode = (value: unknown) => Buffer.from(JSON.stringify(value)).toString("base64url");
const iat = Math.floor(Date.now() / 1000);
const header = encode({ alg: "EdDSA", typ: identity.CLOUD_CONTROL_JWS_TYPE, kid: publicJwk.kid });
const payload = encode({ v: 1, iss: identity.CLOUD_RUNTIME_IDENTITY_ISSUER, aud: identity.CLOUD_CONTROL_AUDIENCE,
sub: "stack-idle-route-test", action: "task-drain:read", requestId: randomUUID(), iat, exp: iat + 60,
idleCapabilities: catalog, ...claims });
return `${header}.${payload}.${sign(null, Buffer.from(`${header}.${payload}`, "ascii"), keyPair.privateKey).toString("base64url")}`;
}
beforeEach(() => {
vi.stubEnv("PAPERCLIP_CLOUD_RUNTIME_IDENTITY_JWKS", JSON.stringify({ keys: [publicJwk] }));
vi.stubEnv("PAPERCLIP_CLOUD_STACK_ID", "stack-idle-route-test");
routeModules.value.controlIdentity.resetCloudControlReplayFenceForTests();
mockHeartbeatService.getTaskDrainStatus.mockReturnValue(idleStatus);
mockReadIdleSleepSafety.mockResolvedValue({ version: 3, backgroundWork: "none" });
});
afterEach(() => vi.unstubAllEnvs());
it("passes only the immutable signed catalog through real middleware and the production route", async () => {
const token = assertion();
const response = await request(createControlApp({ type: "none" }))
.get(`${path}&incomingWake=${encodeURIComponent(JSON.stringify({ ...catalog.incomingWake, generation: "b".repeat(64) }))}`)
.set("x-paperclip-cloud-control", token)
.send({ idleCapabilities: { incomingWake: { ...catalog.incomingWake, ownerId: randomUUID() } } }).expect(200);
expect(response.body.idleSleepSafety).toEqual({ version: 3, backgroundWork: "none" });
expect(mockReadIdleSleepSafety).toHaveBeenCalledExactlyOnceWith(mockDb, expect.any(Function), Date.now,
ownerId, expect.any(Function), undefined, undefined, false, false,
{ incomingWake: catalog, deadlineCapability: undefined });
const options = mockReadIdleSleepSafety.mock.calls[0][9];
expect(options.deadlineCapability).toBeUndefined();
expect(Object.isFrozen(options.incomingWake)).toBe(true);
expect(Object.isFrozen(options.incomingWake.incomingWake)).toBe(true);
expect(Object.isFrozen(options.incomingWake.incomingWake.routes)).toBe(true);
await request(createControlApp({ type: "none" })).get(path).set("x-paperclip-cloud-control", token).expect(401);
expect(mockReadIdleSleepSafety).toHaveBeenCalledTimes(1);
});
it("passes the signed deadline catalog only for its explicit named query", async () => {
await request(createControlApp({ type: "none" })).get(`${path}&scheduledWake=domain-deadlines-v1`)
.set("x-paperclip-cloud-control", assertion()).expect(200);
expect(mockReadIdleSleepSafety).toHaveBeenCalledExactlyOnceWith(mockDb, expect.any(Function), Date.now,
ownerId, expect.any(Function), undefined, undefined, true, true,
{ incomingWake: catalog, deadlineCapability: catalog });
const options = mockReadIdleSleepSafety.mock.calls[0][9];
expect(options.incomingWake).toBe(options.deadlineCapability);
expect(Object.isFrozen(options.deadlineCapability)).toBe(true);
});
it.each([
["wrong stack", () => ({ sub: "other-stack" })],
["wrong action", () => ({ action: "task-drain:start" })],
["expired", () => ({ iat: Math.floor(Date.now() / 1000) - 600, exp: Math.floor(Date.now() / 1000) - 300 })],
["unsupported catalog", () => ({ idleCapabilities: { incomingWake: { ...catalog.incomingWake, routes: ["unverified-path"] } } })],
])("rejects %s before safety inspection", async (_name, claims) => {
await request(createControlApp(adminActor)).get(path).set("x-paperclip-cloud-control", assertion(claims())).expect(401);
expect(mockReadIdleSleepSafety).not.toHaveBeenCalled();
});
it("rejects a tampered catalog signature before safety inspection", async () => {
const [header, payload, signature] = assertion().split(".");
const changed = JSON.parse(Buffer.from(payload!, "base64url").toString());
changed.idleCapabilities.incomingWake.generation = "b".repeat(64);
const tampered = `${header}.${Buffer.from(JSON.stringify(changed)).toString("base64url")}.${signature}`;
await request(createControlApp(adminActor)).get(path).set("x-paperclip-cloud-control", tampered).expect(401);
expect(mockReadIdleSleepSafety).not.toHaveBeenCalled();
});
it("leaves legacy signed reads without a catalog conservative", async () => {
await request(createControlApp({ type: "none" })).get(path)
.set("x-paperclip-cloud-control", assertion({ idleCapabilities: undefined })).expect(200);
expect(mockReadIdleSleepSafety.mock.calls[0][9]).toEqual({ incomingWake: undefined, deadlineCapability: undefined });
});
it("cannot install capabilities from tenant, actor, query or body values", async () => {
for (const source of ["session", "cloud_tenant", "local_implicit", "cloud_control"]) {
const actor = { ...adminActor, source, idleCapabilities: catalog, incomingWake: catalog };
await request(createControlApp(actor)).get(`${path}&incomingWake=${encodeURIComponent(JSON.stringify(catalog))}`)
.send({ idleCapabilities: catalog }).expect(200);
expect(mockReadIdleSleepSafety.mock.lastCall?.[9]).toEqual({ incomingWake: undefined, deadlineCapability: undefined });
}
mockReadIdleSleepSafety.mockClear();
await request(createControlApp(nonAdminActor)).get(path).send({ idleCapabilities: catalog }).expect(403);
expect(mockReadIdleSleepSafety).not.toHaveBeenCalled();
});
});
it("uses the live worker manager for inspection and releases only the owned hold", async () => {
const inspect = vi.fn(async () => ({ backgroundWork: "none", pluginIds: [] }));
const release = vi.fn();
const workers = {
inspectIdleSleep: inspect,
releaseIdleSleep: release,
} as unknown as PluginWorkerManager;
const ownerId = "fixture-idle-owner";
const lease = { ownerId, expiresAt: Date.now() + 60_000 };
mockHeartbeatService.getTaskDrainStatus.mockReturnValue({ ...idleStatus, draining: true, ownerId });
mockReadIdleSleepSafety.mockImplementation(async (_db, _status, _now, owner, _local, inspectPlugins) => {
expect(owner).toBe(ownerId);
return { version: 1, backgroundWork: (await inspectPlugins(lease)).backgroundWork };
});
const app = createApp(adminActor, workers);
await request(app).get(`/api/instance/task-drain?idleSleepSafety=1&ownerId=${ownerId}`).expect(200);
expect(inspect).toHaveBeenCalledWith(lease);
expect(inspect.mock.contexts[0]).toBe(workers);
await request(app).delete("/api/instance/task-drain?ownerId=stale-owner").expect(409);
expect(release).not.toHaveBeenCalled();
await request(app).delete(`/api/instance/task-drain?ownerId=${ownerId}`).expect(200);
expect(release).toHaveBeenCalledOnce();
});
it("passes the operator backup hook only through the protected safety report", async () => {
const backup = vi.fn(async () => true);
mockHeartbeatService.getTaskDrainStatus.mockReturnValue(idleStatus);
const app = createApp(adminActor, undefined, backup);
await request(app).get("/api/instance/task-drain").expect(200);
expect(mockReadIdleSleepSafety).not.toHaveBeenCalled();
await request(app).get("/api/instance/task-drain?idleSleepSafety=1&ownerId=fixture-owner").expect(200);
expect(mockReadIdleSleepSafety).toHaveBeenCalledWith(mockDb, expect.any(Function), Date.now,
"fixture-owner", expect.any(Function), undefined, backup, false, false, { incomingWake: undefined, deadlineCapability: undefined });
mockReadIdleSleepSafety.mockClear();
await request(createApp(nonAdminActor, undefined, backup)).get("/api/instance/task-drain?idleSleepSafety=1").expect(403);
expect(mockReadIdleSleepSafety).not.toHaveBeenCalled();
expect(backup).not.toHaveBeenCalled();
});
it("reserves managed checkpoint creation for verified Cloud control actors", async () => {
const backup = vi.fn(async () => true);
process.env.PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN = "fixture-managed-signal";
mockHeartbeatService.getTaskDrainStatus.mockReturnValue(idleStatus);
try {
for (const source of ["session", "cloud_tenant", "local_implicit"]) {
const tenantAdmin = createApp({ ...adminActor, source }, undefined, backup);
await request(tenantAdmin).get("/api/instance/task-drain?idleSleepSafety=1&ownerId=fixture-owner")
.set("x-paperclip-cloud-control", "unverified-header").expect(403);
}
expect(mockReadIdleSleepSafety).not.toHaveBeenCalled();
expect(backup).not.toHaveBeenCalled();
const control = createApp({ ...adminActor, source: "cloud_control" }, undefined, backup);
await request(control).get("/api/instance/task-drain?idleSleepSafety=1&ownerId=fixture-owner").expect(200);
expect(mockReadIdleSleepSafety).toHaveBeenCalledWith(mockDb, expect.any(Function), Date.now,
"fixture-owner", expect.any(Function), undefined, backup, false, false, { incomingWake: undefined, deadlineCapability: undefined });
} finally {
delete process.env.PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN;
}
});
it.each([
["company member", nonAdminActor],
["agent", { type: "agent", agentId: "agent-1", companyId: "company-1" }],
["anonymous caller", { type: "none" }],
])("does not expose the instance-wide work report to a %s", async (_name, actor) => {
const res = await request(createApp(actor)).get("/api/instance/task-drain?idleSleepSafety=1");
expect(res.status).toBe(403);
expect(mockReadIdleSleepSafety).not.toHaveBeenCalled();
});
it("writes an activity record for every company, then applies the same drain values, in one transaction", async () => {
const drain = { startedAt: "2026-08-29T00:00:00.000Z", expiresAt: "2026-08-29T06:00:00.000Z" };
mockHeartbeatService.computeTaskDrain.mockReturnValue(drain);
const app = await createApp(adminActor);
const res = await request(app)
.post("/api/instance/task-drain")
.send({ ttlMs: 21_600_000 });
expect(res.status).toBe(200);
expect(res.body).toEqual(drain);
expect(mockHeartbeatService.computeTaskDrain).toHaveBeenCalledWith({ ttlMs: 21_600_000 });
expect(mockDb.transaction).toHaveBeenCalledTimes(1);
expect(mockLogActivity).toHaveBeenCalledTimes(2);
for (const call of mockLogActivity.mock.calls) {
expect(call[0]).toBe(TX_SENTINEL);
expect(call[1]).toMatchObject({
action: "instance.task_drain.started",
details: { startedAt: drain.startedAt, expiresAt: drain.expiresAt },
});
}
// The mutation applies the same values the audit rows already carry,
// and only after the shared transaction commits.
expect(mockHeartbeatService.applyTaskDrain).toHaveBeenCalledTimes(1);
expect(mockHeartbeatService.applyTaskDrain).toHaveBeenCalledWith(drain);
expect(mockPublishActivity).toHaveBeenCalledTimes(2);
});
it("starts an indefinite drain when the caller sends no ttlMs", async () => {
mockHeartbeatService.computeTaskDrain.mockReturnValue({ startedAt: "2026-08-29T00:00:00.000Z", expiresAt: null });
const app = await createApp(adminActor);
const res = await request(app).post("/api/instance/task-drain").send({});
expect(res.status).toBe(200);
expect(mockHeartbeatService.computeTaskDrain).toHaveBeenCalledWith({ ttlMs: null });
});
it("writes an activity record for every company, then stops the drain, using one wasActive value throughout", async () => {
mockHeartbeatService.getTaskDrainStatus.mockReturnValue({
draining: true,
startedAt: new Date(),
expiresAt: null,
activeRuns: 0,
pendingWakes: 0,
quiescent: true,
});
const app = await createApp(adminActor);
const res = await request(app).delete("/api/instance/task-drain");
expect(res.status).toBe(200);
expect(res.body).toEqual({ wasActive: true });
expect(mockDb.transaction).toHaveBeenCalledTimes(1);
expect(mockLogActivity).toHaveBeenCalledTimes(2);
for (const call of mockLogActivity.mock.calls) {
expect(call[0]).toBe(TX_SENTINEL);
expect(call[1]).toMatchObject({
action: "instance.task_drain.stopped",
details: { wasActive: true },
});
}
// The mutation runs only after the shared transaction commits.
expect(mockHeartbeatService.stopTaskDrain).toHaveBeenCalledWith();
expect(mockPublishActivity).toHaveBeenCalledTimes(2);
});
it("does not apply a drain when the company list read fails", async () => {
mockInstanceSettingsService.listCompanyIds.mockRejectedValue(new Error("db unavailable"));
const app = await createApp(adminActor);
const res = await request(app).post("/api/instance/task-drain").send({});
expect(res.status).toBeGreaterThanOrEqual(500);
expect(mockHeartbeatService.applyTaskDrain).not.toHaveBeenCalled();
});
it("commits no activity record for any company when one company's audit write fails", async () => {
// company-1 succeeds, company-2 fails. A real transaction rolls both
// back together; here we prove the route puts both writes in the
// SAME transaction (rather than firing one independent write per
// company) and never publishes a record for the company that did
// succeed before the shared transaction rejected.
mockHeartbeatService.computeTaskDrain.mockReturnValue({
startedAt: "2026-08-29T00:00:00.000Z",
expiresAt: null,
});
mockLogActivity.mockImplementation((_db: unknown, input: { companyId: string }) => (
input.companyId === "company-2"
? Promise.reject(new Error("activity insert failed"))
: Promise.resolve({ id: `activity-${input.companyId}` })
));
const app = await createApp(adminActor);
const res = await request(app).post("/api/instance/task-drain").send({});
expect(res.status).toBeGreaterThanOrEqual(500);
expect(mockDb.transaction).toHaveBeenCalledTimes(1);
for (const call of mockLogActivity.mock.calls) {
expect(call[0]).toBe(TX_SENTINEL);
}
expect(mockPublishActivity).not.toHaveBeenCalled();
});
it("does not apply the drain when the audit transaction rejects", async () => {
mockHeartbeatService.computeTaskDrain.mockReturnValue({
startedAt: "2026-08-29T00:00:00.000Z",
expiresAt: null,
});
mockLogActivity.mockRejectedValue(new Error("activity insert failed"));
const app = await createApp(adminActor);
const res = await request(app).post("/api/instance/task-drain").send({});
expect(res.status).toBeGreaterThanOrEqual(500);
expect(mockHeartbeatService.applyTaskDrain).not.toHaveBeenCalled();
});
it("still reports the started drain when publishing its committed audit record fails", async () => {
// The audit row already committed by the time publish runs, so a
// publish failure must not turn the response into a false failure:
// the caller asked to start a drain, and the drain did start.
const drain = { startedAt: "2026-08-29T00:00:00.000Z", expiresAt: null };
mockHeartbeatService.computeTaskDrain.mockReturnValue(drain);
mockPublishActivity.mockImplementation(() => {
throw new Error("live event bus unavailable");
});
const app = await createApp(adminActor);
const res = await request(app).post("/api/instance/task-drain").send({});
expect(res.status).toBe(200);
expect(res.body).toEqual(drain);
expect(mockDb.transaction).toHaveBeenCalledTimes(1);
expect(mockLogActivity).toHaveBeenCalledTimes(2);
expect(mockHeartbeatService.applyTaskDrain).toHaveBeenCalledWith(drain);
});
it("does not stop the drain when the company list read fails", async () => {
mockInstanceSettingsService.listCompanyIds.mockRejectedValue(new Error("db unavailable"));
const app = await createApp(adminActor);
const res = await request(app).delete("/api/instance/task-drain");
expect(res.status).toBeGreaterThanOrEqual(500);
expect(mockHeartbeatService.stopTaskDrain).not.toHaveBeenCalled();
});
it("does not dispatch work when the drain-stop audit transaction rejects", async () => {
mockHeartbeatService.getTaskDrainStatus.mockReturnValue({ ...idleStatus, draining: true });
mockLogActivity.mockRejectedValue(new Error("activity insert failed"));
const res = await request(createApp(adminActor)).delete("/api/instance/task-drain");
expect(res.status).toBeGreaterThanOrEqual(500);
expect(mockHeartbeatService.resumeQueuedRunsAfterDrain).not.toHaveBeenCalled();
});
it("reports the committed drain release even when queued dispatch fails", async () => {
mockHeartbeatService.getTaskDrainStatus.mockReturnValue({ ...idleStatus, draining: true });
mockHeartbeatService.resumeQueuedRunsAfterDrain.mockRejectedValue(new Error("database unavailable"));
const res = await request(createApp(adminActor)).delete("/api/instance/task-drain");
expect(res.status).toBe(200);
expect(res.body).toEqual({ wasActive: true });
expect(mockHeartbeatService.resumeQueuedRunsAfterDrain).toHaveBeenCalledTimes(1);
});
it("does not stop the drain when the audit transaction rejects", async () => {
mockHeartbeatService.getTaskDrainStatus.mockReturnValue({
draining: true,
startedAt: new Date(),
expiresAt: null,
activeRuns: 0,
pendingWakes: 0,
quiescent: true,
});
mockLogActivity.mockRejectedValue(new Error("activity insert failed"));
const app = await createApp(adminActor);
const res = await request(app).delete("/api/instance/task-drain");
expect(res.status).toBeGreaterThanOrEqual(500);
expect(mockHeartbeatService.stopTaskDrain).not.toHaveBeenCalled();
});
it("still reports the stopped drain when publishing its committed audit record fails", async () => {
mockHeartbeatService.getTaskDrainStatus.mockReturnValue({
draining: true,
startedAt: new Date(),
expiresAt: null,
activeRuns: 0,
pendingWakes: 0,
quiescent: true,
});
mockPublishActivity.mockImplementation(() => {
throw new Error("live event bus unavailable");
});
const app = await createApp(adminActor);
const res = await request(app).delete("/api/instance/task-drain");
expect(res.status).toBe(200);
expect(res.body).toEqual({ wasActive: true });
expect(mockDb.transaction).toHaveBeenCalledTimes(1);
expect(mockLogActivity).toHaveBeenCalledTimes(2);
expect(mockHeartbeatService.stopTaskDrain).toHaveBeenCalledWith();
});
it("still publishes the second company's record when the first company's publish fails", async () => {
// Each committed audit record publishes independently, so one
// company's publish failure must not stop the rest from publishing.
const drain = { startedAt: "2026-08-29T00:00:00.000Z", expiresAt: null };
mockHeartbeatService.computeTaskDrain.mockReturnValue(drain);
mockPublishActivity.mockImplementation((publication: { companyId: string }) => {
if (publication.companyId === "company-1") throw new Error("live event bus unavailable");
});
const app = await createApp(adminActor);
const res = await request(app).post("/api/instance/task-drain").send({});
expect(res.status).toBe(200);
expect(res.body).toEqual(drain);
expect(mockPublishActivity).toHaveBeenCalledTimes(2);
expect(mockPublishActivity.mock.calls.map(([publication]) => publication.companyId)).toEqual([
"company-1",
"company-2",
]);
});
it("queues an overlapping DELETE behind a POST whose audit transaction is still pending, so the audit order and the live state always agree", async () => {
// Model the real drain state instead of a canned return value, so
// this test can prove the applied state, the audit rows, and the
// response all agree even when the earlier request's transaction
// resolves after the later request's would have.
const liveState = { draining: false };
mockHeartbeatService.computeTaskDrain.mockReturnValue({
startedAt: "2026-08-29T00:00:00.000Z",
expiresAt: null,
});
mockHeartbeatService.applyTaskDrain.mockImplementation(() => {
liveState.draining = true;
});
mockHeartbeatService.stopTaskDrain.mockImplementation(() => {
const wasActive = liveState.draining;
liveState.draining = false;
return { wasActive };
});
mockHeartbeatService.getTaskDrainStatus.mockImplementation(() => ({
draining: liveState.draining,
startedAt: liveState.draining ? "2026-08-29T00:00:00.000Z" : null,
expiresAt: null,
activeRuns: 0,
pendingWakes: 0,
quiescent: true,
}));
// The POST's transaction call blocks until the test releases it. The
// DELETE's transaction call, if it is ever reached, commits at once —
// so if the route let the two requests race, the DELETE would commit
// its audit row, and reach stopTaskDrain, first.
const transactionCalls: string[] = [];
let releasePostTransaction: (() => void) | undefined;
let sawFirstCall = false;
// Resolves the instant the first (blocked) transaction call starts.
// The test then waits for this real event, not a fixed duration.
// Under CPU contention the event loop can take far longer than any
// fixed budget to reach this call, so a timer would flake here.
let notifyFirstTransactionStarted: (() => void) | undefined;
const firstTransactionStarted = new Promise<void>((resolve) => {
notifyFirstTransactionStarted = resolve;
});
mockDb.transaction.mockImplementation((fn: (tx: unknown) => Promise<unknown>) => {
if (!sawFirstCall) {
sawFirstCall = true;
transactionCalls.push("post-start");
notifyFirstTransactionStarted?.();
return new Promise((resolve) => {
releasePostTransaction = () => {
transactionCalls.push("post-commit");
resolve(fn(TX_SENTINEL));
};
});
}
transactionCalls.push("delete-start-and-commit");
return fn(TX_SENTINEL);
});
// Each route handler awaits listCompanyIds as its last step before it
// enters the task-drain transition queue, so a second call proves the
// DELETE passed authorization and reached the queue — not merely that
// it has not arrived yet.
let listCompanyIdsCallCount = 0;
let notifySecondListCompanyIdsCall: (() => void) | undefined;
const secondListCompanyIdsCall = new Promise<void>((resolve) => {
notifySecondListCompanyIdsCall = resolve;
});
mockInstanceSettingsService.listCompanyIds.mockImplementation(async () => {
listCompanyIdsCallCount += 1;
if (listCompanyIdsCallCount === 2) notifySecondListCompanyIdsCall?.();
return ["company-1", "company-2"];
});
const app = await createApp(adminActor);
// supertest only sends a request once something calls .then() on it,
// so force the POST to send now instead of waiting for the final
// Promise.all below to do it.
const postPromise = request(app).post("/api/instance/task-drain").send({});
postPromise.then(() => {}, () => {});
// Wait for the POST's transaction call to start before the test sends
// the DELETE. At that point the POST already called listCompanyIds,
// already entered the task-drain transition queue, and sits blocked
// inside the mocked db.transaction call — the POST holds the queue.
// Only a real event proves this; a fixed wait would not, because the
// event loop can take far longer than any fixed budget under CPU
// contention. Sending the DELETE only after this event fixes the
// request order by the queue, not by which socket the operating
// system happens to service first.
await firstTransactionStarted;
const deletePromise = request(app).delete("/api/instance/task-drain");
deletePromise.then(() => {}, () => {});
// Wait for the DELETE's own listCompanyIds call. It proves the DELETE
// passed authorization and reached the transition queue behind the
// POST — not merely that it has not shown up yet.
await secondListCompanyIdsCall;
expect(transactionCalls).toEqual(["post-start"]);
expect(mockHeartbeatService.applyTaskDrain).not.toHaveBeenCalled();
expect(mockHeartbeatService.stopTaskDrain).not.toHaveBeenCalled();
releasePostTransaction?.();
const [postRes, deleteRes] = await Promise.all([postPromise, deletePromise]);
expect(postRes.status).toBe(200);
expect(deleteRes.status).toBe(200);
// The DELETE's transaction only starts once the POST's has committed
// and the POST has already applied its drain — audit order matches
// application order.
expect(transactionCalls).toEqual(["post-start", "post-commit", "delete-start-and-commit"]);
// The DELETE observed the drain the POST applied, so its audit row
// and its response correctly report an active drain, and the live
// state ends idle — not stuck "draining" from a stale POST that
// applied after the DELETE that was meant to be the final word.
expect(deleteRes.body).toEqual({ wasActive: true });
expect(liveState.draining).toBe(false);
});
it("rejects a board actor without instance admin rights", async () => {
const app = await createApp(nonAdminActor);
const res = await request(app).post("/api/instance/task-drain").send({});
expect(res.status).toBe(403);
expect(mockHeartbeatService.applyTaskDrain).not.toHaveBeenCalled();
});
it("rejects a ttl above the maximum", async () => {
const app = await createApp(adminActor);
const res = await request(app)
.post("/api/instance/task-drain")
.send({ ttlMs: 24 * 60 * 60 * 1000 + 1 });
expect(res.status).toBe(400);
expect(mockHeartbeatService.applyTaskDrain).not.toHaveBeenCalled();
});
it("rejects a zero or negative ttl", async () => {
const app = await createApp(adminActor);
const zeroRes = await request(app).post("/api/instance/task-drain").send({ ttlMs: 0 });
expect(zeroRes.status).toBe(400);
const negativeRes = await request(app).post("/api/instance/task-drain").send({ ttlMs: -1 });
expect(negativeRes.status).toBe(400);
expect(mockHeartbeatService.applyTaskDrain).not.toHaveBeenCalled();
});
});
describe("cloud lifecycle read-back and unarchive", () => {
const STACK_ID = "stack-lifecycle-routes";
const adminActor = {
type: "board",
userId: "paperclip-cloud",
source: "cloud_control",
isInstanceAdmin: true,
companyIds: [],
};
const memberActor = {
type: "board",
userId: "member-1",
source: "cloud_tenant",
isInstanceAdmin: false,
companyIds: ["company-1"],
};
// The pinned primary company id the routes derive from the stack id.
let primaryId: string;
beforeEach(async () => {
process.env.PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN = "test-server-token";
process.env.PAPERCLIP_CLOUD_STACK_ID = STACK_ID;
const { cloudTenantPrimaryCompanyId } = await vi.importActual<
typeof import("../services/cloud-instance.js")
>("../services/cloud-instance.js");
primaryId = cloudTenantPrimaryCompanyId(STACK_ID);
mockCompanyRows = [];
});
afterEach(() => {
delete process.env.PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN;
delete process.env.PAPERCLIP_CLOUD_STACK_ID;
});
it("reports the primary company status and how many other companies are not archived", async () => {
mockCompanyRows = [
{ id: primaryId, status: "archived" },
{ id: "company-sibling-live", status: "active" },
{ id: "company-sibling-paused", status: "paused" },
{ id: "company-sibling-archived", status: "archived" },
];
const app = await createApp(adminActor);
const res = await request(app).get("/api/instance/lifecycle");
expect(res.status).toBe(200);
expect(res.body).toEqual({
primaryCompanyId: primaryId,
primaryCompanyStatus: "archived",
// paused counts: any non-archived sibling keeps the stack alive.
otherUnarchivedCompanyCount: 2,
});
});
it("reports a missing primary company without failing", async () => {
mockCompanyRows = [{ id: "company-other", status: "active" }];
const app = await createApp(adminActor);
const res = await request(app).get("/api/instance/lifecycle");
expect(res.status).toBe(200);
expect(res.body.primaryCompanyStatus).toBe("missing");
});
it("hides the cross-company lifecycle summary from non-admin board members", async () => {
mockCompanyRows = [{ id: primaryId, status: "archived" }];
const app = await createApp(memberActor);
const res = await request(app).get("/api/instance/lifecycle");
expect(res.status).toBe(403);
});
it("answers 404 when the instance is not cloud-managed", async () => {
delete process.env.PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN;
delete process.env.PAPERCLIP_CLOUD_STACK_ID;
const readRes = await request(await createApp(adminActor)).get("/api/instance/lifecycle");
expect(readRes.status).toBe(404);
// The admin gate runs first, so prove the 404 with an admin actor.
const unarchiveRes = await request(await createApp(adminActor))
.post("/api/instance/lifecycle/unarchive-primary")
.send({});
expect(unarchiveRes.status).toBe(404);
expect(mockCompanyService.update).not.toHaveBeenCalled();
});
it("unarchives an archived primary company as a system actor", async () => {
mockCompanyService.getById.mockResolvedValue({ id: "", status: "archived" });
mockCompanyService.update.mockImplementation(async (id: string) => ({ id, status: "active" }));
const app = await createApp(adminActor);
const res = await request(app)
.post("/api/instance/lifecycle/unarchive-primary")
.send({});
expect(res.status).toBe(200);
expect(res.body).toEqual({ status: "active", changed: true });
expect(mockCompanyService.update).toHaveBeenCalledWith(
primaryId,
{ status: "active" },
{ actorType: "system", actorId: "paperclip-cloud", agentId: null, runId: null },
);
});
it("attributes a human admin's unarchive to that admin, not to Cloud", async () => {
mockCompanyService.getById.mockResolvedValue({ id: "", status: "archived" });
mockCompanyService.update.mockImplementation(async (id: string) => ({ id, status: "active" }));
const humanAdmin = {
type: "board",
userId: "human-admin",
source: "session",
isInstanceAdmin: true,
companyIds: ["company-1"],
};
const app = await createApp(humanAdmin);
const res = await request(app)
.post("/api/instance/lifecycle/unarchive-primary")
.send({});
expect(res.status).toBe(200);
expect(mockCompanyService.update).toHaveBeenCalledWith(
primaryId,
{ status: "active" },
expect.objectContaining({ actorType: "user", actorId: "human-admin" }),
);
});
it("is idempotent: an unarchived primary company reports changed:false", async () => {
mockCompanyService.getById.mockResolvedValue({ id: "", status: "active" });
const app = await createApp(adminActor);
const res = await request(app)
.post("/api/instance/lifecycle/unarchive-primary")
.send({});
expect(res.status).toBe(200);
expect(res.body).toEqual({ status: "active", changed: false });
expect(mockCompanyService.update).not.toHaveBeenCalled();
});
it("requires instance admin rights to unarchive", async () => {
const app = await createApp(memberActor);
const res = await request(app)
.post("/api/instance/lifecycle/unarchive-primary")
.send({});
expect(res.status).toBe(403);
expect(mockCompanyService.update).not.toHaveBeenCalled();
});
});
});