mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-25 16:14:26 +01:00
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - Hosted stacks move from a volume to volume-free storage, and the
move reports a code for each blocked item
> - Three native codes each cover several unrelated conditions
> - An operator or a fix agent cannot tell from the code which condition
holds, so stuck stacks stay stuck
> - This pull request names the exact condition next to each code,
without changing what either path accepts
> - The benefit is that the next pass says what to fix
## Linked Issues or Issue Description
**What happened?**
A stack reports
`workspaces:native_workspace_migration_identity_unproven`,
`native_controllers:artifact_unproven` and
`native_controllers:archive_source_unsettled` on every pass. Each code
is thrown from a check with up to eleven separate conditions, so the
report cannot say which saved state blocks the move.
**Expected behavior**
Each blocked item names the failing condition, and the online and
offline paths accept the same data as before.
**Steps to reproduce**
1. Save a paperclip_runner session whose resume run has no workspace
sync descriptor, then migrate its workspace.
2. Or archive a failed controller online while its coordinator holds a
lease.
3. Before this change, the reports are only
`native_workspace_migration_identity_unproven` or
`archive_source_unsettled`.
**Paperclip version or commit**
master at b2a12fab49.
## What Changed
- `inspectNativeWorkspaceMigration` throws
`native_workspace_migration_identity_rebound`, `_unsynced`,
`_other_workspace` or `_path_invalid` instead of one code. The online
pass and offline maintenance both see the same named code.
- `assertSettledControllerArchiveSource` throws
`NativeControllerArchiveSourceUnsettled` with a state
(`coordinator_missing`, `coordinator_leased`,
`coordinator_retry_scheduled`, `coordinator_unsettled`,
`coordinator_changed`, `finalization_busy`, `task_active`,
`session_selection_changed`, `run_changed`, `turn_active`,
`resume_source_changed`, `controller_files_changed`,
`controller_fingerprint_missing`). The message stays
`native_controller_archive_source_unsettled`.
- `prestageNativeControllers` keeps the existing outcome and count, and
also reports `archive_source_unsettled:<state>`. For `artifact_unproven`
it also reports `artifact_unproven:<run status>_run`, the same
`code:state` form that workspace details use.
- Previous-release story: no persisted state changes. Only error names
and report details change.
## Verification
- Red: on master the new unit test
(`native-workspace-migration.test.ts`, 4 cases) and the archive and
artifact assertions in `native-controller-migration.integration.test.ts`
fail.
- Green: `npx vitest run
src/services/native-runtime/native-workspace-migration.test.ts
src/services/native-runtime/native-controller-migration.integration.test.ts
src/services/native-runtime/native-harness-filesystem-independence.integration.test.ts
src/services/remote-workspaces.integration.test.ts` (297 passed).
- `pnpm typecheck` in `server` passes.
## Risks
- Low. Acceptance rules do not change. A dashboard that matches the
exact text `native_workspace_migration_identity_unproven` sees the new
names instead.
## Model Used
- Claude Opus 5.5 (`claude-opus-5-5`), Claude Code agent with tool use
and code execution.
## Checklist
- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
86 lines
6.7 KiB
TypeScript
86 lines
6.7 KiB
TypeScript
import path from "node:path";
|
|
import { and, eq, sql } from "drizzle-orm";
|
|
import { executionWorkspaces, heartbeatRuns, workspaceOperations, type Db } from "@paperclipai/db";
|
|
import { parseNativeExecutionInput } from "../../vendor/paperclip-runner/index.js";
|
|
import { findNativeSessionResumeRun } from "./native-session-resume.js";
|
|
import { readNativeWorkspaceSyncReference } from "./native-workspace-sync.js";
|
|
|
|
const SCHEMA = "paperclip.native-workspace-migration.v1";
|
|
const object = (value: unknown): Record<string, unknown> => value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
|
|
const absolute = (value: unknown): value is string => typeof value === "string" && value !== "/"
|
|
&& !value.includes("\0") && path.posix.isAbsolute(value) && path.posix.normalize(value) === value;
|
|
const uuid = (value: unknown): value is string => typeof value === "string" && /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(value);
|
|
type Workspace = Pick<typeof executionWorkspaces.$inferSelect, "companyId" | "id">;
|
|
type SessionBinding = { sourceRunId: string; agentId: string; issueId: string; sessionId: string; logicalCwd: string };
|
|
export type NativeWorkspaceMigration = { schema: typeof SCHEMA; remoteCwd: string; sessions: SessionBinding[] };
|
|
|
|
export async function inspectNativeWorkspaceMigration(db: Db, workspace: Workspace): Promise<NativeWorkspaceMigration | null> {
|
|
const rows = await db.execute<{ agentId: string; issueId: string; sessionId: string; createdAt: Date }>(sql`
|
|
select s.agent_id as "agentId", r.native_issue_id as "issueId", r.native_session_id as "sessionId", r.created_at as "createdAt"
|
|
from agent_task_sessions s join heartbeat_runs r on r.id = s.last_run_id
|
|
and r.company_id = s.company_id and r.agent_id = s.agent_id
|
|
where s.company_id = ${workspace.companyId} and s.adapter_type = 'paperclip_runner'
|
|
and r.native_issue_id is not null and r.native_session_id is not null
|
|
and r.runner_profile_json#>>'{nativeExecutionInput,binding,executionWorkspaceId}' = ${workspace.id}
|
|
order by s.id limit 1001`);
|
|
if (rows.length > 1000) throw new Error("native_workspace_migration_session_limit");
|
|
const sessions: SessionBinding[] = [];
|
|
let remoteCwd: string | null = null;
|
|
for (const row of rows) {
|
|
const source = await findNativeSessionResumeRun(db, { companyId: workspace.companyId, agentId: row.agentId,
|
|
issueId: row.issueId, normalizedSessionId: row.sessionId, beforeCreatedAt: new Date(row.createdAt), includeProgressBarrier: true });
|
|
if (!source) continue;
|
|
const execution = parseNativeExecutionInput(source.runnerProfileJson.nativeExecutionInput);
|
|
const [saved] = await db.select({ sync: sql<unknown>`${heartbeatRuns.runnerProfileJson}->'nativeWorkspaceSync'` })
|
|
.from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, workspace.companyId), eq(heartbeatRuns.id, source.id)));
|
|
const sync = readNativeWorkspaceSyncReference(saved?.sync);
|
|
if (execution.binding.executionWorkspaceId !== workspace.id || execution.binding.companyId !== workspace.companyId
|
|
|| execution.binding.agentId !== row.agentId || execution.binding.issueId !== row.issueId
|
|
|| execution.session.normalizedSessionId !== row.sessionId) throw new Error("native_workspace_migration_identity_rebound");
|
|
if (!sync) throw new Error("native_workspace_migration_identity_unsynced");
|
|
if (sync.workspaceId !== workspace.id) throw new Error("native_workspace_migration_identity_other_workspace");
|
|
if (!absolute(execution.workspace.cwd) || !absolute(sync.remoteCwd)) throw new Error("native_workspace_migration_identity_path_invalid");
|
|
if (remoteCwd && remoteCwd !== sync.remoteCwd) throw new Error("native_workspace_migration_remote_path_conflict");
|
|
remoteCwd = sync.remoteCwd;
|
|
sessions.push({ sourceRunId: source.id, agentId: row.agentId, issueId: row.issueId, sessionId: row.sessionId, logicalCwd: execution.workspace.cwd });
|
|
}
|
|
return remoteCwd ? { schema: SCHEMA, remoteCwd, sessions } : null;
|
|
}
|
|
|
|
export async function readNativeWorkspaceMigration(db: Pick<Db, "select">, workspace: Workspace) {
|
|
const [row] = await db.select({ workspaceMetadata: executionWorkspaces.metadata, metadata: workspaceOperations.metadata, operationId: workspaceOperations.id })
|
|
.from(executionWorkspaces).leftJoin(workspaceOperations, and(
|
|
eq(workspaceOperations.companyId, executionWorkspaces.companyId), eq(workspaceOperations.executionWorkspaceId, executionWorkspaces.id),
|
|
sql`${workspaceOperations.id} = case when ${executionWorkspaces.metadata}->'nativeWorkspaceMigration'->>'operationId' ~ '^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$'
|
|
then (${executionWorkspaces.metadata}->'nativeWorkspaceMigration'->>'operationId')::uuid end`,
|
|
eq(workspaceOperations.phase, "remote_workspace_migration"), eq(workspaceOperations.status, "succeeded"),
|
|
)).where(and(eq(executionWorkspaces.companyId, workspace.companyId), eq(executionWorkspaces.id, workspace.id)));
|
|
if (!row?.workspaceMetadata?.nativeWorkspaceMigration) return null;
|
|
const migration = object(row.metadata?.nativeSessionContinuity);
|
|
if (object(row.workspaceMetadata.nativeWorkspaceMigration).schema !== SCHEMA || !row.operationId || row.metadata?.schema !== "paperclip.remote-workspace-migration.v1" || !uuid(row.metadata.snapshotId)
|
|
|| migration.schema !== SCHEMA || !absolute(migration.remoteCwd) || !Array.isArray(migration.sessions)
|
|
|| !migration.sessions.length || migration.sessions.length > 1000
|
|
|| !migration.sessions.every(value => {
|
|
const session = object(value);
|
|
return [session.sourceRunId, session.agentId, session.issueId, session.sessionId].every(uuid) && absolute(session.logicalCwd);
|
|
})) throw new Error("native_workspace_migration_receipt_invalid");
|
|
return { ...(migration as NativeWorkspaceMigration), operationId: row.operationId };
|
|
}
|
|
|
|
export function nativeWorkspaceMigrationMarker(operationId: string) {
|
|
return { schema: SCHEMA, operationId };
|
|
}
|
|
|
|
export function migratedNativeExecutionCwd(migration: NativeWorkspaceMigration | null, input: { agentId: string; issueId: string; sessionId: string }) {
|
|
return migration?.sessions.find(session => session.agentId === input.agentId && session.issueId === input.issueId
|
|
&& session.sessionId === input.sessionId)?.logicalCwd ?? null;
|
|
}
|
|
|
|
export async function canRestoreMigratedNativeSession(db: Db, input: {
|
|
companyId: string; workspaceId: string; agentId: string; issueId: string; sessionId: string; logicalCwd: string | null; remoteCwd: string;
|
|
}) {
|
|
if (input.logicalCwd === null) return false;
|
|
const migration = await readNativeWorkspaceMigration(db, { companyId: input.companyId, id: input.workspaceId });
|
|
return migration?.remoteCwd === input.remoteCwd && migratedNativeExecutionCwd(migration, input) === input.logicalCwd;
|
|
}
|