Skip to content

AI Fix for Issue #40: Feat: Monitor PR comments for follow-up tasks - #42

Merged
integry merged 1 commit into
mainfrom
ai-fix/40-feat-monitor-pr-comments--20250722-0134-opus-vjb
Jul 22, 2025
Merged

integry merged 1 commit into
mainfrom
ai-fix/40-feat-monitor-pr-comments--20250722-0134-opus-vjb

Conversation

@propr-dev

@propr-dev propr-dev Bot commented Jul 21, 2025

Copy link
Copy Markdown
Contributor

AI Implementation Summary

Closes #40

Model Used: opus
Status: ✅ Implementation Completed
Branch: ai-fix/40-feat-monitor-pr-comments--20250722-0134-opus-vjb
Commits: ✅ Changes committed (7657132)


🤖 AI Processing Completed

Execution Details:

Summary:

Implementation Summary

I've successfully implemented the PR comment monitoring feature for GitFix as requested in issue #40. Here's what was done:

  1. Added new environment variables in .env.example:

    • GITHUB_BOT_USERNAME: Bot username to exclude from PR comment monitoring
    • GITHUB_USER_WHITELIST: Comma-separated list of allowed users for PR comments
    • GITHUB_USER_BLACKLIST: Comma-separated list of excluded users for PR comments
  2. Updated README.md to document the new environment variables in the configuration section.

  3. Implemented pollForPullRequestComments function in src/daemon.js that:

    • Fetches all open pull requests for monitored repositories
    • Retrieves comments for each PR
    • Filters comments containing !gitfix based on:
      • Bot username exclusion
      • User blacklist checking
      • User whitelist validation
    • Extracts the target LLM from patterns like !gitfix:opus
    • Creates processPullRequestComment jobs with all necessary data
  4. Integrated the new function into the main polling loop so it runs after processing issues for each repository.

  5. Updated daemon help text to include documentation for the new environment variables.

The implementation follows the existing code patterns and conventions, uses proper error handling with correlation IDs, and includes retry logic. The system will now monitor PR comments and enqueue jobs for the worker to process in the next phase of development.

Claude Code Results:

  • Turns Used: 101
  • Cost: $unknown
  • Session ID: 527c977e-f131-41e0-86a6-41b42e5422fe

📁 Detailed Logs:
Execution logs generated:

  • Conversation: 101 messages
  • Session: 527c977e-f131-41e0-86a6-41b42e5422fe
  • Raw Output: 124,469 characters

Log files stored at:

  • conversation: /tmp/claude-logs/issue-40-2025-07-21T23-38-48-132Z-conversation.json
  • output: /tmp/claude-logs/issue-40-2025-07-21T23-38-48-132Z-output.txt
💬 Latest Conversation Messages
ASSISTANT: [content unavailable]

ASSISTANT: ## Implementation Summary

I've successfully implemented the PR comment monitoring feature for GitFix as requested in issue #40. Here's what was done:

1. **Added new environment variables** in `.env....


Powered by Claude Code v1.0.0


This PR was created automatically by Claude Code after processing issue #40.

…tasks

Implemented by Claude Code using opus model.

Implementation completed successfully.
@integry
integry merged commit df094f2 into main Jul 22, 2025
@integry
integry deleted the ai-fix/40-feat-monitor-pr-comments--20250722-0134-opus-vjb branch July 22, 2025 08:34
propr-dev Bot pushed a commit that referenced this pull request Apr 23, 2026
Summary

1. API (`packages/api/routes/llmLogsRoutes.ts`)
- Added 7 work-reference columns to the SQL SELECT: `work_type`, `task_id`, `task_number`, `pr_number`, `plan_draft_id`, `plan_issue_id`, `work_repository`
- Extended `LlmLogRow` interface and `formatLlmLogRow` to return camelCase fields: `workType`, `taskId`, `taskNumber`, `prNumber`, `planDraftId`, `planIssueId`, `workRepository`
- Added `work_type` filter parameter with validation (must be `task`, `plan`, or `repository`)

2. Frontend types (`propr-ui/src/api/llmLogsApi.ts`)
- Added all 7 work-reference fields to `LlmLogEntry` interface with proper types
- Added `work_type` to `LlmLogsParams` for filtering

3. CLI types (`packages/cli/src/api/logs.ts`)
- Added all 7 work-reference fields to CLI `LlmLogEntry` interface
- Added `workType` filter to `ListLlmLogsOptions` and query parameter construction

4. Display helpers (`propr-ui/src/pages/llmLogsUtils.ts`)
- `getWorkReferenceDisplay()` — renders human-readable summary (e.g., "integry/propr · Issue #42, PR #99")
- `getWorkTypeLabel()` — returns "Task", "Plan", or "Repo" labels
- Updated `hasDetailedInfo()` to also check `workType`

5. LLM Logs Page (`LlmLogsPage.tsx`)
- Replaced "Context" column header with "Work Ref"
- Work reference cell shows colored type badge + summary text
- Added "All Work / Tasks / Plans / Repository" filter dropdown
- Falls back to legacy context display when no work reference

6. Expanded Row Details (`LlmLogsPageComponents.tsx`)
- Added "Work Reference" section with all fields displayed
- Task IDs link to `/tasks/:taskId`, draft IDs link to `/plans/:planDraftId`
- Color-coded type badges (blue for task, purple for plan, gray for repo)

7. Tests (`test/llmLogsWorkRefDisplay.test.ts`)
- 21 tests covering `getWorkReferenceDisplay`, `getWorkTypeLabel`, `hasDetailedInfo`, and API response shape
- All tests pass, and existing tests remain green
propr-dev Bot added a commit that referenced this pull request Apr 23, 2026
Summary

1. API (`packages/api/routes/llmLogsRoutes.ts`)
- Added 7 work-reference columns to the SQL SELECT: `work_type`, `task_id`, `task_number`, `pr_number`, `plan_draft_id`, `plan_issue_id`, `work_repository`
- Extended `LlmLogRow` interface and `formatLlmLogRow` to return camelCase fields: `workType`, `taskId`, `taskNumber`, `prNumber`, `planDraftId`, `planIssueId`, `workRepository`
- Added `work_type` filter parameter with validation (must be `task`, `plan`, or `repository`)

2. Frontend types (`propr-ui/src/api/llmLogsApi.ts`)
- Added all 7 work-reference fields to `LlmLogEntry` interface with proper types
- Added `work_type` to `LlmLogsParams` for filtering

3. CLI types (`packages/cli/src/api/logs.ts`)
- Added all 7 work-reference fields to CLI `LlmLogEntry` interface
- Added `workType` filter to `ListLlmLogsOptions` and query parameter construction

4. Display helpers (`propr-ui/src/pages/llmLogsUtils.ts`)
- `getWorkReferenceDisplay()` — renders human-readable summary (e.g., "integry/propr · Issue #42, PR #99")
- `getWorkTypeLabel()` — returns "Task", "Plan", or "Repo" labels
- Updated `hasDetailedInfo()` to also check `workType`

5. LLM Logs Page (`LlmLogsPage.tsx`)
- Replaced "Context" column header with "Work Ref"
- Work reference cell shows colored type badge + summary text
- Added "All Work / Tasks / Plans / Repository" filter dropdown
- Falls back to legacy context display when no work reference

6. Expanded Row Details (`LlmLogsPageComponents.tsx`)
- Added "Work Reference" section with all fields displayed
- Task IDs link to `/tasks/:taskId`, draft IDs link to `/plans/:planDraftId`
- Color-coded type badges (blue for task, purple for plan, gray for repo)

7. Tests (`test/llmLogsWorkRefDisplay.test.ts`)
- 21 tests covering `getWorkReferenceDisplay`, `getWorkTypeLabel`, `hasDetailedInfo`, and API response shape
- All tests pass, and existing tests remain green
propr-dev Bot pushed a commit that referenced this pull request Sep 17, 2026
…ications are the only group left, and cards are titled by their actual PR or issue title. The type checks, lint (zero warnings), 124 UI notification tests, the server notification tests and 7 browser tests all pass.

The Inbox is now one plain list, newest first. System notifications are the only group left, and cards are titled by their actual PR or issue title. The type checks, lint (zero warnings), 124 UI notification tests, the server notification tests and 7 browser tests all pass.

**Layout**
- The "Needs attention", "Ready for review" and "Completed" groups are gone. Everything except system updates is in one list sorted by time, newest on top.
- System and indexing updates stay in one collapsed "System" section above the list. Its header is plain grey text with a count and a chevron.
- Cards no longer have colored backgrounds, including the teal fill on unread ones. Every card is white with a grey border. Unread is shown only by the small dot and a bold title.

**Titles and IDs**
- The title is now the PR or issue title. For example, "Review completed for PR #81" becomes "Guard Inbox recaps against empty metadata". The server gets it from the title stored with the task, stripping prefixes like "Follow-up PR #42:" and "New Issue:".
- If a task has no stored title, the old wording is used.
- Plan notifications are titled by the plan name, with "Ready for review with 4 planned tasks." underneath.
- The PR or issue number is still shown, as a small grey `PR81` or `#12` chip. The chips and dot separators are copied from the metadata row on the task details page (the one in your screenshot), so no new element styles were added.
- The event type (e.g. "Review completed", "Fix completed") is plain grey text in that same row.

Notifications already stored keep their old titles; only new ones get the PR/issue title.

I updated the existing unit and browser tests for the flat list. I also added one server test checking that merge and failed-issue notifications use the real title.

PR: #2441
Comment by: @integry (ID: 5711992010)
Model: claude-opus-5
propr-dev Bot pushed a commit that referenced this pull request Sep 23, 2026
…es where the diagnosis didn't match what was on the branch.

All five points are done. Here's what changed, and two places where the diagnosis didn't match what was on the branch.

### 1. The `/10` is gone — the pill is back
`ScoreBadge` gained a `bracketed` variant and the outcome feed uses it: `[ ● 9 ]`, `[ ◆ 7 ]`, `[ ◆ 8 ]` inside the existing `w-12 min-w-12 max-w-12`. The out-of-ten scale now reaches screen readers only. The right rail is a straight edge.

One conflict you should know about: commit `7e515aee6` on `main` ("Removed the square brackets from the rating", PR #2431) deleted exactly these brackets from the shared `ScoreBadge` at your request. So I made brackets **opt-in** — the dashboard's fixed-width rail uses them, the task list keeps the bare form you asked for there. If you want them everywhere, it's a one-line default flip.

### 2. Split-pane console
The quadrants had no `rounded-lg border` at HEAD — nothing was wrapped in a box. What *was* real:
- The pane divider stopped wherever content ended, leaving ~200px of dead white below it. The grid is now `flex-1` with a last row of `minmax(min-content,1fr)`, so `border-r` runs unbroken to the bottom of the viewport.
- `HISTORICAL STATS` (with a segmented control) was 40px tall while `HAPPENING NOW` (without one) was 28px, so the two columns' rules landed on different pixels — that's what made them read as separate boxes. `SectionHeading` now has `min-h-10`, putting every pane header on one horizon.

### 3. The sidebar was never amputated
`git diff main...HEAD -- Layout.tsx` on this branch is one added nav item. The profile block and the USAGE widget are intact; they render behind `user &&` and `isDemoMode || canManageAgents`, and the preview fixture was signed out with no Agent Tank data, so both short-circuited. The fixture now signs in a plain member and serves usage — previews show nav → USAGE (Claude 34%, Codex 12%) → account block. The member role is deliberate: an admin would add three banners above the dashboard.

### 4. Fixed-width actions
`Open` / `Review`, at `w-20 justify-center`. All three left edges are on one line (asserted in the e2e spec by comparing bounding rects). The entity moved to `aria-label` — a visually-hidden span gets concatenated without a separator and announced as "Openissue #42".

### 5. Summary strip is a sub-toolbar
`min-h-10 border-b border-slate-200 bg-slate-50/50`, moved out of the grid and anchored directly above the panes. `min-h-` rather than `h-` so it wraps at 320px instead of overflowing. Its first label sits on the same `px-3` rail as `HAPPENING NOW` below it.

**Verification:** 1256 vitest tests / 160 files pass, typecheck and lint clean, docs site builds. Six new design-rule tests cover the toolbar, the horizon, the continuous divider, the pill, and the action widths. All 4 dashboard e2e specs plus `startup-critical-path` and `task-list-desktop` (12 tests) pass. Previews captured at 1440px populated, 1440px empty-attention, and 320px.

PR: #2486
Comment by: @integry (ID: 5796747130)
Model: claude-opus-5
propr-dev Bot pushed a commit that referenced this pull request Oct 2, 2026
I fixed both states in the New Task dialog.

**Submitting state**
- **Body box removed:** the "Submitting…" box in the form body is gone. The primary button now shows a spinner with "Submitting…", is disabled, ignores clicks, and stays at 80% opacity.
- **Inputs locked:** the Repository, Prompt, attachments and Advanced Options fields were already disabled during a submission but looked interactive. They're now dimmed to 60% whenever they're disabled.

**Partial failure (issue created, agent didn't start)**
- **One amber alert:** the red box and the teal box are now a single amber warning. It reads "⚠ Issue #42 created, but agent failed to queue" with the description from your mockup and a "View issue #42 ↗" link. I kept the server's error reason as one small line inside the box so the cause isn't lost. That adds a line your mockup didn't have, and it's easy to drop.
- **Two-button footer:** "Close" on the left and "Retry agent" on the right. "Start over" and both explanation lines are gone. "Retry agent" calls the existing retry endpoint, and I checked the server code: it re-applies the labels and re-queues the existing issue without creating a new one.
- **Close also clears the saved retry:** Close (and the dialog's ✕ and Escape) deletes the locally saved copy of the request, so the next New Task dialog opens empty. Without this, Close would bring the same failed state back on reopen, and with no Start over there would be no way out. Issue #42 stays on GitHub.

**Other states**
- No message is wrapped in teal any more unless work is actually progressing. Each state shows a single box:
  - **Teal:** in progress, i.e. "Queued", "Issue created — starting task" and "Confirming submission with GitHub".
  - **Red:** outright failures ("Could not create issue", "Could not start task", "Could not confirm submission").
- "Start over" still appears when the outcome is unknown or the issue was rejected, since that flow still needs it.

**Tests**
- All 12 unit tests in `NewTaskPage.test.tsx` pass. I updated them for the new wording and added a test for the in-flight state and the single warning, plus one for Close clearing the saved request.
- All 9 browser tests in `e2e/new-task.pw.ts` pass. I updated them to use "Retry agent", "View issue #42" and Close instead of "Retry submission" and "Start over".
- Lint and the type check are clean for these files.

The task's worktree path was mounted read-only, so I made the edits in `/home/node/workspace`, which is the same branch at the same commit.

I captured desktop and mobile previews of the submitting state and the partial-failure state.

PR: #2681
Comment by: @integry (ID: 5951721858)
Model: claude-opus-5-5
propr-dev Bot pushed a commit that referenced this pull request Oct 5, 2026
…er now collapses into a single 44px line. The Files Changed error alert can no longer appear without its header.

Both fixes are in. When you scroll down on mobile, the header now collapses into a single 44px line. The Files Changed error alert can no longer appear without its header.

All 1950 UI unit tests pass and lint is clean. All 32 cases in the task-details responsive, cleanup and visual-preview Playwright specs, plus the task-list spec, pass. Typecheck reports no errors in the changed files.

**#2: Sticky header collision**
- **Why it collided:** the old sticky summary had no fixed height. It held the repo, the full action row and the chip row, so it wrapped. When it shrank, the content scrolling behind it, including the Completed badge, showed through.
- **Now:** the full summary scrolls away with the title. Once it has passed under the top of the screen, a separate bar fades in. It is always one line and 44px tall, and appearing doesn't move the page under it.
- **Left side:** `[⎇ PR #42] acme/web`, with the repo name truncated. The rest of the chips and the Completed badge don't appear in it.
- **Right side:** the `⋯` menu, which holds Follow Up, Prompt, Logs and Delete.
- **One change from your spec:** while a task is running, the red **Stop** button stays visible next to `⋯` instead of going into the menu. You said earlier that Stop must never leave the header, so I kept that rule here too. Completed tasks show only `⋯`.

**#3: Error alert without its header**
- **Why it happened:** the alert wasn't actually detached from its section. The old tall sticky bar covered the `FILES CHANGED` heading while the alert below it was still visible.
- **Now:** the heading and the alert are in one section. The `FILES CHANGED` heading sticks just under the compact bar for as long as any part of the section is on screen. So you can't see the alert without its heading, and the two scroll away together.
- **Also on desktop:** the heading also sticks below the `TIMELINE` header in the desktop timeline pane, since both are 44px.

**Tests added**
- **Unit:** what goes in the compact menu, Stop staying out of it, and the one-line PR + repo layout.
- **Playwright:** at 390px with your fixture (the demo banner, and Files Changed returning HTTP 503), it checks that:
  - the bar is one line, 44px tall, at the top of the scroll area.
  - the Completed badge is fully above the bar.
  - the heading sits between the bar and the alert, and stays pinned there as the alert scrolls under it.
- **Short page in the test:** that fixture is too short to scroll far enough, so the test adds blank space below the page first.

**Fixed along the way:** my first version clipped the `⋯` dropdown inside the 44px bar. Opening it also scrolled the bar's contents out of view. Now only the left side is clipped.

I captured previews at 390px of the collapsed bar and of its open menu. Most of the change is in `propr-ui/src/components/TaskDetails/index.tsx`, with the compact modes in `ActionBar.tsx` and `ContextStrip.tsx`.

PR: #2720
Comment by: @integry (ID: 5994216805)
Model: claude-opus-5-5
propr-dev Bot pushed a commit that referenced this pull request Oct 5, 2026
…it tests pass and lint is clean. All 32 cases in the task-details cleanup, responsive and visual-preview Playwright specs and the task-list spec pass. Typecheck reports no errors in the changed files.

I made all three fixes to the mobile header. All 1953 UI unit tests pass and lint is clean. All 32 cases in the task-details cleanup, responsive and visual-preview Playwright specs and the task-list spec pass. Typecheck reports no errors in the changed files.

**1. `⋯` now opens a bottom action sheet**
- **The sheet:** tapping `⋯` in the collapsed bar dims the page and slides a sheet up from the bottom of the screen. It covers the bottom navigation, so nothing underneath is hidden behind a floating box.
- **The rows:** Follow Up (with Prompt and Logs when the task has them), Delete in red, and Cancel at the bottom. Each row is full width and at least 48px tall.
- **Closing it:** Cancel, tapping the dimmed area, or Escape closes it without doing anything, and focus goes back to `⋯`.
- **Still the same:** while a task is running, Delete is greyed out in the sheet, and the red Stop button stays visible in the bar rather than going into the sheet.
- **The full header too:** the `⋯` in the full mobile header, which holds only Delete, now opens the same sheet. That way the same button doesn't open two different kinds of menu on a phone. Desktop keeps its popover.

**2. The task title replaces the repo name**
- The bar now reads `⎇ #42: Render visual previews full width`, truncated with an ellipsis. `#42` still links to the pull request.
- The title is the same cleaned-up one shown in the page heading.
- If a task has no title yet, the bar falls back to the repo name.

**3. The `⋯` touch target**
- The button is now a 44×44px circle with a pressed background (`h-11 w-11 -mr-2 rounded-full active:bg-slate-100 text-slate-500`).
- I used 44px instead of the 40px your `w-10 h-10` would give, because 44px is the minimum you quoted.
- **Side effect:** the action row in the full mobile header is about 16px taller because of the bigger button.

**Tests updated**
- **Unit:** the sheet's rows, the three ways to close it, the title line and the repo fallback.
- **Playwright:** at 390px the bar checks the title text and a button of at least 44×44px. With the sheet open, it checks the sheet is full width at the bottom edge with rows at least 48px tall.
- **Cleanup spec:** it now looks for Delete in the page-level sheet, because the sheet isn't drawn inside the task pane.

The sheet is new, in `TaskActionSheet.tsx`. The title line is in `ContextStrip.tsx`, and the slide-up animation is in `tailwind.config.js`. I captured previews at 390px of the collapsed bar and of the open sheet.

PR: #2720
Comment by: @integry (ID: 5994459947)
Model: claude-opus-5-5
propr-dev Bot pushed a commit that referenced this pull request Oct 8, 2026
… to-dos. A duplicate POST or a retry used to complete a to-do the user had reopened, or point it back from a newer issue to the older one. Now it does neither.

I fixed F1: replaying an older submission no longer changes to-dos. A duplicate POST or a retry used to complete a to-do the user had reopened, or point it back from a newer issue to the older one. Now it does neither.

**Fix**
- **New column:** migration `20261013010000_add_task_submission_todos_linked.js` adds a `todos_linked` flag to `task_submissions`, default false. Rolling back drops it. `TaskSubmission` now has the field.
- **Route helper:** `linkSubmissionTodos` in `packages/api/routes/taskSubmissionRoutes.ts` now does nothing if the submission's to-dos have already been linked. Otherwise, in one transaction, it sets `todos_linked` (only if it is still false) and completes the to-dos.
  - If the to-do update fails, the whole transaction rolls back, the flag stays false, and a later retry can still apply it. Failures are still only logged, and the response is unchanged.
  - If two replays run at the same moment, the one that loses doesn't touch the to-dos.
- **Other callers:** `submit`, `retry` and MCP `create_task` all go through the same `resume` wrapper, so the one guard covers all of them. `completeTodosForIssue` itself is unchanged; a genuinely new submission still relinks a reopened to-do to its new issue, as intended.

**Tests** (in `packages/api/test/taskSubmissionRoutes.test.ts`)
- **New regression:** submission A links issue #42. The user reopens the to-do, then A is replayed by both a duplicate POST and its retry endpoint; the to-do stays open. Then submission B links it to #43, A is replayed again by both paths, and the to-do keeps #43.
- **Updated existing test:** duplicates and retries no longer call the completion step again (2 calls instead of 4). A submission whose to-do write failed links the to-do on its later retry.
- **Checked against the old code:** both of these tests fail on the old code and pass with the fix.
- **Results:** the route, `repoTodosIssueLink`, `taskSubmissionService`, `mcpTaskSubmissions` and `mcpIntegration` suites pass, and type checks pass for the root and `api`. I didn't run the new migration against a real database, only in-memory SQLite.

**One side effect:** the issue link records `linked_task_id` from the submission at the moment of linking. The task id is usually set later by the worker, and retries used to fill it in on the to-do afterwards. Since replays now skip that step, `linked_task_id` will usually stay null. The completion and the issue link are unaffected. I left this alone because it's outside F1.

There's no visible UI change, so I didn't capture a preview.

The claude.ai Gmail, Google Calendar, Google Drive and ProPR connectors need to be authorized in your claude.ai connector settings before they can be used. This task didn't need them.

PR: #2887
Comment by: @propr-ultrafix (ID: 0)
Model: Claude Opus 5.5
propr-dev Bot pushed a commit that referenced this pull request Oct 8, 2026
…fixed by the previous commit on this branch, so it needed no new changes. The affected suites pass (27 tests), and the two new regression tests fail when the guard is taken out.

I added a per-to-do freshness guard for F2. F1 was already fixed by the previous commit on this branch, so it needed no new changes. The affected suites pass (27 tests), and the two new regression tests fail when the guard is taken out.

**F1 (replaying a submission undoes later to-do changes).** The required fix is already on the branch:
- **The record:** each submission row now has a `todos_linked` flag. It is set in the same transaction as the to-do update.
- **Replays:** duplicate POSTs and retries skip the to-do update once the flag is set.
- **Failures:** if the update fails, the flag stays false, so a later retry can still apply it.
- **Callers:** form submit, the retry endpoint and the MCP `create_task` tool all go through this one guarded path.
- **Test:** the existing test reopens the to-do and relaunches it before replaying the older submission. Both cases are covered.

**F2 (an older submission's retry replaces a newer issue link).** In `completeTodosForIssue` (`packages/core/src/services/repoTodosService.ts`), a submission now leaves a to-do alone if it is already linked to a higher-numbered issue in the same repository.
- **Why issue numbers:** GitHub issue numbers only increase within a repository, so a higher number means a newer launch. This needs no new column.
- **Still allowed:** to-dos with no link yet, a re-apply of the same issue, and a link to a higher-numbered issue. If the stored link points to a different repository, the numbers can't be compared, so the update is allowed.
- **When a to-do is skipped:** the older submission's flag is still set. It doesn't retry forever and simply counts as replaced by the newer launch.

**Regression tests:**
- `packages/api/test/taskSubmissionTodos.test.ts`: submission A opens issue #42 but its to-do write fails. Submission B opens #43 and links the to-do. Retrying A leaves the to-do on #43 and sets A's flag, and a further retry doesn't attempt the update again.
- `packages/core/test/repoTodosIssueLink.test.ts`: a link from an older issue doesn't replace the newer issue number or task ID, and doesn't complete a reopened to-do. A link from a newer issue still does.

**Checks run:**
- **Tests:** `repoTodosIssueLink`, `taskSubmissionTodos`, `taskSubmissionRoutes` and `mcpTaskSubmissions` all pass.
- **Types:** type checks pass for `api` and `core`.
- **Lint:** ESLint passes on the changed service and API test. `packages/core/test` is excluded by the lint config, so the core test file wasn't linted.

**One trade-off:** the guard orders launches by when their issue was created, not when they were submitted. Suppose submission A failed before creating an issue, then B created #42, and A's retry later created #43. The to-do would end up on #43, which is the most recently opened issue.

There's no visible UI change, so I didn't capture a preview. The claude.ai Gmail, Google Calendar, Google Drive and ProPR connectors need to be authorized in your claude.ai connector settings before they can be used; this task didn't need them.

PR: #2887
Comment by: @propr-ultrafix (ID: 0)
Model: Claude Opus 5.5
propr-dev Bot pushed a commit that referenced this pull request Oct 15, 2026
…w starts a new run on the same issue, and never queues a PR-comment job or makes a `GET /pulls` call. The 80 follow-up/review route tests and the MCP and OpenAPI tests pass, and lint and typecheck are clean. I haven't run it against real GitHub, so the live acceptance step (follow-up → new run → eventually a PR) is still untested.

What happens now when you follow up on a task without a PR (new file `packages/api/routes/taskIssueFollowup.ts`):
1. Checks first, nothing posted if they fail:
   - PR commands like `/review`, `/fix`, `/use` or `/switch` are rejected with 400, since there's no PR.
   - The task's latest state must be `failed`.
   - No run for that issue can already be queued or running.
   - The issue must be open and not marked done or cancelled.

   Each of these returns a 409 with a plain explanation, which the modal shows as the error.
2. Posts your request on the issue as plain text, with no hidden marker. The issue run reads all issue comments, so it becomes part of the prompt.
3. Removes and re-adds the trigger label (e.g. `AI`, preferring the label the failed run used). This matters for issues created through task submission: the worker only re-runs those after a new label event, so just queuing a job would be skipped.
4. Queues the normal issue job with your user ID, through the same function plan and submission implementations use. The model comes from the issue's existing `llm-*` labels, so the same model runs again.

Deduplication and reported results:
- The route briefly claims the same "recently triggered" key the label webhook uses. When the bot re-adds the label, that webhook skips instead of queuing a second run without your user ID. A repeated click gets a 409.
- The response only reports `queued` once the job was actually added.
- If the label can't be re-added, it reports `failed` and frees that key.
- If the queue call fails, it reports `unknown` with the job ID, matching the existing PR route.

PR routing:
- Second broken case: a follow-up with no target on an implementation task that *did* create a PR was also going to the issue number as if it were a PR. It now goes to the task's real PR (`pr_number`), branch lookup included.
- Unchanged: PR-comment tasks, `/review`, and anything explicitly targeted at the PR keep their old routing.

Other changes:
- New tests (`packages/api/test/taskFollowupIssueRoutes.test.ts`, plus fixture updates) cover:
  - issue-only success, with the actor, label order and absence of a PR read checked.
  - repeated requests and an already-queued run.
  - six slash commands.
  - non-failed, closed and done issues.
  - label-write and queue failures.
  - the issue comment being ignored by the PR webhook.
  - issue-with-PR and PR-comment tasks.
- Existing MCP test changed: `packages/api/test/mcpWorkflows.test.ts` had encoded the bug — a completed task with no PR expecting a PR job keyed by the issue number. It now records the created PR (#42), which is what a completed implementation actually stores.
- API docs: the OpenAPI docs now list the 409 responses and the new `intent`/`issueNumber` fields. I regenerated `docs/static/openapi/propr-api.yaml` and the client's generated API types.

Limitations:
- Only failed runs can be retried. Completed-without-PR or cancelled issue tasks get a 409 rather than a retry; I kept the scope to what the issue described.
- MCP progress for an issue retry can show "unknown" after a while. For `send_task_followup`, the returned job ID belongs to the short-lived job that starts the run. Once that job finishes, MCP progress tracking can only report "unknown" (accurate, but vague) instead of following the new run.

No UI changes, so no previews.
integry pushed a commit that referenced this pull request Oct 15, 2026
* I've fixed the bug: Follow Up on a failed task that never got a PR now starts a new run on the same issue, and never queues a PR-comment job or makes a `GET /pulls` call. The 80 follow-up/review route tests and the MCP and OpenAPI tests pass, and lint and typecheck are clean. I haven't run it against real GitHub, so the live acceptance step (follow-up → new run → eventually a PR) is still untested.

What happens now when you follow up on a task without a PR (new file `packages/api/routes/taskIssueFollowup.ts`):
1. Checks first, nothing posted if they fail:
   - PR commands like `/review`, `/fix`, `/use` or `/switch` are rejected with 400, since there's no PR.
   - The task's latest state must be `failed`.
   - No run for that issue can already be queued or running.
   - The issue must be open and not marked done or cancelled.

   Each of these returns a 409 with a plain explanation, which the modal shows as the error.
2. Posts your request on the issue as plain text, with no hidden marker. The issue run reads all issue comments, so it becomes part of the prompt.
3. Removes and re-adds the trigger label (e.g. `AI`, preferring the label the failed run used). This matters for issues created through task submission: the worker only re-runs those after a new label event, so just queuing a job would be skipped.
4. Queues the normal issue job with your user ID, through the same function plan and submission implementations use. The model comes from the issue's existing `llm-*` labels, so the same model runs again.

Deduplication and reported results:
- The route briefly claims the same "recently triggered" key the label webhook uses. When the bot re-adds the label, that webhook skips instead of queuing a second run without your user ID. A repeated click gets a 409.
- The response only reports `queued` once the job was actually added.
- If the label can't be re-added, it reports `failed` and frees that key.
- If the queue call fails, it reports `unknown` with the job ID, matching the existing PR route.

PR routing:
- Second broken case: a follow-up with no target on an implementation task that *did* create a PR was also going to the issue number as if it were a PR. It now goes to the task's real PR (`pr_number`), branch lookup included.
- Unchanged: PR-comment tasks, `/review`, and anything explicitly targeted at the PR keep their old routing.

Other changes:
- New tests (`packages/api/test/taskFollowupIssueRoutes.test.ts`, plus fixture updates) cover:
  - issue-only success, with the actor, label order and absence of a PR read checked.
  - repeated requests and an already-queued run.
  - six slash commands.
  - non-failed, closed and done issues.
  - label-write and queue failures.
  - the issue comment being ignored by the PR webhook.
  - issue-with-PR and PR-comment tasks.
- Existing MCP test changed: `packages/api/test/mcpWorkflows.test.ts` had encoded the bug — a completed task with no PR expecting a PR job keyed by the issue number. It now records the created PR (#42), which is what a completed implementation actually stores.
- API docs: the OpenAPI docs now list the 409 responses and the new `intent`/`issueNumber` fields. I regenerated `docs/static/openapi/propr-api.yaml` and the client's generated API types.

Limitations:
- Only failed runs can be retried. Completed-without-PR or cancelled issue tasks get a 409 rather than a retry; I kept the scope to what the issue described.
- MCP progress for an issue retry can show "unknown" after a while. For `send_task_followup`, the returned job ID belongs to the short-lived job that starts the run. Once that job finishes, MCP progress tracking can only report "unknown" (accurate, but vague) instead of following the new run.

No UI changes, so no previews.

* feat(ai): I fixed the lint failure. It came from 21 `no-explicit-any` errors in three files this PR never touched: `packages/api/authSession.ts`, `test/browserSessionShutdown.test.ts` and `test/taskWatcher.test.ts`. They were added on main in f3de8e277 (#3112), which this branch is based on, so main's API lint fails the same way. None of the follow-up changes on this branch caused it.

I fixed the lint failure. It came from 21 `no-explicit-any` errors in three files this PR never touched: `packages/api/authSession.ts`, `test/browserSessionShutdown.test.ts` and `test/taskWatcher.test.ts`. They were added on main in f3de8e277 (#3112), which this branch is based on, so main's API lint fails the same way. None of the follow-up changes on this branch caused it.

**What changed:** each `any` is replaced with a proper type. None of the code's behaviour changes.
- **`authSession.ts`:** the store-method wrapper arguments and the callback results are now typed as `unknown[]`.
- **`browserSessionShutdown.test.ts`:** the fake request/response objects are cast `as never`, the session data uses the cast the file already uses elsewhere, and the server address is typed as `AddressInfo` (imported from `node:net`).
- **`taskWatcher.test.ts`:** the private-field access on the manager uses a small typed view instead of `as any`.

**Verification:**
- `npm run lint` in `packages/api` is clean.
- `tsc --noEmit` is clean, but the API tsconfig doesn't include the test files, so the edited tests are not typechecked by it.
- The two edited test files pass (43 of 43). They need a GitHub login setting to start, so I ran them with `PROPR_DEMO_MODE=true NODE_ENV=test`.

This changes nothing visible, so there are no previews.

PR: #3125
Comment by: @propr-dev[bot] (ID: 6188074477)
Comment by: @github-actions[bot] (ID: 6188075436)
Model: Claude Opus 5.5

* feat(ai): I fixed F1 and added S1's coverage. On a submission-backed issue, a retry posted in the same second the run failed now starts a new run, instead of reporting "queued" and running nothing.

I fixed F1 and added S1's coverage. On a submission-backed issue, a retry posted in the same second the run failed now starts a new run, instead of reporting "queued" and running nothing.

**F1: retries in the failure's second were skipped**
- **Fix:** before re-adding the processing label, the route now waits until the second after the failure. GitHub records label events only to the second, and the dispatcher treats an event in the failure's own second as the original trigger. In practice the wait is at most a second. The change is in `packages/api/routes/taskIssueFollowup.ts`.
- **Shared rule:** the "earliest second a retry can count" rule now lives in one place, a new `submissionRetryAdmissibleAt` in `packages/core/src/services/taskSubmissionRetry.ts`. `resolveTaskSubmissionRetry` uses the same "latest run finished, and when" lookup, so the route and the dispatcher can't drift apart. The dispatcher's decision itself is unchanged.
- **Same defect, second path:** if the issue's latest run isn't recorded as finished (still running, or no valid timestamp), the dispatcher would also skip the new trigger, yet the route would have reported "queued". The route now refuses these with a 409, before posting the comment.
- **Regression test:** it runs the route and then the real dispatcher on the job the route queued. The run fails at 10:00:00.500 and the retry arrives at 10:00:00.700, the case in the finding. The label event lands at 10:00:01 and the dispatcher dispatches. With the wait disabled, the same test gets `skipped`, so it catches the defect. A second new test covers the refusal.

**S1: the relabel test now delivers the real label webhook**
That test now passes the label event through the production webhook handler (`processDetectedIssue`) and checks it is dropped as a duplicate. It then clears the shared duplicate-request block and delivers the event again; this time it queues a run. That shows the block, not some other check, is what stops the second run.

**Verification:** 110 tests pass across the follow-up route suites, the core submission tests, `mcpWorkflows` and the issue-detection integration test. Lint and typecheck are clean for the API and core packages. The fix has not been run against real GitHub.

**Separate discovery, not addressed:** the comparison is between the time our database records for the failure and GitHub's clock. If those two clocks disagree, the wait can still be wrong. The wait is capped at 2 seconds so a database clock running ahead can't stall the request. Closing this fully would mean re-reading GitHub's timeline and resolving the retry before reporting "queued". GitHub may not show a new event right away, so that risks false failures; I left it out.

There's no visible UI change, so I made no previews.

PR: #3125
Comment by: @integry (ID: 6189190840)
Model: Claude Opus 5.5

* feat(ai): I fixed F2. If the bounded wait ends before a new run could actually start, a follow-up on a failed issue task now gets a refusal instead of a success message for a run that never begins.

I fixed F2. If the bounded wait ends before a new run could actually start, a follow-up on a failed issue task now gets a refusal instead of a success message for a run that never begins.

**What changed** (`packages/api/routes/taskIssueFollowup.ts`):
- `waitUntil` still caps its sleep at 2 seconds. Afterwards it now reports whether the API clock has reached the admission time.
- The wait and that check now happen before the dedup claim, the comment post and the relabel. If the time still hasn't arrived, the route returns 409 ("…would not start a run yet. Try again in a few seconds."). Nothing has been posted, relabelled, queued or claimed at that point, so a refusal leaves no partial follow-up behind.
- On the normal path the order is the same as before (wait, then post the comment, then relabel), so the relabel still lands after the failure's second.

**Regression test** (`packages/api/test/taskFollowupIssueRoutes.test.ts`): this is the scenario from the review. The failure timestamp is set five seconds ahead of the injected clock. The test checks that the route returns 409 after a single 2000 ms sleep, posts no comment, writes no labels, queues no job and holds no dedup claim. It fails against the previous route code and passes with the fix.

**Same-defect check:** `submissionRetryAdmissibleAt` and `waitUntil` have no other callers, so this route was the only place that needed the fix. Database/API clock skew is a real race, so the route can only wait a bounded time and then refuse; it can't guarantee the retry gets in.

**Verification:** the issue follow-up, PR follow-up and MCP workflow tests all pass (3 files). The API package typechecks, and ESLint passes on both changed files.

I found nothing outside F2 to report separately. This change has nothing visual, so there are no previews.

PR: #3125
Comment by: @integry (ID: 6189489687)
Model: Claude Opus 5.5

* feat(ai): I fixed F3 and S3. The new focused tests, the related suites (296 tests) and typecheck all pass, and lint shows no new warnings in the files I changed. I haven't run any of this against real GitHub.

I fixed F3 and S3. The new focused tests, the related suites (296 tests) and typecheck all pass, and lint shows no new warnings in the files I changed. I haven't run any of this against real GitHub.

**F3: the retry now runs as the user who asked for it.**
- The follow-up route now also records who asked for the retry in a new job field, `retryRequesterId` (`packages/api/routes/taskIssueFollowup.ts`, `packages/api/routes/planIssueHelpers.ts`, `packages/core/src/queue/taskQueue.types.ts`).
- For an issue created from a submission, the dispatcher uses that person only when the dispatch is an accepted retry. It's a new helper in `src/jobs/issueJobDispatcher.ts`, which also keeps that function under the lint complexity limit.
- Ordinary webhook deliveries never set the field, so they still run as the original submitter. The existing test where a webhook retry stays with `alice` still passes.
- The dispatcher test now has the submitter and the requester as different users, and checks that the run's `userId` is the requester's.

**S3: the retry instructions now reach the agent.** The check S3 asked for found a real gap. The route posts the comment with the app's GitHub credentials, so it's authored by `propr-dev[bot]`. `fetchIssueComments` drops comments from bot accounts, so the retry request never reached the prompt.
- **Fix:** the route now passes the posted comment's ID in the job (`retryCommentId`). `fetchIssueComments` (`src/jobs/issueJob/github.ts`) always keeps that one comment; every other bot comment is still filtered out.
- **Test:** it takes the actual job the dispatcher produces, runs it through `fetchIssueComments` and `generateClaudePrompt`, and checks that the request text is in the prompt and an unrelated bot comment isn't.

Both new checks fail if their fix is reverted. This is a code-level check with stubbed GitHub responses, not a live run.

**Found separately, not changed:** only the most recent retry comment is exempt from the bot filter. If someone retries the same issue twice, the second run sees the new instructions but not the earlier app-posted ones.

There's no visual change, so I didn't make previews.

PR: #3125
Comment by: @integry (ID: 6189664289)
Model: Claude Opus 5.5

* feat(ai): I fixed F4. If the route's own enqueue fails and the relabel webhook later restarts the retry, the run now still belongs to the person who asked for it and still includes their posted instructions. The 162 tests in the follow-up, dispatcher and submission suites pass, and typecheck and lint are clean for the files I changed. I haven't run any of this against real GitHub.

I fixed F4. If the route's own enqueue fails and the relabel webhook later restarts the retry, the run now still belongs to the person who asked for it and still includes their posted instructions. The 162 tests in the follow-up, dispatcher and submission suites pass, and typecheck and lint are clean for the files I changed. I haven't run any of this against real GitHub.

**What changed**
- **New `packages/core/src/services/issueRetryRequest.ts`:** stores the requester and comment ID in Redis, one entry per issue, for 24 hours. It only deletes the entry if it still holds the same request, so a newer request is never wiped out.
- **Route (`taskIssueFollowup.ts`):** saves that entry after posting the comment and before re-applying the label. If saving fails, the label is never re-applied and the user gets the existing "could not be started" reply. If the label can't be re-applied, the entry is removed.
- **Dispatcher (`issueJobDispatcher.ts`):** when a job arrives without the retry fields (as a webhook or polling job does), it fills them in from the stored entry. That puts the requester as the run owner and lets the comment through the author filter. The entry is removed only after the child jobs are queued. If dispatch fails, it stays for the next attempt.

**Same bug on issues without a submission:** this path had the same problem, so I fixed it too. The webhook job's user is the app account that re-applied the label, so the run would have belonged to the app and dropped the comment. The run now goes to the requester, which matches what the route's own enqueue already does.

**New tests** in `taskFollowupIssueRoutes.test.ts`, each simulating a failed enqueue, an expired dedup window and the relabel webhook:
- On a submission-backed issue, the child job belongs to `user-1` (not the submitter), the prompt contains the retry text, and the stored entry is gone afterwards.
- On an issue without a submission, the same holds.
- A failed dispatch keeps the stored entry.
- A label that can't be re-applied leaves no entry behind.

The existing test for a retry queued directly by the route now also checks that the entry is removed.

**Limits, not changed:**
- The stored entry is tied to the issue, not to one specific label event. Matching by timestamp would compare GitHub's clock with ours, and any clock difference could make the real recovery miss its own entry. So whichever trigger is dispatched next, within 24 hours, picks it up. Since the route refuses a retry while a run is queued, that trigger is the recovery.
- If the relabel webhook arrives inside the 30-second dedup window after a failed enqueue, it is still dropped as a duplicate. A run then only starts when polling sees the label. That behaviour is unchanged; when polling does start it, the run now gets the right owner and instructions.

There is no visible UI change, so no previews were made.

PR: #3125
Comment by: @integry (ID: 6189842500)
Model: Claude Opus 5.5

* feat(ai): I've fixed the Redis leak: `test/issueJobDispatcher.handleDispatch.test.ts` and the other affected test files now finish with exit code 0 instead of hanging.

I've fixed the Redis leak: `test/issueJobDispatcher.handleDispatch.test.ts` and the other affected test files now finish with exit code 0 instead of hanging.

**Cause:** `src/jobs/issueJobDispatcher.ts` imported `redisClient` from `./issueJob/config.js` at the top of the file. Any test that imported `handleDispatchWithDeps` therefore opened a live ioredis connection that nothing closed.

**Fix:** I removed that top-level import. The production `handleDispatch` now loads the existing client only when it first looks up or clears a stored retry request (`workerRedis()`). The worker already loads that config module, so production still uses the same single connection. Tests that inject their own dependencies never load it, so no connection is opened. I didn't add a forced exit, longer timeouts or skipped tests, and nothing needs a live Redis. The recovery logic and its regression tests are unchanged.

**Tests:** I ran each affected file on its own, under a timeout, with `NODE_ENV=test npx tsx --experimental-test-module-mocks --test <file>` and no Redis running:

| File | Exit | Pass / fail | ECONNREFUSED lines |
|---|---|---|---|
| `test/issueJobDispatcher.handleDispatch.test.ts` | 0 (about 3s) | 1 / 0 | 0 |
| `test/issueJobDispatcher.test.ts` | 0 | 91 / 0 | 0 |
| `packages/api/test/taskFollowupIssueRoutes.test.ts` | 0 | 25 / 0 | 0 |
| `test/taskSubmissionLifecycle.test.ts` | 0 | 29 / 0 | 44 |
| `packages/core/test/taskSubmissionService.test.ts` | 0 | 8 / 0 | 0 |
| `test/issueDetection.integration.test.ts` | 0 | 36 / 0 | 0 |

`test/taskSubmissionLifecycle.test.ts` still prints connection-refused lines, but it finishes and passes. That test already replaces the config module with a mock, and my change only removes a connection. So those lines must come from another source in that test, which I didn't track down.

Typecheck (`tsc --noEmit`) and eslint on the changed file are clean. There's no visible UI change, so I made no previews.

PR: #3125
Comment by: @integry (ID: 6190119673)
Model: Claude Opus 5.5

* feat(ai): I fixed S7. When GitHub applies the retry's trigger label but the response is lost, the saved retry request and the dedupe window are now kept. The receipt says the retry may still start instead of saying it did not start, and the run that recovery later picks up belongs to the person who asked for it and includes their instructions. All of this is in `packages/api/routes/taskIssueFollowup.ts`. The new tests pass, nothing ran against real GitHub, and the change is server-side only, so there are no previews.

I fixed S7. When GitHub applies the retry's trigger label but the response is lost, the saved retry request and the dedupe window are now kept. The receipt says the retry may still start instead of saying it did not start, and the run that recovery later picks up belongs to the person who asked for it and includes their instructions. All of this is in `packages/api/routes/taskIssueFollowup.ts`. The new tests pass, nothing ran against real GitHub, and the change is server-side only, so there are no previews.

**What changed:** `safeAddLabel` can't tell a lost response from a refusal, so when it reports failure the route now re-reads the issue's labels to decide what happened:

| What the re-read shows | What the route does now | Request and dedupe |
|---|---|---|
| Label is there | Treats it as applied and queues the run with the requester and comment, as normal. A relabel webhook arriving inside the dedupe window is ignored as a duplicate. | Kept |
| Label is missing (a definite refusal) | Same refusal as before: "could not be started" | Released |
| Labels can't be read | Returns `state: 'unknown'`: "could not be confirmed, so the retry may still start" | Kept, same as the existing enqueue-failure path |

If removing the old label fails, the route still refuses as before. That step never adds a label, so nothing can start from it.

**One gap I can't close:** if the re-read shows the label missing but the add is still in progress on GitHub and lands afterwards, the request has already been released, so that run would start without the requester. This is a race between two separate GitHub calls, and I didn't try to make it atomic.

**New tests** in `packages/api/test/taskFollowupIssueRoutes.test.ts`:
- **The regression you asked for, run twice:** once for a submission-backed issue and once for an issue-only one. GitHub accepts the label but the response is lost and the re-read also fails. The route reports `unknown`, saves no job and keeps the request and dedupe; a webhook inside the window is ignored. After the window, the relabel webhook starts the run, which belongs to `user-1` (not the submitter) and includes the posted comment in the prompt. The request is released afterwards.
- **Lost response, label confirmed:** exactly one job is queued, with the requester and comment, and the relabel webhook is ignored as a duplicate.
- **Definite refusal (422):** reports "not started", queues nothing, and releases the request and dedupe.

To support these, the shared test fixture (`packages/api/test/taskFollowupFixture.ts`) now records label adds and removals on the fake issue. It also has modes for a lost response, a refusal and a failed re-read. No existing test or assertion was changed or weakened.

**Verification:**
- **New tests against the old route:** all four fail and the existing 25 still pass. With the change, all 29 pass.
- **The five focused files** (both dispatcher tests, the follow-up routes, submission lifecycle and the submission service): 158 tests, 158 pass, 0 failures, 0 skips, exit 0 in 13s. Your set of 163 is a different selection, so I can't confirm those numbers.
- **Isolated dispatcher test:** exits 0 in 5s with no Redis running, so the Redis leak fix still holds.
- **Typecheck and lint:** clean for the three changed files. My first version added two complexity warnings, which I removed by splitting the code into small helpers.

These tests have to be run from the repo root. Run from inside `packages/api`, the follow-up test file loads core's built `dist` code and hung until I killed it.

The Gmail, Google Calendar and Google Drive connectors need to be authorized in your claude.ai connector settings before they can be used. This task didn't need them.

PR: #3125
Comment by: @integry (ID: 6190302290)
Model: Claude Opus 5.5

* feat(ai): I've fixed F5 and closed the delayed label-write gap. A saved retry request now only applies to the trigger it actually published. A later, separate trigger can't pick up the earlier requester or their comment, even when deleting the saved request failed. A timed-out label write that GitHub may still apply now gets an "unknown" receipt instead of "failed". The focused suites pass: 229 tests, 0 failed or skipped, and the run exits on its own in about 19s. Typecheck is clean and lint shows no new warnings. Nothing ran against real GitHub.

I've fixed F5 and closed the delayed label-write gap. A saved retry request now only applies to the trigger it actually published. A later, separate trigger can't pick up the earlier requester or their comment, even when deleting the saved request failed. A timed-out label write that GitHub may still apply now gets an "unknown" receipt instead of "failed". The focused suites pass: 229 tests, 0 failed or skipped, and the run exits on its own in about 19s. Typecheck is clean and lint shows no new warnings. Nothing ran against real GitHub.

**How the saved request is tied to its trigger** (`packages/core/src/services/issueRetryRequest.ts`)
- Before posting the comment, the route reads the issue's latest trigger-label event. The saved request records that event, the time of the request, and the GitHub account the app posts as (taken from the posted comment).
- The request belongs only to the first trigger label that same account adds after that event, and only if it lands within 10 minutes of the request.
- The dispatcher uses the saved request only when the trigger it is running is that one. For submission-backed issues that's the trigger it resolved; for issue-only it's the latest. The proof comes from the issue's timeline on GitHub, not from Redis:
  - **Dispatched, then deletion failed:** a later trigger is no longer the first one after the recorded event, so it runs for the submitter (or whoever triggered it) with no exempt comment.
  - **Refused, then deletion failed:** no trigger from the app ever exists. A later trigger by someone else, or by the app after the 10 minutes, is not matched.
- Deleting the request after dispatch or refusal is now just cleanup.

**The delayed label write** (`packages/api/routes/taskIssueFollowup.ts`)
- The route now adds the label itself instead of going through `safeAddLabel`, so it can tell outcomes apart:
  - **GitHub answered with a 4xx:** the write was refused. The existing "not started" path is unchanged: delete the request and the dedupe key, and return `failed`.
  - **Timeout, no response, or 5xx:** if reading the labels back shows the trigger, the route queues the run as before. If not, the result stays `unknown`: the request and the dedupe key are kept and the receipt says the retry may still start. A read that doesn't show the label doesn't prove the write was rejected.
- If the label history can't be read, the route refuses with a 502 before posting anything.

**Tests**
- They're in a new file, `packages/api/test/taskFollowupIssueRetryOwnership.test.ts`. Each case runs for both a submission-backed and an issue-only issue:
  - **Delayed write:** the label POST times out, reading it back shows nothing, and the route returns `unknown` and queues nothing. The write then lands and the relabel is delivered; the run belongs to the requester and includes their instructions.
  - **Your F5 scenario:** the run is dispatched and deleting the request fails. A later trigger by the app's own account doesn't take the old requester or comment.
  - **Refused write, then deletion fails:** a later trigger by someone else, or by the app after the 10 minutes, doesn't take them.
- To check the tests catch the bugs, I disabled the trigger check in the dispatcher: 6 of the new tests failed. Treating every failed write as refused made the delayed-write tests fail, along with the earlier lost-response ones.
- The dispatcher test helpers moved into `packages/api/test/taskFollowupIssueDispatch.ts`, so the original test file stays under the line limit. The test version of `recordDispatch` now writes the same dispatch record as production.
- Still passing: the S7 lost-response, F4 enqueue-recovery and F1 same-second tests, requester ownership, duplicate suppression, and the refused-write path. The dispatcher test still finishes without a Redis connection.
- Your probe file isn't on this host, so I didn't run it. The new delayed-write test recreates the same steps.

**What's still uncertain**
- **Cleanup fails and the write never lands, then the app adds the trigger again within 10 minutes:** a later trigger added by the app's own account within 10 minutes could still take an old request. That covers a write GitHub refused, or one left `unknown` that never lands. Only another write could rule this out, so I narrowed it rather than claiming it can't happen.
- **Very late or out-of-order triggers:** if a write lands more than 10 minutes late, or someone else adds the label between our late write and the dispatch on an issue-only task, the run falls back to the submitter or the triggering user without the instructions. That's a lost recovery, not a run credited to the wrong person.
- **Untested against real GitHub:** I'm assuming GitHub's timeline names the same account for the label event as for the comment the app posts, since both use the same credentials. If the account were missing from the comment, the account check would be skipped.
- **Extra GitHub reads:** one timeline read per follow-up, plus one per dispatch while a saved request exists.

PR: #3125
Comment by: @integry (ID: 6190576336)
Model: Claude Opus 5.5

* feat(ai): I've fixed F6, F7 and F8. The 221 tests in the follow-up, dispatcher, submission and MCP suites pass, and the run exits on its own in about 18s. Typecheck is clean (root, core and api), and lint shows no new warnings in the files I changed. Nothing ran against real GitHub. The change is server-side only, so there are no previews.

I've fixed F6, F7 and F8. The 221 tests in the follow-up, dispatcher, submission and MCP suites pass, and the run exits on its own in about 18s. Typecheck is clean (root, core and api), and lint shows no new warnings in the files I changed. Nothing ran against real GitHub. The change is server-side only, so there are no previews.

**How a saved retry request works now** (`packages/core/src/services/issueRetryRequest.ts`):
- **Several requests per issue.** The issue's key now holds a list of requests instead of one record. Every change is a compare-and-swap, so one request can't overwrite another.
- **Not usable until the label write is reported.** A request is saved as `pending` before the label write. Recovery only uses it after the route marks it `possible`, meaning the label was applied or may still be.

**F6 – refused requests.** A refused write never gets marked `possible`, so recovery can't use it even if deleting it and every later Redis write fail. Deleting it is now just cleanup. The new test covers the case the review named: the app labels the issue again within the publication window. The other-actor and after-the-window cases now also fail Redis from the label write onward.

**F7 – a second request overwriting an unresolved one.** A new request is refused with a 409 ("An earlier retry … may still start") while an earlier request's label write could still land. That is, its trigger isn't on the issue yet and its 10-minute publication window hasn't passed. The refusal happens before anything is posted. The check runs before the comment is posted, and again atomically when the request is saved. Saving also keeps earlier requests whose trigger was already published, and drops ones that are refused, expired or never landed. Tests cover:
- A still pending, B refused, then A landing late and running for A's requester with A's instructions.
- B replacing A once A's window has passed with nothing landing.

**F8 – queued jobs and later triggers** (`src/jobs/issueJobDispatcher.ts`). When the dispatcher consumes a trigger, a queued job's request must have published that trigger. If it didn't (someone relabelled before the job ran), the job runs the newer trigger for the submitter. It drops the requester and comment, records the newer trigger as consumed, and leaves the request saved instead of releasing it. Recovery and queued jobs now use the same matching function.

Each new test fails when I disable the matching part of the fix.

**Things you should know:**
- **One trade-off.** If Redis fails right after a label write whose result is unknown, the request stays `pending`. A late trigger then runs without the requester's identity and instructions. I chose that over giving one person's identity and instructions to a run they didn't ask for, and a test covers it.
- **Superseded requests don't run separately.** In the F8 case the earlier request stays saved, but on a submission-backed issue the dispatcher only runs the latest trigger. So that request's own trigger won't start a separate run, and the record expires after 24 hours.
- **A small behaviour change.** A request whose label write was refused and whose deletion also failed blocks new follow-ups on that issue for up to 10 minutes.

**Outside this fix (not changed):**
- On issue-only issues, a job the route queued still keeps its request even if someone relabelled before it ran. No trigger is consumed there, and the shared job ID merges both triggers into one run, which is how it already worked.
- The publication window compares the server's clock with GitHub's event timestamps, so large clock drift could misclassify a late label.

PR: #3125
Comment by: @integry (ID: 6191058507)
Model: Claude Opus 5.5

* feat(ai): I've fixed F9 and F10. A saved retry request now keeps its requester and instructions through outcome recording and dispatch. When the dispatcher can't tell whose a trigger is, it now holds off instead of running that trigger with the wrong context.

I've fixed F9 and F10. A saved retry request now keeps its requester and instructions through outcome recording and dispatch. When the dispatcher can't tell whose a trigger is, it now holds off instead of running that trigger with the wrong context.

**Tests:** The focused route, ownership, dispatcher, submission, issue-detection and MCP suites pass: 282 tests, 0 failed or skipped, and the run exits on its own in about 18s. The two suites that apply every migration also pass with the new one. Typecheck is clean (root, core and api) and lint is clean in the files I changed. Nothing ran against real GitHub, and the change is server-side only, so there are no previews.

**F9 (outcome recording fails):**
- The route now writes the label write's outcome ("possible" or "refused") to a new SQLite table, `issue_retry_request_states`, before updating Redis. This is a new migration file. If Redis fails, the record still tells the dispatcher what happened, so a late trigger runs for the requester with their instructions, and a refusal still can't be adopted.
- If the outcome can't be recorded anywhere, the dispatcher returns `skipped` with reason `retry_request_unreconciled`. Nothing is dispatched or consumed and the request stays saved, so a later webhook or poll can try again.
- The `unreported-trigger` tests now require the original requester and instructions to be kept. New tests cover a timed-out write and a refused write that can't be recorded anywhere; both must defer on repeated deliveries without consuming the trigger.

**F10 (a newer trigger strands a queued request):**
- Direct jobs and recovery deliveries now pick the run with the same function, `selectRetryRun`. It serves saved requests oldest first, each only on its own trigger, and only while that trigger is still eligible and hasn't been used.
- `admittedSubmissionTriggers` checks a specific older trigger against the submission's rules, not just the latest one.
- When a request runs on its own trigger, the dispatch is recorded up to the latest trigger, so the newer independent label doesn't start a second run.
- The dispatcher also marks the request as dispatched in SQLite. That lets issue-only work tell a request that has already run from one still waiting, even if clearing it from Redis fails.
- The new tests cover both submission-backed and issue-only work: a queued retry overtaken by a person's relabel, and a retry whose enqueue failed and is then recovered after an independent relabel.

**What's preserved:** the protection against adopting refused requests, conditional reservation, actor matching, duplicate suppression, and the F1–F8 cases (their tests still pass).

**Limitations that remain:**
- **Both stores fail:** if neither SQLite nor Redis can record the outcome, or the API process dies between the label write and the recording, the outcome stays unknown. That trigger is then deferred until the saved request expires, 24 hours after its last write. After that the trigger is treated as unrelated work and runs without the request's context. The same holds for a refused write whose records both failed, if the app labels the issue again within 10 minutes.
- **Retry depends on later deliveries:** a deferral is only retried when a later delivery arrives (polling or a webhook redelivery). Nothing reconciles it in the background.
- **Waiting for an unconfirmed label:** while a request's label write may still land (up to 10 minutes), deliveries from independent triggers are deferred too. Running them would use up the request's trigger and strand the request.

**Separate finding (not fixed):** if a follow-up's enqueue fails and a second follow-up is accepted before recovery, there are two outstanding requests. Only one run can carry instructions, so the newer request is absorbed without its context. Before this change the older one was. The real fix is for the route to refuse a second request while an earlier one is still waiting; I left that alone because it's outside F9 and F10.

PR: #3125
Comment by: @integry (ID: 6191590304)
Model: Claude Opus 5.5

* feat(ai): I've fixed F11, F12 and F13, and the F1–F10 regressions still pass. To do it I moved saved retry requests out of Redis into the database table, which means a request no longer expires after 24 hours. Nothing ran against real GitHub, and the change is server-side only, so there are no previews.

I've fixed F11, F12 and F13, and the F1–F10 regressions still pass. To do it I moved saved retry requests out of Redis into the database table, which means a request no longer expires after 24 hours. Nothing ran against real GitHub, and the change is server-side only, so there are no previews.

**One thing to check before merge:** I rewrote this PR's own migration (`20261015080000_create_issue_retry_request_states.js`) in place rather than adding a new one. Any database that already ran the earlier version keeps the old table layout and has to drop and recreate `issue_retry_request_states`.

**F11 – a second request no longer takes over an earlier one's run**
- An issue can now have only one request still waiting to run, and the database enforces it with a unique constraint. The slot is reserved before anything is posted.
- A second follow-up while an earlier request is still waiting gets a 409 before any comment or label is written. Requests that are known to be finished are released at that point: already run, refused, or never published.
- A run on the latest trigger therefore can't absorb another accepted request's trigger. The dispatcher also reads the label history before the saved requests, and takes its own trigger from that same read. This closes a window where a request published mid-dispatch could be absorbed.

**F12 – a refused label write stays refused**
- When GitHub answers the label write with a 4xx, the retry is reported as not started straight away, and there's no read-back.
- When the outcome is unclear (timeout or lost response), the confirmation now comes from the issue timeline: the first trigger applied by the app's own GitHub account after the request. It no longer checks whether the label is present. A label someone else adds confirms nothing.
- A queued issue-only job now uses the same ownership rules as recovery. If its own trigger isn't on the timeline yet, the job is deferred. Once it can no longer arrive, the job is skipped instead of running with the request.

**F13 – old requests don't lose their context**
- The requester, issue, comment, label baseline and app identity are saved before the label is written. Time limits are gone: a request whose outcome is unknown keeps deferring its trigger, including after 1 day and after 8 days.
- Cleanup only deletes requests already known to be finished.
- If recording that a run used a request fails, the dispatch now fails so the queue retries it. Previously that failure was only logged.

**Tests:** the focused set passes, 294 tests with no failures or skips, and finishes on its own in about 26s. Run standalone, each suite exits 0 in 3–4s. Root/core/api typecheck, lint and the OpenAPI check are clean; I documented the new 503 and the wider 409 and regenerated the spec and client types. The new tests cover:
- a failed enqueue followed by a second follow-up, with different comment IDs
- both stores unavailable
- a later delivery beyond the old 24-hour limit and beyond cleanup
- a person relabelling during both a refused write and a timed-out write

I also undid each fix one at a time, and each time the tests written for it failed.

**Limits that remain:**
1. If GitHub's answer to the label write is unclear and the outcome can't be recorded, and the app's own account labels the issue soon after, nothing can tell whose trigger that is. That issue's trigger stays deferred, and new follow-ups get a 409, until someone updates the database row by hand.
2. If an accepted request never runs because someone removed the label, new follow-ups get a 409. Adding the label back lets the request run, which frees the issue.
3. For an issue with no submission record: if recording that a run used the request keeps failing through every queue retry, a later trigger can run the same request again. It's the same requester and instructions, so it duplicates the run rather than mixing context.
4. If the timeline is slow to show the label, a queued job waits for the next polling pass.
5. A trigger is matched to a request by the GitHub account that applied the label. Another ProPR process labelling as the same app within 10 minutes can't be told apart.

**Already there, not fixed:**
- `taskFollowupIssueRoutes.test.ts` has two type errors at lines 41 and 369.
- The route's 502 response isn't in the OpenAPI docs.

PR: #3125
Comment by: @integry (ID: 6192129045)
Model: Claude Opus 5.5

* feat(ai): I've fixed F14, F15 and S11 along with the two type errors and the 502 docs entry, and the F1–F13 regressions still pass. The 14 focused suites pass together: 334 tests, 0 failed, skipped or cancelled. The combined run exits on its own in about 31s, and each file run alone exits 0 in 1–18s. Typecheck is clean for root, core and api, lint shows nothing new, and the OpenAPI check passes. Nothing ran against real GitHub, and the change is server-side only, so there are no previews.

I've fixed F14, F15 and S11 along with the two type errors and the 502 docs entry, and the F1–F13 regressions still pass. The 14 focused suites pass together: 334 tests, 0 failed, skipped or cancelled. The combined run exits on its own in about 31s, and each file run alone exits 0 in 1–18s. Typecheck is clean for root, core and api, lint shows nothing new, and the OpenAPI check passes. Nothing ran against real GitHub, and the change is server-side only, so there are no previews.

**F14 – a confirmed label write is no longer left stuck**
- If saving the outcome fails after GitHub confirmed the label, the route no longer swallows the error. The receipt is now `unknown` ("starts once that record is saved"), not `queued`.
- The route still queues the job, and the job serves as the evidence. It is only queued after GitHub confirms the label. So when the dispatcher finds that job's own request still marked `pending`, it records the outcome itself and then runs the request.
- If that save fails, the dispatch fails so the queue retries it, instead of finishing as `skipped`.
- Any outcome the route couldn't save is also retried in the background, with growing pauses for up to a day. This covers confirmed, timed-out and refused writes, so a `pending` request no longer depends only on someone editing the database.
- A relabel delivery carries no such evidence, so it still holds off. Unknown and refused stay distinct, and the ownership checks are unchanged.

**F15 – a slow comment post no longer invalidates the retry**
- The reservation time (`requested_at`) and the start of the label write (new `published_at`) are now stored separately. Only the second one sets the 10-minute window for matching the label.
- `published_at` is recorded right before the label is added. Removing the old label now happens before that point, so no GitHub call sits between recording it and adding the label.
- The same value is used by the route's read-back check and by the dispatcher.

**S11 and test fixes**
- The recovery helper now dispatches the job the relabel actually queued, and checks that this job carries no retry details.
- In the "both run in turn" test, the second request now comes from a different user (`user-2`) with its own comment ID. Each run is checked for its requester, comment and instructions.
- I fixed the two type errors in `taskFollowupIssueRoutes.test.ts` by typing `issue_number` on the fixture's request mock.
- I documented the route's 502 next to the 503 and regenerated the spec.

**New tests** are in `packages/api/test/taskFollowupIssuePublication.test.ts`, each run for both issue-only and submission-backed issues:
- a comment post that takes 11 minutes, combined with a normal, lost-response or delayed label write
- a confirmed write whose outcome can't be saved
- a write whose outcome and job both can't be saved, for each kind of write

I undid the F15 and F14 fixes one at a time, and the matching tests failed each time (6 and 2 tests).

**Limits that remain:**
1. The background retry lives only in the API process. If the database and the queue both fail at that moment and the process then restarts, the outcome is lost. If the app's own account labelled the issue within the window, that issue's trigger is held back until someone edits the row by hand.
2. When the job records the outcome itself, the queue retries it at most three times (after 2s and 4s). Past that, only the background retry and later deliveries remain.
3. If GitHub's timeline hasn't caught up with a confirmed label yet, the job is skipped and waits for a later delivery (unchanged from before).
4. Because the old label is now removed before the request is marked `pending`, a failure at that step leaves the label off. The receipt then says not started and asks for the label back.
5. I added the `published_at` column to this PR's own migration in place, again. Any database that ran an earlier version has to drop and recreate `issue_retry_request_states`.
6. The remaining type errors in `taskFollowupFixture.ts` are about importing `.js` migrations. Other test files in the repo hit the same errors, so I left them alone.

**Found separately, not fixed:** when a request gives up, it deletes the issue's duplicate-guard key in Redis without checking whose key it is. If its reservation expired and another request took over, that other request loses its guard. I haven't confirmed this has a visible effect.

PR: #3125
Comment by: @integry (ID: 6192902761)
Model: Claude Opus 5.5

* feat(ai): I fixed the restart limbo, but the recovery is user-triggered, not automatic. After a restart, the next Follow Up on the task restarts the stuck request for its original requester, with their original instructions. Until someone follows up, webhook and poll deliveries still return `retry_request_unreconciled`. That's on purpose: once the API process's memory is gone, nothing on GitHub can tell "our write landed" from "GitHub refused it and another app flow added the same label". So the only safe automatic choice would be to keep waiting, and I didn't want to guess.

I fixed the restart limbo, but the recovery is user-triggered, not automatic. After a restart, the next Follow Up on the task restarts the stuck request for its original requester, with their original instructions. Until someone follows up, webhook and poll deliveries still return `retry_request_unreconciled`. That's on purpose: once the API process's memory is gone, nothing on GitHub can tell "our write landed" from "GitHub refused it and another app flow added the same label". So the only safe automatic choice would be to keep waiting, and I didn't want to guess.

**What happens now**
- **When a restart is offered:** a request is "stranded" once 10 minutes have passed since its label write began (the write can no longer land) and no run has picked it up. A Follow Up before that point still gets the 409 "may still start".
- **The restart itself:** the route removes and re-adds the trigger label for the earlier request, after a fresh baseline, so the new label event is unambiguously its own. The run is queued for the original requester with the original comment.
- **What the user sees:** the new follow-up text is not posted. The response is 202 with `success:false`, `state:refused`, `posted:false` and a new `restartedRequest: {state, commentId}` field. The message tells them to send the text again once that run finishes. Because `success` is false, the existing modal shows the message instead of "Follow-up queued successfully".
- **Pointing users to it:** receipts whose outcome couldn't be recorded now end with "If it has not started in about ten minutes, follow up again to restart it."

**Protections kept**
- **Refused restart:** if GitHub refuses the restart's label, the request stays owed and the old label stays deferred, so it never runs without its instructions. Another Follow Up restarts it again.
- **Stale evidence can't confirm the wrong write:** a background outcome retry or an old queued job from the lost write can't confirm the restart. Jobs now carry `retryPublishedAt`, and outcome records must match it.
- **Unchanged:** unknown/refused/successful outcomes, ownership, comment/requester binding, later independent labels running without a request, and the cancelled/closed/not-failed guards. A cancelled issue gets the 409 and the request is kept.
- **Late timeline visibility:** a queued request whose label shows up late in the timeline is still reachable. Early deliveries defer without consuming it, the next normal delivery runs it, and if none comes, a Follow Up restarts it.

**Before merge:** this adds a new migration, `packages/core/src/db/migrations/20261015090000_add_issue_retry_request_resumed_at.js`, which adds a `resumed_at` column. No tables are dropped. The OpenAPI spec and client types are regenerated.

**Tests**
- New file `packages/api/test/taskFollowupIssueRestart.test.ts`, 14 tests covering both issue-only and submission-backed issues:
  - Your exact reproduction: the label is confirmed, the request table is offline and `queue.add` is rejected; then both stores come back, the callbacks are dropped and an hour passes. Three webhook/poll deliveries each defer. After the Redis claim expires, a Follow Up from another user restarts the request, and the run belongs to `user-1` with the original instructions. A later follow-up then works normally.
  - Restart too early, refused restart, stale evidence, late timeline visibility (with and without a later delivery), and a cancelled issue.
- In `packages/api/test/taskFollowupIssueRetryOwnership.test.ts`, the four tests that asserted permanent deferral now expect a later Follow Up to restart the request.
- The focused set passes: 500 tests in 27 suites, 0 failed, skipped or cancelled, exit 0. That set is the five `packages/api/test/taskFollowup*` files plus `mcpWorkflows`, both OpenAPI tests, both `test/issueJobDispatcher*`, `taskSubmissionService`, `taskSubmissionLifecycle`, `planIssueHandlers.followup`, `intentWithdrawalWebhook` and `taskIntentWithdrawal`.
- Each file run alone exits 0. Most take 1–15s; `test/taskIntentWithdrawal.test.ts` takes about 154s.
- Typecheck is clean for root, core and api, lint is clean on the changed files, the core build succeeds, and `gen:openapi:check` passes.

Nothing ran against real GitHub. No UI code changed, so I made no previews; the new message shows up in the existing follow-up error display.

PR: #3125
Comment by: @integry (ID: 6193475463)
Model: Claude Opus 5.5

* feat(ai): I've fixed F16, F17, F18 and F19 and added the S12 real-queue coverage. The F1–F15 regressions still pass.

I've fixed F16, F17, F18 and F19 and added the S12 real-queue coverage. The F1–F15 regressions still pass.

The focused set (17 files) passes: 357 tests, 0 failed, skipped or cancelled. It exits on its own in 28s. This run used a Redis 7.2.5 server I built in `/tmp` only to run S12; it isn't part of the repo. Each touched file run alone exits 0 in 0–5s, and the slower `taskIntentWithdrawal` suite passes too (170 tests). Typecheck is clean for root, core and api, there are no new lint warnings, and `gen:openapi:check` passes. Nothing ran against real GitHub. The change is server-side only, so there are no previews.

**F16 – outcome recovery after a restart**
- **Where the outcome is kept:** when the route learns GitHub's answer but can't save it to the database, it now stores that answer in Redis with no expiry. The record names the exact request and write, so it never confirms a later restart's write.
- **Who reads it:** any later webhook or poll records it before deciding what to run, and so does the next follow-up. A confirmed write runs for the original requester with their instructions. A refusal releases the request, so it is never restarted.
- **When it is deleted:** only after the database save succeeds. It survives the API process restarting, the queued job using up its attempts, and outages longer than the route's 24-hour retry.
- **Your reproduction:** the case in your comment 6193475463 now runs on the next delivery instead of returning `retry_request_unreconciled`.
- **Fallback:** the follow-up restart from the last round is only needed now if the database and Redis are both down at that moment. Those tests now take both stores down.

**F17 – an expired request touching its successor**
- The route now claims the issue in the database before it changes any labels. A request whose reservation expired stops without touching anything.
- The dedupe key is now deleted only if it still holds the releasing request's own token. This applies to the abandon, refusal and restart paths.
- If a request's label write runs past its window and a later request takes over, it now stops. It doesn't queue a job, doesn't relabel, and reports `unknown`. Before, it returned a false `queued`.

**F18 – matching earlier triggers**
- A request's trigger must now fall between the second its write began and the end of its window. App labels added while the comment was still posting are skipped. The route's read-back uses the same rule, so an earlier app label can't confirm a write that timed out.

**F19 – label adds that change nothing**
- The label is removed based on the issue's current state just before the add, not the stale snapshot.
- A successful add only counts if an event from the request's own identity appears. If none does, the route checks it still owns the issue and writes again once. If there is still no event, the receipt is `unknown` and no job is queued.
- The GitHub test fixture now treats adding an already-present label as a no-op, including delayed writes that land late. One existing test now has the person remove their label before the delayed write lands.

**S12 – real BullMQ/Redis lifecycle** (`taskFollowupIssueQueueLifecycle.test.ts`)
- Repeated issue-only retries reuse the same job ID, each running for its own requester.
- A poll, and even a direct add with the same job ID, doesn't replace a waiting retry job.
- For both routings, a job carrying a confirmation fails 3 times while the database is down and is removed. Its Redis record outlives it, and the next poll runs the request.
- It skips when Redis is unreachable, and fails instead when `PROPR_REQUIRE_REDIS_INTEGRATION=1` is set, as CI does.

New regression files are `taskFollowupIssueOutcomeRecovery.test.ts` and `taskFollowupIssuePublicationRaces.test.ts`. I checked that they fail against the old route and the old trigger matcher.

**Races that can't be closed:**
- If the database and Redis are both down when the outcome is learned, only the follow-up restart can recover the request.
- If a person adds the label while our write is timing out, the late write changes nothing. The receipt says `unknown`, and after 10 minutes the issue is free for a new follow-up.
- An app-identity label in the very second our write begins, or between our remove and add, can't be told apart from our own.
- If GitHub's timeline is slow to show our event, we may write the label a second time. This is limited to two writes.

**Cost:** every retry now sends a DELETE first, which returns 404 when the label is absent, plus one timeline read after a successful add.

There's no new migration and no API schema change. I made no permission or credential changes and didn't touch user data or the Git boundary.

PR: #3125
Comment by: @integry (ID: 6193541028)
Model: Claude Opus 5.5

* feat(ai): I've fixed F20, F21 and F22 and done S13. The F1–F19 regressions still pass. The final run covered 14 files and 333 tests, including the real BullMQ suite against a dedicated Redis with `PROPR_REQUIRE_REDIS_INTEGRATION=1`. Nothing failed, was skipped or was cancelled, and every process exited normally. Types and lint are clean. I made no changes to permissions, credentials, the user DB, Git finalization or the Claude route.

I've fixed F20, F21 and F22 and done S13. The F1–F19 regressions still pass. The final run covered 14 files and 333 tests, including the real BullMQ suite against a dedicated Redis with `PROPR_REQUIRE_REDIS_INTEGRATION=1`. Nothing failed, was skipped or was cancelled, and every process exited normally. Types and lint are clean. I made no changes to permissions, credentials, the user DB, Git finalization or the Claude route.

**F20 – same-second events losing the retry's instructions** (`taskIssueFollowup.ts`, `issueRetryRequest.ts`)
- The route now reads the trigger history again after the comment is posted, just before the label write. It saves that baseline together with the publication start time. A trigger another app flow added while the comment was posting, even in the same GitHub second, is no longer taken as the retry's own.
- If that history can't be read, nothing is published. The reservation and Redis claim are released, and the response says the label history couldn't be read.
- The restart path had the same problem, so it also reads a fresh baseline just before recording the restart.
- The interval rules and second-level precision are unchanged.
- New test: the comment finishes in the same second as an independent app trigger that has already been dispatched. On the old code the child ran as `submitter`; now it runs for `user-1` with the posted instructions.

**F21 – restarted requests ignoring successful dispatch** (`issueRetryRequest.ts`, `issueJobDispatcher.ts`)
- A request now counts as already carried only when all of these hold: its write was applied, its own trigger can still be identified, and the submission's recorded consumed trigger is that trigger or a later one in the history. A trigger that merely isn't admitted proves nothing.
- Dispatch selection settles such a request and doesn't defer the delivery. Reservation admission releases it, so it is never restarted.
- Pending, refused or unresolvable restarted requests stay owed exactly as before.
- New tests:
  - Restart, then dispatch with the consumption write failing: the child and its receipt are durable. The dispatch retry settles the request without re-running it, deliveries are no longer deferred, and a new follow-up runs only its own instructions.
  - The same setup with no dispatch retry: the next follow-up's reservation releases the old request.
  - Negative cases that must stay owed: no receipt, a receipt before the trigger, a receipt the history no longer shows, a lost baseline, a refused restart, and an unknown outcome.

**F22 – real-queue cleanup deleting unrelated keys** (`taskFollowupIssueQueueLifecycle.test.ts`)
- Everything the suite writes now lives under a per-run namespace:
  - The route, poll and dispatcher use a key-prefixed Redis client, which covers claims, outcome keys and the poll's activity log.
  - BullMQ uses a prefix inside that namespace.
- Cleanup scans and deletes only that namespace. There are no `keys`, flushes or production-pattern deletes.
- Unrelated claim and outcome sentinels are checked after every test (value and expiry unchanged), then removed.
- Extra check on my dedicated Redis: I placed foreign keys at the exact production names (`issue:dedup:integry:propr:14` and an `issue:retry-outcome:*` key). The new suite left both untouched. The old suite deleted both and also left a stray `system:activity:log` key outside any test namespace.

**S13 – real child jobs**
- The repeated-retry test, for both submission-backed and issue-only issues, now runs child jobs through BullMQ. The child step is simulated: it only builds the prompt, with no provider calls.
- The first dispatch fails to record consumption while its child is still running. On the issue-only path, BullMQ's retry re-adds the same child ID, which is deduplicated. On the submission-backed path, nothing is re-added. Either way the child runs exactly once.
- Removal and reuse behave as intended: issue-only children are removed and their ID is reused for the next retry, while a submission's child is kept as its receipt and the next retry gets a new trigger-specific ID.
- Each actual child run is checked for its requester and instructions.
- I also fixed a hang: if an assertion failed while a child was being held, cleanup waited forever on it. Cleanup now releases the hold first.

**Other things I found (not changed)**
- **Duplicate issue-only runs:** if an issue-only dispatch fails to record consumption and its child completes or fails within the parent's 2-second retry backoff, the retry re-adds a now-free child ID. The same request would then run twice. Real runs take minutes, but a fast failure (like the original auth failure) could hit this.
- **Unavoidable race:** an app-identity trigger added between the fresh history read and the label write, in that same second, can still be mistaken for the retry's own. It can't be fully closed, because GitHub only timestamps to the second and the label add can't be made conditional.

There's no Redis in this container, so I built one from source in `/tmp` (outside the repo) on 127.0.0.1:16392 and shut it down afterwards. The suites have to be run from the repo root; from `packages/api`, `@propr/core` loads the built package and the test mocks don't apply.

PR: #3125
Comment by: @integry (ID: 6195097031)
Model: Claude Opus 5.5

* feat(ai): I fixed the duplicate issue-only run. When recording consumption fails and the child completes or fails before the parent's 2-second retry, the accepted request's child now runs exactly once. The next real follow-up still runs normally for its own requester and instructions. The final run covered 15 files and 356 tests, including the real BullMQ suite against a dedicated Redis with `PROPR_REQUIRE_REDIS_INTEGRATION=1`. Nothing failed, was skipped or was cancelled, and every process exited normally. Types and lint are clean. All F1–F22 and S13 regressions still pass.

I fixed the duplicate issue-only run. When recording consumption fails and the child completes or fails before the parent's 2-second retry, the accepted request's child now runs exactly once. The next real follow-up still runs normally for its own requester and instructions. The final run covered 15 files and 356 tests, including the real BullMQ suite against a dedicated Redis with `PROPR_REQUIRE_REDIS_INTEGRATION=1`. Nothing failed, was skipped or was cancelled, and every process exited normally. Types and lint are clean. All F1–F22 and S13 regressions still pass.

**The fix** has two layers, in `issueJobDispatcher.ts` and `issueRetryRequest.ts`:
1. **Dispatch receipt.** After an issue-only dispatch adds the children, it saves a receipt for that request in Redis before recording consumption. This uses the same queue connection and storage as the existing outcome evidence. The receipt has no expiry and is deleted only once consumption is recorded.
   - When the dispatch is retried, it sees the receipt, records consumption, adds nothing, and returns `skipped` / `retry_request_already_dispatched`.
   - A later delivery, a restart, or the next follow-up settles the request the same way. So a new follow-up is accepted and runs only its own instructions; the old request is not restarted or replayed.
2. **BullMQ deduplication by request.** If saving the receipt itself fails, the child was still added with a BullMQ deduplication ID of `<childId>-retry-request-<requestId>` that lasts 24 hours. BullMQ sets this in the same atomic step as the add, and it outlives the removal of the completed or failed child. A retried add for the same request is absorbed. A new request has a new ID, so it is never blocked.

**What's unchanged:** submission-backed runs, plain deliveries, child IDs, normal job removal, outcome recovery, consumed-trigger evidence, cancellation/withdrawal and restarts of requests that never ran. No job is kept: finished children are removed as before. The deduplication key expires on its own, and the receipt exists only until consumption is recorded.

**New tests:**
- **Real B…
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Feat: Monitor PR comments for follow-up tasks

2 participants