[codex] Guard git-sensitive adapter workspaces (#7644)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The affected subsystem is the heartbeat execution path that turns
issue assignment into adapter-backed work in a selected workspace.
> - PAP-10409 and sibling follow-ups failed before useful adapter output
because project/workspace identity became incoherent.
> - A project-workspace-linked child issue could keep
`projectWorkspaceId` / execution workspace state while losing
`projectId`, then a git-sensitive local adapter could fall through
toward an invalid fallback cwd.
> - Paperclip needs to treat coherent workspace identity as part of the
live-path contract, not only as post-failure cleanup.
> - This pull request documents that rule, repairs issue inheritance,
and blocks git-sensitive adapter launch before it can run from the wrong
cwd.
> - The benefit is a bounded recovery path: affected issues are repaired
explicitly, future malformed workspaces fail fast with a clear recovery
action, and the UI surfaces that reason.

## Linked Issues or Issue Description

Refs #7646

Bug report fields:

- Summary: adapter-backed follow-up issues can fail before doing work
when issue creation/inheritance preserves workspace ids but drops
project identity.
- Affected issues: internal Paperclip issues PAP-10408 through
PAP-10412, especially PAP-10409.
- Steps to reproduce: create a project-scoped parent/follow-up tree
where a child issue keeps `projectWorkspaceId` or an inherited execution
workspace but has `projectId: null`, then launch a git-sensitive local
adapter such as `codex_local`.
- Expected behavior: Paperclip derives or preserves coherent project
identity during issue creation, and heartbeat refuses malformed
git-sensitive workspace launches with one clear recovery action.
- Actual behavior before this PR: the run could reach adapter bootstrap
with an incoherent workspace context and fail with git errors such as
`fatal: not a git repository (or any parent up to mount point /srv)`.
- Root cause: child/follow-up issue inheritance preserved workspace
execution context without coherent project context. That let heartbeat
workspace resolution/adapter launch reach a fallback cwd instead of
refusing the malformed workspace state up front.

## What Changed

- Documented the adapter workspace-coherence live-path precondition in
`doc/execution-semantics.md`.
- Updated issue creation/inheritance so workspace-inheriting issues
preserve or derive project identity, while existing mismatch validation
still rejects incoherent project/workspace combinations.
- Added a heartbeat preflight guard for git-sensitive local adapters
that validates effective cwd, persisted workspace identity, project
workspace identity, and required git metadata before launch.
- Added `workspace_validation` recovery actions for this failure class
and ensured the source issue gets a visible, idempotent recovery
comment.
- Surfaced workspace-validation recovery state in issue rows, blocked
notices, and recovery action cards, including the manual-repair wake
policy label.
- Added focused regression coverage for issue inheritance, all heartbeat
workspace-validation guard branches, recovery display helpers, and UI
recovery components.

## Verification

- `pnpm exec vitest run
server/src/__tests__/heartbeat-workspace-session.test.ts`
  - Result: 1 test file passed, 68 tests passed.
- `pnpm exec vitest run
ui/src/components/IssueRecoveryActionCard.test.tsx`
  - Result: 1 test file passed, 12 tests passed.
- `pnpm exec vitest run ui/src/components/IssueBlockedNotice.test.tsx
ui/src/components/IssueRecoveryActionCard.test.tsx`
  - Result: 2 test files passed, 18 tests passed.
- `pnpm --filter @paperclipai/ui typecheck`
  - Result: passed.
- `pnpm exec vitest run
server/src/__tests__/heartbeat-plugin-environment.test.ts
server/src/__tests__/issues-service.test.ts
server/src/__tests__/heartbeat-workspace-session.test.ts
server/src/__tests__/heartbeat-process-recovery.test.ts
ui/src/components/IssueBlockedNotice.test.tsx
ui/src/components/IssueRecoveryActionCard.test.tsx
ui/src/lib/recovery-display.test.ts`
- Result: 7 test files passed, 200 tests passed before the final
guard-branch additions; the changed server file was re-run above.
- UI coverage: `ui/storybook/stories/source-issue-recovery.stories.tsx`
contains rendered scenarios for the generic recovery chip,
workspace-validation recovery chip, blocked notice indicator, recovery
action card, and issue-row chip.
- Screenshot capture attempt: Storybook started successfully on
`http://127.0.0.1:6016/`, but screenshots could not be captured in this
runner because `agent-browser` launched an unusable Chrome binary and
Playwright Chromium failed on missing system library `libatk-1.0.so.0`;
the runner is non-root and lacks passwordless sudo for installing
browser dependencies.
- Hosted CI on final commit `969594e7` is green, including `verify`,
`Build`, `Typecheck + Release Registry`, `General tests (server)`,
workspace suites, serialized server suites, `Canary Dry Run`, and `e2e`.
- Roadmap checked: no duplicate roadmap item; this is a tightly scoped
reliability fix for existing heartbeat/workspace behavior.
- Duplicate PR search checked: no open PR matched `workspace coherence
adapter cwd`.

## Risks

- Medium risk: heartbeat launch is stricter for git-sensitive local
adapters and can now block malformed workspace states before adapter
execution.
- Mitigation: the guard is limited to local git-sensitive adapters and
records a source-scoped recovery action with structured evidence instead
of retrying indefinitely.
- Compatibility: valid project/workspace execution paths continue
normally; explicit project/workspace mismatches remain rejected.

> 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

OpenAI Codex, GPT-5-based `codex_local` coding agent with terminal/tool
use. Work was produced through Paperclip issue execution with focused
local test runs.

## 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 run tests locally and they pass
- [x] I have added or updated tests where applicable
- [ ] If this change affects the UI, I have included before/after
screenshots
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
Dotta
2026-06-06 09:39:26 -05:00
committed by GitHub
parent eaef47f4c7
commit 7428fb956f
16 changed files with 1040 additions and 28 deletions
+73 -3
View File
@@ -1,7 +1,7 @@
// @vitest-environment jsdom
import { act } from "react";
import { createRoot } from "react-dom/client";
import { flushSync } from "react-dom";
import type { AnchorHTMLAttributes, ReactElement, ReactNode } from "react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
@@ -27,6 +27,18 @@ vi.mock("../api/issues", () => ({
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
function act<T>(callback: () => T): T {
let result: T | undefined;
flushSync(() => {
result = callback();
});
const maybePromise = result as unknown as PromiseLike<unknown>;
if (result && typeof maybePromise.then === "function") {
throw new TypeError("This test act shim only supports synchronous callbacks.");
}
return result as T;
}
let root: ReturnType<typeof createRoot> | null = null;
let container: HTMLDivElement | null = null;
let dateNowSpy: ReturnType<typeof vi.spyOn> | null = null;
@@ -158,9 +170,8 @@ describe("IssueBlockedNotice", () => {
expect(button).not.toBeNull();
expect(button!.textContent ?? "").toContain("Retry now");
await act(async () => {
act(() => {
button!.click();
await Promise.resolve();
});
await vi.waitFor(() => {
@@ -263,6 +274,65 @@ describe("IssueBlockedNotice", () => {
);
expect(indicator).not.toBeNull();
expect(indicator?.getAttribute("data-recovery-state")).toBe("needed");
expect(indicator?.getAttribute("data-recovery-kind")).toBe("missing_disposition");
expect(indicator?.textContent).toContain("Recovery needed");
});
it("labels a workspace_validation blocker recovery distinctly", () => {
const node = render(
<IssueBlockedNotice
issueStatus="blocked"
blockers={[
{
id: "blocker-2",
identifier: "PAP-409",
title: "Workspace cwd lost git context",
status: "blocked",
priority: "medium",
assigneeAgentId: null,
assigneeUserId: null,
activeRecoveryAction: {
id: "rec-2",
companyId: "co-1",
sourceIssueId: "blocker-2",
recoveryIssueId: null,
kind: "workspace_validation",
status: "active",
ownerType: "agent",
ownerAgentId: "agent-cto",
ownerUserId: null,
previousOwnerAgentId: null,
returnOwnerAgentId: null,
cause: "workspace_validation_failed",
fingerprint: "fp-2",
evidence: {
latestRunErrorCode: "workspace_validation_failed",
},
nextAction:
"Repair the source issue workspace link, project workspace cwd, or git checkout before resuming adapter execution.",
wakePolicy: { type: "wake_owner" },
monitorPolicy: null,
attemptCount: 1,
maxAttempts: 3,
timeoutAt: null,
lastAttemptAt: null,
outcome: null,
resolutionNote: null,
resolvedAt: null,
createdAt: "2026-05-01T00:00:00.000Z",
updatedAt: "2026-05-01T00:00:00.000Z",
},
},
]}
/>,
);
const indicator = node.querySelector(
'[data-testid="issue-blocked-notice-recovery-indicator"]',
);
expect(indicator).not.toBeNull();
expect(indicator?.getAttribute("data-recovery-state")).toBe("needed");
expect(indicator?.getAttribute("data-recovery-kind")).toBe("workspace_validation");
expect(indicator?.textContent).toContain("Workspace recovery needed");
});
});
+6 -3
View File
@@ -17,6 +17,7 @@ import { isAssignedBacklogBlocker } from "../lib/issue-blockers";
import {
deriveActiveRecoveryDisplayState,
RECOVERY_CHIP_DEFAULT_TONE,
recoveryChipLabel,
} from "../lib/recovery-display";
function BlockerRecoveryIndicator({ action }: { action: IssueRecoveryAction }) {
@@ -24,17 +25,19 @@ function BlockerRecoveryIndicator({ action }: { action: IssueRecoveryAction }) {
if (!state) return null;
const tone = RECOVERY_CHIP_DEFAULT_TONE[state];
const Icon = tone.icon;
const label = recoveryChipLabel(state, action.kind);
return (
<span
data-testid="issue-blocked-notice-recovery-indicator"
data-recovery-state={state}
data-recovery-kind={action.kind}
role="status"
aria-label={tone.label}
title={`${tone.label} — open the source issue to act.`}
aria-label={label}
title={`${label} — open the source issue to act.`}
className={`inline-flex shrink-0 items-center gap-0.5 rounded-full border px-1.5 py-0.5 text-[10px] font-medium ${tone.className}`}
>
<Icon className="h-2.5 w-2.5" aria-hidden />
{tone.label}
{label}
</span>
);
}
@@ -1,7 +1,7 @@
// @vitest-environment jsdom
import { act } from "react";
import { createRoot } from "react-dom/client";
import { flushSync } from "react-dom";
import type { AnchorHTMLAttributes, ReactElement } from "react";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { Agent, IssueRecoveryAction } from "@paperclipai/shared";
@@ -16,6 +16,18 @@ vi.mock("@/lib/router", () => ({
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
function act<T>(callback: () => T): T {
let result: T | undefined;
flushSync(() => {
result = callback();
});
const maybePromise = result as unknown as PromiseLike<unknown>;
if (result && typeof maybePromise.then === "function") {
throw new TypeError("This test act shim only supports synchronous callbacks.");
}
return result as T;
}
let root: ReturnType<typeof createRoot> | null = null;
let container: HTMLDivElement | null = null;
@@ -157,6 +169,33 @@ describe("IssueRecoveryActionCard", () => {
expect(node.textContent).toContain("OBSERVING ACTIVE RUN");
});
it("renders a workspace-specific label and headline for workspace_validation", () => {
const node = render(
<IssueRecoveryActionCard
action={buildAction({
kind: "workspace_validation",
cause: "workspace_validation_failed",
nextAction:
"Repair the source issue workspace link, project workspace cwd, or git checkout before resuming adapter execution.",
wakePolicy: { type: "manual_repair_required" },
evidence: {
recoveryCause: "workspace_validation_failed",
latestRunErrorCode: "workspace_validation_failed",
},
})}
/>,
);
const section = node.querySelector("section[aria-label]");
expect(section?.getAttribute("data-recovery-kind")).toBe("workspace_validation");
expect(node.textContent).toContain("Workspace Validation");
expect(node.textContent).not.toContain("workspace_validation\n");
expect(node.textContent).toContain(
"Paperclip stopped this run because the issue's git workspace could not be validated.",
);
expect(node.textContent).toContain("Repair the source issue workspace link");
expect(node.textContent).toContain("Manual repair required");
});
it("renders the resolved label and outcome when resolved", () => {
const node = render(
<IssueRecoveryActionCard action={buildAction({ status: "resolved", outcome: "restored", resolvedAt: "2026-05-09T19:35:00.000Z" })} />,
@@ -46,6 +46,7 @@ export interface IssueRecoveryActionCardProps {
const KIND_LABEL: Record<IssueRecoveryActionKind, string> = {
missing_disposition: "Missing Disposition",
stranded_assigned_issue: "Stranded Issue",
workspace_validation: "Workspace Validation",
active_run_watchdog: "Active Watchdog",
issue_graph_liveness: "Graph Liveness",
};
@@ -54,6 +55,8 @@ const KIND_HEADLINE: Record<IssueRecoveryActionKind, string> = {
missing_disposition: "This issue's run finished, but no next step was chosen.",
stranded_assigned_issue:
"Paperclip retried this issue's last run and it still has no live execution path.",
workspace_validation:
"Paperclip stopped this run because the issue's git workspace could not be validated.",
active_run_watchdog:
"The active run has been silent. Recovery is observing without interrupting it.",
issue_graph_liveness:
@@ -169,6 +172,7 @@ function readWakePolicySummary(action: IssueRecoveryAction): string | null {
if (type === "wake_owner") return "Corrective wake queued";
if (type === "board_escalation") return "Escalated to board";
if (type === "manual") return "Manual";
if (type === "manual_repair_required") return "Manual repair required";
if (type === "monitor") {
const interval = readEvidenceString(policy.intervalLabel);
return interval ? `Monitor scheduled · ${interval}` : "Monitor scheduled";
+10 -4
View File
@@ -8,7 +8,11 @@ import {
withIssueDetailHeaderSeed,
} from "../lib/issueDetailBreadcrumb";
import { cn } from "../lib/utils";
import { deriveActiveRecoveryDisplayState, RECOVERY_CHIP_DEFAULT_TONE } from "../lib/recovery-display";
import {
deriveActiveRecoveryDisplayState,
RECOVERY_CHIP_DEFAULT_TONE,
recoveryChipLabel,
} from "../lib/recovery-display";
import { StatusIcon } from "./StatusIcon";
import { productivityReviewTriggerLabel } from "./ProductivityReviewBadge";
import { hasAssignedBacklogBlocker } from "../lib/issue-blockers";
@@ -233,21 +237,23 @@ function renderRecoveryChip(action: IssueRecoveryAction, selected: boolean): Rea
if (!state) return null;
const tone = RECOVERY_CHIP_DEFAULT_TONE[state];
const Icon = tone.icon;
const label = recoveryChipLabel(state, action.kind);
return (
<span
data-testid="issue-row-recovery-indicator"
data-recovery-state={state}
data-recovery-kind={action.kind}
role="status"
aria-label={tone.label}
aria-label={label}
className={cn(
"ml-1.5 inline-flex shrink-0 items-center gap-0.5 rounded-full border px-2 py-0.5 text-[10px] font-medium",
tone.className,
selected ? "!border-muted-foreground !text-muted-foreground" : null,
)}
title={`${tone.label} — open the source issue to act.`}
title={`${label} — open the source issue to act.`}
>
<Icon className="h-2.5 w-2.5" aria-hidden />
{tone.label}
{label}
</span>
);
}