fix(workspaces): keep the saved strategy for fresh managed-storage retries (#23002)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Master publishes its Core Docker image only after the "Cloud
readiness" run passes for the same commit
> - Readiness fails on every verified master commit since #22972 and
#22969 merged together, so the Docker image does not publish and staging
cannot deploy
> - Two server tests fail every time. One failure is a real product
regression. One failure is a test that checks a mock call instead of the
real retry decision
> - This pull request fixes the regression and makes the test check the
real scheduler outcome
> - The benefit is that a fresh Retry on a managed-storage project works
again, and master readiness and the Docker publish can pass

## Linked Issues or Issue Description

Refs #22972, Refs #22969

**What happened?**

1. #22972 changed the strategy that heartbeat workspace preparation
sends to a workspace-storage plugin. It sends `project_primary` for
every fresh retry (`fresh || useIsolatedTaskDirectory`), not only for a
private isolated task directory. A storage plugin that declares only
`git_worktree` refuses the fresh retry with "The storage plugin does not
support this workspace mode or strategy". Before #22972, a fresh retry
sent the project's resolved strategy.
2. #22969 added a `hermes_gateway` test. The test expects that
completion does not call `scheduleBoundedRetryForRun` for an ambiguous
`create_run` HTTP 429/5xx failure. But completion always sends a
`transient_upstream` failure to the scheduler (the same test asserts
this call for the shutdown case). The scheduler then refuses with
`legacy_execution_requires_reconciliation`. So no retry happens, but the
mock assertion fails every time.

**Expected behavior**

1. A fresh retry on a managed-storage project keeps the project strategy
(for example `git_worktree`). Only a private isolated task directory
uses `project_primary`.
2. An ambiguous `hermes_gateway` `create_run` failure does not schedule
a retry.

**Steps to reproduce**

1. `pnpm exec vitest run
server/src/services/heartbeat/workspace-preparation.test.ts -t "fresh:
true"` on master fails with "The storage plugin does not support this
workspace mode or strategy".
2. `pnpm exec vitest run
server/src/services/heartbeat/run-completion.test.ts -t "hermes_gateway
shutdown"` on master fails with `expected "vi.fn()" to not be called at
all`.

**Paperclip version or commit**

`origin/master` at `d21ae3724f`. Both failures are deterministic.
Readiness first verified a commit after these merges at `8e8c1b9f4d` and
failed there. The readiness "passes" on `168253f74d`, `e18fe61c8f` and
`a74b4f8196` skipped `verify` at admission, so they did not run these
tests.

## What Changed

- `server/src/services/heartbeat/workspace-preparation.ts`: send
`project_primary` to the storage plugin only when
`useIsolatedTaskDirectory` is set (outside remote authority). A fresh
retry sends the resolved project strategy again. The host workspace
config still uses `project_primary` for fresh retries, as before #22972.
- `server/src/services/heartbeat/run-completion.test.ts`: in the
`hermes_gateway` `create_run` 429/5xx cases, route the scheduler mock to
the real `createHeartbeatRetries` scheduler. Every dependency after the
reconciliation gate throws. The test asserts that each call returns
`not_scheduled` with `legacy_execution_requires_reconciliation`, and
that no retry run exists.

## Verification

- Red on `origin/master` (`d21ae3724f`), local embedded Postgres:
`workspace-preparation.test.ts -t "prepares managed storage"` gives 1
failed, 10 passed (the `fresh: true` case). `run-completion.test.ts -t
"hermes_gateway shutdown"` fails 3 of 3 runs.
- The same two failures occur in master Cloud readiness runs
45705488994, 45709638795, 45710758887 and 45716955324 (General tests
server shards 8/10 and 10/10).
- Green on this branch: `workspace-preparation.test.ts` 160/160 passed.
`run-completion.test.ts` 174/174 passed.
- `pnpm --filter @paperclipai/server typecheck` passed.

## Risks

- Low risk. The product change restores the pre-#22972 strategy for
fresh retries on the storage-plugin path only. The private isolated task
directory path from #22972 does not change.
- The test change does not weaken the safety check. It now checks the
real scheduler decision instead of a mock call.

## Model Used

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

## Checklist

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

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

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
DottaandClaude Opus 5.5 authored and GitHub committed 2026-11-25 23:59:59 +00:00
1 parent d21ae3724f
commit 3f1632c7b7
2 files changed
+24 -2

No files matched your search

@@ -46,6 +46,7 @@ import { createHeartbeatRunState, getAdapterSessionCodec } from "./run-state.js"
import { buildEffectiveRunSessionConfigMetadata } from "./workspaces.js";
import { createHeartbeatRunCompletion, type CompleteHeartbeatRunInput, type FailHeartbeatRunInput, type HeartbeatRunCompletionDependencies } from "./run-completion.js";
import { createHeartbeatAgentStatus } from "./agent-status.js";
import { createHeartbeatRetries } from "./retries.js";
import { prepareNativeHeartbeatRun } from "../native-runtime/prepare-native-run.js";
import { buildNativeCompletionContract } from "../native-runtime/completion-contracts.js";
import { readPendingNativeRunStop } from "../native-runtime/native-cancellation-request.js";
@@ -2096,6 +2097,20 @@ describe.skipIf(!support.supported && !process.env.PAPERCLIP_TEST_DATABASE_URL)(
const fCreateErr = await fixture({}, `${tag}${randomUUID().slice(0, 6)}`);
const [hermesCreateAgent] = await db.update(agents).set({ adapterType: "hermes_gateway" })
.where(eq(agents.id, fCreateErr.agent.id)).returning();
const unreachable = () => { throw new Error("retry scheduling passed the reconciliation gate"); };
const realRetries = createHeartbeatRetries(db, {
hasCaseHandoffForRun: async () => false,
getAgent: unreachable, getRun: unreachable, resolveSessionBeforeForWakeup: unreachable,
resolveResponsibleUserIdForRunContext: unreachable, getAgentInvokability: unreachable,
appendRunEvent: unreachable, escalatePlanApprovalResumeFailureNeedsAttention: unreachable,
recordPlanApprovalResumeFailureRetry: unreachable, setRunStatusIfRunning: unreachable,
setWakeupStatus: unreachable, releaseIssueExecutionAndPromote: unreachable, finalizeAgentStatus: unreachable,
getWorktreeExecutionCutoff: unreachable, applyRunDispatchPostCommitEffects: unreachable,
runDispatch: { nextScheduledRetryAt: unreachable, evaluateScheduledRetryGate: unreachable,
promoteDueScheduledRetries: unreachable, promoteScheduledRetry: unreachable },
});
fCreateErr.deps.scheduleBoundedRetryForRun.mockImplementation((run, agent, opts) =>
realRetries.scheduleBoundedRetryForRun(run, agent, opts));
await fCreateErr.completion.completeRun({
...fCreateErr.input,
agent: hermesCreateAgent!,
@@ -2121,7 +2136,14 @@ describe.skipIf(!support.supported && !process.env.PAPERCLIP_TEST_DATABASE_URL)(
expect(createErrPersisted?.status).toBe("failed");
expect(hasConversationContinuationPolicy(createErrPersisted?.resultJson)).toBe(false);
expect(legacyExecutionNeedsReconciliation(createErrPersisted!)).toBe(true);
expect(fCreateErr.deps.scheduleBoundedRetryForRun).not.toHaveBeenCalled();
const retryOutcomes = await Promise.all(
fCreateErr.deps.scheduleBoundedRetryForRun.mock.results.map(result => result.value),
);
expect(retryOutcomes).toEqual(retryOutcomes.map(() => expect.objectContaining({
outcome: "not_scheduled", errorCode: "legacy_execution_requires_reconciliation",
})));
expect(await db.select({ id: heartbeatRuns.id }).from(heartbeatRuns)
.where(eq(heartbeatRuns.retryOfRunId, fCreateErr.run.id))).toEqual([]);
}
});
});
@@ -760,7 +760,7 @@ async function prepareHeartbeatWorkspaceLocked(db: Db, input: HeartbeatWorkspace
acquireTaskLease,
onTaskPrepared: ensure => { ensureTaskWorkspace = ensure; },
mode: requestedExecutionWorkspaceMode,
strategy: (fresh || useIsolatedTaskDirectory) && !remoteAuthority
strategy: useIsolatedTaskDirectory && !remoteAuthority
? "project_primary"
: resolveEffectiveWorkspaceStrategyType(requestedExecutionWorkspaceMode, mergedConfig),
branchMode: typeof parseObject(mergedConfig.workspaceStrategy).existingBranch === "string" ? "existing" : "create",