fix(recovery): do not cap new runs at the legacy disposition-repair allowance (#15923)

## Thinking Path
> - The execution-semantics spec gives `deliberate_wait_without_target`
recovery five disposition-repair attempts, with delays 0, 60, 120, 240,
and 480 seconds.
> - The disposition-repair module implements that schedule. A separate
legacy-episode helper also exists, to protect pre-upgrade episodes that
already spent attempts under an older, tighter allowance.
> - The helper never answered "not a legacy episode". A run with an
entirely empty context snapshot — clearly not a pre-upgrade episode —
still got a legacy episode capped at 2 attempts (1 for handoff and
old-recovery runs).
> - The common continuation path passes that episode unconditionally, so
the documented five-attempt fallback next to it was dead code for every
non-native run.
> - The fix makes the helper return no episode when a run has no legacy
markers and has consumed no attempts. Marked or partly spent pre-upgrade
runs keep the legacy cap, so no spent budget is resurrected.

## Linked Issues

Fixes #15776

## What Changed

- `server/src/services/recovery/legacy-continuation.ts`:
`legacyDispositionEpisode` now gives a run with no legacy markers (no
persisted episode record, no handoff or old-recovery markers, no repair
fingerprint, no liveness-continuation source) and no consumed attempts
the documented budget, `DISPOSITION_REPAIR_MAX_ATTEMPTS` (5), instead of
the legacy cap. The episode object still exists for every run, so repair
dispatch keeps its persisted binding, issue state guard, and
source-identity semantics. Marked or partly spent runs still derive
their capped episodes, unchanged.
- `server/src/services/recovery/legacy-continuation.ts`: the
persisted-record branch no longer clamps every episode to the legacy
cap. A record keeps the budget it was written with: records written
under the legacy scheme carry at most the legacy cap and keep it, and
records written under the documented scheme keep theirs. Without this, a
new episode was re-capped at 2 from its second attempt on.
- Tests in `legacy-continuation.test.ts`: marker-less runs derive the
five-attempt budget; persisted records keep their written budget (2
stays 2, 5 stays 5); fingerprinted, liveness-sourced, and partly spent
runs still derive their capped episodes.
- Test updates in `legacy-continuation-authority.test.ts` and
`heartbeat-process-recovery.test.ts`: expectations that pinned the old
cap for marker-less runs now expect `maxAttempts: 5`; the exhaustion
tests (ACCT-02, ACCT-04, and the bounded-episode test) stamp a genuine
pre-upgrade episode on their source runs so they keep pinning the legacy
bound. No production behavior outside the budget derivation changed for
those tests.

## Verification

- `vitest run server/src/services/recovery/legacy-continuation.test.ts`
— 28 of 28 pass, including the existing "does not resurrect an exhausted
pre-upgrade budget" cases.
- CI on the final head: all checks pass (55 of 55), including the suites
that pin the surrounding semantics — `legacy-continuation-authority`,
`heartbeat-process-recovery`, `heartbeat-stale-queue-invalidation`,
`heartbeat-slack-invitation`, `heartbeat-issue-liveness-escalation`, and
the chat integration suites.
- An earlier revision of this PR returned `undefined` for marker-less
runs; CI showed that episode presence also drives the state guard and
dispatch identity checks, so the fix was reworked to change only the
budget derivation. The PR comments carry the full history.

## Risks

- A run whose only history is a positive generic continuation counter
stays on the legacy cap. That matches this repo's existing test
expectation that a run with `continuationAttempt: 2` is an exhausted
pre-upgrade episode; the counters cannot distinguish schemes, so the
conservative reading wins.
- Note for sequencing: open PR #15658 also touches the recovery area
(owner continuation after partial work) but does not change the attempt
cap, so the two changes are independent.

## Model Used

- **Provider / Model ID:** Meta, Muse Spark 1.3
- **Context window:** 1M+ tokens (exact limit not disclosed);
large-repository tasks with long tool transcripts
- **Capabilities:** agentic coding with tool use — file editing, shell
execution, test execution, browser and API access, multi-step planning

## 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)
- [ ] 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
- [ ] 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

---------

Signed-off-by: Josh Cox <joshuacox@users.noreply.github.com>
Co-authored-by: Review <review@local>
Co-authored-by: commitperclip[bot] <284812584+commitperclip[bot]@users.noreply.github.com>
This commit is contained in:
authored and GitHub committed 2026-12-04 21:38:49 -08:00
1 parent 587de9420f
commit 1dcab931a6
4 files changed
+66 -6

No files matched your search

@@ -7836,7 +7836,7 @@ describeEmbeddedPostgres(`heartbeat orphaned process recovery (part ${part}/4)`,
expect(repairs).toHaveLength(1);
const repair = await heartbeat.getRun(repairs[0].runId!);
expect(repair?.contextSnapshot).toMatchObject({
legacyDispositionEpisode: { id: runId, attempt: 1, maxAttempts: 2 },
legacyDispositionEpisode: { id: runId, attempt: 1, maxAttempts: 5 },
dispositionRepairInstruction: LEGACY_DISPOSITION_REPAIR_INSTRUCTION,
});
expect({ status: repair?.status, errorCode: repair?.errorCode, error: repair?.error })
@@ -7904,7 +7904,7 @@ describeEmbeddedPostgres(`heartbeat orphaned process recovery (part ${part}/4)`,
expect(repairs).toHaveLength(1);
const repair = await heartbeat.getRun(repairs[0].runId!);
expect(repair?.contextSnapshot).toMatchObject({
legacyDispositionEpisode: { id: runId, attempt: 1, maxAttempts: 2 },
legacyDispositionEpisode: { id: runId, attempt: 1, maxAttempts: 5 },
dispositionRepairInstruction: LEGACY_DISPOSITION_REPAIR_INSTRUCTION,
});
expect(repair?.status).toBe("succeeded");
@@ -7995,7 +7995,7 @@ describeEmbeddedPostgres(`heartbeat orphaned process recovery (part ${part}/4)`,
expect(repairs).toHaveLength(1);
const repair = await heartbeat.getRun(repairs[0].runId!);
expect(repair?.contextSnapshot).toMatchObject({
legacyDispositionEpisode: { id: runId, attempt: 1, maxAttempts: 2 },
legacyDispositionEpisode: { id: runId, attempt: 1, maxAttempts: 5 },
dispositionRepairInstruction: LEGACY_DISPOSITION_REPAIR_INSTRUCTION,
});
expect(repair?.status).toBe("succeeded");
@@ -8050,7 +8050,7 @@ describeEmbeddedPostgres(`heartbeat orphaned process recovery (part ${part}/4)`,
expect(repairs).toHaveLength(1);
const repair = await heartbeat.getRun(repairs[0].runId!);
expect(repair?.contextSnapshot).toMatchObject({
legacyDispositionEpisode: { id: runId, attempt: 1, maxAttempts: 2 },
legacyDispositionEpisode: { id: runId, attempt: 1, maxAttempts: 5 },
dispositionRepairInstruction: LEGACY_DISPOSITION_REPAIR_INSTRUCTION,
});
expect(repair?.status).toBe("succeeded");
@@ -142,7 +142,7 @@ describe("legacy continuation persisted authority", () => {
await f.createRecovery().reconcileLegacyContinuation(f.runId);
expect(await f.runs()).toHaveLength(2);
const repair = (await f.runs()).find(r => r.id !== f.runId)!;
expect(repair.contextSnapshot).toMatchObject({ legacyDispositionEpisode: { id: f.runId, attempt: 1, maxAttempts: 2 } });
expect(repair.contextSnapshot).toMatchObject({ legacyDispositionEpisode: { id: f.runId, attempt: 1, maxAttempts: 5 } });
});
it("does not roll back the ledger when a fast repair finishes before enqueue returns", async () => {
const f = await fixture();
@@ -157,6 +157,13 @@ describe("legacy continuation persisted authority", () => {
});
it("keeps the same bounded episode across restart and commentary, then escalates only after agent attempts", async () => {
const f = await fixture();
// Stamp a genuine pre-upgrade episode on the source run: this test
// pins the legacy bounded behavior, which now applies only to runs
// that carry a legacy episode (marker-less runs get the documented
// five-attempt budget instead).
await db.update(heartbeatRuns).set({
contextSnapshot: { issueId: f.issueId, legacyDispositionEpisode: { id: f.runId, attempt: 0, maxAttempts: 2 } },
}).where(eq(heartbeatRuns.id, f.runId));
await f.createRecovery().reconcileLegacyContinuation(f.runId);
const first = (await f.runs()).find(r => r.id !== f.runId)!;
await f.finish(first);
@@ -173,6 +180,11 @@ describe("legacy continuation persisted authority", () => {
});
it.each(["silent", "comments", "tool-calls"])("ACCT-02 full recovery sweep cannot replenish an exhausted episode with %s", async noise => {
const f = await fixture();
// Stamp a genuine pre-upgrade episode: exhaustion finality is pinned
// here under the legacy bound (marker-less runs now get five attempts).
await db.update(heartbeatRuns).set({
contextSnapshot: { issueId: f.issueId, legacyDispositionEpisode: { id: f.runId, attempt: 0, maxAttempts: 2 } },
}).where(eq(heartbeatRuns.id, f.runId));
await f.createRecovery().reconcileLegacyContinuation(f.runId);
const first = (await f.runs()).find(r => r.id !== f.runId)!;
await f.finish(first);
@@ -237,6 +249,11 @@ describe("legacy continuation persisted authority", () => {
it.each(["foreign-source", "changed-episode", "exhausted-slot"])("ACCT-04 rejects a delayed repair with %s", async mutation => {
const f = await fixture();
// Stamp a genuine pre-upgrade episode so the exhausted-slot mutation
// (attempt 3) exceeds the episode bound it is rejected against.
await db.update(heartbeatRuns).set({
contextSnapshot: { issueId: f.issueId, legacyDispositionEpisode: { id: f.runId, attempt: 0, maxAttempts: 2 } },
}).where(eq(heartbeatRuns.id, f.runId));
await f.createRecovery().reconcileLegacyContinuation(f.runId);
const first = (await f.runs()).find(r => r.id !== f.runId)!;
await f.finish(first);
@@ -49,4 +49,28 @@ describe("legacy continuation authority", () => {
it("leaves native finalization to its own authority", () => {
expect(decideLegacyContinuation({ ...input, run: { ...input.run, runtimeMode: "native" } }).kind).toBe("skip");
});
it("gives a run with no legacy markers the documented five-attempt budget", () => {
// Such a run has spent nothing under the legacy scheme, so the legacy
// cap must not apply to it through the episode fallback.
expect(legacyDispositionEpisode({ id: "run-1" }))
.toMatchObject({ id: "run-1", attempt: 0, maxAttempts: 5 });
expect(legacyDispositionEpisode({ id: "run-1", contextSnapshot: {} }))
.toMatchObject({ id: "run-1", attempt: 0, maxAttempts: 5 });
expect(legacyDispositionEpisode({ id: "run-1", contextSnapshot: { issueId: "issue" }, continuationAttempt: 0 }))
.toMatchObject({ id: "run-1", attempt: 0, maxAttempts: 5 });
});
it("keeps the budget a persisted episode record was written with", () => {
expect(legacyDispositionEpisode({ id: "old", contextSnapshot: { legacyDispositionEpisode: { id: "ep", attempt: 1, maxAttempts: 2 } } }))
.toMatchObject({ id: "ep", attempt: 1, maxAttempts: 2 });
expect(legacyDispositionEpisode({ id: "new", contextSnapshot: { legacyDispositionEpisode: { id: "ep", attempt: 1, maxAttempts: 5 } } }))
.toMatchObject({ id: "ep", attempt: 1, maxAttempts: 5 });
});
it("still derives an episode for marked or partly spent pre-upgrade runs", () => {
expect(legacyDispositionEpisode({ id: "old", contextSnapshot: { dispositionRepairFingerprint: "old-episode" } }))
.toMatchObject({ id: "old-episode", attempt: 0, maxAttempts: 2 });
expect(legacyDispositionEpisode({ id: "old", contextSnapshot: { livenessContinuationSourceRunId: "source-run" } }))
.toMatchObject({ id: "source-run", attempt: 0, maxAttempts: 2 });
expect(legacyDispositionEpisode({ id: "old", continuationAttempt: 1 }))
.toMatchObject({ id: "old", attempt: 1, maxAttempts: 2 });
});
});
@@ -1,4 +1,5 @@
import { createHash } from "node:crypto";
import { DISPOSITION_REPAIR_MAX_ATTEMPTS } from "./disposition-repair.js";
/** This contract deliberately has no narrative, liveness label or progress count. */
export interface LegacyContinuationInput {
@@ -43,13 +44,31 @@ export function legacyDispositionEpisode(run: {
const context = record(run.contextSnapshot);
const episode = record(context.legacyDispositionEpisode);
if (typeof episode.id === "string" && episode.id) {
return { id: episode.id, attempt: count(episode.attempt), maxAttempts: Math.max(1, Math.min(LEGACY_DISPOSITION_REPAIR_MAX_ATTEMPTS, count(episode.maxAttempts) || LEGACY_DISPOSITION_REPAIR_MAX_ATTEMPTS)) };
// The persisted record is authoritative for its own budget. Records
// written under the legacy scheme carry its cap and keep it, so a
// pre-upgrade episode is never granted a fresh budget. Records
// written under the documented scheme carry that budget and keep it
// too; clamping them here would silently re-cap new episodes at the
// legacy allowance from their second attempt on.
return { id: episode.id, attempt: count(episode.attempt), maxAttempts: Math.max(1, count(episode.maxAttempts) || LEGACY_DISPOSITION_REPAIR_MAX_ATTEMPTS) };
}
// Pre-upgrade repairs have already consumed their old (possibly tighter)
// allowance. A classifier/key migration must not grant them a fresh budget.
const handoff = context.wakeReason === "finish_successful_run_handoff" || context.handoffRequired === true;
const oldRecovery = context.source === "issue.productive_terminal_continuation_recovery";
const attempt = Math.max(count(run.continuationAttempt), count(context.livenessContinuationAttempt), count(context.dispositionRepairAttempt), handoff ? count(context.handoffAttempt) || 1 : 0, oldRecovery ? 1 : 0);
// A run with no legacy markers and no consumed attempts has spent
// nothing under any older scheme, so it is a new episode and gets the
// documented disposition-repair budget, not the legacy cap. The episode
// object still exists: repair dispatch relies on it for the persisted
// binding, the issue state guard, and source-identity checks, and those
// semantics must not depend on which budget a run falls under.
const hasLegacyMarker = handoff || oldRecovery
|| typeof context.dispositionRepairFingerprint === "string"
|| typeof context.livenessContinuationSourceRunId === "string";
if (!hasLegacyMarker && attempt === 0) {
return { id: run.id, attempt: 0, maxAttempts: DISPOSITION_REPAIR_MAX_ATTEMPTS };
}
return {
id: typeof context.dispositionRepairFingerprint === "string" ? context.dispositionRepairFingerprint : typeof context.livenessContinuationSourceRunId === "string" ? context.livenessContinuationSourceRunId : run.id,
attempt,