From 6b171c9616aec025a1839424c0e5e5b44da4275b Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Wed, 7 Oct 2026 18:54:35 -0700 Subject: [PATCH] Keep proven local workspace configuration conflicts out of Sentry (#15521) Apply the reviewed change for Keep proven local workspace configuration conflicts out of Sentry. Validation: required local typecheck and tests, passing CI, Greptile 5/5, and independent review of the exact source head. Co-Authored-By: Paperclip --- doc/observability.md | 13 ++- .../heartbeat-process-recovery.test.ts | 50 +++++++++ .../heartbeat-workspace-session.test.ts | 106 ++++++++++++++++++ .../__tests__/run-failure-report.test.ts | 73 ++++++++++++ server/src/services/heartbeat.ts | 66 ++++++++++- server/src/services/run-failure-report.ts | 20 ++++ 6 files changed, 325 insertions(+), 3 deletions(-) diff --git a/doc/observability.md b/doc/observability.md index c09b7219296..77fe0a28860 100644 --- a/doc/observability.md +++ b/doc/observability.md @@ -440,8 +440,17 @@ This requires a failed `configuration_incomplete` run in the preparing stage, a setup-phase report, explicit proof that provider work did not start, and a nonempty list of recognized missing or inactive secret bindings. Process exit evidence, unknown binding reasons, secret-provider failures, ambiguous missing -secret-definition lookups, and workspace failures remain reportable. This filter -does not change task recovery, credentials, or execution policy. +secret-definition lookups remain reportable. This filter does not change task +recovery, credentials, or execution policy. + +A workspace policy conflict also stays local when the resolver proves that an +explicit `local_path` or `non_git_path` project workspace has no repository URL, +Git confirms the selected directory is not a repository, and the task requests +a Git worktree. The run must fail during setup before provider work starts. +Its existing validation error, blocked task and board recovery action remain. +Git command failures, permissions, corrupt repositories, failed materialization, +fallback paths, and generic missing or unrestorable workspaces remain reportable; +the error text or `workspace_validation_failed` code alone never suppresses them. The `run_failure` context also includes the recorded process `exitCode` and `signal`, so a generic adapter error can still distinguish a nonzero exit from diff --git a/server/src/__tests__/heartbeat-process-recovery.test.ts b/server/src/__tests__/heartbeat-process-recovery.test.ts index 702c941fde1..386f2a30ac3 100644 --- a/server/src/__tests__/heartbeat-process-recovery.test.ts +++ b/server/src/__tests__/heartbeat-process-recovery.test.ts @@ -5541,6 +5541,56 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => { expect(validationComment).toBeTruthy(); }); + it("keeps an explicit local-path/worktree conflict blocked with a board action and no Sentry event", async () => { + const { companyId, agentId, runId, issueId } = await seedQueuedIssueRunFixture(); + const cwd = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-local-workspace-policy-")); + const projectId = randomUUID(); + const workspaceId = randomUUID(); + const heartbeat = heartbeatService(db); + const previousSettings = await instanceSettingsService(db).getExperimental(); + try { + await instanceSettingsService(db).updateExperimental({ enableIsolatedWorkspaces: true }); + await db.insert(projects).values({ id: projectId, companyId, name: "Local documents", status: "in_progress" }); + await db.insert(projectWorkspaces).values({ + id: workspaceId, companyId, projectId, name: "Documents", sourceType: "local_path", cwd, isPrimary: true, + }); + await db.update(issues).set({ + projectId, projectWorkspaceId: workspaceId, executionWorkspaceSettings: { mode: "isolated_workspace" }, + }).where(eq(issues.id, issueId)); + await db.update(agents).set({ adapterConfig: { workspaceStrategy: { type: "git_worktree" } } }).where(eq(agents.id, agentId)); + + await heartbeat.resumeQueuedRuns(); + await waitForRunToSettle(heartbeat, runId, 5_000); + await heartbeat.waitForRunExecutionDrain(runId); + await waitForPendingRunFailureReports(); + + const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)); + expect(run).toMatchObject({ + status: "failed", errorCode: "workspace_validation_failed", processStartedAt: null, + resultJson: { + workspaceValidation: { reason: "git_worktree_base_not_git_checkout", configurationReason: "local_path_requires_git_checkout" }, + executionRecovery: { kind: "bootstrap", providerWorkStarted: false }, + }, + }); + expect(run.error).toContain("is not a git checkout"); + expect(mockAdapterExecute).not.toHaveBeenCalled(); + const [issue] = await db.select().from(issues).where(eq(issues.id, issueId)); + expect(issue).toMatchObject({ status: "blocked", executionRunId: null, projectId, projectWorkspaceId: workspaceId }); + const [action] = await db.select().from(issueRecoveryActions).where(and( + eq(issueRecoveryActions.companyId, companyId), eq(issueRecoveryActions.sourceIssueId, issueId), + )); + expect(action).toMatchObject({ status: "active", kind: "workspace_validation", ownerType: "board" }); + expect(action.nextAction).toContain("workspace"); + const comments = await db.select().from(issueComments).where(eq(issueComments.issueId, issueId)); + expect(comments.some((comment) => comment.body.includes("workspace failed validation"))).toBe(true); + expect(mockCaptureRunFailure.mock.calls.filter(([event]) => event.runId === runId)).toEqual([]); + } finally { + await heartbeat.waitForRunExecutionDrain(runId); + await instanceSettingsService(db).updateExperimental({ enableIsolatedWorkspaces: previousSettings.enableIsolatedWorkspaces }); + await fs.rm(cwd, { recursive: true, force: true }); + } + }); + it.each(["throw", "result"])("redacts opaque environment-bound credentials from Sentry diagnostics: %s", async (mode) => { const { companyId, agentId, runId } = await seedQueuedIssueRunFixture(); const svc = secretService(db); diff --git a/server/src/__tests__/heartbeat-workspace-session.test.ts b/server/src/__tests__/heartbeat-workspace-session.test.ts index aa11c777a72..e57c34ff195 100644 --- a/server/src/__tests__/heartbeat-workspace-session.test.ts +++ b/server/src/__tests__/heartbeat-workspace-session.test.ts @@ -567,6 +567,112 @@ describe("assertGitWorktreeBaseWorkspaceReady", () => { } }); + function configuredLocalPathInput(cwd: string): Parameters[0] { + return { + requestedExecutionWorkspaceMode: "isolated_workspace", + config: { workspaceStrategy: { type: "git_worktree" } }, + issue: { id: "issue-1", identifier: null, projectId: "project-1", projectWorkspaceId: "workspace-1" }, + base: { baseCwd: cwd, source: "project_primary", projectId: "project-1", workspaceId: "workspace-1", repoUrl: null, repoRef: null }, + anchor: { localPathOnlyWorkspace: true, baseCwdFallback: false, materializationFailures: [] }, + }; + } + + it("marks a proven non-Git local path as an owner configuration conflict without changing the failure", async () => { + const cwd = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-local-path-policy-")); + try { + await expect(assertGitWorktreeBaseWorkspaceReady(configuredLocalPathInput(cwd))).rejects.toMatchObject({ + code: "workspace_validation_failed", + message: expect.stringContaining("is not a git checkout"), + resultJson: { workspaceValidation: { + reason: "git_worktree_base_not_git_checkout", + configurationReason: "local_path_requires_git_checkout", + } }, + }); + } finally { await fs.rm(cwd, { recursive: true, force: true }); } + }); + + it.each(["legacy", "repository", "fallback", "materialization", "session", "unbound"])( + "does not mark ambiguous non-Git workspace evidence as a configuration-only failure: %s", async (kind) => { + const cwd = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-ambiguous-workspace-")); + try { + const input = configuredLocalPathInput(cwd); + if (kind === "legacy") input.anchor!.localPathOnlyWorkspace = undefined; + if (kind === "repository") input.base.repoUrl = "https://example.com/repository.git"; + if (kind === "fallback") input.anchor!.baseCwdFallback = true; + if (kind === "materialization") input.anchor!.materializationFailures = [{ projectWorkspaceId: "another-workspace", repoUrl: null, error: "checkout failed" }]; + if (kind === "session") input.base.source = "task_session"; + if (kind === "unbound") input.base.workspaceId = null; + const error = await assertGitWorktreeBaseWorkspaceReady(input).catch((error) => error); + expect(error.code).toBe("workspace_validation_failed"); + expect(error.resultJson.workspaceValidation.configurationReason).toBeUndefined(); + } finally { await fs.rm(cwd, { recursive: true, force: true }); } + }, + ); + + it.each(["missing_git", "permission", "git_error", "killed", "missing_directory"])( + "does not classify a Git or filesystem failure as an owner-only configuration mismatch: %s", async (kind) => { + const cwd = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-git-probe-failure-")); + const bin = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-git-probe-bin-")); + try { + if (kind !== "missing_git" && kind !== "missing_directory") { + const command = kind === "killed" + ? "kill -TERM $$" + : kind === "permission" + ? "printf '%s\\n' 'fatal: cannot open .git: Permission denied' >&2; exit 128" + : "printf '%s\\n' 'fatal: bad object HEAD' >&2; exit 128"; + await fs.writeFile(path.join(bin, "git"), `#!/bin/sh\n${command}\n`, { mode: 0o755 }); + } + if (kind !== "missing_directory") vi.stubEnv("PATH", bin); + const input = configuredLocalPathInput(kind === "missing_directory" ? path.join(cwd, "absent") : cwd); + const error = await assertGitWorktreeBaseWorkspaceReady(input).catch((error) => error); + expect(error.code).toBe("workspace_validation_failed"); + expect(error.resultJson.workspaceValidation.configurationReason).toBeUndefined(); + } finally { + vi.unstubAllEnvs(); + await fs.rm(cwd, { recursive: true, force: true }); + await fs.rm(bin, { recursive: true, force: true }); + } + }, + ); + + it("still accepts a configured local path that is a Git checkout", async () => { + const cwd = await createGitCheckout({ withRemote: false }); + try { await expect(assertGitWorktreeBaseWorkspaceReady(configuredLocalPathInput(cwd))).resolves.toBeUndefined(); } + finally { await fs.rm(cwd, { recursive: true, force: true }); } + }); + + it.each(["empty_metadata", "missing_head", "damaged_head", "dangling_metadata", "ancestor_metadata", "bare_metadata"])( + "keeps real broken repository metadata reportable even when Git says not a repository: %s", async (kind) => { + const root = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-broken-local-repo-")); + try { + let cwd = root; + if (kind === "missing_head" || kind === "damaged_head") { + await execFile("git", ["init", root]); + if (kind === "missing_head") await fs.rm(path.join(root, ".git", "HEAD")); + else await fs.writeFile(path.join(root, ".git", "HEAD"), "damaged HEAD\n"); + } else if (kind === "dangling_metadata") { + await fs.symlink(path.join(root, "missing-git-dir"), path.join(root, ".git")); + } else if (kind === "bare_metadata") { + await fs.mkdir(path.join(root, "objects")); + } else { + await fs.mkdir(path.join(root, ".git")); + if (kind === "ancestor_metadata") { + cwd = path.join(root, "documents"); + await fs.mkdir(cwd); + } + } + const gitFailure = await execFile("git", ["rev-parse", "--show-toplevel"], { + cwd, env: { ...process.env, LC_ALL: "C" }, + }).catch((error) => error); + expect(gitFailure.code).toBe(128); + expect(gitFailure.stderr).toMatch(/^fatal: not a git repository/); + const failure = await assertGitWorktreeBaseWorkspaceReady(configuredLocalPathInput(cwd)).catch((error) => error); + expect(failure.code).toBe("workspace_validation_failed"); + expect(failure.resultJson.workspaceValidation.configurationReason).toBeUndefined(); + } finally { await fs.rm(root, { recursive: true, force: true }); } + }, + ); + it("rejects isolated git worktrees when the project workspace could not be materialized, even if the fallback cwd is a git checkout", async () => { // The fallback agent-home dir being a git repo must not let the run proceed: it would be an // unrelated repository, and the not-a-git-checkout probe would mask the real clone failure. diff --git a/server/src/services/__tests__/run-failure-report.test.ts b/server/src/services/__tests__/run-failure-report.test.ts index 9176bdb659b..6271b6f520c 100644 --- a/server/src/services/__tests__/run-failure-report.test.ts +++ b/server/src/services/__tests__/run-failure-report.test.ts @@ -212,6 +212,79 @@ describeEmbeddedPostgres("reportRunFailure", () => { expect(mockCaptureRunFailure).toHaveBeenCalledTimes(1); }); + function localPathConfigurationRun(overrides: Partial = {}) { + return buildRun({ + errorCode: "workspace_validation_failed", + executionStage: "preparing", + resultJson: { + workspaceValidation: { + reason: "git_worktree_base_not_git_checkout", + configurationReason: "local_path_requires_git_checkout", + resolvedWorkspaceSource: "project_primary", + workspaceStrategyType: "git_worktree", + requestedExecutionWorkspaceMode: "isolated_workspace", + }, + executionRecovery: { kind: "bootstrap", providerWorkStarted: false }, + }, + ...overrides, + }); + } + + it.each(["isolated_workspace", "operator_branch"])("keeps proven local-path policy conflicts actionable locally: %s", async (mode) => { + await seedCompanyAndAgent(); + const run = localPathConfigurationRun(); + (run.resultJson!.workspaceValidation as Record).requestedExecutionWorkspaceMode = mode; + const before = structuredClone(run); + + await reportRunFailure(db, run, { phase: "setup" }); + + expect(mockCaptureRunFailure).not.toHaveBeenCalled(); + expect(run).toEqual(before); + }); + + it.each([ + { configurationReason: undefined }, + { configurationReason: "unknown_reason" }, + { reason: "git_worktree_base_materialization_failed" }, + { reason: "git_worktree_not_reusable" }, + { reason: "inherited_workspace_reuse_unavailable" }, + { resolvedWorkspaceSource: "agent_home" }, + { workspaceStrategyType: "project_primary" }, + { requestedExecutionWorkspaceMode: "agent_default" }, + ])("reports unproven and other workspace failures: %j", async (validation) => { + await seedCompanyAndAgent(); + const run = localPathConfigurationRun(); + Object.assign(run.resultJson!.workspaceValidation as object, validation); + await reportRunFailure(db, run, { phase: "setup" }); + expect(mockCaptureRunFailure).toHaveBeenCalledTimes(1); + }); + + it.each([ + { status: "timed_out" }, { errorCode: "setup_failed" }, { executionStage: "executing" }, + { exitCode: 1 }, { signal: "SIGTERM" }, { resultJson: {} }, + { resultJson: { workspaceValidation: { reason: "git_worktree_base_not_git_checkout", configurationReason: "local_path_requires_git_checkout" } } }, + ])("reports workspace failures without an exact pre-dispatch outcome: %j", async (overrides) => { + await seedCompanyAndAgent(); + await reportRunFailure(db, localPathConfigurationRun(overrides), { phase: "setup" }); + expect(mockCaptureRunFailure).toHaveBeenCalledTimes(1); + }); + + it.each([undefined, "execute"] as const)("reports local-path markers outside the setup report: %s", async (phase) => { + await seedCompanyAndAgent(); + await reportRunFailure(db, localPathConfigurationRun(), { phase }); + expect(mockCaptureRunFailure).toHaveBeenCalledTimes(1); + }); + + it.each([undefined, { kind: "bootstrap" }, { kind: "bootstrap", providerWorkStarted: true }])( + "reports local-path markers without affirmative unstarted-provider evidence: %j", async (executionRecovery) => { + await seedCompanyAndAgent(); + const run = localPathConfigurationRun(); + run.resultJson!.executionRecovery = executionRecovery; + await reportRunFailure(db, run, { phase: "setup" }); + expect(mockCaptureRunFailure).toHaveBeenCalledTimes(1); + }, + ); + it("captures once for the status timed_out", async () => { await seedCompanyAndAgent(); const run = buildRun({ status: "timed_out" }); diff --git a/server/src/services/heartbeat.ts b/server/src/services/heartbeat.ts index 475242c071e..86dceae8c08 100644 --- a/server/src/services/heartbeat.ts +++ b/server/src/services/heartbeat.ts @@ -2948,6 +2948,52 @@ async function isGitCheckout(cwd: string | null | undefined) { .catch(() => false); } +async function probeGitWorktreeBase(cwd: string) { + try { + const result = await execFile("git", ["rev-parse", "--show-toplevel"], { + cwd, + env: { ...process.env, LC_ALL: "C" }, + }); + return { isCheckout: Boolean(readNonEmptyString(result.stdout)), notRepository: false }; + } catch (error) { + const failure = error as { code?: unknown; signal?: unknown; stderr?: unknown }; + // Git's absence result is only a candidate: damaged metadata can produce + // the same message. Verify its absence too. Missing Git, permission errors, + // corruption and I/O failures must remain reportable in Sentry. + const notRepository = failure.code === 128 && failure.signal == null && + typeof failure.stderr === "string" && + /^fatal: not a git repository \(or any of the parent directories\): \.git\r?\n?$/.test(failure.stderr) && + !process.env.GIT_DIR && !process.env.GIT_WORK_TREE && !process.env.GIT_COMMON_DIR && + await hasNoGitMetadataInWorkspaceAncestors(cwd); + return { isCheckout: false, notRepository }; + } +} + +async function hasNoGitMetadataInWorkspaceAncestors(cwd: string): Promise { + try { + let directory = await fs.realpath(cwd); + if (!(await fs.stat(directory)).isDirectory()) return false; + for (;;) { + // Damaged repositories can produce the same "not a git repository" + // message as ordinary directories. Retain those failures in Sentry. + // lstat deliberately recognizes dangling .git links as metadata too. + for (const name of [".git", "HEAD", "objects", "refs"]) { + try { + await fs.lstat(path.join(directory, name)); + return false; + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ENOENT") return false; + } + } + const parent = path.dirname(directory); + if (parent === directory) return true; + directory = parent; + } + } catch { + return false; + } +} + function sameResolvedPath( left: string | null | undefined, right: string | null | undefined, @@ -3005,6 +3051,8 @@ export async function assertGitWorktreeBaseWorkspaceReady(input: { anchor?: { baseCwdFallback?: boolean; materializationFailures?: WorkspaceMaterializationFailure[]; + /** Selected database workspace is an explicit local path with no repository URL. */ + localPathOnlyWorkspace?: boolean; } | null; }) { if (!input.issue) return; @@ -3073,10 +3121,19 @@ export async function assertGitWorktreeBaseWorkspaceReady(input: { ); } - if (!(await isGitCheckout(input.base.baseCwd))) { + const checkoutProbe = await probeGitWorktreeBase(input.base.baseCwd); + if (!checkoutProbe.isCheckout) { + const knownLocalPathMismatch = checkoutProbe.notRepository && + input.anchor?.localPathOnlyWorkspace === true && + input.anchor.baseCwdFallback === false && materializationFailures.length === 0 && + input.base.source === "project_primary" && Boolean(input.base.projectId) && + Boolean(input.base.workspaceId) && !readNonEmptyString(input.base.repoUrl); fail( "git_worktree_base_not_git_checkout", `Issue ${issueLabel} requested ${input.requestedExecutionWorkspaceMode} with git_worktree, but base workspace "${input.base.baseCwd}" is not a git checkout. ${remediation}`, + knownLocalPathMismatch + ? { configurationReason: "local_path_requires_git_checkout" } + : {}, ); } @@ -3888,6 +3945,8 @@ export type ResolvedWorkspaceForRun = { baseCwdFallback: boolean; /** Failed materialization attempts behind {@link baseCwdFallback}; empty when every candidate resolved or none was attempted. */ materializationFailures: WorkspaceMaterializationFailure[]; + /** True only for an explicitly configured local project path without a repository URL. */ + localPathOnlyWorkspace?: boolean; /** * Read-only referenced (mentioned) project workspaces for this run, one per authorized * additional project. The array is empty unless the multi-project workspace-sync flag is on @@ -12669,6 +12728,10 @@ export function heartbeatService( ].filter((value): value is string => Boolean(value)), baseCwdFallback: false, materializationFailures, + localPathOnlyWorkspace: + (workspace.sourceType === "local_path" || workspace.sourceType === "non_git_path") && + Boolean(readNonEmptyString(workspace.cwd)) && workspace.cwd !== REPO_ONLY_CWD_SENTINEL && + !readNonEmptyString(workspace.repoUrl), }; } if (preferredWorkspace?.id === workspace.id) { @@ -22267,6 +22330,7 @@ export function heartbeatService( anchor: { baseCwdFallback: resolvedWorkspace.baseCwdFallback, materializationFailures: resolvedWorkspace.materializationFailures, + localPathOnlyWorkspace: resolvedWorkspace.localPathOnlyWorkspace, }, }); const workspaceStrategyForFingerprint = parseObject( diff --git a/server/src/services/run-failure-report.ts b/server/src/services/run-failure-report.ts index 9c341eeca6a..33f6fbe33e8 100644 --- a/server/src/services/run-failure-report.ts +++ b/server/src/services/run-failure-report.ts @@ -84,6 +84,25 @@ function isMissingSecretConfigurationBlocker(run: HeartbeatRun, options: RunFail }); } +/** The workspace resolver proved an explicit local-path/worktree policy mismatch. */ +function isLocalPathWorkspaceConfigurationBlocker(run: HeartbeatRun, options: RunFailureReportOptions): boolean { + if ( + run.status !== "failed" || run.errorCode !== "workspace_validation_failed" || + run.executionStage !== "preparing" || options.phase !== "setup" || + run.exitCode != null || run.signal != null + ) return false; + + const validation = asRecord(run.resultJson?.workspaceValidation); + const recovery = asRecord(run.resultJson?.executionRecovery); + return validation?.reason === "git_worktree_base_not_git_checkout" && + validation.configurationReason === "local_path_requires_git_checkout" && + validation.resolvedWorkspaceSource === "project_primary" && + validation.workspaceStrategyType === "git_worktree" && + (validation.requestedExecutionWorkspaceMode === "isolated_workspace" || + validation.requestedExecutionWorkspaceMode === "operator_branch") && + recovery?.kind === "bootstrap" && recovery.providerWorkStarted === false; +} + /** * Report a terminal run failure to Sentry. Returns at once for any status * other than failures and unexpected started cancellations. Never throws — a Sentry failure or a @@ -99,6 +118,7 @@ export function reportRunFailure(db: Db, run: HeartbeatRun, options: RunFailureR if (!isRunFailureStatus(run.status)) return Promise.resolve(); if (run.status === "cancelled" && !isUnexpectedRunCancellation(run)) return Promise.resolve(); if (isMissingSecretConfigurationBlocker(run, options)) return Promise.resolve(); + if (isLocalPathWorkspaceConfigurationBlocker(run, options)) return Promise.resolve(); const runStatus = run.status; const report = captureTerminalRunFailure(db, run, runStatus, options); pendingRunFailureReports.add(report);