fix: restore escalation-to-PR lifecycle#112
Conversation
|
Warning Review limit reached
Next review available in: 58 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (7)
📝 WalkthroughWalkthroughThe PR adds GitHub ref writeback fallback and provider failure details, revises Factory dispatch, reconciliation, delivery, triage, Slack identity, babysitter, and issue-matching flows, updates writeback validation, and expands heuristic acceptance detection. ChangesGitHub writeback and mount validation
Factory lifecycle and triage
Estimated code review effort: 5 (Critical) | ~100 minutes Sequence Diagram(s)sequenceDiagram
participant GitHubIssue
participant FactoryLoop
participant Slack
participant GithubConnectionWrite
GitHubIssue->>FactoryLoop: provide issue, labels, and reporter identity
FactoryLoop->>Slack: resolve reporter and mirror triage escalation
Slack-->>FactoryLoop: clarification or actionable reply
FactoryLoop->>GithubConnectionWrite: publish or reconcile pull request
GithubConnectionWrite-->>FactoryLoop: pull request receipt
Possibly related PRs
Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Code Review
This pull request introduces improvements to the local-clone publication retry logic by handling existing branches, enhances the cleanup of failed dispatches, ignores non-critical delivery failures, and expands the triage escalation questions with detailed reply instructions. The review feedback highlights two important improvements: first, typing the issue parameter in triageEscalationQuestion more generically to prevent TypeScript compilation errors when called with GitHub issues; second, making the isGithubReferenceAlreadyExistsError check more robust by safely extracting the message property from plain object API errors that do not inherit from the standard Error class.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
| } | ||
|
|
||
| const triageEscalationQuestion = (decision: TriageDecision): string => { | ||
| const triageEscalationQuestion = (decision: TriageDecision, issue?: LinearIssue): string => { |
There was a problem hiding this comment.
The issue parameter is typed as LinearIssue, but this function is also called from #escalateTriageToGithub where the issue is retrieved from a GitHub path and is a GitHub issue object rather than a LinearIssue. To prevent TypeScript compilation errors and ensure type safety, we should use a more generic structural type since only the title property is accessed.
| const triageEscalationQuestion = (decision: TriageDecision, issue?: LinearIssue): string => { | |
| const triageEscalationQuestion = (decision: TriageDecision, issue?: { title?: string }): string => { |
| const isGithubReferenceAlreadyExistsError = (error: unknown): boolean => | ||
| /reference already exists/iu.test(errorMessage(error)) |
There was a problem hiding this comment.
The errorMessage helper only extracts the message property if the error is an instance of Error. However, API errors (such as those from GitHub/Octokit or other HTTP clients) are often plain objects or custom error types that do not inherit from Error. If such an error is thrown, errorMessage will return "[object Object]", causing the regex check to fail. We should make this check more robust by safely extracting the message property from plain objects as well.
| const isGithubReferenceAlreadyExistsError = (error: unknown): boolean => | |
| /reference already exists/iu.test(errorMessage(error)) | |
| const isGithubReferenceAlreadyExistsError = (error: unknown): boolean => { | |
| const msg = error instanceof Error ? error.message : (error && typeof error === 'object' && 'message' in error ? String((error as any).message) : String(error)) | |
| return /reference already exists/iu.test(msg) | |
| } |
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@src/mount/relayfile-github-connection-write.ts`:
- Around line 72-74: The existing-reference fallback must inspect the provider
failure reason preserved or exposed by confirmWrite, rather than relying on a
discarded original error. Update
src/mount/relayfile-github-connection-write.ts:72-74 around confirmWrite and
isGithubReferenceAlreadyExistsError to use that failure detail; update
src/mount/relayfile-github-connection-write.test.ts:153-159 to simulate the
concrete failed-confirmation result instead of throwing the provider response
directly.
In `@src/orchestrator/factory.ts`:
- Around line 4172-4181: The abandonment path around `#dispatchFailureHandoffs`
must also release agents not represented by worktreeHandoffs before the batch
completes; update src/orchestrator/factory.ts lines 4172-4181 to identify and
pass those agents to `#releaseAndTerminateAgents` while preserving worktree
teardown. Extend src/orchestrator/factory.test.ts lines 7400-7424 with a
non-worktree agent and assert that it is released.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: a846b936-79e0-418a-820a-71525a948a5f
📒 Files selected for processing (4)
src/mount/relayfile-github-connection-write.test.tssrc/mount/relayfile-github-connection-write.tssrc/orchestrator/factory.test.tssrc/orchestrator/factory.ts
There was a problem hiding this comment.
Actionable comments posted: 5
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/mount/relayfile-github-connection-write.ts (1)
63-82: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick winSerialize create-ref writes that share
refs/factory.json.Concurrent PR publications for the same repository overwrite the mount’s path-keyed operation ID between
writeFileandconfirmWrite. One caller can therefore confirm another branch’s operation and open a PR before its own ref exists. Queue the complete write-and-confirm sequence per create path.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/mount/relayfile-github-connection-write.ts` around lines 63 - 82, Serialize the complete create-ref write-and-confirm sequence in the head-ref creation flow around `#writeAndConfirm` and createRefPath, using a per-path queue or lock keyed by createRefPath. Ensure concurrent publications sharing refs/factory.json cannot overwrite each other’s operation state, while preserving the existing already-exists fallback to updateRefPath and keeping unrelated repository paths independent.
♻️ Duplicate comments (1)
src/orchestrator/factory.ts (1)
4222-4226: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winFailed non-worktree releases lose all durable ownership during abandonment.
src/orchestrator/factory.ts#L4222-L4226: retain or persist agents returned as failed before completing the batch record.src/orchestrator/factory.test.ts#L7550-L7556: simulate a release rejection and verify cleanup remains retryable.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/orchestrator/factory.ts` around lines 4222 - 4226, When abandoning a batch in `#releaseAndTerminateAgents`, preserve or persist any non-worktree agents whose release fails before the batch record is completed, so their ownership remains retryable. Update src/orchestrator/factory.ts lines 4222-4226 accordingly, and in src/orchestrator/factory.test.ts lines 7550-7556 add coverage that simulates a release rejection and verifies cleanup remains retryable.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@src/mount/relayfile-cloud-mount-client.test.ts`:
- Around line 1069-1070: Extend the integration tests around mount confirmation
and getConfirmedWriteFailureReason to cover a concrete “reference already
exists” confirmation failure. Assert that the rejected confirmation is consumed
by the writer and reaches the update-ref fallback, rather than only verifying
the stored failure detail after a resolved failed status.
In `@src/mount/relayfile-cloud-mount-client.ts`:
- Around line 446-452: The retained provider failure reason must remain
available to the writer in both outcomes. In
src/mount/relayfile-cloud-mount-client.ts lines 446-452, retain the reason for
returned failed statuses or expose it when rethrowing; in
src/mount/relayfile-github-connection-write.ts lines 145-152, retrieve it when
confirmWrite rejects as well as when it resolves failed; in
src/mount/relayfile-cloud-mount-client.test.ts lines 1069-1070, add coverage
proving a concrete existing-reference failure triggers update-ref fallback.
In `@src/orchestrator/factory.test.ts`:
- Around line 7550-7556: Add coverage in the mixed-abandonment test around the
fleet release flow, using a fleet stub that rejects one non-worktree release.
Assert that after the failure the affected agent remains durably tracked or
dispatch ownership remains in factory.status().inFlight for retry, while
preserving the existing cleanup and successful-release assertions.
- Around line 1939-1991: The live-state-race test currently covers only the
worktree-managed path. Add a corresponding no-worktree case around
ConcurrentStateChangeMount and the factory run, omit the worktrees dependency,
and assert that both raced issue agents are released while preserving the
skipped race result and zero-error expectations.
In `@src/orchestrator/factory.ts`:
- Around line 2079-2092: Release any agents spawned for the dispatch before
calling batch.abandon in the live-state-race handling around the error path in
src/orchestrator/factory.ts:2079-2092, including when no worktree manager is
configured; preserve the existing abandonment and retry flow. Add the
corresponding no-worktree live-state race test in
src/orchestrator/factory.test.ts:1939-1991 and verify that spawned agents are
released.
---
Outside diff comments:
In `@src/mount/relayfile-github-connection-write.ts`:
- Around line 63-82: Serialize the complete create-ref write-and-confirm
sequence in the head-ref creation flow around `#writeAndConfirm` and
createRefPath, using a per-path queue or lock keyed by createRefPath. Ensure
concurrent publications sharing refs/factory.json cannot overwrite each other’s
operation state, while preserving the existing already-exists fallback to
updateRefPath and keeping unrelated repository paths independent.
---
Duplicate comments:
In `@src/orchestrator/factory.ts`:
- Around line 4222-4226: When abandoning a batch in `#releaseAndTerminateAgents`,
preserve or persist any non-worktree agents whose release fails before the batch
record is completed, so their ownership remains retryable. Update
src/orchestrator/factory.ts lines 4222-4226 accordingly, and in
src/orchestrator/factory.test.ts lines 7550-7556 add coverage that simulates a
release rejection and verifies cleanup remains retryable.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 42be46a1-6a6e-40a2-a75e-7d64217afcf7
📒 Files selected for processing (11)
src/cli/fleet.test.tssrc/cli/fleet.tssrc/mount/relayfile-cloud-mount-client.test.tssrc/mount/relayfile-cloud-mount-client.tssrc/mount/relayfile-github-connection-write.test.tssrc/mount/relayfile-github-connection-write.tssrc/orchestrator/factory.test.tssrc/orchestrator/factory.tssrc/ports/mount.tssrc/triage/heuristic.tssrc/triage/triage.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- src/mount/relayfile-github-connection-write.test.ts
| it('continues startup reconciliation when an issue changes state during dispatch', async () => { | ||
| const racedPath = githubIssuePath('AgentWorkforce', 'pear', 59) | ||
| const freshPath = githubIssuePath('AgentWorkforce', 'pear', 60) | ||
| const racedReady = githubIssueFile(59, { labels: ['factory', 'pear'] }) | ||
| class ConcurrentStateChangeMount extends FakeMountClient { | ||
| racedReads = 0 | ||
|
|
||
| override async readFile(path: string): Promise<{ content: unknown; revision?: string }> { | ||
| if (path === racedPath) { | ||
| this.racedReads += 1 | ||
| if (this.racedReads >= 3) { | ||
| return { | ||
| content: githubIssueFile(59, { labels: ['factory', 'pear', 'factory:in-progress'] }), | ||
| } | ||
| } | ||
| } | ||
| return super.readFile(path) | ||
| } | ||
| } | ||
| const mount = new ConcurrentStateChangeMount({ | ||
| [racedPath]: racedReady, | ||
| [freshPath]: githubIssueFile(60, { labels: ['factory', 'pear'] }), | ||
| }) | ||
| const fleet = new FakeFleetClient() | ||
| const worktrees = new RecordingWorktreeManager() | ||
| const factory = createFactory(config({ issueSource: 'github', batchSize: 4 }), { | ||
| mount, | ||
| fleet, | ||
| triage: new StaticTriage(), | ||
| githubWriteback: new RecordingGithubWriteback(), | ||
| worktrees, | ||
| }) | ||
|
|
||
| const report = await factory.runOnce() | ||
|
|
||
| expect(report.skipped).toContainEqual({ | ||
| issue: { uuid: 'AgentWorkforce/pear#59', key: '59', path: racedPath }, | ||
| reason: 'live state changed during dispatch', | ||
| }) | ||
| expect(report.dispatched.map((result) => result.issue.key)).toEqual(['60']) | ||
| expect(fleet.spawns.map((spawn) => spawn.name)).toEqual([ | ||
| 'ar-59-impl-pear', | ||
| 'ar-59-review-pear', | ||
| 'ar-60-impl-pear', | ||
| 'ar-60-review-pear', | ||
| ]) | ||
| expect(fleet.releases.map((release) => release.name).sort()).toEqual([ | ||
| 'ar-59-impl-pear', | ||
| 'ar-59-review-pear', | ||
| ]) | ||
| expect(factory.status().counters.dispatchLiveStateRaces).toBe(1) | ||
| expect(factory.status().counters.errors ?? 0).toBe(0) | ||
| }) |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Add a no-worktree live-state-race case.
Because this fixture always supplies RecordingWorktreeManager, it misses the path where spawned agents are abandoned without being released. Run the same race without worktrees and assert both agents are released.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/orchestrator/factory.test.ts` around lines 1939 - 1991, The
live-state-race test currently covers only the worktree-managed path. Add a
corresponding no-worktree case around ConcurrentStateChangeMount and the factory
run, omit the worktrees dependency, and assert that both raced issue agents are
released while preserving the skipped race result and zero-error expectations.
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/orchestrator/factory.ts (1)
10628-10629: 🔒 Security & Privacy | 🔴 Critical | ⚡ Quick winRestrict encoded ref writes to the
factory/namespace.The regex also accepts paths such as
refs%2Fheads%2Fmain.json. Combined with the existing-ref update fallback, guarded writes can target arbitrary repository branches. Apply the same restriction to the matching CLI predicate.Proposed fix
const isFactoryGithubWritebackPath = (path: string): boolean => - /^\/github\/repos\/[^/]+\/[^/]+\/(?:pull-requests\/factory-[^/]+\.json|refs\/(?:factory\.json|refs%2Fheads%2F[^/]+\.json)|pulls\/[1-9]\d*\/close\.json)$/iu.test(path) + /^\/github\/repos\/[^/]+\/[^/]+\/(?:pull-requests\/factory-[^/]+\.json|refs\/(?:factory\.json|refs%2Fheads%2Ffactory%2F[^/]+\.json)|pulls\/[1-9]\d*\/close\.json)$/iu.test(path)🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/orchestrator/factory.ts` around lines 10628 - 10629, Update isFactoryGithubWritebackPath and its matching CLI predicate so encoded branch-reference paths are accepted only under the factory/ namespace, rejecting arbitrary refs such as main while preserving pull-request and close-path matches.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@src/orchestrator/factory.ts`:
- Around line 1349-1356: The custom resolver path in `#openPrForIssue` must
enforce the open-only contract instead of trusting a result without state.
Update src/orchestrator/factory.ts:1349-1356 to revalidate the custom-resolved
PR through an authoritative state-aware check, apply the same validation in the
orphan recovery flow at src/orchestrator/factory.ts:1714-1722, and add a
regression test covering a closed or merged custom-resolver result at
src/orchestrator/factory.test.ts:2054-2059.
- Around line 4161-4167: The existing-PR reconciliation condition in snapshot
validation must require snapshot.draft === false, rejecting both draft and
unknown states; update src/orchestrator/factory.ts lines 4161-4167 accordingly.
In src/orchestrator/factory.test.ts lines 4171-4176, explicitly set draft: false
in the valid fixture and add coverage confirming unknown and draft states are
rejected.
---
Outside diff comments:
In `@src/orchestrator/factory.ts`:
- Around line 10628-10629: Update isFactoryGithubWritebackPath and its matching
CLI predicate so encoded branch-reference paths are accepted only under the
factory/ namespace, rejecting arbitrary refs such as main while preserving
pull-request and close-path matches.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: e9c67fca-e54b-4096-89a8-b580be95e46a
📒 Files selected for processing (6)
src/issue-key-match.test.tssrc/issue-key-match.tssrc/mount/relayfile-github-connection-write.test.tssrc/mount/relayfile-github-connection-write.tssrc/orchestrator/factory.test.tssrc/orchestrator/factory.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- src/mount/relayfile-github-connection-write.test.ts
Summary
Root cause
Factory used the Relayfile path for updating an existing GitHub ref when publishing a brand-new local branch. GitHub returned 422 Reference does not exist, so completed agent work could not become a PR. Separately, every broker delivery failure was labeled critical even when Factory had not recorded it as critical, and terminal no-PR dispatches left their worktrees behind.
Validation