diff --git a/doc/DATABASE.md b/doc/DATABASE.md index e29d899e303..2b4450de2cc 100644 --- a/doc/DATABASE.md +++ b/doc/DATABASE.md @@ -767,4 +767,17 @@ Migration [0337_exotic_proemial_gods.sql](../packages/db/src/migrations/0337_exo Migration [0338_absurd_vengeance.sql](../packages/db/src/migrations/0338_absurd_vengeance.sql) adds internal `execution_workspace_repository_access` provenance. Company/canonical-root source entries retain execution-workspace and source-project identities; reader entries retain the exact admitted run, task, agent and responsible user. New repository receipts also record their root at creation; legacy receipts receive no inferred origin. Shared project-source entries retain which physical owners require workspace write authority. Current admission, selection, requests and publication check the current task’s writer against those owners; retained past readers and file APIs still require only read authority. Genuine isolated copies retain source read access without requiring shared-folder write access. An existing linked worktree can recover a missing isolated-copy proof only after Git registration and its captured source owner are verified. Configured local sibling copies retain deny-only task/project source ownership on the bound task root before materialization; ordinary repository clones create no isolation proof. The shared root fence checks every reader against every source before admission and future publication, including tasks without repository requests. File APIs apply the same source privacy without writing provenance. These entries grant no authority and have no workspace or run deletion cascade; unavailable retained identity fails closed. Automatic provenance release is deferred, so a newly incompatible permission scope requires a separate physical root. +Git-source capture checks the actual common Git storage directory and verified +checkout owners. Separately stored metadata does not make its parent a checkout. +When Git cannot identify the primary checkout, the service verifies company-known +configured, execution, and retained roots against that metadata identity. Ordinary +repositories and registered worktrees avoid this fallback scan. + +After source authorization and retained-reader checks pass, the existing +`source` and `project_source` kinds retain ownership on shared Git storage. +Removing the original checkout cannot release private committed files in surviving +worktrees. These records grant no authority and create no isolation proof. Denied +source captures leave no new records. Worktree realization uses a verified checkout +as its Git command directory, including when metadata sits inside another repository. + No migration scans or copies existing agent home directories. Keep admitted native descriptors and recovery references until compatible controllers finish their persistence obligations. See [the architecture rollout contract](plans/2026-10-09-task-workspaces.md). diff --git a/maps/agent-access-map/workspaces.md b/maps/agent-access-map/workspaces.md index 23284cf1736..74d7fce034c 100644 --- a/maps/agent-access-map/workspaces.md +++ b/maps/agent-access-map/workspaces.md @@ -147,6 +147,11 @@ File reads also enforce retained source privacy after local copy, configuration move/removal, reopen, and project deletion. A task assignment or repository receipt does not grant access to private files from another physical owner. +Authorized Git-source capture also retains ownership on the actual shared Git +storage. Source checks use verified checkout identities, including company-known +owners when separate metadata has no primary-checkout registration. Removing that +checkout does not release its private committed files in surviving worktrees. + ## `closure` Review: `baseline`. diff --git a/server/src/__tests__/task-workspace-repositories-trust.test.ts b/server/src/__tests__/task-workspace-repositories-trust.test.ts index a4faaa29312..c2477043879 100644 --- a/server/src/__tests__/task-workspace-repositories-trust.test.ts +++ b/server/src/__tests__/task-workspace-repositories-trust.test.ts @@ -423,6 +423,171 @@ const support = await getEmbeddedPostgresTestSupport(); expect(entries.filter(entry => entry.kind === "reader")).toHaveLength(peer ? 1 : 0); }); + it.each(["primary", "linked"] as const)("does not probe unrelated company Git paths when the normal %s source is identified", async kind => { + const f = await fixture(), exec = promisify(execFileCallback); + await exec("git", ["init", "--initial-branch=main", f.admission.cwd]); + const privateCwd = path.join(f.admission.cwd, "private"); await mkdir(privateCwd); + await writeFile(path.join(privateCwd, "secret.txt"), "Private tracked bytes\n"); + await exec("git", ["-C", f.admission.cwd, "add", "."]); + await exec("git", ["-C", f.admission.cwd, "-c", "user.name=Fixture", "-c", "user.email=fixture@example.test", "commit", "-m", "source"]); + let sourceCwd = f.admission.cwd; + if (kind === "linked") { + sourceCwd = path.join(root, `${f.issueId}-linked-normal`); + await exec("git", ["-C", f.admission.cwd, "worktree", "add", "-b", "linked-normal", sourceCwd]); + } + const [project] = await db.insert(projects).values({ companyId: f.companyId, name: "Private nested owner", visibility: "private" }).returning(); + await db.insert(projectWorkspaces).values({ companyId: f.companyId, projectId: project.id, name: "Nested source", cwd: privateCwd }); + const unrelated = path.join(root, `${f.issueId}-unrelated-candidate`); await mkdir(unrelated); + await db.insert(executionWorkspaces).values({ companyId: f.companyId, name: "Unrelated task files", cwd: unrelated, + mode: "shared_workspace", strategyType: "operator_directory" }); + const wrapper = path.join(root, `${f.issueId}-git-bin`); await mkdir(wrapper); + const probeLog = path.join(wrapper, "probed.txt"); + await writeFile(probeLog, ""); + const realGit = (await exec("sh", ["-c", "command -v git"])).stdout.trim(); + await writeFile(path.join(wrapper, "git"), `#!/bin/sh +if [ "$1" = "-C" ] && [ "$2" = "$PROBE_UNRELATED" ]; then + printf 'unexpected Git probe\\n' >> "$PROBE_LOG" + exit 78 +fi +exec "$PROBE_REAL_GIT" "$@" +`, { mode: 0o755 }); + const previous = { PATH: process.env.PATH, PROBE_UNRELATED: process.env.PROBE_UNRELATED, + PROBE_LOG: process.env.PROBE_LOG, PROBE_REAL_GIT: process.env.PROBE_REAL_GIT }; + try { + vi.stubEnv("PATH", `${wrapper}${path.delimiter}${process.env.PATH}`); + vi.stubEnv("PROBE_UNRELATED", await realpath(unrelated)); + vi.stubEnv("PROBE_LOG", probeLog); vi.stubEnv("PROBE_REAL_GIT", realGit); + const input = { companyId: f.companyId, sourceCwd, actor: f.actor }; + await expect(assertIsolatedWorkspaceSourceReadAccess(db, input)).rejects.toThrow(/source project/); + await db.insert(projectAccessMembers).values([ + { companyId: f.companyId, projectId: project.id, subjectType: "agent", subjectId: f.agentId }, + { companyId: f.companyId, projectId: project.id, subjectType: "user", subjectId: f.userId }, + ]); + const captured = await assertIsolatedWorkspaceSourceReadAccess(db, input); + expect(captured.projectIds).toContain(project.id); + expect(await readFile(probeLog, "utf8")).toBe(""); + } finally { + for (const [name, value] of Object.entries(previous)) vi.stubEnv(name, value); + } + }); + + it.each(["unrelated", "metadata", "checkout", "linked_main", "linked_retained"] as const)("authorizes actual separate Git storage without inferring its parent (%s)", async owner => { + const f = await fixture(), exec = promisify(execFileCallback); + const storageParent = path.join(root, `${f.issueId}-storage`); + const metadata = path.join(storageParent, "metadata"), unrelated = path.join(storageParent, "private-task"); + await mkdir(unrelated, { recursive: true }); + await exec("git", ["init", "--initial-branch=main", "--separate-git-dir", metadata, f.admission.cwd]); + await writeFile(path.join(f.admission.cwd, "source.txt"), "Source bytes\n"); + await exec("git", ["-C", f.admission.cwd, "add", "."]); + await exec("git", ["-C", f.admission.cwd, "-c", "user.name=Fixture", "-c", "user.email=fixture@example.test", "commit", "-m", "source"]); + let sourceCwd = f.admission.cwd; + if (owner === "linked_main" || owner === "linked_retained") { + sourceCwd = path.join(root, `${f.issueId}-linked-source`); + await exec("git", ["-C", f.admission.cwd, "worktree", "add", "-b", "source-linked", sourceCwd]); + } + const [project] = await db.insert(projects).values({ companyId: f.companyId, name: "Private actual owner", visibility: "private" }).returning(); + const [configuration] = await db.insert(projectWorkspaces).values({ companyId: f.companyId, projectId: project.id, name: "Private source", + cwd: owner === "metadata" ? metadata : owner === "unrelated" ? unrelated : f.admission.cwd }).returning(); + if (owner === "linked_retained") { + const taskRoot = path.join(root, `${f.issueId}-different-task-root`); + await mkdir(taskRoot); + await db.update(executionWorkspaces).set({ cwd: taskRoot }).where(eq(executionWorkspaces.id, f.workspace.id)); + await projectService(db).removeWorkspace(project.id, configuration.id); + } + const input = { companyId: f.companyId, sourceCwd, actor: f.actor, copyKind: "repository" as const }; + if (owner !== "unrelated") { + await expect(assertIsolatedWorkspaceSourceReadAccess(db, input)).rejects.toThrow(/source project/); + await db.insert(projectAccessMembers).values([ + { companyId: f.companyId, projectId: project.id, subjectType: "agent", subjectId: f.agentId }, + { companyId: f.companyId, projectId: project.id, subjectType: "user", subjectId: f.userId }, + ]); + } + const captured = await assertIsolatedWorkspaceSourceReadAccess(db, input); + expect(captured.roots).toContain(await realpath(metadata)); + expect(captured.roots).toContain(await realpath(f.admission.cwd)); + expect(captured.roots).not.toContain(await realpath(storageParent)); + expect(captured.projectIds.includes(project.id)).toBe(owner !== "unrelated"); + }); + + it.each(["deleted_primary", "retained_reader"] as const)("retains separate metadata privacy across %s", async scenario => { + const f = await fixture(), exec = promisify(execFileCallback); + const storageParent = path.join(root, `${f.issueId}-deleted-primary-storage`); + const metadata = path.join(storageParent, "metadata"), linked = path.join(root, `${f.issueId}-surviving-linked`); + await mkdir(storageParent); + await exec("git", ["init", "--initial-branch=main", "--separate-git-dir", metadata, f.admission.cwd]); + await writeFile(path.join(f.admission.cwd, "private.txt"), "PRIVATE_PRIMARY_BYTES"); + await exec("git", ["-C", f.admission.cwd, "add", "."]); + await exec("git", ["-C", f.admission.cwd, "-c", "user.name=Fixture", "-c", "user.email=fixture@example.test", "commit", "-m", "private source"]); + await exec("git", ["-C", f.admission.cwd, "worktree", "add", "-b", "surviving-linked", linked]); + const [project] = await db.insert(projects).values({ companyId: f.companyId, name: "Deleted private primary", visibility: "private" }).returning(); + const [configuration] = await db.insert(projectWorkspaces).values({ companyId: f.companyId, projectId: project.id, name: "Private source", cwd: f.admission.cwd }).returning(); + const input = { companyId: f.companyId, sourceCwd: f.admission.cwd, actor: f.actor, copyKind: "repository" as const }; + await expect(assertIsolatedWorkspaceSourceReadAccess(db, input)).rejects.toThrow(/source project/); + expect(await db.select().from(executionWorkspaceRepositoryAccess).where(eq(executionWorkspaceRepositoryAccess.companyId, f.companyId))).toEqual([]); + const peer = scenario === "retained_reader" ? await standardPeer(f) : null; + if (peer) { + await db.update(executionWorkspaces).set({ cwd: metadata }).where(eq(executionWorkspaces.id, peer.workspace.id)); + await f.service.prepareForAdmission({ ...peer.admission, cwd: metadata }); + } + await db.insert(projectAccessMembers).values([ + { companyId: f.companyId, projectId: project.id, subjectType: "agent", subjectId: f.agentId }, + { companyId: f.companyId, projectId: project.id, subjectType: "user", subjectId: f.userId }, + ]); + if (peer) { + await expect(assertIsolatedWorkspaceSourceReadAccess(db, input)).rejects.toThrow(/source project/); + const before = await db.select().from(executionWorkspaceRepositoryAccess).where(eq(executionWorkspaceRepositoryAccess.companyId, f.companyId)); + expect(before.some(entry => entry.kind === "project_source" && entry.scopeId === project.id)).toBe(false); + await db.insert(projectAccessMembers).values([ + { companyId: f.companyId, projectId: project.id, subjectType: "agent", subjectId: peer.agentId }, + { companyId: f.companyId, projectId: project.id, subjectType: "user", subjectId: peer.userId }, + ]); + } + const captured = await assertIsolatedWorkspaceSourceReadAccess(db, input); + expect(captured.projectIds).toContain(project.id); + const metadataRows = await db.select().from(executionWorkspaceRepositoryAccess).where(eq(executionWorkspaceRepositoryAccess.companyId, f.companyId)); + expect(metadataRows).toContainEqual(expect.objectContaining({ canonicalCwd: await realpath(metadata), kind: "project_source", scopeId: project.id })); + expect(metadataRows.some(entry => entry.kind === "isolated_copy")).toBe(false); + if (peer) return; + const firstCopy = path.join(root, `${f.issueId}-authorized-copy`); + await retainIsolatedWorkspaceSourceAccess(db, { ...input, captured, targetCwd: firstCopy, issueId: f.issueId }); + await exec("git", ["clone", "--no-hardlinks", f.admission.cwd, firstCopy]); + await projectService(db).removeWorkspace(project.id, configuration.id); + await rm(f.admission.cwd, { recursive: true, force: true }); + await db.delete(projectAccessMembers).where(eq(projectAccessMembers.projectId, project.id)); + expect(await readFile(path.join(linked, "private.txt"), "utf8")).toBe("PRIVATE_PRIMARY_BYTES"); + await expect(assertIsolatedWorkspaceSourceReadAccess(db, { ...input, sourceCwd: linked })).rejects.toThrow(/source project/); + }); + + it.each(["ordinary", "linked"] as const)("requires real linked-worktree identity with separate Git metadata (%s)", async kind => { + const f = await fixture(), exec = promisify(execFileCallback); + const metadata = path.join(root, `${f.issueId}-metadata`); + await exec("git", ["init", "--initial-branch=main", "--separate-git-dir", metadata, f.admission.cwd]); + await writeFile(path.join(f.admission.cwd, "source.txt"), "Source bytes\n"); + await exec("git", ["-C", f.admission.cwd, "add", "."]); + await exec("git", ["-C", f.admission.cwd, "-c", "user.name=Fixture", "-c", "user.email=fixture@example.test", "commit", "-m", "source"]); + const [project] = await db.insert(projects).values({ companyId: f.companyId, name: "Protected separate checkout", visibility: "private", + executionWorkspacePolicy: { authorizationPolicy: { assignmentPolicy: { mode: "protected" } } } }).returning(); + await db.insert(projectWorkspaces).values({ companyId: f.companyId, projectId: project.id, name: "Source", cwd: f.admission.cwd }); + await db.insert(projectAccessMembers).values([ + { companyId: f.companyId, projectId: project.id, subjectType: "agent", subjectId: f.agentId }, + { companyId: f.companyId, projectId: project.id, subjectType: "user", subjectId: f.userId }, + ]); + const captured = await assertIsolatedWorkspaceSourceReadAccess(db, { companyId: f.companyId, sourceCwd: f.admission.cwd, actor: f.actor }); + const targetCwd = kind === "ordinary" ? f.admission.cwd : path.join(f.admission.cwd, "linked"); + if (kind === "linked") await exec("git", ["-C", f.admission.cwd, "worktree", "add", "-b", "linked", targetCwd]); + await writeFile(path.join(targetCwd, "source.txt"), "Preserved dirty edit\n"); + const retain = () => retainIsolatedWorkspaceSourceAccess(db, { companyId: f.companyId, sourceCwd: f.admission.cwd, + targetCwd, actor: f.actor, issueId: f.issueId, captured, phase: "verified" }); + if (kind === "ordinary") await expect(retain()).rejects.toThrow(/not a verified Git worktree|protected/); + else { + await expect(retain()).resolves.toBeUndefined(); + await expect(assertExecutionWorkspaceRootWriteAccess(db, { companyId: f.companyId, cwd: targetCwd, actor: f.actor, issueId: f.issueId })).resolves.toBeUndefined(); + } + const entries = await db.select().from(executionWorkspaceRepositoryAccess).where(eq(executionWorkspaceRepositoryAccess.companyId, f.companyId)); + expect(entries.some(entry => entry.kind === "isolated_copy")).toBe(kind === "linked"); + expect(await readFile(path.join(targetCwd, "source.txt"), "utf8")).toBe("Preserved dirty edit\n"); + }); + it.each(["upgrade", "interrupted_creation", "unrelated_owner"] as const)("validates a registered dirty worktree without completed copy proof after %s", async scenario => { const f = await fixture(), exec = promisify(execFileCallback); const git = async (...args: string[]) => (await exec("git", ["-C", f.admission.cwd, ...args])).stdout; diff --git a/server/src/__tests__/workspace-runtime.test.ts b/server/src/__tests__/workspace-runtime.test.ts index 418c9dad8df..23e5fd89c72 100644 --- a/server/src/__tests__/workspace-runtime.test.ts +++ b/server/src/__tests__/workspace-runtime.test.ts @@ -794,6 +794,41 @@ describe("ensureServerWorkspaceLinksCurrent", () => { }); describe("realizeExecutionWorkspace", () => { + it.each(["primary", "linked"] as const)("realizes from a %s checkout with separate Git metadata without adopting its unrelated parent", async sourceKind => { + const root = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-separate-owner-")); + try { + const wrongOwner = path.join(root, "wrong-owner"), primary = path.join(root, "source"); + const common = path.join(wrongOwner, "separate-metadata"); + await fs.mkdir(wrongOwner); + await runGit(wrongOwner, ["init", "-b", "main"]); + await runGit(wrongOwner, ["config", "user.email", "test@example.test"]); + await runGit(wrongOwner, ["config", "user.name", "Test"]); + await fs.writeFile(path.join(wrongOwner, "wrong.txt"), "UNRELATED_PARENT_BYTES"); + await runGit(wrongOwner, ["add", "."]); + await runGit(wrongOwner, ["commit", "-m", "unrelated"]); + await execFileAsync("git", ["init", "-b", "main", "--separate-git-dir", common, primary]); + await runGit(primary, ["config", "user.email", "test@example.test"]); + await runGit(primary, ["config", "user.name", "Test"]); + await fs.writeFile(path.join(primary, "source.txt"), "AUTHORIZED_SOURCE_BYTES"); + await runGit(primary, ["add", "."]); + await runGit(primary, ["commit", "-m", "source"]); + const source = sourceKind === "primary" ? primary : path.join(root, "linked-source"); + if (sourceKind === "linked") await runGit(primary, ["worktree", "add", "-b", "linked-source", source]); + const wrongHead = await readGit(wrongOwner, ["rev-parse", "HEAD"]); + const expectedHead = await readGit(source, ["rev-parse", "HEAD"]); + const workspace = await realizeWorktreeForTest(source, "HEAD"); + expect(await readGit(workspace.cwd, ["rev-parse", "HEAD"])).toBe(expectedHead); + expect(await fs.readFile(path.join(workspace.cwd, "source.txt"), "utf8")).toBe("AUTHORIZED_SOURCE_BYTES"); + await expect(fs.stat(path.join(workspace.cwd, "wrong.txt"))).rejects.toMatchObject({ code: "ENOENT" }); + expect(await readGit(wrongOwner, ["rev-parse", "HEAD"])).toBe(wrongHead); + expect(await readGit(wrongOwner, ["branch", "--list", workspace.branchName!])).toBe(""); + expect(await fs.realpath(path.resolve(workspace.cwd, await readGit(workspace.cwd, ["rev-parse", "--git-common-dir"])))).toBe(await fs.realpath(common)); + const reused = await realizeWorktreeForTest(source, "HEAD"); + expect(reused.cwd).toBe(workspace.cwd); + expect(reused.created).toBe(false); + } finally { await fs.rm(root, { recursive: true, force: true }); } + }); + it("defaults new git worktrees to freshly fetched origin/master", async () => { const sourceRepo = await createTempRepo("master"); const remoteDir = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-worktree-remote-")); diff --git a/server/src/services/execution-workspace-repositories.ts b/server/src/services/execution-workspace-repositories.ts index eaa03262867..d3cfcf5de3c 100644 --- a/server/src/services/execution-workspace-repositories.ts +++ b/server/src/services/execution-workspace-repositories.ts @@ -359,9 +359,11 @@ async function verifiedIsolatedWorktree(cwd: string, allowedOwnerRoots?: Set { /** Match realization's checkout and common repository roots. A configured cwd * may be a subdirectory or linked worktree while Git copies a broader tree. */ type WorkspaceSourceCopyKind = "linked_worktree" | "repository"; -async function isolatedWorkspaceSourceRoots(sourceCwd: string, copyKind: WorkspaceSourceCopyKind = "linked_worktree"): Promise { - const git = async (cwd: string, argument: string) => (await execFile("git", ["-C", cwd, "rev-parse", argument], { +async function isolatedWorkspaceSourceRoots(db: Db | DbTransaction, companyId: string, sourceCwd: string, copyKind: WorkspaceSourceCopyKind = "linked_worktree"): Promise<{ roots: string[]; commonRoot: string }> { + const git = async (cwd: string, ...args: string[]) => (await execFile("git", ["-C", cwd, ...args], { timeout: 30_000, env: { ...process.env, GIT_NO_LAZY_FETCH: "1" }, })).stdout.trim(); const localRoot = await fs.realpath(sourceCwd); - if (copyKind === "repository" && await git(sourceCwd, "--is-bare-repository") === "true") { - const gitRoot = await fs.realpath(path.resolve(sourceCwd, await git(sourceCwd, "--absolute-git-dir"))); - return [...new Set([localRoot, gitRoot])]; + if (copyKind === "repository" && await git(sourceCwd, "rev-parse", "--is-bare-repository") === "true") { + const gitRoot = await fs.realpath(path.resolve(sourceCwd, await git(sourceCwd, "rev-parse", "--absolute-git-dir"))); + return { roots: [...new Set([localRoot, gitRoot])], commonRoot: gitRoot }; } - const checkoutRoot = await fs.realpath(path.resolve(await git(sourceCwd, "--show-toplevel"))); - const commonDir = await git(checkoutRoot, "--git-common-dir"); - const ownerRoot = await fs.realpath(path.dirname(path.resolve(checkoutRoot, commonDir))); - return [...new Set(copyKind === "repository" ? [localRoot, checkoutRoot, ownerRoot] : [checkoutRoot, ownerRoot])]; + const checkoutRoot = await fs.realpath(path.resolve(await git(sourceCwd, "rev-parse", "--show-toplevel"))); + const commonRoot = await fs.realpath(path.resolve(checkoutRoot, await git(checkoutRoot, "rev-parse", "--git-common-dir"))); + const roots = new Set(copyKind === "repository" ? [localRoot, checkoutRoot, commonRoot] : [checkoutRoot, commonRoot]); + // An ordinary primary checkout identifies its own metadata directly. Linked + // worktrees can identify that primary through Git's registered checkout list. + let primaryIdentified = commonRoot === path.join(checkoutRoot, ".git") + && await fs.realpath(await git(checkoutRoot, "rev-parse", "--absolute-git-dir")) === commonRoot; + const considerPrimary = async (candidatePath: string): Promise => { + const candidate = await fs.realpath(candidatePath).catch(() => null); + if (!candidate || candidate === checkoutRoot || candidate === commonRoot) return false; + try { + const candidateGitRoot = await fs.realpath(await git(candidate, "rev-parse", "--absolute-git-dir")); + if (candidateGitRoot !== commonRoot) return false; + const candidateCheckout = await fs.realpath(await git(candidate, "rev-parse", "--show-toplevel")); + const candidateCommon = await fs.realpath(path.resolve(candidate, await git(candidate, "rev-parse", "--git-common-dir"))); + const relative = path.relative(candidateCheckout, candidate); + if (relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative) + && candidateCommon === commonRoot) { + roots.add(candidateCheckout); + return true; + } + } catch { /* Unverified candidates cannot identify another checkout owner. */ } + return false; + }; + if (!primaryIdentified) { + const registrations = (await git(checkoutRoot, "worktree", "list", "--porcelain", "-z")).split("\0"); + for (const registration of registrations) { + if (registration.startsWith("worktree ") && await considerPrimary(registration.slice("worktree ".length))) { + primaryIdentified = true; + break; + } + } + } + if (!primaryIdentified) { + // Separate Git metadata has no backlink to its main checkout. Only this + // layout needs company-owned current/retained candidates; never infer an + // owner from the metadata directory's parent or probe unrelated history for + // already-identified ordinary repositories. + const candidates = new Set(); + const configured = await db.select({ cwd: projectWorkspaces.cwd, repoUrl: projectWorkspaces.repoUrl }).from(projectWorkspaces) + .where(eq(projectWorkspaces.companyId, companyId)); + for (const workspace of configured) { + const cwd = await configuredWorkspaceRoot(workspace, true); + if (cwd) candidates.add(cwd); + } + const workspaces = await db.select({ cwd: executionWorkspaces.cwd }).from(executionWorkspaces).where(eq(executionWorkspaces.companyId, companyId)); + for (const workspace of workspaces) if (workspace.cwd) candidates.add(workspace.cwd); + const retained = await db.select({ cwd: executionWorkspaceRepositoryAccess.canonicalCwd }).from(executionWorkspaceRepositoryAccess) + .where(eq(executionWorkspaceRepositoryAccess.companyId, companyId)); + for (const entry of retained) candidates.add(entry.cwd); + for (const candidate of candidates) await considerPrimary(candidate); + } + return { roots: [...roots], commonRoot }; } /** Internal, deny-only snapshot captured before copying; never accepted from a model or API payload. */ @@ -402,10 +453,31 @@ export type IsolatedWorkspaceSourceAccess = { projectIds: string[]; }; +/** Shared Git objects outlive checkout pointers. Associate their verified + * storage with authorized owners before copying, without granting write access. */ +async function retainGitMetadataOwners(tx: DbTransaction, input: { + companyId: string; commonRoot: string; workspaceIds: Set; projectIds: Set; +}): Promise { + const closure = await resolveRepositoryRootSources(tx, { companyId: input.companyId, cwd: input.commonRoot, inspectCurrentAliases: true }); + const workspaceIds = new Set([...closure.sourceIds, ...input.workspaceIds]); + const projectIds = new Set([...closure.sourceProjectIds, ...input.projectIds]); + for (const reader of closure.overlappingEntries.filter(entry => entry.kind === "reader")) { + const { actor } = await retainedRootReader(tx, input.companyId, reader); + for (const id of workspaceIds) await assertTaskWorkspaceAccess(tx, actor, input.companyId, id); + await assertRootProjectAccess(tx, actor, input.companyId, projectIds); + } + for (const [kind, ids] of [["source", workspaceIds], ["project_source", projectIds]] as const) { + for (const scopeId of ids) if (!closure.entries.some(entry => entry.kind === kind && entry.scopeId === scopeId)) { + await tx.insert(executionWorkspaceRepositoryAccess).values({ companyId: input.companyId, + canonicalCwd: closure.canonicalCwd, rootKey: closure.rootKey, kind, scopeId }); + } + } +} + export async function assertIsolatedWorkspaceSourceReadAccess(db: Db, input: { companyId: string; sourceCwd: string; actor: AuthorizationActor; copyKind?: WorkspaceSourceCopyKind; }): Promise { - const roots = await isolatedWorkspaceSourceRoots(input.sourceCwd, input.copyKind); + const { roots, commonRoot } = await isolatedWorkspaceSourceRoots(db, input.companyId, input.sourceCwd, input.copyKind); return db.transaction(async tx => { await lockExecutionWorkspaceRootProvenance(tx, input.companyId); const workspaceIds = new Set(), projectIds = new Set(); @@ -418,6 +490,7 @@ export async function assertIsolatedWorkspaceSourceReadAccess(db: Db, input: { await assertRootProjectAccess(tx, input.actor, input.companyId, closure.sourceProjectIds); for (const id of closure.sourceProjectIds) projectIds.add(id); } + await retainGitMetadataOwners(tx, { companyId: input.companyId, commonRoot, workspaceIds, projectIds }); return { companyId: input.companyId, roots, workspaceIds: [...workspaceIds], projectIds: [...projectIds] }; }); } @@ -432,7 +505,7 @@ export async function retainIsolatedWorkspaceSourceAccess(db: Db, input: { if (input.captured.companyId !== input.companyId) throw forbidden("Isolated copy source identity changed"); let sourceFailure: unknown; const roots = new Set(input.captured.roots); - try { for (const cwd of await isolatedWorkspaceSourceRoots(input.sourceCwd, input.copyKind)) roots.add(cwd); } + try { for (const cwd of (await isolatedWorkspaceSourceRoots(db, input.companyId, input.sourceCwd, input.copyKind)).roots) roots.add(cwd); } catch (error) { sourceFailure = error; } const canonicalCwd = await canonicalRepositoryRoot(input.targetCwd); const rootKey = createHash("sha256").update(canonicalCwd).digest("hex"); @@ -770,9 +843,12 @@ export function executionWorkspaceRepositoryService(db: Db) { const roots = new Set(), workspaceIds = new Set(), projectIds = new Set(); const retain = async () => { let sourceFailure: unknown; + let commonRoot: string | undefined; try { roots.add(await fs.realpath(input.sourceCwd)); - for (const cwd of await isolatedWorkspaceSourceRoots(input.sourceCwd, "repository")) roots.add(cwd); + const source = await isolatedWorkspaceSourceRoots(db, input.companyId, input.sourceCwd, "repository"); + commonRoot = source.commonRoot; + for (const cwd of source.roots) roots.add(cwd); } catch (error) { sourceFailure = error; } const denied = await db.transaction(async tx => { await lockExecutionWorkspaceRootProvenance(tx, input.companyId); @@ -807,6 +883,10 @@ export function executionWorkspaceRepositoryService(db: Db) { await authorizeRootAccess(tx, { companyId: input.companyId, cwd: input.cwd, sourceWorkspaceId: workspace.id, actor, issueId: input.issueId }); } catch (error) { failure ??= error; } + if (!failure && commonRoot) { + try { await retainGitMetadataOwners(tx, { companyId: input.companyId, commonRoot, workspaceIds, projectIds }); } + catch (error) { failure ??= error; } + } return failure; }); if (denied) throw denied; diff --git a/server/src/services/workspace-runtime.ts b/server/src/services/workspace-runtime.ts index 54841b45e21..4c40721f3fd 100644 --- a/server/src/services/workspace-runtime.ts +++ b/server/src/services/workspace-runtime.ts @@ -2702,10 +2702,22 @@ function parseGitWorktreeListPorcelain(raw: string): GitWorktreeListEntry[] { } async function resolveGitOwnerRepoRoot(cwd: string): Promise { - const checkoutRoot = path.resolve(await runGit(["rev-parse", "--show-toplevel"], cwd)); - const commonDir = await runGit(["rev-parse", "--git-common-dir"], checkoutRoot).catch(() => null); - if (!commonDir) return checkoutRoot; - return path.dirname(path.resolve(checkoutRoot, commonDir)); + const checkoutRoot = await fs.realpath(path.resolve(await runGit(["rev-parse", "--show-toplevel"], cwd))); + try { + const commonDir = await fs.realpath(path.resolve(checkoutRoot, await runGit(["rev-parse", "--git-common-dir"], checkoutRoot))); + const candidate = path.dirname(commonDir); + // A conventional .git directory belongs to its parent checkout. Separate + // Git storage can live inside an unrelated repository, so verify both the + // checkout boundary and metadata identity before using that parent. + const candidateRoot = await fs.realpath(path.resolve(await runGit(["rev-parse", "--show-toplevel"], candidate))); + const candidateGitDir = await fs.realpath(path.resolve(candidate, await runGit(["rev-parse", "--absolute-git-dir"], candidate))); + const candidateCommonDir = await fs.realpath(path.resolve(candidate, await runGit(["rev-parse", "--git-common-dir"], candidate))); + if (candidateRoot === candidate && candidateGitDir === commonDir && candidateCommonDir === commonDir) return candidateRoot; + } catch { + // A main or linked checkout is itself a valid Git command anchor, even + // when separate metadata does not identify a primary checkout directory. + } + return checkoutRoot; } async function findRegisteredGitWorktreeByBranch(repoRoot: string, branchName: string): Promise {