Skip to content

fix(goals): rebuild a pruned goal worktree on recovery instead of failing forever - #3366

Merged
integry merged 4 commits into
mainfrom
fix/goal-recovery-rebuilds-missing-worktree
Oct 29, 2026
Merged

integry merged 4 commits into
mainfrom
fix/goal-recovery-rebuilds-missing-worktree

Conversation

@integry

@integry integry commented Oct 28, 2026

Copy link
Copy Markdown
Owner

Problem

Goal 5db30345 ran for 4+ hours showing "running" in the UI while nothing was executing. Its worktree under /tmp/git-processor/worktrees/... had been pruned by the host cleanup timer after the agent container exited. From then on:

  1. The recovery sweep in goalRecovery.ts saw a running, claimed goal with a dead heartbeat, no live container, and a saved session + worktree path, so it rotated the generation and enqueued a new job.
  2. ensureGoalWorktree threw Saved goal worktree is missing; exact-session recovery cannot continue.
  3. That throw escaped processGoalJob uncaught. The BullMQ job failed (attempts: 1) with the attempt still claimed, which is exactly the shape step 1 recovers.

Result: 121 generations, a failed job every ~2.5 minutes, and a task history full of "Resuming native goal session" that made the goal look alive.

Fix

  • Rebuild instead of throw. The rebuild-from-remote-branch logic already existed in prepareContinuedGoal, but only ran for operator-continued terminal goals (continue_requested). It is extracted into restoreMissingGoalWorktree and ensureGoalWorktree now calls it when the saved directory is gone. The worktree is recreated under the same directory name, so the saved provider session resumes against the same mount path. The branch carries every published checkpoint; only uncommitted work is lost.
  • Tell the resumed agent. A rebuilt checkout prepends a notice to the attempt feedback so the session re-checks the working tree rather than trusting files it never committed.
  • Branch gone is terminal. If the remote branch no longer exists, restoreMissingGoalWorktree throws GoalWorktreeLostError and preparation finalizes the goal as failed through the same path continued-goal preparation failures use. No prepare failure should leave an attempt claimed with a dead heartbeat, because recovery relaunches that forever.
  • failContinuedGoal is generalized to failGoalPreparation; the transient-retry and claim-guard helpers are shared between the continue and restore paths.

Tests

  • test/goalContinuation.test.ts: live goal rebuilt in place, rebuilt at a new path is saved under the claim, existing checkout untouched, lost branch throws GoalWorktreeLostError, takeover during a transient rebuild error prevents retry.
  • test/processGoalJob.test.ts: ensureGoalWorktree uses the restore path for a missing checkout, skips it for an existing one, and surfaces GoalWorktreeLostError.

Both files pass (39 tests). ESLint is clean on the changed sources; tsc --noEmit reports no errors in the touched files (the remaining errors are pre-existing in packages/api/mcp, hooklessGit.ts, and scripts/generate-openapi.ts).

Follow-ups not in this PR

  • The stuck goal itself still needs to be cancelled or will pick up this fix on the next recovery after deploy.
  • A recovery attempt cap in recoverClaimedAttempt would bound any future unrecoverable prepare error.

🤖 Generated with Claude Code

…ling forever

A live goal whose saved checkout disappeared (for example pruned by the
host cleanup timer after its container exited) could never recover: the
worker job threw "Saved goal worktree is missing" out of preparation, which
left the attempt claimed with a dead heartbeat, and the recovery sweep
re-enqueued it ~every 2.5 minutes indefinitely. The task kept reporting
"Resuming native goal session" so the goal looked alive in the UI.

The rebuild logic already existed for operator-continued terminal goals but
was gated behind continue_requested. Extract it into
restoreMissingGoalWorktree and call it from ensureGoalWorktree, so a missing
checkout is rebuilt from the published branch (same directory name, so the
saved provider session resumes against the same mount path). The resumed
session is told its checkout was rebuilt and that uncommitted work is gone.

When the branch itself no longer exists on the remote there is nothing to
resume from, so preparation now finalizes the goal as failed (via the same
path continued-goal preparation failures use) instead of throwing, which is
what recovery would otherwise relaunch forever.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@integry integry added the AI label Oct 28, 2026
@integry

integry commented Oct 28, 2026

Copy link
Copy Markdown
Owner Author

/review

@propr-dev

propr-dev Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

✅ AI Code Review Complete requested by @integry

Posted 1 review:

View Task Details

@propr-dev

propr-dev Bot commented Oct 28, 2026

Copy link
Copy Markdown
Contributor

🔍 AI Code Review — claude:claude-opus-5-5

Overall Evaluation

This PR fixes an infinite recovery loop. When a live goal's checkout was pruned, ensureGoalWorktree threw, the attempt stayed claimed, and recovery relaunched it every ~2.5 minutes indefinitely.

The fix has three parts:

  • It extracts the existing rebuild-from-remote-branch logic into restoreMissingGoalWorktree. ensureGoalWorktree now uses it whenever the saved directory is gone.
  • It adds a terminal GoalWorktreeLostError for the case where the published branch no longer exists. prepareGoalCheckout converts that error into a fenced goal failure through the generalized failGoalPreparation.
  • It prepends a notice to the attempt feedback so the resumed session knows uncommitted work is gone.

I traced the restore path against the claim fences, the recovery producer (goalRecovery.ts), and the feedback consumers (Codex, Claude, Antigravity). I found no PR-introduced blocker. The PR is merge-ready, conditional on the pending CI shards completing green.

✅ Faithful reuse of hardened logic — retryTransient and attemptClaimGuard are lifted verbatim from prepareContinuedGoal. The restore path therefore inherits the same rules: retry once only on transient errors, and recheck authority before retrying. The new takeover test confirms this (a takeover during a transient rebuild error prevents the retry).

✅ Fenced path persistence — When the rebuild lands at a different path, the new worktree_path is written under the full attempt predicate (goal_id, current_task_id, run_generation, run_claim, null result_state) and re-read via fencedGoal. A superseded worker therefore cannot overwrite the replacement's checkout identity.

✅ Terminal handling for the lost-branch case — GoalWorktreeLostError is thrown before any DB mutation. It is caught narrowly in prepareGoalCheckout and finalized through the fenced finalizeGoal. As a result, the exact incident shape (claimed attempt, dead heartbeat, saved session) is no longer left behind when the branch is gone.

Merge blockers

No merge blockers.

Suggestions

These are optional follow-ups and are not sent to /fix.

S1: 🟢 Other permanent restore failures still loop

prepareGoalCheckout (src/jobs/processGoalJob.ts) rethrows every error except GoalWorktreeLostError, so some permanent failures still leave the attempt claimed for recovery to relaunch:

  • createWorktreeFromExistingBranch refusing a "missing but already registered" worktree whose detached HEAD holds unpublished commits (see test/worktreeLifecycle.integration.test.ts:817).
  • A repository access check that throws after the ref 404.
  • A non-transient filesystem error.
  • Goal worktree restoration left no checkout to resume.

That conflicts with the PR's stated principle that "no prepare failure should leave an attempt claimed with a dead heartbeat." This is not a regression, because these cases already threw before the PR. Classifying such errors as terminal (excluding claim-loss and transient errors) or landing the recovery attempt cap from the follow-up list would close the remaining loop shapes.

S2: 🟢 restored: true is set unconditionally

ensureGoalWorktree ignores the restored flag returned by restoreMissing and always reports restored: true. If the directory reappears between the existsSync check and restoreMissingGoalWorktree's own isDirectory check, the agent is wrongly told its uncommitted work was lost. Propagating the returned flag is a one-line change.

S3: 🟢 Notice dropped for whole-session providers with pending input

In runPreparedGoal, a non-native-control resumed session uses pendingInput?.message ?? checkpointFeedback as its prompt. When an input is pending, the rebuilt-checkout notice in checkpointFeedback is silently dropped for those providers. Native-control providers receive it via initialGoalFeedback. Prepending the notice to the prompt when worktree.restored is set would make delivery consistent.

S4: 🟢 No end-to-end test of the terminal failure path

The new tests cover restoreMissingGoalWorktree and ensureGoalWorktree in isolation. Nothing exercises prepareGoalCheckout → failGoalPreparation. A DB-backed test asserting that a lost branch yields result_state = 'failed' and a task marked failed would lock in the loop-breaking behavior. That behavior is the core of the fix.

S5: 🟢 Continued-goal rebuilds get no notice

When prepareContinuedGoal rebuilds an expired worktree, ensureGoalWorktree then sees an existing directory and returns without restored. The continued session is therefore not told its checkout was rebuilt. This path is pre-existing, but returning a rebuilt flag from prepareContinuedGoal would give both paths the same notice.

Score

The fix addresses the reported incident directly. It reuses already-fenced logic and has focused tests, and I found no PR-introduced correctness regression. Remaining gaps are pre-existing loop shapes and minor notice-delivery inconsistencies; merge readiness depends on the pending shards passing.

Score: 8/10


🤖 Review Details

  • Model: Claude Opus 5.5
  • Time: 38s
  • Tokens: 72,095 (68,306 in / 3,789 out)
  • Cost: $0.42

View Task


💡 Next step: Comment /fix to address every F# merge blocker, /fix all for every pending blocker and suggestion, or name records explicitly, as in /fix F3 S5.
F# and S# IDs increment across review comments and remain permanent, so selectors such as /fix F3 F5 stay unambiguous across cycles. S# suggestions stay optional: they are implemented only when you name them or request /fix all, and they never relax a merge blocker.

Copy and edit to choose records from this review:

/fix S1 S2 S3 S4 S5

🤖 Review by ProPR

@integry

integry commented Oct 28, 2026

Copy link
Copy Markdown
Owner Author

/review astra

@propr-dev

propr-dev Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

✅ AI Code Review Complete requested by @integry

Posted 1 review:

View Task Details

@propr-dev

propr-dev Bot commented Oct 28, 2026

Copy link
Copy Markdown
Contributor

🔍 AI Code Review — astra

Overall Evaluation

The PR adds a useful restoration path, but needs changes before merge: restoration errors can still reproduce the recovery loop, and some resumed sessions never receive the checkout-loss notice.

✅ Preserved checkout identity — Restoration reuses the saved directory name and branch; a changed path is persisted under the attempt claim.

✅ Confirmed branch loss — The restoration dependency checks repository access before treating a missing remote ref as lost work.

✅ Fenced retries — Transient failures recheck attempt ownership before retrying, with a test covering takeover during failure.

The supplied checks show no failures and four pending test shards. This review uses static analysis of the supplied code; no commands were run.

Merge blockers

Every finding below was introduced by this PR and must be resolved before merging.

F1: 🔴 Other restoration failures retain the recovery loop

  • Required behavior: Preparation failures must not leave a claimed, nonterminal attempt that recovery relaunches indefinitely.

  • Evidence: src/jobs/processGoalJob.ts, prepareGoalCheckout; src/jobs/goalContinuation.ts, restoreMissingGoalWorktree.

    1. A running goal has a saved session and a pruned checkout, but its remote branch still exists.
    2. Restoration encounters a persistent setup failure. One concrete supported case is a missing worktree registration containing an unpublished detached commit: the supplied lifecycle integration test establishes that rebuilding rejects with “missing but already registered.”
    3. retryTransient propagates that error, and prepareGoalCheckout rethrows it because it is not GoalWorktreeLostError.
    4. processGoalJob exits without finalizing the goal. Its heartbeat stops while the claimed attempt and saved identities remain.
    5. The supplied recovery path rotates the generation and launches restoration again against the same unresolved condition.

    The goal therefore remains visibly running without execution, reproducing the incident this PR intends to resolve. Ownership checks do not settle the attempt, and the transient retry does not handle this permanent refusal. The new tests check error propagation from helpers, not terminal settlement through preparation. Verification provenance — static trace: changed preparation and restoration paths, supplied recovery excerpts, and the supplied worktree lifecycle test.

  • Minimum fix: Route restoration failures through fenced preparation failure handling after the bounded retry, while allowing superseded attempts to exit without modifying their replacements. Preserve saved branch and checkout identities for operator recovery.

F2: 🔴 Restoration notices can disappear before delivery

  • Required behavior: A resumed session must be told that its checkout was rebuilt and unpublished working-tree state was lost.

  • Evidence: src/jobs/processGoalJob.ts, attemptFeedback, prepareClaimedGoalAttempt, and runPreparedGoal.

    1. A resumed whole-session provider, such as the tested opencode provider, has a pending user input when its checkout is restored.
    2. attemptFeedback creates the restoration notice in checkpointFeedback.
    3. runPreparedGoal chooses pendingInput.message ahead of checkpointFeedback, and supplies initialGoalFeedback only to native-control providers.
    4. The whole-session provider receives the user input without the restoration notice and continues against a checkout missing work remembered by its saved session.

    A second verified path loses the same notice before any provider starts: while restoration awaits remote/Git operations, an operator can pause the goal without changing its attempt claim. The subsequent boundary check returns paused before constructing feedback. On resume, the directory already exists, so restored is absent and the notice is never reconstructed. The claim guard does not exclude paused goals, and no durable notice records the completed restoration.

    Verification provenance — static trace: the supplied prompt-selection logic, pause boundary, restoration flag, and fencing contract. Neither path is covered by the added tests.

  • Minimum fix: Preserve a pending restoration notice across preparation exits until delivery, and include it alongside pending user input for whole-session providers. Retain the separate input-acknowledgement semantics for native providers.

Suggestions

These are optional follow-ups and are not sent to /fix.

S6: 🟢 Bound automatic recovery attempts

The proposed recovery cap remains a useful separate follow-up. Recovery currently rotates generations without a bound, so unrelated future worker failures could produce the same operational symptom. This is broader hardening beyond correcting the restoration paths in this PR.

Score

The restoration mechanism and claim-aware retry handling are sound improvements, but incomplete failure settlement and notice delivery leave two correctness gaps. Passing checks do not cover these sequences; four test shards remain pending.

Score: 6/10


🤖 Review Details

  • Model: GPT-6 Astra
  • Time: 55s
  • Tokens: 53,420 (52,151 in / 1,269 out)
  • Cost: $0.48

View Task


💡 Next step: Comment /fix to address every F# merge blocker, /fix all for every pending blocker and suggestion, or name records explicitly, as in /fix F3 S5.
F# and S# IDs increment across review comments and remain permanent, so selectors such as /fix F3 F5 stay unambiguous across cycles. S# suggestions stay optional: they are implemented only when you name them or request /fix all, and they never relax a merge blocker.

Copy and edit to choose records from this review:

/fix F1 F2 S6

🤖 Review by ProPR

@integry

integry commented Oct 28, 2026

Copy link
Copy Markdown
Owner Author

/fix

@propr-dev

propr-dev Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

✅ Applied the requested follow-up changes in commit d3f7eb0

Addressed 1 AI review comment (IDs: 6482868444)

Addressed findings F1, F2

Summary of Changes

Implemented F1 and F2 only.

  • Restoration failures now settle through fenced preparation failure handling while preserving saved recovery identities.
  • Durable restoration notices survive preparation exits and reach providers without conflating native user-input acknowledgements.
  • All 50 focused tests pass. TypeScript, ESLint, and diff checks pass.

🤖 Implementation Details

  • Model: GPT-6.1 Sol (medium)
  • Requested By: @integry
  • Time: 6m 13s
  • Tokens: 1,013,871 (1,003,895 in / 9,976 out)
  • Cost: $0.29

Undo Changes • View Task Execution


💡 ProPR Slash Commands
Command Description Example
/merge Merge target branch into this PR and resolve conflicts /merge
/review Request an AI code review /review or /review claude-sonnet
/fix Address review blockers, or blockers and suggestions with /fix all /fix, /fix all, or /fix F3 S5
/switch Change the AI model for this PR /switch claude-opus
/use Override the model for a single follow-up run /use claude-sonnet
/ultrafix Loop review→fix cycles until score goal is met /ultrafix or /ultrafix goal=8 max=10

🤖 Generated by ProPR
Processing comment ID: 6483413357✓

Implemented F1 and F2 only.

- Restoration failures now settle through fenced preparation failure handling while preserving saved recovery identities.
- Durable restoration notices survive preparation exits and reach providers without conflating native user-input acknowledgements.
- All 50 focused tests pass. TypeScript, ESLint, and diff checks pass.

PR: #3366
Comment by: @integry (ID: 6483413357)
Model: GPT-6.1 Sol
@integry

integry commented Oct 28, 2026

Copy link
Copy Markdown
Owner Author

/review astra

@propr-dev

propr-dev Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

✅ AI Code Review Complete requested by @integry

Posted 1 review:

View Task Details

@propr-dev

propr-dev Bot commented Oct 28, 2026

Copy link
Copy Markdown
Contributor

🔍 AI Code Review — astra

Overall Evaluation

The PR addresses missing-checkout recovery with shared restoration logic and durable agent notices, but two failure paths still need correction before merge.

✅ Fenced persistence — Worktree updates and restoration notices share a transaction guarded by task, generation, claim, and nonterminal state.

✅ Preparation failures settle — Checkout errors now reach goal finalization, with tests covering permanent failures, exhausted transient retries, and takeover.

Review verification was static only, as requested. Current checks show no failures and five pending.

Merge blockers

Every finding below was introduced by this PR and must be resolved before merging.

F3: 🔴 Pending notices cause unlimited failed attempts

  • Required behavior: Restoration must not introduce another indefinite recovery loop when execution cannot proceed.

  • Evidence: src/jobs/processGoalJob.ts, acknowledgeWholeSessionInput and its interaction with scheduleFurtherWork.

    1. An existing OpenCode session resumes after its checkout is restored; the restoration notice is pending.
    2. The provider returns success: false with a permanent execution error.
    3. The changed acknowledgement code deliberately leaves the restoration notice pending.
    4. scheduleFurtherWork finds that pending input and enqueues another attempt before checking whether the failure is recoverable.
    5. Every subsequent failed execution leaves the same notice pending and schedules another attempt.

    The goal remains running indefinitely instead of reaching failure. Claim fences and heartbeats do not prevent this because each attempt legitimately owns its claim. The new tests verify retention after failure but do not exercise the subsequent scheduling decision.

    static trace: the supplied acknowledgement, result-handling, and scheduling implementations establish this sequence without relying on a concurrency assumption.

  • Minimum fix: Preserve undelivered notices, but prevent a pending restoration notice from overriding terminal execution failure. Apply failure classification or a bounded retry decision before scheduling another attempt solely to deliver that notice.

F4: 🔴 Rebuild completion can lose its notice

  • Required behavior: A resumed agent must receive the restoration warning whenever its checkout was reconstructed, including after worker recovery.

  • Evidence: src/jobs/goalContinuation.ts, restoreMissingGoalWorktree and prepareContinuedGoal.

    1. A saved checkout is missing, and rebuildWorktree successfully recreates it at the saved path.
    2. The worker exits after the filesystem operation completes but before the subsequent transaction records the restoration notice.
    3. After the heartbeat becomes stale, recovery rotates the claim and launches another attempt using the saved session and path.
    4. The checkout now exists, so restoration is skipped. No pending notice exists, and the saved session resumes without being told its uncommitted work disappeared.

    The same ordering exists in continued-goal preparation. The transaction protects the database update and notice together, but it starts after the filesystem mutation; it cannot recover the missing obligation. Existing pause and takeover tests do not cover worker interruption at this boundary.

    static trace: both restoration paths persist the notice after rebuilding, while the supplied recovery path relaunches the saved session and existing-directory checks bypass restoration.

  • Minimum fix: Persist a fenced restoration obligation before rebuilding, in both paths, and retain it until delivery. Alternatively, persist restoration intent that the next attempt reconciles even when the directory already exists.

Suggestions

These are optional follow-ups and are not sent to /fix.

No suggestions.

Score

The implementation has useful fencing and focused coverage, but unsuccessful execution can loop indefinitely and worker interruption can silently lose the restoration warning. Both require localized corrections.

Score: 5/10


🤖 Review Details

  • Model: GPT-6 Astra
  • Time: 1m 1s
  • Tokens: 52,014 (50,687 in / 1,327 out)
  • Cost: $0.44

View Task


💡 Next step: Comment /fix to address every F# merge blocker, /fix all for every pending blocker and suggestion, or name records explicitly, as in /fix F3 S5.
F# and S# IDs increment across review comments and remain permanent, so selectors such as /fix F3 F5 stay unambiguous across cycles. S# suggestions stay optional: they are implemented only when you name them or request /fix all, and they never relax a merge blocker.

Copy and edit to choose records from this review:

/fix F3 F4

🤖 Review by ProPR

@integry

integry commented Oct 28, 2026

Copy link
Copy Markdown
Owner Author

/ultrafix

@propr-dev propr-dev Bot added the ultrafix label Oct 28, 2026
@propr-dev

propr-dev Bot commented Oct 28, 2026

Copy link
Copy Markdown
Contributor

🔄 Ultrafix loop started (goal: 8/10, max cycles: 10)

First action: /fix

💡 Tip: Remove the ultrafix label from this PR to stop further ultrafix cycles.

@propr-dev

propr-dev Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

✅ Applied the requested follow-up changes in commit fc0c16e

Addressed 1 AI review comment (IDs: 6483615143)

Addressed findings F3, F4

Summary of Changes

Implemented F3 and F4 only.

  • Pending restoration notices no longer trigger retries after permanent execution failures.
  • Both rebuild paths persist fenced notice obligations before filesystem changes and retain them through worker recovery until delivery.
  • Added regressions for interruptions, claim takeovers, delivery, and failure scheduling.

Validation: all 62 focused tests pass; TypeScript, source ESLint, and diff checks pass. No visual preview needed.


🤖 Implementation Details

  • Model: GPT-6.1 Sol (medium)
  • Requested By: @integry
  • Time: 4m 16s
  • Tokens: 640,511 (634,449 in / 6,062 out)
  • Cost: $0.21
  • Subscription usage: Weekly +1%

Undo Changes • View Task Execution


💡 ProPR Slash Commands
Command Description Example
/merge Merge target branch into this PR and resolve conflicts /merge
/review Request an AI code review /review or /review claude-sonnet
/fix Address review blockers, or blockers and suggestions with /fix all /fix, /fix all, or /fix F3 S5
/switch Change the AI model for this PR /switch claude-opus
/use Override the model for a single follow-up run /use claude-sonnet
/ultrafix Loop review→fix cycles until score goal is met /ultrafix or /ultrafix goal=8 max=10

🤖 Generated by ProPR
Processing comment ID: 6483786934✓

Implemented F3 and F4 only.

- Pending restoration notices no longer trigger retries after permanent execution failures.
- Both rebuild paths persist fenced notice obligations before filesystem changes and retain them through worker recovery until delivery.
- Added regressions for interruptions, claim takeovers, delivery, and failure scheduling.

Validation: all 62 focused tests pass; TypeScript, source ESLint, and diff checks pass. No visual preview needed.

PR: #3366
Comment by: @integry (ID: 6483786934)
Model: GPT-6.1 Sol
@propr-dev

propr-dev Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

✅ AI Code Review Complete requested by @propr-ultrafix

Posted 1 review:

View Task Details

@propr-dev

propr-dev Bot commented Oct 29, 2026

Copy link
Copy Markdown
Contributor

🔍 AI Code Review — claude:claude-opus-5-5

Overall Evaluation

The PR fixes the endless relaunch loop for a live goal whose saved checkout was pruned. There are three parts to the fix:

  • Rebuild instead of throw. ensureGoalWorktree now rebuilds the checkout from the published branch through restoreMissingGoalWorktree.
  • Fail the goal, not the job. prepareGoalCheckout routes every checkout-preparation failure into failGoalPreparation, so the goal finalizes instead of throwing out with the attempt still claimed.
  • Durable notice. The "your checkout was rebuilt" warning is stored as a goal_inputs row with kind: 'restoration'. Whole-session and native providers deliver and acknowledge it differently.

The fencing work is careful. The obligation is committed under a FOR UPDATE claim check before any external mutation. The rebuilt path is saved only under the current claim. The retry helper rechecks authority before its second try. Tests cover pause, takeover, interruption and the provider-specific delivery paths.

One defect remains. The durable notice outlives the cases where its text is true. When the goal moves to a fresh branch, the agent is told its checkout holds the last published checkpoint when it actually holds only the base branch. This needs a small fix before merge.

✅ Obligation-before-mutation ordering — persistRestorationObligation commits the notice under a locked claim check before rebuildWorktree runs. The interruption tests show a recovered attempt neither duplicates the notice nor loses it.

✅ Prepare failures can no longer leave a claimed zombie — prepareGoalCheckout catches errors from both continuation and checkout restoration and finalizes the goal through the fenced finalizeGoal. This removes the exact claimed-with-dead-heartbeat shape the recovery sweep relaunched.

✅ Independent acknowledgement identities — for native providers, prepareGoalAttemptInputs sends only the notice as initialControlInputId, leaving user input in the FIFO queue. The provider tests show acknowledging the notice does not discharge the user message.

Merge blockers

Every finding below was introduced by this PR and must be resolved before merging.

F5: 🔴 Restoration notice survives a move to a fresh branch and misinforms the agent

  • Required behavior: The restoration notice must truthfully describe the checkout the resumed agent receives. The PR objective says the agent is told the checkout was rebuilt from the branch carrying every published checkpoint. That statement is false once the goal has moved to a fresh branch cut from base.

  • Evidence: src/jobs/goalContinuation.ts:164-175 (prepareContinuedGoal, the rebuilt === null → FRESH_BRANCH branch), together with persistRestorationObligation and restoreMissingGoalWorktree.

    Static trace:

    1. A continued goal (continue_requested) has a saved worktree_path that was pruned, and its remote branch was deleted.
    2. In prepareContinuedGoal, persistRestorationObligation commits a pending kind: 'restoration' input whose text is GOAL_WORKTREE_RESTORED_NOTICE.
    3. rebuildWorktree returns null (branch confirmed absent), so updates gets FRESH_BRANCH and the goal row's worktree_path and branch_name are cleared. Nothing touches the pending notice.
    4. ensureGoalWorktree then allocates a brand-new worktree from the base branch through createWorktreeForIssue.
    5. prepareGoalAttemptInputs gives the notice top priority. The agent is told the checkout "contains the last published checkpoint; any uncommitted changes from before are lost", while it actually holds none of the goal's prior commits.

    The same stale notice also reaches the agent through a second path:

    1. A live goal hits GoalWorktreeLostError in restoreMissingGoalWorktree. The notice was persisted before the rebuild, so it stays pending after the goal fails.
    2. Separately, a restored attempt can fail permanently; scheduleFurtherWork deliberately leaves the notice pending in that case.
    3. In either case, a later operator continue that takes the merged-PR or branch-gone FRESH_BRANCH path delivers the leftover notice against a fresh base checkout.

    Consequence: the provider session remembers its prior work and is told that work is in the checkout. It can then conclude the work is done, or build on files that are not there, and publish a PR missing earlier checkpoints.

    Existing protections do not catch this. The deduplication in persistRestorationObligation only prevents duplicate notices; it never retracts one. No path marks restoration inputs superseded when the branch identity is reset. The existing test 'a deleted remote branch continues on a fresh branch' does not assert anything about goal_inputs.

  • Minimum fix: In the transaction in prepareContinuedGoal that applies FRESH_BRANCH, mark any pending kind: 'restoration' inputs for the goal as superseded or undeliverable (for example state: 'superseded' plus a delivery_error), or delete them. Do this both when rebuilt === null and when a merged PR forces a fresh branch. Add assertions to the existing branch-gone and merged-PR continuation tests that no pending restoration input remains.

Suggestions

These are optional follow-ups and are not sent to /fix.

S7: 🟢 Transient rebuild failures now fail the goal terminally

prepareGoalCheckout turns any ensureGoalWorktree error into a failed goal. That includes a second consecutive fetch failed, which the new test explicitly expects to fail. This stops the infinite loop, but a brief GitHub outage during recovery now ends a long-running goal that needs an operator continue. A bounded retry or attempt cap in recovery, as the PR's own follow-up notes, would let transient outages self-heal without reopening the loop.

S8: 🟢 Pending notice can re-trigger "continuing" on native success

For native providers, a successful run that never steered the notice re-enqueues the goal, because scheduleFurtherWork uses firstPendingGoalInput when result.success is true. One example is Claude's start() returning early from recordedVerdict. A queued user input already behaves this way, but the restoration notice is created by the system itself. It is worth confirming that a recorded-verdict session cannot loop on an undeliverable notice.

S9: 🟢 Skipped control acknowledgement on failed restoration-only turns

When acknowledgeWholeSessionInput has no ids to deliver, it now returns early. That happens for a failed whole-session turn whose only input is the notice. In that case it also skips the control_ack_generation update the old code always made. This is probably harmless, but it is a quiet behavior change worth either a comment or keeping the ack update.

S10: 🟢 Unused restored flag and mismatched failure wording

GoalWorktree.restored is set but never read; delivery happens through goal_inputs. Also, failGoalPreparation labels fresh-worktree allocation errors "Could not restore the goal checkout". Either drop the flag or use it, for example for logging or metrics, and make the reason text match the path taken.

Score

The core loop fix is sound, well fenced and well tested, and no checks have failed (four test shards are still running). However, the new durable restoration notice can give the agent false information after a move to a fresh branch, and that needs a small fix before merge.

Score: 6/10


🤖 Review Details

  • Model: Claude Opus 5.5
  • Time: 1m 7s
  • Tokens: 82,054 (75,455 in / 6,599 out)
  • Cost: $0.51

View Task


💡 Next step: Comment /fix to address every F# merge blocker, /fix all for every pending blocker and suggestion, or name records explicitly, as in /fix F3 S5.
F# and S# IDs increment across review comments and remain permanent, so selectors such as /fix F3 F5 stay unambiguous across cycles. S# suggestions stay optional: they are implemented only when you name them or request /fix all, and they never relax a merge blocker.

Copy and edit to choose records from this review:

/fix F5 S7 S8 S9 S10

🤖 Review by ProPR

@propr-dev

propr-dev Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

✅ Applied the requested follow-up changes in commit 5aefc43

Addressed 1 AI review comment (IDs: 6483978762)

Addressed finding F5

Summary of Changes

Addressed F5 only. Both fresh-branch paths now supersede pending restoration notices atomically with the branch reset.

Regressions cover deleted branches, merged PRs, notices retained after failures, and claim loss during awaited operations. Both test files pass; source ESLint passes.

No visual preview needed for this backend change.


🤖 Implementation Details

  • Model: GPT-6.1 Sol (medium)
  • Requested By: @propr-ultrafix
  • Time: 3m 15s
  • Tokens: 395,300 (392,156 in / 3,144 out)
  • Cost: $0.14

View Task Execution


💡 ProPR Slash Commands
Command Description Example
/merge Merge target branch into this PR and resolve conflicts /merge
/review Request an AI code review /review or /review claude-sonnet
/fix Address review blockers, or blockers and suggestions with /fix all /fix, /fix all, or /fix F3 S5
/switch Change the AI model for this PR /switch claude-opus
/use Override the model for a single follow-up run /use claude-sonnet
/ultrafix Loop review→fix cycles until score goal is met /ultrafix or /ultrafix goal=8 max=10

🤖 Generated by ProPR

…nding restoration notices atomically with the branch reset.

Addressed F5 only. Both fresh-branch paths now supersede pending restoration notices atomically with the branch reset.

Regressions cover deleted branches, merged PRs, notices retained after failures, and claim loss during awaited operations. Both test files pass; source ESLint passes.

No visual preview needed for this backend change.

PR: #3366
Comment by: @propr-ultrafix (ID: 0)
Model: GPT-6.1 Sol
@propr-dev

propr-dev Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

✅ AI Code Review Complete requested by @propr-ultrafix

Posted 1 review:

View Task Details

@propr-dev

propr-dev Bot commented Oct 29, 2026

Copy link
Copy Markdown
Contributor

🔍 AI Code Review — claude:claude-opus-5-5

Overall Evaluation

The PR fixes a recovery loop. A live goal whose saved checkout was pruned no longer throws out of processGoalJob with its attempt still claimed. Instead:

  • Checkout rebuilt from the branch. ensureGoalWorktree calls a new restoreMissingGoalWorktree, which rebuilds the checkout from the published branch under the attempt claim.
  • Unrecoverable cases fail the goal. A lost branch, or any other unrecoverable preparation error, now finalizes the goal through failGoalPreparation.
  • The agent is told. The PR goes further than its description: the restoration notice is a durable goal_inputs row (kind: 'restoration'), not just text in the attempt feedback. Each transport acknowledges it:
    • native providers through markInputDelivered;
    • whole-session providers only on a successful turn.
  • Notices cannot cause their own loop. scheduleFurtherWork was adjusted so an undelivered notice cannot turn a permanent execution failure into endless rescheduling.

I traced the claim/fence paths, the four restore failure modes, the pause, takeover and interruption interleavings, and the provider delivery paths. All of them hold up, and CI is fully green. I found no merge blockers. The PR is ready to merge, with a few optional follow-ups below.

✅ Obligation committed before external mutation — persistRestorationObligation inserts the notice inside a transaction that locks the claimed row (forUpdate) before rebuildWorktree runs.

  • A crash or takeover mid-rebuild therefore leaves the notice for the replacement attempt.
  • The "only if none pending" check deduplicates across recovery generations.
  • The interruption-before/after-rebuild tests cover this.

✅ No prepare failure leaves a claimed, stale attempt — prepareGoalCheckout wraps both prepareContinuedGoal and ensureGoalWorktree.

  • failGoalPreparation is fenced: a takeover yields skipped and never finalizes another attempt's goal.
  • This is the exact shape that produced the 121-generation loop, and the parameterized processGoalJob test checks it for each failure mode.

✅ Failure-safe acknowledgement and scheduling — acknowledgeWholeSessionInput releases restoration ids only when result.success, while still acknowledging user input as before.

  • scheduleFurtherWork ignores restoration-only pending inputs on non-recoverable failure, so a permanent error still terminates.
  • When a continued goal moves to a fresh branch, prepareContinuedGoal supersedes stale notices.

Merge blockers

No merge blockers.

Suggestions

These are optional follow-ups and are not sent to /fix.

S11: 🟢 Transient rebuild outage now terminal for live goals

restoreMissingGoalWorktree retries a transient error once. A second consecutive network failure (e.g. GitHub 5xx or ECONNRESET) then reaches prepareGoalCheckout, and the goal is finalized as failed. This is intentional: it bounds the loop the PR fixes, and the operator can continue the goal. Still, a long-running goal can die from a brief outage. The attempt cap in recoverClaimedAttempt that the PR lists as a follow-up would allow a few bounded retries for transient errors. Only GoalWorktreeLostError and claim-independent permanent errors would then fail immediately.

S12: 🟢 Rejected-checkpoint feedback suppressed by a pending notice

previousCheckpointFeedback returns undefined whenever pendingInput is set, and it only looks at run_generation - 1. If the previous attempt rejected or published a checkpoint and the checkout was then pruned, the restoration notice displaces that feedback. A later attempt will not find it either. This edge case is narrow and matches the existing behaviour for user input. Appending checkpointFeedback to restoration notices for whole-session providers would preserve it.

S13: 🟢 Fresh whole-session start pauses on a pending notice

For a whole-session provider with no session_id, a restoration notice with kind: 'restoration' is not included in the initial prompt. onSessionId then sees a pending input and pauses/aborts the run, which resumes on the next attempt. The outcome is correct but wastes one startup. This mostly applies to the continue path, since recovery requires a saved session. Treating restoration notices like context inputs for fresh sessions would avoid the extra cycle.

S14: 🟢 Check other goal_inputs consumers for the new kind

kind: 'restoration' rows now share goal_inputs with operator inputs. Other consumers may assume every pending row is user-authored, such as console input history, pending-input badges, and cancel/supersede flows. I could not inspect those from the supplied context. A quick audit, or a filter where operator-only semantics are intended, would avoid confusing UI output.

S15: 🟢 Restoration runs before the cancelled/paused boundary check

ensureGoalWorktree rebuilds a missing checkout, and records a notice, before prepareClaimedGoalAttempt checks desired_state. A goal cancelled just before the attempt is claimed may therefore do a clone and worktree build it never uses. This is harmless but avoidable: skip restoration when the fenced goal is no longer running.

Score

The PR closes the reported recovery loop with properly fenced, durable restoration, and its tests are thorough across the takeover, interruption and provider paths. CI is green, and no verified blockers remain.

Score: 8/10


🤖 Review Details

  • Model: Claude Opus 5.5
  • Time: 59s
  • Tokens: 84,272 (78,556 in / 5,716 out)
  • Cost: $0.51

View Task


💡 Next step: Comment /fix to address every F# merge blocker, /fix all for every pending blocker and suggestion, or name records explicitly, as in /fix F3 S5.
F# and S# IDs increment across review comments and remain permanent, so selectors such as /fix F3 F5 stay unambiguous across cycles. S# suggestions stay optional: they are implemented only when you name them or request /fix all, and they never relax a merge blocker.

Copy and edit to choose records from this review:

/fix S11 S12 S13 S14 S15

🤖 Review by ProPR

@propr-dev propr-dev Bot removed the ultrafix label Oct 29, 2026
@integry
integry merged commit 2727fe3 into main Oct 29, 2026
45 checks passed
propr-dev Bot pushed a commit that referenced this pull request Oct 29, 2026
…) into the branch and added both fixes to the 0.9.0 release notes. One catch: this is not a real merge commit, because `git merge` can't run in this workspace. Git's metadata folder is read-only here, so it failed trying to write `ORIG_HEAD`. Instead I made the working tree match what the merge would produce:

I brought `main` (`2727fe3ad`, which includes #3364 and #3366) into the branch and added both fixes to the 0.9.0 release notes. One catch: this is not a real merge commit, because `git merge` can't run in this workspace. Git's metadata folder is read-only here, so it failed trying to write `ORIG_HEAD`. Instead I made the working tree match what the merge would produce:

- **Files only `main` changed** (8 of them, from the two PRs) were copied over from `origin/main` unchanged.
- **`src/jobs/processGoalJob.ts`** was changed on both sides, so I combined it with a three-way merge. There were no conflicts, and the only difference from `main` is this branch's earlier agent-failure-reason change.

When ProPR commits this, the commit will have one parent rather than two, so GitHub may still show the branch as behind `main`. The contents will merge cleanly either way. If you need a true merge commit, use ProPR's merge-from-main flow.

**Release notes:**
- **`CHANGELOG.md`**: no existing bullet covered goal recovery, and **Worker restarts** under 0.9.0 **Fixed** already covers worker recovery and storage claims. So I added both fixes to that bullet rather than starting new ones.
- **`docs/release-0.9.0-audit.md`**: I added a "Later merges" note to the end of the 2026-10-29 section. It lists #3364 and #3366 and says the release scope now runs through `2727fe3ad`.

Nothing else changed. There's nothing visual here, so I made no previews.

**Checks:**
- `EXPECTED_VERSION=0.9.0 RELEASE_TAG=v0.9.0 RELEASE_CANDIDATE=true npm run release:verify`: passed ("Release metadata is consistent for v0.9.0").
- `node --test test/releaseValidation.test.mjs`: all 15 tests passed.
- `git diff --check` is clean, and eslint with zero warnings allowed passes on the merged `processGoalJob.ts`.
- `test/processGoalJob.test.ts` (18), `test/goalContinuation.test.ts` (46) and `test/workerTaskStateRecovery.test.ts` (11) all pass when run one file at a time. Running all three in a single `tsx --test` command gave 46 failures. I put that down to the files clashing with each other rather than the merge, since every file passes alone, but I didn't confirm it.

I didn't merge, tag, publish or deploy anything.

PR: #3368
Comment by: @integry (ID: 6484905795)
Model: Claude Opus 5.5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants