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>
105 lines
8.3 KiB
TypeScript
105 lines
8.3 KiB
TypeScript
import { and, eq, inArray, or, sql } from "drizzle-orm";
|
|
import { createHash } from "node:crypto";
|
|
import { agentTaskSessions, heartbeatRuns, issues, nativeRunFinalizations, type Db } from "@paperclipai/db";
|
|
import { nativeSha256 } from "./canonical.js";
|
|
import { findNativeSessionResumeRun } from "./native-session-resume.js";
|
|
import { readLegacyNativeControllerArchiveDigests, readLegacyNativeControllerArchiveSource } from "./native-controller-migration.js";
|
|
import { tryLockNativeWorkspaceFinalization } from "./native-workspace-finalization-ownership.js";
|
|
import { archiveFailedLegacyNativeController } from "./native-controller-archive.js";
|
|
import type { StorageService } from "../../storage/types.js";
|
|
import { assertOriginalHarnessVolumeSource, type OriginalHarnessVolumeCapability } from "./native-harness-original-volume.js";
|
|
|
|
export type SettledControllerArchiveOwner = {
|
|
kind: "settled_controller_archive";
|
|
companyId: string; issueId: string; agentId: string; runId: string; sessionId: string;
|
|
selectedSessionId: string; selectedLastRunId: string;
|
|
profileDigest: string; coordinatorDigest: string; controllerDigest: string | null; supervisorDigest: string | null;
|
|
filesystemIndependence?: { source: OriginalHarnessVolumeCapability; scopeDigest: string; factsDigest: string };
|
|
};
|
|
const fileDigest = (value: string) => createHash("sha256").update(value).digest("hex");
|
|
export class NativeControllerArchiveSourceUnsettled extends Error {
|
|
constructor(readonly state: string) { super("native_controller_archive_source_unsettled"); }
|
|
}
|
|
|
|
export function nativeControllerArchiveProfileDigest(value: unknown) {
|
|
const profile = value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
|
|
return nativeSha256({ nativeExecutionInput: profile.nativeExecutionInput ?? null, nativeToolContractFingerprint: profile.nativeToolContractFingerprint ?? null,
|
|
sessionCheckpoint: profile.sessionCheckpoint ?? null, nativeControllerRecovery: profile.nativeControllerRecovery ?? null });
|
|
}
|
|
|
|
export function nativeControllerArchiveCoordinatorDigest(value: {
|
|
phase: string; resultId: string | null; controllerBootId: string | null; controllerGeneration: number; recoveryState: unknown;
|
|
}) {
|
|
return nativeSha256({ phase: value.phase, resultId: value.resultId, controllerBootId: value.controllerBootId,
|
|
controllerGeneration: value.controllerGeneration, recoveryState: value.recoveryState });
|
|
}
|
|
|
|
export async function assertSettledControllerArchiveSource(db: Db, owner: SettledControllerArchiveOwner) {
|
|
function fail(state: string): never { throw new NativeControllerArchiveSourceUnsettled(state); }
|
|
if (owner.controllerDigest === null && !owner.filesystemIndependence) fail("controller_fingerprint_missing");
|
|
if (owner.filesystemIndependence) {
|
|
await assertOriginalHarnessVolumeSource(owner.filesystemIndependence.source);
|
|
await (await import("./native-harness-filesystem-independence.js")).assertNativeHarnessFilesystemArchiveSource(db, owner);
|
|
}
|
|
await db.execute(sql`set local lock_timeout = '1s'`);
|
|
if (!await tryLockNativeWorkspaceFinalization(db, owner)) fail("finalization_busy");
|
|
const [task] = await db.select().from(issues).where(and(eq(issues.companyId, owner.companyId), eq(issues.id, owner.issueId))).for("update");
|
|
if (!task || task.executionRunId || task.checkoutRunId) fail("task_active");
|
|
const [coordinator] = await db.select().from(nativeRunFinalizations).where(and(
|
|
eq(nativeRunFinalizations.companyId, owner.companyId), eq(nativeRunFinalizations.issueId, owner.issueId),
|
|
eq(nativeRunFinalizations.runId, owner.runId))).for("update");
|
|
if (!coordinator) fail("coordinator_missing");
|
|
if (coordinator.leaseOwner) fail("coordinator_leased");
|
|
if (coordinator.nextAttemptAt) fail("coordinator_retry_scheduled");
|
|
if (!(coordinator.phase === "terminal_failure" || coordinator.phase === "committed" && coordinator.resultId)) fail("coordinator_unsettled");
|
|
if (nativeControllerArchiveCoordinatorDigest(coordinator) !== owner.coordinatorDigest) fail("coordinator_changed");
|
|
const [selection] = await db.select().from(agentTaskSessions).where(and(eq(agentTaskSessions.id, owner.selectedSessionId),
|
|
eq(agentTaskSessions.companyId, owner.companyId), eq(agentTaskSessions.agentId, owner.agentId),
|
|
eq(agentTaskSessions.lastRunId, owner.selectedLastRunId))).for("share");
|
|
const [selectedRun] = await db.select({ createdAt: heartbeatRuns.createdAt }).from(heartbeatRuns).where(and(
|
|
eq(heartbeatRuns.id, owner.selectedLastRunId), eq(heartbeatRuns.companyId, owner.companyId), eq(heartbeatRuns.agentId, owner.agentId),
|
|
eq(heartbeatRuns.nativeIssueId, owner.issueId), eq(heartbeatRuns.nativeSessionId, owner.sessionId)));
|
|
const [run] = await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.id, owner.runId),
|
|
eq(heartbeatRuns.companyId, owner.companyId), eq(heartbeatRuns.agentId, owner.agentId), eq(heartbeatRuns.nativeIssueId, owner.issueId),
|
|
eq(heartbeatRuns.nativeSessionId, owner.sessionId), eq(heartbeatRuns.runtimeMode, "native"))).for("share");
|
|
if (!selection || !selectedRun) fail("session_selection_changed");
|
|
if (!run?.finishedAt
|
|
|| (owner.filesystemIndependence ? !["failed", "succeeded"].includes(run.status)
|
|
|| run.status === "succeeded" && (coordinator.phase !== "committed" || !coordinator.resultId) : run.status !== "failed")
|
|
|| nativeControllerArchiveProfileDigest(run.runnerProfileJson) !== owner.profileDigest) fail("run_changed");
|
|
const [active] = await db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, owner.companyId),
|
|
inArray(heartbeatRuns.status, ["queued", "running"]), or(eq(heartbeatRuns.nativeIssueId, owner.issueId),
|
|
eq(heartbeatRuns.issueId, owner.issueId), eq(heartbeatRuns.nativeSessionId, owner.sessionId)))).limit(1);
|
|
if (active) fail("turn_active");
|
|
const selected = await findNativeSessionResumeRun(db, { companyId: owner.companyId, agentId: owner.agentId, issueId: owner.issueId,
|
|
normalizedSessionId: owner.sessionId, beforeCreatedAt: selectedRun.createdAt, includeProgressBarrier: true });
|
|
if (!selected || selected.id !== owner.runId || nativeControllerArchiveProfileDigest(selected.runnerProfileJson) !== owner.profileDigest) fail("resume_source_changed");
|
|
const material = await readLegacyNativeControllerArchiveDigests(selected);
|
|
if ((material.controllerDigest ?? null) !== owner.controllerDigest
|
|
|| (material.supervisorDigest ?? null) !== owner.supervisorDigest) fail("controller_files_changed");
|
|
}
|
|
|
|
export async function archiveSettledFailedNativeController(db: Db, input: {
|
|
selected: { id: string; lastRunId: string; companyId: string; agentId: string; issueId: string; sessionId: string };
|
|
source: NonNullable<Awaited<ReturnType<typeof findNativeSessionResumeRun>>>;
|
|
storage: StorageService; signal: AbortSignal;
|
|
}) {
|
|
input.signal.throwIfAborted();
|
|
const { selected, source } = input;
|
|
const material = await readLegacyNativeControllerArchiveSource(source);
|
|
if (material.controller === undefined) return "source_already_absent" as const;
|
|
const [coordinator] = await db.select().from(nativeRunFinalizations).where(and(eq(nativeRunFinalizations.companyId, selected.companyId),
|
|
eq(nativeRunFinalizations.issueId, selected.issueId), eq(nativeRunFinalizations.runId, source.id)));
|
|
if (!coordinator) throw new NativeControllerArchiveSourceUnsettled("coordinator_missing");
|
|
const owner: SettledControllerArchiveOwner = { kind: "settled_controller_archive", companyId: selected.companyId,
|
|
issueId: selected.issueId, agentId: selected.agentId, runId: source.id, sessionId: selected.sessionId,
|
|
selectedSessionId: selected.id, selectedLastRunId: selected.lastRunId,
|
|
profileDigest: nativeControllerArchiveProfileDigest(source.runnerProfileJson), coordinatorDigest: nativeControllerArchiveCoordinatorDigest(coordinator),
|
|
controllerDigest: fileDigest(material.controller), supervisorDigest: material.supervisor === undefined ? null : fileDigest(material.supervisor) };
|
|
await db.transaction(tx => assertSettledControllerArchiveSource(tx as unknown as Db, owner));
|
|
input.signal.throwIfAborted();
|
|
await archiveFailedLegacyNativeController(db, { companyId: selected.companyId, issueId: selected.issueId, runId: source.id,
|
|
controller: material.controller, supervisor: material.supervisor, storage: input.storage, onlineOwner: owner, signal: input.signal });
|
|
return "archived_failed" as const;
|
|
}
|