fix(maintenance): report an owner's exact offline migration refusal (#22801)

## Thinking Path

- Paperclip Cloud moves a hosted instance off its volume with an offline
maintenance process (`server/src/maintenance/ephemeral-migration*.ts`).
Each data owner either migrates its records or refuses with a fixed
code; the maintenance receipt reports that code to the Cloud enrollment
driver, which rolls back and records it.
- The workspace owner refuses as
`remote_workspace_migration_blocked:<reason,reason>` (for example
`...:workspace_recovery_unresolved` or
`...:archived_git_source_unavailable,local_source_unsafe_or_missing`).
- The receipt only accepted bare `[a-z_]` codes, so every workspace
refusal collapsed to `owner_migration_failed`, and the process logged
nothing. Two hosted enrollments rolled back with only
`owner_migration_failed`, leaving the admin unable to see which owner
refused or why.
- This change lets the owner's fixed reason list through (still
lowercase codes only, never free text) and logs the blocked phase and
code so the deployment log carries it too.

## Linked Issues or Issue Description

No existing issue; described in-PR per the bug report template. Related:
paperclipai/paperclip-cloud#1777 (Cloud side of the same fix).

### What happened?

Offline (maintenance) enrollment of two hosted instances rolled back.
The recorded reason was only `failure: "owner_migration_failed"` (Cloud
showed `phase: "unreported"`), and the maintenance deployment log
contained no refusal at all.

### Expected behavior

The receipt and the deployment log name the refusing owner and its fixed
reason codes, e.g.
`remote_workspace_migration_blocked:workspace_recovery_unresolved`.

### Steps to reproduce

Start `startEphemeralMigrationService` with a `migrate` that throws
`remote_workspace_migration_blocked:archived_git_source_unavailable,local_source_unsafe_or_missing`
(what `reserveMigration` throws for a blocked workspace); `GET /status`
reports `owner_migration_failed` and nothing is logged. The new test in
this PR does exactly this.

### Paperclip version or commit

7d26bdaa (deployed) and origin/master 4daeab5c76; the maintenance files
are identical.

### Deployment mode

Hosted (Cloud-managed), offline maintenance entry
`server/dist-runtime/ephemeral-migration.mjs`.

## What Changed

- `server/src/maintenance/ephemeral-migration-service.ts`: new
`ownerRefusalCode`. A bare `[a-z_]` code passes as before. Only an
allowlisted reason-list owner (`remote_workspace_migration_blocked`) may
carry `:reason,reason`; each reason must be a fixed lowercase code, a
malformed list keeps just the owner code, and more than 32 reasons keep
the first 31 plus `more_reasons_truncated`. Anything else reports
`owner_migration_failed`. Logs `{event: "ephemeral_migration_blocked",
phase, failure}` to stderr when blocked.
- `server/src/maintenance/ephemeral-migration-service.test.ts`: receipt
and log for a structured refusal with a workspace phase; sanitized log
for an arbitrary error; allowlist, malformed and truncation cases.

## Verification

- Red: new test failed on origin/master (`failure:
"owner_migration_failed"`).
- Green: `cd server && npx vitest run
src/maintenance/ephemeral-migration-service.test.ts` (16/16). `npx tsc
-p server/tsconfig.json --noEmit` clean.
- `pnpm verify` selected a broad server shard; stopped it after 30 min
per AGENTS.md section 7 and rely on CI for broad coverage.
- Not run: a live enrollment.

## Risks

- Low. Diagnostics only; migration and blocking behavior are unchanged.
The accepted shape cannot carry paths, URLs, secrets or stack text.
Rollback: revert.

## Model Used

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

## Checklist

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

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
DottaandClaude Opus 5.5 authored and GitHub committed 2026-11-24 13:36:00 -06:00
1 parent 1a36a8f3c0
commit 7a9f099cc4
2 files changed
+73 -5

No files matched your search

@@ -1,9 +1,9 @@
import { randomBytes, randomUUID } from "node:crypto";
import { afterEach, expect, it } from "vitest";
import { startEphemeralMigrationService, type EphemeralMigrationResult } from "./ephemeral-migration-service.js";
import { afterEach, expect, it, vi } from "vitest";
import { ownerRefusalCode, startEphemeralMigrationService, type EphemeralMigrationResult } from "./ephemeral-migration-service.js";
let service: Awaited<ReturnType<typeof startEphemeralMigrationService>> | undefined;
afterEach(async () => { await service?.close(); service = undefined; });
afterEach(async () => { await service?.close(); service = undefined; vi.restoreAllMocks(); });
const result = (): EphemeralMigrationResult => ({ counts: { files: 2 }, eligibility: { eligible: true, blockers: [] }, decisionSigningSecret: randomBytes(32).toString("base64") });
async function start(migrate: Parameters<typeof startEphemeralMigrationService>[0]["migrate"], timeoutMs?: number) {
const id = randomUUID(), token = randomBytes(32).toString("base64url"), commit = "a".repeat(40);
@@ -41,6 +41,51 @@ it("fails closed without exposing owner errors or credentials", async () => {
expect((await request("/export", "POST")).status).toBe(409);
});
it("reports an owner's structured refusal and the workspace it was moving, in the receipt and the deployment log", async () => {
const logged = vi.spyOn(console, "error").mockImplementation(() => {});
const workspaceId = randomUUID();
const refusal = "remote_workspace_migration_blocked:archived_git_source_unavailable,local_source_unsafe_or_missing";
const { request } = await start(async (_signal, phase) => {
phase(`workspace:${workspaceId}`);
throw new Error(refusal);
});
await service!.finished;
expect(await (await request("/status")).json()).toMatchObject({ state: "blocked", phase: `workspace:${workspaceId}`, failure: refusal });
expect(logged.mock.calls.map(call => JSON.parse(String(call[0]))))
.toEqual([{ event: "ephemeral_migration_blocked", phase: `workspace:${workspaceId}`, failure: refusal }]);
});
it("logs only the sanitized code for an arbitrary owner error", async () => {
const logged = vi.spyOn(console, "error").mockImplementation(() => {});
await start(async () => { throw new Error("provider rejected secret-value at https://private.invalid"); });
await service!.finished;
expect(logged.mock.calls.map(call => JSON.parse(String(call[0]))))
.toEqual([{ event: "ephemeral_migration_blocked", phase: "configuration", failure: "owner_migration_failed" }]);
});
it.each([
["remote_workspace_migration_blocked:workspace_recovery_unresolved", "remote_workspace_migration_blocked:workspace_recovery_unresolved"],
["active_execution_requires_drain", "active_execution_requires_drain"],
// Only known reason-list owners may carry text after a colon.
["provider:secretvalue", "owner_migration_failed"],
["a:b:c", "owner_migration_failed"],
// A known owner keeps its code when its reasons are malformed.
["remote_workspace_migration_blocked:", "remote_workspace_migration_blocked"],
["remote_workspace_migration_blocked:Secret", "remote_workspace_migration_blocked"],
["remote_workspace_migration_blocked:a:b", "remote_workspace_migration_blocked"],
["x".repeat(81), "owner_migration_failed"],
])("reports %s as %s", (message, expected) => {
expect(ownerRefusalCode(new Error(message))).toBe(expected);
});
it("keeps the owner and its first reasons when a refusal names too many", () => {
const reasons = Array.from({ length: 40 }, (_, index) => `reason_${String.fromCharCode(97 + index % 26)}${index >= 26 ? "_again" : ""}`);
const code = ownerRefusalCode(new Error(`remote_workspace_migration_blocked:${reasons.join(",")}`));
expect(code).toBe(`remote_workspace_migration_blocked:${[...reasons.slice(0, 31), "more_reasons_truncated"].join(",")}`);
expect(ownerRefusalCode(new Error(`remote_workspace_migration_blocked:${reasons.slice(0, 17).join(",")}`)))
.toBe(`remote_workspace_migration_blocked:${reasons.slice(0, 17).join(",")}`);
});
it("rejects incomplete eligibility even when a key was recovered", async () => {
const { request } = await start(async () => ({ ...result(), eligibility: { eligible: false, blockers: ["legacy_data"] } }));
await service!.finished;
@@ -7,6 +7,27 @@ export interface EphemeralMigrationResult {
decisionSigningSecret: string;
}
const OWNER_CODE = /^[a-z_]{1,80}$/;
// Owners that refuse with their fixed reason list as `owner_code:reason,...`.
// Only these may carry reasons; any other colon message is not an owner code.
const OWNER_REASON_LISTS = new Set(["remote_workspace_migration_blocked"]);
const MAX_REPORTED_REASONS = 32;
/** Reports an owner's refusal without echoing arbitrary error text. A known
* owner keeps its code when its reason list is malformed or too long. */
export function ownerRefusalCode(error: unknown) {
const message = error instanceof Error ? error.message : "";
if (OWNER_CODE.test(message)) return message;
const separator = message.indexOf(":");
const owner = message.slice(0, separator);
if (separator < 0 || !OWNER_REASON_LISTS.has(owner)) return "owner_migration_failed";
const reasons = message.slice(separator + 1).split(",");
if (!reasons.every(reason => OWNER_CODE.test(reason))) return owner;
return reasons.length > MAX_REPORTED_REASONS
? `${owner}:${[...reasons.slice(0, MAX_REPORTED_REASONS - 1), "more_reasons_truncated"].join(",")}`
: `${owner}:${reasons.join(",")}`;
}
/** A dedicated maintenance process, never mounted on the ordinary app router.
* Cloud supplies a fresh attempt token and keeps tenant routing closed. Only
* the authenticated export transfers the original key to its durable vault. */
@@ -59,9 +80,11 @@ export async function startEphemeralMigrationService(input: {
} catch (error) {
// Owner codes are safe diagnostics. Never echo arbitrary SDK errors,
// credential-bearing URLs, file contents or stack traces through HTTP.
const code = error instanceof Error ? error.message : "owner_migration_failed";
failure = /^[a-z_]{1,80}$/.test(code) ? code : "owner_migration_failed";
failure = ownerRefusalCode(error);
state = "blocked";
// The maintenance process has no other log. Record the same fixed codes
// so the provider's deployment log names the refusal too.
console.error(JSON.stringify({ event: "ephemeral_migration_blocked", phase, failure }));
} finally {
// Successful export authority expires at the original deadline too.
// A failed migration has no export authority to retain.