fix(cloud): name why an online workspace source scope is unproven (#22644)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - A hosted server moves each local workspace to shared storage in
bounded online passes while it serves work
> - Before a Git or managed workspace moves online, the server must
prove which tasks and projects can write its files
> - Staging stacks stay blocked with many
`online_workspace_source_scope_unproven` workspaces after repeated
passes
> - The proof has more than 30 separate checks, and the pass does not
say which check failed
> - This pull request names the failed check for each workspace
> - The benefit is that the next pass on a blocked stack shows the exact
cause, so the right fix can follow

## Linked Issues or Issue Description

Refs #22270, #22294

**What happened?**
After repeated online passes, staging stacks report
`workspaces:online_workspace_source_scope_unproven` for 26 to 49
workspaces each. The code does not say which part of the source proof
failed. Most of the same workspaces also report
`overlapping_workspace_requires_maintenance`, because a workspace
without a proven scope cannot treat its Git siblings as one unit.

**Expected behavior**
The pass names the part of the source proof that failed for each
workspace.

**Steps to reproduce**
1. Create a nested Git wrapper workspace with a linked worktree.
2. Remove the linked worktree directory without `git worktree prune`.
3. Run the online inventory. It reports only
`online_workspace_source_scope_unproven`.

## What Changed

- `explainOnlineWorkspaceSource` and `explainOnlineOrdinarySource`
return `{ unproven: <code> }` for each failed check.
`inspectOnlineWorkspaceSource` and `inspectOnlineOrdinarySource` keep
their old `null` result.
- Inventory returns `sourceScopeUnproven` with the code. The `reasons`
list does not change.
- The online pass reports the code as `workspaces:source_scope_<code>`
next to `workspaces:online_workspace_source_scope_unproven`.
- The linked-worktree reader throws `workspace_git_link_stale` when a
registered worktree directory is gone, and
`workspace_git_links_exceeded` above 256 links. Both still reject the
proof.
- Codes include `git_link_stale`, `git_link_unregistered`,
`git_links_unreadable`, `member_status_unsupported`,
`member_task_binding_missing`, `member_locator_mismatch`,
`member_git_expiration_pending`, `source_keys_exceeded`,
`members_exceeded`, `foreign_alias`, `companion_recovery_unresolved`,
`companion_copyback_unresolved`, `ordinary_member_nested` and others.

## Verification

- `cd server && npx vitest run
src/services/remote-workspace-migration.test.ts
src/services/remote-workspace-online-source.test.ts
src/services/remote-workspace-cohort-migration.test.ts
src/services/workspace-git-source-roots.test.ts
src/services/online-durable-data-migration.test.ts
src/services/online-durable-data-migration-postgres.test.ts
src/services/finalized-workspace-recovery-migration.test.ts` (embedded
PostgreSQL): 7 files, 407 tests passed.
- Red/green: the linked-worktree test now checks the code for five cases
(unregistered, wrong backlink, wrong pointer, symlinked backlink,
stale). On `origin/master` the result has no `sourceScopeUnproven`
field. The new pass test fails on `origin/master` because the pass has
no `source_scope_` key.
- `pnpm --filter @paperclipai/server typecheck`: passed.

## Risks

- Low risk. No proof accepts more than before. Each check returns the
same accept or reject result. Only the reported code is new.
- The pass result gets new `workspaces:source_scope_<code>` keys.
Readers that count deferral keys see more keys.

> 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

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

## Checklist

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

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

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
DottaandClaude Opus 5.5 authored and GitHub committed 2026-11-23 12:56:12 -06:00
1 parent 348749305c
commit e856a607ed
7 files changed
+120 -57

No files matched your search

@@ -373,6 +373,18 @@ describe("online durable-data migration pass", () => {
expect(result.deferred).toMatchObject({ "workspaces:pending_inspection": 1 });
});
it("names why a workspace source scope is unproven", async () => {
const fixture = owners({
localWorkspaces: async () => [workspace(1), workspace(2)],
inventoryWorkspace: async (_db: Db, input: { workspaceId: string }) => input.workspaceId === "w1"
? { reasons: ["online_workspace_source_scope_unproven"], sourceScopeUnproven: "git_link_stale" }
: { reasons: ["online_workspace_source_scope_unproven"], sourceScopeUnproven: "/private path" },
});
const result = await runOnlineDurableDataMigration(db, { budgetMs: 60_000 }, fixture.owners);
expect(result.deferred).toMatchObject({ "workspaces:online_workspace_source_scope_unproven": 2, "workspaces:source_scope_git_link_stale": 1 });
expect(JSON.stringify(result)).not.toContain("private");
});
it("migrates an idle workspace through the online owner with a bounded source-lock wait, never the offline mode", async () => {
const migrateWorkspace = vi.fn(async () => ({ alreadyMigrated: true, reasons: [] }));
const fixture = owners({ localWorkspaces: async () => [workspace(1)], migrateWorkspace });
@@ -43,7 +43,7 @@ type Owners = {
workspaceCompanies: typeof listLocalWorkspaceCompanies;
workspaceOperations: (db: Db, input: { companyId: string; signal: AbortSignal }) => Promise<{ reconciled: number; held: Array<{ reason: string }> }>;
localWorkspaces: typeof listLocalWorkspaces;
inventoryWorkspace: (db: Db, input: { companyId: string; workspaceId: string }) => Promise<{ reasons: string[] }>;
inventoryWorkspace: (db: Db, input: { companyId: string; workspaceId: string }) => Promise<{ reasons: string[]; sourceScopeUnproven?: string }>;
migrateWorkspace: (input: { db: Db; storage: StorageService; companyId: string; workspaceId: string; apply: true;
signal: AbortSignal; sourceLockWaitMs: number }) => Promise<{ alreadyMigrated: boolean; reasons: string[] }>;
nativeHarnessBackups: typeof prestageNativeHarnessBackups;
@@ -255,7 +255,9 @@ async function migrate(db: Db, input: { budgetMs: number; now?: () => number },
for (const { companyId, workspaceId } of rows) {
let reasons: string[];
try {
reasons = (await owners.inventoryWorkspace(db, { companyId, workspaceId })).reasons;
const inventory = await owners.inventoryWorkspace(db, { companyId, workspaceId });
reasons = inventory.sourceScopeUnproven && /^[a-z_]{1,60}$/.test(inventory.sourceScopeUnproven)
? [...inventory.reasons, `source_scope_${inventory.sourceScopeUnproven}`] : inventory.reasons;
if (!reasons.length) {
const work = owners.migrateWorkspace({ db, storage, companyId, workspaceId, apply: true, signal,
sourceLockWaitMs: WORKSPACE_SOURCE_LOCK_WAIT_MS });
+58 -33
View File
@@ -4,7 +4,7 @@ import { createHash } from "node:crypto";
import { and, eq, gt, inArray, ne, sql } from "drizzle-orm";
import { executionWorkspaces, heartbeatRuns, issueRecoveryActions, type Db } from "@paperclipai/db";
import { resolvePaperclipInstanceRoot } from "../home-paths.js";
import { inspectImportedWorkspaceSourcePaths, inspectOnlineOrdinarySource, physicalPath, requiresOnlineOrdinarySource, type WorkspaceSourceScope } from "./remote-workspace-migration-tree.js";
import { explainOnlineOrdinarySource, inspectImportedWorkspaceSourcePaths, physicalPath, requiresOnlineOrdinarySource, type WorkspaceSourceScope } from "./remote-workspace-migration-tree.js";
import { workspaceSourceIdentities } from "./workspace-source-lock.js";
import { readNestedWorkspaceGitSourceRoots, readWorkspaceGitLinkedRoots, readWorkspaceGitSourceRoots, type WorkspaceGitSourceRoots } from "./workspace-git-source-roots.js";
import { inspectOnlineLegacyWorkspaceRecoveryHold, inspectOnlineLegacyWorkspaceRecoverySource, type OnlineLegacyWorkspaceRecoveryHold } from "./online-legacy-workspace-recovery.js";
@@ -45,7 +45,7 @@ async function companion(db: ReadDb, workspace: Workspace, runs: CompanionRun[])
const sources: LegacyWorkspaceRecoverySource[] = [];
for (const run of runs.filter(run => run.state === "prepared")) {
const source = await inspectOnlineLegacyWorkspaceRecoverySource(db, { workspace, runId: run.id });
if (!source) return null;
if (!source) return "companion_copyback_unresolved";
sources.push(source);
}
const issueIds = [...new Set([workspace.sourceIssueId, ...runs.map(run => run.issueId)].filter((id): id is string => Boolean(id)))];
@@ -56,23 +56,45 @@ async function companion(db: ReadDb, workspace: Workspace, runs: CompanionRun[])
const holds: Array<OnlineLegacyWorkspaceRecoveryHold & { actionId: string }> = [];
for (const recovery of actions) {
const hold = await inspectOnlineLegacyWorkspaceRecoveryHold(db, { workspace, recovery });
if (!hold) return null;
if (!hold) return "companion_recovery_unresolved";
holds.push({ actionId: recovery.id, ...hold });
}
return { workspaceId: workspace.id, sources, holds, recoveryIssueIds: issueIds };
}
export async function inspectOnlineWorkspaceSource(db: ReadDb, workspace: Workspace): Promise<OnlineWorkspaceSource | null> {
const result = await explainOnlineWorkspaceSource(db, workspace);
return "unproven" in result ? null : result;
}
function gitLinkUnproven(error: unknown) {
const message = error instanceof Error ? error.message : "";
return message === "workspace_git_link_stale" ? "git_link_stale" : message === "workspace_git_links_exceeded" ? "git_links_exceeded" : "git_links_unreadable";
}
function memberUnproven(row: Workspace) {
if (!row.sourceIssueId) return "member_task_binding_missing";
if (row.cwd && row.providerRef && row.cwd !== row.providerRef) return "member_locator_mismatch";
if (!["active", "idle", "in_review", "archived"].includes(row.status)) return "member_status_unsupported";
if (row.metadata?.remoteWorkspace) return "member_already_remote";
if (hasPendingGitExpiration(row)) return "member_git_expiration_pending";
return null;
}
export async function explainOnlineWorkspaceSource(db: ReadDb, workspace: Workspace): Promise<OnlineWorkspaceSource | { unproven: string }> {
const unproven = (code: string) => ({ unproven: code });
const cwd = workspace.cwd ?? workspace.providerRef;
if (!cwd || !path.isAbsolute(cwd) || !["local_fs", "git_worktree"].includes(workspace.providerType)) return null;
const ordinary = await inspectOnlineOrdinarySource(db, workspace);
if (!cwd || !path.isAbsolute(cwd) || !["local_fs", "git_worktree"].includes(workspace.providerType)) return unproven("locator_unsupported");
const explained = await explainOnlineOrdinarySource(db, workspace);
const ordinary = explained && !("unproven" in explained) ? explained : null;
const ordinaryUnproven = explained && "unproven" in explained ? explained.unproven : null;
let nestedGit: WorkspaceGitSourceRoots[] = [];
if (ordinary) {
const marker = await fs.lstat(path.join(ordinary.root, ".git")).catch((error: NodeJS.ErrnoException) => {
if (error.code !== "ENOENT") throw error; return null;
});
if (!marker) {
try { nestedGit = await readNestedWorkspaceGitSourceRoots(ordinary.root); } catch { return null; }
try { nestedGit = await readNestedWorkspaceGitSourceRoots(ordinary.root); } catch { return unproven("nested_git_unreadable"); }
if (!nestedGit.length) return { ...ordinary, kind: "ordinary", projectIds: ordinary.projectId ? [ordinary.projectId] : [], companions: [] };
}
}
@@ -82,50 +104,53 @@ export async function inspectOnlineWorkspaceSource(db: ReadDb, workspace: Worksp
issueIds: [...ordinary.issueIds], unownedPaths: [], git: null } : await workspaceSourceIdentities(workspace.companyId, cwd);
for (const source of nestedGit) {
const nested = await workspaceSourceIdentities(workspace.companyId, source.root);
if (!nested.git || nested.git.fingerprint !== source.fingerprint) return null;
if (!nested.git || nested.git.fingerprint !== source.fingerprint) return unproven("nested_git_changed");
selected.projectIds = [...new Set([...selected.projectIds, ...nested.projectIds])].sort();
selected.issueIds = [...new Set([...selected.issueIds, ...nested.issueIds])].sort();
selected.unownedPaths = [...new Set([...selected.unownedPaths, ...nested.unownedPaths])].sort();
}
} catch { return null; }
} catch { return unproven("git_identity_unreadable"); }
const captureRoot = await physicalPath(cwd), gitSources = selected.git ? [selected.git] : nestedGit;
if (!gitSources.length || selected.git && selected.git.root !== captureRoot || selected.unownedPaths.length || !workspace.sourceIssueId
|| workspace.cwd && workspace.providerRef && workspace.cwd !== workspace.providerRef) return null;
if (!gitSources.length) return unproven(ordinaryUnproven ?? "not_git_source");
if (selected.git && selected.git.root !== captureRoot) return unproven("git_root_mismatch");
if (selected.unownedPaths.length) return unproven("unowned_path");
if (!workspace.sourceIssueId) return unproven("task_binding_missing");
if (workspace.cwd && workspace.providerRef && workspace.cwd !== workspace.providerRef) return unproven("locator_mismatch");
for (const source of gitSources) {
const head = await fs.lstat(path.join(source.gitDirectory.path, "HEAD")).catch((error: NodeJS.ErrnoException) => {
if (error.code !== "ENOENT") throw error; return null;
});
if (!head || !head.isFile() && !head.isSymbolicLink()) return null;
if (!head || !head.isFile() && !head.isSymbolicLink()) return unproven("git_head_missing");
}
const linkedSources = new Map<string, Awaited<ReturnType<typeof readWorkspaceGitLinkedRoots>>[number]>();
try {
for (const source of gitSources) {
for (const proof of await readWorkspaceGitLinkedRoots(source)) {
const existing = linkedSources.get(proof.commonDirectory.path);
if (existing && JSON.stringify(existing) !== JSON.stringify(proof)) return null;
if (existing && JSON.stringify(existing) !== JSON.stringify(proof)) return unproven("git_links_conflict");
linkedSources.set(proof.commonDirectory.path, proof);
}
}
for (const proof of linkedSources.values()) {
for (const link of proof.links) {
const linked = await workspaceSourceIdentities(workspace.companyId, link.root.path);
if (!linked.git || linked.git.gitDirectory.path !== link.gitDirectory.path) return null;
if (!linked.git || linked.git.gitDirectory.path !== link.gitDirectory.path) return unproven("git_link_changed");
selected.projectIds = [...new Set([...selected.projectIds, ...linked.projectIds])].sort();
selected.issueIds = [...new Set([...selected.issueIds, ...linked.issueIds])].sort();
selected.unownedPaths = [...new Set([...selected.unownedPaths, ...linked.unownedPaths])].sort();
}
}
} catch { return null; }
if (selected.unownedPaths.length) return null;
} catch (error) { return unproven(gitLinkUnproven(error)); }
if (selected.unownedPaths.length) return unproven("unowned_path");
const selectedFingerprint = createHash("sha256").update(JSON.stringify([gitSources, [...linkedSources.values()]])).digest("hex");
const entry = await fs.lstat(cwd);
const rows = await db.select().from(executionWorkspaces).where(and(eq(executionWorkspaces.companyId, workspace.companyId),
inArray(executionWorkspaces.providerType, ["local_fs", "git_worktree"]))).orderBy(executionWorkspaces.id).limit(1001);
if (rows.length > 1000) return null;
if (rows.length > 1000) return unproven("company_records_exceeded");
const nodes: Array<{ row: Workspace; identities: Identities; fingerprint: string | null }> = [];
for (const row of rows) {
const paths = localWorkspaceSourcePaths(row);
if (!paths.length || paths.some(cwd => !path.isAbsolute(cwd))) return null;
if (!paths.length || paths.some(cwd => !path.isAbsolute(cwd))) return unproven("member_locator_invalid");
try {
const identities = paths[0] === captureRoot ? { ...selected, projectIds: [...selected.projectIds], issueIds: [...selected.issueIds] }
: await workspaceSourceIdentities(workspace.companyId, paths[0]);
@@ -135,7 +160,7 @@ export async function inspectOnlineWorkspaceSource(db: ReadDb, workspace: Worksp
identities.issueIds = [...new Set([...identities.issueIds, ...alternate.issueIds])].sort();
}
nodes.push({ row, identities, fingerprint: paths[0] === captureRoot ? selectedFingerprint : identities.git?.fingerprint ?? null });
} catch { return null; }
} catch { return unproven("member_unreadable"); }
}
const projectIds = new Set(selected.projectIds), physicalIssueIds = new Set(selected.issueIds), aliases = new Set<string>();
const importedChildren: NonNullable<OnlineWorkspaceSource["importedChildren"]> = [];
@@ -143,12 +168,12 @@ export async function inspectOnlineWorkspaceSource(db: ReadDb, workspace: Worksp
for (const child of await inspectImportedWorkspaceSourcePaths(db, workspace,
[...linkedSources.values()].flatMap(proof => proof.links.map(link => link.root.path)))) {
const identities = await workspaceSourceIdentities(workspace.companyId, child.sourcePath);
if (identities.unownedPaths.length) return null;
if (identities.unownedPaths.length) return unproven("imported_child_unowned");
for (const id of identities.projectIds) projectIds.add(id);
for (const id of identities.issueIds) physicalIssueIds.add(id);
importedChildren.push({ ...child, gitFingerprint: identities.git?.fingerprint ?? null });
}
} catch { return null; }
} catch { return unproven("imported_child_unreadable"); }
for (;;) {
let changed = false;
for (const node of nodes) {
@@ -157,9 +182,8 @@ export async function inspectOnlineWorkspaceSource(db: ReadDb, workspace: Worksp
&& !intersects(node.identities.issueIds, physicalIssueIds)
&& !(node.row.projectId && projectIds.has(node.row.projectId))
&& !(node.row.sourceIssueId && physicalIssueIds.has(node.row.sourceIssueId))) continue;
if (!node.row.sourceIssueId || node.row.cwd && node.row.providerRef && node.row.cwd !== node.row.providerRef
|| !["active", "idle", "in_review", "archived"].includes(node.row.status)
|| node.row.metadata?.remoteWorkspace || hasPendingGitExpiration(node.row)) return null;
const member = memberUnproven(node.row);
if (member) return unproven(member);
aliases.add(node.row.id); changed = true;
for (const id of node.identities.projectIds) projectIds.add(id);
for (const id of node.identities.issueIds) physicalIssueIds.add(id);
@@ -167,14 +191,15 @@ export async function inspectOnlineWorkspaceSource(db: ReadDb, workspace: Worksp
}
if (!changed) break;
}
if (!aliases.has(workspace.id) || aliases.size > 256) return null;
if (!aliases.has(workspace.id)) return unproven("self_excluded");
if (aliases.size > 256) return unproven("members_exceeded");
const included = nodes.filter(node => aliases.has(node.row.id));
const registeredRoots = await Promise.all([...included.flatMap(node => localWorkspaceSourcePaths(node.row)),
...importedChildren.map(child => child.sourcePath)].map(physicalPath));
if ([...linkedSources.values()].some(proof => proof.links.some(link => !registeredRoots.some(root =>
link.root.path === root || link.root.path.startsWith(root + path.sep))))) return null;
link.root.path === root || link.root.path.startsWith(root + path.sep))))) return unproven("git_link_unregistered");
const issueIds = [...new Set([...physicalIssueIds, ...included.map(node => node.row.sourceIssueId!)])].sort();
if (issueIds.length + projectIds.size > 128) return null;
if (issueIds.length + projectIds.size > 128) return unproven("source_keys_exceeded");
const instance = await physicalPath(resolvePaperclipInstanceRoot());
const gitSourceRoots = [...[...projectIds].map(id => path.join(instance, "projects", workspace.companyId, id)),
...issueIds.flatMap(id => ["isolated-workspaces", "isolated-workspace-attempts", "isolated-repository-sources"].map(kind =>
@@ -188,21 +213,21 @@ export async function inspectOnlineWorkspaceSource(db: ReadDb, workspace: Worksp
.orderBy(executionWorkspaces.id).limit(256);
for (const row of foreign) {
for (const cwd of localWorkspaceSourcePaths(row)) {
if (!path.isAbsolute(cwd)) return null;
if (!path.isAbsolute(cwd)) return unproven("foreign_locator_invalid");
try {
if (owned(await physicalPath(cwd))) return null;
if (owned(await physicalPath(cwd))) return unproven("foreign_alias");
const git = await readWorkspaceGitSourceRoots(cwd, { ancestors: true });
if (git && [git.gitDirectory.path, git.commonDirectory.path, ...git.objectDirectories.map(root => root.path)].some(owned)) return null;
} catch { return null; }
if (git && [git.gitDirectory.path, git.commonDirectory.path, ...git.objectDirectories.map(root => root.path)].some(owned)) return unproven("foreign_git_alias");
} catch { return unproven("foreign_unreadable"); }
}
}
if (foreign.length < 256) break;
if (page === 39) return null;
if (page === 39) return unproven("foreign_records_exceeded");
after = foreign.at(-1)!.id;
}
const recipe = readGitCacheRestoration(workspace);
if (recipe && (!recipe.restoredAt || recipe.contents && !recipe.contentsRestoredAt
|| recipe.restorePoint && !recipe.restorePoint.expiredAt && !recipe.restorePoint.appliedAt)) return null;
|| recipe.restorePoint && !recipe.restorePoint.expiredAt && !recipe.restorePoint.appliedAt)) return unproven("git_restoration_pending");
const runs = await db.select({ id: heartbeatRuns.id, issueId: heartbeatRuns.nativeIssueId,
workspaceId: sql<string>`${heartbeatRuns.runnerProfileJson}->'nativeWorkspaceSync'->>'workspaceId'`,
state: sql<string>`${heartbeatRuns.runnerProfileJson}->'nativeWorkspaceSync'->>'state'` }).from(heartbeatRuns).where(and(
@@ -219,7 +244,7 @@ export async function inspectOnlineWorkspaceSource(db: ReadDb, workspace: Worksp
const companions: OnlineWorkspaceSource["companions"] = [], settledPreparedWorkspaceIds: string[] = [], settledRecoveryIssueIds = new Set<string>();
for (const node of included) {
const proof = await companion(db, node.row, runsByWorkspace.get(node.row.id) ?? []);
if (!proof) return null;
if (typeof proof === "string") return unproven(proof);
companions.push({ workspaceId: proof.workspaceId, sources: proof.sources, holds: proof.holds });
if (proof.sources.length) settledPreparedWorkspaceIds.push(proof.workspaceId);
for (const id of proof.recoveryIssueIds) settledRecoveryIssueIds.add(id);
@@ -85,7 +85,29 @@ export async function requiresOnlineOrdinarySource(workspace: Workspace): Promis
return false;
}
export async function inspectOnlineOrdinarySource(db: ReadDb, workspace: Workspace): Promise<Omit<WorkspaceSourceScope, "importedChildren"> | null> {
type OrdinarySource = Omit<WorkspaceSourceScope, "importedChildren">;
export async function inspectOnlineOrdinarySource(db: ReadDb, workspace: Workspace): Promise<OrdinarySource | null> {
const result = await explainOnlineOrdinarySource(db, workspace);
return result && !("unproven" in result) ? result : null;
}
function ordinaryMemberUnproven(row: { cwd: string | null; providerRef: string | null; providerType: string; repoUrl: string | null;
branchName: string | null; sourceIssueId: string | null; strategyType: string; mode: string; status: string;
metadata: Record<string, unknown> | null }, root: string, isolatedIssueId: string | null) {
if (row.cwd?.startsWith(`${root}/`)) return "ordinary_member_nested";
if (row.cwd !== root || row.providerRef && row.providerRef !== root) return "ordinary_member_locator_mismatch";
if (row.providerType !== "local_fs" || row.repoUrl || row.branchName) return "ordinary_member_git";
if (!row.sourceIssueId || isolatedIssueId && row.sourceIssueId !== isolatedIssueId) return "ordinary_member_task_binding";
if (row.strategyType !== "project_primary" || !["isolated_workspace", "shared_workspace"].includes(row.mode)) return "ordinary_member_strategy_unsupported";
if (!["active", "idle", "in_review", "archived"].includes(row.status)) return "member_status_unsupported";
if (row.metadata?.remoteWorkspace) return "member_already_remote";
if (row.metadata?.gitCacheRestoration || row.metadata?.nestedCloneMigrationPending) return "ordinary_member_restoration_pending";
return null;
}
export async function explainOnlineOrdinarySource(db: ReadDb, workspace: Workspace): Promise<OrdinarySource | { unproven: string } | null> {
const unproven = (code: string) => ({ unproven: code });
if (!workspace.cwd || workspace.providerType !== "local_fs" || workspace.repoUrl || workspace.branchName) return null;
const root = await physicalPath(workspace.cwd);
const instance = await physicalPath(resolvePaperclipInstanceRoot());
@@ -96,11 +118,11 @@ export async function inspectOnlineOrdinarySource(db: ReadDb, workspace: Workspa
|| parts[0] === "isolated-workspace-attempts" && parts.length === 4 && /^[a-zA-Z0-9_-]+$/.test(parts[3]));
const projectId = await managedProjectSourceIdentity(workspace.companyId, root);
if (root !== workspace.cwd || !(isolated || projectId && path.dirname(root) === path.join(
instance, "projects", workspace.companyId, projectId))) return null;
instance, "projects", workspace.companyId, projectId))) return unproven("ordinary_root_unmanaged");
const entry = await fs.lstat(root).catch((error: NodeJS.ErrnoException) => {
if (error.code === "ENOENT") return null; throw error;
});
if (!entry?.isDirectory() || entry.isSymbolicLink()) return null;
if (!entry?.isDirectory() || entry.isSymbolicLink()) return unproven("ordinary_root_missing");
const columns = { id: executionWorkspaces.id, companyId: executionWorkspaces.companyId,
cwd: executionWorkspaces.cwd, providerRef: executionWorkspaces.providerRef, providerType: executionWorkspaces.providerType,
repoUrl: executionWorkspaces.repoUrl, branchName: executionWorkspaces.branchName, sourceIssueId: executionWorkspaces.sourceIssueId,
@@ -113,19 +135,15 @@ export async function inspectOnlineOrdinarySource(db: ReadDb, workspace: Workspa
const rows = await db.select(columns).from(executionWorkspaces).where(and(
eq(executionWorkspaces.companyId, workspace.companyId),
inArray(executionWorkspaces.providerType, ["local_fs", "git_worktree"]))).limit(1001);
if (rows.length > 1000) return null;
if (rows.length > 1000) return unproven("company_records_exceeded");
const aliases: typeof rows = [];
for (const row of rows) {
const paths = localWorkspaceSourcePaths(row);
let physical: string[];
try { physical = await Promise.all(paths.map(physicalPath)); } catch { return null; }
try { physical = await Promise.all(paths.map(physicalPath)); } catch { return unproven("member_unreadable"); }
if (!physical.some(cwd => overlaps(root, cwd))) continue;
if (row.cwd !== root || row.providerRef && row.providerRef !== root
|| row.providerType !== "local_fs" || row.repoUrl || row.branchName || !row.sourceIssueId
|| isolated && row.sourceIssueId !== workspace.sourceIssueId
|| row.strategyType !== "project_primary" || !["isolated_workspace", "shared_workspace"].includes(row.mode)
|| !["active", "idle", "in_review", "archived"].includes(row.status) || row.metadata?.remoteWorkspace
|| row.metadata?.gitCacheRestoration || row.metadata?.nestedCloneMigrationPending) return null;
const member = ordinaryMemberUnproven(row, root, isolated ? workspace.sourceIssueId : null);
if (member) return unproven(member);
aliases.push(row);
}
let after: string | undefined;
@@ -138,14 +156,15 @@ export async function inspectOnlineOrdinarySource(db: ReadDb, workspace: Workspa
)).orderBy(executionWorkspaces.id).limit(256);
for (const row of foreign) {
for (const cwd of localWorkspaceSourcePaths(row)) {
try { if (overlaps(root, await physicalPath(cwd))) return null; } catch { return null; }
try { if (overlaps(root, await physicalPath(cwd))) return unproven("foreign_alias"); } catch { return unproven("foreign_unreadable"); }
}
}
if (foreign.length < 256) break;
if (page === 39) return null;
if (page === 39) return unproven("foreign_records_exceeded");
after = foreign.at(-1)!.id;
}
if (!aliases.some(row => row.id === workspace.id) || aliases.length > 64) return null;
if (!aliases.some(row => row.id === workspace.id)) return unproven("self_excluded");
if (aliases.length > 64) return unproven("members_exceeded");
return { root, projectId, device: entry.dev, inode: entry.ino,
issueIds: [...new Set(aliases.map(row => row.sourceIssueId!))].sort(), workspaceIds: aliases.map(row => row.id).sort() };
}
@@ -1897,7 +1897,8 @@ describe.skipIf(!support.supported)("remote workspace migration", () => {
await expect(migrateRemoteWorkspace({ db, storage, ...f, apply: true })).rejects.toThrow("online_workspace_source_scope_unproven");
expect(readRemoteWorkspaceAuthority((await workspace(f.workspaceId)).metadata)).toBeNull();
});
it.each(["unregistered", "backlink", "pointer", "symlink-backlink"])("refuses a nested Git wrapper with an unproven linked %s", async mode => {
it.each([["unregistered", "git_link_unregistered"], ["backlink", "git_links_unreadable"], ["pointer", "git_links_unreadable"],
["symlink-backlink", "git_links_unreadable"], ["stale", "git_link_stale"]])("refuses a nested Git wrapper with an unproven linked %s and names it", async (mode, code) => {
const { f, nested } = await nestedGitWrapperFixture(), issueId = randomUUID();
await db.insert(issues).values({ id: issueId, companyId: f.companyId, title: "Linked wrapper" });
const cwd = path.join(resolvePaperclipInstanceRoot(), "isolated-workspaces", f.companyId, issueId), alias = path.join(cwd, "nested");
@@ -1908,7 +1909,9 @@ describe.skipIf(!support.supported)("remote workspace migration", () => {
if (mode === "backlink") await fs.writeFile(backlink, path.join(alias, "wrong-marker") + "\n");
if (mode === "pointer") await fs.writeFile(path.join(alias, ".git"), `gitdir: ${path.join(admin, "wrong")}\n`);
if (mode === "symlink-backlink") { await fs.rename(backlink, backlink + ".real"); await fs.symlink(backlink + ".real", backlink); }
expect(await inventoryRemoteWorkspaceMigration(db, f)).toMatchObject({ eligible: false, reasons: ["online_workspace_source_scope_unproven"] });
if (mode === "stale") await fs.rm(alias, { recursive: true, force: true });
expect(await inventoryRemoteWorkspaceMigration(db, f)).toMatchObject({ eligible: false, reasons: ["online_workspace_source_scope_unproven"],
sourceScopeUnproven: code });
await expect(migrateRemoteWorkspace({ db, storage, ...f, apply: true })).rejects.toThrow("online_workspace_source_scope_unproven");
expect(await db.select().from(workspaceOperations)).toHaveLength(0);
expect(await db.select().from(executionWorkspaceSnapshots)).toHaveLength(0);
@@ -25,7 +25,7 @@ import { readNativeWorkspaceSyncReference } from "./native-runtime/native-worksp
import { isLegacyWorkspaceTaskRelated, readLegacyWorkspaceRecoveryAllocations, LEGACY_WORKSPACE_RECOVERY_MIGRATION, type LegacyWorkspaceRecoverySource } from "./legacy-workspace-recovery-migration.js";
import { createNestedWorkspaceImportVerifier, onlineOrdinarySourceBlockers, offlineWorkspaceMigrationBlockers, prepareNestedWorkspaceImports, validateImportedWorkspaceChildren, workspaceMigrationLayoutBlockers, type WorkspaceMigrationCohort } from "./remote-workspace-migration-tree.js";
import { inspectOnlineWorkspaceSource, requiresOnlineWorkspaceSource, type OnlineWorkspaceSource } from "./online-workspace-source.js";
import { explainOnlineWorkspaceSource, inspectOnlineWorkspaceSource, requiresOnlineWorkspaceSource, type OnlineWorkspaceSource } from "./online-workspace-source.js";
import { withWorkspaceSourceLocks, withIndependentWorkspaceSourceLocks, IsolatedRepositorySourceBusy } from "./workspace-source-lock.js";
import { inspectOnlineLegacyWorkspaceRecoverySource, inspectOnlineLegacyWorkspaceRecoveryHold, isTaskDispositionRecovery, lockOnlineLegacyWorkspaceRecoverySources, ONLINE_LEGACY_WORKSPACE_PRESERVATION, type OnlineLegacyWorkspaceRecoveryHold } from "./online-legacy-workspace-recovery.js";
import { inspectNativeWorkspaceMigration, nativeWorkspaceMigrationMarker } from "./native-runtime/native-workspace-migration.js";
@@ -344,11 +344,12 @@ async function inspect(db: ReadDb, input: { companyId: string; workspaceId: stri
export async function inventoryRemoteWorkspaceMigration(db: Db, input: { companyId: string; workspaceId: string; writersStopped?: boolean }) {
const [workspace] = !input.writersStopped ? await db.select().from(executionWorkspaces).where(and(
eq(executionWorkspaces.companyId, input.companyId), eq(executionWorkspaces.id, input.workspaceId))) : [];
const onlineSource = workspace && !readRemoteWorkspaceAuthority(workspace.metadata)
? await inspectOnlineWorkspaceSource(db, workspace) ?? undefined : undefined;
const result = await inspect(db, { ...input, onlineSource, onlineSourceUnproven: Boolean(workspace && !onlineSource
&& !readRemoteWorkspaceAuthority(workspace.metadata) && await requiresOnlineWorkspaceSource(workspace)) });
const explained = workspace && !readRemoteWorkspaceAuthority(workspace.metadata) ? await explainOnlineWorkspaceSource(db, workspace) : undefined;
const onlineSource = explained && !("unproven" in explained) ? explained : undefined;
const onlineSourceUnproven = Boolean(workspace && explained && !onlineSource && await requiresOnlineWorkspaceSource(workspace));
const result = await inspect(db, { ...input, onlineSource, onlineSourceUnproven });
return { companyId: input.companyId, workspaceId: input.workspaceId, eligible: result.reasons.length === 0,
...(onlineSourceUnproven && explained && "unproven" in explained ? { sourceScopeUnproven: explained.unproven } : {}),
alreadyMigrated: Boolean(result.authority), reasons: result.reasons, localPath: result.workspace.cwd ?? result.workspace.providerRef,
source: result.source, operationId: typeof result.marker.operationId === "string" ? result.marker.operationId : null,
snapshotId: result.authority?.snapshotId ?? null };
@@ -154,7 +154,7 @@ export async function readWorkspaceGitLinkedRoots(source: WorkspaceGitSourceRoot
const target = path.join(commonDirectory.path, "worktrees"), present = await entry(target);
if (!present) { results.push({ commonDirectory, directory: null, links: [], metadata: [] }); continue; }
const directory = await directoryIdentity(target), names = (await fs.readdir(directory.path)).sort();
if (names.length > 256) throw invalid();
if (names.length > 256) throw new Error("workspace_git_links_exceeded");
const links: Array<{ root: Identity; gitDirectory: Identity }> = [], metadata: Metadata[] = [];
for (const name of names) {
const gitDirectory = await directoryIdentity(path.join(directory.path, name));
@@ -163,6 +163,7 @@ export async function readWorkspaceGitLinkedRoots(source: WorkspaceGitSourceRoot
if (!backlink || !common || path.resolve(gitDirectory.path, metadataPath(common.text)) !== commonDirectory.path) throw invalid();
const marker = path.resolve(gitDirectory.path, metadataPath(backlink.text));
if (path.basename(marker) !== ".git") throw invalid();
if (!await entry(path.dirname(marker))) throw new Error("workspace_git_link_stale");
const root = await directoryIdentity(path.dirname(marker)), pointer = await readMetadata(marker, 4096);
if (marker !== path.join(root.path, ".git") || !pointer?.text.startsWith("gitdir: ")
|| path.resolve(root.path, metadataPath(pointer.text.slice(8))) !== gitDirectory.path) throw invalid();