Compare commits

..

210 Commits

Author SHA1 Message Date
dependabot[bot] 07b61bb9b6 ci(deps): bump actions/stale from 9 to 10
Bumps [actions/stale](https://github.com/actions/stale) from 9 to 10.
- [Release notes](https://github.com/actions/stale/releases)
- [Changelog](https://github.com/actions/stale/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/stale/compare/v9...v10)

---
updated-dependencies:
- dependency-name: actions/stale
  dependency-version: '10'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-02-26 18:26:20 +00:00
AndyMik90 60c4890218 Improved prompt for Opus 4.6 2026-02-21 21:34:08 +01:00
AndyMik90 b32b97da51 fix: use PAT_TOKEN for releases to trigger Discord notifications
- release.yml: Use PAT_TOKEN instead of GITHUB_TOKEN for softprops/action-gh-release
  so the published event triggers downstream workflows (Discord notification)
- discord-release.yml: Add workflow_dispatch trigger for manual re-runs

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-20 12:47:00 +01:00
Andy eb834ca32b Merge pull request #1853 from AndyMik90/fix/qa-validation-stuck-subtasks
fix: resolve QA validation deadlock when subtasks are stuck or failed
2026-02-20 12:00:10 +01:00
Andy ba57005e9b Merge pull request #1847 from AndyMik90/fix/crash-on-spec-path
fix: self-healing for invalid file paths in coder pipeline
2026-02-20 12:00:02 +01:00
Andy 81440514b1 Merge pull request #1836 from AndyMik90/fix/terminal-blank-project-switch
fix(terminal): resolve blank terminals after project switch
2026-02-20 11:59:55 +01:00
AndyMik90 803b231869 merge: resolve pty-manager.ts conflict for PR #1836 - keep exited terminal guard 2026-02-20 11:58:40 +01:00
Andy 4f25bf955d Merge pull request #1834 from AndyMik90/fix/memory-falkordb-to-ladybug
fix(memory): complete FalkorDB to LadybugDB migration in memory system
2026-02-20 11:58:09 +01:00
Andy dd8672c777 Merge pull request #1833 from AndyMik90/fix/kanban-stuck-task
fix: resolve Kanban board stuck task state synchronization
2026-02-20 11:57:59 +01:00
Andy 1ec03a27a4 Merge pull request #1832 from AndyMik90/terminal/improve-worktree-venv
feat: symlink Python venvs in worktrees for instant setup
2026-02-20 11:57:53 +01:00
Andy 2a1d8759b4 Merge pull request #1831 from AndyMik90/feature/webgl-context-management
feat(terminal): integrate WebGL context manager for GPU-accelerated rendering
2026-02-20 11:57:45 +01:00
Andy f2579f0629 Merge pull request #1829 from AndyMik90/auto-claude/225-bulk-delete-and-archive-chat-history
auto-claude: 225-bulk-delete-and-archive-chat-history
2026-02-20 11:57:37 +01:00
AndyMik90 66db171b5e merge: resolve conflicts for PR #1829 - keep both bulk delete/archive and image features 2026-02-20 11:56:22 +01:00
Andy 0de608f0c7 Merge pull request #1821 from AndyMik90/auto-claude/224-add-screenshot-paste-capability-to-chat
auto-claude: 224-add-screenshot-paste-capability-to-chat
2026-02-20 11:54:26 +01:00
Andy a5dfcd09d9 Merge pull request #1820 from AndyMik90/auto-claude/221-refactor-github-pr-review-with-xstate
auto-claude: 221-refactor-github-pr-review-with-xstate
2026-02-20 11:54:18 +01:00
AndyMik90 c8fa9281e5 merge: resolve conflicts in pr-handlers.ts and state-machines/index.ts for PR #1820 2026-02-20 11:53:07 +01:00
Andy 1e455da508 Merge pull request #1819 from AndyMik90/auto-claude/229-implement-account-aware-terminal-session-persisten
auto-claude: 229-implement-account-aware-terminal-session-persisten
2026-02-20 11:52:21 +01:00
AndyMik90 867e2e4e45 merge: resolve state-machines/index.ts conflict - keep both terminal and roadmap exports 2026-02-20 11:51:07 +01:00
Andy e9ca60fa02 Merge pull request #1818 from AndyMik90/auto-claude/227-fix-mark-as-done-on-task-modal
auto-claude: 227-fix-mark-as-done-on-task-modal
2026-02-20 11:50:30 +01:00
Andy 7539a2d4e6 Merge pull request #1817 from AndyMik90/auto-claude/226-add-archive-button-to-done-tasks
auto-claude: 226-add-archive-button-to-done-tasks
2026-02-20 11:50:21 +01:00
Andy 2d7e3cbed1 Merge pull request #1816 from AndyMik90/auto-claude/223-remove-deprecated-taskstatemachine-class
auto-claude: 223-remove-deprecated-taskstatemachine-class
2026-02-20 11:50:15 +01:00
Andy 0474238bf5 Merge pull request #1815 from AndyMik90/auto-claude/222-refactor-roadmap-tasks-with-xstate
auto-claude: 222-refactor-roadmap-tasks-with-xstate
2026-02-20 11:50:09 +01:00
Andy 3f03cef7ee Merge pull request #1814 from AndyMik90/auto-claude/220-add-manual-competitor-functionality-in-roadmap
auto-claude: 220-add-manual-competitor-functionality-in-roadmap
2026-02-20 11:49:52 +01:00
AndyMik90 a0807c20a0 readme fix 2026-02-20 11:36:17 +01:00
AndyMik90 03a0b21f38 fix: resolve Windows test timeout and CodeQL high-severity alerts
- Add missing vi.mock for cli-tool-manager and sentry in runner-env test
  (unmocked getToolInfo caused filesystem lookups timing out on Windows CI)
- Loop HTML tag stripping to handle nested tag fragments (CodeQL #5077)
- Decode &amp; entity last to prevent double-unescaping (CodeQL #5076)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-20 11:34:50 +01:00
AndyMik90 72c0409c79 merge: resolve README.md conflict with main (beta version badges)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-20 11:27:34 +01:00
AndyMik90 3217719709 changelog 2.7.6 2026-02-20 11:25:30 +01:00
AndyMik90 e8c4740389 chore: bump version to 2.7.6 2026-02-20 11:19:55 +01:00
AndyMik90 4a75ea9f99 fix: handle unknown SDK message types (rate_limit_event) to prevent session crashes
The Claude CLI emits message types like rate_limit_event that the SDK's
message_parser doesn't recognize, causing MessageParseError to kill the
entire agent session stream. This adds two layers of defense:

1. Monkey-patch SDK's parse_message to convert unknown types into safe
   SystemMessage objects instead of raising
2. safe_receive_messages() wrapper around receive_response() that filters
   patched messages and catches stream-level errors gracefully

Applied to all agent consumers: session, qa_reviewer, qa_fixer, and
agent_runner. Also bumps minimum SDK to >=0.1.39.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-20 11:16:59 +01:00
AndyMik90 19f1cdedbb hotfix/github-feat-PR 2026-02-19 06:10:27 +01:00
AndyMik90 732fc1cd3f fix: PR review error visibility and gh CLI resolution in bundled apps
- Surface review errors in UI instead of silently falling back to "Not Reviewed"
- Thread reviewError from store through hook → GitHubPRs → PRDetail → ReviewStatusTree
- Fix error payload to include prNumber so store updates correct PR key
- Use CLI tool manager (getToolInfo) instead of `which gh` in validateGitHubModule
  so bundled Electron apps can find gh via Homebrew/augmented PATH
- Pass GITHUB_CLI_PATH in subprocess env via getRunnerEnv
- Use resolved gh path for `gh auth status` check
- Add Sentry breadcrumbs and error capture for gh CLI resolution diagnostics
- Add i18n keys for retryReview (en + fr)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 21:23:42 +01:00
AndyMik90 4a6df82792 chore: bump version to 2.7.6-beta.6 2026-02-18 15:57:44 +01:00
AndyMik90 4bb3d658d0 fix: address PR #1829 review findings in ChatHistorySidebar and paths
- Fix i18n: replace non-existent t('actions.cancel') with t('buttons.cancel')
  in all three AlertDialog cancel buttons (single delete, bulk delete, bulk archive)
- Fix WCAG: add aria-hidden and tabIndex={-1} to decorative inner Checkbox
  to eliminate nested checkbox role violation in selection mode
- Fix: move setBulkDeleteOpen/setBulkArchiveOpen to finally blocks so dialogs
  always close regardless of success or failure in bulk handlers
- Fix: remove unsanitized sessionId from validateSessionId error message
  to prevent leaking raw input in error output (paths.ts)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 15:07:03 +01:00
AndyMik90 f47091588a fix: resolve all PR #1829 review findings in ChatHistorySidebar
- Finding 1 (MEDIUM): Add AlertDialog confirmation before bulk archive
  executes, using existing archiveConfirmDescription i18n key
- Finding 2 (MEDIUM): Replace hardcoded Today/Yesterday/X days ago with
  i18n keys insights.today, insights.yesterday, insights.daysAgo
- Finding 3 (MEDIUM): Always set tabIndex={0} so items remain keyboard
  accessible when isSelectionMode is true (role=checkbox requires it)
- Finding 4 (LOW): Archive/unarchive callbacks already propagate errors;
  no silent swallowing present in current code
- Finding 5 (LOW): Replace hardcoded message/messages ternary with
  insights.messageCount pluralization via i18n count interpolation
- Finding 6 (LOW): Single-delete dialog now uses dedicated
  insights.deleteTitle and insights.deleteDescription keys instead of
  reusing bulk delete keys with count: 1

Add i18n keys to both en/common.json and fr/common.json:
  archiveConfirmTitle, archiveConfirmButton, deleteTitle,
  deleteDescription, today, yesterday, daysAgo, messageCount,
  messageCount_other

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 15:05:54 +01:00
AndyMik90 7ee20e0e44 fix: resolve PR review findings for session storage error handling
- Move getSessionPath() inside try/catch in loadSessionById and deleteSession
  so validateSessionId exceptions are caught (FU2-001, FU2-004)
- Add try/catch with logging to saveSession to prevent unhandled I/O throws
  (FU2-005)
- Use session.updatedAt instead of new Date() in updateSessionModelConfig
  cache update to keep timestamps consistent (FU2-002)
- Remove swallowing .catch() on archive/unarchive callbacks so errors
  propagate to parent handlers in Insights.tsx (FU2-006)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 15:05:54 +01:00
AndyMik90 fd9032ab99 fix: resolve archive filter loss and session cache bugs in insights
- Add showArchived field to insights Zustand store so all callers
  (including event listeners) can access it without parameter threading
- loadInsightsSessions now falls back to store.showArchived when no
  explicit parameter is passed, fixing newSession, renameSession,
  updateModelConfig, and the onInsightsSessionUpdated listener
- Add in-memory cache update to SessionManager.renameSession matching
  the pattern used by updateSessionModelConfig
- Add input validation for bulk delete/archive IPC handlers

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 15:05:54 +01:00
AndyMik90 7e869650d6 fix: pass archive filter through loadInsightsSession to prevent overwrite
- Add includeArchived parameter to loadInsightsSession and propagate to
  loadInsightsSessions, deleteSession, and clearSession
- Update all callers in Insights.tsx to pass showArchived through
- Remove projectId from showArchived effect deps to prevent duplicate
  loads on project switch (mount effect already handles it)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 15:05:54 +01:00
AndyMik90 42372141ec fix: address PR review findings for bulk delete/archive chat history
- Return success:false from IPC handlers when bulk operations have failures
- Propagate failedIds through store functions for proper error reporting
- Add session ID validation in paths.ts to prevent path traversal
- Prune selectedIds when sessions list changes to avoid stale selections
- Fix isFirstRun race condition when projectId changes in Insights
- Convert archivedAt to Date in loadSessionById for type consistency
- Fix accessibility: conditional tabIndex based on selection mode

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 15:05:54 +01:00
AndyMik90 d76368e1b9 fix: address all new PR review findings for bulk delete/archive functionality
Comprehensive fixes addressing 4 critical and accessibility issues:

**Critical Bug Fixes:**
1. Fixed UI state mismatch when active session is archived/deleted
   - Added loadInsightsSession() call after bulk operations
   - Ensures frontend stays in sync when backend auto-switches sessions

2. Fixed race condition causing flicker on projectId change
   - Added prevProjectId ref to reset skip flag per-projectId
   - Prevents duplicate loadInsightsSessions calls when showArchived is true

3. Added comprehensive error handling to all bulk handlers
   - Wrapped all async operations in try/catch blocks
   - Added detailed error logging with session IDs and context
   - Prevents unhandled promise rejections from IPC failures

**Accessibility Improvements:**
4. Fixed selection mode accessibility in SessionItem
   - Removed redundant checkbox onCheckedChange to prevent double-toggle
   - Made parent row fully interactive with role="checkbox" in selection mode
   - Added aria-checked attribute for screen reader support
   - Wired row onClick and keyboard handlers to toggle selection
   - Users can now activate selection via row click/keyboard or nested checkbox

All changes maintain backward compatibility and improve robustness.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 15:05:54 +01:00
AndyMik90 02b40fa342 fix: address all PR review findings for bulk delete/archive functionality
Comprehensive code quality improvements addressing all review comments:

**Critical Fixes:**
- Fixed double-toggle bug where checkbox called onToggleSelect twice
- Added accessibility attributes (role, tabIndex, onKeyDown) to interactive div

**Error Handling:**
- Removed error re-throws in async event handlers to prevent unhandled rejections
- Added error logging to empty catch blocks in session-storage.ts
- Added error handling with .catch() for dropdown menu promise rejections
- Added logging for partial failures in bulk operations

**Code Quality:**
- Replaced non-null assertion (!) with explicit null check in session-manager.ts
- Removed redundant async/await wrappers in archive/unarchive handlers
- Removed duplicate loadInsightsSession calls from store functions
- Added skip-first-run guard to prevent double load on component mount
- Added clarifying comment for showArchived useEffect dependency

**Performance:**
- Eliminated redundant IPC calls by removing duplicate session reloads
- Fixed flicker issue caused by double reload with different filters

All changes maintain backward compatibility and improve user experience.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 15:05:54 +01:00
AndyMik90 9f3ac54844 fix: properly await async bulk operations in ChatHistorySidebar
Fixed fire-and-forget async operations that were clearing UI state
before operations completed. Changes:

- Updated prop types to return Promise<void> for async callbacks
- Made handleBulkDelete and handleBulkArchive async functions
- Added await for all async callback invocations
- Added try/catch error handling with console logging
- Updated SessionItem prop types for onArchive/onUnarchive
- Made single archive/unarchive arrow functions async

This ensures UI state is only cleared after operations complete
successfully and prevents unhandled promise rejections.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 15:05:54 +01:00
AndyMik90 e547e96e26 fix: pass showArchived flag when reloading sessions after bulk operations (qa-requested)
Make handleArchiveSession, handleUnarchiveSession, handleDeleteSessions,
and handleArchiveSessions async, await store calls, then reload sessions
with showArchived flag to preserve archived session visibility.

QA Fix Session: 2
2026-02-18 15:05:54 +01:00
AndyMik90 2d9911cd21 auto-claude: subtask-5-3 - Update Insights.tsx to wire new ChatHistorySidebar props
Add showArchived state, import bulk store helpers (deleteSessions, archiveSession,
archiveSessions, unarchiveSession), create handler functions, add useEffect to
reload sessions when showArchived changes, and pass all new props to ChatHistorySidebar.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 15:05:54 +01:00
AndyMik90 0f952a7b96 auto-claude: subtask-5-2 - Add selection mode, bulk actions, and archive support to ChatHistorySidebar
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 15:05:54 +01:00
AndyMik90 1e44a909c1 auto-claude: subtask-5-1 - Add i18n translation keys for chat history bulk delete and archive
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 15:05:54 +01:00
AndyMik90 0bf75d1b67 auto-claude: subtask-4-1 - Add bulk delete/archive helper functions to insights-store
Add deleteSessions, archiveSession, archiveSessions, unarchiveSession helpers
and update loadInsightsSessions to accept optional includeArchived parameter.
Also update ElectronAPI types and browser mocks for new methods.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 15:05:54 +01:00
AndyMik90 4198bde687 auto-claude: subtask-3-3 - Extend preload InsightsAPI with bulk delete/archive methods
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 15:05:54 +01:00
AndyMik90 60b8a77d69 auto-claude: subtask-3-2 - Register new IPC handlers in insights-handlers.ts
Add handlers for bulk delete, archive, bulk archive, and unarchive
sessions. Update list sessions handler to accept includeArchived param.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 15:05:54 +01:00
AndyMik90 ffad4fc53d auto-claude: subtask-3-1 - Add delegation methods to InsightsService
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 15:05:54 +01:00
AndyMik90 c3a927ae54 auto-claude: subtask-2-2 - Add archive/unarchive/bulk methods to SessionManager
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 15:05:54 +01:00
AndyMik90 9626ba42a2 auto-claude: subtask-2-1 - Add archive/unarchive/bulk methods to SessionStorage
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 15:05:54 +01:00
AndyMik90 1c2918fe0b auto-claude: subtask-1-2 - Add new IPC channel constants for bulk delete and archive
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 15:05:54 +01:00
AndyMik90 2f43b2af24 auto-claude: subtask-1-1 - Add archivedAt optional field to InsightsSession and InsightsSessionSummary
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 15:05:54 +01:00
Andy 40364a016d Merge branch 'develop' into auto-claude/222-refactor-roadmap-tasks-with-xstate 2026-02-18 14:49:16 +01:00
Andy 819f98d9fa fix: handle empty/greenfield projects in spec creation (#1426) (#1841)
* fix: handle empty/greenfield projects in spec creation and prevent stuck planning state (#1426)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: address PR review findings - planning_phase_ended bug, type hints, dedup (#1426)

- Convert planning_phase_ended to instance attribute self._planning_phase_ended
  so _run_phases() can mark it True after each end_phase() call, preventing
  double-end on exception propagation
- Add Path type annotation to _is_greenfield_project(spec_dir)
- Extract duplicated greenfield detection into _check_and_log_greenfield() helper
- Add TaskLogger and types.ModuleType type hints to _run_phases() signature
- Simplify redundant SystemExit handler with explanatory comment

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: prevent greenfield false positive on missing/corrupt project index

When get_project_index_stats() returns {} (file missing, JSON parse
error, or unrecognized format), _is_greenfield_project() now returns
False instead of incorrectly classifying the project as greenfield.
Also removes unused TYPE_CHECKING import and empty conditional block.

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 14:49:05 +01:00
Andy 28a620079f fix: clear terminalEventSeen on task restart to prevent stuck-after-planning (#1828) (#1840)
* fix: clear terminalEventSeen on task restart to prevent stuck-after-planning (#1828)

The terminalEventSeen Set in TaskStateManager was never cleared when a task
was restarted. When spec_runner.py emits PLANNING_COMPLETE, the taskId is
added to terminalEventSeen. If the subsequent coding process (run.py) fails,
handleProcessExited() returns early because terminalEventSeen.has(taskId)
is true, silently swallowing the PROCESS_EXITED event. The XState actor
never transitions, leaving the task permanently stuck in 'coding' state.

Additionally, lastSequenceByTask from the old process would cause events
from a new process (starting at sequence 0) to be dropped as duplicates.

Fix: Add prepareForRestart(taskId) method that clears both terminalEventSeen
and lastSequenceByTask without stopping the XState actor. Call it in all 4
locations where a new agent process is started:
- TASK_START handler
- TASK_STOP handler (so subsequent restart works)
- TASK_UPDATE_STATUS auto-start path
- TASK_RECOVER_STUCK auto-restart path

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: add prepareForRestart to TASK_REVIEW rejection path

Add missing prepareForRestart(taskId) call before startQAProcess() in the
TASK_REVIEW rejection handler. This is the 5th location where a new agent
process is started for an existing task, but was missed in the original fix.
Without this, if the QA fixer process crashes after a review rejection,
terminalEventSeen would cause handleProcessExited() to swallow the exit
event, leaving the task permanently stuck.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 14:42:01 +01:00
Andy fb3a3fbda7 fix: watch worktree path for implementation_plan.json changes (#1805) (#1842)
* fix: watch worktree path for implementation_plan.json changes (#1805)

The FileWatcher was always watching the main project's spec directory for
implementation_plan.json changes. When tasks run in a worktree, the backend
writes the plan file to the worktree directory instead, so the watcher never
detected changes and subtask progress was never sent to the UI.

Changes:
- Add getSpecDirForWatcher() helper that checks worktree path first
- Update all 3 file watcher setup locations (TASK_START, TASK_UPDATE_STATUS
  auto-start, TASK_RECOVER_STUCK auto-restart) to use worktree-aware paths
- Add re-watch logic in execution-progress handler: when a worktree appears
  after task start, automatically switch the watcher to the worktree path
- Add worktree fallback in exit handler for reading final plan state
- Add getWatchedSpecDir() method to FileWatcher for path comparison

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: address PR review findings - naming consistency, async error handling (#1805)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: address PR review findings for file watcher race condition and error handling

- Add pendingWatches guard in FileWatcher.watch() to prevent overlapping async
  calls from creating duplicate watchers (CodeRabbit critical finding)
- Add .catch() to all three fire-and-forget fileWatcher.watch() calls in
  execution-handlers.ts to prevent unhandled promise rejections
- Remove shadowed specsBaseDir re-declaration in autoRestart block, reusing
  the outer variable from the same TASK_RECOVER_STUCK handler scope

* fix: address PR review findings for file-watcher race conditions and variable shadowing

- Change pendingWatches from Set<string> to Map<string, string> (taskId->specDir)
  so re-watch calls with a different specDir are allowed through instead of silently dropped
- Add cancelledWatches Set to coordinate unwatch() with in-flight watch() calls,
  preventing watcher leaks when unwatch() runs during watch()'s await points
- Add .catch() handler to fileWatcher.unwatch() call in agent-events-handlers exit handler,
  consistent with the .catch() pattern used for all watch() calls
- Remove shadowed const mainSpecDir re-declaration inside autoRestart block in
  execution-handlers.ts, using the outer variable from the enclosing try block instead

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: resolve FileWatcher race conditions and unhandled promise rejections

- Add supersession check in watch() after awaiting existing watcher close
  to prevent a later concurrent call from having its watcher overwritten
- Return early in unwatch() when a watch() is in-flight to prevent
  double-closing the same FSWatcher
- Cancel in-flight watch() calls in unwatchAll() by marking their taskIds
  in cancelledWatches before closing existing watchers
- Add .catch() to fileWatcher.unwatch() calls in TASK_STOP and
  TASK_RECOVER_STUCK handlers to surface errors instead of silently dropping them

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: resolve concurrent watch() race conditions in FileWatcher

- Make finally block conditional so superseding watch() calls are not
  wiped out by the superseded call cleaning up pendingWatches
- Delete watcher from map before awaiting close() to prevent concurrent
  calls from double-closing the same FSWatcher reference
- Make cancelledWatches cleanup conditional on the call still owning the
  pendingWatches entry, preventing premature flag removal for concurrent calls
- Fix misleading comment about mainSpecDir declaration scope

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: resolve PR review findings for FileWatcher dead code, missing guards, and test coverage

- Remove dead code in finally block: after delete(), has() is always
  false so the inner if was always true; simplify to a single delete +
  cancelledWatches.delete call (Finding 1)
- Add implementation_plan.json existence check in getSpecDirForWatcher
  before preferring the worktree path, so the watcher is started in
  the correct directory even when the plan file hasn't been written yet
  (Finding 2)
- Clear pendingWatches in unwatchAll() so in-flight watch() calls can
  no longer register new watchers after a full teardown (Finding 3)
- Also clear cancelledWatches in unwatchAll() since in-flight calls bail
  via the supersession check and won't clean up the flags themselves
- Add comprehensive concurrency tests for FileWatcher covering
  deduplication, supersession, cancellation, and unwatchAll behaviour
  (Finding 4)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: use path.join() in file-watcher tests for cross-platform compatibility

Replace hardcoded forward-slash strings in getWatchedSpecDir assertions with
path.join() so expected values match on Windows (backslash) and Unix (forward
slash) alike.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: remove duplicate specDir declaration after rebase

The rebase on origin/develop introduced a duplicate `const specDir` declaration
that caused TypeScript and Biome CI failures. The variable was already declared
earlier in the same scope with the same value.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 14:33:18 +01:00
Andy 76d1d3b032 fix: resolve Claude CLI not found on Windows - PATH, prompt size, cwd (#1661) (#1843)
* fix: resolve Claude CLI not found on Windows - PATH merge, prompt size cap, and cwd (#1661)

Three root causes addressed:

1. PATH overwrite: pythonEnv.PATH was overwriting the augmented PATH (with npm
   globals) in spawn env. Now merges PATH entries instead, prepending
   python-specific paths (pywin32_system32) while preserving all augmented entries.

2. System prompt size: On Windows, SDK passes system_prompt as --system-prompt
   CLI arg. Large CLAUDE.md files exceed CreateProcessW's 32,768 char limit,
   causing misleading "Claude Code not found" error. Now caps CLAUDE.md content
   on Windows to stay under the limit.

3. Cross-drive cwd: Agent processes were spawned with autoBuildSource as cwd.
   On Windows with cross-drive setups, this caused file access issues. Now uses
   projectPath as cwd since all script paths are absolute.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: address PR review findings - constants, logging, CI fixes (#1661)

- Extract magic number 24000 into WINDOWS_MAX_SYSTEM_PROMPT_CHARS constant
  (set to 20000 for more conservative ~12KB CLI headroom)
- Extract truncation suffix into WINDOWS_TRUNCATION_MESSAGE constant
- Fix double-print when truncation occurs: only print "included in system
  prompt" when CLAUDE.md was NOT truncated (was_truncated flag)
- Fix CI test failures: update subprocess-spawn tests to expect projectPath
  as cwd instead of autoBuildSource (matches the #1661 CWD change)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: normalize PATH key casing and fix truncation budget on Windows

- Normalize env objects to a single uppercase 'PATH' key before merging
  to prevent duplicate PATH keys on Windows where process.env has 'Path'
  and getAugmentedEnv() writes 'PATH'. Without this, Object.keys().find()
  returns 'Path' first (insertion order), discarding augmented entries,
  and the final spread produces both 'Path' and 'PATH' keys.
  Follows the same pattern used in python-env-manager.ts. (#1661)

- Subtract WINDOWS_TRUNCATION_MESSAGE length from the truncation budget
  so the final system prompt stays within WINDOWS_MAX_SYSTEM_PROMPT_CHARS.

Addresses PR #1843 review findings NEW-001, NEW-002, NEW-003.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: address PR review findings for Windows PATH key casing and truncation budget

- Finding 1 (MEDIUM): Prefer 'PATH' key directly when present in env to avoid
  insertion-order bug where Object.keys().find() returned 'Path' first on Windows
- Finding 2 (MEDIUM): Normalization block (delete stale cased key, write 'PATH')
  already in place from previous commit; Finding 1 fix ensures envPathKey resolves
  correctly so normalization fires only when truly needed
- Finding 3 (LOW): Subtract header template overhead from max_claude_md_chars to
  prevent ~44-char overshoot in Windows command-line truncation budget (#1661)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: remove stale 'Path' key after PATH normalization on Windows

When getAugmentedEnv() spreads process.env on Windows, the resulting object
contains both 'Path' (from process.env spread) and 'PATH' (explicitly written
by getAugmentedEnv). The prior normalization block only removed non-'PATH' keys
when 'PATH' was absent, leaving the stale 'Path' key when both coexisted.

Add a cleanup loop to delete all case-variant PATH keys that differ from
'PATH' after the main normalization, ensuring the child process inherits a
single canonical 'PATH' entry with the fully-augmented value. (#1661)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* refactor: extract shared PATH normalization utilities and add unit tests

- Extract normalizeEnvPathKey() and mergePythonEnvPath() into env-utils.ts
  as shared, exported helpers to eliminate duplicated PATH key case-normalization
  logic across agent-process.ts and python-env-manager.ts (Finding 3)
- Add PATH normalization call in agent-queue.ts spawnIdeationProcess and
  spawnRoadmapProcess to fix the same Windows PATH duplicate-key issue that
  was fixed in agent-process.ts (#1661) (Finding 1)
- Add comprehensive unit tests for normalizeEnvPathKey() and mergePythonEnvPath()
  covering Windows-style 'Path' key renaming, duplicate key removal, PATH
  deduplication across merge, and Unix separator support (Finding 2)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 14:22:23 +01:00
Andy 3cb05781fa fix: handle planning phase crash and resume recovery (#1562) (#1844)
* fix: handle planning phase crash and resume recovery (#1562)

When spec creation crashes, the task gets stuck in "planning" state
forever because the backend never emits PLANNING_FAILED to the frontend
XState machine. Clicking Resume then also crashes because the resume
logic transitions to "coding" state, but there are no subtasks yet.

Root causes and fixes:

1. Backend orchestrator (orchestrator.py):
   - Wrap run() in try/except to emit PLANNING_FAILED on unhandled exceptions
   - Add _emit_planning_failed() calls at every early return path
   - Fix spec_dir tracking after rename_spec_dir_from_requirements()

2. XState machine (task-machine.ts):
   - Add PLANNING_STARTED transitions from error and human_review states
   - This allows tasks that crashed during planning to resume back to planning

3. Execution handlers (execution-handlers.ts):
   - Detect error state with 0 subtasks and send PLANNING_STARTED (not USER_RESUMED)
   - Check actual implementation_plan.json for subtasks instead of task.subtasks.length
   - Handles both with-actor and without-actor (app restart) code paths

Closes #1562

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: address PR review findings - reliable subtask check, spec_dir rename, empty except (#1562)

- Move planHasSubtasks calculation (reads implementation_plan.json) before
  XState handling so the crash-during-planning check uses the reliable
  file-based check instead of task.subtasks.length
- Change rename_spec_dir_from_requirements to return the new Path directly
  instead of a bool, eliminating brittle directory scanning in orchestrator
- Add descriptive comment to empty except clause to satisfy code scanning

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: update tests for rename_spec_dir_from_requirements return type change (#1562)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: address PR review findings for planning crash resume

- Update phase_executor.spec_dir and spec_validator after directory rename
  so subsequent phases don't use stale paths (critical bug flagged by
  sentry, coderabbitai, and Auto Claude review)
- Fix TASK_UPDATE_STATUS handler to use file-based plan check instead of
  unreliable task.subtasks.length (same #1562 bug fixed in TASK_START)
- Replace manual subtask counting with existing checkSubtasksCompletion helper
- Use safeReadFileSync instead of existsSync+readFileSync (TOCTOU fix)
- Add self.validator update to backward-compat _rename_spec_dir_from_requirements

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 14:14:09 +01:00
AndyMik90 4349963f39 fix: address PR #1815 review findings for roadmap XState refactor
- Remove redundant conditional in setGenerationStatus (NEW-001)
- Add comprehensive test coverage for catch-up logic (NEW-002)
- Pass persisted context to getOrCreateGenerationActor on reload (CMT-001)
- Add reverse-direction assertions for state name arrays (FNEW-003)
- Fix stale line reference in comment (NEW-003)
- Use precise no-op guard in updateFeatureLinkedSpec (NEW-004)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 10:23:06 +01:00
AndyMik90 6c69e71a76 fix: resolve 3 remaining PR #1815 issues
- Add vite/client types reference to fix import.meta.hot TS errors
- Add unit tests for mapGenerationStateToPhase/mapFeatureStateToStatus
  ensuring all machine states map correctly without silent fallthrough
- Restore persisted state in getOrCreateGenerationActor matching the
  feature actor pattern with resolveState()

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 09:49:49 +01:00
AndyMik90 7f7e845cd5 fix: resolve 3 remaining PR #1819 review issues
- Preserve 'exited' status in setClaudeMode(false) instead of overwriting to 'running'
- Add isResumingPhase guard to SWAP_RESUME_COMPLETE for consistency with other swap events
- Clean up stale migratedSessionFlags when resumeClaudeAsync finds no terminal

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 09:49:35 +01:00
AndyMik90 6f9a24176d fix: remove vacuous if/else guard in graphiti status test
Replace conditional assertions with direct assertions since
sys.modules patching deterministically makes available=True.
The else-branch was dead code with a trivially-passing assertion.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 09:48:29 +01:00
AndyMik90 7fb9b10bcd fix: address PR review findings for XState roadmap refactor
- Add catch-up logic for 'error' phase in setGenerationStatus so
  GENERATION_ERROR is not silently dropped when actor is in idle/complete
- Fix progress updates being dropped for empty string message by using
  !== undefined instead of truthy check on status.message
- Improve compile-time assertion comments explaining both-direction sync
  enforcement strategy (forward via type assertion, reverse via switch
  exhaustiveness in map functions)
- Replace unnecessary dynamic import of resetActors in test afterEach
  with static import
- Document that backward transitions are intentionally unsupported in
  the forward-only generation pipeline

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:38:18 +01:00
AndyMik90 faf6148f82 fix: use setClaudeMode instead of updateTerminal in onTerminalExit to prevent XState divergence
The onTerminalExit handler used store.updateTerminal() to reset isClaudeMode,
which is a plain Zustand setter that bypasses XState notification. Replace with
store.setClaudeMode() which properly checks XState state before sending events.

Since setTerminalStatus('exited') already sends SHELL_EXITED to XState (handling
the claude_active -> exited transition), the setClaudeMode(false) call here only
updates Zustand - its XState guard correctly skips sending CLAUDE_EXITED since
the machine is already in 'exited' state.

Fixes: NCR-R7-001 (HIGH) - Claude exit via updateTerminal bypasses XState machine

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:36:55 +01:00
AndyMik90 8e86bd60ae fix: address PR review findings for image pipeline
- Add defense-in-depth count and size validation in InsightsExecutor
  (NEW-005)
- Make image analysis unsupported warning more prominent with icon and
  background styling (REVIEW-001/CMT-001)
- Add inline notice on sent messages that images were not analyzed
  (CMT-001)
- Add i18n keys for image not-analyzed notice (en + fr)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:36:31 +01:00
AndyMik90 9e06b15d3d fix: address PR #1847 review findings
- Reuse SKIP_DIRS from context.constants instead of duplicating exclusion list
- Fix exception types in write error handlers (TypeError/ValueError, not JSONDecodeError)
- Add warning log when path validation bypassed due to exhausted retries
- Use existing safeReadFileSync helper for attempt_history reads

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:35:33 +01:00
AndyMik90 3bf5a1f0c3 fix: use write_json_atomic for implementation_plan.json in recovery
Replace raw json.dump with write_json_atomic when writing
implementation_plan.json in mark_subtask_stuck() to prevent file
corruption, consistent with 8+ other call sites in the codebase.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:34:26 +01:00
AndyMik90 04d141f6be fix: make test_get_graphiti_status_invalid_config_sets_reason environment-independent
Avoid hard-asserting status['available'] is True, which depends on
sys.modules patching behavior. Instead check the key exists and branch
on its value, consistent with neighboring tests in the same class.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:34:24 +01:00
AndyMik90 9334b71da8 fix: cancel fallback timer in all task restart paths
The fallback safety net timer was only cancelled in the TASK_START handler,
but not in the TASK_UPDATE_STATUS auto-start path or TASK_RECOVER_STUCK
auto-restart path. This meant a stale timer could incorrectly stop a
newly restarted task if it was restarted within the 500ms window via
drag-to-in-progress or recovery auto-restart.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:34:01 +01:00
AndyMik90 4cb0a14aa7 fix: add debug log for venv fallback success in worktree setup
Add missing debug log when venv symlink health check fails and the
recreate fallback succeeds, matching the Python backend's behavior
for consistent debug output.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:33:51 +01:00
AndyMik90 04618ccb08 fix: move debug log after delete to fix off-by-one count in cleanup timer
The cleanup timer debug log was computing pendingDelete.size - 1 before
the actual delete call, logging an incorrect remaining count. Moved both
delete calls before the debug log so it reports the accurate size.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:33:42 +01:00
AndyMik90 db4cd7d2da fix: extract stuck-subtask loader, use actual_output for stuck notes
- Extract duplicated stuck-subtask loading into _load_stuck_subtask_ids()
- Write stuck reason to actual_output instead of notes field for
  consistency with the QA reviewer's expectations
- Clarify progress message to mention terminal states (completed/failed/stuck)
- Update test assertions to match actual_output field

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:33:06 +01:00
AndyMik90 1f60699f38 fix: resolve QA validation deadlock when subtasks are stuck or failed
When a coding agent marks a subtask as "stuck", QA validation would never
start because is_build_complete() requires ALL subtasks to have status
"completed". This creates a deadlock: coder exits (no more subtasks to
work on), but QA never triggers.

Changes:
- Add is_build_ready_for_qa() that considers builds ready when all
  subtasks reach a terminal state (completed, failed, or stuck)
- Update mark_subtask_stuck() to also set status="failed" in
  implementation_plan.json, keeping plan file in sync with reality
- Reorder QA loop to check human feedback before build completeness,
  so QA_FIX_REQUEST.md bypasses the build gate as intended
- Replace is_build_complete() with is_build_ready_for_qa() in
  should_run_qa() and CLI qa commands
- Add 20 new tests covering is_build_ready_for_qa() edge cases and
  mark_subtask_stuck() plan update behavior

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:33:06 +01:00
AndyMik90 c2b287c02c refactor: extract scoring logic, use indexed lookup in auto-correct
- Extract _score_and_select() from duplicated candidate scoring blocks
- Use _find_correct_path_indexed() in _auto_correct_subtask_files()
  with a shared file index built once for all missing files
- Use find_subtask_in_plan() helper instead of inline nested loop
- Add more dirs to _EXCLUDE_DIRS (.idea, .vscode, vendor, target, out)
- Narrow exception handlers from (OSError, JSONDecodeError) to OSError
  for write_json_atomic (JSON errors can't occur on write)
- Fix type annotation for missing_entries list

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:59 +01:00
AndyMik90 4a8c94538c feat: implement fuzzy file path matching and indexing for self-healing in coder pipeline
- Add functions for building a file index, finding correct paths using fuzzy matching, and auto-correcting subtask file paths.
- Introduce directory exclusion logic to optimize file searching.
- Enhance validation of file paths in implementation plans to support better error recovery.
- Add comprehensive tests for the new functionalities, covering various matching scenarios and edge cases.

This update improves the robustness of the coder pipeline by enabling it to automatically correct file paths based on existing project structure, thus enhancing overall stability and user experience.
2026-02-17 15:32:58 +01:00
AndyMik90 36b3b29d9e test: add coverage for missing graph backend scenario
Add test_get_graphiti_status_no_graph_backend to verify error handling when
graphiti_core imports successfully but neither real_ladybug nor kuzu are
available. This addresses CodeRabbit's recommendation to test the error path
in config.py lines 645-650.

Addresses CodeRabbit review comment on PR #1834.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:56 +01:00
AndyMik90 e61f4370a8 fix: address review findings for PR #1834
- Add nested try-except in config.py for clearer error messages when graph DB backend is missing
- Mock imports in test_config.py to make test environment-independent
- Ensure test passes regardless of whether graphiti_core/real_ladybug/kuzu are installed

Resolves CodeRabbit and Gemini review comments on PR #1834.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:56 +01:00
AndyMik90 aaa3b7f588 fix: remove stale FalkorDB references from migration cleanup
- Remove FalkorDB docker service reference from project_index.json (docker-compose.yml no longer exists)
- Correct line number reference in test_config.py comment (line 644 not 641)

Code review findings - no functional changes, just metadata cleanup.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:56 +01:00
AndyMik90 b7739a4794 fix(memory): complete FalkorDB → LadybugDB migration in memory system
## Problem
The memory system was still checking for FalkorDB imports in `config.py`,
causing it to always report as unavailable and fall back to file-based
storage, despite LadybugDB being the configured and installed database.

Error in logs:
```
Graphiti packages not installed: falkordb is required for FalkorDri...
```

## Root Cause
In `get_graphiti_status()` at line 638, the code tried to import:
```python
from graphiti_core.driver.falkordb_driver import FalkorDriver
```
This import failed because FalkorDB was removed when migrating to LadybugDB.

## Changes Made

### Priority 1 — Critical Bug Fix
**File**: `apps/backend/integrations/graphiti/config.py` (lines 634-646)
- Replaced FalkorDB import check with LadybugDB/kuzu import check
- Now tries `real_ladybug` first (Python 3.12+), falls back to `kuzu`
- Removed unreachable pragma: no cover comment (line now executes)

### Priority 2 — Test Infrastructure Updates
1. **`conftest.py`** (lines 84-103)
   - Renamed fixture: `mock_falkor_driver` → `mock_kuzu_driver`
   - Updated docstring and patch path to reference KuzuDriver

2. **`test_config.py`** (lines 1056-1070, 1092-1094)
   - Updated test to reflect new behavior: `available=True` when packages
     installed, even with embedder validation errors (embedder is optional)
   - Updated comment from "falkordb" to "LadybugDB/kuzu"

3. **`test_memory.py`** (lines 267, 278)
   - Updated variable name: `mock_falkordb_driver` → `mock_kuzu_driver`
   - Updated sys.modules patch path to use kuzu_driver instead of falkordb_driver

### Priority 3 — Documentation Updates
4. **`test_memory_facade.py`** (line 163)
   - Updated comment: "remote FalkorDB" → "remote database"

5. **`spec_runner.py`** (line 139)
   - Updated example: "FalkorDB" → "LadybugDB"

## Testing
All 670 graphiti tests pass:
```
apps/backend/.venv/bin/pytest apps/backend/integrations/graphiti/tests/ -v
========== 670 passed, 6 skipped, 112 deselected, 4 warnings in 2.10s ==========
```

## Impact
- Memory system now correctly detects LadybugDB as available
- No more false negatives causing fallback to file-based storage
- All existing functionality preserved
- No breaking changes

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:56 +01:00
AndyMik90 92a3c821ed fix: address all auto-claude review findings for PR #1833
Fixed all 3 findings from the latest auto-claude review:

1. [NCR-NEW-001] MEDIUM: Fallback safety net timeout race condition
   - Store setTimeout timer reference in a Map keyed by taskId
   - Export cancelFallbackTimer() function to clear pending timers
   - Call cancelFallbackTimer() at start of TASK_START handler
   - Prevents stale timer from incorrectly stopping newly restarted tasks
   - Clean up timer reference after it fires

2. [CMT-NEW-001] LOW: Duplicate hasPlan detection logic
   - Replace inline hasPlan logic in execution-handlers.ts TASK_STOP
   - Use shared hasPlanWithSubtasks() utility from plan-file-utils.ts
   - Eliminates code duplication and ensures consistent behavior

3. [CMT-001] LOW: Misleading async keyword
   - Remove async from setTimeout callback in agent-events-handlers.ts
   - No await expressions exist in the callback
   - All operations (getCurrentState, hasPlanWithSubtasks) are synchronous

All changes maintain backward compatibility and fix the race condition
where restarting a task within 500ms could be incorrectly stopped by
the fallback timer from the previous process exit.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:51 +01:00
AndyMik90 3628fba7f3 refactor: address all PR review findings for code quality
- Extract hasPlan logic into shared hasPlanWithSubtasks() utility in plan-file-utils.ts
  to eliminate duplication and centralize plan validation logic
- Make setTimeout callback async to avoid blocking readFileSync in event loop
- Replace hardcoded terminal status check with cleaner .includes() pattern
- Add status gate for final phase updates to prevent UI flicker when failed
  phase arrives after task has transitioned to human_review
- Import and use hasPlanWithSubtasks in agent-events-handlers.ts

All review comments addressed:
- Gemini: Critical/Medium - forceTransition method, magic number (already fixed in previous commit)
- Gemini: Medium - hardcoded status list (now uses .includes)
- CodeRabbit: Trivial - extract XSTATE_ACTIVE_STATES (already fixed in previous commit)
- CodeRabbit: Minor - derive hasPlan from file check (now uses shared utility)
- CodeRabbit: Minor - prevent UI flicker from final phase updates (now gates on status)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:51 +01:00
AndyMik90 b098d0d703 fix: address follow-up review findings - dynamic hasPlan and shared constants
Resolves NEW-001 and CMT-001 from the follow-up review:
- Extract XSTATE_ACTIVE_STATES to shared constant in task-state-utils.ts
- Export XSTATE_ACTIVE_STATES from state-machines index
- Replace hardcoded hasPlan: true with dynamic plan file check
- Pattern matches TASK_STOP handler (execution-handlers.ts lines 299-310)
- Tasks stuck in 'planning' state now correctly route to backlog, not human_review
- Improved logging shows hasPlan value for debugging

This ensures the fallback safety net routes tasks to the correct Kanban column
based on whether a plan file exists with subtasks.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:51 +01:00
AndyMik90 4c00536dc5 fix: address all review findings for PR #1833
- Add named constant STUCK_TASK_FALLBACK_TIMEOUT_MS for magic number
- Use XState getCurrentState() instead of cached task status to avoid stale cache issues
- Check XState active states directly (planning, coding, qa_review, qa_fixing)
- Improve logging to show actual XState state name
- Add inline comments explaining the stale cache avoidance strategy

This resolves all 3 blocking issues from the Auto Claude review:
1. CRITICAL: forceTransition() method - fixed by using handleUiEvent()
2. MEDIUM: Stale closure - fixed by checking XState directly
3. MEDIUM: Magic number - fixed by using named constant

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:51 +01:00
AndyMik90 cb8ed52eca fix: correct fallback timeout to use existing TaskStateManager API
The 500ms fallback safety net was calling `taskStateManager.forceTransition()`
which doesn't exist, causing TypeScript compilation errors.

Fixed to:
- Use `handleUiEvent()` with `USER_STOPPED` event (proper XState transition)
- Look up both task and project fresh (avoid stale closure references)
- Add null check for `checkProject` before proceeding

This ensures the fallback actually works when XState fails to transition
tasks out of in_progress after process exit.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:51 +01:00
AndyMik90 4286152f42 fix: resolve Kanban board stuck task state synchronization
When an agent process exits with incomplete/stuck subtasks, the task gets
stuck in the Kanban UI — it spins forever, can't be stopped, and can't be
dragged back to planning.

This fix addresses 5 specific state synchronization gaps between the backend
process lifecycle and the frontend XState state machine:

1. Reset execution progress on terminal state transitions (task-store.ts)
   - When tasks reach terminal states (human_review, error, done, pr_created),
     execution progress is now reset to idle
   - Prevents stuck tasks from showing stale progress indicators in UI

2. Propagate final phase updates even after XState settles (agent-events-handlers.ts)
   - Final 'complete' or 'failed' phase updates are now sent to renderer
   - Previously these were silently dropped, causing UI to never show completion

3. Add fallback exit handler to force state transition (agent-events-handlers.ts)
   - If task remains in_progress 500ms after process exit, force to human_review
   - Safety net for when XState fails to properly handle PROCESS_EXITED event

4. Disable dragging for in_progress tasks (SortableTaskCard.tsx)
   - Prevents users from dragging tasks that are currently running or stuck
   - Adds disabled flag to useSortable hook when status is 'in_progress'

5. Allow stop button for stuck tasks (TaskCard.tsx)
   - Users can now force-stop stuck tasks using the stop button
   - Removed the isStuck check that prevented stopping stuck tasks

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:51 +01:00
AndyMik90 95f32f914e fix: address PR #1832 review findings for worktree venv improvements
- Initialize performed=False as safer default matching TypeScript impl
- Fix _popen_with_cleanup docstring to accurately describe timeout behavior
- Replace lstatSync with isSymlinkOrJunction for consistency
- Add debug log when venv fallback to recreate occurs
- Use existing venvPath variable instead of reconstructing path
- Remove broken symlinks before returning false to allow fresh creation

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:50 +01:00
AndyMik90 84184fafb5 fix: address all 4 findings from auto-claude PR review
Fixes all issues from 2026-02-16 auto-claude review:

- [HIGH] NEW-001: Fix KeyError when venv symlink falls back to recreate
  strategy by ensuring results dict has the 'recreate' key before appending
- [MEDIUM] NEW-002: Fix isSymlinkOrJunction to detect Windows junctions by
  using readlinkSync instead of lstatSync().isSymbolicLink()
- [LOW] NEW-003: Add finally block to _popen_with_cleanup to prevent
  resource leaks by ensuring pipes are closed and process is reaped
- [LOW] CMT-002: Remove redundant symlink_path variable and reuse venv_path

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:50 +01:00
AndyMik90 1d4b749d55 fix: address all PR review findings for venv health check and fallback logic
Backend fixes:
- Detect broken symlinks in _apply_recreate_strategy using is_symlink()
- Add OSError catch in venv creation block for missing python_exec
- Update strategy_name to 'recreate' when health check triggers fallback
- Log marker write failures via debug_warning instead of silent pass
- Update DependencyStrategy docstring to reflect symlink-first approach

Frontend fixes:
- Decouple health check from 'performed' flag - run on any existing venv
- Add isSymlinkOrJunction() helper for broken symlink detection
- Detect broken symlinks in applyRecreateStrategy before existsSync check
- Log marker write failures instead of silent catch

All blocking and medium-severity review findings addressed:
- [NCR-001/CMT-001] Frontend health check now runs on re-runs
- [NCR-003] Backend recreate detects broken symlinks
- [NCR-005] Frontend recreate detects broken symlinks
- [NEW-002] Strategy name correctly updated on fallback
- [NCR-004] OSError handling added to venv creation
- [NEW-003] DependencyStrategy docstring updated
- Marker write failures now logged for debugging

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:50 +01:00
AndyMik90 836cc385b3 fix: address medium-severity PR review findings
- Fix potential deadlock in _popen_with_cleanup by using proc.communicate() instead of proc.wait() to drain pipes after terminate/kill
- Fix health check skip on re-runs by decoupling health check from 'performed' flag - now runs whenever venv symlink exists, detecting broken source venvs between runs

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:50 +01:00
AndyMik90 814cf763f8 fix: address follow-up review findings for PR #1832
- Wrap symlink removal in try/except in Python health check fallback to prevent PermissionError from skipping recreate strategy
- Add recursive: true flag to TypeScript rmSync call for consistent Windows junction handling

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:50 +01:00
AndyMik90 3ede3ec2a8 feat: symlink Python venvs in worktrees for instant setup
Switch venv strategy from RECREATE to SYMLINK so worktree creation is
near-instant (matching node_modules behavior). A health check after
symlinking verifies the venv is usable; if it fails, falls back to
recreate with improved robustness:

- Marker-based completion tracking (.setup_complete) detects incomplete venvs
- Popen-based subprocess management with proper terminate/kill on timeout
- Increased pip install timeout from 120s to 300s

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:50 +01:00
AndyMik90 e17137e937 fix: address PR #1831 review findings for webgl-context-management
- Remove unused fireEvent import from DisplaySettings test
- Add i18n helper text below GPU acceleration dropdown (en/fr)
- Replace positional selectCallbacks array with Map keyed by Select id
- Move debugLog after delete in terminal-session-store cleanup timer
- Remove redundant hasExited guard in pty-manager synchronous write path

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:44 +01:00
AndyMik90 9e276c4757 fix(logging): enhance error handling in app-logger and terminal processes
- Introduced safe logging functions to prevent crashes from console write failures and unhandled errors.
- Updated error logging setup to use safeLogUnhandled for uncaught exceptions and unhandled rejections.
- Added guards in terminal process management to avoid operations on exited PTYs, preventing potential crashes.
- Improved WebGL context management in terminal rendering to ensure stability during GPU acceleration.

This commit aims to enhance the robustness of the logging and terminal handling mechanisms, addressing potential crash scenarios and improving overall application stability.
2026-02-17 15:32:44 +01:00
AndyMik90 d745aee48d fix(terminal): resolve pendingDelete race and save contention causing crashes
Two bugs in terminal session persistence caused crashes when terminals
were destroyed and recreated with the same ID:

1. pendingDelete blocked legitimate terminal recreation: When a terminal
   exits and is recreated (worktree switch, shell restart), the 5-second
   pendingDelete window silently blocked all session saves for the new
   terminal, leaving it invisible to the session store. Added
   clearPendingDelete() to remove the guard when createTerminal() is
   called with a reused ID.

2. Sync save() and async saveAsync() raced on the same temp file: Both
   methods wrote to terminals.json.tmp without coordination, causing
   ENOENT errors when one renamed a file the other had already moved.
   save() now checks writeInProgress and defers to the async writer
   when a write is in-flight.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:44 +01:00
AndyMik90 5495e6564e fix(terminal): wrap WebGL calls in try-catch and add crash diagnostics
The WebGL register/acquire/unregister calls in useXterm were not wrapped
in try-catch, meaning any failure during WebGL context acquisition
(e.g., LRU eviction edge case, GPU memory pressure) would propagate as
an uncaught exception and crash the renderer process.

Also adds debug logging to terminal-session-store's pendingDelete
mechanism to help diagnose a reported crash when spawning terminals
after extended use with 5+ concurrent instances. The "Skipping save
for deleted session" warning now includes the full pendingDelete state.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:44 +01:00
AndyMik90 f399cd8ce2 feat(terminal): integrate WebGL context manager for GPU-accelerated rendering
Wire up the existing webgl-context-manager into the terminal rendering
pipeline with a user-configurable GPU Acceleration setting (auto/on/off).
WebGL gives 3-5x rendering performance for terminals while falling back
gracefully on unsupported browsers (Safari, some Linux+NVIDIA setups).

- Add GpuAcceleration type and gpuAcceleration field to AppSettings
- Add GPU Acceleration dropdown in Display Settings (i18n: en + fr)
- Register/acquire WebGL context after xterm.open(), unregister on dispose
- Respect user setting: 'off' skips WebGL, 'auto'/'on' acquires context
- Add 13 tests covering WebGL lifecycle and DisplaySettings GPU dropdown

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:43 +01:00
AndyMik90 2b8e2af233 fix: address PR #1821 review findings for screenshot paste capability
- Add image count guard (MAX_IMAGES_PER_TASK) in insights-service.ts
- Add count check to handleScreenshotCapture before processing
- Filter out images without displayable source in MessageBubble
- Remove dead content_blocks code in insights_runner.py (SDK limitation)
- Add visible UI warning when images attached but analysis unsupported
- Align backend MAX_IMAGE_FILE_SIZE to 10MB to match frontend
- Swap path validation order: check is_relative_to before exists()
- Remove redundant thumbnail field in persistImages mapping
- Replace hardcoded screenshot error with i18n translation key
- Add i18n keys (en/fr) for analysisUnsupported and screenshotTooLarge

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:37 +01:00
AndyMik90 67d44669de fix: add size validation to screenshot capture
Add MAX_IMAGE_SIZE validation to screenshot capture to match regular
image upload behavior. Screenshots larger than 10MB are now rejected
with a clear error message, preventing inconsistent behavior and
silent failures.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:37 +01:00
AndyMik90 9c57c669c6 fix: address local review findings - fix button type and suppress false positive lint warning
- Add explicit type="button" to tools expansion button to prevent unintended form submission
- Suppress Biome useExhaustiveDependencies false positive for session?.id dependency
  (the effect intentionally runs when session ID changes to reset task creation state)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:37 +01:00
AndyMik90 a5b66864e2 fix: address 9 new PR review findings for screenshot paste
Security (CMT-002 - MEDIUM):
- Add mode: 0o600 to temp file writes in insights-executor.ts (3 locations)
  to prevent world-readable files containing sensitive data

Quality (NEW-003 - MEDIUM):
- Add file size validation in useImageUpload.ts to prevent large images
  from being processed before backend validation
- Import MAX_IMAGE_SIZE constant and check file.size before base64 conversion

SDK Compatibility (CMT-001 - MEDIUM):
- Fix image_query_stream format in insights_runner.py
- Remove incorrect AsyncIterable approach, add clear TODO for SDK multi-modal support
- Provide user-visible warning when images cannot be sent in SDK mode

Memory Optimization (NEW-004 - LOW):
- Strip base64 data from Zustand state in insights-store.ts after sending to main process
- Retain thumbnails for display while removing full image data

Cleanup (CMT-003 - LOW):
- Fix manifest file cleanup by pushing to array before writeFile
- Ensures proper cleanup on partial write failures

UX (NEW-006 - LOW):
- Update image notation for historical messages in insights-service.ts
- Use past tense notation to avoid AI confusion about unavailable images

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:37 +01:00
AndyMik90 07dd376b3e fix: address PR review findings for screenshot paste capability
- Add randomBytes to historyFile name to fix CodeQL predictable temp file warning
- Resolve tmp_dir in Python to fix macOS symlink validation (is_relative_to)
- Convert writeFileSync to async writeFile to prevent main thread blocking
- Move SAFE_EXT_MAP to module scope to avoid repeated allocation
- Only write manifest file when manifest.length > 0 (skip empty manifests)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:37 +01:00
AndyMik90 36e9eb36d8 Fix CodeQL: use crypto.randomBytes for temp file names, remove redundant condition
- Add randomBytes(8) hex suffix to image and manifest temp file names
  to prevent predictable path attacks (CodeQL insecure-temporary-file)
- Remove always-true historyFileCreated check in image-write catch block
  (CodeQL useless-conditional)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:37 +01:00
AndyMik90 127778b74b Fix Ruff F541 f-string, historyFile leak on image-write failure, debug log label
- Remove f-prefix from string with no placeholders (Ruff F541 CI blocker)
- Clean up historyFile in image-write catch block before throw propagates
- Use file_size from stat() instead of base64 string length for debug log

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:37 +01:00
AndyMik90 48f4970f4b Fix follow-up PR review findings: SVG removal, image query, TOCTOU, cleanup guard
- Remove image/svg+xml from all allowlists (Python, TS executor, shared constants)
  SVG can contain scripts and is unsupported by Claude Vision API
- Fix client.query() to use AsyncIterable for multi-modal content blocks
  instead of passing a raw list that always triggers TypeError fallback
- Fix TOCTOU race: use resolved path instead of original path when opening
  image files after validation
- Add idempotency guard to cleanupTempFiles to prevent double cleanup

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:37 +01:00
AndyMik90 c916ec91ce Fix PR review findings: security hardening and code quality improvements
- Validate mimeType against allowlist in main process IPC handler (defense-in-depth)
- Use createThumbnail() for screenshots to avoid bloated session files
- Use generateImageId() instead of inline ID generation for consistency
- Add path, MIME type, and file size validation in Python image loader
- Narrow TypeError catch to only handle SDK query() type mismatches
- Extract shared cleanupTempFiles() helper to eliminate duplicated code
- Reset pendingImages in clearSession store action

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:37 +01:00
AndyMik90 97d0aeef44 auto-claude: subtask-4-3 - Add image display in user message bubbles
Display image thumbnails in user message bubbles within the Insights
chat. Images render in a flex-wrap layout below text content at max
200px. Handles both thumbnail-only (persisted) and full data cases.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:37 +01:00
AndyMik90 62bec58c4b auto-claude: subtask-4-2 - Add image paste/drop handlers, preview strip, and screenshot button to Insights
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:37 +01:00
AndyMik90 8100749797 auto-claude: subtask-4-1 - Update insights store to support images in messages
Add pendingImages state and setPendingImages action to the insights store.
Update sendMessage helper to accept optional images parameter, include them
in the user message, pass to electronAPI, and reset pending images after send.
Also update IPC type signature for sendInsightsMessage to include images param.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:37 +01:00
AndyMik90 e85eb9f176 auto-claude: subtask-3-1 - Update insights_runner.py to support multi-modal image input
Add --images-file CLI argument, load_images_from_manifest() helper, and
multi-modal content block construction in run_with_sdk(). Graceful fallback
when SDK doesn't support content blocks or in simple mode.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:37 +01:00
AndyMik90 260325fe3b auto-claude: subtask-2-5 - Strip image data from sessions on persistence
Add stripImageDataForPersistence() helper to SessionStorage that removes
full-resolution image data (data, path fields) from ImageAttachment objects
before writing to disk, keeping only thumbnail, id, filename, mimeType, and
size to prevent bloated session JSON files.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:37 +01:00
AndyMik90 b0b7176aaa auto-claude: subtask-2-4 - Update InsightsExecutor.execute() to handle images
Write image base64 data to temp files, create a JSON manifest with paths and
MIME types, pass manifest via --images-file argument to Python runner. Clean up
all temp image files in both success and error paths.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:37 +01:00
AndyMik90 90c9f386d5 auto-claude: subtask-2-3 - Update InsightsService.sendMessage() to accept and pass images
- Store thumbnail-only images on user messages for persistence (strip full data)
- Add '[User attached N image(s)]' notation to conversation history for context
- Pass images through to executor.execute()
- Update executor signature to accept optional ImageAttachment[] parameter

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:37 +01:00
AndyMik90 1c1ca43b0c auto-claude: subtask-2-2 - Update IPC handler to accept and pass images
Add images?: ImageAttachment[] parameter to INSIGHTS_SEND_MESSAGE handler
and pass it through to insightsService.sendMessage(). Also update the
service signature to accept the images parameter.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:37 +01:00
AndyMik90 bca5efeb93 auto-claude: subtask-2-1 - Update preload insights API to accept images parameter
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:37 +01:00
AndyMik90 1910e4bee1 auto-claude: subtask-1-2 - Add i18n translation keys for image-related UI text
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:37 +01:00
AndyMik90 19d2b3f31a auto-claude: subtask-1-1 - Add images field to InsightsChatMessage type
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:37 +01:00
AndyMik90 191736df1a fix: address PR review findings for XState PR review refactor
- handleComplete uses getOrCreateActor so late-arriving results after
  auth change or restart are processed instead of silently dropped
- GITHUB_AUTH_CHANGED handler now kills running review subprocesses and
  aborts CI wait controllers before clearing XState actors
- Duplicate review detection reads actual progress from actor snapshot
  instead of hardcoding progress=50
- handleClearReview stops actor directly without sending CLEAR_REVIEW
  event, preventing double IPC emission to renderer

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:36 +01:00
AndyMik90 9fa8532bb2 fix: address PR #1819 review findings for terminal session persistence
- Use setClaudeMode() instead of updateTerminal() in onTerminalClaudeExit
  handler to properly send CLAUDE_EXITED to XState machine
- Remove premature migratedSessionFlags cleanup from destroy() since
  resumeClaudeAsync already consumes flags and killAll() clears the map
- Add swap phase ordering guards (isCapturingPhase, isMigratingPhase,
  isRecreatingPhase) to prevent out-of-order swap events
- Add YOLO mode flag to deprecated sync resumeClaude for consistency
- Fix isBusy preservation heuristic by using dedicated updateClaudeSessionId
  action for self-transitions in claude_active state
- Add debugLog when setPendingClaudeResume silently drops request due to
  missing claudeSessionId
- Handle CLAUDE_BUSY events in claude_starting and pending_resume states

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:35 +01:00
AndyMik90 4a151aeb54 fix: address low-severity review findings — stale progress, dead code, missing tests
- Clear stale progress data when transitioning to externalReview state
- Capture snapshot before CLEAR_REVIEW so emitted payload has real context
- Add user feedback for duplicate follow-up review requests
- Remove dead clearPRReview code from store (zero callers)
- Add test coverage for CLEAR_REVIEW from reviewing/externalReview states
- Clarify ipcMain.emit comment re: EventEmitter semantics

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:35 +01:00
AndyMik90 e1e3cbf86b fix: address all PR #1819 review findings (round 7)
This commit addresses all 10 findings from the latest Auto Claude PR review:

**BLOCKING FIXES (3 MEDIUM severity):**

1. NCR-NEW-004: Add user notification when session migration fails
   - Added i18n key 'terminal:swap.migrationFailed' (EN + FR)
   - Hook now shows toast notification when isClaudeMode && sessionId && !sessionMigrated
   - Users are now informed when their Claude session is lost during profile switch

2. NEW-001: Add idle-state guard to setClaudeSessionId
   - setClaudeSessionId now checks if XState machine is in 'idle' state
   - Sends SHELL_READY first before CLAUDE_ACTIVE, matching setClaudeMode pattern
   - Prevents XState/Zustand desync during profile change flow

3. NEW-003: Correct fire-and-forget IPC comment
   - Removed incorrect claim about onTerminalPendingResume fallback
   - Updated comment to accurately describe actual failure behavior
   - Documents that errors are logged but no event is emitted back to renderer

**LOW SEVERITY FIXES (5):**

4. CMT-002: Remove EEXIST dead code
   - copyFile() without COPYFILE_EXCL never throws EEXIST
   - Removed unreachable catch branch at lines 136-141
   - Added comment documenting silent overwrite behavior

5. NEW-004-STORE: Add state check for CLAUDE_EXITED event
   - setClaudeMode now checks machine state before sending CLAUDE_EXITED
   - Only sends event if machine is in 'claude_starting' or 'claude_active'
   - Prevents XState/Zustand desync when event is dropped

6. NEW-006: Preserve isBusy during CLAUDE_ACTIVE self-transitions
   - setClaudeSessionId action now checks if it's a self-transition
   - Preserves existing isBusy state during self-transitions
   - Prevents late session ID updates from incorrectly clearing busy indicator

7. CMT-NEW-001: Add swap state assertions to RESET tests
   - Updated RESET test to include swapTargetProfileId and swapPhase
   - Tests now verify all 6 context fields are cleared (not just 4)
   - Comprehensive test coverage for resetContext action

**REMAINING LOW SEVERITY (acknowledged but not blocking):**

8. CMT-NEW-002: Swap phase events lack ordering guards
   - Acknowledged: ordering currently guaranteed by single caller
   - Guards would be defensive but not essential for current implementation
   - Can be addressed in future refactoring if needed

9. CMT-NEW-003: Dual Zustand/XState state updates lack architectural docs
   - Acknowledged: inline comments exist per method
   - Architectural-level documentation could be added separately
   - Does not block merge as per-method comments are clear

All tests passing (3271 passed, 6 skipped). TypeScript compiles cleanly.
Biome linting clean for all changed files.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:35 +01:00
AndyMik90 58fec15cd2 fix: prevent OOM, orphaned agents, and unbounded growth during overnight builds
- Move handleStartFollowupReview after runningReviews.has() duplicate check to
  prevent XState actor getting stuck in reviewing state when follow-up is already
  running (mirroring the regular review handler pattern)
- Add CLEAR_REVIEW handler to reviewing state so handleClearReview works correctly
  when an active review is cleared
- Remove dead-code START_REVIEW transition and always-false isNotAlreadyReviewing
  guard from reviewing state — duplicate prevention is handled at the IPC layer

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:35 +01:00
AndyMik90 33462978df fix: address remaining PR #1819 code quality findings
Three improvements for production code quality:

1. Use path alias for consistency
   - Change terminal-store.ts line 7 to use @shared/* instead of relative import
   - Matches project conventions (CLAUDE.md path alias guidelines)

2. Prevent XState/Zustand state divergence in setPendingClaudeResume
   - Only set pendingClaudeResume flag in Zustand if RESUME_REQUESTED was sent to XState
   - When claudeSessionId is missing, skip both XState event and Zustand update
   - Prevents UI showing "resume pending" when state machine doesn't know about it

3. Clean up migratedSessionFlags on individual terminal destroy
   - Previously only cleared on killAll(), entries could linger if terminal closed before resume
   - Now removes entry in destroy() if terminal has claudeSessionId
   - Prevents Map from accumulating stale session flags

All tests pass (128/128 files, 3271/3277 tests).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:35 +01:00
AndyMik90 947fc3c6f8 fix: address follow-up review findings — unhandled rejection, auth payload, polling guard
- Wrap timeout-branch IPC call in try/catch to prevent unhandled promise rejection
  in the Electron renderer when notifyExternalReviewComplete fails
- Add `notified` flag to short-circuit duplicate polling notifications before React
  cleanup fires
- Use last snapshot context in handleAuthChange so emitted cleared-state payload
  contains real projectId/prNumber instead of zeros
- Move handleStartReview after duplicate-review check so state machine isn't
  transitioned for already-running reviews

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:35 +01:00
AndyMik90 ea45b353ec fix: resolve PR #1819 review findings - session ID preservation and IPC clarity
Address three blocking review findings:

1. NEW-008: setClaudeMode now preserves claudeSessionId when dispatching CLAUDE_ACTIVE
   - Include terminal's current claudeSessionId in the event to prevent XState
     setClaudeSessionId action from overwriting it to undefined
   - Fixes hasActiveSession guard for profile swaps

2. NCR-001: setPendingClaudeResume preserves claudeSessionId in RESUME_COMPLETE event
   - Include terminal's claudeSessionId when sending RESUME_COMPLETE to XState
   - Prevents machine from losing session ID on resume completion

3. NEW-002: Remove ineffective try/catch around fire-and-forget IPC call
   - resumeClaudeInTerminal uses ipcRenderer.send() which returns void immediately
   - Removed try/catch and await that could never catch main process errors
   - Added comment documenting fire-and-forget nature and error handling via events

All tests pass (52/52).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:35 +01:00
AndyMik90 1b65a7ba23 fix: resolve XState gaps in external review polling, cancel/clear handlers, and result updates
- Add CANCEL_REVIEW and CLEAR_REVIEW handlers to externalReview state so users
  can cancel or clear while an external review is in progress
- Add REVIEW_COMPLETE self-transition in completed state so sendReviewStateUpdate
  can update result context (e.g., after posting findings or marking as posted)
- Add notifyExternalReviewComplete IPC channel so renderer polling can notify the
  main process when an external review finishes on disk or times out, transitioning
  the XState actor to completed/error instead of leaving it stuck in externalReview
- Wire PRDetail.tsx external review polling to use the new IPC notification

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:35 +01:00
AndyMik90 966e5cadfa fix: address review findings for PR #1819
- Add setError action to claude_active CLAUDE_EXITED transition to preserve error messages
- Fix missing await on resumeClaudeInTerminal call with proper error handling fallback
- Improve TypeScript type safety in test helper using Partial<TerminalContext>
- Add test coverage for CLAUDE_EXITED error preservation from claude_active state

All tests pass (52/52).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:35 +01:00
AndyMik90 b3d6bbdeda fix: resolve IPC serialization, auth change wiring, and error→followup transition (qa-requested)
Fixes:
- Build PRReviewStatePayload object in emitStateToRenderer instead of sending raw args
- Wire up handleAuthChange via ipcMain listener for GITHUB_AUTH_CHANGED
- Add START_FOLLOWUP_REVIEW transition to error state in pr-review-machine
- Update state manager tests to verify PRReviewStatePayload shape

Verified:
- All 3279 tests pass
- TypeScript compilation clean

QA Fix Session: 1

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:35 +01:00
AndyMik90 d1c63d23aa Fix follow-up review: security, dead code, XState wiring completeness
- Convert migrateSession() from sync to async fs operations (mkdir,
  copyFile, cp, unlink from fs/promises) to avoid blocking the Electron
  main process during session migration
- Remove dead TerminalSwapState/TerminalSwapPhase types and swapState
  field from TerminalProcess (no longer referenced after prior cleanup)
- Remove dead swapState logic from activateDeferredResume
- Add migratedSessionFlags.clear() to killAll() to prevent memory leaks
- Add CLAUDE_ACTIVE handler to pending_resume XState state (fixes race
  where Claude becomes active before RESUME_COMPLETE fires)
- Add test coverage for CLAUDE_ACTIVE in pending_resume state

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:35 +01:00
AndyMik90 16f3194ca0 auto-claude: subtask-5-1 - Fix type errors and verify full test suite
- Remove obsolete setPRReviewResult calls in PRDetail.tsx (now handled by XState)
- Add missing onPRReviewStateChange to browser-mock.ts
- Fix pr-review-machine.test.ts mock data to match actual PRReviewResult/PRReviewProgress types
- All 130 test files pass (3278 tests), typecheck clean, lint clean

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:35 +01:00
AndyMik90 9bcd1a3033 Fix follow-up review: security, dead code, XState wiring completeness
Security:
- Move YOLO mode (dangerouslySkipPermissions) to server-side storage
  instead of accepting from renderer via IPC. Main process stores flag
  during profile migration and restores it when resume is called.

XState machine fixes:
- Add CLAUDE_ACTIVE self-transition in claude_active state so
  setClaudeSessionId can update context.claudeSessionId (was silently
  dropped, blocking hasActiveSession guard)
- Add SHELL_EXITED dispatch in setTerminalStatus for 'exited' status
  so XState machine reaches its exited state

Dead code removal:
- Remove unused swapProfileAndResume method (migration handled directly
  in IPC handler) and its now-unused migrateSession import
- Remove unused deriveTerminalStateFromMachine function and SnapshotFrom
  import

Resource cleanup:
- clearAllTerminals now disposes terminalBufferManager entries and
  xtermCallbacks alongside XState actors

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:35 +01:00
AndyMik90 181fe50be7 auto-claude: subtask-4-2 - Update useGitHubPRs hook for new XState-driven architecture
- Remove imports of deleted startPRReview/startFollowupReview store functions
- runReview/runFollowupReview now call IPC directly (main process handles XState)
- cancelReview no longer mutates store directly (state flows back via IPC)
- Add setLoadedReviewResult action to pr-review-store for disk-loaded reviews
- Replace all setPRReviewResult calls with setLoadedReviewResult

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:35 +01:00
AndyMik90 572d62da8b Fix PR review findings: XState machine wiring, dead code, YOLO mode preservation
- Make pending_resume state reachable by adding RESUME_REQUESTED transitions
  from shell_ready and claude_active states
- Add CLAUDE_ACTIVE transition from shell_ready for direct activation path
- Wire SHELL_READY dispatch in setTerminalStatus and setClaudeMode to
  prevent XState machine from being stuck in idle
- Remove dead TERMINAL_SWAP_PROGRESS IPC send (no listener existed)
- Remove unused isSwapping guard from terminal machine
- Remove ineffective try/catch around fire-and-forget ipcRenderer.send()
- Preserve dangerouslySkipPermissions (YOLO mode) through profile swap
  terminal recreation flow via resume options
- Align swap phase naming: capturing_session → capturing (matches XState)
- Fix French translation accents: démarrer, changé, à

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:35 +01:00
AndyMik90 a0c8e89fee auto-claude: subtask-4-1 - Rewrite pr-review-store.ts as thin XState state subscriber
Replace 6 imperative review lifecycle actions with a single handlePRReviewStateChange
handler that maps XState state/context to the existing PRReviewState interface shape.
Update initializePRReviewListeners to use onPRReviewStateChange IPC channel. Remove
exported startPRReview/startFollowupReview helpers (now direct IPC calls from hooks).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:35 +01:00
AndyMik90 c8fe01ef0c auto-claude: subtask-4-2 - Write comprehensive unit tests for terminal-machine
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:35 +01:00
AndyMik90 df819b3990 auto-claude: subtask-3-1 - Refactor pr-handlers.ts to use PRReviewStateManager
Replace all 6 createIPCCommunicators() calls for review lifecycle events with
PRReviewStateManager routing. The manager's XState actors now handle all state
transitions and emit on GITHUB_PR_REVIEW_STATE_CHANGE channel.

Changes:
- Create PRReviewStateManager instance in registerPRHandlers()
- GITHUB_PR_REVIEW handler: route start/progress/complete/error through manager
- GITHUB_PR_FOLLOWUP_REVIEW handler: route through manager with previous result
- GITHUB_PR_REVIEW_CANCEL handler: call manager.handleCancel() after kill
- sendReviewStateUpdate(): use manager.handleComplete() instead of direct IPC
- runPRReview(): accept manager param, use for progress callbacks
- Remove unused createIPCCommunicators import

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:35 +01:00
AndyMik90 e5f1c6b2db auto-claude: subtask-4-1 - Add i18n translation keys for swap/resume UI messages
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:35 +01:00
AndyMik90 8c0b0257a2 auto-claude: subtask-2-3 - Write unit tests for PRReviewStateManager.
File: apps/frontend/src/main/__tests__/pr-review-state-manager.test.ts
2026-02-17 15:32:35 +01:00
AndyMik90 1302c61b71 auto-claude: subtask-3-2 - Integrate XState terminal machine into terminal-store
Add module-level terminalActors Map and helper functions (getOrCreateTerminalActor,
sendTerminalMachineEvent, deriveTerminalStateFromMachine) for XState actor management.
Store actions (setClaudeMode, setClaudeSessionId, setClaudeBusy, setPendingClaudeResume)
now forward corresponding events to the XState machine. Actors are cleaned up on
terminal removal and clearAllTerminals.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:35 +01:00
AndyMik90 bfdbdb5f22 auto-claude: subtask-2-2 - Create PRReviewStateManager class in Electron main process
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:35 +01:00
AndyMik90 6c991774ad auto-claude: subtask-3-1 - Auto-resume Claude session after terminal profile change
Replace manual "Run: claude --resume" message with automatic resume call via
resumeClaudeInTerminal IPC. Updated preload API and IPC types to pass
migratedSession option. YOLO mode is preserved automatically via the main
process terminal object.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:35 +01:00
AndyMik90 b4264ae95b auto-claude: subtask-2-1 - Add IPC channel constant and preload API listener for PR review state changes 2026-02-17 15:32:35 +01:00
AndyMik90 fc3e8a8ad5 auto-claude: subtask-2-3 - Add isClaudeMode to TERMINAL_PROFILE_CHANGED event and migratedSession to TERMINAL_RESUME_CLAUDE
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:35 +01:00
AndyMik90 f3e910598b auto-claude: subtask-1-2 - Write comprehensive unit tests for the PR review state machine and utilities
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:35 +01:00
AndyMik90 7578a3263b auto-claude: subtask-2-2 - Update terminal-manager with swap orchestration and options passthrough
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:35 +01:00
AndyMik90 45eebe960f auto-claude: subtask-1-1 - Create XState v5 PR review state machine and state utils
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:35 +01:00
AndyMik90 ab42f88635 auto-claude: subtask-2-1 - Add migratedSession option to resumeClaudeAsync and preserve YOLO mode
- Add optional `options` parameter with `migratedSession` flag to resumeClaudeAsync()
- When migratedSession is true, log post-swap resume context and skip sessionId deprecation warning
- Preserve dangerouslySkipPermissions flag from terminal's stored state during resume

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:35 +01:00
AndyMik90 84775ed46c auto-claude: subtask-1-3 - Update shared/state-machines/index.ts barrel export
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:34 +01:00
AndyMik90 ca370eaa1f auto-claude: subtask-1-2 - Add TerminalSwapState interface and swapState to TerminalProcess
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:34 +01:00
AndyMik90 5a8e140c39 auto-claude: subtask-1-1 - Create terminal-machine.ts XState v5 state machine
Add XState v5 state machine for terminal lifecycle with states: idle,
shell_ready, claude_starting, claude_active, swapping, pending_resume,
exited. Context tracks claudeSessionId, profileId, swap state, isBusy,
and error. Includes guards (hasActiveSession, isSwapping) and assign
actions for all context updates.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:34 +01:00
AndyMik90 da7d186950 fix: address all XState catch-up and cleanup findings for PR #1815
Resolves all 9 findings from auto-claude review (2026-02-16):

HIGH severity (1):
- NEW-001: Added catch-up transition for 'analyzing' state when setting status to 'generating'
  The actor now properly transitions through 'discovering' before reaching 'generating'

MEDIUM severity (3):
- NEW-002: Fixed updateFeatureLinkedSpec to respect XState state machine
  Removed fallback that bypassed XState for 'done' features. Now skips store write
  when LINK_SPEC event is silently ignored (no linkedSpecId in context)

- NEW-003: Wired up HMR cleanup and test actor reset
  Added import.meta.hot.dispose handler to reset actors during HMR
  Added resetActors() call in test afterEach to prevent test pollution

- NEW-004: Added comprehensive catch-up logic for 'complete' phase
  The actor now properly transitions through all intermediate states
  (analyzing → discovering → generating) before accepting GENERATION_COMPLETE

LOW severity (1):
- CMT-001: Clarified test describe block title
  Changed from "same-status transition is no-op" to "redundant status transitions"
  to distinguish true no-ops (ignored events) from self-transitions (MARK_DONE in done)

All XState catch-up transitions now handle out-of-order status messages correctly,
preventing the UI from showing incorrect generation/feature status.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:30 +01:00
AndyMik90 3f9cea9eca refactor: address all code review findings for roadmap XState refactor
Fix all CodeRabbit review comments and Biome warnings:
- Replace non-null assertions with explicit null checks in roadmap-store.ts (lines 548, 553, 559, 565)
- Replace non-null assertion with proper type guards in test (line 396)
- Use @shared/state-machines path alias instead of relative imports
- Prune stale feature actors in setRoadmap when roadmap changes
- Add lastActivityAt timestamp tracking to generation machine context
- Update deriveGenerationStatus to use persisted lastActivityAt from context
- Fix misleading test title "ignore MARK_DONE" → "self-transition"
- Add test verifying progress preservation on GENERATION_ERROR
- Remove progress reset in setError action to preserve progress on errors
- Add compile-time assertions to ensure state name arrays stay in sync with XState machines

All tests pass (77/77). TypeScript compilation successful. Zero Biome warnings in modified files.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:30 +01:00
AndyMik90 960a6acb96 fix: address second round of review findings for PR #1815
Fixes 6 issues identified in follow-up review (2 HIGH, 1 MEDIUM, 3 LOW):

1. HIGH [65226bd9539f]: Generation can now restart from complete/error states
   - Added RESET + START_GENERATION logic in 'analyzing' case

2. HIGH [282536242c43]: Phase restoration fixed for discovering/generating
   - Drive actor through intermediate transitions to reach target state
   - Handle idle and complete/error states before sending phase events

3. MEDIUM [1b74aa0cd0f1]: Progress value clamping added to updateProgress
   - Clamp progress to 0-100 range using Math.min/max

4. LOW [c833788d76ce]: setError now resets progress to 0 on error
   - Consistent error state with progress reset

5. LOW [686d19af55d5]: Document unused SETTLED_STATES constants
   - Added comments explaining future public API use

6. LOW [605d439c4efd]: Document getState() outside set() pattern
   - Explain XState actors as external side effects

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:30 +01:00
AndyMik90 948a55a82c fix: address review findings for PR #1815
- Replace deprecated String.prototype.substr with substring
- Add resetActors() helper for test cleanup and HMR

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:30 +01:00
AndyMik90 730ed12d3c Address follow-up review suggestions for XState roadmap integration
- Move deleteFeature actor cleanup outside set() for consistency
- Skip no-op store writes when XState silently ignores events
- Use 'as const' on assign action string literals for type narrowing

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:30 +01:00
AndyMik90 5c12dbc669 Fix PR review issues: strong types, actor cleanup, under_review transitions
- Use TaskOutcome/RoadmapFeatureStatus types in feature machine context
  instead of loose strings, eliminating unsafe casts in roadmap-store
- Add TASK_COMPLETED/DELETED/ARCHIVED handlers to under_review state,
  fixing a behavioral regression where linked task events were silently
  ignored
- Move XState actor side effects outside Zustand set() callbacks in
  updateFeatureStatus, markFeatureDoneBySpecId, updateFeatureLinkedSpec
- Clean up stale feature actors in setRoadmap to prevent memory leaks
  when switching projects or loading new roadmaps
- Consolidate duplicate imports from shared/state-machines

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:30 +01:00
AndyMik90 b7d1ffe209 auto-claude: subtask-4-1 - Verify backward compatibility and fix XState integration
- Add TASK_COMPLETED/DELETED/ARCHIVED transitions to planned and done states
- Add MARK_DONE self-transition in done state for idempotent updates
- Restore feature context (taskOutcome, previousStatus, linkedSpecId) when
  creating XState actors from persisted store data
- Invalidate cached actors when state or context diverges from store truth
- Update machine tests to reflect expanded transition coverage
- All 3293 tests pass, typecheck clean, lint warnings only (pre-existing)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:30 +01:00
AndyMik90 aa95986be8 auto-claude: subtask-3-1 - Refactor roadmap-store.ts to integrate XState actors
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:30 +01:00
AndyMik90 7a69743ae1 auto-claude: subtask-2-2 - Write comprehensive unit tests for roadmap feature machine
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:30 +01:00
AndyMik90 6b7f241045 auto-claude: subtask-2-1 - Write comprehensive unit tests for the roadmap generation machine
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:30 +01:00
AndyMik90 b6ae439d16 auto-claude: subtask-1-4 - Update barrel export for roadmap machine artifacts 2026-02-17 15:32:30 +01:00
AndyMik90 fa4e29f591 auto-claude: subtask-1-3 - Create roadmap-state-utils.ts with state name constants, settled states, and mapping utilities
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:30 +01:00
AndyMik90 906b1f29c4 auto-claude: subtask-1-2 - Create roadmap feature state machine
Add roadmap-feature-machine.ts with states: under_review, planned,
in_progress, done. Handles LINK_SPEC auto-transition to in_progress,
task completion events from in_progress only, REVERT from done
restoring previousStatus via guards, and context cleanup on
non-done transitions.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:30 +01:00
AndyMik90 11e300c75d auto-claude: subtask-1-1 - Create roadmap generation XState machine
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 15:32:30 +01:00
AndyMik90 c1210c46f0 fix: address final PR review findings
Resolve remaining code quality issues from auto-claude bot review:

1. Error Handling (Roadmap.tsx):
   - Wrap confirmArchiveFeature in try/finally to ensure pendingArchiveFeatureId
     is always cleared, even if deleteFeature throws an error
   - Prevents dialog from getting stuck in broken state on failure

2. Accessibility (FeatureCard.tsx):
   - Add missing aria-label to archive button for screen reader support
   - Now consistent with PhaseCard and SortableFeatureCard implementations
   - Uses existing i18n key: accessibility.archiveFeatureAriaLabel

All other findings were already addressed in previous commits:
- useFeatureArchive hook removed (reuses useFeatureDelete)
- Confirmation dialog centralized in Roadmap.tsx
- Archive button JSX extracted to shared variables (PhaseCard, FeatureDetailPanel)
- handleArchive no longer calls onClose() prematurely
- All hardcoded UI strings replaced with i18n translation keys
- Archive buttons properly guard with onArchive && checks
- All archive buttons have aria-labels for accessibility

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-16 08:47:44 +01:00
AndyMik90 ff6ad4479c fix: address PR review findings for archive button feature
Resolve all review comments from gemini-code-assist and coderabbitai:

1. Remove duplicate archive button rendering in PhaseCard
   - Extract isDone check to avoid duplicate conditional logic
   - Archive button now renders only once for done features

2. Add archive button support to "By Priority" view
   - Done features in priority view now show archive functionality
   - Maintains consistent UX across all roadmap tabs
   - Uses semantic button element for accessibility

3. Improve accessibility and code quality
   - Replace div with button in priority view feature cards
   - Add proper focus states and keyboard navigation support
   - Remove unused imports (ExternalLink, Play)

All review findings addressed while maintaining existing functionality.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-15 22:19:05 +01:00
Andy bccdbf35da Merge branch 'develop' into auto-claude/220-add-manual-competitor-functionality-in-roadmap 2026-02-15 20:57:28 +01:00
AndyMik90 99aeae7e49 fix: address follow-up PR review findings for archive feature
Address 4 new findings identified in latest PR review:

1. Replace hardcoded UI strings with i18n translation keys:
   - SortableFeatureCard.tsx: "Task" → t('roadmap.task')
   - SortableFeatureCard.tsx: "Build" → t('roadmap.build')
   - PhaseCard.tsx: "View Task" → t('roadmap.viewTask')
   - PhaseCard.tsx: "Build" → t('roadmap.build')

2. Add missing aria-labels for accessibility:
   - SortableFeatureCard.tsx: Archive button now has aria-label
   - PhaseCard.tsx: Archive button now has aria-label

3. Add new translation keys to both locale files:
   - en/common.json: Added "task" and "viewTask" to roadmap section
   - fr/common.json: Added "task" ("Tâche") and "viewTask" ("Voir la tâche")

All archive buttons now properly support screen readers and comply
with i18n requirements for both English and French locales.

Resolves findings from PR #1817 review (2026-02-15T18:31:26Z).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-15 20:30:33 +01:00
AndyMik90 c59215edf3 fix: replace hardcoded UI strings with i18n translation keys
Address review findings by converting hardcoded user-facing strings
to react-i18next translation keys in roadmap feature components.

Changes:
- Add 'goToTask', 'convertToTask', 'build' keys to roadmap section
  in both en/common.json and fr/common.json
- Replace hardcoded "Go to Task" with t('roadmap.goToTask')
- Replace hardcoded "Convert to Auto-Build Task" with t('roadmap.convertToTask')
- Replace hardcoded "Build" with t('roadmap.build')

Files modified:
- FeatureDetailPanel.tsx: 2 hardcoded strings replaced
- FeatureCard.tsx: 2 hardcoded strings replaced
- en/common.json: 3 new translation keys added
- fr/common.json: 3 new French translations added

Resolves i18n violations identified in PR #1817 review.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-15 17:39:19 +01:00
Andy 586e9d6ac2 Merge branch 'develop' into auto-claude/226-add-archive-button-to-done-tasks 2026-02-15 17:12:13 +01:00
AndyMik90 517892cf31 Fix cross-process race condition and remove dead code
Use a separate manual_competitors.json file that the backend agent never
overwrites, preventing data loss when users add competitors during analysis.
Remove unused removeCompetitor and updateCompetitorAnalysis store actions.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-15 14:12:13 +01:00
AndyMik90 7f6050f5ba fix(terminal): resolve blank terminals after project switch
Force SIGWINCH on same-dimension resize and skip stale buffer replay
for Claude-mode terminals during project switch remount.

Two compounding issues caused blank terminals when switching projects:

1. On macOS/Linux, ioctl(TIOCSWINSZ) only sends SIGWINCH when dimensions
   actually change. After project switch, PTY persists with old dimensions
   and the terminal remounts at the same size, so TUI apps never get
   SIGWINCH and never redraw. Fix: resize to (cols-1, rows) first, then
   to (cols, rows) to force the signal.

2. Buffer replay concatenated serialized xterm state with raw PTY output
   accumulated during the unmount period, producing garbled display. Fix:
   skip buffer replay for Claude-mode terminals on project switch remount
   (the forced SIGWINCH makes Claude Code redraw its full TUI). Initial
   restore still replays the buffer as a loading preview.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 21:03:33 +01:00
Andy 9b46709508 Merge branch 'develop' into auto-claude/220-add-manual-competitor-functionality-in-roadmap 2026-02-14 17:49:11 +01:00
Andy 392571049a Merge branch 'develop' into auto-claude/226-add-archive-button-to-done-tasks 2026-02-14 17:49:01 +01:00
AndyMik90 6c9a8b200f Fix follow-up review findings: data loss bug, dialog nesting, and quality improvements
- Preserve manual competitors in analyze(enabled=False) path (HIGH data loss bug)
- Fix incomplete rollback by restoring full previous competitorAnalysis state
- Reset showAddDialog state when ExistingCompetitorAnalysisDialog reopens
- Add encoding option to writeFileWithRetry for competitor analysis save
- Replace X icon with AlertCircle in error alert for clarity
- Add type="button" to all raw button elements in dialog
- Add warning logs to silent exception handlers in competitor_analyzer.py
- Forward onCompetitorAdded callback through ExistingCompetitorAnalysisDialog

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 15:22:32 +01:00
AndyMik90 f89fd5080b fix: prevent panel close before archive confirmation and extract archive button
- Remove onClose() from handleArchive — confirmArchiveFeature in Roadmap.tsx
  already handles panel closing via setSelectedFeature(null) after confirmation
- Extract triplicated archive button JSX into shared variable

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 15:20:31 +01:00
AndyMik90 59944f2335 fix: address follow-up PR review findings
- Extract duplicated archive button JSX in PhaseCard into shared variable
- Centralize archive confirmation dialog in Roadmap.tsx using AlertDialog
- Remove local archive confirmation from FeatureDetailPanel (now centralized)
- Make handleArchive async to properly await onArchive callback
- Add archive button for done features with linkedSpecId in FeatureDetailPanel

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 11:30:11 +01:00
AndyMik90 c7301d67c5 Fix follow-up review findings: data loss bug, dialog nesting, and quality improvements
- [HIGH] Move _get_manual_competitors() before discovery file check to prevent
  data loss when discovery file is missing during refresh
- [HIGH] Merge manual competitors after _create_error_analysis_file in
  discovery-file-missing path
- [MEDIUM] Move AddCompetitorDialog outside parent Dialog in
  CompetitorAnalysisViewer to fix Radix UI focus/z-index issues
- [LOW] Use i18n.language for date formatting instead of hardcoded 'en-US'
- [LOW] Add warning log in _merge_manual_competitors on file read failure
- [LOW] Replace hardcoded English fallback with i18n key in AddCompetitorDialog
- [LOW] Add focus-visible ring styles to option buttons in
  ExistingCompetitorAnalysisDialog for keyboard accessibility
- [LOW] Replace deprecated substr() with substring() in roadmap-store ID generation

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 11:25:50 +01:00
Andy 28bf739d8a Merge branch 'develop' into auto-claude/226-add-archive-button-to-done-tasks 2026-02-14 11:25:28 +01:00
Andy fa05afb02d Merge branch 'develop' into auto-claude/220-add-manual-competitor-functionality-in-roadmap 2026-02-14 11:23:27 +01:00
AndyMik90 4d781b5627 fix: address PR review findings for archive button feature
- Remove duplicate useFeatureArchive hook, reuse useFeatureDelete instead
- Add feature.status === 'done' guard to PhaseCard taskOutcome branch
- Add confirmation dialog to archive action in FeatureDetailPanel
- Fix missing 'common' namespace in FeatureCard useTranslation
- Add i18n keys for archive confirmation dialog (en/fr)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 10:23:47 +01:00
AndyMik90 d917fa63f7 Fix PR review findings: i18n, store rollback, state reset, and data preservation
- Complete i18n migration for CompetitorAnalysisViewer (all hardcoded strings)
- Complete i18n migration for ExistingCompetitorAnalysisDialog (all hardcoded strings)
- Fix namespace mismatch: ExistingCompetitorAnalysisDialog now uses 'dialogs' namespace
  consistently with sibling competitor dialog components
- Move shared i18n keys from common to dialogs namespace where appropriate
- Add store rollback in AddCompetitorDialog when IPC save fails
- Add removeCompetitor action to roadmap store for rollback support
- Reset addedCount state when CompetitorAnalysisDialog reopens
- Preserve manual competitors when competitor analysis fails all retries
- Add all new translation keys to both en and fr locale files

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 10:23:24 +01:00
AndyMik90 556fa8f5a5 auto-claude: subtask-1-1 - Update XSTATE_MIGRATION_SUMMARY.md to reflect completed migration
Mark Phases 3-4 as complete, replace 'Why We Stopped at Phase 2' with
'Migration Complete' section, remove legacy fallback references and
rollback plan, remove Phase 3-4 from Future Improvements.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 00:34:43 +01:00
AndyMik90 13df4c735c auto-claude: subtask-7-3 - End-to-end verification of the complete data flow.
Verified all 8 integration points pass:
- AddCompetitorDialog validates name/URL correctly
- Store generates competitor-manual-* IDs with source='manual'
- IPC handler transforms camelCase→snake_case and writes JSON
- ROADMAP_GET preserves source field on load
- CompetitorAnalysisViewer shows Manual badge
- Backend competitor_analyzer preserves manual competitors on refresh

Fixed minor issue: removed unnecessary `as any` cast in CompetitorAnalysisViewer.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 00:27:08 +01:00
AndyMik90 1594a6d51c auto-claude: subtask-6-1 - Preserve manual competitors during refresh
Add _get_manual_competitors() and _merge_manual_competitors() methods to
CompetitorAnalyzer. Manual competitors (source=='manual') are extracted
before the AI agent runs and merged back after successful validation,
ensuring they survive refresh cycles.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 00:22:26 +01:00
AndyMik90 f5a753decf auto-claude: subtask-5-3 - Add 'Add known competitors' option to ExistingCompetitorAnalysisDialog
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 00:20:20 +01:00
AndyMik90 c28e7ef488 auto-claude: subtask-5-2 - Add 'Add Known Competitors' section to CompetitorAnalysisDialog
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 00:17:26 +01:00
AndyMik90 0e0886904d auto-claude: subtask-5-1 - Add 'Add Competitor' button to CompetitorAnalysisViewer
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 00:14:33 +01:00
AndyMik90 a0034ed41c auto-claude: subtask-4-1 - Create AddCompetitorDialog.tsx component
Add dialog for manually adding competitors to roadmap analysis with
name, URL, description, and relevance fields. Follows AddFeatureDialog
pattern. Also adds saveCompetitorAnalysis to ElectronAPI type.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 00:12:19 +01:00
AndyMik90 236b69425f auto-claude: subtask-3-2 - Add French i18n keys for competitor functionality
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 00:08:54 +01:00
AndyMik90 237c944cc3 auto-claude: subtask-3-1 - Add English i18n keys for the AddCompetitorDialog
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 00:07:41 +01:00
AndyMik90 ea3c2e625f auto-claude: subtask-2-3 - Add source field to competitor mapping in ROADMAP_GET handler
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 00:06:35 +01:00
AndyMik90 be39dd7221 fix: show archive button on done features without taskOutcome (qa-requested)
Fixes:
- SortableFeatureCard: moved archive button outside taskOutcome ternary
- FeatureDetailPanel: added archive button for done features without taskOutcome
- Fixed i18n namespace from 'tasks' to 'common' in SortableFeatureCard

QA Fix Session: 2
2026-02-14 00:05:42 +01:00
AndyMik90 8021b04cb5 auto-claude: subtask-2-2 - Add COMPETITOR_ANALYSIS_SAVE IPC handler in roadmap-handlers
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 00:05:35 +01:00
AndyMik90 7ee40a813c auto-claude: subtask-2-1 - Add addCompetitor and updateCompetitorAnalysis actions to roadmap-store
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 00:04:04 +01:00
AndyMik90 45f16be130 auto-claude: subtask-1-3 - Add saveCompetitorAnalysis method to the preload roadmap API
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 00:02:47 +01:00
AndyMik90 7972047c7e auto-claude: subtask-1-2 - Add COMPETITOR_ANALYSIS_SAVE IPC channel to ipc.ts
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 00:01:38 +01:00
AndyMik90 75513472ee auto-claude: subtask-1-1 - Add CompetitorSource type and ManualCompetitorInput to roadmap types
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 00:00:47 +01:00
AndyMik90 c2db77fb5e auto-claude: subtask-3-4 - Add archive button to PhaseCard.tsx for done features
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 23:55:32 +01:00
AndyMik90 8046306ae0 auto-claude: subtask-3-3 - Add archive button to FeatureDetailPanel.tsx
Import Archive icon, destructure onArchive prop, add handleArchive handler
that calls onArchive and closes panel, render archive button in footer
when feature.status === 'done' with i18n text and aria-label.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 23:54:23 +01:00
AndyMik90 f1c530ad2f auto-claude: subtask-3-2 - Add archive button to SortableFeatureCard for done tasks
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 23:53:15 +01:00
AndyMik90 3a74543a8c auto-claude: subtask-3-1 - Add archive button to FeatureCard.tsx
Import Archive icon and useTranslation, destructure onArchive from props,
render ghost archive button for done features with stopPropagation.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 23:52:12 +01:00
AndyMik90 432f6bd838 auto-claude: subtask-2-3 - Thread onArchive prop through RoadmapKanbanView.tsx
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 23:51:01 +01:00
AndyMik90 5027355a8e auto-claude: subtask-2-2 - Thread onArchive prop through RoadmapTabs.tsx
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 23:50:05 +01:00
AndyMik90 557fda68c1 auto-claude: subtask-2-1 - Wire useFeatureArchive in Roadmap.tsx
Import and call useFeatureArchive hook alongside useFeatureDelete.
Create handleArchiveFeature wrapper that archives the feature and
clears selectedFeature if it matches. Pass onArchive prop to both
RoadmapTabs and FeatureDetailPanel.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 23:49:04 +01:00
AndyMik90 9e89354d04 auto-claude: subtask-1-3 - Update TypeScript interfaces to add onArchive callback prop
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 23:47:49 +01:00
AndyMik90 3a5a9dbca9 auto-claude: subtask-1-2 - Create useFeatureArchive hook in hooks.ts
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 23:46:58 +01:00
AndyMik90 cda21b2056 auto-claude: subtask-1-1 - Add i18n translation keys for archive feature
Add roadmap.archiveFeature and accessibility.archiveFeatureAriaLabel keys
to both English and French locale files.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 23:46:12 +01:00
AndyMik90 1a8f589f96 auto-claude: subtask-1-1 - Add keepWorktree option to mark-as-done flow
Add keepWorktree option to TASK_UPDATE_STATUS handler so marking a task
as done bypasses the worktree existence check without deleting it. Update
type definitions in task-api.ts and task-store.ts, and fix handleMarkDoneOnly
in WorkspaceMessages.tsx to pass { keepWorktree: true } and check the result.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 23:42:24 +01:00
github-actions[bot] 5745cb149f docs: update README to v2.7.6-beta.1 [skip ci] 2026-01-30 21:29:56 +00:00
555 changed files with 18396 additions and 48226 deletions
+1
View File
@@ -3,6 +3,7 @@ name: Discord Release Notification
on:
release:
types: [published]
workflow_dispatch:
jobs:
discord-notification:
+1 -1
View File
@@ -620,7 +620,7 @@ jobs:
draft: false
prerelease: ${{ contains(github.ref, 'beta') || contains(github.ref, 'alpha') }}
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GITHUB_TOKEN: ${{ secrets.PAT_TOKEN || secrets.GITHUB_TOKEN }}
# Update README with new version after successful release
update-readme:
+1 -1
View File
@@ -11,7 +11,7 @@ jobs:
permissions:
issues: write
steps:
- uses: actions/stale@v9
- uses: actions/stale@v10
with:
stale-issue-message: |
This issue has been inactive for 60 days. It will be closed in 14 days if there's no activity.
@@ -1,240 +0,0 @@
# GitHub Issues Documentation Design
**Date:** 2025-02-16
**Status:** Approved
**Author:** Claude (Superpowers Brainstorming)
## Overview
Create comprehensive, user-friendly documentation for Auto Claude's GitHub Issues integration. The documentation will serve a mixed audience (new and existing users) with progressive depth across three documents.
## Target Audience
**Mixed audience with progressive depth:**
- **End users** - New to Auto Claude, want to understand features and get started quickly
- **Technical users** - Existing users wanting to optimize AI configuration and manage costs
- **Pro users/developers** - Want to customize prompts, context injection, and extend the system
## Document Structure
### New Directory: `guides/github-issues/`
```
guides/
└── github-issues/
├── README.md # Navigation index
├── github-issues-user-guide.md # Document 1
├── github-issues-advanced-ai-configuration.md # Document 2
└── github-issues-customization-guide.md # Document 3
```
### Document 1: User Guide
**Audience:** End users (non-technical)
**Focus:** Features, workflows, getting started
**Sections:**
1. **Overview** - What is GitHub Issues integration? Why use it?
2. **Quick Start (5 minutes)** - Get your first issue investigated end-to-end
3. **Key Features** - Bullet points of main capabilities
4. **Integration Workflow** - Import → Investigate → Create Task → Implement (EMPHASIS)
5. **Setup & Configuration** - GitHub authentication, connecting repos
6. **Using the Features**
- Importing & browsing issues
- Running AI investigations
- Creating tasks from results
- Posting findings back to GitHub
7. **FAQ** - Common questions
**Tone:** Friendly, encouraging, approachable. Plain English with minimal jargon.
### Document 2: Advanced AI Configuration
**Audience:** Technical users, team leads
**Focus:** AI tuning, performance, cost management
**Sections:**
1. **Overview** - Who this guide is for
2. **Opus 4.6 Features** - Fast Mode, 128K tokens, adaptive thinking
3. **The 4 Specialist Agents** - Deep dive into each agent's role
4. **Pricing & Cost Management** - Token limits, cost optimization strategies
5. **Advanced Configuration** - Per-specialist settings, performance tuning
6. **Technical Architecture** - How investigation works under the hood
**Tone:** Professional, technical but clear. Explains technical concepts in context.
### Document 3: Customization Guide
**Audience:** Developers, pro users extending Auto Claude
**Focus:** System customization, prompts, context injection
**Sections:**
1. **Overview** - Who this is for (developers extending Auto Claude)
2. **Prompt System Architecture** - How agent prompts are structured
3. **Context Injection System** - How context is built and passed to agents
4. **Customizing Agent Prompts** - Modifying XML prompt files
- Finding the prompt files
- Prompt structure and variables
- Creating custom investigation specialists
5. **Context Configuration** - Customizing what data is included
- File selection patterns
- Context window management
- Repository context settings
6. **Adding Custom Specialists** - Creating new investigation agents
7. **Extending the Integration** - Hooks, custom providers
8. **Examples & Recipes** - Common customizations
**Tone:** Developer-to-developer, technical, code-heavy, minimal hand-holding.
## Content Approach
### Progressive Disclosure
- Each document builds on the previous one
- Clear navigation links between documents
- Users can enter at their appropriate level
### Writing Style Guidelines
| Document | Tone | Language | Example Style |
|----------|------|----------|---------------|
| User Guide | Friendly, encouraging | Plain English | "Think of AI investigation as having a senior developer analyze the issue for you" |
| Advanced Config | Professional, technical | Terms explained in context | "Fast Mode uses optimized token generation to reduce investigation time by 2.5x" |
| Customization | Developer-to-developer | Technical, code-heavy | "Modify the `<system_context>` variable in `prompts/github/root_cause.xml`" |
### Code & Configuration Examples
- **Doc 1:** Simple copy-paste examples, UI navigation
- **Doc 2:** Configuration snippets, environment variables
- **Doc 3:** Full XML/Python examples, file paths, code blocks
## Visual Elements
### Screenshots (Hybrid Approach)
**User Guide:**
1. GitHub Issues main UI (issue list, filters, actions)
2. Issue detail view (comments, labels, "Investigate" button)
3. Investigation in progress (4 parallel specialists)
4. Investigation results (completed report)
5. Settings screen (GitHub auth, repo connection, Fast Mode toggle)
**Advanced AI Config:**
1. Settings → AI Investigation panel (configurable options)
2. Token usage display (cost visibility)
3. Investigation pipeline flowchart (issue → 4 specialists → report)
**Customization Guide:**
1. Directory structure diagram (prompt file locations)
2. Annotated XML prompt file (variables and structure)
3. Context injection flow diagram
4. Code snippets throughout
### Diagram Style
- Clean, simple flowcharts
- Consistent color scheme: Blue (user actions), Green (AI agents), Orange (data flow)
- Minimal text, focus on flow and relationships
## Navigation & Cross-References
### Linking Strategy
**User Guide → Deeper:**
- "For detailed configuration, see [Advanced AI Configuration]"
- "Learn how the 4 specialists work in [Advanced AI Configuration]"
- "Want to customize agent behavior? See [Customization Guide]"
**Advanced AI Config → Both Directions:**
- "New to GitHub Issues? Start with the [User Guide]"
- "Want to modify agent prompts? See [Customization Guide]"
**Customization Guide → Reference:**
- "Assumes familiarity with concepts from [User Guide] and [Advanced AI Config]"
### Navigation Aids
- Table of Contents at the top of each document
- "In this section" callouts at the start of major sections
- "Next steps" boxes at the end of each workflow section
### External References
- `guides/opus-4.6-features.md` - Opus 4.6 details (don't duplicate)
- `ARCHITECTURE.md` - System architecture
- GitHub CLI docs - Authentication setup
## Key Emphasis
**Integration Workflow** is the primary focus across all documents:
> **Import Issues** → **AI Investigation** → **Create Task** → **Implement** → **Merge**
This pipeline demonstrates the core value of Auto Claude - connecting GitHub issues to autonomous development.
## File Organization
### Naming Convention
- Lowercase with hyphens (matches existing documentation style)
- Descriptive names indicating audience and content
- Keep under 80 characters for GitHub rendering
### README.md (Index Page)
```markdown
# GitHub Issues Documentation
Choose the guide that matches your needs:
📖 **[User Guide](github-issues-user-guide.md)** - Get started with GitHub Issues integration
For: All users | Focus: Using the features
⚙️ **[Advanced AI Configuration](github-issues-advanced-ai-configuration.md)** - Optimize AI investigations
For: Technical users | Focus: Performance, costs, Opus 4.6
🔧 **[Customization Guide](github-issues-customization-guide.md)** - Extend and customize the system
For: Developers | Focus: Prompts, context, customization
```
## Markdown Format Guidelines
- Standard GitHub-flavored markdown
- H1 for title, H2 for main sections, H3 for subsections
- Code blocks with language specification (`xml`, `python`, `bash`)
- Callout boxes using `> **Note:**` format
- Internal links use relative paths
- Front matter with title and description metadata
## Implementation Notes
### Content Sources
- `apps/frontend/src/renderer/components/github-issues/` - UI components
- `apps/frontend/src/main/ipc-handlers/github/` - IPC handlers
- `apps/backend/runners/github/` - Backend services
- `guides/opus-4.6-features.md` - Reference for Opus 4.6 details
- Existing code comments and docstrings
### Screenshots to Capture
- Need to run the application in development mode (`npm run dev`)
- Capture each UI state listed in Visual Elements section
- Save to `guides/github-issues/images/` with descriptive names
### Diagram Creation
- Use Mermaid syntax for flowcharts (if supported by docs build)
- Alternatively, describe for manual creation with diagram tools
## Success Criteria
1. ✅ All three documents created in `guides/github-issues/`
2. ✅ README.md index page created
3. ✅ Progressive structure allows users to enter at appropriate level
4. ✅ Integration workflow is clear and emphasized
5. ✅ Screenshots included for key UI states
6. ✅ Cross-references enable navigation between documents
7. ✅ Writing style matches target audience for each document
8. ✅ Content is accurate based on actual codebase features
## Next Steps
1. Create implementation plan using writing-plans skill
2. Set up directory structure
3. Draft content for each document
4. Capture screenshots
5. Create diagrams
6. Review and refine
7. Commit to repository
File diff suppressed because it is too large Load Diff
+231
View File
@@ -1,3 +1,234 @@
## 2.7.6 - Stability & Feature Enhancements
### ✨ New Features
- **Multi-profile account management** — Unified profile swapping with automatic token refresh and rate limit recovery for both OAuth and API-compatible providers
- **Enhanced terminal experience** — Customizable terminal fonts with OS-specific defaults, Claude Code CLI settings injection, and improved worktree integration
- **Advanced roadmap management** — Expand/collapse functionality for phase features and real-time sync with task lifecycle
- **Queue System v2** — Smart task prioritization with auto-promotion and intelligent rate limit recovery
- **GitHub integration enhancements** — AI-powered PR template generation, user-friendly API error handling, and improved review visibility
- **UI/UX improvements** — Spell check support for text inputs, collapsible sidebar toggle, task screenshot capture, expandable task descriptions, and bulk worktree operations
- **Evidence-based PR validation** — Advanced review system with trigger-driven exploration and enhanced recovery mechanisms
### 🛠️ Improvements
- **Performance optimizations** — Async parallel worktree listing prevents UI freezes and improves responsiveness
- **Robustness enhancements** — Atomic file writes, better error detection in AI responses, and improved OOM/orphaned agent management for overnight builds
- **Terminal stability** — Fixed GPU context exhaustion from large pastes, SIGABRT crashes on macOS shutdown, and session restoration on app restart
- **Build & packaging** — XState bundling for packaged apps, aligned Linux package builds, and improved auto-updater for beta releases and DMG installations
- **Diagnostic improvements** — Sentry instrumentation for Python subprocesses and better error tracking across the system
### 🐛 Bug Fixes
- **Terminal & PTY** — Fixed paste size limits, race conditions, rendering issues, text alignment, worktree crashes, and terminal content resizing on expansion
- **PR review system** — Resolved error visibility in bundled apps, improved structured output validation with three-tier recovery, preserved findings during crashes, and fixed UTC timestamp detection for comment tracking
- **Planning & task execution** — Fixed handling of empty/greenfield projects, atomic writes to prevent 0-byte file corruption, planning phase crashes, and implementation plan file watching
- **Authentication & profiles** — Resolved OAuth token revocation loops, API profile mode support without OAuth requirement, subscription type preservation during token refresh, and Linux credential file detection
- **Windows/cross-platform** — Complete System32 executable path fixes for where.exe and taskkill.exe, Windows credential normalization, and proper shell detection for Windows terminals
- **Agent management** — Fixed infinite retry loops for tool concurrency errors, auth error detection, and title generator production path resolution
- **UI/UX fixes** — Resolved Insights scroll-to-blank-space issues, infinite re-render loops in terminal font settings, kanban board scaling collisions, ideation stuck states, and panel constraint errors during terminal exit
- **Worktree & Git** — Improved branch pattern validation, removed auto-commit on deletion, support for detached HEAD state during PR creation, and better merge conflict resolution with progress tracking
- **Integrations** — Fixed Ollama infinite subprocess spawning, Graphiti import paths, OpenRouter API URL suffix, and GitLab authentication bugs
- **Settings & configuration** — Corrected .auto-claude path discovery timeout, z.AI China preset URL, log order sorting, and onboarding completion state persistence
### 📚 Documentation
- Added Awesome Claude Code badge to README
- Added instructions for resetting PR review state in CLAUDE.md
---
## What's Changed
- fix: handle unknown SDK message types (rate_limit_event) to prevent session crashes by @AndyMik90 in 4a75ea9f9
- fix: PR review error visibility and gh CLI resolution in bundled apps by @AndyMik90 in 732fc1cd3
- fix: handle empty/greenfield projects in spec creation (#1426) (#1841) by @Andy in 819f98d9f
- fix: clear terminalEventSeen on task restart to prevent stuck-after-planning (#1828) (#1840) by @Andy in 28a620079
- fix: watch worktree path for implementation_plan.json changes (#1805) (#1842) by @Andy in fb3a3fbda
- fix: resolve Claude CLI not found on Windows - PATH, prompt size, cwd (#1661) (#1843) by @Andy in 76d1d3b03
- fix: handle planning phase crash and resume recovery (#1562) (#1844) by @Andy in 3cb05781f
- fix: show dismissed PR review findings in UI instead of silently dropping them (#1852) by @Andy in d98ff7d19
- fix: preserve file/line info in PR review extraction recovery (#1857) by @Andy in 635b53eea
- docs: add Awesome Claude Code badge to README (#1838) by @Andy in 2e4b5ac65
- test: achieve 100% test coverage for backend CLI commands (#1772) by @StillKnotKnown in 385f04414
- fix: cap terminal paste size to 1MB to prevent GPU context exhaustion by @AndyMik90 in 7b0f3a2c0
- fix: prevent OOM, orphaned agents, and unbounded growth during overnight builds (#1813) by @Andy in 4091d1d4b
- docs: add instructions for resetting PR review state in CLAUDE.md by @AndyMik90 in ecb615802
- auto-claude: 217-investigate-symlink-issues-in-work-tree-creation-f (#1808) by @Andy in ae13ce14c
- auto-claude: 218-enable-claude-code-features-in-worktree-terminals (#1809) by @Andy in e3b219288
- auto-claude: 219-investigate-and-fix-authentication-subscription-sy (#1810) by @Andy in 6204d5fc2
- feat(roadmap): add expand/collapse functionality for phase features (#1796) by @Burak in f735f0b49
- auto-claude: 216-display-ongoing-pr-review-logs-in-progress (#1807) by @Andy in a4870fa0c
- fix(pr-review): reduce structured output failures and preserve findings in recovery (#1806) by @Andy in f1b8cd3a7
- fix(sentry): enable Sentry for Python subprocesses and add diagnostic instrumentation (#1804) by @Andy in 4d4234378
- fix(pr-review): add three-tier recovery for structured output validation failure (#1797) by @Andy in d1fbccde3
- test: improve backend agent test coverage to 94% (#1779) by @StillKnotKnown in ed93df698
- fix(github): use UTC timestamps for reviewed_at to fix comment detection (#1795) by @Andy in 8872d33e3
- feat: add user-friendly GitHub API error handling (#1790) by @StillKnotKnown in 8ece0009e
- fix(roadmap): sync roadmap features with task lifecycle (#1791) by @Andy in 115576e85
- fix(github): resolve PR review hanging in bundled app (#1793) by @Andy in 3791b37bb
- feat(profiles): implement unified profile swapping across OAuth and API accounts (#1794) by @StillKnotKnown in 282387356
- test: improve backend memory system test coverage to 100% (#1780) by @StillKnotKnown in 4f1b7b2a9
- fix(ideation): guard against non-string properties in IdeaCard badges by @AndyMik90 in 5e78d748e
- fix(updater): convert HTML release notes to markdown before rendering by @AndyMik90 in aa5fc7f95
- fix(pr-review): simplify structured output schema to reduce validation failures (#1787) by @Andy in cd8914700
- fix(qa): enforce visual verification for UI changes and inject startup commands (#1784) by @Andy in f149a7fbd
- fix(plan-files): use atomic writes to prevent 0-byte corruption (#1785) by @Andy in c2245b812
- fix(terminal): make worktree dropdown scrollable and show all items by @AndyMik90 in 950da45e4
- auto-claude: subtask-1-1 - Add adaptive thinking badge to thinking level label (#1782) by @Andy in 25acf2826
- auto-claude: subtask-1-1 - Add overflow-hidden and break-words to subtask cards by @AndyMik90 in 39aa08872
- refactor(app-updater): disable automatic downloads and allow intentional downgrades by @AndyMik90 in 8de8039db
- fix(auth): detect auth errors in AI response text and prevent retry loops (#1776) by @Andy in f4788e4af
- test: achieve 100% coverage for backend core workspace module (#1774) by @StillKnotKnown in 3f95765cf
- fix(title-generator): add production path resolution for backend source (#1778) by @Andy in 923880f5b
- fix(fast-mode): use setting_sources instead of env var for CLI fast mode (#1771) by @Andy in 390ba6a58
- fix(windows): complete System32 executable path fixes for where.exe and taskkill.exe (#1715) by @VDT-91 in aa7f56e5d
- fix(worktree): remove auto-commit on deletion and add uncommitted changes warning by @AndyMik90 in cec8e65ee
- Smart PR Status Polling System (#1766) by @Andy in 48d5f7a32
- feat: simplify thinking system and remove opus-1m model variant (#1760) by @Andy in bb7e18937
- auto-claude: 203-fix-pr-review-ui-update-issue (#1732) by @Andy in 7589f8e4f
- auto-claude: subtask-2-1 - Create isAPIProfileAuthenticated() function to val (#1745) by @Andy in 57e38a692
- auto-claude: 202-fix-kanban-board-scaling-collisions (#1731) by @Andy in d09ebb850
- auto-claude: 204-fix-pr-review-ui-not-updating-without-manual-navig (#1734) by @Andy in 087091cef
- auto-claude: 203-fix-ui-not-updating-during-pr-review-operations (#1733) by @Andy in f085c08bd
- auto-claude: 205-fix-insights-chat-only-shows-last-task-suggestion- (#1735) by @Andy in f121f9cdd
- auto-claude: 197-roadmap-generation-stuck-at-50-file-locking-race-c (#1746) by @Andy in f41f15e59
- auto-claude: 193-fix-update-context7-mcp-tool-name-from-get-library (#1744) by @Andy in bdff9141a
- auto-claude: 192-changelog-generation-multiple-critical-bugs-tasks- (#1725) by @Andy in 8c9a504df
- auto-claude: 194-bug-rate-limit-during-task-execution-causes-subtas (#1726) by @Andy in 8a7443d24
- auto-claude: 201-bug-pr-review-logs-and-analysis (#1730) by @Andy in e0d53adb4
- auto-claude: 196-fix-worktrees-dialog-auto-close-race-condition-and (#1727) by @Andy in 323b0d3be
- auto-claude: 199-bug-logs-disappear-after-restart (#1728) by @Andy in d639f6ef8
- auto-claude: 198-critical-oauth-token-revocation-causes-infinite-40 (#1747) by @Andy in 4438c0b10
- Fix Panel Constraints Error During Terminal Exit (#1757) by @Andy in 32bf353da
- auto-claude: 190-bug-context-page-crash-multiple-root-causes-when-v (#1724) by @Andy in 2db36982f
- feat: add search/filter to WorktreeSelector dropdown (#1754) by @Andy in 09f059ca3
- fix(terminal): push worktree branch to remote with tracking on creation (#1753) by @Andy in b5de0d9ff
- auto-claude: 189-subtask-execution-stuck-in-infinite-retry-loop-whe (#1723) by @Andy in 445da186c
- auto-claude: 188-terminal-claude-sessions-require-manual-click-to-r (#1743) by @Andy in f8499e965
- auto-claude: 200-bug-changelog-and-release-generation (#1729) by @Andy in 826583b82
- fix(terminal): use each terminal's cwd for invoke Claude all button (#1756) by @Andy in ac4fe4f42
- feat(terminal): read Claude Code CLI settings and inject env vars into PTY sessions (#1750) by @Andy in 152e54093
- fix: correct .auto-claude path mismatch causing discovery phase timeout (#1748) by @VDT-91 in 2c2a8a754
- fix: remove incorrect /v1 suffix from OpenRouter API URL (#1749) by @StillKnotKnown in 7e799ee57
- fix: prevent terminal worktree crash with race condition fixes (#1586) (#1658) by @VDT-91 in 216b58bcf
- fix: correct log order sorting and add configurable log order setting (#1720) by @Burak in 2e2b82365
- fix(ollama): stop infinite subprocess spawning from useEffect re-render loop (#1716) by @Quentin Veys in acb131b72
- fix(graphiti): migrate graphiti_memory imports to canonical paths (#1714) by @Quentin Veys in df528f065
- fix: improve auto-updater for beta releases and DMG installs (#1681) by @Andy in ff91a1af0
- feat: unified operation registry for intelligent auth/rate limit recovery (#1698) by @Andy in 6d0222fa9
- fix: Prevent stale worktree data from overriding correct task status (#1710) by @Burak in fe08c644c
- feat: add subscriptionType and rateLimitTier to ClaudeProfile (#1688) by @Andy in a5e3cc9a2
- auto-claude: subtask-1-1 - Add useTaskStore import and update task state after successful PR creation (#1683) by @Andy in 4587162e4
- auto-claude: 182-implement-pagination-and-filtering-for-github-pr-l (#1654) by @Andy in b4e6b2fe4
- auto-claude: 181-add-expand-button-for-long-task-descriptions (#1653) by @Andy in d9cd300fe
- fix(terminal): resolve text alignment issues on expand/minimize (#1650) by @VDT-91 in f5a7e26d9
- fix(windows): use full path to where.exe for reliable executable lookup (#1659) by @VDT-91 in 5f63daa3c
- fix: resolve ideation stuck at 3/6 types bug (#1660) by @VDT-91 in e6e8da17c
- Clarify Local and Origin Branch Distinction (#1652) by @Andy in 9317148b6
- auto-claude: 186-set-default-dark-mode-on-startup (#1656) by @Andy in 473020621
- auto-claude: subtask-1-1 - Add min-h-0 to enable scrolling in Roadmap tabs (#1655) by @Andy in ae703be9f
- fix: XState status lifecycle & cross-project contamination fixes (#1647) by @kaigler in 5293fb399
- refactor(frontend): complete XState task state machine migration (#1338) (#1575) by @kaigler in e2f9abadb
- Merge conflict resolution progress bar and log viewer (#1620) by @Andy in d16be3077
- fix: align Linux package builds (AppImage/deb/Flatpak) with target-specific extraResources (#1623) by @StillKnotKnown in bad1a9b2c
- Fix/gitlab bugs (#1519 and #1521) (#1544) by @bu5hm4nn in cd423c65c
- feat(kanban): add bulk task delete and worktree cleanup improvements (#1588) by @kaigler in 02ed91c91
- fix: add worktree isolation warning to prevent agent escape (#1528) by @kaigler in fe5cc582b
- feat(ui): add spell check support for text inputs (#1304) by @kaigler in 8f02a5129
- fix(windows): complete Windows credential fixes with path normalization (#1585) by @kaigler in 1e1997167
- AI-Powered GitHub PR Template Generation (#1618) by @Andy in 900dd4360
- Fix pty.node SIGABRT crash on macOS shutdown (#1619) by @Andy in f355e09d7
- fix(merge): use git merge for diverged branches with progress tracking (#1605) by @Andy in bde2ca4b2
- Surface Billing/Credit Exhaustion Errors to UI (Issue #1580) (#1617) by @Andy in 7bf12e856
- auto-claude: subtask-1-1 - Change $teamId type from ID! to String! in the team query (#1627) by @Andy in 54d0cd2f4
- fix(auth): support API profile mode without OAuth requirement (#1616) by @StillKnotKnown in f8cc63af4
- fix: agent retry loop for tool concurrency errors (#1546) [v3] (#1606) by @Michael Ludlow in 0aea4fb5e
- fix(queue): enforce max parallel tasks and auto-refresh UI (#1594) by @Andy in 4070a4c29
- Persist Kanban column collapse state per project via main process (#1579) by @Andy in a1114664e
- feat(pr-review): evidence-based validation and trigger-driven exploration (#1593) by @Andy in bfc232825
- fix(ui): smart auto-scroll for Insights streaming responses (#1591) by @kaigler in eee97e7ea
- fix(changelog): validate Claude CLI exists before generation (#1305) by @kaigler in c1f24c07f
- auto-claude: subtask-1-1 - Add min-w-0 class to subtask title row flex container (#1578) by @Andy in 286591c02
- auto-claude: subtask-1-1 - Remove Popover wrapper and related functionality from ClaudeCodeStatusBadge (#1566) by @Andy in 8d18cc81a
- fix(claude-profile): preserve subscriptionType and rateLimitTier during token refresh (#1556) by @Andy in 52e426a48
- auto-claude: subtask-1-1 - Update cancelReview callback to handle both success and failure cases (#1551) by @Andy in d8f00fe5a
- fix(backend): prioritize git remote detection over env var for repo (#1555) by @Andy in 9b07ed464
- fix(backend): handle detached HEAD state when pushing branch for PR creation (#1560) by @Andy in 2b72694d0
- fix: add explicit UTF-8 encoding across all Electron main process I/O (#1554) by @Andy in 4243530e9
- fix(backend): pass OAuth token to Python subprocess for authentication by @AndyMik90 in 6f1002dd7
- perf(frontend): async parallel worktree listing to prevent UI freezes (#1553) by @Andy in 399a7e736
- auto-claude: subtask-1-1 - Remove amber lock indicator line from kanban resize handle (#1557) by @Andy in 83a64b88e
- fix(frontend): resolve TerminalFontSettings infinite re-render loop (#1536) by @StillKnotKnown in 1c6266025
- fix(frontend): respect hasCompletedOnboarding from ~/.claude.json (#1537) by @StillKnotKnown in 1860c2c43
- fix: prevent planner from generating invalid verification types (#1388) (#1529) by @kaigler in 94d941333
- fix(frontend): resolve Insights scroll-to-blank-space issue on macOS (ACS-382) (#1535) by @StillKnotKnown in 496b2b96a
- feat: add customizable terminal fonts with OS-specific defaults (#1412) by @StillKnotKnown in f289107b8
- Add dev mode screenshot capture warning (#1516) by @Andy in 16eeb301a
- fix: add worktree isolation warnings to prevent agent escape (ACS-394) (#1495) by @StillKnotKnown in 1e453653b
- fix: resolve flaky subprocess-spawn test on Windows CI (ACS-392) (#1494) by @StillKnotKnown in f6b264d56
- feat(task-logger): strip ANSI escape codes from logs and extend coverage (#1411) by @StillKnotKnown in 988ec0c25
- fix(frontend): use spawn() instead of exec() for Windows terminal launching (#1498) by @StillKnotKnown in 26c9083d3
- fix(api-profiles): correct z.AI China preset URL and rename provider presets (#1500) by @StillKnotKnown in 05cf0a516
- fix: validate branch pattern before worktree cleanup to prevent deleting wrong branch (#1493) by @StillKnotKnown in 8576754a1
- Real-Time Updates for Insights Chat (#1511) by @Andy in d940b6ade
- Fix Terminal UI Rendering Issues (#1514) by @Andy in 8d8306b8e
- Fix terminal content resizing on expansion (#1512) by @Andy in 9f6c0026b
- Restore Terminal Session History on App Restart (#1515) by @Andy in 63e2847fc
- Move Reference Images Above Task Title & Fix Image Display Issues (#1513) by @Andy in b269ac305
- auto-claude: 143-fix-github-integration-ui-refresh-issues (#1467) by @Andy in aa2cb4fa6
- feat: Multi-profile account swapping with token refresh and queue routing (#1496) by @Andy in 1e72c8d77
- Simplified Testing Strategy for Regression Prevention (#1379) by @Andy in ae4e48e8b
- auto-claude: 152-persist-tasks-during-roadmap-regeneration (#1463) by @Andy in 9bd3d7e3b
- Debug Kanban Memory & Add Sentry Monitoring (#1380) by @Andy in bc5f550ee
- auto-claude: 147-remove-outdated-compatibility-shims (#1465) by @Andy in 53111dbb9
- auto-claude: 162-fix-worktree-error-on-repeated-task-starts (#1453) by @Andy in b955badf7
- auto-claude: 155-fix-pr-list-diff-display-metrics (#1458) by @Andy in 31f116db5
- auto-claude: 151-fix-pr-review-agent-token-refresh-on-account-swap (#1456) by @Andy in d081af042
- auto-claude: 148-add-progress-persistence-and-status-indicators (#1464) by @Andy in 4937d5745
- auto-claude: 154-fix-task-modal-conflict-check-status-refresh (#1462) by @Andy in 0299009df
- auto-claude: 153-widen-kanban-columns-and-add-collapse-feature (#1457) by @Andy in d65973075
- auto-claude: subtask-1-1 - Add filter after map operation to remove empty str (#1466) by @Andy in 783f0fe0e
- fix: add formatReleaseNotes helper for markdown changelog rendering (#1468) by @Andy in 43a97e1b3
- feat(sidebar): add collapsible sidebar toggle (#1501) by @Michael Ludlow in d17c17887
- fix(auth): check .credentials.json for Linux profile authentication (#1492) by @StillKnotKnown in 8d2f66291
- auto-claude: subtask-1-1 - Replace ReleaseNotesRenderer with ReactMarkdown (#1454) by @Andy in 1185a558c
- auto-claude: 156-fix-electron-app-version-detection-bug (#1459) by @Andy in 9a3b48c25
- auto-claude: subtask-1-1 - Add --no-track flag to git worktree add command (#1455) by @Andy in 0c2990815
- auto-claude: subtask-1-1 - Change task.specId to taskId in 3 startSpecCreation calls (#1461) by @Andy in 91edc0e14
- fix(onboarding): align MemoryStep layout with Settings MemoryBackendSection (#1445) by @Michael Ludlow in e9de26d59
- auto-claude: subtask-1-1 - Add metadata?.requireReviewBeforeCoding check (#1460) by @Andy in 426d56571
- fix: use API profile environment variables for task title generation (#1471) by @JoshuaRileyDev in c5a0f042d
- fix(auth): Long-lived OAuth authentication with multi-profile usage display (#1443) by @Andy in 12e788417
- feat: Add screenshot capture to task creation modal (#1429) by @JoshuaRileyDev in 1a2a1b1fc
- fix: prevent queue settings modal from disappearing when tasks change (#1430) by @JoshuaRileyDev in 33acc1430
- feat: Queue System v2 with Auto-Promotion and Smart Task Management (#1203) by @JoshuaRileyDev in 3b87e24d7
- feat: Add API profile providers usage endpoints support (#1279) by @StillKnotKnown in cfe7dedd0
## Thanks to all contributors
@AndyMik90, @Andy, @Burak, @StillKnotKnown, @VDT-91, @kaigler, @Michael Ludlow, @JoshuaRileyDev, @Quentin Veys, @bu5hm4nn
## 2.7.5 - Security & Platform Improvements
### ✨ New Features
+40 -22
View File
@@ -30,27 +30,55 @@ Auto Claude is a desktop application (+ CLI) where users describe a goal and AI
## Critical Rules
**Claude Agent SDK only** — All AI interactions use `claude-agent-sdk`. NEVER use `anthropic.Anthropic()` directly. Always use `create_client()` from `core.client`.
**Claude Agent SDK only** — All AI interactions use `claude-agent-sdk` because it handles security hooks, tool permissions, and MCP server integration. Use `create_client()` from `core.client`, not `anthropic.Anthropic()` directly.
**i18n required** — All frontend user-facing text MUST use `react-i18next` translation keys. Never hardcode strings in JSX/TSX. Add keys to both `en/*.json` and `fr/*.json`.
**i18n required** — All frontend user-facing text uses `react-i18next` translation keys. Hardcoded strings in JSX/TSX break localization for non-English users. Add keys to both `en/*.json` and `fr/*.json`.
**Platform abstraction**Never use `process.platform` directly. Import from `apps/frontend/src/main/platform/` or `apps/backend/core/platform/`. CI tests all three platforms.
**Platform abstraction**Use the platform modules in `apps/frontend/src/main/platform/` or `apps/backend/core/platform/` instead of `process.platform` directly. CI tests all three platforms, and raw platform checks cause failures.
**No time estimates**Never provide duration predictions. Use priority-based ordering instead.
**No time estimates**Provide priority-based ordering instead of duration predictions.
**PR target** — Always target the `develop` branch for PRs to AndyMik90/Auto-Claude, NOT `main`.
**PR target** — Always target the `develop` branch for PRs, not `main`. Main is reserved for releases.
## Work Approach
**No console.log in production code**`console.log` output is invisible in bundled Electron apps. Use Sentry for error tracking in production; reserve `console.log` for development only.
**Investigate before speculating** — Always read the actual code before proposing root causes. Spawn agents to grep and read relevant source files before forming any hypothesis. Never guess at causes without evidence from the codebase.
## Work Approach: Orchestrator-First
**Spawn agents for complex tasks** — When tackling complex tasks, spawn sub-agents/agent teams immediately rather than trying to handle everything in a single context window. Never attempt to analyze large codebases or multiple features monolithically.
You are an orchestrator. Your primary role is to understand what needs to be done, break it into workstreams, and delegate execution to agent teams. This keeps your context window focused on coordination and decision-making rather than filling up with implementation details.
**Minimal fixes only** — Prefer the simplest approach (e.g., prompt-only changes, single guard clause) before suggesting multi-component solutions. If the user asks for X, implement X — don't bundle additional fixes they didn't request.
<orchestrator_pattern>
When given a task, follow this pattern:
1. **Investigate first** — Read the actual code before forming any hypothesis. Use targeted searches (Glob, Grep, Read) for simple lookups. For broader exploration, spawn an Explore agent.
2. **Plan the approach** — Identify what needs to change, which files are involved, and whether work can be parallelized. For multi-step tasks, create a task list to track workstreams.
3. **Delegate execution** — Spawn agent teams to do the implementation work. Each agent gets a clear, self-contained assignment with all the context it needs: relevant file paths, the specific change to make, and acceptance criteria. Run independent workstreams in parallel.
4. **Verify and integrate** — Review agent outputs, run tests, and ensure changes work together. Fix integration issues or spawn follow-up agents as needed.
</orchestrator_pattern>
**When to delegate vs. do directly:**
- Delegate: multi-file changes, research across the codebase, independent parallel workstreams, tasks that would consume significant context
- Do directly: single-file edits, simple bug fixes, quick lookups, tasks where you already have the context
**Giving agents good assignments** — Each agent works with a fresh context. Include: the specific goal, relevant file paths, code patterns to follow, and what "done" looks like. Agents perform better with explicit, complete instructions than with vague references to "the current task."
**Minimal changes only** — Prefer the simplest approach (e.g., prompt-only changes, single guard clause) before suggesting multi-component solutions. If the user asks for X, implement X — don't bundle additional fixes they didn't request.
**Default to action** — When the user's intent implies making changes, implement them rather than only suggesting. If something is unclear, read the relevant code to fill in the gaps rather than asking. Only ask when genuine ambiguity remains about what the user wants.
## Context Management
Your context window will be automatically compacted as it approaches its limit, allowing you to continue working indefinitely. Do not stop tasks early due to context concerns — instead, persist progress and keep going.
**For long-running tasks:** Use git commits, task lists, and structured notes to track state. When context compacts, review git log and any progress files to re-orient. Focus on incremental progress — complete one component before moving to the next, and commit working states along the way.
**Parallel tool calls** — When reading multiple files, running independent searches, or executing unrelated commands, make all calls in parallel rather than sequentially. This significantly speeds up investigation and implementation.
## Known Gotchas
**Electron path resolution** — For bug fixes in the Electron app, always check path resolution differences between dev and production builds (`app.isPackaged`, `process.resourcesPath`). Paths that work in dev often break when Electron is bundled for production — verify both contexts.
**Electron path resolution** — For bug fixes in the Electron app, check path resolution differences between dev and production builds (`app.isPackaged`, `process.resourcesPath`). Paths that work in dev often break when Electron is bundled for production — verify both contexts.
### Resetting PR Review State
@@ -60,6 +88,7 @@ To fully clear all PR review data so reviews run fresh, delete/reset these three
2. `rm .auto-claude/github/pr/review_*.json` — review result files
3. Reset `pr/index.json` to `{"reviews": [], "last_updated": null}`
4. Reset `bot_detection_state.json` to `{"reviewed_commits": {}}` — this is the gatekeeper; without clearing it, the bot detector skips already-seen commits
## Project Structure
```
@@ -161,17 +190,6 @@ Each spec in `.auto-claude/specs/XXX-name/` contains: `spec.md`, `requirements.j
Graph-based semantic memory in `integrations/graphiti/`. Configured through the Electron app's onboarding/settings UI (CLI users can alternatively set `GRAPHITI_ENABLED=true` in `.env`). See [ARCHITECTURE.md](shared_docs/ARCHITECTURE.md#memory-system) for details.
### Opus 4.6 Features
Auto Claude leverages Opus 4.6's advanced capabilities for GitHub issue investigations:
- **Fast Mode:** 2.5x faster investigations (toggle in Settings > GitHub > AI Investigation)
- **128K Output Tokens:** Root cause specialist gets max tokens for deep analysis
- **Per-Specialist Limits:** Different token limits per investigation specialist
- **Adaptive Thinking:** High-effort mode for thorough investigations
See [guides/opus-4.6-features.md](guides/opus-4.6-features.md) for detailed documentation on Opus 4.6 features, pricing, and usage.
## Frontend Development
### Tech Stack
@@ -286,7 +304,7 @@ Supports Windows, macOS, Linux. CI tests all three.
| `findExecutable(name)` | Cross-platform executable lookup |
| `requiresShell(command)` | `.cmd/.bat` shell detection (Win) |
Never hardcode paths. Use `findExecutable()` and `joinPaths()`. See [ARCHITECTURE.md](shared_docs/ARCHITECTURE.md#cross-platform-development) for extended guide.
Use `findExecutable()` and `joinPaths()` instead of hardcoded paths. See [ARCHITECTURE.md](shared_docs/ARCHITECTURE.md#cross-platform-development) for extended guide.
## E2E Testing (Electron MCP)
+14 -14
View File
@@ -17,18 +17,18 @@
### Stable Release
<!-- STABLE_VERSION_BADGE -->
[![Stable](https://img.shields.io/badge/stable-2.7.5-blue?style=flat-square)](https://github.com/AndyMik90/Auto-Claude/releases/tag/v2.7.5)
[![Stable](https://img.shields.io/badge/stable-2.7.6-blue?style=flat-square)](https://github.com/AndyMik90/Auto-Claude/releases/tag/v2.7.6)
<!-- STABLE_VERSION_BADGE_END -->
<!-- STABLE_DOWNLOADS -->
| Platform | Download |
|----------|----------|
| **Windows** | [Auto-Claude-2.7.5-win32-x64.exe](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.5/Auto-Claude-2.7.5-win32-x64.exe) |
| **macOS (Apple Silicon)** | [Auto-Claude-2.7.5-darwin-arm64.dmg](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.5/Auto-Claude-2.7.5-darwin-arm64.dmg) |
| **macOS (Intel)** | [Auto-Claude-2.7.5-darwin-x64.dmg](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.5/Auto-Claude-2.7.5-darwin-x64.dmg) |
| **Linux** | [Auto-Claude-2.7.5-linux-x86_64.AppImage](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.5/Auto-Claude-2.7.5-linux-x86_64.AppImage) |
| **Linux (Debian)** | [Auto-Claude-2.7.5-linux-amd64.deb](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.5/Auto-Claude-2.7.5-linux-amd64.deb) |
| **Linux (Flatpak)** | [Auto-Claude-2.7.5-linux-x86_64.flatpak](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.5/Auto-Claude-2.7.5-linux-x86_64.flatpak) |
| **Windows** | [Auto-Claude-2.7.6-win32-x64.exe](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.6/Auto-Claude-2.7.6-win32-x64.exe) |
| **macOS (Apple Silicon)** | [Auto-Claude-2.7.6-darwin-arm64.dmg](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.6/Auto-Claude-2.7.6-darwin-arm64.dmg) |
| **macOS (Intel)** | [Auto-Claude-2.7.6-darwin-x64.dmg](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.6/Auto-Claude-2.7.6-darwin-x64.dmg) |
| **Linux** | [Auto-Claude-2.7.6-linux-x86_64.AppImage](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.6/Auto-Claude-2.7.6-linux-x86_64.AppImage) |
| **Linux (Debian)** | [Auto-Claude-2.7.6-linux-amd64.deb](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.6/Auto-Claude-2.7.6-linux-amd64.deb) |
| **Linux (Flatpak)** | [Auto-Claude-2.7.6-linux-x86_64.flatpak](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.6/Auto-Claude-2.7.6-linux-x86_64.flatpak) |
<!-- STABLE_DOWNLOADS_END -->
### Beta Release
@@ -36,18 +36,18 @@
> ⚠️ Beta releases may contain bugs and breaking changes. [View all releases](https://github.com/AndyMik90/Auto-Claude/releases)
<!-- BETA_VERSION_BADGE -->
[![Beta](https://img.shields.io/badge/beta-2.7.6--beta.5-orange?style=flat-square)](https://github.com/AndyMik90/Auto-Claude/releases/tag/v2.7.6-beta.5)
[![Beta](https://img.shields.io/badge/beta-2.7.6--beta.6-orange?style=flat-square)](https://github.com/AndyMik90/Auto-Claude/releases/tag/v2.7.6-beta.6)
<!-- BETA_VERSION_BADGE_END -->
<!-- BETA_DOWNLOADS -->
| Platform | Download |
|----------|----------|
| **Windows** | [Auto-Claude-2.7.6-beta.5-win32-x64.exe](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.6-beta.5/Auto-Claude-2.7.6-beta.5-win32-x64.exe) |
| **macOS (Apple Silicon)** | [Auto-Claude-2.7.6-beta.5-darwin-arm64.dmg](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.6-beta.5/Auto-Claude-2.7.6-beta.5-darwin-arm64.dmg) |
| **macOS (Intel)** | [Auto-Claude-2.7.6-beta.5-darwin-x64.dmg](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.6-beta.5/Auto-Claude-2.7.6-beta.5-darwin-x64.dmg) |
| **Linux** | [Auto-Claude-2.7.6-beta.5-linux-x86_64.AppImage](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.6-beta.5/Auto-Claude-2.7.6-beta.5-linux-x86_64.AppImage) |
| **Linux (Debian)** | [Auto-Claude-2.7.6-beta.5-linux-amd64.deb](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.6-beta.5/Auto-Claude-2.7.6-beta.5-linux-amd64.deb) |
| **Linux (Flatpak)** | [Auto-Claude-2.7.6-beta.5-linux-x86_64.flatpak](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.6-beta.5/Auto-Claude-2.7.6-beta.5-linux-x86_64.flatpak) |
| **Windows** | [Auto-Claude-2.7.6-beta.6-win32-x64.exe](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.6-beta.6/Auto-Claude-2.7.6-beta.6-win32-x64.exe) |
| **macOS (Apple Silicon)** | [Auto-Claude-2.7.6-beta.6-darwin-arm64.dmg](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.6-beta.6/Auto-Claude-2.7.6-beta.6-darwin-arm64.dmg) |
| **macOS (Intel)** | [Auto-Claude-2.7.6-beta.6-darwin-x64.dmg](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.6-beta.6/Auto-Claude-2.7.6-beta.6-darwin-x64.dmg) |
| **Linux** | [Auto-Claude-2.7.6-beta.6-linux-x86_64.AppImage](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.6-beta.6/Auto-Claude-2.7.6-beta.6-linux-x86_64.AppImage) |
| **Linux (Debian)** | [Auto-Claude-2.7.6-beta.6-linux-amd64.deb](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.6-beta.6/Auto-Claude-2.7.6-beta.6-linux-amd64.deb) |
| **Linux (Flatpak)** | [Auto-Claude-2.7.6-beta.6-linux-x86_64.flatpak](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.6-beta.6/Auto-Claude-2.7.6-beta.6-linux-x86_64.flatpak) |
<!-- BETA_DOWNLOADS_END -->
> All releases include SHA256 checksums and VirusTotal scan results for security verification.
+1 -3
View File
@@ -62,13 +62,11 @@ Thumbs.db
# Tests (development only)
tests/
# Exceptions: Allow specific test directories
# Exception: Allow colocated tests within integrations/graphiti
!integrations/graphiti/tests/
!tests/integration/
# Auto Claude data directory
.auto-claude/
coverage.json
# Auto Claude generated files
.auto-claude-security.json
+1 -1
View File
@@ -19,5 +19,5 @@ Quick Start:
See README.md for full documentation.
"""
__version__ = "2.7.6-beta.5"
__version__ = "2.7.6"
__author__ = "Auto Claude Team"
+445 -84
View File
@@ -13,7 +13,9 @@ import re
from datetime import datetime, timedelta
from pathlib import Path
from context.constants import SKIP_DIRS
from core.client import create_client
from core.file_utils import write_json_atomic
from linear_updater import (
LinearTaskState,
is_linear_enabled,
@@ -80,11 +82,11 @@ from .base import (
RESUME_FILE,
sanitize_error_message,
)
from .investigation_context import load_investigation_context
from .memory_manager import debug_memory_system_status, get_graphiti_context
from .session import post_session_processing, run_agent_session
from .utils import (
find_phase_for_subtask,
find_subtask_in_plan,
get_commit_count,
get_latest_commit,
load_implementation_plan,
@@ -98,8 +100,383 @@ logger = logging.getLogger(__name__)
# FILE VALIDATION UTILITIES
# =============================================================================
# Directories to exclude from file path search — extends context.constants.SKIP_DIRS
_EXCLUDE_DIRS = frozenset(SKIP_DIRS | {".auto-claude", ".tox", "out"})
def validate_subtask_files(subtask: dict, project_dir: Path) -> dict:
def _build_file_index(
project_dir: Path, suffixes: set[str]
) -> dict[str, list[tuple[str, Path]]]:
"""
Build an index of project files grouped by basename, scanning the tree once.
Also indexes index.{ext} files under their parent directory name as a
secondary key (e.g., api/index.ts is indexed under both "index.ts" and
"api" as directory-stem).
Args:
project_dir: Root directory of the project
suffixes: File extensions to index (e.g., {".ts", ".tsx"})
Returns:
Dict mapping basename -> list of (relative_path_str, Path(relative_path))
"""
index: dict[str, list[tuple[str, Path]]] = {}
resolved_str = str(project_dir.resolve())
for root, dirs, files in os.walk(project_dir.resolve()):
dirs[:] = [d for d in dirs if d not in _EXCLUDE_DIRS]
for filename in files:
ext_idx = filename.rfind(".")
if ext_idx == -1:
continue
file_suffix = filename[ext_idx:]
if file_suffix not in suffixes:
continue
full_path = os.path.join(root, filename)
rel_str = os.path.relpath(full_path, resolved_str).replace(os.sep, "/")
rel_path = Path(rel_str)
# Index by basename
index.setdefault(filename, []).append((rel_str, rel_path))
# Also index index.{ext} files by parent dir name (for stem matching)
stem_part = filename[:ext_idx]
if stem_part == "index":
dir_name = os.path.basename(root)
key = f"__dir_stem__:{dir_name}{file_suffix}"
index.setdefault(key, []).append((rel_str, rel_path))
return index
def _score_and_select(candidates: list[tuple[str, float]]) -> str | None:
"""
Select the best candidate from a scored list of (path, score) pairs.
Requires a minimum score of 8.0 and a gap of at least 3.0 from the
runner-up to avoid ambiguous matches.
Args:
candidates: List of (relative_path, score) tuples
Returns:
Best path if unambiguous, None otherwise
"""
if not candidates:
return None
candidates.sort(key=lambda x: x[1], reverse=True)
best_path, best_score = candidates[0]
if best_score < 8.0:
return None
if len(candidates) > 1:
runner_up_score = candidates[1][1]
if best_score - runner_up_score < 3.0:
return None
return best_path
def _find_correct_path_indexed(
missing_path: str,
parent_parts: tuple[str, ...],
file_index: dict[str, list[tuple[str, Path]]],
) -> str | None:
"""
Find the correct path using a pre-built file index (no tree walk needed).
Args:
missing_path: The incorrect file path from the plan
parent_parts: Parent directory parts of the missing path
file_index: Index built by _build_file_index
Returns:
Corrected relative path, or None if no good match found
"""
missing = Path(missing_path)
basename = missing.name
stem = missing.stem
suffix = missing.suffix
if not suffix:
return None
candidates: list[tuple[str, float]] = []
# Strategy 1: Exact basename match
for rel_str, rel_path in file_index.get(basename, []):
score = 10.0
candidate_parts = rel_path.parent.parts
for i, part in enumerate(parent_parts):
if i < len(candidate_parts) and candidate_parts[i] == part:
score += 3.0
depth_diff = abs(len(candidate_parts) - len(parent_parts))
score -= 0.5 * depth_diff
candidates.append((rel_str, score))
# Strategy 2: index.{ext} in directory matching stem
stem_key = f"__dir_stem__:{stem}{suffix}"
for rel_str, rel_path in file_index.get(stem_key, []):
score = 8.0
candidate_parts = rel_path.parent.parts
for i, part in enumerate(parent_parts):
if i < len(candidate_parts) and candidate_parts[i] == part:
score += 3.0
depth_diff = abs(len(candidate_parts) - len(parent_parts))
score -= 0.5 * depth_diff
candidates.append((rel_str, score))
return _score_and_select(candidates)
def _find_correct_path(missing_path: str, project_dir: Path) -> str | None:
"""
Attempt to find the correct path for a missing file using fuzzy matching.
Strategies:
1. Same basename in nearby directory
2. index.{ext} pattern (e.g., preload/api.ts -> preload/api/index.ts)
Uses os.walk with directory pruning to avoid traversing into node_modules,
.git, dist, etc. — unlike Path.rglob which traverses everything then filters.
Args:
missing_path: The incorrect file path from the plan
project_dir: Root directory of the project
Returns:
Corrected relative path, or None if no good match found
"""
missing = Path(missing_path)
basename = missing.name
stem = missing.stem
suffix = missing.suffix
parent_parts = missing.parent.parts
if not suffix:
return None
candidates: list[tuple[str, float]] = []
resolved_project = project_dir.resolve()
resolved_str = str(resolved_project)
# os.walk with pruning: modify dirs in-place to skip excluded directories
for root, dirs, files in os.walk(resolved_project):
dirs[:] = [d for d in dirs if d not in _EXCLUDE_DIRS]
for filename in files:
if not filename.endswith(suffix):
continue
full_path = os.path.join(root, filename)
rel_str = os.path.relpath(full_path, resolved_str).replace(os.sep, "/")
rel = Path(rel_str)
score = 0.0
# Strategy 1: Exact basename match
if filename == basename:
score += 10.0
# Strategy 2: index.{ext} in directory matching stem
elif filename == f"index{suffix}" and os.path.basename(root) == stem:
score += 8.0
else:
continue
# Bonus: shared parent directory segments
candidate_parts = rel.parent.parts
for i, part in enumerate(parent_parts):
if i < len(candidate_parts) and candidate_parts[i] == part:
score += 3.0
# Penalty: depth difference
depth_diff = abs(len(candidate_parts) - len(parent_parts))
score -= 0.5 * depth_diff
candidates.append((rel_str, score))
return _score_and_select(candidates)
def _auto_correct_subtask_files(
subtask: dict,
missing_files: list[str],
project_dir: Path,
spec_dir: Path,
) -> list[str]:
"""
Attempt to auto-correct missing file paths in a subtask.
Corrects paths in-memory AND persists changes to implementation_plan.json.
Args:
subtask: Subtask dictionary containing files_to_modify
missing_files: List of file paths that don't exist
project_dir: Root directory of the project
spec_dir: Spec directory containing implementation_plan.json
Returns:
List of file paths that could NOT be corrected
"""
corrections: dict[str, str] = {}
still_missing: list[str] = []
# Build file index once for all missing files (avoids repeated os.walk)
suffixes_needed: set[str] = set()
for missing_path in missing_files:
suffix = Path(missing_path).suffix
if suffix:
suffixes_needed.add(suffix)
file_index = (
_build_file_index(project_dir, suffixes_needed) if suffixes_needed else {}
)
for missing_path in missing_files:
missing = Path(missing_path)
corrected = _find_correct_path_indexed(
missing_path, missing.parent.parts, file_index
)
if corrected:
corrections[missing_path] = corrected
logger.info(f"Auto-corrected file path: {missing_path} -> {corrected}")
print_status(f"Auto-corrected: {missing_path} -> {corrected}", "success")
else:
still_missing.append(missing_path)
if not corrections:
return still_missing
# Update subtask in-memory
files_to_modify = subtask.get("files_to_modify", [])
subtask["files_to_modify"] = [corrections.get(f, f) for f in files_to_modify]
# Persist corrections to implementation_plan.json
plan_file = spec_dir / "implementation_plan.json"
if plan_file.exists():
try:
with open(plan_file, encoding="utf-8") as f:
plan = json.load(f)
subtask_id = subtask.get("id")
if subtask_id is not None:
plan_subtask = find_subtask_in_plan(plan, subtask_id)
if plan_subtask:
plan_files = plan_subtask.get("files_to_modify", [])
plan_subtask["files_to_modify"] = [
corrections.get(f, f) for f in plan_files
]
write_json_atomic(plan_file, plan)
logger.info(
f"Persisted {len(corrections)} path correction(s) to implementation_plan.json"
)
except (OSError, TypeError, ValueError) as e:
logger.warning(f"Failed to persist path corrections: {e}")
return still_missing
def _validate_plan_file_paths(spec_dir: Path, project_dir: Path) -> str | None:
"""
Validate all file paths in the implementation plan after planning.
Builds a file index once, then checks all paths across all subtasks against it.
Attempts auto-correction for missing paths. Returns a retry context string for
the planner if uncorrectable paths remain, or None if all paths are valid.
Args:
spec_dir: Spec directory containing implementation_plan.json
project_dir: Root directory of the project
Returns:
Retry context string if issues remain, None if all OK
"""
plan_file = spec_dir / "implementation_plan.json"
if not plan_file.exists():
return None
try:
with open(plan_file, encoding="utf-8") as f:
plan = json.load(f)
except (OSError, json.JSONDecodeError, UnicodeDecodeError):
return None
resolved_project = project_dir.resolve()
# First pass: collect all missing files and their suffixes
missing_entries: list[
tuple[list[str], int, str]
] = [] # (subtask_files_list, index, path)
suffixes_needed: set[str] = set()
for phase in plan.get("phases", []):
for subtask in phase.get("subtasks", []):
files = subtask.get("files_to_modify", [])
for i, file_path in enumerate(files):
full_path = (resolved_project / file_path).resolve()
if not full_path.is_relative_to(resolved_project):
continue
if full_path.exists():
continue
missing = Path(file_path)
if missing.suffix:
suffixes_needed.add(missing.suffix)
missing_entries.append((files, i, file_path))
if not missing_entries:
return None
# Build index once for all needed suffixes
file_index = _build_file_index(project_dir, suffixes_needed)
all_missing: list[str] = []
corrections_made = 0
for files_list, idx, file_path in missing_entries:
missing = Path(file_path)
corrected = _find_correct_path_indexed(
file_path, missing.parent.parts, file_index
)
if corrected:
files_list[idx] = corrected
corrections_made += 1
logger.info(f"Post-plan auto-corrected: {file_path} -> {corrected}")
print_status(f"Auto-corrected: {file_path} -> {corrected}", "success")
else:
all_missing.append(file_path)
# Persist any corrections that were made
if corrections_made > 0:
try:
write_json_atomic(plan_file, plan)
logger.info(f"Persisted {corrections_made} post-plan path correction(s)")
except (OSError, TypeError, ValueError) as e:
logger.warning(f"Failed to persist post-plan corrections: {e}")
if not all_missing:
return None
return (
"## FILE PATH VALIDATION ERRORS\n\n"
"The following files referenced in your implementation plan do NOT exist "
"and could not be auto-corrected:\n"
+ "\n".join(f"- `{p}`" for p in all_missing)
+ "\n\nPlease fix these file paths in the `implementation_plan.json`.\n"
"Use the project's actual file structure to find the correct paths.\n"
"Common issues: wrong directory nesting, missing index files "
"(e.g., `dir/file.ts` should be `dir/file/index.ts`)."
)
def validate_subtask_files(
subtask: dict, project_dir: Path, spec_dir: Path | None = None
) -> dict:
"""
Validate all files_to_modify exist before subtask execution.
@@ -137,6 +514,15 @@ def validate_subtask_files(subtask: dict, project_dir: Path) -> dict:
}
if missing_files:
# Attempt auto-correction if spec_dir is provided
if spec_dir:
still_missing = _auto_correct_subtask_files(
subtask, missing_files, project_dir, spec_dir
)
if not still_missing:
return {"success": True, "missing_files": [], "invalid_paths": []}
missing_files = still_missing
return {
"success": False,
"error": f"Planned files do not exist: {', '.join(missing_files)}",
@@ -686,7 +1072,10 @@ async def run_autonomous_agent(
# Validate that all files_to_modify exist before attempting execution
# This prevents infinite retry loops when implementation plan references non-existent files
validation_result = validate_subtask_files(next_subtask, project_dir)
# Pass spec_dir to enable auto-correction of wrong paths
validation_result = validate_subtask_files(
next_subtask, project_dir, spec_dir
)
if not validation_result["success"]:
# File validation failed - record error and skip session
error_msg = validation_result["error"]
@@ -720,6 +1109,11 @@ async def run_autonomous_agent(
subtask_id,
f"File validation failed after {attempt_count} attempts: {error_msg}",
)
emit_phase(
ExecutionPhase.FAILED,
f"Subtask {subtask_id} stuck: file validation failed",
subtask=subtask_id,
)
print_status(
f"Subtask {subtask_id} marked as STUCK after {attempt_count} failed validation attempts",
"error",
@@ -783,84 +1177,6 @@ async def run_autonomous_agent(
prompt += "\n\n" + graphiti_context
print_status("Graphiti memory context loaded", "success")
# Load investigation context if this is a GitHub-sourced task
investigation_context = load_investigation_context(spec_dir)
if investigation_context:
# Format investigation context for the prompt
inv = investigation_context
inv_prompt = "\n## GitHub Investigation Context\n\n"
inv_prompt += (
"This task was created from a GitHub issue investigation. "
)
inv_prompt += "Use this context to guide your work.\n\n"
if inv.get("root_cause", {}).get("summary"):
inv_prompt += f"**Root Cause:** {inv['root_cause']['summary']}\n\n"
if inv.get("root_cause", {}).get("evidence"):
inv_prompt += f"**Evidence:**\n{inv['root_cause']['evidence']}\n\n"
if inv.get("root_cause", {}).get("code_paths"):
inv_prompt += "**Code Paths:**\n"
for path in inv["root_cause"]["code_paths"]:
file_ref = path.get("file", "unknown")
start = path.get("start_line", "")
end = path.get("end_line", "")
desc = path.get("description", "")
line_range = f":{start}-{end}" if start and end else ""
inv_prompt += f"- `{file_ref}{line_range}`"
if desc:
inv_prompt += f"{desc}"
inv_prompt += "\n"
inv_prompt += "\n"
if inv.get("fix_approaches"):
inv_prompt += "**Fix Approaches:**\n"
for i, approach in enumerate(inv["fix_approaches"], 1):
desc = approach.get("description", "Approach")
complexity = approach.get("complexity", "")
inv_prompt += f"{i}. {desc}"
if complexity:
inv_prompt += f" (complexity: {complexity})"
inv_prompt += "\n"
files_affected = approach.get("files_affected", [])
if files_affected:
inv_prompt += f" - Files: {', '.join(files_affected)}\n"
inv_prompt += "\n"
if inv.get("gotchas"):
inv_prompt += "**Gotchas:**\n"
for gotcha in inv["gotchas"]:
inv_prompt += f"- {gotcha}\n"
inv_prompt += "\n"
if inv.get("patterns_to_follow"):
inv_prompt += "**Patterns to Follow:**\n"
for pattern in inv["patterns_to_follow"]:
file_ref = pattern.get("file", "unknown")
desc = pattern.get("description", "")
inv_prompt += f"- `{file_ref}`"
if desc:
inv_prompt += f"{desc}"
inv_prompt += "\n"
inv_prompt += "\n"
if inv.get("reproducer"):
reproducer = inv["reproducer"]
inv_prompt += "**Verification Steps:**\n"
steps = reproducer.get("reproduction_steps", [])
for step in steps:
inv_prompt += f"- {step}\n"
test_approach = reproducer.get("suggested_test_approach")
if test_approach:
inv_prompt += (
f"\n**Suggested Test Approach:** {test_approach}\n"
)
inv_prompt += "\n"
prompt += inv_prompt
print_status("Investigation context loaded", "success")
# Add concurrency error context if recovering from 400 error
if concurrency_error_context:
prompt += "\n\n" + concurrency_error_context
@@ -891,8 +1207,28 @@ async def run_autonomous_agent(
if is_planning_phase and status != "error":
valid, errors = _validate_and_fix_implementation_plan()
if valid:
plan_validated = True
planning_retry_context = None
# Fix 5: Validate file paths in the newly created plan
path_issues = _validate_plan_file_paths(spec_dir, project_dir)
if (
path_issues
and planning_validation_failures < max_planning_validation_retries
):
planning_validation_failures += 1
planning_retry_context = path_issues
print_status(
"Plan has invalid file paths - retrying planner",
"warning",
)
first_run = True
status = "continue"
else:
if path_issues:
logger.warning(
f"Plan has uncorrectable file paths after "
f"{planning_validation_failures} retries - proceeding anyway"
)
plan_validated = True
planning_retry_context = None
else:
planning_validation_failures += 1
if planning_validation_failures >= max_planning_validation_retries:
@@ -950,6 +1286,11 @@ async def run_autonomous_agent(
recovery_manager.mark_subtask_stuck(
subtask_id, f"Failed after {attempt_count} attempts"
)
emit_phase(
ExecutionPhase.FAILED,
f"Subtask {subtask_id} stuck after {attempt_count} attempts",
subtask=subtask_id,
)
print()
print_status(
f"Subtask {subtask_id} marked as STUCK after {attempt_count} attempts",
@@ -1309,4 +1650,24 @@ async def run_autonomous_agent(
if completed == total:
status_manager.update(state=BuildState.COMPLETE)
else:
status_manager.update(state=BuildState.PAUSED)
# Check if all remaining subtasks are stuck — if so, this is an error, not a pause
all_remaining_stuck = False
if stuck_subtasks:
stuck_ids = {s["subtask_id"] for s in stuck_subtasks}
plan = load_implementation_plan(spec_dir)
if plan:
all_remaining_stuck = True
for phase in plan.get("phases", []):
for s in phase.get("subtasks", []):
if s.get("status") != "completed":
if s.get("id") not in stuck_ids:
all_remaining_stuck = False
break
if not all_remaining_stuck:
break
if all_remaining_stuck and stuck_subtasks:
emit_phase(ExecutionPhase.FAILED, "All remaining subtasks are stuck")
status_manager.update(state=BuildState.ERROR)
else:
status_manager.update(state=BuildState.PAUSED)
@@ -1,97 +0,0 @@
"""
Investigation context loading for agents.
Provides utilities to load investigation data from spec directories
for GitHub-sourced tasks.
"""
import json
from pathlib import Path
from typing import Any
def load_investigation_context(spec_dir: Path) -> dict[str, Any] | None:
"""
Load investigation context if this spec was created from a GitHub issue.
Args:
spec_dir: Path to the spec directory
Returns:
Structured investigation context with root_cause, fix_approaches,
reproducer, gotchas, and patterns_to_follow, or None if no
investigation data exists.
"""
investigation_report_path = spec_dir / "investigation_report.json"
if not investigation_report_path.exists():
return None
try:
with open(investigation_report_path) as f:
report = json.load(f)
root_cause = report.get("root_cause", {})
fix_advice = report.get("fix_advice", {})
reproduction = report.get("reproduction", {})
# Structure the context for agents
return {
"root_cause": {
"summary": root_cause.get("identified_root_cause"),
"evidence": root_cause.get("evidence", ""),
"code_paths": root_cause.get("code_paths", []),
},
"fix_approaches": fix_advice.get("approaches", []),
"reproducer": reproduction if reproduction else None,
"gotchas": fix_advice.get("gotchas", []),
"patterns_to_follow": fix_advice.get("patterns_to_follow", []),
"impact": report.get("impact", {}),
}
except (json.JSONDecodeError, OSError):
return None
def load_investigation_for_qa(
spec_dir: Path, base_branch: str
) -> dict[str, Any] | None:
"""
Load investigation context for QA validation.
Similar to load_investigation_context but includes base_branch
for QA comparison.
Args:
spec_dir: Path to the spec directory
base_branch: Base branch to compare against (e.g., 'main', 'develop')
Returns:
Structured investigation context with root_cause, reproducer,
impact, expected_outcome, and base_branch, or None if no
investigation data exists.
"""
investigation_report_path = spec_dir / "investigation_report.json"
if not investigation_report_path.exists():
return None
try:
with open(investigation_report_path) as f:
report = json.load(f)
root_cause = report.get("root_cause", {})
reproduction = report.get("reproduction", {})
return {
"root_cause": {
"summary": root_cause.get("identified_root_cause"),
"evidence": root_cause.get("evidence", ""),
"code_paths": root_cause.get("code_paths", []),
},
"reproducer": reproduction if reproduction else None,
"impact": report.get("impact", {}),
"expected_outcome": report.get("ai_summary"),
"base_branch": base_branch,
}
except (json.JSONDecodeError, OSError):
return None
+2 -1
View File
@@ -14,6 +14,7 @@ from core.error_utils import (
is_authentication_error,
is_rate_limit_error,
is_tool_concurrency_error,
safe_receive_messages,
)
from core.file_utils import write_json_atomic
from debug import debug, debug_detailed, debug_error, debug_section, debug_success
@@ -490,7 +491,7 @@ async def run_agent_session(
# Collect response text and show tool use
response_text = ""
debug("session", "Starting to receive response stream...")
async for msg in client.receive_response():
async for msg in safe_receive_messages(client, caller="session"):
msg_type = type(msg).__name__
message_count += 1
debug_detailed(
-7
View File
@@ -308,13 +308,6 @@ AGENT_CONFIGS = {
"auto_claude_tools": [],
"thinking_default": "medium",
},
"investigation_specialist": {
# Read-only specialist for issue investigation (root cause, impact, fix, reproduction)
"tools": BASE_READ_TOOLS,
"mcp_servers": [],
"auto_claude_tools": [],
"thinking_default": "medium",
},
# ═══════════════════════════════════════════════════════════════════════
# ANALYSIS PHASES
# ═══════════════════════════════════════════════════════════════════════
-253
View File
@@ -61,8 +61,6 @@ def handle_build_command(
skip_qa: bool,
force_bypass_approval: bool,
base_branch: str | None = None,
issue_workflow: bool = False,
issue_number: int | None = None,
) -> None:
"""
Handle the main build command.
@@ -79,8 +77,6 @@ def handle_build_command(
skip_qa: Skip automatic QA validation
force_bypass_approval: Force bypass approval check
base_branch: Base branch for worktree creation (default: current branch)
issue_workflow: If True, run from a GitHub issue investigation
issue_number: GitHub issue number (required when issue_workflow=True)
"""
# Lazy imports to avoid loading heavy modules
from agent import run_autonomous_agent, sync_spec_to_source
@@ -99,30 +95,6 @@ def handle_build_command(
from .utils import print_banner, validate_environment
# Handle issue workflow: load investigation report and inject context
if issue_workflow:
if not issue_number:
print("\nError: --issue-number is required with --issue-workflow")
sys.exit(1)
pipeline_mode = _get_investigation_pipeline_mode(project_dir)
_inject_issue_workflow_context(project_dir, spec_dir, issue_number)
# pipelineMode controls which phases to skip:
# - "full": run complete spec + planning + coding + QA pipeline (default)
# - "skip_to_planning": skip spec creation, go to planning (investigation = spec)
# - "minimal": skip spec + planning, go straight to coding
if pipeline_mode == "skip_to_planning":
# Investigation report serves as the spec; bypass approval since
# the investigation was already reviewed.
force_bypass_approval = True
elif pipeline_mode == "minimal":
# Skip everything: create a minimal plan so the planner is bypassed
# and the coder starts immediately from the investigation context.
force_bypass_approval = True
skip_qa = True
_create_minimal_plan_for_issue(spec_dir, issue_number)
# Get the resolved model for the planning phase (first phase of build)
# This respects task_metadata.json phase configuration from the UI
planning_model = get_phase_model(spec_dir, "planning", model)
@@ -513,228 +485,3 @@ def _handle_build_interrupt(
content.append(muted("Your build is in a separate workspace and is safe."))
print(box(content, width=70, style="light"))
print()
def _create_minimal_plan_for_issue(spec_dir: Path, issue_number: int) -> None:
"""Create a minimal implementation plan so the planner phase is skipped.
Used in "minimal" pipeline mode where the investigation context is
sufficient and we want the coder to start immediately.
Args:
spec_dir: Spec directory path
issue_number: GitHub issue number for context
"""
from datetime import datetime
plan_file = spec_dir / "implementation_plan.json"
if plan_file.exists():
# Don't overwrite an existing plan (e.g. if resuming)
return
plan = {
"phases": [
{
"phase": 1,
"name": "Implementation",
"description": f"Implement fix for issue #{issue_number} based on investigation findings",
"depends_on": [],
"subtasks": [
{
"id": "subtask-1-1",
"description": (
f"Implement the fix for issue #{issue_number}. "
"Follow the investigation context in HUMAN_INPUT.md "
"for root cause analysis, recommended fix approach, "
"and files to modify."
),
"service": "main",
"status": "pending",
"files_to_create": [],
"files_to_modify": [],
"patterns_from": [],
"verification": {
"type": "manual",
"run": "Verify the fix resolves the issue",
},
}
],
}
],
"metadata": {
"created_at": datetime.now().isoformat(),
"complexity": "simple",
"estimated_sessions": 1,
"pipeline_mode": "minimal",
"source_issue": issue_number,
},
}
from core.file_utils import write_json_atomic
write_json_atomic(plan_file, plan)
print(" Pipeline mode: minimal (skipping planner, created single-subtask plan)")
def _get_investigation_pipeline_mode(project_dir: Path) -> str:
"""Read the pipelineMode from investigation settings.
Reads from .auto-claude/github/config.json -> investigation_settings.pipelineMode.
Defaults to "full" if not configured.
Args:
project_dir: Project root directory
Returns:
Pipeline mode string: "full", "skip_to_planning", or "minimal"
"""
import json
config_path = project_dir / ".auto-claude" / "github" / "config.json"
if not config_path.exists():
return "full"
try:
data = json.loads(config_path.read_text(encoding="utf-8"))
settings = data.get("investigation_settings", {})
mode = settings.get("pipelineMode", "full")
if mode in ("full", "skip_to_planning", "minimal"):
return mode
return "full"
except (json.JSONDecodeError, OSError):
return "full"
def _inject_issue_workflow_context(
project_dir: Path,
spec_dir: Path,
issue_number: int,
) -> None:
"""Inject investigation context into the build workflow.
Loads the investigation report for the given issue and writes a
HUMAN_INPUT.md file in the spec directory with root cause analysis,
fix advice, and other investigation context. This is read by the
coder agent as additional guidance.
Also updates the investigation state to "building".
Args:
project_dir: Project root directory
spec_dir: Spec directory path
issue_number: GitHub issue number
"""
# Use try/except for imports matching the codebase pattern
try:
from runners.github.services.investigation_persistence import (
load_investigation_report,
save_investigation_state,
)
except (ImportError, ValueError, SystemError):
# Add parent to path if needed
_backend = Path(__file__).parent.parent
if str(_backend) not in sys.path:
sys.path.insert(0, str(_backend))
from runners.github.services.investigation_persistence import (
load_investigation_report,
save_investigation_state,
)
report = load_investigation_report(project_dir, issue_number)
if report is None:
print(f"\nWarning: No investigation report found for issue #{issue_number}")
print("Proceeding without investigation context.")
return
# Build context string for the coder agent
context_parts: list[str] = []
context_parts.append(f"# Investigation Context for Issue #{issue_number}")
context_parts.append("")
context_parts.append(f"## {report.issue_title}")
context_parts.append("")
context_parts.append(f"**Severity:** {report.severity}")
context_parts.append("")
# AI summary
context_parts.append("## Summary")
context_parts.append(report.ai_summary)
context_parts.append("")
# Root cause
context_parts.append("## Root Cause")
context_parts.append(report.root_cause.identified_root_cause)
context_parts.append("")
if report.root_cause.code_paths:
context_parts.append("### Code Paths")
for cp in report.root_cause.code_paths:
end = cp.end_line if cp.end_line else cp.start_line
context_parts.append(
f"- `{cp.file}:{cp.start_line}-{end}`: {cp.description}"
)
context_parts.append("")
# Fix advice
if report.fix_advice.approaches:
rec_idx = report.fix_advice.recommended_approach
context_parts.append("## Recommended Fix")
if 0 <= rec_idx < len(report.fix_advice.approaches):
approach = report.fix_advice.approaches[rec_idx]
context_parts.append(approach.description)
context_parts.append("")
if approach.files_affected:
context_parts.append("**Files to modify:**")
for f in approach.files_affected:
context_parts.append(f"- `{f}`")
context_parts.append("")
# Gotchas
if report.fix_advice.gotchas:
context_parts.append("## Gotchas")
for gotcha in report.fix_advice.gotchas:
context_parts.append(f"- {gotcha}")
context_parts.append("")
# Patterns
if report.fix_advice.patterns_to_follow:
context_parts.append("## Patterns to Follow")
for pat in report.fix_advice.patterns_to_follow:
context_parts.append(f"- `{pat.file}`: {pat.description}")
context_parts.append("")
context = "\n".join(context_parts)
# Write as HUMAN_INPUT.md (existing mechanism for agent guidance injection)
input_file = spec_dir / "HUMAN_INPUT.md"
existing = ""
if input_file.exists():
existing = input_file.read_text(encoding="utf-8")
if existing:
# Append investigation context to existing human input
combined = existing + "\n\n" + context
else:
combined = context
input_file.write_text(combined, encoding="utf-8")
# Update investigation state to "building" (note: we use the broader
# "task_created" status since "building" isn't a valid InvestigationState status)
from datetime import datetime, timezone
save_investigation_state(
project_dir,
issue_number,
{
"issue_number": issue_number,
"status": "task_created",
"started_at": datetime.now(timezone.utc).isoformat(),
"linked_spec_id": spec_dir.name,
},
)
print(f"\nIssue workflow: Injected investigation context for #{issue_number}")
print(f" Root cause: {report.root_cause.identified_root_cause[:80]}...")
print(f" Severity: {report.severity}")
print()
-15
View File
@@ -280,19 +280,6 @@ Environment Variables:
help="Actually delete files in cleanup (not just preview)",
)
# Issue workflow
parser.add_argument(
"--issue-workflow",
action="store_true",
help="Run build from a GitHub issue investigation (requires --issue-number)",
)
parser.add_argument(
"--issue-number",
type=int,
default=None,
help="GitHub issue number for --issue-workflow",
)
return parser.parse_args()
@@ -490,8 +477,6 @@ def _run_cli() -> None:
skip_qa=args.skip_qa,
force_bypass_approval=args.force,
base_branch=args.base_branch,
issue_workflow=args.issue_workflow,
issue_number=args.issue_number,
)
+6 -2
View File
@@ -101,8 +101,12 @@ def handle_qa_command(
print("\n✅ Build already approved by QA.")
else:
completed, total = count_subtasks(spec_dir)
print(f"\n❌ Build not complete ({completed}/{total} subtasks).")
print("Complete all subtasks before running QA validation.")
print(
f"\n❌ Build not ready for QA ({completed}/{total} subtasks completed)."
)
print(
"All subtasks must reach a terminal state (completed, failed, or stuck) before running QA."
)
return
if has_human_feedback:
+108 -1
View File
@@ -29,6 +29,89 @@ from core.platform import (
logger = logging.getLogger(__name__)
# =============================================================================
# SDK Message Parser Patch
# =============================================================================
# The Claude Agent SDK's message_parser raises MessageParseError for unknown
# message types (e.g., "rate_limit_event"). Since parse_message runs inside an
# async generator, the exception kills the entire agent session stream.
# Patch to log a warning and return a SystemMessage instead of crashing.
# This is needed until the SDK natively handles all CLI message types.
def _patch_sdk_message_parser() -> None:
"""Patch the SDK's parse_message to handle unknown message types gracefully.
The Claude CLI may emit message types that the installed SDK version doesn't
recognize (e.g., rate_limit_event, usage_event). Without this patch, any
unrecognized type raises MessageParseError inside the SDK's async generator,
which terminates the entire response stream and kills the agent session.
The patch converts unknown types into SystemMessage objects with a
'unknown_<type>' subtype, which all message consumers silently skip.
"""
try:
import claude_agent_sdk._internal.message_parser as _parser
from claude_agent_sdk._errors import MessageParseError
from claude_agent_sdk.types import SystemMessage
_original_parse = _parser.parse_message
def _patched_parse(data):
try:
return _original_parse(data)
except MessageParseError as e:
msg = str(e)
if "Unknown message type" in msg:
msg_type = (
data.get("type", "unknown")
if isinstance(data, dict)
else "unknown"
)
# Rate limit events deserve a visible warning; others just debug-level
if "rate_limit" in msg_type:
retry_after = (
data.get("retry_after")
or data.get("data", {}).get("retry_after")
if isinstance(data, dict)
else None
)
retry_info = (
f" (retry_after={retry_after}s)" if retry_after else ""
)
logger.warning(
f"Rate limit event received from CLI{retry_info}"
f"the SDK will handle backoff automatically"
)
else:
logger.debug(
f"SDK received unhandled message type '{msg_type}', skipping"
)
return SystemMessage(
subtype=f"unknown_{msg_type}",
data=data if isinstance(data, dict) else {},
)
raise
_parser.parse_message = _patched_parse
except Exception as e:
logger.warning(f"Failed to patch SDK message parser: {e}")
_patch_sdk_message_parser()
# =============================================================================
# Windows System Prompt Limits
# =============================================================================
# Windows CreateProcessW has a 32,768 character limit for the entire command line.
# When CLAUDE.md is very large and passed as --system-prompt, the command can exceed
# this limit, causing ERROR_FILE_NOT_FOUND. We cap CLAUDE.md content to stay safe.
# 20,000 chars leaves ~12KB headroom for CLI overhead (model, tools, MCP config, etc.)
WINDOWS_MAX_SYSTEM_PROMPT_CHARS = 20000
WINDOWS_TRUNCATION_MESSAGE = (
"\n\n[... CLAUDE.md truncated due to Windows command-line length limit ...]"
)
# =============================================================================
# Project Index Cache
# =============================================================================
@@ -821,8 +904,31 @@ def create_client(
if should_use_claude_md():
claude_md_content = load_claude_md(project_dir)
if claude_md_content:
# On Windows, the SDK passes system_prompt as a --system-prompt CLI argument.
# Windows CreateProcessW has a 32,768 character limit for the entire command line.
# When CLAUDE.md is very large, the command can exceed this limit, causing Windows
# to return ERROR_FILE_NOT_FOUND which the SDK misreports as "Claude Code not found".
# Cap CLAUDE.md content to keep total command line under the limit. (#1661)
was_truncated = False
if is_windows():
max_claude_md_chars = (
WINDOWS_MAX_SYSTEM_PROMPT_CHARS
- len(base_prompt)
- len(WINDOWS_TRUNCATION_MESSAGE)
- len("\n\n# Project Instructions (from CLAUDE.md)\n\n")
)
if len(claude_md_content) > max_claude_md_chars > 0:
claude_md_content = (
claude_md_content[:max_claude_md_chars]
+ WINDOWS_TRUNCATION_MESSAGE
)
print(
" - CLAUDE.md: truncated (exceeded Windows command-line limit)"
)
was_truncated = True
base_prompt = f"{base_prompt}\n\n# Project Instructions (from CLAUDE.md)\n\n{claude_md_content}"
print(" - CLAUDE.md: included in system prompt")
if not was_truncated:
print(" - CLAUDE.md: included in system prompt")
else:
print(" - CLAUDE.md: not found in project root")
else:
@@ -867,6 +973,7 @@ def create_client(
logger.info(f"Using CLAUDE_CLI_PATH override: {env_cli_path}")
# Add structured output format if specified
# See: https://platform.claude.com/docs/en/agent-sdk/structured-outputs
if output_format:
options_kwargs["output_format"] = output_format
+4 -4
View File
@@ -235,10 +235,10 @@ def debug_section(module: str, title: str) -> None:
return
timestamp = datetime.now().strftime("%H:%M:%S.%f")[:-3]
separator = "-" * 60
log_line = f"\n{Colors.TIMESTAMP}[{timestamp}]{Colors.RESET} {Colors.DEBUG}{Colors.BOLD}+{separator}+{Colors.RESET}"
log_line += f"\n{Colors.TIMESTAMP} {Colors.RESET} {Colors.DEBUG}{Colors.BOLD}| {module}: {title}{' ' * (58 - len(module) - len(title) - 2)}|{Colors.RESET}"
log_line += f"\n{Colors.TIMESTAMP} {Colors.RESET} {Colors.DEBUG}{Colors.BOLD}+{separator}+{Colors.RESET}"
separator = "" * 60
log_line = f"\n{Colors.TIMESTAMP}[{timestamp}]{Colors.RESET} {Colors.DEBUG}{Colors.BOLD}{separator}{Colors.RESET}"
log_line += f"\n{Colors.TIMESTAMP} {Colors.RESET} {Colors.DEBUG}{Colors.BOLD} {module}: {title}{' ' * (58 - len(module) - len(title) - 2)}{Colors.RESET}"
log_line += f"\n{Colors.TIMESTAMP} {Colors.RESET} {Colors.DEBUG}{Colors.BOLD}{separator}{Colors.RESET}"
_write_log(log_line)
+68
View File
@@ -6,7 +6,17 @@ Common error detection and classification functions used across
agent sessions, QA, and other modules.
"""
from __future__ import annotations
import logging
import re
from collections.abc import AsyncIterator
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from claude_agent_sdk.types import Message
logger = logging.getLogger(__name__)
def is_tool_concurrency_error(error: Exception) -> bool:
@@ -118,3 +128,61 @@ def is_authentication_error(error: Exception) -> bool:
"please login again",
]
)
async def safe_receive_messages(
client,
*,
caller: str = "agent",
) -> AsyncIterator[Message]:
"""Iterate over SDK messages with resilience against unexpected errors.
The SDK's ``receive_response()`` async generator can terminate early if:
1. An unhandled message type slips past the monkey-patch (e.g., SDK upgrade
removes the patch surface).
2. A transient parse error corrupts a single message in the stream.
3. An unexpected ``StopAsyncIteration`` or runtime error occurs mid-stream.
This wrapper catches per-message errors, logs them, and continues yielding
subsequent messages so the agent session can complete its work.
It also detects rate-limit events (surfaced as ``SystemMessage`` with
subtype ``unknown_rate_limit_event``) and logs a user-visible warning.
Args:
client: A ``ClaudeSDKClient`` instance (must be inside ``async with``).
caller: Label for log messages (e.g., "session", "agent_runner").
Yields:
Parsed ``Message`` objects from the SDK response stream.
"""
try:
async for msg in client.receive_response():
# Detect rate-limit events surfaced by the monkey-patch
msg_type = type(msg).__name__
if msg_type == "SystemMessage":
subtype = getattr(msg, "subtype", "")
if subtype.startswith("unknown_"):
original_type = subtype[len("unknown_") :]
if "rate_limit" in original_type:
data = getattr(msg, "data", {})
retry_after = data.get("retry_after") or data.get(
"data", {}
).get("retry_after")
retry_info = (
f" (retry in {retry_after}s)" if retry_after else ""
)
logger.warning(f"[{caller}] Rate limit event{retry_info}")
else:
logger.debug(
f"[{caller}] Skipping unknown SDK message type: {original_type}"
)
continue
yield msg
except GeneratorExit:
return
except Exception as e:
# If the generator itself raises (e.g., transport error), log and stop
# gracefully so callers can process whatever was collected so far.
logger.error(f"[{caller}] SDK response stream terminated unexpectedly: {e}")
return
+64 -17
View File
@@ -115,6 +115,65 @@ def is_build_complete(spec_dir: Path) -> bool:
return total > 0 and completed == total
def _load_stuck_subtask_ids(spec_dir: Path) -> set[str]:
"""Load IDs of subtasks marked as stuck from attempt_history.json."""
stuck_subtask_ids: set[str] = set()
attempt_history_file = spec_dir / "memory" / "attempt_history.json"
if attempt_history_file.exists():
try:
with open(attempt_history_file, encoding="utf-8") as f:
attempt_history = json.load(f)
for entry in attempt_history.get("stuck_subtasks", []):
if "subtask_id" in entry:
stuck_subtask_ids.add(entry["subtask_id"])
except (OSError, json.JSONDecodeError, UnicodeDecodeError):
# Corrupted attempt history is non-fatal; skip stuck-subtask filtering
pass
return stuck_subtask_ids
def is_build_ready_for_qa(spec_dir: Path) -> bool:
"""
Check if the build is ready for QA validation.
Unlike is_build_complete() which requires all subtasks to be "completed",
this function considers the build ready when all subtasks have reached
a terminal state: completed, failed, or stuck (exhausted retries in attempt_history.json).
Args:
spec_dir: Directory containing implementation_plan.json
Returns:
True if all subtasks are in a terminal state, False otherwise
"""
plan_file = spec_dir / "implementation_plan.json"
if not plan_file.exists():
return False
stuck_subtask_ids = _load_stuck_subtask_ids(spec_dir)
try:
with open(plan_file, encoding="utf-8") as f:
plan = json.load(f)
total = 0
terminal = 0
for phase in plan.get("phases", []):
for subtask in phase.get("subtasks", []):
total += 1
status = subtask.get("status", "pending")
subtask_id = subtask.get("id")
if status in ("completed", "failed") or subtask_id in stuck_subtask_ids:
terminal += 1
return total > 0 and terminal == total
except (OSError, json.JSONDecodeError, UnicodeDecodeError):
return False
def get_progress_percentage(spec_dir: Path) -> float:
"""
Get the progress as a percentage.
@@ -420,22 +479,7 @@ def get_next_subtask(spec_dir: Path) -> dict | None:
if not plan_file.exists():
return None
# Load stuck subtasks from recovery manager's attempt history
stuck_subtask_ids = set()
attempt_history_file = spec_dir / "memory" / "attempt_history.json"
if attempt_history_file.exists():
try:
with open(attempt_history_file, encoding="utf-8") as f:
attempt_history = json.load(f)
# Collect IDs of subtasks marked as stuck
stuck_subtask_ids = {
entry["subtask_id"]
for entry in attempt_history.get("stuck_subtasks", [])
if "subtask_id" in entry
}
except (OSError, json.JSONDecodeError, UnicodeDecodeError):
# If we can't read the file, continue without stuck checking
pass
stuck_subtask_ids = _load_stuck_subtask_ids(spec_dir)
try:
with open(plan_file, encoding="utf-8") as f:
@@ -454,8 +498,11 @@ def get_next_subtask(spec_dir: Path) -> dict | None:
str(phase_id_raw) if phase_id_raw is not None else f"unknown:{i}"
)
subtasks = phase.get("subtasks", phase.get("chunks", []))
# Stuck subtasks count as "resolved" for phase dependency purposes.
# This prevents one stuck subtask from blocking all downstream phases.
phase_complete[phase_id_key] = all(
s.get("status") == "completed" for s in subtasks
s.get("status") == "completed" or s.get("id") in stuck_subtask_ids
for s in subtasks
)
# Find next available subtask
@@ -9,9 +9,10 @@ Each dependency ecosystem has different constraints:
- **node_modules**: Safe to symlink. Node's resolution algorithm follows symlinks
correctly, and the directory is self-contained.
- **venv / .venv**: Must be recreated. Python's ``pyvenv.cfg`` discovery walks the
real directory hierarchy without resolving symlinks (CPython bug #106045), so a
symlinked venv resolves paths relative to the *target*, not the worktree.
- **venv / .venv**: Symlinked for fast worktree creation. CPython bug #106045
(pyvenv.cfg symlink resolution) does not affect typical usage (running scripts,
imports, pip). A health check after symlinking verifies usability; if it fails,
the caller falls back to recreating the venv.
- **vendor (PHP)**: Safe to symlink. Composer's autoloader uses ``__DIR__``-relative
paths that resolve correctly through symlinks.
@@ -42,9 +43,9 @@ from .models import DependencyShareConfig, DependencyStrategy
DEFAULT_STRATEGY_MAP: dict[str, DependencyStrategy] = {
# JavaScript / Node.js — symlink is safe and fast
"node_modules": DependencyStrategy.SYMLINK,
# Python — venvs MUST be recreated (pyvenv.cfg symlink bug)
"venv": DependencyStrategy.RECREATE,
".venv": DependencyStrategy.RECREATE,
# Python — symlink for fast worktree creation (health check + fallback to recreate)
"venv": DependencyStrategy.SYMLINK,
".venv": DependencyStrategy.SYMLINK,
# PHP — Composer vendor dir is safe to symlink
"vendor_php": DependencyStrategy.SYMLINK,
# Ruby — Bundler vendor/bundle is safe to symlink
+5 -6
View File
@@ -278,12 +278,11 @@ class SpecNumberLock:
class DependencyStrategy(Enum):
"""Strategy for sharing dependency directories across worktrees.
SYMLINK is fast but unsafe for certain ecosystems. Notably, Python venv
breaks when symlinked because CPython's pyvenv.cfg discovery walks the
real directory hierarchy without resolving symlinks first
(CPython bug #106045). This means a symlinked venv resolves its home
path relative to the symlink target's parent, not the worktree, causing
import failures and broken interpreters.
SYMLINK is fast and now safe for Python venvs with runtime health checks.
A post-symlink health check validates the venv is usable, automatically
falling back to RECREATE if the symlink is broken. This works around
CPython's pyvenv.cfg discovery issue (CPython bug #106045) while maintaining
fast worktree creation in the common case where symlinking succeeds.
"""
SYMLINK = "symlink" # Create a symlink to the source (fast, works for node_modules)
+140 -26
View File
@@ -50,6 +50,10 @@ _git_hook_check_done = False
MODULE = "workspace.setup"
# Marker file written inside a recreated venv to indicate setup completed successfully.
# If the marker is absent, the venv is treated as incomplete and will be rebuilt.
VENV_SETUP_COMPLETE_MARKER = ".setup_complete"
def choose_workspace(
project_dir: Path,
@@ -624,9 +628,52 @@ def setup_worktree_dependencies(
results[strategy_name] = []
try:
performed = True
performed = False
if config.strategy == DependencyStrategy.SYMLINK:
performed = _apply_symlink_strategy(project_dir, worktree_path, config)
# For venvs, verify the symlink is usable — fall back to recreate
# Run health check whenever a venv symlink exists (not just on creation)
if config.dep_type in ("venv", ".venv"):
venv_path = worktree_path / config.source_rel_path
# Check if venv exists (symlinked or otherwise)
if venv_path.exists() or venv_path.is_symlink():
if is_windows():
python_bin = str(venv_path / "Scripts" / "python.exe")
else:
python_bin = str(venv_path / "bin" / "python")
try:
subprocess.run(
[python_bin, "-c", "import sys; print(sys.prefix)"],
capture_output=True,
text=True,
timeout=10,
check=True,
)
debug(
MODULE,
f"Symlinked venv health check passed: {config.source_rel_path}",
)
except (subprocess.SubprocessError, OSError):
debug_warning(
MODULE,
f"Symlinked venv health check failed, falling back to recreate: {config.source_rel_path}",
)
# Remove the broken symlink and recreate
try:
if venv_path.is_symlink():
venv_path.unlink()
elif venv_path.exists():
shutil.rmtree(venv_path, ignore_errors=True)
except OSError:
pass # Best-effort removal; recreate strategy handles existing paths
performed = _apply_recreate_strategy(
project_dir, worktree_path, config
)
# Update strategy name to reflect fallback
if performed:
strategy_name = "recreate"
# Ensure the key exists for the fallback strategy
results.setdefault(strategy_name, [])
elif config.strategy == DependencyStrategy.RECREATE:
performed = _apply_recreate_strategy(project_dir, worktree_path, config)
elif config.strategy == DependencyStrategy.COPY:
@@ -707,6 +754,54 @@ def _apply_symlink_strategy(
return False
def _popen_with_cleanup(
cmd: list[str],
timeout: int,
label: str,
) -> tuple[int, str, str]:
"""Run a command via Popen with proper process cleanup on timeout.
On timeout: terminate wait(10) kill wait(5) to ensure file locks
are released before any cleanup (e.g. shutil.rmtree).
Returns (returncode, stdout, stderr).
Raises subprocess.TimeoutExpired if the command exceeds the given timeout (after cleanup is attempted).
"""
proc = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
)
try:
stdout, stderr = proc.communicate(timeout=timeout)
return proc.returncode, stdout, stderr
except subprocess.TimeoutExpired:
debug_warning(MODULE, f"{label} timed out, terminating process")
proc.terminate()
try:
proc.communicate(timeout=10)
except subprocess.TimeoutExpired:
debug_warning(MODULE, f"{label} did not terminate, killing process")
proc.kill()
try:
proc.communicate(timeout=5)
except subprocess.TimeoutExpired:
# Final cleanup attempt if kill() also hangs
debug_warning(MODULE, f"{label} could not be stopped even after kill()")
raise
finally:
# Ensure pipes are closed and process is reaped to avoid zombie processes
if proc.stdout:
proc.stdout.close()
if proc.stderr:
proc.stderr.close()
try:
proc.wait(timeout=0.1)
except subprocess.TimeoutExpired:
pass # Process still running, already logged warning above
def _apply_recreate_strategy(
project_dir: Path,
worktree_path: Path,
@@ -717,10 +812,25 @@ def _apply_recreate_strategy(
Returns True if the venv was successfully created, False if skipped or failed.
"""
venv_path = worktree_path / config.source_rel_path
marker_path = venv_path / VENV_SETUP_COMPLETE_MARKER
if venv_path.exists():
debug(MODULE, f"Skipping recreate {config.source_rel_path} - already exists")
return False
# Check for broken symlinks that exists() would miss
if venv_path.is_symlink() and not venv_path.exists():
debug(MODULE, f"Removing broken symlink at {config.source_rel_path}")
try:
venv_path.unlink()
except OSError:
pass # Best-effort removal
elif venv_path.exists():
if marker_path.exists():
debug(
MODULE,
f"Skipping recreate {config.source_rel_path} - already complete (marker present)",
)
return False
# Venv exists but marker is missing — incomplete, remove and rebuild
debug(MODULE, f"Removing incomplete venv {config.source_rel_path} (no marker)")
shutil.rmtree(venv_path, ignore_errors=True)
# Detect Python executable from the source venv or fall back to sys.executable
source_venv = project_dir / config.source_rel_path
@@ -737,29 +847,34 @@ def _apply_recreate_strategy(
# Create the venv
try:
debug(MODULE, f"Creating venv at {venv_path}")
result = subprocess.run(
returncode, _, stderr = _popen_with_cleanup(
[python_exec, "-m", "venv", str(venv_path)],
capture_output=True,
text=True,
timeout=120,
label=f"venv creation ({config.source_rel_path})",
)
if result.returncode != 0:
debug_warning(MODULE, f"venv creation failed: {result.stderr}")
if returncode != 0:
debug_warning(MODULE, f"venv creation failed: {stderr}")
print_status(
f"Warning: Could not create venv at {config.source_rel_path}",
"warning",
)
# Clean up partial venv so retries aren't blocked
if venv_path.exists():
shutil.rmtree(venv_path, ignore_errors=True)
return False
except subprocess.TimeoutExpired:
debug_warning(MODULE, f"venv creation timed out for {config.source_rel_path}")
print_status(
f"Warning: venv creation timed out for {config.source_rel_path}",
"warning",
)
# Clean up partial venv so retries aren't blocked
if venv_path.exists():
shutil.rmtree(venv_path, ignore_errors=True)
return False
except OSError as e:
debug_warning(MODULE, f"venv creation failed: {e}")
print_status(
f"Warning: Could not create venv at {config.source_rel_path}",
"warning",
)
if venv_path.exists():
shutil.rmtree(venv_path, ignore_errors=True)
return False
@@ -800,46 +915,45 @@ def _apply_recreate_strategy(
if install_cmd:
try:
debug(MODULE, f"Installing deps from {req_file}")
pip_result = subprocess.run(
returncode, _, stderr = _popen_with_cleanup(
install_cmd,
capture_output=True,
text=True,
timeout=120,
timeout=300,
label=f"pip install ({req_file})",
)
if pip_result.returncode != 0:
if returncode != 0:
debug_warning(
MODULE,
f"pip install failed (exit {pip_result.returncode}): "
f"{pip_result.stderr}",
f"pip install failed (exit {returncode}): {stderr}",
)
print_status(
f"Warning: Dependency install failed for {req_file}",
"warning",
)
# Clean up broken venv so retries aren't blocked
if venv_path.exists():
shutil.rmtree(venv_path, ignore_errors=True)
return False
except subprocess.TimeoutExpired:
debug_warning(
MODULE,
f"pip install timed out for {req_file}",
)
print_status(
f"Warning: Dependency install timed out for {req_file}",
"warning",
)
# Clean up broken venv so retries aren't blocked
if venv_path.exists():
shutil.rmtree(venv_path, ignore_errors=True)
return False
except OSError as e:
debug_warning(MODULE, f"pip install failed: {e}")
# Clean up broken venv so retries aren't blocked
if venv_path.exists():
shutil.rmtree(venv_path, ignore_errors=True)
return False
# Write completion marker so future runs know this venv is complete
try:
marker_path.touch()
except OSError as e:
debug_warning(
MODULE, f"Failed to write completion marker at {marker_path}: {e}"
)
debug(MODULE, f"Recreated venv at {config.source_rel_path}")
return True
+6
View File
@@ -1211,6 +1211,9 @@ class WorktreeManager:
)
target = target_branch or self.base_branch
# Strip remote prefix (e.g., "origin/feat/x" → "feat/x") since gh expects branch names only
if target.startswith("origin/"):
target = target[len("origin/") :]
pr_title = title or f"auto-claude: {spec_name}"
# Try AI-powered PR body from project's PR template, fall back to spec summary
@@ -1381,6 +1384,9 @@ class WorktreeManager:
)
target = target_branch or self.base_branch
# Strip remote prefix (e.g., "origin/feat/x" → "feat/x") since glab expects branch names only
if target.startswith("origin/"):
target = target[len("origin/") :]
mr_title = title or f"auto-claude: {spec_name}"
# Get MR body from spec.md if available
+13 -3
View File
@@ -635,10 +635,20 @@ def get_graphiti_status() -> dict:
try:
# Attempt to import the main graphiti_memory module
import graphiti_core # noqa: F401
from graphiti_core.driver.falkordb_driver import FalkorDriver # noqa: F401
# If we got here, packages are importable
status["available"] = True # pragma: no cover
# Try LadybugDB first (preferred for Python 3.12+), fall back to kuzu
try:
import real_ladybug # noqa: F401
except ImportError:
try:
import kuzu # noqa: F401
except ImportError:
status["available"] = False
status["reason"] = (
"Graph database backend not installed (need real_ladybug or kuzu)"
)
return status
status["available"] = True
except ImportError as e:
status["available"] = False
status["reason"] = f"Graphiti packages not installed: {e}"
@@ -81,16 +81,16 @@ def mock_graphiti_core():
@pytest.fixture
def mock_falkor_driver():
"""Mock graphiti_core.driver.falkordb_driver.FalkorDriver.
def mock_kuzu_driver():
"""Mock graphiti_core.driver.kuzu_driver.KuzuDriver.
Prevents actual FalkorDB connections during tests.
Prevents actual LadybugDB/kuzu connections during tests.
Yields:
tuple: (mock_driver_class, mock_driver_instance)
"""
with patch(
"integrations.graphiti.queries_pkg.graphiti.graphiti_core.driver.falkordb_driver.FalkorDriver"
"integrations.graphiti.queries_pkg.graphiti.graphiti_core.driver.kuzu_driver.KuzuDriver"
) as mock_driver:
mock_instance = MagicMock()
mock_driver.return_value = mock_instance
@@ -15,7 +15,7 @@ Tests cover:
import json
import os
from pathlib import Path
from unittest.mock import patch
from unittest.mock import MagicMock, patch
import pytest
from integrations.graphiti.config import (
@@ -1054,20 +1054,48 @@ class TestModuleLevelFunctions:
assert "OPENAI_API_KEY" in status["errors"][0]
def test_get_graphiti_status_invalid_config_sets_reason(self, clean_env):
"""Test get_graphiti_status sets reason when config is invalid.
"""Test get_graphiti_status with validation errors (embedder misconfigured).
This tests lines 628-629 where the reason is set from validation errors.
When packages are installed but embedder config has errors, available should
still be True (embedder is optional - keyword search fallback exists).
Validation errors are reported in the errors list for informational purposes.
"""
os.environ["GRAPHITI_ENABLED"] = "true"
os.environ["GRAPHITI_EMBEDDER_PROVIDER"] = "voyage"
status = get_graphiti_status()
# Mock imports to ensure test is independent of environment
with patch.dict(
"sys.modules",
{"graphiti_core": MagicMock(), "real_ladybug": MagicMock()},
):
status = get_graphiti_status()
assert status["enabled"] is True
# available depends on whether mocked packages are resolved correctly;
# sys.modules patching should make imports succeed, but guard against
# environment quirks (consistent with test_get_graphiti_status_enabled)
assert status["available"] is True
assert len(status["errors"]) > 0
assert "VOYAGE_API_KEY" in status["errors"][0]
def test_get_graphiti_status_no_graph_backend(self, clean_env):
"""Test get_graphiti_status when graphiti_core exists but no graph DB backend.
This tests the error path in config.py lines 645-650 where graphiti_core
imports successfully but neither real_ladybug nor kuzu is available.
"""
os.environ["GRAPHITI_ENABLED"] = "true"
# Mock graphiti_core as present, but ensure real_ladybug and kuzu are absent
with patch.dict(
"sys.modules",
{"graphiti_core": MagicMock(), "real_ladybug": None, "kuzu": None},
):
status = get_graphiti_status()
assert status["enabled"] is True
assert status["available"] is False
# When config is invalid, reason should be set from errors
assert status["reason"] != ""
assert len(status["errors"]) > 0
assert "real_ladybug or kuzu" in status["reason"]
@pytest.mark.slow
def test_get_graphiti_status_with_graphiti_installed(self, clean_env):
@@ -1089,9 +1117,9 @@ class TestModuleLevelFunctions:
assert "reason" in status
assert "errors" in status
# Note: Line 641 (status["available"] = True) requires falkordb to be installed.
# Since falkordb is not installed in the test environment, that line is marked
# with pragma: no cover. The except clause (lines 642-644) is tested here.
# Note: Line 644 (status["available"] = True) requires LadybugDB/kuzu to be installed.
# Since LadybugDB/kuzu may not be installed in all test environments, that line
# may be marked with pragma: no cover. The except clause is tested here.
def test_get_available_providers_empty(self, clean_env):
"""Test get_available_providers with no credentials."""
@@ -264,7 +264,7 @@ class TestTestGraphitiConnection:
# Mock graphiti_core imports to succeed
mock_graphiti = MagicMock()
mock_falkordb_driver = MagicMock()
mock_kuzu_driver = MagicMock()
# Mock provider creation to raise ProviderError
with patch("graphiti_providers.create_llm_client") as mock_create_llm:
@@ -275,7 +275,7 @@ class TestTestGraphitiConnection:
{
"graphiti_core": MagicMock(Graphiti=mock_graphiti),
"graphiti_core.driver": MagicMock(),
"graphiti_core.driver.falkordb_driver": mock_falkordb_driver,
"graphiti_core.driver.kuzu_driver": mock_kuzu_driver,
"graphiti_providers": MagicMock(
ProviderError=ProviderError,
create_embedder=MagicMock(),
@@ -160,7 +160,7 @@ class TestTestGraphitiConnection:
"""Tests for the test_graphiti_connection async function.
Note: The function now uses embedded LadybugDB via patched KuzuDriver
instead of remote FalkorDB with host/port credentials.
instead of remote database with host/port credentials.
"""
@pytest.mark.asyncio
+2
View File
@@ -14,6 +14,7 @@ from core.progress import (
get_plan_summary,
get_progress_percentage,
is_build_complete,
is_build_ready_for_qa,
print_build_complete_banner,
print_paused_banner,
print_progress_summary,
@@ -29,6 +30,7 @@ __all__ = [
"get_plan_summary",
"get_progress_percentage",
"is_build_complete",
"is_build_ready_for_qa",
"print_build_complete_banner",
"print_paused_banner",
"print_progress_summary",
@@ -1,100 +0,0 @@
<role>
You are a fix strategy specialist. You have been spawned to provide concrete, actionable fix approaches for a reported GitHub issue.
</role>
<mission>
Analyze the codebase and provide concrete fix approaches with specific files to modify, pros/cons for each approach, and a recommended solution that follows existing codebase patterns.
</mission>
<available_context>
The issue context below includes:
- Issue title, description, labels, and comments
- Recent git commits (last 20 commits) - use these to understand recent changes and patterns
</available_context>
<root_context_integration>
If a "Root Cause Analysis" section is provided below the issue context, use it as the foundation for your fix approaches. The root cause agent has already identified the exact code location and cause — your job is to design fix strategies that address that specific root cause.
This means you can skip Step 1 (understanding the problem space) when root cause context is available, and instead focus on designing fixes that target the identified code paths.
</root_context_integration>
<investigation_process>
<step_1>
<title>Understand the Problem Space</title>
- Read the issue description to understand what needs fixing
- Use Grep and Glob to locate the relevant code
- Read the affected files to understand the current implementation
</step_1>
<step_2>
<title>Study Existing Patterns</title>
- Search for similar patterns in the codebase using Grep
- Look at how related features or modules handle similar logic
- Identify coding conventions (naming, error handling, state management)
- Note any utility functions or shared abstractions that should be reused
</step_2>
<step_3>
<title>Design Fix Approaches</title>
For each approach, specify:
- What to change: Exact files and the nature of the modification
- Complexity: simple (< 1 hour), moderate (1-4 hours), complex (> 4 hours)
- Pros: Why this approach is good
- Cons: Risks or downsides of this approach
Provide at least 2 approaches when possible:
1. The minimal fix - smallest change that resolves the issue
2. The proper fix - addresses underlying design issues if applicable
</step_3>
<step_4>
<title>Identify Files to Modify</title>
- List ALL files that need changes across all approaches
- Include test files that need updating
- Include configuration or schema files if relevant
</step_4>
<step_5>
<title>Document Gotchas</title>
- Identify edge cases the fix must handle
- Note platform-specific concerns (Windows/macOS/Linux)
- Flag any migration or backward compatibility considerations
- Warn about tightly coupled code that could break
</step_5>
</investigation_process>
<pattern_discovery>
When exploring the codebase for patterns, look for:
- How similar bugs were fixed in the past (git log, related files)
- Existing utility functions that could be reused
- Framework-level patterns (e.g., error handling middleware, validation layers)
- Test patterns for the affected module
</pattern_discovery>
<evidence_requirements>
Every fix approach MUST include:
1. Specific file paths - Not "the auth module" but "src/auth/login.ts"
2. Nature of change - What code to add, modify, or remove
3. Pattern references - Links to existing code that demonstrates the approach
4. Complexity assessment - Realistic effort estimate
</evidence_requirements>
<constraints>
- Do not provide vague advice like "improve error handling"
- Do not suggest rewriting large portions of code unless necessary
- Do not ignore existing patterns in favor of "better" approaches
- Do not recommend approaches that conflict with the project's architecture
- Do not assess impact or severity (that is the Impact Assessor's job)
- Do not analyze root cause (that is the Root Cause Analyzer's job)
</constraints>
<output_format>
Provide your analysis as structured output with:
- approaches: List of fix approaches ordered by recommendation
- recommended_approach: Index of the recommended approach
- files_to_modify: All files that need modification across all approaches
- patterns_to_follow: Existing codebase patterns the fix should follow
- gotchas: Potential pitfalls when implementing the fix
</output_format>
@@ -1,89 +0,0 @@
<role>
You are an impact assessment specialist. You have been spawned to evaluate the blast radius and severity of a reported GitHub issue.
</role>
<mission>
Assess how far-reaching the reported issue is: which components are affected, how users are impacted, and what risks exist if the issue is fixed incorrectly.
</mission>
<available_context>
The issue context below includes:
- Issue title, description, labels, and comments
- Recent git commits (last 20 commits) - use these to identify recent changes that may affect impact assessment
</available_context>
<root_context_integration>
If a "Root Cause Analysis" section is provided below the issue context, use it as the starting point for your impact assessment. The root cause agent has already identified the problematic code — your job is to trace outward from those code paths to determine blast radius and severity.
This means you can skip Steps 1-2 (identifying affected code) when root cause context is available, and instead focus on mapping dependencies outward from the identified code paths.
</root_context_integration>
<investigation_process>
<step_1>
<title>Identify Affected Code</title>
- Use Grep to find all references to the functions/modules mentioned in the issue
- Use Glob to find related files by naming patterns
- Read each affected file to understand its role
</step_1>
<step_2>
<title>Map the Dependency Graph</title>
- Trace imports and call chains from the affected code outward
- Identify which features, views, or API endpoints depend on the buggy code
- Categorize each affected component as:
- direct - Code that directly uses the buggy function/module
- indirect - Code that depends on code that uses the buggy code
- dependency - External consumers or downstream systems affected
</step_2>
<step_3>
<title>Assess User Impact</title>
- Determine which user-facing features are affected
- Evaluate if data integrity is at risk
- Check if the issue causes crashes, data loss, or security exposure
- Consider the frequency: does this affect all users or edge cases only?
</step_3>
<step_4>
<title>Evaluate Severity</title>
- critical - Data loss, security vulnerability, system crash for most users
- high - Major feature broken, significant workflow disruption
- medium - Feature partially broken, workaround exists
- low - Minor inconvenience, cosmetic issue, edge case only
</step_4>
<step_5>
<title>Assess Regression Risk</title>
- Identify what could break if the issue is fixed
- Look for tightly coupled code that might be affected by a fix
- Check if the affected code has test coverage
- Evaluate whether a fix could introduce new issues
</step_5>
</investigation_process>
<evidence_requirements>
Every impact assessment MUST include:
1. File paths - Exact locations of affected components
2. Component names - Clear identification of what is affected
3. Impact type classification - direct/indirect/dependency for each component
4. User-facing description - How end users experience the problem
</evidence_requirements>
<constraints>
- Do not identify the root cause (that is the Root Cause Analyzer's job)
- Do not suggest fixes (that is the Fix Advisor's job)
- Do not speculate about impact without reading the actual code
- Do not inflate severity; be objective and evidence-based
- Do not report components as affected unless you verified the dependency
</constraints>
<output_format>
Provide your analysis as structured output with:
- severity: Overall severity (critical/high/medium/low)
- affected_components: List of affected components with file paths and impact types
- blast_radius: Description of how far-reaching the impact is
- user_impact: How end users are affected
- regression_risk: Risk assessment for potential fixes
</output_format>
@@ -1,80 +0,0 @@
<role>
You are a reproduction and testing specialist. You have been spawned to determine if a reported GitHub issue is reproducible and assess the test coverage of the affected code.
</role>
<mission>
Determine whether the issue can be reproduced, document reproduction steps, assess existing test coverage for the affected code paths, and suggest how to write a test that verifies the fix.
</mission>
<available_context>
The issue context below includes:
- Issue title, description, labels, and comments
- Recent git commits (last 20 commits) - use these to check if tests were recently added or modified
</available_context>
<investigation_process>
<step_1>
<title>Analyze Reproducibility</title>
- Read the issue description for any reproduction steps provided
- Identify the conditions under which the bug manifests
- Determine if the issue depends on specific state, timing, or environment
- Classify reproducibility:
- yes - Clear, deterministic steps to reproduce
- likely - High probability of reproduction with the right conditions
- unlikely - Depends on rare conditions or timing
- no - Cannot be reproduced (e.g., already fixed, environment-specific)
</step_1>
<step_2>
<title>Document Reproduction Steps</title>
- Write clear, numbered steps from a clean starting state
- Include any required configuration or environment setup
- Specify expected vs actual behavior at each step
- Note any prerequisites (specific data, user state, feature flags)
</step_2>
<step_3>
<title>Assess Test Coverage</title>
- Use Glob to find test files related to the affected code
- Common patterns: *test*, *spec*, __tests__/, tests/
- Read the test files to understand what is covered
- Identify gaps: which code paths lack tests?
- Check if the specific scenario described in the issue is tested
</step_3>
<step_4>
<title>Suggest Test Approach</title>
- Recommend what type of test to write (unit, integration, e2e)
- Describe what the test should verify
- Reference existing test patterns in the codebase
- Include any mocking or setup requirements
</step_4>
</investigation_process>
<evidence_requirements>
Every reproduction analysis MUST include:
1. Test file paths - Existing test files for the affected code
2. Coverage assessment - What is tested and what is not
3. Concrete reproduction steps - Not vague descriptions
4. Test approach - Specific enough for a developer to implement
</evidence_requirements>
<constraints>
- Do not write the actual test code (just describe the approach)
- Do not identify the root cause (that is the Root Cause Analyzer's job)
- Do not suggest fixes (that is the Fix Advisor's job)
- Do not assess impact (that is the Impact Assessor's job)
- Do not claim an issue is unreproducible without checking the code
- Do not list test files you haven't actually read
</constraints>
<output_format>
Provide your analysis as structured output with:
- reproducible: Whether the issue can be reproduced (yes/likely/unlikely/no)
- reproduction_steps: Numbered steps to reproduce the issue
- test_coverage: Assessment of existing test coverage (has_existing_tests, test_files, coverage_assessment)
- related_test_files: Test files related to the affected code
- suggested_test_approach: How to write a test that verifies the fix
</output_format>
@@ -1,114 +0,0 @@
<role>
You are a root cause analysis specialist. You have been spawned to trace the source of a bug or issue reported in a GitHub issue.
</role>
<mission>
Identify the root cause of the reported issue by tracing through the codebase. Find the exact code path from entry point to the underlying problem.
</mission>
<available_context>
The issue context below includes:
- Issue title, description, labels, and comments
- Recent git commits (last 20 commits) - USE THESE to identify recent changes that may have introduced the bug
</available_context>
<image_analysis>
If the issue context includes an "Images" section with screenshot URLs:
- Treat these as PRIMARY EVIDENCE - screenshots often show the actual bug manifestation
- Use image URLs to understand visual bugs, UI issues, error messages, or crash screens
- When the issue description is vague but screenshots are provided, prioritize the visual evidence
- Describe what you see in the images in your evidence section (e.g., "Screenshot shows X component displaying incorrectly")
- If the screenshot shows an error message, trace that error in the codebase
</image_analysis>
<investigation_process>
<step_1>
<title>Understand the Issue</title>
- Check the Images section first - screenshots may show the actual bug
- Read the issue title and description carefully
- Identify the reported symptoms (error messages, unexpected behavior, crashes)
- Note any file paths, stack traces, or code references mentioned
- If screenshots are provided, describe the visual evidence you observe
</step_1>
<step_2>
<title>Review Recent Commits</title>
- Check the Recent Commits section in the issue context
- Look for commits that modified files related to the issue
- Identify recent changes that might have introduced the bug
- If a commit message mentions the issue or related symptoms, investigate that commit first
</step_2>
<step_3>
<title>Locate Entry Points</title>
- Use Grep to find relevant functions, classes, or files mentioned in the issue
- Identify the user-facing entry point where the problem manifests
- Read the entry point code with surrounding context
</step_3>
<step_4>
<title>Trace the Code Path</title>
- Follow the execution flow from the entry point inward
- Use Grep to find function definitions, callers, and imports
- Read each file in the chain to understand data flow
- Identify where the logic diverges from expected behavior
</step_4>
<step_5>
<title>Identify the Root Cause</title>
- Pinpoint the exact code location where the bug originates
- Distinguish between the symptom (where the error appears) and the cause (where the logic is wrong)
- Check if the issue is in recently changed code or a pre-existing problem
- Cross-reference with recent commits - did a recent change introduce this issue?
</step_5>
<step_6>
<title>Check If Already Fixed</title>
- Search for recent changes to the affected files using git log or git show
- Look for commits that might have addressed this issue
- Check if the problematic code pattern still exists in the current codebase
</step_6>
</investigation_process>
<evidence_requirements>
Every root cause identification MUST include:
1. File paths and line numbers - Exact locations in the codebase
2. Code snippets - Copy-paste the actual problematic code (not descriptions)
3. Execution trace - How the code flows from entry point to the bug
4. Confidence level - How certain you are about the root cause
</evidence_requirements>
<confidence_levels>
- high - You found the exact code causing the issue, verified with code evidence
- medium - You identified a likely cause but could not fully verify (e.g., depends on runtime state)
- low - You found a plausible explanation but other causes are equally likely
</confidence_levels>
<constraints>
- Do not speculate without reading the actual code
- Do not report multiple unrelated potential causes; identify the MOST LIKELY one
- Do not suggest fixes (that is the Fix Advisor's job)
- Do not assess impact (that is the Impact Assessor's job)
- Do not explore code paths unrelated to the reported issue
</constraints>
<depth_requirements>
- You MUST trace at least 3 levels deep in the call chain (entry point → intermediate → root cause location) before concluding
- You MUST explore at least 2 competing hypotheses before settling on a root cause — read both code paths and explain why one is more likely
- Do NOT conclude with "medium" or "low" confidence if you still have unexplored code paths you could Read or Grep
- If the issue mentions a UI behavior, trace it from the React component through the store, IPC handler, and into the backend
- If you find the likely cause early, keep investigating to VERIFY it — read callers, check edge cases, look for related patterns
- Use your full tool budget. Read more files, run more greps. Thoroughness is more valuable than speed for root cause analysis
</depth_requirements>
<output_format>
Provide your analysis as structured output with:
- identified_root_cause: Clear description of what causes the issue
- code_paths: Ordered list of code locations from entry point to root cause
- confidence: Your confidence level (high/medium/low)
- evidence: Code snippets and traces supporting your analysis
- related_issues: Known issue patterns this matches (e.g., "race condition", "null reference")
- likely_already_fixed: True if evidence suggests the issue is already resolved
</output_format>
+7 -1
View File
@@ -24,7 +24,7 @@ You MUST create `spec.md` with ALL required sections (see template below).
## PHASE 0: LOAD ALL CONTEXT (MANDATORY)
```bash
# Read all input files
# Read all input files (some may not exist for greenfield/empty projects)
cat project_index.json
cat requirements.json
cat context.json
@@ -35,6 +35,12 @@ Extract from these files:
- **From requirements.json**: Task description, workflow type, services, acceptance criteria
- **From context.json**: Files to modify, files to reference, patterns
**IMPORTANT**: If any input file is missing, empty, or shows 0 files, this is likely a **greenfield/new project**. Adapt accordingly:
- Skip sections that reference existing code (e.g., "Files to Modify", "Patterns to Follow")
- Instead, focus on files to CREATE and the initial project structure
- Define the tech stack, dependencies, and setup instructions from scratch
- Use industry best practices as patterns rather than referencing existing code
---
## PHASE 1: ANALYZE CONTEXT
+3 -3
View File
@@ -8,7 +8,7 @@ Manages acceptance criteria validation and status tracking.
import json
from pathlib import Path
from progress import is_build_complete
from progress import is_build_ready_for_qa
# =============================================================================
# IMPLEMENTATION PLAN I/O
@@ -95,10 +95,10 @@ def should_run_qa(spec_dir: Path) -> bool:
Determine if QA validation should run.
QA should run when:
- All subtasks are completed
- All subtasks have reached a terminal state (completed, failed, or stuck)
- QA has not yet approved
"""
if not is_build_complete(spec_dir):
if not is_build_ready_for_qa(spec_dir):
return False
if is_qa_approved(spec_dir):
+6 -36
View File
@@ -13,10 +13,13 @@ from pathlib import Path
# Memory integration for cross-session learning
from agents.base import sanitize_error_message
from agents.investigation_context import load_investigation_context
from agents.memory_manager import get_graphiti_context, save_session_memory
from claude_agent_sdk import ClaudeSDKClient
from core.error_utils import is_rate_limit_error, is_tool_concurrency_error
from core.error_utils import (
is_rate_limit_error,
is_tool_concurrency_error,
safe_receive_messages,
)
from debug import debug, debug_detailed, debug_error, debug_section, debug_success
from security.tool_input_validator import get_safe_tool_input
from task_logger import (
@@ -128,39 +131,6 @@ async def run_qa_fixer_session(
print("✓ Memory context loaded for QA fixer")
debug_success("qa_fixer", "Graphiti memory context loaded for fixer")
# Load investigation context for GitHub-sourced tasks
investigation_context = load_investigation_context(spec_dir)
if investigation_context:
# Format investigation context for the fixer
inv = investigation_context
inv_prompt = "\n## Investigation Context\n\n"
inv_prompt += "The original investigation identified:\n\n"
if inv.get("root_cause", {}).get("summary"):
inv_prompt += f"- **Root cause**: {inv['root_cause']['summary']}\n"
if inv.get("reproducer"):
inv_prompt += f"- **Reproducer**: {inv['reproducer']}\n"
if inv.get("fix_approaches"):
inv_prompt += "\n**Recommended fix approaches:**\n"
for i, approach in enumerate(inv["fix_approaches"][:3], 1):
inv_prompt += f"{i}. {approach.get('name', 'Approach')}: "
if approach.get("description"):
inv_prompt += approach["description"]
inv_prompt += "\n"
inv_prompt += (
"\n**Guidance**: Ensure your fix actually addresses these findings. "
)
inv_prompt += (
"Don't just make the QA errors go away — fix the underlying issue.\n"
)
prompt += inv_prompt
print("✓ Investigation context loaded for QA fixer")
debug_success("qa_fixer", "Investigation context loaded for fixer")
# Add session context - use full path so agent can find files
prompt += f"\n\n---\n\n**Fix Session**: {fix_session}\n"
prompt += f"**Spec Directory**: {spec_dir}\n"
@@ -175,7 +145,7 @@ async def run_qa_fixer_session(
response_text = ""
debug("qa_fixer", "Starting to receive response stream...")
async for msg in client.receive_response():
async for msg in safe_receive_messages(client, caller="qa_fixer"):
msg_type = type(msg).__name__
message_count += 1
debug_detailed(
+20 -13
View File
@@ -28,7 +28,7 @@ from phase_config import (
get_phase_model_betas,
)
from phase_event import ExecutionPhase, emit_phase
from progress import count_subtasks, is_build_complete
from progress import count_subtasks, is_build_ready_for_qa
from security.constants import PROJECT_DIR_ENV_VAR
from task_logger import (
LogPhase,
@@ -114,14 +114,25 @@ async def run_qa_validation_loop(
# Initialize task logger for the validation phase
task_logger = get_task_logger(spec_dir)
# Verify build is complete
if not is_build_complete(spec_dir):
debug_warning("qa_loop", "Build is not complete, cannot run QA")
print("\n❌ Build is not complete. Cannot run QA validation.")
completed, total = count_subtasks(spec_dir)
debug("qa_loop", "Build progress", completed=completed, total=total)
print(f" Progress: {completed}/{total} subtasks completed")
return False
# Check if there's pending human feedback that needs to be processed
fix_request_file = spec_dir / "QA_FIX_REQUEST.md"
has_human_feedback = fix_request_file.exists()
# Human feedback takes priority — if the user explicitly asked to proceed,
# skip the build completeness gate entirely
if not has_human_feedback:
# Verify build is ready for QA (all subtasks in terminal state)
if not is_build_ready_for_qa(spec_dir):
debug_warning(
"qa_loop", "Build is not ready for QA - subtasks still in progress"
)
print("\n❌ Build is not ready for QA validation.")
completed, total = count_subtasks(spec_dir)
debug("qa_loop", "Build progress", completed=completed, total=total)
print(
f" Progress: {completed}/{total} subtasks in terminal state (completed/failed/stuck)"
)
return False
# Emit phase event at start of QA validation (before any early returns)
emit_phase(ExecutionPhase.QA_REVIEW, "Starting QA validation")
@@ -136,10 +147,6 @@ async def run_qa_validation_loop(
f"[Fast Mode] {'ENABLED' if fast_mode else 'disabled'} for QA validation",
)
# Check if there's pending human feedback that needs to be processed
fix_request_file = spec_dir / "QA_FIX_REQUEST.md"
has_human_feedback = fix_request_file.exists()
# Check if already approved - but if there's human feedback, we need to process it first
if is_qa_approved(spec_dir) and not has_human_feedback:
debug_success("qa_loop", "Build already approved by QA")
+6 -95
View File
@@ -8,20 +8,19 @@ acceptance criteria.
Memory Integration:
- Retrieves past patterns, gotchas, and insights before QA session
- Saves QA findings (bugs, patterns, validation outcomes) after session
Investigation Integration:
- Loads GitHub investigation context for issue-based validation
"""
import json
from pathlib import Path
# Memory integration for cross-session learning
from agents.base import sanitize_error_message
from agents.investigation_context import load_investigation_for_qa
from agents.memory_manager import get_graphiti_context, save_session_memory
from claude_agent_sdk import ClaudeSDKClient
from core.error_utils import is_rate_limit_error, is_tool_concurrency_error
from core.error_utils import (
is_rate_limit_error,
is_tool_concurrency_error,
safe_receive_messages,
)
from debug import debug, debug_detailed, debug_error, debug_section, debug_success
from prompts_pkg import get_qa_reviewer_prompt
from security.tool_input_validator import get_safe_tool_input
@@ -112,94 +111,6 @@ async def run_qa_agent_session(
print("✓ Memory context loaded for QA reviewer")
debug_success("qa_reviewer", "Graphiti memory context loaded for QA")
# Load investigation context for GitHub-sourced tasks
task_metadata_path = spec_dir / "task_metadata.json"
base_branch = "main" # Default base branch
# Try to read base_branch from task_metadata.json
if task_metadata_path.exists():
try:
with open(task_metadata_path) as f:
task_metadata = json.load(f)
base_branch = task_metadata.get("baseBranch", "main")
except (json.JSONDecodeError, OSError):
pass
investigation_context = load_investigation_for_qa(spec_dir, base_branch)
if investigation_context:
# Format investigation context for the prompt
inv = investigation_context
inv_prompt = "\n## GitHub Issue Validation\n\n"
inv_prompt += "This task was created from a GitHub issue investigation. "
inv_prompt += "You must verify that the issue is actually fixed.\n\n"
if inv.get("root_cause", {}).get("summary"):
inv_prompt += f"**Root Cause:** {inv['root_cause']['summary']}\n\n"
if inv.get("root_cause", {}).get("evidence"):
inv_prompt += (
f"**Evidence of the Issue:**\n{inv['root_cause']['evidence']}\n\n"
)
if inv.get("root_cause", {}).get("code_paths"):
inv_prompt += "**Affected Code Paths:**\n"
for path in inv["root_cause"]["code_paths"]:
file_ref = path.get("file", "unknown")
start = path.get("start_line", "")
end = path.get("end_line", "")
desc = path.get("description", "")
line_range = f":{start}-{end}" if start and end else ""
inv_prompt += f"- `{file_ref}{line_range}`"
if desc:
inv_prompt += f"{desc}"
inv_prompt += "\n"
inv_prompt += "\n"
if inv.get("reproducer"):
reproducer = inv["reproducer"]
inv_prompt += "**Verification Steps:**\n"
steps = reproducer.get("reproduction_steps", [])
for step in steps:
inv_prompt += f"- {step}\n"
test_approach = reproducer.get("suggested_test_approach")
if test_approach:
inv_prompt += f"\n**Suggested Test Approach:** {test_approach}\n"
inv_prompt += "\n"
inv_prompt += "**ACTION REQUIRED:** Attempt to reproduce the issue following these steps. "
inv_prompt += "If a reproducer script or test is mentioned, run it to confirm the issue is fixed.\n\n"
if inv.get("impact"):
inv_prompt += "**Expected Impact:**\n"
if inv["impact"].get("severity"):
inv_prompt += f"- **Severity:** {inv['impact']['severity']}\n"
if inv["impact"].get("user_impact"):
inv_prompt += f"- **User Impact:** {inv['impact']['user_impact']}\n"
if inv["impact"].get("blast_radius"):
inv_prompt += f"- **Blast Radius:** {inv['impact']['blast_radius']}\n"
if inv["impact"].get("regression_risk"):
inv_prompt += (
f"- **Regression Risk:** {inv['impact']['regression_risk']}\n"
)
inv_prompt += "\n"
inv_prompt += "**Validation Checklist:**\n"
inv_prompt += "In your review, you MUST:\n"
inv_prompt += "1. Verify the root cause is addressed\n"
inv_prompt += "2. Validate the issue is resolved"
if inv.get("reproducer"):
inv_prompt += " (run the reproducer)\n"
else:
inv_prompt += "\n"
inv_prompt += "3. Check for regressions\n"
inv_prompt += "4. Verify minimal changes\n\n"
inv_prompt += f"You are comparing changes from branch `{inv.get('base_branch', 'main')}` to the current worktree.\n"
inv_prompt += "Focus your review on whether these changes actually fix the described issue.\n"
prompt += inv_prompt
print("✓ Investigation context loaded for QA reviewer")
debug_success("qa_reviewer", "Investigation context loaded for QA validation")
# Add session context
prompt += f"\n\n---\n\n**QA Session**: {qa_session}\n"
prompt += f"**Max Iterations**: {max_iterations}\n"
@@ -288,7 +199,7 @@ This is attempt {previous_error.get("consecutive_errors", 1) + 1}. If you fail t
response_text = ""
debug("qa_reviewer", "Starting to receive response stream...")
async for msg in client.receive_response():
async for msg in safe_receive_messages(client, caller="qa_reviewer"):
msg_type = type(msg).__name__
message_count += 1
debug_detailed(
+4 -3
View File
@@ -1,7 +1,8 @@
# Auto-Build Framework Dependencies
# SDK 0.1.33+ required for Opus 4.6 adaptive thinking support
# Earlier versions lacked effort parameter and thinking type configuration
claude-agent-sdk>=0.1.33
# SDK 0.1.39+ required for Opus 4.6 adaptive thinking support and stability fixes
# Earlier versions lacked effort parameter, thinking type configuration,
# and crashed on unhandled CLI message types (e.g., rate_limit_event)
claude-agent-sdk>=0.1.39
python-dotenv>=1.0.0
# TOML parsing fallback for Python < 3.11
+6 -4
View File
@@ -153,8 +153,9 @@ class BotDetector:
# Identify bot username from token
self.bot_username = self._get_bot_username()
logger.debug(
f"[BotDetector] Initialized: bot_user={self.bot_username}, review_own_prs={review_own_prs}"
print(
f"[BotDetector] Initialized: bot_user={self.bot_username}, review_own_prs={review_own_prs}",
file=sys.stderr,
)
def _get_bot_username(self) -> str | None:
@@ -165,8 +166,9 @@ class BotDetector:
Bot username or None if token not provided or invalid
"""
if not self.bot_token:
logger.debug(
"[BotDetector] No bot token provided, cannot identify bot user"
print(
"[BotDetector] No bot token provided, cannot identify bot user",
file=sys.stderr,
)
return None
+9 -171
View File
@@ -331,12 +331,7 @@ class GHClient:
args = self._add_repo_flag(args)
result = await self.run(args)
try:
return json.loads(result.stdout) if result.stdout.strip() else []
except json.JSONDecodeError:
logger.warning("Failed to parse PR list response as JSON")
logger.debug("Raw stdout (truncated): %s", result.stdout[:200])
return []
return json.loads(result.stdout)
async def pr_get(
self, pr_number: int, json_fields: list[str] | None = None
@@ -376,12 +371,7 @@ class GHClient:
args = self._add_repo_flag(args)
result = await self.run(args)
try:
return json.loads(result.stdout) if result.stdout.strip() else {}
except json.JSONDecodeError:
logger.warning("Failed to parse PR #%d response as JSON", pr_number)
logger.debug("Raw stdout (truncated): %s", result.stdout[:200])
return {}
return json.loads(result.stdout)
async def pr_diff(self, pr_number: int) -> str:
"""
@@ -486,15 +476,9 @@ class GHClient:
"--json",
",".join(json_fields),
]
args = self._add_repo_flag(args)
result = await self.run(args)
try:
return json.loads(result.stdout) if result.stdout.strip() else []
except json.JSONDecodeError:
logger.warning("Failed to parse issue list response as JSON")
logger.debug("Raw stdout (truncated): %s", result.stdout[:200])
return []
return json.loads(result.stdout)
async def issue_get(
self, issue_number: int, json_fields: list[str] | None = None
@@ -529,135 +513,20 @@ class GHClient:
"--json",
",".join(json_fields),
]
args = self._add_repo_flag(args)
result = await self.run(args)
try:
return json.loads(result.stdout) if result.stdout.strip() else {}
except json.JSONDecodeError:
logger.warning("Failed to parse issue #%d response as JSON", issue_number)
logger.debug("Raw stdout (truncated): %s", result.stdout[:200])
return {}
return json.loads(result.stdout)
async def issue_comment(self, issue_number: int, body: str) -> int:
async def issue_comment(self, issue_number: int, body: str) -> None:
"""
Post a comment to an issue.
Args:
issue_number: Issue number
body: Comment body
Returns:
The ID of the created comment
Raises:
GHCommandError: If the gh CLI command fails
ValueError: If the comment ID is not returned
"""
# Use GitHub API directly via 'gh api' to post the comment
# This allows us to get JSON response with the comment ID
# Note: gh issue comment doesn't support --json flag, but gh api does
endpoint = f"repos/{{owner}}/{{repo}}/issues/{issue_number}/comments"
args = [
"api",
"--method",
"POST",
endpoint,
"-f",
f"body={body}",
"--jq",
".id",
]
# Note: gh api doesn't use -R flag, the repo is already in the endpoint URL
# Only add -R if we have a custom repo configured (not the default from git)
if self.repo:
# For gh api, we need to use --hostname to specify a different repo
# But since the endpoint already has {{owner}}/{{repo}}, it will be
# expanded correctly by gh CLI using the default git remote
pass
result = await self.run(args, raise_on_error=False)
# Check for gh CLI errors
if result.returncode != 0:
stderr_lower = result.stderr.lower()
error_msg = (
result.stderr.strip()
or f"gh CLI failed with exit code {result.returncode}"
)
# Provide user-friendly error messages for common failure modes
if (
"401" in result.stderr
or "unauthenticated" in stderr_lower
or "not logged in" in stderr_lower
):
raise GHCommandError(
"GitHub authentication failed. Please run 'gh auth login' to authenticate."
)
elif (
"403" in result.stderr
or "429" in result.stderr
or "rate limit" in stderr_lower
):
raise GHCommandError(
"GitHub API rate limit exceeded. Please wait a few minutes before trying again."
)
elif "404" in result.stderr or "not found" in stderr_lower:
if self.repo:
raise GHCommandError(
f"Repository or issue not found. Please verify that the repository '{self.repo}' exists and you have access to it."
)
else:
raise GHCommandError(
f"Issue #{issue_number} not found. Please verify that the issue exists in the repository."
)
elif "permission" in stderr_lower or "forbidden" in stderr_lower:
raise GHCommandError(
"You do not have permission to comment on this issue. Please ensure you have write access to the repository."
)
# Generic error with stderr output
raise GHCommandError(f"Failed to post comment to GitHub: {error_msg}")
# Parse the comment ID from the output (gh api --jq .id returns just the ID)
try:
stdout = result.stdout.strip()
if not stdout:
raise ValueError("Empty response from GitHub API")
comment_id = int(stdout)
if comment_id:
return comment_id
else:
raise ValueError(f"Invalid comment ID returned: {stdout}")
except (ValueError, json.JSONDecodeError) as e:
logger.error(
"Failed to parse comment ID response for issue #%d: %s", issue_number, e
)
logger.debug("Raw stdout (first 500 chars): %s", result.stdout[:500])
logger.debug("Raw stderr (first 500 chars): %s", result.stderr[:500])
raise ValueError(f"Failed to parse GitHub response: {str(e)}")
async def issue_comments(self, issue_number: int) -> list[dict]:
"""
Fetch comments on an issue.
Args:
issue_number: Issue number
Returns:
List of comment dicts from the GitHub API
"""
endpoint = f"repos/{{owner}}/{{repo}}/issues/{issue_number}/comments"
args = ["api", "--method", "GET", endpoint]
result = await self.run(args, raise_on_error=False)
if result.returncode == 0:
try:
return json.loads(result.stdout)
except json.JSONDecodeError:
logger.warning(f"Failed to parse comments for issue #{issue_number}")
return []
args = ["issue", "comment", str(issue_number), "--body", body]
await self.run(args)
async def issue_add_labels(self, issue_number: int, labels: list[str]) -> None:
"""
@@ -677,7 +546,6 @@ class GHClient:
"--add-label",
",".join(labels),
]
args = self._add_repo_flag(args)
await self.run(args)
async def issue_remove_labels(self, issue_number: int, labels: list[str]) -> None:
@@ -698,7 +566,6 @@ class GHClient:
"--remove-label",
",".join(labels),
]
args = self._add_repo_flag(args)
# Don't raise on error - labels might not exist
await self.run(args, raise_on_error=False)
@@ -720,12 +587,7 @@ class GHClient:
args.extend(["-f", f"{key}={value}"])
result = await self.run(args)
try:
return json.loads(result.stdout) if result.stdout.strip() else {}
except json.JSONDecodeError:
logger.warning("Failed to parse API response for %s as JSON", endpoint)
logger.debug("Raw stdout (truncated): %s", result.stdout[:200])
return {}
return json.loads(result.stdout)
async def pr_merge(
self,
@@ -765,25 +627,6 @@ class GHClient:
args = self._add_repo_flag(args)
await self.run(args)
async def pr_comment_reply(
self, pr_number: int, comment_id: int, body: str
) -> None:
"""
Reply to a specific review comment on a pull request.
Uses: POST /repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies
Args:
pr_number: PR number (used for the API endpoint)
comment_id: The ID of the review comment to reply to
body: Reply body text
"""
endpoint = (
f"repos/{{owner}}/{{repo}}/pulls/{pr_number}/comments/{comment_id}/replies"
)
args = ["api", "--method", "POST", endpoint, "-f", f"body={body}"]
await self.run(args)
async def pr_get_assignees(self, pr_number: int) -> list[str]:
"""
Get assignees for a pull request.
@@ -843,12 +686,7 @@ class GHClient:
args = ["api", endpoint]
result = await self.run(args, timeout=60.0) # Longer timeout for large diffs
try:
return json.loads(result.stdout) if result.stdout.strip() else {}
except json.JSONDecodeError:
logger.warning("Failed to parse commit comparison response as JSON")
logger.debug("Raw stdout (truncated): %s", result.stdout[:200])
return {}
return json.loads(result.stdout)
async def get_comments_since(
self, pr_number: int, since_timestamp: str
-32
View File
@@ -1004,12 +1004,6 @@ class GitHubRunnerConfig:
True # Use SDK subagent parallel orchestrator (default)
)
# Investigation settings
investigation_auto_post: bool = False
investigation_auto_close: bool = False
investigation_max_parallel: int = 3
investigation_pipeline_mode: str = "full"
# Model settings
# Note: Default uses shorthand "sonnet" which gets resolved via resolve_model_id()
# to respect environment variable overrides (e.g., ANTHROPIC_DEFAULT_SONNET_MODEL)
@@ -1017,10 +1011,6 @@ class GitHubRunnerConfig:
thinking_level: str = "medium"
fast_mode: bool = False
# Per-specialist investigation config (overrides model/thinking_level for each specialist)
# Dict mapping specialist name → {"model": str, "thinking": str}
specialist_config: dict[str, dict[str, str]] | None = None
def to_dict(self) -> dict:
return {
"token": "***", # Never save token
@@ -1043,10 +1033,6 @@ class GitHubRunnerConfig:
"model": self.model,
"thinking_level": self.thinking_level,
"fast_mode": self.fast_mode,
"investigation_auto_post": self.investigation_auto_post,
"investigation_auto_close": self.investigation_auto_close,
"investigation_max_parallel": self.investigation_max_parallel,
"investigation_pipeline_mode": self.investigation_pipeline_mode,
}
def save_settings(self, github_dir: Path) -> None:
@@ -1075,9 +1061,6 @@ class GitHubRunnerConfig:
else:
settings = {}
# Load investigation_settings from nested structure if present
investigation_settings = settings.get("investigation_settings", {})
return cls(
token=token,
repo=repo,
@@ -1103,19 +1086,4 @@ class GitHubRunnerConfig:
# Note: model is stored as shorthand and resolved via resolve_model_id()
model=settings.get("model", "sonnet"),
thinking_level=settings.get("thinking_level", "medium"),
# Load fast_mode from investigation_settings (front-end uses camelCase "fastInvestigations")
fast_mode=investigation_settings.get("fastInvestigations", False),
# Load investigation settings from nested structure
investigation_auto_post=investigation_settings.get(
"autoPostToGitHub", False
),
investigation_auto_close=investigation_settings.get(
"autoCloseIssues", False
),
investigation_max_parallel=investigation_settings.get(
"maxParallelInvestigations", 3
),
investigation_pipeline_mode=investigation_settings.get(
"pipelineMode", "full"
),
)
@@ -53,6 +53,7 @@ class RepoConfig:
relationship: Relationship to other repos
upstream_repo: Upstream repo if this is a fork
labels: Label configuration overrides
trust_level: Trust level for this repo
"""
repo: str # owner/repo format
@@ -63,6 +64,7 @@ class RepoConfig:
labels: dict[str, list[str]] = field(
default_factory=dict
) # e.g., {"auto_fix": ["fix-me"]}
trust_level: int = 0 # 0-4 trust level
display_name: str | None = None # Human-readable name
# Feature toggles per repo
@@ -123,6 +125,7 @@ class RepoConfig:
"relationship": self.relationship.value,
"upstream_repo": self.upstream_repo,
"labels": self.labels,
"trust_level": self.trust_level,
"display_name": self.display_name,
"auto_fix_enabled": self.auto_fix_enabled,
"pr_review_enabled": self.pr_review_enabled,
@@ -138,6 +141,7 @@ class RepoConfig:
relationship=RepoRelationship(data.get("relationship", "standalone")),
upstream_repo=data.get("upstream_repo"),
labels=data.get("labels", {}),
trust_level=data.get("trust_level", 0),
display_name=data.get("display_name"),
auto_fix_enabled=data.get("auto_fix_enabled", True),
pr_review_enabled=data.get("pr_review_enabled", True),
+3 -388
View File
@@ -43,12 +43,9 @@ try:
from .services import (
AutoFixProcessor,
BatchProcessor,
EnrichmentEngine,
PRReviewEngine,
SplitEngine,
TriageEngine,
)
from .services.investigation_label_manager import InvestigationLabelManager
from .services.io_utils import safe_print
except (ImportError, ValueError, SystemError):
# When imported directly (runner.py adds github dir to path)
@@ -75,12 +72,9 @@ except (ImportError, ValueError, SystemError):
from services import (
AutoFixProcessor,
BatchProcessor,
EnrichmentEngine,
PRReviewEngine,
SplitEngine,
TriageEngine,
)
from services.investigation_label_manager import InvestigationLabelManager
from services.io_utils import safe_print
@@ -191,26 +185,6 @@ class GitHubOrchestrator:
progress_callback=self.progress_callback,
)
self.enrichment_engine = EnrichmentEngine(
project_dir=self.project_dir,
github_dir=self.github_dir,
config=self.config,
progress_callback=self.progress_callback,
)
self.split_engine = SplitEngine(
project_dir=self.project_dir,
github_dir=self.github_dir,
config=self.config,
progress_callback=self.progress_callback,
)
# Read investigation label customization from config
label_customization = self._load_investigation_label_customization()
self.label_manager = InvestigationLabelManager(
customization=label_customization
)
def _report_progress(
self,
phase: str,
@@ -264,9 +238,9 @@ class GitHubOrchestrator:
event=event.lower(),
)
async def _post_issue_comment(self, issue_number: int, body: str) -> int:
"""Post a comment to an issue and return the comment ID."""
return await self.gh_client.issue_comment(issue_number, body)
async def _post_issue_comment(self, issue_number: int, body: str) -> None:
"""Post a comment to an issue."""
await self.gh_client.issue_comment(issue_number, body)
async def _add_issue_labels(self, issue_number: int, labels: list[str]) -> None:
"""Add labels to an issue."""
@@ -309,24 +283,6 @@ class GitHubOrchestrator:
# Helper Methods
# =========================================================================
def _load_investigation_label_customization(self) -> dict | None:
"""Load investigation label customization from GitHub config."""
try:
config_path = self.github_dir / "config.json"
if config_path.exists():
import json
with open(config_path) as f:
config = json.load(f)
investigation_settings = config.get("investigation_settings", {})
return investigation_settings.get("labelCustomization")
except Exception as e:
safe_print(
f"[DEBUG orchestrator] Could not load label customization: {e}",
flush=True,
)
return None
async def _create_skip_result(
self, pr_number: int, skip_reason: str
) -> PRReviewResult:
@@ -1533,347 +1489,6 @@ class GitHubOrchestrator:
self._report_progress("complete", 100, f"Triaged {len(results)} issues")
return results
# =========================================================================
# ISSUE INVESTIGATION WORKFLOW
# =========================================================================
async def _run_investigation_with_state_management(
self,
issue_number: int,
issue_title: str,
issue_body: str,
issue_labels: list[str],
issue_comments: list[str],
project_root: Path | None = None,
resume_sessions: dict[str, str] | None = None,
return_dict: bool = True,
):
"""
Core investigation logic with state and label management.
This helper method encapsulates the common pattern of:
1. Saving initial "investigating" state
2. Syncing lifecycle labels
3. Running the investigation
4. Updating state to "findings_ready" or "failed"
5. Syncing final labels
Args:
issue_number: The GitHub issue number
issue_title: The issue title
issue_body: The issue body text
issue_labels: List of label names
issue_comments: List of comment bodies
project_root: Working directory for agents
resume_sessions: Optional dict mapping specialist name to SDK session ID
return_dict: If True, return report.model_dump(); otherwise return report
Returns:
InvestigationReport (as dict if return_dict=True, else as object)
Raises:
Exception: If investigation fails
"""
from datetime import datetime, timezone
try:
from .services.investigation_persistence import (
load_investigation_state,
save_investigation_state,
)
from .services.issue_investigation_orchestrator import (
IssueInvestigationOrchestrator,
)
except (ImportError, ValueError, SystemError):
from services.investigation_persistence import (
load_investigation_state,
save_investigation_state,
)
from services.issue_investigation_orchestrator import (
IssueInvestigationOrchestrator,
)
working_dir = project_root or self.project_dir
# Save initial state, preserving any existing sessions (for resume scenarios)
existing_state = load_investigation_state(self.project_dir, issue_number)
initial_state = {
"issue_number": issue_number,
"status": "investigating",
"started_at": datetime.now(timezone.utc).isoformat(),
"model_used": self.config.model or "sonnet",
}
# Preserve existing sessions if present (resume scenario)
if existing_state and existing_state.sessions:
initial_state["sessions"] = existing_state.sessions
save_investigation_state(
self.project_dir,
issue_number,
initial_state,
)
# Sync lifecycle label to GitHub
try:
await self.label_manager.ensure_labels_exist(self.gh_client)
await self.label_manager.set_investigation_label(
self.gh_client, issue_number, "investigating"
)
except Exception as e:
safe_print(f"[Investigation] Label sync warning: {e}", flush=True)
try:
# Create investigation orchestrator
orchestrator = IssueInvestigationOrchestrator(
project_dir=self.project_dir,
github_dir=self.github_dir,
config=self.config,
progress_callback=self.progress_callback,
)
# Run investigation
report = await orchestrator.investigate(
issue_number=issue_number,
issue_title=issue_title,
issue_body=issue_body,
issue_labels=issue_labels,
issue_comments=issue_comments,
project_root=working_dir,
resume_sessions=resume_sessions,
)
# Update state to findings_ready, preserving started_at and sessions
existing_state = load_investigation_state(self.project_dir, issue_number)
started_at = (
existing_state.started_at
if existing_state
else datetime.now(timezone.utc).isoformat()
)
success_state = {
"issue_number": issue_number,
"status": "findings_ready",
"started_at": started_at,
"completed_at": datetime.now(timezone.utc).isoformat(),
"model_used": self.config.model or "sonnet",
}
# Preserve existing sessions if present (for edge case where user might want to re-run)
if existing_state and existing_state.sessions:
success_state["sessions"] = existing_state.sessions
save_investigation_state(
self.project_dir,
issue_number,
success_state,
)
# Sync lifecycle label to GitHub
try:
await self.label_manager.set_investigation_label(
self.gh_client, issue_number, "findings_ready"
)
except Exception as e:
safe_print(f"[Investigation] Label sync warning: {e}", flush=True)
return report.model_dump(mode="json") if return_dict else report
except Exception as e:
# Update state to failed, preserving any existing sessions for resume support
existing_state = load_investigation_state(self.project_dir, issue_number)
failed_state = {
"issue_number": issue_number,
"status": "failed",
"started_at": (
existing_state.started_at
if existing_state and existing_state.started_at
else datetime.now(timezone.utc).isoformat()
),
"completed_at": datetime.now(timezone.utc).isoformat(),
"error": str(e),
"model_used": self.config.model or "sonnet",
}
# Preserve existing sessions if present (critical for resume feature)
if existing_state and existing_state.sessions:
failed_state["sessions"] = existing_state.sessions
save_investigation_state(
self.project_dir,
issue_number,
failed_state,
)
# Remove lifecycle labels on failure
try:
await self.label_manager.remove_all_investigation_labels(
self.gh_client, issue_number
)
except Exception as label_err:
safe_print(
f"[Investigation] Label cleanup warning: {label_err}",
flush=True,
)
safe_print(
f"[Investigation] Investigation failed for issue #{issue_number}: {e}",
flush=True,
)
raise
async def investigate_issue(
self,
issue_number: int,
project_root: Path | None = None,
resume_sessions: dict[str, str] | None = None,
) -> dict:
"""
Run an AI investigation on a GitHub issue.
Launches 4 specialist agents in parallel (root cause, impact,
fix advisor, reproducer) to explore the codebase and produce
a structured investigation report.
Args:
issue_number: The GitHub issue number to investigate
project_root: Working directory for agents (e.g., worktree path).
Defaults to self.project_dir.
resume_sessions: Optional dict mapping specialist name to SDK
session ID for resuming interrupted investigations.
Returns:
Dict with investigation results (InvestigationReport as dict)
"""
self._report_progress(
"fetching",
5,
f"Fetching issue #{issue_number}...",
issue_number=issue_number,
)
# Fetch issue data
issue = await self._fetch_issue_data(issue_number)
issue_title = issue.get("title", f"Issue #{issue_number}")
issue_body = issue.get("body", "")
issue_labels = [label.get("name", "") for label in issue.get("labels", [])]
# Fetch comments
issue_comments = []
try:
comments_data = await self.gh_client.issue_comments(issue_number)
issue_comments = [c.get("body", "") for c in comments_data if c.get("body")]
except Exception as e:
safe_print(
f"[Investigation] Warning: Could not fetch comments: {e}",
flush=True,
)
return await self._run_investigation_with_state_management(
issue_number=issue_number,
issue_title=issue_title,
issue_body=issue_body,
issue_labels=issue_labels,
issue_comments=issue_comments,
project_root=project_root,
resume_sessions=resume_sessions,
return_dict=True,
)
async def start_investigation(
self,
issue_number: int,
issue_title: str,
issue_body: str,
issue_labels: list[str] | None = None,
issue_comments: list[str] | None = None,
):
"""
Start an AI investigation on a GitHub issue (typed API).
This is a higher-level wrapper that accepts pre-fetched issue data
and returns a typed InvestigationReport.
Args:
issue_number: The GitHub issue number
issue_title: The issue title
issue_body: The issue body text
issue_labels: Optional list of label names
issue_comments: Optional list of comment bodies
Returns:
InvestigationReport from the investigation
"""
return await self._run_investigation_with_state_management(
issue_number=issue_number,
issue_title=issue_title,
issue_body=issue_body,
issue_labels=issue_labels or [],
issue_comments=issue_comments or [],
project_root=self.project_dir,
resume_sessions=None,
return_dict=False,
)
# =========================================================================
# ENRICHMENT WORKFLOW
# =========================================================================
async def enrich_issue(self, issue_number: int) -> dict:
"""
Perform deep AI enrichment on a single issue.
Args:
issue_number: The issue number to enrich
Returns:
Dict matching AIEnrichmentResult interface
"""
self._report_progress(
"fetching",
10,
f"Fetching issue #{issue_number}...",
issue_number=issue_number,
)
issue = await self._fetch_issue_data(issue_number)
result = await self.enrichment_engine.enrich_single_issue(issue)
self._report_progress(
"complete",
100,
"Enrichment complete!",
issue_number=issue_number,
)
return result
# =========================================================================
# SPLIT SUGGESTION WORKFLOW
# =========================================================================
async def split_issue(self, issue_number: int) -> dict:
"""
Analyze an issue and suggest how to split it into sub-issues.
Args:
issue_number: The issue number to analyze
Returns:
Dict matching SplitSuggestion interface
"""
self._report_progress(
"fetching",
10,
f"Fetching issue #{issue_number}...",
issue_number=issue_number,
)
issue = await self._fetch_issue_data(issue_number)
result = await self.split_engine.suggest_split(issue)
self._report_progress(
"complete",
100,
"Split analysis complete!",
issue_number=issue_number,
)
return result
# =========================================================================
# AUTO-FIX WORKFLOW
# =========================================================================
-198
View File
@@ -177,10 +177,6 @@ def get_config(args) -> GitHubRunnerConfig:
)
sys.exit(1)
specialist_config = None
if hasattr(args, "specialist_config") and args.specialist_config:
specialist_config = json.loads(args.specialist_config)
return GitHubRunnerConfig(
token=token,
repo=repo,
@@ -191,7 +187,6 @@ def get_config(args) -> GitHubRunnerConfig:
auto_fix_enabled=getattr(args, "auto_fix_enabled", False),
auto_fix_labels=getattr(args, "auto_fix_labels", ["auto-fix"]),
auto_post_reviews=getattr(args, "auto_post", False),
specialist_config=specialist_config,
)
@@ -348,153 +343,6 @@ async def cmd_followup_review_pr(args) -> int:
return 1
async def cmd_investigate(args) -> int:
"""Run AI investigation on a GitHub issue."""
import sys
# Force unbuffered output so Electron sees it in real-time
if hasattr(sys.stdout, "reconfigure"):
sys.stdout.reconfigure(line_buffering=True)
if hasattr(sys.stderr, "reconfigure"):
sys.stderr.reconfigure(line_buffering=True)
config = get_config(args)
# Parse resume sessions if provided
resume_sessions = None
if getattr(args, "resume_sessions", None):
try:
resume_sessions = json.loads(args.resume_sessions)
except json.JSONDecodeError:
safe_print("Warning: Invalid --resume-sessions JSON, starting fresh")
orchestrator = GitHubOrchestrator(
project_dir=args.project,
config=config,
progress_callback=print_progress,
)
try:
result = await orchestrator.investigate_issue(
args.issue_number,
resume_sessions=resume_sessions,
)
# Check if investigation failed (result may contain error info)
# The investigate_issue method raises on failure, but we check result anyway
if not result:
safe_print("Error: Investigation returned no result")
return 1
# Output JSON for the Electron frontend to parse
safe_print("\nJSON Output")
safe_print(f"{'=' * 60}")
safe_print(json.dumps(result, indent=2))
return 0
except Exception as e:
# Return non-zero exit code on investigation failure
safe_print(f"Error: Investigation failed: {e}")
return 1
async def cmd_post_investigation(args) -> int:
"""Post investigation results to GitHub as a comment."""
from services.investigation_persistence import load_investigation_report
from services.investigation_report_builder import build_github_comment
def output_error(error_message: str) -> None:
"""Output an error in JSON format for the Electron frontend to parse."""
safe_print("\nJSON Output")
safe_print(f"{'=' * 60}")
safe_print(json.dumps({"success": False, "error": error_message}))
try:
config = get_config(args)
orchestrator = GitHubOrchestrator(
project_dir=args.project,
config=config,
progress_callback=print_progress,
)
# Load investigation report from .auto-claude/issues/{issueNumber}/investigation_report.json
report = load_investigation_report(args.project, args.issue_number)
if report is None:
error_msg = (
f"No investigation report found for issue #{args.issue_number}. "
f"Please run the investigation first."
)
safe_print(f"Error: {error_msg}")
output_error(error_msg)
return 1
# Build the GitHub comment from the report
comment_body = build_github_comment(report)
# Post it to GitHub
try:
comment_id = await orchestrator._post_issue_comment(
args.issue_number, comment_body
)
except Exception as e:
error_msg = f"Failed to post comment to GitHub: {str(e)}"
safe_print(f"Error: {error_msg}")
output_error(error_msg)
return 1
safe_print(f"Posted investigation results to issue #{args.issue_number}")
# Output JSON for the Electron frontend to parse
safe_print("\nJSON Output")
safe_print(f"{'=' * 60}")
safe_print(json.dumps({"success": True, "commentId": comment_id}))
return 0
except Exception as e:
error_msg = f"Unexpected error: {str(e)}"
safe_print(f"Error: {error_msg}")
output_error(error_msg)
return 1
async def cmd_enrich(args) -> int:
"""Enrich a single issue with deep AI analysis."""
config = get_config(args)
orchestrator = GitHubOrchestrator(
project_dir=args.project,
config=config,
progress_callback=print_progress,
)
result = await orchestrator.enrich_issue(args.issue_number)
# Output JSON for the Electron frontend to parse
safe_print("\nJSON Output")
safe_print(f"{'=' * 60}")
safe_print(json.dumps(result, indent=2))
return 0
async def cmd_split(args) -> int:
"""Suggest how to split an issue into sub-issues."""
config = get_config(args)
orchestrator = GitHubOrchestrator(
project_dir=args.project,
config=config,
progress_callback=print_progress,
)
result = await orchestrator.split_issue(args.issue_number)
# Output JSON for the Electron frontend to parse
safe_print("\nJSON Output")
safe_print(f"{'=' * 60}")
safe_print(json.dumps(result, indent=2))
return 0
async def cmd_triage(args) -> int:
"""Triage issues."""
config = get_config(args)
@@ -879,48 +727,6 @@ def main():
)
followup_parser.add_argument("pr_number", type=int, help="PR number to review")
# investigate command
investigate_parser = subparsers.add_parser(
"investigate", help="Run AI investigation on a GitHub issue"
)
investigate_parser.add_argument(
"issue_number", type=int, help="Issue number to investigate"
)
investigate_parser.add_argument(
"--resume-sessions",
type=str,
default=None,
help="JSON dict of specialist_name:session_id for resuming interrupted investigations",
)
investigate_parser.add_argument(
"--specialist-config",
type=str,
default=None,
help="JSON dict of specialist configs: {name: {model, thinking}}",
)
# post-investigation command
post_investigation_parser = subparsers.add_parser(
"post-investigation", help="Post investigation results to GitHub"
)
post_investigation_parser.add_argument(
"issue_number", type=int, help="Issue number to post results for"
)
# enrich command
enrich_parser = subparsers.add_parser(
"enrich", help="Enrich a single issue with deep AI analysis"
)
enrich_parser.add_argument("issue_number", type=int, help="Issue number to enrich")
# split command
split_parser = subparsers.add_parser(
"split", help="Suggest how to split an issue into sub-issues"
)
split_parser.add_argument(
"issue_number", type=int, help="Issue number to analyze for splitting"
)
# triage command
triage_parser = subparsers.add_parser("triage", help="Triage issues")
triage_parser.add_argument(
@@ -1013,10 +819,6 @@ def main():
commands = {
"review-pr": cmd_review_pr,
"followup-review-pr": cmd_followup_review_pr,
"investigate": cmd_investigate,
"post-investigation": cmd_post_investigation,
"enrich": cmd_enrich,
"split": cmd_split,
"triage": cmd_triage,
"auto-fix": cmd_auto_fix,
"check-auto-fix-labels": cmd_check_labels,
@@ -15,35 +15,9 @@ from __future__ import annotations
_LAZY_IMPORTS: dict[str, tuple[str, str]] = {
"AutoFixProcessor": (".autofix_processor", "AutoFixProcessor"),
"BatchProcessor": (".batch_processor", "BatchProcessor"),
"EnrichmentEngine": (".enrichment_engine", "EnrichmentEngine"),
"InvestigationReport": (".investigation_models", "InvestigationReport"),
"InvestigationState": (".investigation_models", "InvestigationState"),
"InvestigationLabelManager": (
".investigation_label_manager",
"InvestigationLabelManager",
),
"IssueInvestigationOrchestrator": (
".issue_investigation_orchestrator",
"IssueInvestigationOrchestrator",
),
"build_github_comment": (
".investigation_report_builder",
"build_github_comment",
),
"build_summary": (
".investigation_report_builder",
"build_summary",
),
"RootCauseAnalysis": (".investigation_models", "RootCauseAnalysis"),
"ImpactAssessment": (".investigation_models", "ImpactAssessment"),
"FixAdvice": (".investigation_models", "FixAdvice"),
"ReproductionAnalysis": (".investigation_models", "ReproductionAnalysis"),
"ParallelAgentOrchestrator": (".parallel_agent_base", "ParallelAgentOrchestrator"),
"PRReviewEngine": (".pr_review_engine", "PRReviewEngine"),
"PromptManager": (".prompt_manager", "PromptManager"),
"ResponseParser": (".response_parsers", "ResponseParser"),
"SpecialistConfig": (".parallel_agent_base", "SpecialistConfig"),
"SplitEngine": (".split_engine", "SplitEngine"),
"TriageEngine": (".triage_engine", "TriageEngine"),
}
@@ -52,22 +26,8 @@ __all__ = [
"ResponseParser",
"PRReviewEngine",
"TriageEngine",
"EnrichmentEngine",
"SplitEngine",
"AutoFixProcessor",
"BatchProcessor",
"ParallelAgentOrchestrator",
"SpecialistConfig",
"InvestigationLabelManager",
"InvestigationReport",
"InvestigationState",
"IssueInvestigationOrchestrator",
"build_github_comment",
"build_summary",
"RootCauseAnalysis",
"ImpactAssessment",
"FixAdvice",
"ReproductionAnalysis",
]
# Cache for lazily loaded modules
@@ -85,8 +45,3 @@ def __getattr__(name: str) -> object:
_loaded[name] = getattr(module, attr_name)
return _loaded[name]
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
def __dir__() -> list[str]:
"""Expose lazy imports in dir() and for static analysis."""
return list(_LAZY_IMPORTS.keys())
@@ -8,11 +8,8 @@ Handles automatic issue fixing workflow including permissions and state manageme
from __future__ import annotations
import json
import logging
from pathlib import Path
logger = logging.getLogger(__name__)
try:
from ..models import AutoFixState, AutoFixStatus, GitHubRunnerConfig
from ..permissions import GitHubPermissionChecker
@@ -148,14 +145,7 @@ class AutoFixProcessor:
except Exception as e:
if state:
try:
state.update_status(AutoFixStatus.FAILED)
except ValueError:
# Last resort: force-set if transition is invalid
logger.warning(
f"Invalid transition {state.status.value} -> failed, forcing"
)
state.status = AutoFixStatus.FAILED
state.status = AutoFixStatus.FAILED
state.error = str(e)
await state.save(self.github_dir)
raise
@@ -1,52 +0,0 @@
"""
Base Engine Class
=================
Shared functionality for GitHub runner engines (enrichment, split, etc.).
"""
from __future__ import annotations
from pathlib import Path
class EngineBase:
"""Base class for GitHub analysis engines."""
def __init__(
self,
project_dir: Path,
github_dir: Path,
config,
progress_callback=None,
):
self.project_dir = Path(project_dir)
self.github_dir = Path(github_dir)
self.config = config
self.progress_callback = progress_callback
def _report_progress(self, phase: str, progress: int, message: str, **kwargs):
"""Report progress if callback is set.
Args:
phase: Current phase name (e.g., "analyzing", "generating")
progress: Progress percentage (0-100)
message: Human-readable progress message
**kwargs: Additional context data
"""
if self.progress_callback:
import sys
if "orchestrator" in sys.modules:
ProgressCallback = sys.modules["orchestrator"].ProgressCallback
else:
try:
from ..orchestrator import ProgressCallback
except ImportError:
from orchestrator import ProgressCallback
self.progress_callback(
ProgressCallback(
phase=phase, progress=progress, message=message, **kwargs
)
)
@@ -1,223 +0,0 @@
"""
Enrichment Engine
=================
Deep analysis of a single GitHub issue to extract structured enrichment data:
problem statement, goal, scope, acceptance criteria, technical context, and risks.
"""
from __future__ import annotations
import json
import re
from pathlib import Path
try:
from ...phase_config import get_model_betas, resolve_model_id
from ..models import GitHubRunnerConfig
from .engine_base import EngineBase
from .prompt_manager import PromptManager
except (ImportError, ValueError, SystemError):
from models import GitHubRunnerConfig
from phase_config import get_model_betas, resolve_model_id
from services.engine_base import EngineBase
from services.prompt_manager import PromptManager
class EnrichmentEngine(EngineBase):
"""Handles single-issue deep enrichment via AI."""
def __init__(
self,
project_dir: Path,
github_dir: Path,
config: GitHubRunnerConfig,
progress_callback=None,
):
super().__init__(project_dir, github_dir, config, progress_callback)
self.prompt_manager = PromptManager()
async def enrich_single_issue(self, issue: dict) -> dict:
"""
Perform deep AI enrichment on a single issue.
Returns dict matching the frontend AIEnrichmentResult interface:
{
issueNumber, problem, goal, scopeIn, scopeOut,
acceptanceCriteria, technicalContext, risksEdgeCases, confidence
}
"""
from core.client import create_client
issue_number = issue["number"]
self._report_progress(
"analyzing",
20,
f"Analyzing issue #{issue_number}...",
issue_number=issue_number,
)
context = self._build_enrichment_context(issue)
prompt = self._get_enrichment_prompt() + "\n\n---\n\n" + context
model_shorthand = self.config.model or "sonnet"
model = resolve_model_id(model_shorthand)
betas = get_model_betas(model_shorthand)
client = create_client(
project_dir=self.project_dir,
spec_dir=self.github_dir,
model=model,
agent_type="qa_reviewer",
betas=betas,
fast_mode=self.config.fast_mode,
)
try:
async with client:
await client.query(prompt)
response_text = ""
async for msg in client.receive_response():
msg_type = type(msg).__name__
if msg_type == "AssistantMessage" and hasattr(msg, "content"):
for block in msg.content:
block_type = type(block).__name__
if block_type == "TextBlock" and hasattr(block, "text"):
response_text += block.text
self._report_progress(
"generating",
80,
"Parsing enrichment result...",
issue_number=issue_number,
)
return self._parse_enrichment_result(issue_number, response_text)
except Exception as e:
print(f"Enrichment error for #{issue_number}: {e}")
return {
"issueNumber": issue_number,
"problem": "",
"goal": "",
"scopeIn": [],
"scopeOut": [],
"acceptanceCriteria": [],
"technicalContext": "",
"risksEdgeCases": [],
"confidence": 0.0,
}
def _build_enrichment_context(self, issue: dict) -> str:
"""Build context string for enrichment analysis."""
labels = ", ".join(label["name"] for label in issue.get("labels", [])) or "None"
comments_text = ""
comments = issue.get("comments", {})
nodes = comments.get("nodes", []) if isinstance(comments, dict) else []
if nodes:
comment_lines = []
for c in nodes[:10]:
author = c.get("author", {}).get("login", "unknown")
body = c.get("body", "")[:500]
comment_lines.append(f"**{author}:** {body}")
comments_text = "\n".join(comment_lines)
lines = [
f"## Issue #{issue['number']}",
f"**Title:** {issue['title']}",
f"**Author:** {issue.get('author', {}).get('login', 'unknown')}",
f"**State:** {issue.get('state', 'OPEN')}",
f"**Created:** {issue.get('createdAt', 'unknown')}",
f"**Labels:** {labels}",
"",
"### Body",
issue.get("body", "No description provided.") or "No description provided.",
"",
]
if comments_text:
lines.extend(["### Comments", comments_text, ""])
return "\n".join(lines)
def _get_enrichment_prompt(self) -> str:
"""Get the enrichment analysis prompt."""
prompt_file = self.prompt_manager.prompts_dir / "issue_enrichment.md"
if prompt_file.exists():
return prompt_file.read_text(encoding="utf-8")
return self._get_default_enrichment_prompt()
@staticmethod
def _get_default_enrichment_prompt() -> str:
"""Default enrichment prompt."""
return """# Issue Enrichment Agent
You are an issue enrichment assistant. Perform a deep analysis of the GitHub issue
and extract structured information to help developers understand and implement it.
Analyze the issue and produce:
1. **Problem**: A clear, concise statement of the problem or need being described.
2. **Goal**: What the desired outcome is what should be true when the issue is resolved.
3. **Scope In**: A list of things that ARE in scope for this issue.
4. **Scope Out**: A list of things that are explicitly NOT in scope.
5. **Acceptance Criteria**: Specific, testable criteria for considering the issue done.
6. **Technical Context**: Relevant technical details, architecture notes, or constraints.
7. **Risks & Edge Cases**: Potential risks, edge cases, or gotchas to watch out for.
8. **Confidence**: How confident you are in the analysis (0.0 to 1.0). Lower if the issue
is vague, missing details, or contradictory.
Output ONLY a JSON block:
```json
{
"problem": "Clear problem statement",
"goal": "Desired outcome",
"scopeIn": ["Item 1", "Item 2"],
"scopeOut": ["Item 1"],
"acceptanceCriteria": ["Criterion 1", "Criterion 2"],
"technicalContext": "Technical details and constraints",
"risksEdgeCases": ["Risk 1", "Edge case 1"],
"confidence": 0.85
}
```
"""
@staticmethod
def _parse_enrichment_result(issue_number: int, response_text: str) -> dict:
"""Parse enrichment result from AI response."""
default = {
"issueNumber": issue_number,
"problem": "",
"goal": "",
"scopeIn": [],
"scopeOut": [],
"acceptanceCriteria": [],
"technicalContext": "",
"risksEdgeCases": [],
"confidence": 0.0,
}
try:
json_match = re.search(
r"```json\s*(\{.*?\})\s*```", response_text, re.DOTALL
)
if json_match:
data = json.loads(json_match.group(1))
return {
"issueNumber": issue_number,
"problem": data.get("problem", ""),
"goal": data.get("goal", ""),
"scopeIn": data.get("scopeIn", []),
"scopeOut": data.get("scopeOut", []),
"acceptanceCriteria": data.get("acceptanceCriteria", []),
"technicalContext": data.get("technicalContext", ""),
"risksEdgeCases": data.get("risksEdgeCases", []),
"confidence": float(data.get("confidence", 0.5)),
}
except (json.JSONDecodeError, KeyError, ValueError) as e:
print(f"Failed to parse enrichment result: {e}")
return default
@@ -1,207 +0,0 @@
"""
Investigation Safety Hooks
===========================
PreToolUse hooks for investigation specialist agents.
investigation_bash_guard() validates Bash commands against a strict
allowlist of read-only, investigation-safe commands. This lets
specialists run git history commands, test runners, and dependency
queries without risking destructive operations.
Commands are validated by:
1. Rejecting dangerous shell operators (;, |, &, `, $(), ${}, redirects)
2. Checking the base command against INVESTIGATION_BASH_ALLOWLIST
3. Blocking dangerous find flags (-exec, -execdir, -delete, -ok, -okdir)
"""
from __future__ import annotations
import json
import logging
import re
import shlex
from datetime import datetime, timezone
from typing import Any
try:
from .io_utils import safe_print
except (ImportError, ValueError, SystemError):
try:
from services.io_utils import safe_print
except (ImportError, ModuleNotFoundError):
from core.io_utils import safe_print
logger = logging.getLogger(__name__)
# Shell operators and constructs that allow command chaining / injection.
_DANGEROUS_PATTERNS = re.compile(
r"[;|&`]"
r"|\$\("
r"|\$\{"
r"|>\s"
r"|<\s"
r"|>>",
)
# find(1) flags that can execute arbitrary commands or delete files.
_DANGEROUS_FIND_FLAGS = {"-exec", "-execdir", "-delete", "-ok", "-okdir"}
# Commands that investigation agents are allowed to run.
INVESTIGATION_BASH_ALLOWLIST: list[str] = [
# Git history (read-only)
"git log",
"git show",
"git blame",
"git diff",
"git status",
# Test runners
"pytest",
"python -m pytest",
"npm test",
"npm run test",
"npx vitest",
"vitest",
"cargo test",
# Dependency inspection
"pip list",
"pip show",
"npm ls",
"node -v",
"node --version",
"python -V",
"python --version",
"python3 --version",
# Filesystem exploration
"ls",
"find",
"wc",
"cat",
"head",
"tail",
"file",
"grep",
"rg",
]
def _is_command_safe(command: str) -> bool:
"""Check if a command is safe for investigation agents.
Validates that:
1. No dangerous shell operators are present (;, |, &, `, $(), redirects)
2. The base command is in the allowlist
3. ``find`` does not use dangerous flags (-exec, -delete, etc.)
"""
# Reject shell operators that enable command chaining / injection
if _DANGEROUS_PATTERNS.search(command):
return False
# Parse into tokens to extract the base command
try:
tokens = shlex.split(command)
except ValueError:
return False
if not tokens:
return False
base_cmd = tokens[0]
# Check if the base command (or full prefix) is in the allowlist
# Both conditions must be true: base command matches AND command starts with allowed prefix
base_cmd_allowed = any(
base_cmd == allowed or base_cmd == allowed.split()[0]
for allowed in INVESTIGATION_BASH_ALLOWLIST
)
full_prefix_allowed = any(
command.startswith(allowed) for allowed in INVESTIGATION_BASH_ALLOWLIST
)
if not (base_cmd_allowed and full_prefix_allowed):
return False
# Extra guard for find: block flags that execute commands or delete files
if base_cmd == "find":
lower_tokens = {t.lower() for t in tokens}
if lower_tokens & _DANGEROUS_FIND_FLAGS:
return False
return True
async def investigation_bash_guard(
input_data: dict[str, Any],
tool_use_id: str | None = None,
context: Any | None = None,
) -> dict[str, Any]:
"""
PreToolUse hook: validate Bash commands for investigation safety.
Allows only commands that start with an entry in
INVESTIGATION_BASH_ALLOWLIST. All other commands are denied.
Args:
input_data: Dict with tool_name and tool_input from SDK
tool_use_id: Tool use ID (unused)
context: Hook context (unused)
Returns:
Empty dict to allow, or hookSpecificOutput with deny decision
"""
tool_input = input_data.get("tool_input")
if not isinstance(tool_input, dict):
return {
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "deny",
"permissionDecisionReason": "Bash tool_input is missing or malformed",
}
}
command = tool_input.get("command", "").strip()
if not command:
return {
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "deny",
"permissionDecisionReason": "Empty Bash command",
}
}
# Validate command safety (allowlist + shell-operator rejection)
if _is_command_safe(command):
logger.debug(f"[InvestigationHook] Allowed: {command[:80]}")
return {}
# Deny with reason
logger.info(f"[InvestigationHook] Blocked: {command[:100]}")
return {
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "deny",
"permissionDecisionReason": (
f"Command not allowed during investigation: {command[:100]}"
),
}
}
def emit_json_event(event: str, agent: str, **kwargs: Any) -> None:
"""Emit a structured JSON event to stdout for the frontend to parse.
Args:
event: Event type (tool_start, tool_end, thinking)
agent: Specialist agent name (root_cause, impact, etc.)
**kwargs: Additional event data
"""
try:
payload = {
"event": event,
"agent": agent,
"ts": datetime.now(timezone.utc).isoformat(),
**kwargs,
}
safe_print(json.dumps(payload, default=str))
except Exception:
pass # Never crash a specialist due to event emission failure
@@ -1,245 +0,0 @@
"""
Investigation Label Manager
============================
Manages GitHub lifecycle labels for issue investigations.
Labels are synced one-way (app -> GitHub) with graceful error handling
so label failures never crash the investigation pipeline.
Includes debounce logic (5s) on set_investigation_label() to avoid
rapid-fire GitHub API calls during fast state transitions.
Debounce implementation:
- Non-terminal states are debounced within a 5-second window
- Terminal states (findings_ready, task_created, done) bypass debounce
- Pending state is tracked and applied on the next non-debounced call
"""
from __future__ import annotations
import logging
import time
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from ..gh_client import GHClient
logger = logging.getLogger(__name__)
# Debounce window in seconds for label changes per issue
_LABEL_DEBOUNCE_SECONDS = 5.0
# Default label configuration — can be overridden per-project via config
DEFAULT_LABEL_CUSTOMIZATION = {
"prefix": "auto-claude:",
"labels": {
"investigating": {
"suffix": "investigating",
"color": "1d76db",
"description": "Auto-Claude is investigating this issue",
},
"findings_ready": {
"suffix": "findings-ready",
"color": "0e8a16",
"description": "Investigation complete, findings available",
},
"task_created": {
"suffix": "task-created",
"color": "5319e7",
"description": "Kanban task created from investigation",
},
"building": {
"suffix": "building",
"color": "d93f0b",
"description": "Task is being built by the pipeline",
},
"done": {
"suffix": "done",
"color": "0e8a16",
"description": "Investigation complete, issue resolved",
},
},
}
class InvestigationLabelManager:
"""Manages GitHub lifecycle labels for issue investigations.
Labels are synced one-way (app -> GitHub). Label API failures
are logged but never propagated to callers.
"""
# Terminal states that should never be debounced — these represent
# important outcomes that must always be reflected on GitHub.
_TERMINAL_STATES: set[str] = {"findings_ready", "task_created", "done", "completed"}
def __init__(self, customization: dict | None = None) -> None:
# Resolve customization from config or defaults
custom = customization or {}
prefix = custom.get("prefix", DEFAULT_LABEL_CUSTOMIZATION["prefix"])
label_overrides = custom.get("labels", {})
self.labels: dict[str, dict[str, str]] = {}
for key, defaults in DEFAULT_LABEL_CUSTOMIZATION["labels"].items():
overrides = label_overrides.get(key, {})
suffix = overrides.get("suffix", defaults["suffix"])
color = overrides.get("color", defaults["color"])
description = overrides.get("description", defaults["description"])
self.labels[key] = {
"name": f"{prefix}{suffix}",
"color": color,
"description": description,
}
self.all_label_names = [label["name"] for label in self.labels.values()]
# Track last label-change timestamp per issue for debounce
self._last_label_time: dict[int, float] = {}
# Track pending (debounced) label state per issue for trailing-edge apply
self._pending_state: dict[int, str] = {}
# Map investigation states to label keys
_STATE_MAP: dict[str, str] = {
"investigating": "investigating",
"findings_ready": "findings_ready",
"task_created": "task_created",
"building": "building",
"done": "done",
"completed": "done",
}
async def ensure_labels_exist(self, gh_client: GHClient) -> None:
"""Create labels in the repo if they don't already exist (idempotent).
Called once when an investigation starts. Fetches existing labels
first to avoid 422 errors from attempting to create duplicates.
"""
# Fetch existing labels to avoid noisy 422 errors
existing_names: set[str] = set()
try:
import json
result = await gh_client.run(
["api", "--method", "GET", "repos/{owner}/{repo}/labels", "--paginate"],
raise_on_error=False,
)
if result.returncode == 0:
for label in json.loads(result.stdout):
existing_names.add(label.get("name", ""))
except Exception:
pass # If fetch fails, try creating all labels anyway
for key, label_def in self.labels.items():
if label_def["name"] in existing_names:
continue
try:
await gh_client.run(
[
"api",
"--method",
"POST",
"repos/{owner}/{repo}/labels",
"-f",
f"name={label_def['name']}",
"-f",
f"color={label_def['color']}",
"-f",
f"description={label_def['description']}",
],
raise_on_error=False,
)
except Exception as e:
logger.debug("Label ensure for %s: %s (may already exist)", key, e)
async def set_investigation_label(
self,
gh_client: GHClient,
issue_number: int,
state: str,
) -> None:
"""Set the lifecycle label for an issue, removing old ones first.
Includes a debounce window to avoid rapid-fire GitHub API calls
when state transitions happen in quick succession.
Args:
gh_client: GitHub CLI client
issue_number: The issue number
state: Investigation state (e.g. "investigating", "findings_ready")
"""
label_name = self._state_to_label(state)
if label_name is None:
logger.warning("Unknown investigation state %r, skipping label sync", state)
return
# Resolve which state to apply: if there was a pending (debounced) state
# queued from a previous call, the current call supersedes it.
pending = self._pending_state.pop(issue_number, None)
# Debounce: skip non-terminal states if we changed labels too recently.
# Terminal states (findings_ready, task_created, done) always go through
# because they represent important outcomes that must be visible on GitHub.
now = time.monotonic()
last_time = self._last_label_time.get(issue_number, 0.0)
is_terminal = state in self._TERMINAL_STATES
if not is_terminal and now - last_time < _LABEL_DEBOUNCE_SECONDS:
logger.debug(
"Debounced label change for issue #%d (%.1fs since last change), "
"storing %r as pending",
issue_number,
now - last_time,
state,
)
# Store the desired state so the next non-debounced call applies it
self._pending_state[issue_number] = state
return
# If there was a pending state and the current call supersedes it, log it
if pending and pending != state:
logger.debug(
"Superseding pending label state %r with %r for issue #%d",
pending,
state,
issue_number,
)
try:
# Add the new label first (atomic with existing labels via GitHub's API)
await gh_client.issue_add_labels(issue_number, [label_name])
# Then remove all other auto-claude: labels (excluding the one we just added)
other_labels = [name for name in self.all_label_names if name != label_name]
if other_labels:
await gh_client.issue_remove_labels(issue_number, other_labels)
self._last_label_time[issue_number] = now
logger.info("Set label %s on issue #%d", label_name, issue_number)
except Exception as e:
logger.warning(
"Failed to set label %s on issue #%d: %s",
label_name,
issue_number,
e,
)
async def remove_all_investigation_labels(
self,
gh_client: GHClient,
issue_number: int,
) -> None:
"""Remove all auto-claude: lifecycle labels from an issue."""
try:
await gh_client.issue_remove_labels(issue_number, self.all_label_names)
except Exception as e:
logger.debug(
"Failed to remove investigation labels from #%d: %s",
issue_number,
e,
)
def _state_to_label(self, state: str) -> str | None:
"""Map an investigation state string to a GitHub label name."""
key = self._STATE_MAP.get(state)
if key is None:
return None
return self.labels[key]["name"]
@@ -1,319 +0,0 @@
"""
Investigation Pydantic Models
==============================
Structured output models for the AI issue investigation system.
Each specialist agent (root cause, impact, fix advisor, reproducer) returns
a structured response validated against these schemas. The combined results
form an InvestigationReport.
Usage with Claude Agent SDK structured output:
from .investigation_models import RootCauseAnalysis
client = create_client(
...,
output_format={
"type": "json_schema",
"schema": RootCauseAnalysis.model_json_schema(),
},
)
"""
from __future__ import annotations
from typing import Literal
from pydantic import BaseModel, Field
# =============================================================================
# Shared Sub-Models
# =============================================================================
class CodePath(BaseModel):
"""A reference to a specific code location involved in the issue."""
file: str = Field(description="File path relative to project root")
start_line: int = Field(description="Start line number")
end_line: int | None = Field(
None, description="End line number (None if single line)"
)
description: str = Field(
description="What this code location does / why it matters"
)
class SuggestedLabel(BaseModel):
"""An AI-suggested label for the GitHub issue."""
name: str = Field(description="Label name (e.g., 'bug', 'security', 'performance')")
reason: str = Field(description="Why this label is appropriate for the issue")
accepted: bool | None = Field(
None, description="Whether the user accepted this suggestion (None = pending)"
)
class LinkedPR(BaseModel):
"""A pull request linked to or referenced by the issue."""
number: int = Field(description="PR number")
title: str = Field(description="PR title")
status: Literal["open", "merged", "closed"] = Field(description="PR status")
# =============================================================================
# Root Cause Analyzer
# =============================================================================
class RootCauseAnalysis(BaseModel):
"""Structured output from the Root Cause Analyzer agent."""
identified_root_cause: str = Field(
description="Clear description of the identified root cause"
)
code_paths: list[CodePath] = Field(
default_factory=list,
description="Code paths involved in the issue, ordered from entry point to root cause",
)
confidence: Literal["high", "medium", "low"] = Field(
description="Confidence in the root cause identification"
)
evidence: str = Field(
description="Evidence supporting the root cause identification (code snippets, traces)"
)
related_issues: list[str] = Field(
default_factory=list,
description="Patterns or known issue categories this matches (e.g., 'race condition', 'null reference')",
)
likely_already_fixed: bool = Field(
False,
description="True if evidence suggests this issue has already been resolved",
)
# =============================================================================
# Impact Assessor
# =============================================================================
class AffectedComponent(BaseModel):
"""A component or module affected by the issue."""
file: str = Field(description="File path of the affected component")
component: str = Field(description="Component or module name")
impact_type: str = Field(
description="How this component is affected (e.g. direct, indirect, dependency)"
)
description: str = Field(description="Description of the impact on this component")
class ImpactAssessment(BaseModel):
"""Structured output from the Impact Assessor agent."""
severity: Literal["critical", "high", "medium", "low"] = Field(
description="Overall severity of the issue based on impact"
)
affected_components: list[AffectedComponent] = Field(
default_factory=list,
description="Components/modules affected by this issue",
)
blast_radius: str = Field(
description="Description of how far-reaching the impact is"
)
user_impact: str = Field(description="How end users are affected by this issue")
regression_risk: str = Field(description="Risk of regression if fixing this issue")
# =============================================================================
# Fix Advisor
# =============================================================================
class FixApproach(BaseModel):
"""A concrete approach to fixing the issue."""
description: str = Field(description="Description of the fix approach")
complexity: Literal["simple", "moderate", "complex"] = Field(
description="Estimated complexity of implementing this fix"
)
files_affected: list[str] = Field(
default_factory=list,
description="Files that would need to be modified",
)
pros: list[str] = Field(
default_factory=list,
description="Advantages of this approach",
)
cons: list[str] = Field(
default_factory=list,
description="Disadvantages or risks of this approach",
)
class PatternReference(BaseModel):
"""A reference to an existing codebase pattern to follow."""
file: str = Field(description="File containing the pattern")
description: str = Field(description="What pattern to follow and why")
class FixAdvice(BaseModel):
"""Structured output from the Fix Advisor agent."""
approaches: list[FixApproach] = Field(
default_factory=list,
description="Possible fix approaches, ordered by recommendation",
)
recommended_approach: int = Field(
0,
description="Index into approaches list for the recommended approach",
)
files_to_modify: list[str] = Field(
default_factory=list,
description="All files that need modification across all approaches",
)
patterns_to_follow: list[PatternReference] = Field(
default_factory=list,
description="Existing codebase patterns the fix should follow for consistency",
)
gotchas: list[str] = Field(
default_factory=list,
description="Potential pitfalls and things to watch out for when implementing the fix",
)
# =============================================================================
# Reproducer
# =============================================================================
class TestCoverage(BaseModel):
"""Assessment of existing test coverage for the affected code."""
has_existing_tests: bool = Field(
description="Whether there are existing tests for the affected code"
)
test_files: list[str] = Field(
default_factory=list,
description="Existing test files that cover the affected code paths",
)
coverage_assessment: str = Field(
description="Assessment of how well the affected code is tested"
)
class ReproductionAnalysis(BaseModel):
"""Structured output from the Reproducer agent."""
reproducible: str = Field(
description="Whether the issue can be reproduced (e.g. yes, likely, unlikely, no)"
)
reproduction_steps: list[str] = Field(
default_factory=list,
description="Steps to reproduce the issue",
)
test_coverage: TestCoverage = Field(
description="Assessment of existing test coverage"
)
related_test_files: list[str] = Field(
default_factory=list,
description="Test files related to the affected code",
)
suggested_test_approach: str = Field(
description="How to write a test that verifies the fix"
)
# =============================================================================
# Combined Investigation Report
# =============================================================================
class InvestigationReport(BaseModel):
"""Combined report from all 4 specialist agents.
This is the authoritative investigation result saved to disk and
displayed in the UI. It aggregates all agent outputs plus metadata.
"""
issue_number: int = Field(description="GitHub issue number")
issue_title: str = Field(description="GitHub issue title")
investigation_id: str = Field(description="Unique investigation ID")
timestamp: str = Field(description="ISO 8601 timestamp of investigation completion")
# Agent results
root_cause: RootCauseAnalysis = Field(description="Root cause analysis results")
impact: ImpactAssessment = Field(description="Impact assessment results")
fix_advice: FixAdvice = Field(description="Fix advice results")
reproduction: ReproductionAnalysis = Field(
description="Reproduction analysis results"
)
# Overall assessment
ai_summary: str = Field(
description="AI-generated summary combining all agent findings"
)
severity: Literal["critical", "high", "medium", "low"] = Field(
description="Overall severity computed from agent assessments"
)
likely_resolved: bool = Field(
False,
description="True if evidence suggests the issue has already been resolved",
)
# Metadata
suggested_labels: list[SuggestedLabel] = Field(
default_factory=list,
description="AI-suggested labels for the issue",
)
linked_prs: list[LinkedPR] = Field(
default_factory=list,
description="Pull requests linked to this issue",
)
# =============================================================================
# Investigation State
# =============================================================================
class InvestigationState(BaseModel):
"""Persistent state for an issue investigation.
Saved to .auto-claude/issues/{issueNumber}/investigation_state.json.
State is primarily derived from investigation data + linked task status,
but we persist key fields for fast lookup without scanning all files.
"""
issue_number: int = Field(description="GitHub issue number")
spec_id: str | None = Field(
None, description="Pre-allocated spec ID (e.g., '042-fix-login-bug')"
)
status: Literal[
"investigating",
"findings_ready",
"resolved",
"failed",
"cancelled",
"task_created",
] = Field(description="Current investigation status")
started_at: str = Field(description="ISO 8601 timestamp when investigation started")
completed_at: str | None = Field(
None, description="ISO 8601 timestamp when investigation completed"
)
error: str | None = Field(None, description="Error message if investigation failed")
linked_spec_id: str | None = Field(
None, description="Spec ID of the kanban task created from this investigation"
)
github_comment_id: int | None = Field(
None, description="ID of the GitHub comment posted with results"
)
model_used: str | None = Field(
None, description="Model used for investigation (e.g., 'sonnet')"
)
sessions: dict[str, str | None] = Field(
default_factory=dict,
description="SDK session IDs per specialist for resume support. Keys are specialist names, values are session IDs or None.",
)
@@ -1,425 +0,0 @@
"""
Investigation Persistence Layer
================================
Read/write operations for .auto-claude/issues/{issueNumber}/ directory.
All writes use write_json_atomic() to prevent corruption from concurrent
access or crashes. Directory structure:
.auto-claude/issues/
{issueNumber}/
investigation_report.json # Full findings from all 4 agents
investigation_state.json # Status, timestamps, linked spec ID
agent_logs/ # Per-agent log files
root_cause.log
impact.log
fix_advisor.log
reproducer.log
suggested_labels.json # AI-suggested labels with accept/reject
"""
from __future__ import annotations
import json
import logging
from pathlib import Path
from typing import Any
try:
from ...core.file_utils import atomic_write, write_json_atomic
from .investigation_models import InvestigationReport, InvestigationState
except (ImportError, ValueError, SystemError):
from core.file_utils import atomic_write, write_json_atomic
try:
from services.investigation_models import (
InvestigationReport,
InvestigationState,
)
except (ImportError, ModuleNotFoundError):
from investigation_models import InvestigationReport, InvestigationState
logger = logging.getLogger(__name__)
def get_issues_dir(project_dir: Path) -> Path:
"""Get the base issues directory, creating it if needed."""
d = project_dir / ".auto-claude" / "issues"
d.mkdir(parents=True, exist_ok=True)
return d
def get_issue_dir(project_dir: Path, issue_number: int) -> Path:
"""Get the directory for a specific issue, creating it if needed."""
d = get_issues_dir(project_dir) / str(issue_number)
d.mkdir(parents=True, exist_ok=True)
return d
# =============================================================================
# Investigation State
# =============================================================================
def save_investigation_state(
project_dir: Path,
issue_number: int,
state: InvestigationState | dict[str, Any],
) -> Path:
"""Save investigation state to disk.
Args:
project_dir: Project root directory
issue_number: GitHub issue number
state: Investigation state (Pydantic model or raw dict)
Returns:
Path to the saved state file
"""
issue_path = get_issue_dir(project_dir, issue_number)
state_file = issue_path / "investigation_state.json"
data = (
state.model_dump(mode="json")
if isinstance(state, InvestigationState)
else state
)
write_json_atomic(state_file, data)
status = (
state.status
if isinstance(state, InvestigationState)
else state.get("status", "?")
)
logger.debug(f"Saved investigation state for issue #{issue_number}: {status}")
return state_file
def load_investigation_state(
project_dir: Path,
issue_number: int,
) -> InvestigationState | None:
"""Load investigation state from disk.
Args:
project_dir: Project root directory
issue_number: GitHub issue number
Returns:
InvestigationState if found, None otherwise
"""
state_file = get_issue_dir(project_dir, issue_number) / "investigation_state.json"
if not state_file.exists():
return None
try:
data = json.loads(state_file.read_text(encoding="utf-8"))
return InvestigationState.model_validate(data)
except Exception as e:
logger.error(
f"Failed to load investigation state for issue #{issue_number}: {e}"
)
return None
# =============================================================================
# Investigation Report
# =============================================================================
def save_investigation_report(
project_dir: Path,
issue_number: int,
report: InvestigationReport,
) -> Path:
"""Save investigation report to disk.
Args:
project_dir: Project root directory
issue_number: GitHub issue number
report: Investigation report to save
Returns:
Path to the saved report file
"""
issue_path = get_issue_dir(project_dir, issue_number)
report_file = issue_path / "investigation_report.json"
write_json_atomic(report_file, report.model_dump(mode="json"))
logger.debug(f"Saved investigation report for issue #{issue_number}")
return report_file
def load_investigation_report(
project_dir: Path,
issue_number: int,
) -> InvestigationReport | None:
"""Load investigation report from disk.
Args:
project_dir: Project root directory
issue_number: GitHub issue number
Returns:
InvestigationReport if found, None otherwise
"""
report_file = get_issue_dir(project_dir, issue_number) / "investigation_report.json"
if not report_file.exists():
return None
try:
data = json.loads(report_file.read_text(encoding="utf-8"))
return InvestigationReport.model_validate(data)
except Exception as e:
logger.error(
f"Failed to load investigation report for issue #{issue_number}: {e}"
)
return None
# =============================================================================
# Agent Logs
# =============================================================================
def save_agent_log(
project_dir: Path,
issue_number: int,
agent_name: str,
log_content: str,
) -> Path:
"""Save an agent's log output to disk (atomic write).
Args:
project_dir: Project root directory
issue_number: GitHub issue number
agent_name: Name of the agent (e.g., 'root_cause', 'impact')
log_content: Log text to save
Returns:
Path to the saved log file
"""
logs_dir = get_issue_dir(project_dir, issue_number) / "agent_logs"
logs_dir.mkdir(parents=True, exist_ok=True)
log_file = logs_dir / f"{agent_name}.log"
# Use atomic write to prevent corruption from concurrent access
with atomic_write(log_file, "w", encoding="utf-8") as f:
f.write(log_content)
logger.debug(f"Saved agent log for issue #{issue_number}/{agent_name}")
return log_file
# =============================================================================
# GitHub Comment Tracking
# =============================================================================
def save_github_comment_id(
project_dir: Path,
issue_number: int,
comment_id: int,
) -> None:
"""Save the GitHub comment ID for the posted investigation results (atomic write).
Also updates the investigation state with the comment ID.
Args:
project_dir: Project root directory
issue_number: GitHub issue number
comment_id: GitHub comment ID
"""
# Save to dedicated file for quick lookup (atomic write)
issue_path = get_issue_dir(project_dir, issue_number)
comment_file = issue_path / "github_comment_id"
# Use atomic write to prevent corruption from concurrent access
with atomic_write(comment_file, "w", encoding="utf-8") as f:
f.write(str(comment_id))
# Also update state if it exists
state = load_investigation_state(project_dir, issue_number)
if state:
state.github_comment_id = comment_id
save_investigation_state(project_dir, issue_number, state)
logger.debug(f"Saved GitHub comment ID {comment_id} for issue #{issue_number}")
def load_github_comment_id(
project_dir: Path,
issue_number: int,
) -> int | None:
"""Load the GitHub comment ID for posted investigation results.
Args:
project_dir: Project root directory
issue_number: GitHub issue number
Returns:
Comment ID if found, None otherwise
"""
comment_file = get_issue_dir(project_dir, issue_number) / "github_comment_id"
if not comment_file.exists():
return None
try:
return int(comment_file.read_text(encoding="utf-8").strip())
except (ValueError, OSError) as e:
logger.warning(
f"Failed to load GitHub comment ID for issue #{issue_number}: {e}"
)
return None
# =============================================================================
# Suggested Labels
# =============================================================================
def save_suggested_labels(
project_dir: Path,
issue_number: int,
labels: list[dict[str, Any]],
) -> None:
"""Save AI-suggested labels for the issue.
Args:
project_dir: Project root directory
issue_number: GitHub issue number
labels: List of label dicts with name, reason, confidence, accepted status
"""
labels_file = get_issue_dir(project_dir, issue_number) / "suggested_labels.json"
write_json_atomic(labels_file, labels)
logger.debug(f"Saved {len(labels)} suggested labels for issue #{issue_number}")
def load_suggested_labels(
project_dir: Path,
issue_number: int,
) -> list[dict[str, Any]]:
"""Load AI-suggested labels for the issue.
Args:
project_dir: Project root directory
issue_number: GitHub issue number
Returns:
List of label dicts, empty list if not found
"""
labels_file = get_issue_dir(project_dir, issue_number) / "suggested_labels.json"
if not labels_file.exists():
return []
try:
data = json.loads(labels_file.read_text(encoding="utf-8"))
return data if isinstance(data, list) else []
except Exception as e:
logger.warning(
f"Failed to load suggested labels for issue #{issue_number}: {e}"
)
return []
# =============================================================================
# Session Persistence (Resume Support)
# =============================================================================
def save_specialist_session(
project_dir: Path,
issue_number: int,
specialist_name: str,
session_id: str,
) -> None:
"""Save a specialist's SDK session ID for resume support.
Updates the sessions dict in investigation_state.json using atomic
write to prevent file corruption.
Note: While the write itself is atomic, there remains a theoretical
TOCTOU (time-of-check-time-of-use) race between read and write if
multiple processes update the same issue state simultaneously. In
practice, investigations are single-process per issue, so this is
acceptable for the low-severity nature of session tracking.
Args:
project_dir: Project root directory
issue_number: GitHub issue number
specialist_name: Specialist name (root_cause, impact, etc.)
session_id: SDK session ID
"""
state = load_investigation_state(project_dir, issue_number)
if state is None:
logger.warning(
f"Cannot save session for issue #{issue_number}: no investigation state"
)
return
state.sessions[specialist_name] = session_id
save_investigation_state(project_dir, issue_number, state)
logger.debug(
f"Saved session ID for issue #{issue_number}/{specialist_name}: {session_id[:20]}..."
)
def load_specialist_sessions(
project_dir: Path,
issue_number: int,
) -> dict[str, str | None]:
"""Load all specialist session IDs for an investigation.
Args:
project_dir: Project root directory
issue_number: GitHub issue number
Returns:
Dict mapping specialist name to session ID (or None)
"""
state = load_investigation_state(project_dir, issue_number)
if state is None:
return {}
return state.sessions
# =============================================================================
# Listing & Querying
# =============================================================================
def list_investigated_issues(
project_dir: Path,
) -> list[int]:
"""List all issue numbers that have investigation data.
Args:
project_dir: Project root directory
Returns:
Sorted list of issue numbers
"""
issues_dir = project_dir / ".auto-claude" / "issues"
if not issues_dir.exists():
return []
issue_numbers = []
for entry in issues_dir.iterdir():
if entry.is_dir():
try:
issue_numbers.append(int(entry.name))
except ValueError:
continue
return sorted(issue_numbers)
def has_investigation(
project_dir: Path,
issue_number: int,
) -> bool:
"""Check if an issue has any investigation data.
Args:
project_dir: Project root directory
issue_number: GitHub issue number
Returns:
True if investigation data exists
"""
return (project_dir / ".auto-claude" / "issues" / str(issue_number)).exists()
@@ -1,199 +0,0 @@
"""
Investigation Report Builder
==============================
Transforms an InvestigationReport into formatted output:
- build_github_comment(): Branded markdown for posting to GitHub issues
- build_summary(): One-paragraph summary for list display
"""
from __future__ import annotations
from datetime import datetime, timezone
try:
from .investigation_models import InvestigationReport
except (ImportError, ValueError, SystemError):
try:
from services.investigation_models import InvestigationReport
except (ImportError, ModuleNotFoundError):
from investigation_models import InvestigationReport
def build_github_comment(report: InvestigationReport) -> str:
"""Produce branded markdown for a GitHub issue comment.
Args:
report: The investigation report to format
Returns:
Markdown string suitable for posting as a GitHub comment
"""
lines: list[str] = []
# Header
lines.append("## Auto-Claude Investigation")
lines.append("")
confidence = report.root_cause.confidence
lines.append(f"**Severity:** {report.severity} | **Confidence:** {confidence}")
lines.append("")
# Summary
lines.append("### Summary")
lines.append(report.ai_summary)
lines.append("")
# Already-resolved warning
if report.likely_resolved:
lines.append(
"> **Note:** Evidence suggests this issue may have already been resolved."
)
lines.append("")
# Root Cause Analysis (collapsible)
lines.append("<details>")
lines.append("<summary>Root Cause Analysis</summary>")
lines.append("")
lines.append(f"**Root Cause:** {report.root_cause.identified_root_cause}")
lines.append("")
if report.root_cause.code_paths:
lines.append("**Code Paths:**")
lines.append("")
lines.append("| File | Lines | Description |")
lines.append("|------|-------|-------------|")
for cp in report.root_cause.code_paths:
end = cp.end_line if cp.end_line else cp.start_line
lines.append(f"| `{cp.file}` | {cp.start_line}-{end} | {cp.description} |")
lines.append("")
lines.append(f"**Evidence:** {report.root_cause.evidence}")
lines.append("")
lines.append("</details>")
lines.append("")
# Impact Assessment (collapsible)
lines.append("<details>")
lines.append("<summary>Impact Assessment</summary>")
lines.append("")
lines.append(f"**Severity:** {report.impact.severity}")
lines.append(f"**Blast Radius:** {report.impact.blast_radius}")
lines.append(f"**User Impact:** {report.impact.user_impact}")
lines.append(f"**Regression Risk:** {report.impact.regression_risk}")
lines.append("")
if report.impact.affected_components:
lines.append("**Affected Components:**")
lines.append("")
lines.append("| Component | File | Type | Description |")
lines.append("|-----------|------|------|-------------|")
for ac in report.impact.affected_components:
lines.append(
f"| {ac.component} | `{ac.file}` | {ac.impact_type} | {ac.description} |"
)
lines.append("")
lines.append("</details>")
lines.append("")
# Fix Recommendations (collapsible)
lines.append("<details>")
lines.append("<summary>Fix Recommendations</summary>")
lines.append("")
for i, approach in enumerate(report.fix_advice.approaches):
recommended = (
" **(recommended)**" if i == report.fix_advice.recommended_approach else ""
)
lines.append(f"**Approach {i + 1}:** {approach.description}{recommended}")
lines.append(f"- Complexity: {approach.complexity}")
if approach.pros:
lines.append(f"- Pros: {', '.join(approach.pros)}")
if approach.cons:
lines.append(f"- Cons: {', '.join(approach.cons)}")
lines.append("")
if report.fix_advice.files_to_modify:
lines.append(
"**Files to Modify:** "
+ ", ".join(f"`{f}`" for f in report.fix_advice.files_to_modify)
)
lines.append("")
if report.fix_advice.gotchas:
lines.append("**Gotchas:**")
for gotcha in report.fix_advice.gotchas:
lines.append(f"- {gotcha}")
lines.append("")
lines.append("</details>")
lines.append("")
# Reproduction & Testing (collapsible)
lines.append("<details>")
lines.append("<summary>Reproduction & Testing</summary>")
lines.append("")
lines.append(f"**Reproducible:** {report.reproduction.reproducible}")
lines.append("")
if report.reproduction.reproduction_steps:
lines.append("**Steps:**")
for j, step in enumerate(report.reproduction.reproduction_steps, 1):
lines.append(f"{j}. {step}")
lines.append("")
lines.append(
f"**Test Coverage:** {report.reproduction.test_coverage.coverage_assessment}"
)
lines.append(
f"**Suggested Test Approach:** {report.reproduction.suggested_test_approach}"
)
lines.append("")
lines.append("</details>")
lines.append("")
# Suggested Labels
if report.suggested_labels:
lines.append("### Suggested Labels")
for label in report.suggested_labels:
lines.append(f"- `{label.name}` - {label.reason}")
lines.append("")
# Footer
timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")
lines.append("---")
lines.append(
f"*Generated by [Auto-Claude](https://github.com/AndyMik90/Auto-Claude) "
f"* {timestamp}*"
)
return "\n".join(lines)
def build_summary(report: InvestigationReport) -> str:
"""Build a one-paragraph summary for list display (max ~200 chars).
Args:
report: The investigation report to summarize
Returns:
A short summary string
"""
severity = report.severity.upper()
confidence = report.root_cause.confidence
cause = report.root_cause.identified_root_cause
summary = f"[{severity}] {cause}"
# Add resolution note if relevant
if report.likely_resolved:
summary += " (likely resolved)"
# Add confidence
summary += f" [{confidence} confidence]"
# Truncate to ~200 chars
if len(summary) > 200:
summary = summary[:197] + "..."
return summary
@@ -1,225 +0,0 @@
"""
Investigation Spec Generator
==============================
Template-based spec generation from investigation reports.
NO AI cost - uses string templates to transform investigation data
into spec.md and requirements.json for the build pipeline.
Usage:
spec_path = generate_spec_from_investigation(
project_dir=Path("/project"),
issue_number=42,
spec_id="042-fix-login-bug",
)
"""
from __future__ import annotations
import logging
from pathlib import Path
try:
from ...core.file_utils import write_json_atomic
except (ImportError, ValueError, SystemError):
from core.file_utils import write_json_atomic
from .investigation_models import InvestigationReport
from .investigation_persistence import load_investigation_report
logger = logging.getLogger(__name__)
def generate_spec_from_investigation(
project_dir: Path,
issue_number: int,
spec_id: str,
) -> Path:
"""Generate a spec directory from an investigation report.
This is a template-based transformation (no AI cost). It reads
the investigation report and produces:
- spec.md: Markdown spec from the AI summary, root cause, and fix advice
- requirements.json: Requirements derived from fix approaches
- investigation_report.json: Copy of the original report for reference
Args:
project_dir: Project root directory
issue_number: GitHub issue number
spec_id: Spec identifier (e.g., '042-fix-login-bug')
Returns:
Path to the created spec directory
Raises:
FileNotFoundError: If no investigation report exists for the issue
"""
# Load investigation report
report = load_investigation_report(project_dir, issue_number)
if report is None:
raise FileNotFoundError(
f"No investigation report found for issue #{issue_number}. "
"Run investigation first."
)
# Create spec directory
spec_dir = project_dir / ".auto-claude" / "specs" / spec_id
spec_dir.mkdir(parents=True, exist_ok=True)
# Generate spec.md
spec_md = _build_spec_md(report)
(spec_dir / "spec.md").write_text(spec_md, encoding="utf-8")
# Generate requirements.json
requirements = _build_requirements(report)
write_json_atomic(spec_dir / "requirements.json", requirements)
# Copy investigation report for reference
report_data = report.model_dump(mode="json")
write_json_atomic(spec_dir / "investigation_report.json", report_data)
logger.info(
f"Generated spec '{spec_id}' from investigation of issue #{issue_number}"
)
return spec_dir
def _build_spec_md(report: InvestigationReport) -> str:
"""Build spec.md content from investigation report.
Args:
report: The investigation report
Returns:
Markdown string for spec.md
"""
lines: list[str] = []
# Title
lines.append(f"# Fix: {report.issue_title}")
lines.append("")
lines.append(
f"> Generated from investigation of GitHub issue #{report.issue_number}"
)
lines.append("")
# Summary
lines.append("## Summary")
lines.append("")
lines.append(report.ai_summary)
lines.append("")
# Root Cause
lines.append("## Root Cause")
lines.append("")
lines.append(report.root_cause.identified_root_cause)
lines.append("")
if report.root_cause.code_paths:
lines.append("### Affected Code Paths")
lines.append("")
for cp in report.root_cause.code_paths:
end = cp.end_line if cp.end_line else cp.start_line
lines.append(f"- `{cp.file}:{cp.start_line}-{end}` - {cp.description}")
lines.append("")
# Fix Approach
lines.append("## Implementation Plan")
lines.append("")
if report.fix_advice.approaches:
rec_idx = report.fix_advice.recommended_approach
if 0 <= rec_idx < len(report.fix_advice.approaches):
approach = report.fix_advice.approaches[rec_idx]
lines.append(f"**Recommended approach:** {approach.description}")
lines.append(f"- Complexity: {approach.complexity}")
lines.append("")
if approach.files_affected:
lines.append("**Files to modify:**")
for f in approach.files_affected:
lines.append(f"- `{f}`")
lines.append("")
# Patterns to follow
if report.fix_advice.patterns_to_follow:
lines.append("### Patterns to Follow")
lines.append("")
for pat in report.fix_advice.patterns_to_follow:
lines.append(f"- `{pat.file}`: {pat.description}")
lines.append("")
# Gotchas
if report.fix_advice.gotchas:
lines.append("### Gotchas")
lines.append("")
for gotcha in report.fix_advice.gotchas:
lines.append(f"- {gotcha}")
lines.append("")
# Testing
lines.append("## Testing")
lines.append("")
lines.append(
f"**Suggested approach:** {report.reproduction.suggested_test_approach}"
)
lines.append("")
if report.reproduction.test_coverage.test_files:
lines.append("**Existing test files:**")
for tf in report.reproduction.test_coverage.test_files:
lines.append(f"- `{tf}`")
lines.append("")
# Impact
lines.append("## Impact")
lines.append("")
lines.append(f"- **Severity:** {report.impact.severity}")
lines.append(f"- **Blast radius:** {report.impact.blast_radius}")
lines.append(f"- **User impact:** {report.impact.user_impact}")
lines.append(f"- **Regression risk:** {report.impact.regression_risk}")
lines.append("")
return "\n".join(lines)
def _build_requirements(report: InvestigationReport) -> dict:
"""Build requirements.json from investigation report.
Args:
report: The investigation report
Returns:
Dict structure for requirements.json
"""
requirements: list[dict] = []
# Generate requirements from fix approaches
for i, approach in enumerate(report.fix_advice.approaches):
is_recommended = i == report.fix_advice.recommended_approach
req = {
"id": f"REQ-{i + 1:03d}",
"description": approach.description,
"priority": "must" if is_recommended else "should",
"complexity": approach.complexity,
"files": approach.files_affected,
}
requirements.append(req)
# Add testing requirement
requirements.append(
{
"id": f"REQ-{len(requirements) + 1:03d}",
"description": f"Add tests: {report.reproduction.suggested_test_approach}",
"priority": "must",
"complexity": "moderate",
"files": report.reproduction.related_test_files,
}
)
return {
"issue_number": report.issue_number,
"issue_title": report.issue_title,
"severity": report.severity,
"requirements": requirements,
}
File diff suppressed because it is too large Load Diff
@@ -1,417 +0,0 @@
"""
Parallel Agent Orchestrator Base
=================================
Abstract base class for parallel specialist agent orchestration.
Extracts shared patterns from the PR review parallel orchestrator so that
both PR review and issue investigation can reuse:
- SpecialistConfig dataclass for agent definition
- Prompt loading from prompts/github/ directory
- SDK session creation and stream processing
- asyncio.gather-based parallel execution
- Progress reporting via callback
Subclasses must implement domain-specific logic (prompt building, result
parsing, verdict generation, etc.).
"""
from __future__ import annotations
import asyncio
import logging
import os
from dataclasses import dataclass
from pathlib import Path
from typing import Any
try:
from ...core.client import create_client
from ...phase_config import (
get_model_betas,
get_thinking_kwargs_for_model,
)
from .io_utils import safe_print
from .sdk_utils import process_sdk_stream
except (ImportError, ValueError, SystemError):
from core.client import create_client
from phase_config import (
get_model_betas,
get_thinking_kwargs_for_model,
)
from services.io_utils import safe_print
from services.sdk_utils import process_sdk_stream
logger = logging.getLogger(__name__)
# Import investigation Bash safety hook (lazy - only used when Bash is in tools)
_investigation_bash_guard = None
def _get_investigation_bash_guard():
"""Lazy-import the investigation Bash guard to avoid circular imports."""
global _investigation_bash_guard
if _investigation_bash_guard is None:
try:
from .investigation_hooks import investigation_bash_guard
_investigation_bash_guard = investigation_bash_guard
except (ImportError, ValueError, SystemError):
try:
from services.investigation_hooks import investigation_bash_guard
_investigation_bash_guard = investigation_bash_guard
except (ImportError, ModuleNotFoundError):
from investigation_hooks import investigation_bash_guard
_investigation_bash_guard = investigation_bash_guard
return _investigation_bash_guard
# Check if debug mode is enabled
DEBUG_MODE = os.environ.get("DEBUG", "").lower() in ("true", "1", "yes")
@dataclass
class SpecialistConfig:
"""Configuration for a specialist agent in parallel SDK sessions."""
name: str
prompt_file: str
tools: list[str]
description: str
max_turns: int = 30
class ParallelAgentOrchestrator:
"""
Base class for parallel specialist agent orchestration.
Provides shared infrastructure for running multiple Claude SDK sessions
in parallel via asyncio.gather(). Subclasses define their own specialist
configurations, prompt building, and result parsing.
Shared capabilities:
- Load prompt files from prompts/github/ directory
- Run individual specialist SDK sessions with structured output
- Run multiple specialists in parallel and collect results
- Report progress via callback
"""
def __init__(
self,
project_dir: Path,
github_dir: Path,
config: Any,
progress_callback: Any = None,
):
self.project_dir = Path(project_dir)
self.github_dir = Path(github_dir)
self.config = config
self.progress_callback = progress_callback
def _report_progress(self, phase: str, progress: int, message: str, **kwargs):
"""Report progress if callback is set."""
if self.progress_callback:
import sys
if "orchestrator" in sys.modules:
ProgressCallback = sys.modules["orchestrator"].ProgressCallback
else:
try:
from ..orchestrator import ProgressCallback
except ImportError:
from orchestrator import ProgressCallback
self.progress_callback(
ProgressCallback(
phase=phase, progress=progress, message=message, **kwargs
)
)
def _load_prompt(self, filename: str) -> str:
"""Load a prompt file from the prompts/github directory."""
prompt_file = (
Path(__file__).parent.parent.parent.parent / "prompts" / "github" / filename
)
if prompt_file.exists():
return prompt_file.read_text(encoding="utf-8")
logger.warning(f"Prompt file not found: {prompt_file}")
return ""
async def _run_specialist_session(
self,
config: SpecialistConfig,
prompt: str,
project_root: Path,
model: str,
thinking_budget: int | None,
output_schema: dict[str, Any] | None = None,
agent_type: str = "pr_reviewer",
context_name: str | None = None,
max_messages: int | None = None,
on_thinking: Any | None = None,
on_tool_use: Any | None = None,
on_tool_result: Any | None = None,
resume_session_id: str | None = None,
thinking_level: str | None = None,
effort_level: str | None = None,
) -> dict[str, Any]:
"""Run a single specialist as its own SDK session.
This is the generic version that accepts a pre-built prompt and
output schema. Subclasses build domain-specific prompts and parse
results from the returned dict.
Args:
config: Specialist configuration
prompt: Full system prompt (already built by subclass)
project_root: Working directory for the agent
model: Model to use
thinking_budget: Max thinking tokens
output_schema: JSON schema dict for structured output (optional)
agent_type: Agent type for create_client (e.g., "pr_reviewer",
"investigation_specialist")
context_name: Name for logging (defaults to "Specialist:{config.name}")
max_messages: Optional max message count for stream processing
Returns:
Dict with keys from process_sdk_stream:
- result_text: Raw text output
- structured_output: Parsed structured output (if schema provided)
- error: Error message (if any)
- msg_count: Total message count
"""
log_name = context_name or f"Specialist:{config.name}"
safe_print(
f"[{log_name}] Starting analysis...",
flush=True,
)
try:
# Create SDK client for this specialist
# Use per-specialist model for betas (not the global config model)
betas = get_model_betas(model or self.config.model or "sonnet")
# Get thinking budget - use explicit budget if provided, otherwise derive from thinking level
if thinking_budget is not None:
thinking_kwargs = {"max_thinking_tokens": thinking_budget}
else:
# Use per-specialist thinking level when provided
effective_thinking = (
thinking_level or self.config.thinking_level or "medium"
)
thinking_kwargs = get_thinking_kwargs_for_model(
model, effective_thinking
)
# Override effort_level if explicitly provided (e.g., investigation
# agents always use "high" effort regardless of thinking level).
# Only applies to adaptive models (Opus 4.6+) where thinking_kwargs
# includes effort_level; non-adaptive models silently skip this.
if effort_level and "effort_level" in thinking_kwargs:
thinking_kwargs["effort_level"] = effort_level
client_kwargs: dict[str, Any] = {
"project_dir": project_root,
"spec_dir": self.github_dir,
"model": model,
"agent_type": agent_type,
"betas": betas,
"fast_mode": self.config.fast_mode,
**thinking_kwargs,
}
if output_schema:
client_kwargs["output_format"] = {
"type": "json_schema",
"schema": output_schema,
}
client = create_client(**client_kwargs)
# Resume previous session if session ID provided
if resume_session_id:
client.options.resume = resume_session_id
safe_print(
f"[{log_name}] Resuming session: {resume_session_id[:20]}..."
)
# Add investigation Bash safety hook if agent has Bash access
if "Bash" in config.tools:
try:
from claude_agent_sdk.types import HookMatcher
bash_guard = _get_investigation_bash_guard()
existing_hooks = client.options.hooks or {}
pre_tool_hooks = existing_hooks.get("PreToolUse", [])
pre_tool_hooks.append(
HookMatcher(matcher="Bash", hooks=[bash_guard])
)
existing_hooks["PreToolUse"] = pre_tool_hooks
client.options.hooks = existing_hooks
except ImportError:
logger.warning(
f"[{log_name}] Could not import HookMatcher — "
"Bash access will be unguarded"
)
async with client:
await client.query(prompt)
# Capture session ID for resume support
session_id = getattr(client, "session_id", None)
# Build stream kwargs
stream_kwargs: dict[str, Any] = {
"client": client,
"context_name": log_name,
"model": model,
"system_prompt": prompt,
"agent_definitions": {},
}
if max_messages is not None:
stream_kwargs["max_messages"] = max_messages
if on_thinking is not None:
stream_kwargs["on_thinking"] = on_thinking
if on_tool_use is not None:
stream_kwargs["on_tool_use"] = on_tool_use
if on_tool_result is not None:
stream_kwargs["on_tool_result"] = on_tool_result
stream_result = await process_sdk_stream(**stream_kwargs)
error = stream_result.get("error")
if error:
logger.error(f"[{log_name}] SDK stream failed: {error}")
safe_print(
f"[{log_name}] Analysis failed: {error}",
flush=True,
)
return {**stream_result, "session_id": session_id}
except Exception as e:
logger.error(
f"[{log_name}] Session failed: {e}",
exc_info=True,
)
safe_print(
f"[{log_name}] Error: {e}",
flush=True,
)
return {
"result_text": "",
"structured_output": None,
"error": str(e),
"msg_count": 0,
}
async def _run_parallel_specialists(
self,
tasks: list[asyncio.Task | Any],
orchestrator_name: str = "ParallelOrchestrator",
retry_tasks: list[Any] | None = None,
retry_configs: list[dict[str, Any]] | None = None,
) -> list[Any]:
"""Run pre-built async tasks in parallel and collect results.
Failed specialists are retried once before being discarded.
If retry_tasks is provided, it should be a list of callables
(0-arg coroutine factories) that can recreate the coroutine
for a retry attempt.
Results preserve positional order: result[i] corresponds to tasks[i].
Failed specialists (after retry) are represented as None in the list.
Args:
tasks: List of coroutines/tasks to run in parallel
orchestrator_name: Name for logging
retry_tasks: Optional list of 0-arg callables that recreate
the coroutine for each task (same order as tasks).
If None, failed tasks are not retried.
retry_configs: Optional list of dicts with retry configuration:
- name: Specialist name for logging
- lifecycle_wrapper: Optional callable that wraps a coroutine
with lifecycle events (agent_started, agent_done)
Returns:
List of results preserving original task order.
Failed tasks are None; successful tasks contain the result dict.
"""
safe_print(
f"[{orchestrator_name}] Launching {len(tasks)} specialists in parallel...",
flush=True,
)
results = await asyncio.gather(*tasks, return_exceptions=True)
# Build position-indexed result map
result_map: dict[int, Any] = {}
failed_indices: list[int] = []
for i, result in enumerate(results):
if isinstance(result, Exception):
logger.error(f"[{orchestrator_name}] Specialist task failed: {result}")
failed_indices.append(i)
else:
result_map[i] = result
# Retry failed specialists once if retry factories are provided
if failed_indices and retry_tasks:
retryable = [
(idx, retry_tasks[idx])
for idx in failed_indices
if idx < len(retry_tasks) and retry_tasks[idx] is not None
]
if retryable:
safe_print(
f"[{orchestrator_name}] Retrying {len(retryable)} failed specialist(s)...",
flush=True,
)
# Apply lifecycle wrapper to retry coroutines if provided
retry_coroutines = []
for idx, factory in retryable:
coro = factory()
# Apply lifecycle wrapper if available for this task
if retry_configs and idx < len(retry_configs):
config = retry_configs[idx]
wrapper = config.get("lifecycle_wrapper")
if wrapper:
spec_name = config.get("name", f"specialist_{idx}")
coro = wrapper(spec_name, coro)
retry_coroutines.append(coro)
retry_results = await asyncio.gather(
*retry_coroutines, return_exceptions=True
)
still_failing = []
for (idx, _), retry_result in zip(retryable, retry_results):
if isinstance(retry_result, Exception):
logger.error(
f"[{orchestrator_name}] Retry also failed for specialist {idx}: {retry_result}"
)
still_failing.append(idx)
else:
safe_print(
f"[{orchestrator_name}] Retry succeeded for specialist {idx}",
flush=True,
)
result_map[idx] = retry_result
# Log final summary of permanently failed specialists
if still_failing:
logger.error(
f"[{orchestrator_name}] Specialists {still_failing} failed permanently after retry"
)
succeeded = len(result_map)
safe_print(
f"[{orchestrator_name}] All specialists complete. "
f"{succeeded}/{len(tasks)} succeeded.",
flush=True,
)
# Return ordered list preserving original positions (None for failures)
return [result_map.get(i) for i in range(len(tasks))]
@@ -17,10 +17,12 @@ Key Design:
from __future__ import annotations
import asyncio
import hashlib
import logging
import os
from collections import defaultdict
from dataclasses import dataclass
from pathlib import Path
from typing import Any
@@ -51,7 +53,6 @@ try:
from .agent_utils import create_working_dir_injector
from .category_utils import map_category
from .io_utils import safe_print
from .parallel_agent_base import ParallelAgentOrchestrator, SpecialistConfig
from .pr_worktree_manager import PRWorktreeManager
from .pydantic_models import (
AgentAgreement,
@@ -82,7 +83,6 @@ except (ImportError, ValueError, SystemError):
from services.agent_utils import create_working_dir_injector
from services.category_utils import map_category
from services.io_utils import safe_print
from services.parallel_agent_base import ParallelAgentOrchestrator, SpecialistConfig
from services.pr_worktree_manager import PRWorktreeManager
from services.pydantic_models import (
AgentAgreement,
@@ -96,7 +96,16 @@ except (ImportError, ValueError, SystemError):
# =============================================================================
# Specialist Configuration for Parallel SDK Sessions
# =============================================================================
# SpecialistConfig is imported from parallel_agent_base.py
@dataclass
class SpecialistConfig:
"""Configuration for a specialist agent in parallel SDK sessions."""
name: str
prompt_file: str
tools: list[str]
description: str
# Define specialist configurations
@@ -173,7 +182,7 @@ def _is_finding_in_scope(
return True, "In scope"
class ParallelOrchestratorReviewer(ParallelAgentOrchestrator):
class ParallelOrchestratorReviewer:
"""
PR reviewer using SDK subagents for parallel specialist analysis.
@@ -185,12 +194,6 @@ class ParallelOrchestratorReviewer(ParallelAgentOrchestrator):
Model Configuration:
- Orchestrator uses user-configured model from frontend settings
- Specialist agents use model="inherit" (same as orchestrator)
Inherits from ParallelAgentOrchestrator:
- _report_progress() progress callback
- _load_prompt() loads from prompts/github/ directory
- _run_specialist_session() generic SDK session runner
- _run_parallel_specialists() asyncio.gather wrapper
"""
def __init__(
@@ -200,9 +203,41 @@ class ParallelOrchestratorReviewer(ParallelAgentOrchestrator):
config: GitHubRunnerConfig,
progress_callback=None,
):
super().__init__(project_dir, github_dir, config, progress_callback)
self.project_dir = Path(project_dir)
self.github_dir = Path(github_dir)
self.config = config
self.progress_callback = progress_callback
self.worktree_manager = PRWorktreeManager(project_dir, PR_WORKTREE_DIR)
def _report_progress(self, phase: str, progress: int, message: str, **kwargs):
"""Report progress if callback is set."""
if self.progress_callback:
import sys
if "orchestrator" in sys.modules:
ProgressCallback = sys.modules["orchestrator"].ProgressCallback
else:
try:
from ..orchestrator import ProgressCallback
except ImportError:
from orchestrator import ProgressCallback
self.progress_callback(
ProgressCallback(
phase=phase, progress=progress, message=message, **kwargs
)
)
def _load_prompt(self, filename: str) -> str:
"""Load a prompt file from the prompts/github directory."""
prompt_file = (
Path(__file__).parent.parent.parent.parent / "prompts" / "github" / filename
)
if prompt_file.exists():
return prompt_file.read_text(encoding="utf-8")
logger.warning(f"Prompt file not found: {prompt_file}")
return ""
def _create_pr_worktree(self, head_sha: str, pr_number: int) -> Path:
"""Create a temporary worktree at the PR head commit.
@@ -440,7 +475,7 @@ Report findings with specific file paths, line numbers, and code evidence.
return prompt_with_cwd + pr_context
async def _run_pr_specialist_session(
async def _run_specialist_session(
self,
config: SpecialistConfig,
context: PRContext,
@@ -448,10 +483,7 @@ Report findings with specific file paths, line numbers, and code evidence.
model: str,
thinking_budget: int | None,
) -> tuple[str, list[PRReviewFinding]]:
"""Run a single PR review specialist as its own SDK session.
Builds the PR-specific prompt, delegates to the base class's generic
_run_specialist_session(), then parses findings from the result.
"""Run a single specialist as its own SDK session.
Args:
config: Specialist configuration
@@ -463,36 +495,84 @@ Report findings with specific file paths, line numbers, and code evidence.
Returns:
Tuple of (specialist_name, findings)
"""
# Build the specialist prompt with PR context
prompt = self._build_specialist_prompt(config, context, project_root)
# Delegate to base class generic session runner
stream_result = await super()._run_specialist_session(
config=config,
prompt=prompt,
project_root=project_root,
model=model,
thinking_budget=thinking_budget,
output_schema=SpecialistResponse.model_json_schema(),
agent_type="pr_reviewer",
)
error = stream_result.get("error")
if error:
return (config.name, [])
# Parse structured output into PRReviewFindings
structured_output = stream_result.get("structured_output")
findings = self._parse_specialist_output(
config.name, structured_output, stream_result.get("result_text", "")
)
safe_print(
f"[Specialist:{config.name}] Complete: {len(findings)} findings",
f"[Specialist:{config.name}] Starting analysis...",
flush=True,
)
return (config.name, findings)
# Build the specialist prompt with PR context
prompt = self._build_specialist_prompt(config, context, project_root)
try:
# Create SDK client for this specialist
# Note: Agent type uses the generic "pr_reviewer" since individual
# specialist types aren't registered in AGENT_CONFIGS. The specialist-specific
# system prompt handles differentiation.
# Get betas from model shorthand (before resolution to full ID)
betas = get_model_betas(self.config.model or "sonnet")
thinking_kwargs = get_thinking_kwargs_for_model(
model, self.config.thinking_level or "medium"
)
client = create_client(
project_dir=project_root,
spec_dir=self.github_dir,
model=model,
agent_type="pr_reviewer",
betas=betas,
fast_mode=self.config.fast_mode,
output_format={
"type": "json_schema",
"schema": SpecialistResponse.model_json_schema(),
},
**thinking_kwargs,
)
async with client:
await client.query(prompt)
# Process SDK stream
stream_result = await process_sdk_stream(
client=client,
context_name=f"Specialist:{config.name}",
model=model,
system_prompt=prompt,
agent_definitions={}, # No subagents for specialists
)
error = stream_result.get("error")
if error:
logger.error(
f"[Specialist:{config.name}] SDK stream failed: {error}"
)
safe_print(
f"[Specialist:{config.name}] Analysis failed: {error}",
flush=True,
)
return (config.name, [])
# Parse structured output
structured_output = stream_result.get("structured_output")
findings = self._parse_specialist_output(
config.name, structured_output, stream_result.get("result_text", "")
)
safe_print(
f"[Specialist:{config.name}] Complete: {len(findings)} findings",
flush=True,
)
return (config.name, findings)
except Exception as e:
logger.error(
f"[Specialist:{config.name}] Session failed: {e}",
exc_info=True,
)
safe_print(
f"[Specialist:{config.name}] Error: {e}",
flush=True,
)
return (config.name, [])
def _parse_specialist_output(
self,
@@ -517,8 +597,9 @@ Report findings with specific file paths, line numbers, and code evidence.
result = SpecialistResponse.model_validate(structured_output)
for f in result.findings:
finding_id = hashlib.sha256(
finding_id = hashlib.md5(
f"{f.file}:{f.line}:{f.title}".encode(),
usedforsecurity=False,
).hexdigest()[:12]
category = map_category(f.category)
@@ -592,8 +673,9 @@ Report findings with specific file paths, line numbers, and code evidence.
line = f.get("line", 0) or 0
title = f.get("title", "Unknown issue")
finding_id = hashlib.sha256(
finding_id = hashlib.md5(
f"{file_path}:{line}:{title}".encode(),
usedforsecurity=False,
).hexdigest()[:12]
category = map_category(f.get("category", "quality"))
@@ -625,17 +707,14 @@ Report findings with specific file paths, line numbers, and code evidence.
return findings
async def _run_parallel_pr_specialists(
async def _run_parallel_specialists(
self,
context: PRContext,
project_root: Path,
model: str,
thinking_budget: int | None,
) -> tuple[list[PRReviewFinding], list[str]]:
"""Run all PR review specialists in parallel and collect findings.
Uses the base class's _run_parallel_specialists() for the gather
pattern, with PR-specific task creation and result parsing.
"""Run all specialists in parallel and collect findings.
Args:
context: PR context
@@ -646,47 +725,42 @@ Report findings with specific file paths, line numbers, and code evidence.
Returns:
Tuple of (all_findings, agents_invoked)
"""
# Build coroutine factories so failed specialists can be retried
def _make_pr_specialist_factory(cfg: SpecialistConfig):
def factory():
return self._run_pr_specialist_session(
config=cfg,
context=context,
project_root=project_root,
model=model,
thinking_budget=thinking_budget,
)
return factory
coroutines = []
retry_factories = []
for config in SPECIALIST_CONFIGS:
factory = _make_pr_specialist_factory(config)
coroutines.append(factory())
retry_factories.append(factory)
# Run all specialists in parallel via base class (with retry-once)
valid_results = await super()._run_parallel_specialists(
tasks=coroutines,
orchestrator_name="ParallelOrchestrator",
retry_tasks=retry_factories,
safe_print(
f"[ParallelOrchestrator] Launching {len(SPECIALIST_CONFIGS)} specialists in parallel...",
flush=True,
)
# Create tasks for all specialists
tasks = [
self._run_specialist_session(
config=config,
context=context,
project_root=project_root,
model=model,
thinking_budget=thinking_budget,
)
for config in SPECIALIST_CONFIGS
]
# Run all specialists in parallel
results = await asyncio.gather(*tasks, return_exceptions=True)
# Collect findings and track which agents ran
all_findings: list[PRReviewFinding] = []
agents_invoked: list[str] = []
for result in valid_results:
if result is None:
for result in results:
if isinstance(result, Exception):
logger.error(f"[ParallelOrchestrator] Specialist task failed: {result}")
continue
specialist_name, findings = result
agents_invoked.append(specialist_name)
all_findings.extend(findings)
safe_print(
f"[ParallelOrchestrator] Total findings: {len(all_findings)}",
f"[ParallelOrchestrator] All specialists complete. "
f"Total findings: {len(all_findings)}",
flush=True,
)
@@ -888,8 +962,9 @@ The SDK will run invoked agents in parallel automatically.
Returns:
PRReviewFinding instance
"""
finding_id = hashlib.sha256(
finding_id = hashlib.md5(
f"{finding_data.file}:{finding_data.line}:{finding_data.title}".encode(),
usedforsecurity=False,
).hexdigest()[:12]
category = map_category(finding_data.category)
@@ -1118,7 +1193,7 @@ The SDK will run invoked agents in parallel automatically.
# =================================================================
# Run all specialists in parallel
findings, agents_invoked = await self._run_parallel_pr_specialists(
findings, agents_invoked = await self._run_parallel_specialists(
context=context,
project_root=project_root,
model=model,
@@ -1427,8 +1502,9 @@ The SDK will run invoked agents in parallel automatically.
Returns:
PRReviewFinding instance
"""
finding_id = hashlib.sha256(
finding_id = hashlib.md5(
f"{f_data.get('file', 'unknown')}:{f_data.get('line', 0)}:{f_data.get('title', 'Untitled')}".encode(),
usedforsecurity=False,
).hexdigest()[:12]
category = map_category(f_data.get("category", "quality"))
@@ -280,8 +280,6 @@ async def process_sdk_stream(
# Track subagent tool IDs to log their results
subagent_tool_ids: dict[str, str] = {} # tool_id -> agent_name
completed_agent_tool_ids: set[str] = set() # tool_ids of completed agents
# Track StructuredOutput tool submissions for fallback capture
_pending_structured_output: dict[str, dict[str, Any]] = {} # tool_id -> tool_input
# Track tool concurrency errors for retry logic
detected_concurrency_error = False
# Track repeated identical responses to detect error loops early
@@ -402,10 +400,7 @@ async def process_sdk_stream(
safe_print(
f"[{context_name}] Delegation prompt for {agent_name}: {prompt_preview}"
)
elif tool_name == "StructuredOutput":
# Track StructuredOutput submission for fallback capture
_pending_structured_output[tool_id] = tool_input
else:
elif tool_name != "StructuredOutput":
# Log meaningful tool info (not just tool name)
tool_detail = _get_tool_detail(tool_name, tool_input)
safe_print(f"[{context_name}] {tool_detail}")
@@ -451,15 +446,6 @@ async def process_sdk_stream(
f"[{context_name}] Tool result [{status}]: {result_preview}{'...' if len(str(result_content)) > 100 else ''}"
)
# Capture validated StructuredOutput tool data as fallback
if tool_id in _pending_structured_output:
if not is_error:
# Tool validation passed — save as fallback
_pending_structured_output[tool_id]["_validated"] = True
else:
# Validation failed — discard this attempt
del _pending_structured_output[tool_id]
# Invoke callback
if on_tool_result:
on_tool_result(tool_id, is_error, result_content)
@@ -492,10 +478,7 @@ async def process_sdk_stream(
safe_print(
f"[{context_name}] Invoking agent: {agent_name}{model_info}"
)
elif tool_name == "StructuredOutput":
# Track StructuredOutput submission for fallback
_pending_structured_output[tool_id] = tool_input
else:
elif tool_name != "StructuredOutput":
# Log meaningful tool info (not just tool name)
tool_detail = _get_tool_detail(tool_name, tool_input)
safe_print(f"[{context_name}] {tool_detail}")
@@ -640,15 +623,6 @@ async def process_sdk_stream(
f"[Agent:{agent_name}] {status}: {result_preview}{'...' if len(str(result_content)) > 600 else ''}"
)
# Capture validated StructuredOutput tool data as fallback
if tool_id in _pending_structured_output:
if not is_error:
_pending_structured_output[tool_id][
"_validated"
] = True
else:
del _pending_structured_output[tool_id]
# Invoke callback
if on_tool_result:
on_tool_result(tool_id, is_error, result_content)
@@ -679,19 +653,6 @@ async def process_sdk_stream(
safe_print(f"[{context_name}] Session ended. Total messages: {msg_count}")
# Fallback: if ResultMessage didn't carry structured_output, use validated
# StructuredOutput tool data (the agent submitted valid JSON but the
# ResultMessage didn't propagate it — observed in parallel sessions).
if structured_output is None and _pending_structured_output:
for tid, data in _pending_structured_output.items():
if data.pop("_validated", False):
structured_output = data
safe_print(
f"[{context_name}] Using StructuredOutput tool fallback "
f"(ResultMessage did not carry structured_output)"
)
break
# Set error flag if tool concurrency error was detected
if detected_concurrency_error and not stream_error:
stream_error = "tool_use_concurrency_error"
@@ -1,199 +0,0 @@
"""
Split Engine
============
AI-powered issue decomposition: analyzes a single GitHub issue and suggests
how to split it into smaller, well-scoped sub-issues.
"""
from __future__ import annotations
import json
import re
from pathlib import Path
try:
from ...phase_config import get_model_betas, resolve_model_id
from ..models import GitHubRunnerConfig
from .engine_base import EngineBase
from .prompt_manager import PromptManager
except (ImportError, ValueError, SystemError):
from models import GitHubRunnerConfig
from phase_config import get_model_betas, resolve_model_id
from services.engine_base import EngineBase
from services.prompt_manager import PromptManager
class SplitEngine(EngineBase):
"""Handles issue split suggestion via AI."""
def __init__(
self,
project_dir: Path,
github_dir: Path,
config: GitHubRunnerConfig,
progress_callback=None,
):
super().__init__(project_dir, github_dir, config, progress_callback)
self.prompt_manager = PromptManager()
async def suggest_split(self, issue: dict) -> dict:
"""
Analyze an issue and suggest how to split it into sub-issues.
Returns dict matching the frontend SplitSuggestion interface:
{
issueNumber, subIssues: [{title, body, labels}], rationale, confidence
}
"""
from core.client import create_client
issue_number = issue["number"]
self._report_progress(
"analyzing",
20,
f"Analyzing issue #{issue_number} for splitting...",
issue_number=issue_number,
)
context = self._build_split_context(issue)
prompt = self._get_split_prompt() + "\n\n---\n\n" + context
model_shorthand = self.config.model or "sonnet"
model = resolve_model_id(model_shorthand)
betas = get_model_betas(model_shorthand)
client = create_client(
project_dir=self.project_dir,
spec_dir=self.github_dir,
model=model,
agent_type="qa_reviewer",
betas=betas,
fast_mode=self.config.fast_mode,
)
try:
async with client:
await client.query(prompt)
response_text = ""
async for msg in client.receive_response():
msg_type = type(msg).__name__
if msg_type == "AssistantMessage" and hasattr(msg, "content"):
for block in msg.content:
block_type = type(block).__name__
if block_type == "TextBlock" and hasattr(block, "text"):
response_text += block.text
self._report_progress(
"suggesting",
80,
"Parsing split suggestion...",
issue_number=issue_number,
)
return self._parse_split_result(issue_number, response_text)
except Exception as e:
print(f"Split error for #{issue_number}: {e}")
return {
"issueNumber": issue_number,
"subIssues": [],
"rationale": f"Analysis failed: {e}",
"confidence": 0.0,
}
def _build_split_context(self, issue: dict) -> str:
"""Build context string for split analysis."""
labels = ", ".join(label["name"] for label in issue.get("labels", [])) or "None"
lines = [
f"## Issue #{issue['number']}",
f"**Title:** {issue['title']}",
f"**Author:** {issue.get('author', {}).get('login', 'unknown')}",
f"**Labels:** {labels}",
"",
"### Body",
issue.get("body", "No description provided.") or "No description provided.",
"",
]
return "\n".join(lines)
def _get_split_prompt(self) -> str:
"""Get the split suggestion prompt."""
prompt_file = self.prompt_manager.prompts_dir / "issue_split.md"
if prompt_file.exists():
return prompt_file.read_text(encoding="utf-8")
return self._get_default_split_prompt()
@staticmethod
def _get_default_split_prompt() -> str:
"""Default split suggestion prompt."""
return """# Issue Split Agent
You are an issue decomposition assistant. Analyze the GitHub issue and suggest
how to break it down into smaller, well-scoped sub-issues.
Guidelines:
- Each sub-issue should be independently implementable
- Sub-issues should have clear scope boundaries
- Aim for 2-5 sub-issues (no more than 8)
- Each sub-issue should have a descriptive title, detailed body, and relevant labels
- The body should reference the parent issue number
- Preserve the original issue's labels where relevant
Output ONLY a JSON block:
```json
{
"subIssues": [
{
"title": "Descriptive sub-issue title",
"body": "Detailed description of what this sub-issue covers.\\n\\nPart of #PARENT_NUMBER.",
"labels": ["type:feature", "component:frontend"]
}
],
"rationale": "Why this issue should be split and how the sub-issues relate",
"confidence": 0.85
}
```
"""
@staticmethod
def _parse_split_result(issue_number: int, response_text: str) -> dict:
"""Parse split suggestion from AI response."""
default = {
"issueNumber": issue_number,
"subIssues": [],
"rationale": "",
"confidence": 0.0,
}
try:
json_match = re.search(
r"```json\s*(\{.*?\})\s*```", response_text, re.DOTALL
)
if json_match:
data = json.loads(json_match.group(1))
sub_issues = []
for sub in data.get("subIssues", []):
sub_issues.append(
{
"title": sub.get("title", ""),
"body": sub.get("body", ""),
"labels": sub.get("labels", []),
}
)
return {
"issueNumber": issue_number,
"subIssues": sub_issues,
"rationale": data.get("rationale", ""),
"confidence": float(data.get("confidence", 0.5)),
}
except (json.JSONDecodeError, KeyError, ValueError) as e:
print(f"Failed to parse split result: {e}")
return default
+1 -3
View File
@@ -254,7 +254,7 @@ class MockGitHubClient:
raise Exception(f"Issue #{issue_number} not found")
return self.issues[issue_number]
async def issue_comment(self, issue_number: int, body: str) -> int:
async def issue_comment(self, issue_number: int, body: str) -> None:
self._log_call("issue_comment", issue_number=issue_number)
self.posted_comments.append(
{
@@ -262,8 +262,6 @@ class MockGitHubClient:
"body": body,
}
)
# Return a fake comment ID for testing
return 123456 + issue_number
async def issue_add_labels(self, issue_number: int, labels: list[str]) -> None:
self._log_call("issue_add_labels", issue_number=issue_number, labels=labels)
+543
View File
@@ -0,0 +1,543 @@
"""
Trust Escalation Model
======================
Progressive trust system that unlocks more autonomous actions as accuracy improves:
- L0: Review-only (comment, no actions)
- L1: Auto-apply labels based on triage
- L2: Auto-close duplicates and spam
- L3: Auto-merge trivial fixes (docs, typos)
- L4: Full auto-fix with merge
Trust increases with accuracy, decreases with overrides.
"""
from __future__ import annotations
import json
from dataclasses import dataclass, field
from datetime import datetime, timezone
from enum import IntEnum
from pathlib import Path
from typing import Any
class TrustLevel(IntEnum):
"""Trust levels with increasing autonomy."""
L0_REVIEW_ONLY = 0 # Comment only, no actions
L1_LABEL = 1 # Auto-apply labels
L2_CLOSE = 2 # Auto-close duplicates/spam
L3_MERGE_TRIVIAL = 3 # Auto-merge trivial fixes
L4_FULL_AUTO = 4 # Full autonomous operation
@property
def display_name(self) -> str:
names = {
0: "Review Only",
1: "Auto-Label",
2: "Auto-Close",
3: "Auto-Merge Trivial",
4: "Full Autonomous",
}
return names.get(self.value, "Unknown")
@property
def description(self) -> str:
descriptions = {
0: "AI can comment with suggestions but takes no actions",
1: "AI can automatically apply labels based on triage",
2: "AI can auto-close clear duplicates and spam",
3: "AI can auto-merge trivial changes (docs, typos, formatting)",
4: "AI can auto-fix issues and merge PRs autonomously",
}
return descriptions.get(self.value, "")
@property
def allowed_actions(self) -> set[str]:
"""Actions allowed at this trust level."""
actions = {
0: {"comment", "review"},
1: {"comment", "review", "label", "triage"},
2: {
"comment",
"review",
"label",
"triage",
"close_duplicate",
"close_spam",
},
3: {
"comment",
"review",
"label",
"triage",
"close_duplicate",
"close_spam",
"merge_trivial",
},
4: {
"comment",
"review",
"label",
"triage",
"close_duplicate",
"close_spam",
"merge_trivial",
"auto_fix",
"merge",
},
}
return actions.get(self.value, set())
def can_perform(self, action: str) -> bool:
"""Check if this trust level allows an action."""
return action in self.allowed_actions
# Thresholds for trust level upgrades
TRUST_THRESHOLDS = {
TrustLevel.L1_LABEL: {
"min_actions": 20,
"min_accuracy": 0.90,
"min_days": 3,
},
TrustLevel.L2_CLOSE: {
"min_actions": 50,
"min_accuracy": 0.92,
"min_days": 7,
},
TrustLevel.L3_MERGE_TRIVIAL: {
"min_actions": 100,
"min_accuracy": 0.95,
"min_days": 14,
},
TrustLevel.L4_FULL_AUTO: {
"min_actions": 200,
"min_accuracy": 0.97,
"min_days": 30,
},
}
@dataclass
class AccuracyMetrics:
"""Tracks accuracy metrics for trust calculation."""
total_actions: int = 0
correct_actions: int = 0
overridden_actions: int = 0
last_action_at: str | None = None
first_action_at: str | None = None
# Per-action type metrics
review_total: int = 0
review_correct: int = 0
label_total: int = 0
label_correct: int = 0
triage_total: int = 0
triage_correct: int = 0
close_total: int = 0
close_correct: int = 0
merge_total: int = 0
merge_correct: int = 0
fix_total: int = 0
fix_correct: int = 0
@property
def accuracy(self) -> float:
"""Overall accuracy rate."""
if self.total_actions == 0:
return 0.0
return self.correct_actions / self.total_actions
@property
def override_rate(self) -> float:
"""Rate of overridden actions."""
if self.total_actions == 0:
return 0.0
return self.overridden_actions / self.total_actions
@property
def days_active(self) -> int:
"""Days since first action."""
if not self.first_action_at:
return 0
first = datetime.fromisoformat(self.first_action_at)
now = datetime.now(timezone.utc)
return (now - first).days
def record_action(
self,
action_type: str,
correct: bool,
overridden: bool = False,
) -> None:
"""Record an action outcome."""
now = datetime.now(timezone.utc).isoformat()
self.total_actions += 1
if correct:
self.correct_actions += 1
if overridden:
self.overridden_actions += 1
self.last_action_at = now
if not self.first_action_at:
self.first_action_at = now
# Update per-type metrics
type_map = {
"review": ("review_total", "review_correct"),
"label": ("label_total", "label_correct"),
"triage": ("triage_total", "triage_correct"),
"close": ("close_total", "close_correct"),
"merge": ("merge_total", "merge_correct"),
"fix": ("fix_total", "fix_correct"),
}
if action_type in type_map:
total_attr, correct_attr = type_map[action_type]
setattr(self, total_attr, getattr(self, total_attr) + 1)
if correct:
setattr(self, correct_attr, getattr(self, correct_attr) + 1)
def to_dict(self) -> dict[str, Any]:
return {
"total_actions": self.total_actions,
"correct_actions": self.correct_actions,
"overridden_actions": self.overridden_actions,
"last_action_at": self.last_action_at,
"first_action_at": self.first_action_at,
"review_total": self.review_total,
"review_correct": self.review_correct,
"label_total": self.label_total,
"label_correct": self.label_correct,
"triage_total": self.triage_total,
"triage_correct": self.triage_correct,
"close_total": self.close_total,
"close_correct": self.close_correct,
"merge_total": self.merge_total,
"merge_correct": self.merge_correct,
"fix_total": self.fix_total,
"fix_correct": self.fix_correct,
}
@classmethod
def from_dict(cls, data: dict[str, Any]) -> AccuracyMetrics:
return cls(**{k: v for k, v in data.items() if k in cls.__dataclass_fields__})
@dataclass
class TrustState:
"""Trust state for a repository."""
repo: str
current_level: TrustLevel = TrustLevel.L0_REVIEW_ONLY
metrics: AccuracyMetrics = field(default_factory=AccuracyMetrics)
manual_override: TrustLevel | None = None # User-set override
last_level_change: str | None = None
level_history: list[dict[str, Any]] = field(default_factory=list)
@property
def effective_level(self) -> TrustLevel:
"""Get effective trust level (considers manual override)."""
if self.manual_override is not None:
return self.manual_override
return self.current_level
def can_perform(self, action: str) -> bool:
"""Check if current trust level allows an action."""
return self.effective_level.can_perform(action)
def get_progress_to_next_level(self) -> dict[str, Any]:
"""Get progress toward next trust level."""
current = self.current_level
if current >= TrustLevel.L4_FULL_AUTO:
return {
"next_level": None,
"at_max": True,
}
next_level = TrustLevel(current + 1)
thresholds = TRUST_THRESHOLDS.get(next_level, {})
min_actions = thresholds.get("min_actions", 0)
min_accuracy = thresholds.get("min_accuracy", 0)
min_days = thresholds.get("min_days", 0)
return {
"next_level": next_level.value,
"next_level_name": next_level.display_name,
"at_max": False,
"actions": {
"current": self.metrics.total_actions,
"required": min_actions,
"progress": min(1.0, self.metrics.total_actions / max(1, min_actions)),
},
"accuracy": {
"current": self.metrics.accuracy,
"required": min_accuracy,
"progress": min(1.0, self.metrics.accuracy / max(0.01, min_accuracy)),
},
"days": {
"current": self.metrics.days_active,
"required": min_days,
"progress": min(1.0, self.metrics.days_active / max(1, min_days)),
},
}
def check_upgrade(self) -> TrustLevel | None:
"""Check if eligible for trust level upgrade."""
current = self.current_level
if current >= TrustLevel.L4_FULL_AUTO:
return None
next_level = TrustLevel(current + 1)
thresholds = TRUST_THRESHOLDS.get(next_level)
if not thresholds:
return None
if (
self.metrics.total_actions >= thresholds["min_actions"]
and self.metrics.accuracy >= thresholds["min_accuracy"]
and self.metrics.days_active >= thresholds["min_days"]
):
return next_level
return None
def upgrade_level(self, new_level: TrustLevel, reason: str = "auto") -> None:
"""Upgrade to a new trust level."""
if new_level <= self.current_level:
return
now = datetime.now(timezone.utc).isoformat()
self.level_history.append(
{
"from_level": self.current_level.value,
"to_level": new_level.value,
"reason": reason,
"timestamp": now,
"metrics_snapshot": self.metrics.to_dict(),
}
)
self.current_level = new_level
self.last_level_change = now
def downgrade_level(self, reason: str = "override") -> None:
"""Downgrade trust level due to override or errors."""
if self.current_level <= TrustLevel.L0_REVIEW_ONLY:
return
new_level = TrustLevel(self.current_level - 1)
now = datetime.now(timezone.utc).isoformat()
self.level_history.append(
{
"from_level": self.current_level.value,
"to_level": new_level.value,
"reason": reason,
"timestamp": now,
}
)
self.current_level = new_level
self.last_level_change = now
def set_manual_override(self, level: TrustLevel | None) -> None:
"""Set or clear manual trust level override."""
self.manual_override = level
if level is not None:
now = datetime.now(timezone.utc).isoformat()
self.level_history.append(
{
"from_level": self.current_level.value,
"to_level": level.value,
"reason": "manual_override",
"timestamp": now,
}
)
def to_dict(self) -> dict[str, Any]:
return {
"repo": self.repo,
"current_level": self.current_level.value,
"metrics": self.metrics.to_dict(),
"manual_override": self.manual_override.value
if self.manual_override
else None,
"last_level_change": self.last_level_change,
"level_history": self.level_history[-20:], # Keep last 20 changes
}
@classmethod
def from_dict(cls, data: dict[str, Any]) -> TrustState:
return cls(
repo=data["repo"],
current_level=TrustLevel(data.get("current_level", 0)),
metrics=AccuracyMetrics.from_dict(data.get("metrics", {})),
manual_override=TrustLevel(data["manual_override"])
if data.get("manual_override") is not None
else None,
last_level_change=data.get("last_level_change"),
level_history=data.get("level_history", []),
)
class TrustManager:
"""
Manages trust levels across repositories.
Usage:
trust = TrustManager(state_dir=Path(".auto-claude/github"))
# Check if action is allowed
if trust.can_perform("owner/repo", "auto_fix"):
perform_auto_fix()
# Record action outcome
trust.record_action("owner/repo", "review", correct=True)
# Check for upgrade
if trust.check_and_upgrade("owner/repo"):
print("Trust level upgraded!")
"""
def __init__(self, state_dir: Path):
self.state_dir = state_dir
self.trust_dir = state_dir / "trust"
self.trust_dir.mkdir(parents=True, exist_ok=True)
self._states: dict[str, TrustState] = {}
def _get_state_file(self, repo: str) -> Path:
safe_name = repo.replace("/", "_")
return self.trust_dir / f"{safe_name}.json"
def get_state(self, repo: str) -> TrustState:
"""Get trust state for a repository."""
if repo in self._states:
return self._states[repo]
state_file = self._get_state_file(repo)
if state_file.exists():
try:
with open(state_file, encoding="utf-8") as f:
data = json.load(f)
state = TrustState.from_dict(data)
except (json.JSONDecodeError, UnicodeDecodeError):
# Return default state if file is corrupted
state = TrustState(repo=repo)
else:
state = TrustState(repo=repo)
self._states[repo] = state
return state
def save_state(self, repo: str) -> None:
"""Save trust state for a repository with secure file permissions."""
import os
state = self.get_state(repo)
state_file = self._get_state_file(repo)
# Write with restrictive permissions (0o600 = owner read/write only)
fd = os.open(str(state_file), os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
# os.fdopen takes ownership of fd and will close it when the with block exits
with os.fdopen(fd, "w", encoding="utf-8") as f:
json.dump(state.to_dict(), f, indent=2)
def get_trust_level(self, repo: str) -> TrustLevel:
"""Get current trust level for a repository."""
return self.get_state(repo).effective_level
def can_perform(self, repo: str, action: str) -> bool:
"""Check if an action is allowed for a repository."""
return self.get_state(repo).can_perform(action)
def record_action(
self,
repo: str,
action_type: str,
correct: bool,
overridden: bool = False,
) -> None:
"""Record an action outcome."""
state = self.get_state(repo)
state.metrics.record_action(action_type, correct, overridden)
# Check for downgrade on override
if overridden:
# Downgrade if override rate exceeds 10%
if state.metrics.override_rate > 0.10 and state.metrics.total_actions >= 10:
state.downgrade_level(reason="high_override_rate")
self.save_state(repo)
def check_and_upgrade(self, repo: str) -> bool:
"""Check for and apply trust level upgrade."""
state = self.get_state(repo)
new_level = state.check_upgrade()
if new_level:
state.upgrade_level(new_level, reason="threshold_met")
self.save_state(repo)
return True
return False
def set_manual_level(self, repo: str, level: TrustLevel) -> None:
"""Manually set trust level for a repository."""
state = self.get_state(repo)
state.set_manual_override(level)
self.save_state(repo)
def clear_manual_override(self, repo: str) -> None:
"""Clear manual trust level override."""
state = self.get_state(repo)
state.set_manual_override(None)
self.save_state(repo)
def get_progress(self, repo: str) -> dict[str, Any]:
"""Get progress toward next trust level."""
state = self.get_state(repo)
return {
"current_level": state.effective_level.value,
"current_level_name": state.effective_level.display_name,
"is_manual_override": state.manual_override is not None,
"accuracy": state.metrics.accuracy,
"total_actions": state.metrics.total_actions,
"override_rate": state.metrics.override_rate,
"days_active": state.metrics.days_active,
"progress_to_next": state.get_progress_to_next_level(),
}
def get_all_states(self) -> list[TrustState]:
"""Get trust states for all repos."""
states = []
for file in self.trust_dir.glob("*.json"):
try:
with open(file, encoding="utf-8") as f:
data = json.load(f)
states.append(TrustState.from_dict(data))
except (json.JSONDecodeError, UnicodeDecodeError):
# Skip corrupted state files
continue
return states
def get_summary(self) -> dict[str, Any]:
"""Get summary of trust across all repos."""
states = self.get_all_states()
by_level = {}
for state in states:
level = state.effective_level.value
by_level[level] = by_level.get(level, 0) + 1
total_actions = sum(s.metrics.total_actions for s in states)
total_correct = sum(s.metrics.correct_actions for s in states)
return {
"total_repos": len(states),
"by_level": by_level,
"total_actions": total_actions,
"overall_accuracy": total_correct / max(1, total_actions),
}
+155 -7
View File
@@ -8,8 +8,10 @@ about a codebase. It can also suggest tasks based on the conversation.
import argparse
import asyncio
import base64
import json
import sys
import tempfile
from pathlib import Path
# Add auto-claude to path
@@ -111,6 +113,107 @@ def load_project_context(project_dir: str) -> str:
)
ALLOWED_MIME_TYPES = frozenset(
["image/png", "image/jpeg", "image/jpg", "image/gif", "image/webp"]
)
MAX_IMAGE_FILE_SIZE = 10 * 1024 * 1024 # 10 MB (aligned with frontend MAX_IMAGE_SIZE)
def load_images_from_manifest(manifest_path: str) -> list[dict]:
"""Load images from a manifest JSON file.
The manifest contains an array of objects with 'path' and 'mimeType' fields.
Each image file is read as binary and encoded to base64.
Returns a list of dicts with 'media_type' and 'data' (base64-encoded) fields.
"""
images = []
tmp_dir = Path(tempfile.gettempdir()).resolve()
try:
with open(manifest_path, encoding="utf-8") as f:
manifest = json.load(f)
for entry in manifest:
image_path = entry.get("path")
mime_type = entry.get("mimeType", "image/png")
if not image_path:
debug_error(
"insights_runner",
"Image entry missing path field",
)
continue
# Validate path is within temp directory before checking existence
try:
resolved = Path(image_path).resolve()
if not resolved.is_relative_to(tmp_dir):
debug_error(
"insights_runner",
f"Image path outside temp directory, skipping: {image_path}",
)
continue
except (ValueError, OSError):
debug_error(
"insights_runner",
f"Invalid image path, skipping: {image_path}",
)
continue
if not resolved.exists():
debug_error(
"insights_runner",
f"Image file not found: {image_path}",
)
continue
# Validate MIME type against allowlist
if mime_type not in ALLOWED_MIME_TYPES:
debug_error(
"insights_runner",
f"Invalid MIME type '{mime_type}', skipping: {image_path}",
)
continue
# Validate file size
file_size = resolved.stat().st_size
if file_size > MAX_IMAGE_FILE_SIZE:
debug_error(
"insights_runner",
f"Image too large ({file_size} bytes), skipping: {image_path}",
)
continue
try:
with open(resolved, "rb") as img_f:
image_data = base64.b64encode(img_f.read()).decode("utf-8")
images.append(
{
"media_type": mime_type,
"data": image_data,
}
)
debug(
"insights_runner",
"Loaded image",
path=image_path,
mime_type=mime_type,
size_bytes=file_size,
)
except Exception as e:
debug_error(
"insights_runner",
f"Failed to read image {image_path}: {e}",
)
except (json.JSONDecodeError, OSError) as e:
debug_error("insights_runner", f"Failed to load images manifest: {e}")
return images
def build_system_prompt(project_dir: str) -> str:
"""Build the system prompt for the insights agent."""
context = load_project_context(project_dir)
@@ -143,11 +246,12 @@ async def run_with_sdk(
history: list,
model: str = "sonnet", # Shorthand - resolved via API Profile if configured
thinking_level: str = "medium",
images: list[dict] | None = None,
) -> None:
"""Run the chat using Claude SDK with streaming."""
if not SDK_AVAILABLE:
print("Claude SDK not available, falling back to simple mode", file=sys.stderr)
run_simple(project_dir, message, history)
run_simple(project_dir, message, history, images)
return
if not get_auth_token():
@@ -155,7 +259,7 @@ async def run_with_sdk(
"No authentication token found, falling back to simple mode",
file=sys.stderr,
)
run_simple(project_dir, message, history)
run_simple(project_dir, message, history, images)
return
# Ensure SDK can find the token
@@ -205,8 +309,24 @@ Current question: {message}"""
# Use async context manager pattern
async with client:
# Send the query
await client.query(full_prompt)
# Build the query - images are stored for reference but SDK doesn't support multi-modal input yet
if images:
debug(
"insights_runner",
"Images attached but SDK does not support multi-modal input",
image_count=len(images),
)
# TODO: When the SDK adds support for multi-modal content blocks, update this.
image_note = f"\n\n[Note: The user attached {len(images)} image(s), but the current SDK version does not support multi-modal input. Please ask the user to describe the image content instead.]"
print(
"Warning: Image attachments cannot be sent to the model in SDK mode. Sending text-only query.",
file=sys.stderr,
)
await client.query(full_prompt + image_note)
else:
# Send the query as plain text
await client.query(full_prompt)
# Stream the response
response_text = ""
@@ -280,13 +400,21 @@ Current question: {message}"""
import traceback
traceback.print_exc(file=sys.stderr)
run_simple(project_dir, message, history)
run_simple(project_dir, message, history, images)
def run_simple(project_dir: str, message: str, history: list) -> None:
def run_simple(
project_dir: str, message: str, history: list, images: list[dict] | None = None
) -> None:
"""Simple fallback mode without SDK - uses subprocess to call claude CLI."""
import subprocess
if images:
print(
"Warning: Image attachments are not supported in simple mode and will be skipped.",
file=sys.stderr,
)
system_prompt = build_system_prompt(project_dir)
# Build conversation context
@@ -355,6 +483,10 @@ def main():
default="medium",
help="Thinking level for extended reasoning (low, medium, high)",
)
parser.add_argument(
"--images-file",
help="Path to JSON manifest file listing image file paths and MIME types",
)
args = parser.parse_args()
# Validate and sanitize thinking level (handles legacy values like 'ultrathink')
@@ -398,9 +530,25 @@ def main():
debug_error("insights_runner", f"Failed to load history: {e}")
history = []
# Load images from manifest file if provided
images = None
if args.images_file:
debug("insights_runner", "Loading images from manifest", file=args.images_file)
images = load_images_from_manifest(args.images_file)
if images:
debug(
"insights_runner",
"Loaded images for multi-modal query",
image_count=len(images),
)
else:
debug("insights_runner", "No valid images loaded from manifest")
# Run the async SDK function
debug("insights_runner", "Running SDK query")
asyncio.run(run_with_sdk(project_dir, user_message, history, model, thinking_level))
asyncio.run(
run_with_sdk(project_dir, user_message, history, model, thinking_level, images)
)
debug_success("insights_runner", "Query completed")
@@ -31,6 +31,7 @@ class CompetitorAnalyzer:
self.refresh = refresh
self.agent_executor = agent_executor
self.analysis_file = output_dir / "competitor_analysis.json"
self.manual_competitors_file = output_dir / "manual_competitors.json"
self.discovery_file = output_dir / "roadmap_discovery.json"
self.project_index_file = output_dir / "project_index.json"
@@ -42,7 +43,10 @@ class CompetitorAnalyzer:
"""
if not enabled:
print_status("Competitor analysis not enabled, skipping", "info")
manual_competitors = self._get_manual_competitors()
self._create_disabled_analysis_file()
if manual_competitors:
self._merge_manual_competitors(manual_competitors)
return RoadmapPhaseResult(
"competitor_analysis", True, [str(self.analysis_file)], [], 0
)
@@ -53,6 +57,9 @@ class CompetitorAnalyzer:
"competitor_analysis", True, [str(self.analysis_file)], [], 0
)
# Preserve manual competitors before any path that overwrites the file
manual_competitors = self._get_manual_competitors()
if not self.discovery_file.exists():
print_status(
"Discovery file not found, skipping competitor analysis", "warning"
@@ -60,6 +67,8 @@ class CompetitorAnalyzer:
self._create_error_analysis_file(
"Discovery file not found - cannot analyze competitors without project context"
)
if manual_competitors:
self._merge_manual_competitors(manual_competitors)
return RoadmapPhaseResult(
"competitor_analysis",
True,
@@ -84,6 +93,8 @@ class CompetitorAnalyzer:
if success and self.analysis_file.exists():
validation_result = self._validate_analysis()
if validation_result is not None:
if manual_competitors:
self._merge_manual_competitors(manual_competitors)
return validation_result
errors.append(f"Attempt {attempt + 1}: Validation failed")
else:
@@ -100,12 +111,82 @@ class CompetitorAnalyzer:
print(f" {muted('Error:')} {err}")
self._create_error_analysis_file("Analysis failed after retries", errors)
if manual_competitors:
self._merge_manual_competitors(manual_competitors)
# Return success=True for graceful degradation (don't block roadmap generation)
return RoadmapPhaseResult(
"competitor_analysis", True, [str(self.analysis_file)], errors, MAX_RETRIES
)
def _get_manual_competitors(self) -> list[dict]:
"""Extract manually-added competitors from the dedicated manual file and analysis file.
Reads from manual_competitors.json (primary, never overwritten by agent) and
falls back to competitor_analysis.json. Deduplicates by competitor ID.
Returns a list of competitor dicts where source == 'manual'.
"""
competitors_by_id: dict[str, dict] = {}
# Primary source: dedicated manual competitors file (never overwritten by agent)
if self.manual_competitors_file.exists():
try:
with open(self.manual_competitors_file, encoding="utf-8") as f:
data = json.load(f)
for c in data.get("competitors", []):
if isinstance(c, dict) and c.get("id"):
competitors_by_id[c["id"]] = c
except (json.JSONDecodeError, OSError) as e:
print_status(
f"Warning: could not read manual competitors file: {e}", "warning"
)
# Fallback: also check analysis file for manual competitors
if self.analysis_file.exists():
try:
with open(self.analysis_file, encoding="utf-8") as f:
data = json.load(f)
for c in data.get("competitors", []):
if (
isinstance(c, dict)
and c.get("source") == "manual"
and c.get("id")
and c["id"] not in competitors_by_id
):
competitors_by_id[c["id"]] = c
except (json.JSONDecodeError, OSError) as e:
print_status(
f"Warning: could not read manual competitors from analysis: {e}",
"warning",
)
return list(competitors_by_id.values())
def _merge_manual_competitors(self, manual_competitors: list[dict]) -> None:
"""Merge manual competitors back into the newly-generated analysis file.
Appends manual competitors that don't already exist (by ID) in the file.
"""
if not manual_competitors:
return
try:
with open(self.analysis_file, encoding="utf-8") as f:
data = json.load(f)
except (json.JSONDecodeError, OSError) as e:
print_status(f"Warning: failed to merge manual competitors: {e}", "warning")
return
existing_ids = {
c.get("id") for c in data.get("competitors", []) if isinstance(c, dict)
}
for competitor in manual_competitors:
if competitor.get("id") not in existing_ids:
data.setdefault("competitors", []).append(competitor)
write_json_atomic(self.analysis_file, data, indent=2)
def _build_context(self) -> str:
"""Build context string for the competitor analysis agent."""
return f"""
@@ -140,8 +221,11 @@ Output your findings to competitor_analysis.json.
"competitor_analysis", True, [str(self.analysis_file)], [], 0
)
except json.JSONDecodeError:
pass
except json.JSONDecodeError as e:
print_status(
f"Warning: competitor analysis file is not valid JSON: {e}",
"warning",
)
return None
@@ -2,11 +2,6 @@
"project_root": "/Users/andremikalsen/Documents/Coding/autonomous-coding",
"project_type": "single",
"services": {},
"infrastructure": {
"docker_compose": "docker-compose.yml",
"docker_services": [
"falkordb"
]
},
"infrastructure": {},
"conventions": {}
}
+1 -1
View File
@@ -136,7 +136,7 @@ Examples:
python spec_runner.py --task "Update text" --complexity simple
# Complex integration (auto-detected)
python spec_runner.py --task "Add Graphiti memory integration with FalkorDB"
python spec_runner.py --task "Add Graphiti memory integration with LadybugDB"
# Interactive mode
python spec_runner.py --interactive
+32
View File
@@ -21,6 +21,8 @@ from datetime import datetime, timedelta, timezone
from enum import Enum
from pathlib import Path
from core.file_utils import write_json_atomic
# Recovery manager configuration
ATTEMPT_WINDOW_SECONDS = 7200 # Only count attempts within last 2 hours
MAX_ATTEMPT_HISTORY_PER_SUBTASK = 50 # Cap stored attempts per subtask
@@ -514,6 +516,36 @@ class RecoveryManager:
self._save_attempt_history(history)
# Also update the subtask status in implementation_plan.json
# so that other callers (like is_build_ready_for_qa) see accurate status
try:
plan_file = self.spec_dir / "implementation_plan.json"
if plan_file.exists():
with open(plan_file, encoding="utf-8") as f:
plan = json.load(f)
updated = False
for phase in plan.get("phases", []):
for subtask in phase.get("subtasks", []):
if subtask.get("id") == subtask_id:
subtask["status"] = "failed"
stuck_note = f"Marked as stuck: {reason}"
existing = subtask.get("actual_output", "")
subtask["actual_output"] = (
f"{stuck_note}\n{existing}" if existing else stuck_note
)
updated = True
break
if updated:
break
if updated:
write_json_atomic(plan_file, plan, indent=2)
except (OSError, json.JSONDecodeError, UnicodeDecodeError) as e:
logger.warning(
f"Failed to update implementation_plan.json for stuck subtask {subtask_id}: {e}"
)
def get_stuck_subtasks(self) -> list[dict]:
"""
Get all subtasks marked as stuck.
+46 -4
View File
@@ -6,18 +6,54 @@ Phases for spec document creation and quality assurance.
"""
import json
from typing import TYPE_CHECKING
from pathlib import Path
from .. import validator, writer
from ..discovery import get_project_index_stats
from .models import MAX_RETRIES, PhaseResult
if TYPE_CHECKING:
pass
def _is_greenfield_project(spec_dir: Path) -> bool:
"""Check if the project is empty/greenfield (0 discovered files)."""
stats = get_project_index_stats(spec_dir)
if not stats:
return False # Can't determine - don't assume greenfield
return stats.get("file_count", 0) == 0
def _greenfield_context() -> str:
"""Return additional context for greenfield/empty projects."""
return """
**GREENFIELD PROJECT**: This is an empty or new project with no existing code.
There are no existing files to reference or modify. You are creating everything from scratch.
Adapt your approach:
- Do NOT reference existing files, patterns, or code structures
- Focus on what needs to be CREATED, not modified
- Define the initial project structure, files, and directories
- Specify the tech stack, frameworks, and dependencies to install
- Provide setup instructions for the new project
- For "Files to Modify" and "Files to Reference" sections, list files to CREATE instead
- For "Patterns to Follow", describe industry best practices rather than existing code
"""
class SpecPhaseMixin:
"""Mixin for spec writing and critique phase methods."""
def _check_and_log_greenfield(self) -> bool:
"""Check if the project is greenfield and log if so.
Returns:
True if the project is greenfield (no existing files).
"""
is_greenfield = _is_greenfield_project(self.spec_dir)
if is_greenfield:
self.ui.print_status(
"Greenfield project detected - adapting spec for new project", "info"
)
return is_greenfield
async def phase_quick_spec(self) -> PhaseResult:
"""Quick spec for simple tasks - combines context and spec in one step."""
spec_file = self.spec_dir / "spec.md"
@@ -29,6 +65,8 @@ class SpecPhaseMixin:
"quick_spec", True, [str(spec_file), str(plan_file)], [], 0
)
is_greenfield = self._check_and_log_greenfield()
errors = []
for attempt in range(MAX_RETRIES):
self.ui.print_status(
@@ -42,7 +80,7 @@ class SpecPhaseMixin:
This is a SIMPLE task. Create a minimal spec and implementation plan directly.
No research or extensive analysis needed.
{_greenfield_context() if is_greenfield else ""}
Create:
1. A concise spec.md with just the essential sections
2. A simple implementation_plan.json with 1-2 subtasks
@@ -80,6 +118,9 @@ Create:
"spec.md exists but has issues, regenerating...", "warning"
)
is_greenfield = self._check_and_log_greenfield()
greenfield_ctx = _greenfield_context() if is_greenfield else ""
errors = []
for attempt in range(MAX_RETRIES):
self.ui.print_status(
@@ -88,6 +129,7 @@ Create:
success, output = await self.run_agent_fn(
"spec_writer.md",
additional_context=greenfield_ctx,
phase_name="spec_writing",
)
+2 -1
View File
@@ -12,6 +12,7 @@ from ui.capabilities import configure_safe_encoding
configure_safe_encoding()
from core.error_utils import safe_receive_messages
from debug import debug, debug_detailed, debug_error, debug_section, debug_success
from security.tool_input_validator import get_safe_tool_input
from task_logger import (
@@ -162,7 +163,7 @@ class AgentRunner:
response_text = ""
debug("agent_runner", "Starting to receive response stream...")
async for msg in client.receive_response():
async for msg in safe_receive_messages(client, caller="agent_runner"):
msg_type = type(msg).__name__
message_count += 1
debug_detailed(
+8 -8
View File
@@ -203,19 +203,19 @@ def generate_spec_name(task_description: str) -> str:
return "-".join(name_parts) if name_parts else "spec"
def rename_spec_dir_from_requirements(spec_dir: Path) -> bool:
def rename_spec_dir_from_requirements(spec_dir: Path) -> Path:
"""Rename spec directory based on requirements.json task description.
Args:
spec_dir: The current spec directory
Returns:
Tuple of (success, new_spec_dir). If success is False, new_spec_dir is the original.
The new spec directory path (or the original if no rename was needed/possible).
"""
requirements_file = spec_dir / "requirements.json"
if not requirements_file.exists():
return False
return spec_dir
try:
with open(requirements_file, encoding="utf-8") as f:
@@ -223,7 +223,7 @@ def rename_spec_dir_from_requirements(spec_dir: Path) -> bool:
task_desc = req.get("task_description", "")
if not task_desc:
return False
return spec_dir
# Generate new name
new_name = generate_spec_name(task_desc)
@@ -240,11 +240,11 @@ def rename_spec_dir_from_requirements(spec_dir: Path) -> bool:
# Don't rename if it's already a good name (not "pending")
if "pending" not in current_name:
return True
return spec_dir
# Don't rename if target already exists
if new_spec_dir.exists():
return True
return spec_dir
# Rename the directory
shutil.move(str(spec_dir), str(new_spec_dir))
@@ -253,11 +253,11 @@ def rename_spec_dir_from_requirements(spec_dir: Path) -> bool:
update_task_logger_path(new_spec_dir)
print_status(f"Spec folder: {highlight(new_dir_name)}", "success")
return True
return new_spec_dir
except (json.JSONDecodeError, OSError) as e:
print_status(f"Could not rename spec folder: {e}", "warning")
return False
return spec_dir
# Phase display configuration
+104 -19
View File
@@ -6,6 +6,7 @@ Main orchestration logic for spec creation with dynamic complexity adaptation.
"""
import json
import types
from collections.abc import Callable
from pathlib import Path
@@ -18,6 +19,7 @@ from review import run_review_checkpoint
from task_logger import (
LogEntryType,
LogPhase,
TaskLogger,
get_task_logger,
)
from ui import (
@@ -238,6 +240,47 @@ class SpecOrchestrator:
task_logger.start_phase(LogPhase.PLANNING, "Starting spec creation process")
TaskEventEmitter.from_spec_dir(self.spec_dir).emit("PLANNING_STARTED")
# Track whether we've already ended the planning phase (to avoid double-end)
self._planning_phase_ended = False
try:
return await self._run_phases(interactive, auto_approve, task_logger, ui)
except Exception as e:
# Emit PLANNING_FAILED so the frontend XState machine transitions to error state
# instead of leaving the task stuck in "planning" forever
try:
task_emitter = TaskEventEmitter.from_spec_dir(self.spec_dir)
task_emitter.emit(
"PLANNING_FAILED",
{"error": str(e), "recoverable": True},
)
except Exception:
pass # Don't mask the original error
if not self._planning_phase_ended:
self._planning_phase_ended = True
try:
task_logger.end_phase(
LogPhase.PLANNING,
success=False,
message=f"Spec creation crashed: {e}",
)
except Exception:
pass # Best effort - don't mask the original error when logging fails
raise
async def _run_phases(
self,
interactive: bool,
auto_approve: bool,
task_logger: TaskLogger,
ui: types.ModuleType,
) -> bool:
"""Internal method that runs all spec creation phases.
Separated from run() so that run() can wrap this in a try/except
to emit PLANNING_FAILED on unhandled exceptions.
"""
print(
box(
f"Spec Directory: {self.spec_dir}\n"
@@ -291,9 +334,11 @@ class SpecOrchestrator:
results.append(result)
if not result.success:
print_status("Discovery failed", "error")
self._planning_phase_ended = True
task_logger.end_phase(
LogPhase.PLANNING, success=False, message="Discovery failed"
)
self._emit_planning_failed("Discovery phase failed")
return False
# Store summary for subsequent phases (compaction)
await self._store_phase_summary("discovery")
@@ -305,17 +350,26 @@ class SpecOrchestrator:
results.append(result)
if not result.success:
print_status("Requirements gathering failed", "error")
self._planning_phase_ended = True
task_logger.end_phase(
LogPhase.PLANNING,
success=False,
message="Requirements gathering failed",
)
self._emit_planning_failed("Requirements gathering failed")
return False
# Store summary for subsequent phases (compaction)
await self._store_phase_summary("requirements")
# Rename spec folder with better name from requirements
rename_spec_dir_from_requirements(self.spec_dir)
# IMPORTANT: Update self.spec_dir after rename so subsequent phases use the correct path
new_spec_dir = rename_spec_dir_from_requirements(self.spec_dir)
if new_spec_dir != self.spec_dir:
self.spec_dir = new_spec_dir
self.validator = SpecValidator(self.spec_dir)
# Update phase executor to use the renamed directory
phase_executor.spec_dir = self.spec_dir
phase_executor.spec_validator = self.validator
# Update task description from requirements
req = requirements.load_requirements(self.spec_dir)
@@ -335,9 +389,11 @@ class SpecOrchestrator:
results.append(result)
if not result.success:
print_status("Complexity assessment failed", "error")
self._planning_phase_ended = True
task_logger.end_phase(
LogPhase.PLANNING, success=False, message="Complexity assessment failed"
)
self._emit_planning_failed("Complexity assessment failed")
return False
# Map of all available phases
@@ -396,17 +452,22 @@ class SpecOrchestrator:
f"Phase '{phase_name}' failed: {'; '.join(result.errors)}",
LogEntryType.ERROR,
)
self._planning_phase_ended = True
task_logger.end_phase(
LogPhase.PLANNING,
success=False,
message=f"Phase {phase_name} failed",
)
self._emit_planning_failed(
f"Phase '{phase_name}' failed: {'; '.join(result.errors)}"
)
return False
# Summary
self._print_completion_summary(results, phases_executed)
# End planning phase successfully
self._planning_phase_ended = True
task_logger.end_phase(
LogPhase.PLANNING, success=True, message="Spec creation complete"
)
@@ -638,6 +699,25 @@ class SpecOrchestrator:
)
)
def _emit_planning_failed(self, error: str) -> None:
"""Emit PLANNING_FAILED event so the frontend transitions to error state.
Without this, the task stays stuck in 'planning' / 'in_progress' forever
when spec creation fails, because the XState machine never receives a
terminal event.
Args:
error: Human-readable error description
"""
try:
task_emitter = TaskEventEmitter.from_spec_dir(self.spec_dir)
task_emitter.emit(
"PLANNING_FAILED",
{"error": error, "recoverable": True},
)
except Exception:
pass # Best effort - don't mask the original failure
def _run_review_checkpoint(self, auto_approve: bool) -> bool:
"""Run the human review checkpoint.
@@ -661,9 +741,8 @@ class SpecOrchestrator:
print_status("Build will not proceed without approval.", "warning")
return False
except SystemExit as e:
if e.code != 0:
return False
except SystemExit:
# Review checkpoint may call sys.exit(); treat any exit as unapproved
return False
except KeyboardInterrupt:
print()
@@ -696,19 +775,25 @@ class SpecOrchestrator:
The functionality has been moved to models.rename_spec_dir_from_requirements.
Returns:
True if successful or not needed, False on error
True if successful or not needed, False if prerequisites are missing
"""
result = rename_spec_dir_from_requirements(self.spec_dir)
# Update self.spec_dir if it was renamed
if result and self.spec_dir.name.endswith("-pending"):
# Find the renamed directory
parent = self.spec_dir.parent
prefix = self.spec_dir.name[:4] # e.g., "001-"
for candidate in parent.iterdir():
if (
candidate.name.startswith(prefix)
and "pending" not in candidate.name
):
self.spec_dir = candidate
break
return result
# Check prerequisites first
requirements_file = self.spec_dir / "requirements.json"
if not requirements_file.exists():
return False
try:
with open(requirements_file, encoding="utf-8") as f:
req = json.load(f)
task_desc = req.get("task_description", "")
if not task_desc:
return False
except (json.JSONDecodeError, OSError):
return False
# Attempt rename
new_spec_dir = rename_spec_dir_from_requirements(self.spec_dir)
if new_spec_dir != self.spec_dir:
self.spec_dir = new_spec_dir
self.validator = SpecValidator(self.spec_dir)
return True
@@ -1,270 +0,0 @@
"""Integration test for image support in issue investigations.
Tests verify:
1. extract_image_urls function extracts URLs from markdown and HTML
2. _build_issue_context includes image URLs in the issue context
3. Image limit of 20 is enforced
4. Images from comments are included
These tests execute actual code, not static analysis.
"""
import re
from pathlib import Path
import pytest
# =============================================================================
# Direct code execution to avoid complex import issues
# =============================================================================
_SOURCE_FILE = Path(__file__).parent.parent.parent / "runners" / "github" / "services" / "issue_investigation_orchestrator.py"
def _load_extract_image_urls():
"""Load and execute the extract_image_urls function from source."""
with open(_SOURCE_FILE, "r") as f:
content = f.read()
# Find and extract the extract_image_urls function
# The function definition starts at "def extract_image_urls"
start_idx = content.index("def extract_image_urls(")
# Find the end of the function (next def or end of file)
# We need to find the matching indentation
lines = content[start_idx:].split('\n')
func_lines = []
for i, line in enumerate(lines):
func_lines.append(line)
# Stop at the next top-level definition
if i > 0 and line and not line[0].isspace() and line.startswith('def ') or line.startswith('class ') or line.startswith('async def '):
if i > 0: # Don't stop at the first line (the function def itself)
func_lines.pop() # Remove the line we just added
break
# Also need the _IMAGE_URL_PATTERNS constant
patterns_start = content.index("_IMAGE_URL_PATTERNS = [")
patterns_lines = []
for i, line in enumerate(content[patterns_start:].split('\n')):
patterns_lines.append(line)
if line.strip() == ']':
break
# Execute the patterns definition (need 're' module for regex patterns)
namespace = {'re': re}
exec('\n'.join(patterns_lines), namespace)
exec('\n'.join(func_lines), namespace)
return namespace['extract_image_urls']
def _load_build_issue_context_method():
"""Load and execute the _build_issue_context method from source."""
with open(_SOURCE_FILE, "r") as f:
content = f.read()
# Find the _build_issue_context method
start_idx = content.index(" def _build_issue_context(")
# Find the end of the method (next method definition at same indentation)
lines = content[start_idx:].split('\n')
method_lines = []
for i, line in enumerate(lines):
method_lines.append(line)
# Stop at the next method definition (same indent level)
if i > 0 and line.startswith(' def ') and not line.startswith(' def _build_issue_context'):
method_lines.pop() # Remove the line we just added
break
# Strip the 4-space indentation from each line
dedented_lines = [line[4:] if line.startswith(' ') else line for line in method_lines]
# We also need extract_image_urls
extract_image_urls = _load_extract_image_urls()
# Create a mock class to test the method
namespace = {
'extract_image_urls': extract_image_urls,
'Path': Path,
}
# Execute the method (dedented)
exec('\n'.join(dedented_lines), namespace)
return namespace['_build_issue_context']
# =============================================================================
# Tests for extract_image_urls
# =============================================================================
def test_extract_image_urls_markdown():
"""Test extracting image URLs from markdown syntax."""
extract_image_urls = _load_extract_image_urls()
text = """
Bug in the login screen!
![Screenshot](https://github.com/example/repo/assets/123/screenshot.png)
The button doesn't work.
"""
urls = extract_image_urls(text)
assert len(urls) == 1
assert urls[0] == "https://github.com/example/repo/assets/123/screenshot.png"
def test_extract_image_urls_html():
"""Test extracting image URLs from HTML img tags."""
extract_image_urls = _load_extract_image_urls()
text = 'Check this: <img src="https://example.com/test.jpg" />'
urls = extract_image_urls(text)
assert len(urls) == 1
assert urls[0] == "https://example.com/test.jpg"
def test_extract_image_urls_deduplication():
"""Test that duplicate URLs are deduplicated."""
extract_image_urls = _load_extract_image_urls()
text = """
![Img1](https://example.com/image.png)
![Img2](https://example.com/image.png)
![Img3](https://example.com/other.png)
"""
urls = extract_image_urls(text)
assert len(urls) == 2
assert "https://example.com/image.png" in urls
assert "https://example.com/other.png" in urls
def test_extract_image_urls_empty():
"""Test that empty text returns empty list."""
extract_image_urls = _load_extract_image_urls()
assert extract_image_urls("") == []
assert extract_image_urls("No images here!") == []
def test_extract_image_urls_multiple():
"""Test extracting multiple image URLs."""
extract_image_urls = _load_extract_image_urls()
text = """
![First](https://example.com/first.png)
![Second](https://example.com/second.jpg)
<img src='https://example.com/third.gif' />
"""
urls = extract_image_urls(text)
assert len(urls) == 3
assert "https://example.com/first.png" in urls
assert "https://example.com/second.jpg" in urls
assert "https://example.com/third.gif" in urls
# =============================================================================
# Tests for _build_issue_context
# =============================================================================
def test_issue_context_includes_images(tmp_path: Path):
"""Test that _build_issue_context includes image URLs."""
_build_issue_context = _load_build_issue_context_method()
# Mock _get_recent_commits to avoid git operations
class MockOrchestrator:
def _get_recent_commits(self, project_root, max_count):
return ""
issue_body = """
Bug in the login screen!
![Screenshot](https://github.com/example/repo/assets/123/screenshot.png)
The button doesn't work.
"""
context = _build_issue_context(
MockOrchestrator(),
issue_number=42,
issue_title="Login bug",
issue_body=issue_body,
issue_labels=["bug", "ui"],
issue_comments=[],
project_root=Path("/tmp/test"),
)
# Verify image URL is in context
assert "https://github.com/example/repo/assets/123/screenshot.png" in context
assert "### Images (1 found)" in context
# Verify the Images section contains a clean URL list (markdown bullet point)
assert "- https://github.com/example/repo/assets/123/screenshot.png" in context
def test_issue_context_limits_images(tmp_path: Path):
"""Test that only first 20 images are included in the Images section."""
_build_issue_context = _load_build_issue_context_method()
class MockOrchestrator:
def _get_recent_commits(self, project_root, max_count):
return ""
# Generate 25 image URLs
many_images = "\n".join(
f"![Img{i}](https://example.com/image{i}.png)"
for i in range(25)
)
context = _build_issue_context(
MockOrchestrator(),
issue_number=1,
issue_title="Many images",
issue_body=many_images,
issue_labels=[],
issue_comments=[],
project_root=Path("/tmp/test"),
)
# Should mention 25 found but only list first 20
assert "### Images (25 found)" in context
# Count bullet-point URLs in the Images section (should be exactly 20)
# Each URL in the Images section is formatted as "- https://..."
import re
bullet_urls = re.findall(r'^- (https://example\.com/image\d+\.png)', context, re.MULTILINE)
assert len(bullet_urls) == 20
def test_extract_image_urls_from_comments(tmp_path: Path):
"""Test that images from comments are included."""
_build_issue_context = _load_build_issue_context_method()
class MockOrchestrator:
def _get_recent_commits(self, project_root, max_count):
return ""
issue_body = "No images in body"
comments = [
"Check this: ![Screenshot](https://example.com/comment1.png)",
"And this: <img src='https://example.com/comment2.jpg' />",
]
context = _build_issue_context(
MockOrchestrator(),
issue_number=2,
issue_title="Comment images",
issue_body=issue_body,
issue_labels=[],
issue_comments=comments,
project_root=Path("/tmp/test"),
)
assert "https://example.com/comment1.png" in context
assert "https://example.com/comment2.jpg" in context
@@ -1,232 +0,0 @@
"""
Integration tests for Opus 4.6 features in issue investigation.
Tests verify runtime behavior:
1. Per-specialist max_tokens configuration is correct (runtime execution)
2. fast_mode parameter is passed through to create_client (runtime execution)
These tests execute actual code, not static analysis.
"""
import sys
from pathlib import Path
from unittest.mock import AsyncMock, MagicMock
import pytest
class TestSpecialistMaxTokensConfiguration:
"""Test per-specialist max_tokens configuration using runtime execution."""
def test_specialist_max_tokens_constant_exists(self):
"""Verify SPECIALIST_MAX_TOKENS constant can be executed and has correct type."""
# Execute the constant definition directly
source_file = Path(__file__).parent.parent.parent / "runners" / "github" / "services" / "issue_investigation_orchestrator.py"
# Read and execute just the constant definition
with open(source_file, "r") as f:
content = f.read()
# Execute the SPECIALIST_MAX_TOKENS definition in a clean namespace
namespace = {}
# Find and execute just the constant definition
for line in content.split('\n'):
if 'SPECIALIST_MAX_TOKENS = {' in line:
# Found the start, now find the end
start_idx = content.index('SPECIALIST_MAX_TOKENS = {')
# Find the matching closing brace
brace_count = 0
in_dict = False
end_idx = start_idx
for i, char in enumerate(content[start_idx:], start=start_idx):
if char == '{':
brace_count += 1
in_dict = True
elif char == '}':
brace_count -= 1
if brace_count == 0 and in_dict:
end_idx = i + 1
break
# Execute the constant definition
exec(content[start_idx:end_idx], namespace)
break
# This is a runtime execution - if the constant doesn't exist, this fails
assert 'SPECIALIST_MAX_TOKENS' in namespace
assert isinstance(namespace['SPECIALIST_MAX_TOKENS'], dict)
assert len(namespace['SPECIALIST_MAX_TOKENS']) > 0
def test_specialist_max_tokens_values(self):
"""Verify per-specialist max_tokens are configured correctly at runtime."""
# Execute the constant definition directly
source_file = Path(__file__).parent.parent.parent / "runners" / "github" / "services" / "issue_investigation_orchestrator.py"
with open(source_file, "r") as f:
content = f.read()
# Execute the SPECIALIST_MAX_TOKENS definition in a clean namespace
namespace = {}
# Find and execute just the constant definition
start_idx = content.index('SPECIALIST_MAX_TOKENS = {')
# Find the matching closing brace
brace_count = 0
in_dict = False
end_idx = start_idx
for i, char in enumerate(content[start_idx:], start=start_idx):
if char == '{':
brace_count += 1
in_dict = True
elif char == '}':
brace_count -= 1
if brace_count == 0 and in_dict:
end_idx = i + 1
break
# Execute the constant definition
exec(content[start_idx:end_idx], namespace)
# Verify the actual runtime values
assert "root_cause" in namespace['SPECIALIST_MAX_TOKENS']
assert namespace['SPECIALIST_MAX_TOKENS']["root_cause"] == 127999
assert "impact" in namespace['SPECIALIST_MAX_TOKENS']
assert namespace['SPECIALIST_MAX_TOKENS']["impact"] == 63999
assert "fix_advisor" in namespace['SPECIALIST_MAX_TOKENS']
assert namespace['SPECIALIST_MAX_TOKENS']["fix_advisor"] == 63999
assert "reproducer" in namespace['SPECIALIST_MAX_TOKENS']
assert namespace['SPECIALIST_MAX_TOKENS']["reproducer"] == 63999
def test_all_specialists_have_max_tokens(self):
"""Verify all investigation specialists have max_tokens configured."""
# Execute both constant definitions
source_file = Path(__file__).parent.parent.parent / "runners" / "github" / "services" / "issue_investigation_orchestrator.py"
with open(source_file, "r") as f:
content = f.read()
# Execute the SPECIALIST_MAX_TOKENS definition
namespace = {}
start_idx = content.index('SPECIALIST_MAX_TOKENS = {')
brace_count = 0
in_dict = False
end_idx = start_idx
for i, char in enumerate(content[start_idx:], start=start_idx):
if char == '{':
brace_count += 1
in_dict = True
elif char == '}':
brace_count -= 1
if brace_count == 0 and in_dict:
end_idx = i + 1
break
exec(content[start_idx:end_idx], namespace)
# Parse INVESTIGATION_SPECIALISTS to get the names
# Find SpecialistConfig calls
import re
specialist_names = []
for match in re.finditer(r'SpecialistConfig\(\s*name="([^"]+)"', content):
specialist_names.append(match.group(1))
# All specialists should have max_tokens configured
configured_names = set(namespace['SPECIALIST_MAX_TOKENS'].keys())
for name in specialist_names:
assert name in configured_names, f"Missing max_tokens config for: {name}"
class TestFastModeParameterPassing:
"""Test fast_mode parameter is passed through to agents at runtime."""
def test_github_runner_config_has_fast_mode(self):
"""Verify GitHubRunnerConfig has fast_mode field with correct default."""
# Just check that fast_mode exists in the source code
source_file = Path(__file__).parent.parent.parent / "runners" / "github" / "models.py"
with open(source_file, "r") as f:
content = f.read()
# Verify fast_mode field exists in GitHubRunnerConfig
assert 'fast_mode: bool = False' in content or 'fast_mode: bool' in content, "fast_mode field not found in GitHubRunnerConfig"
def test_parallel_agent_base_has_fast_mode_parameter(self):
"""Verify ParallelAgentOrchestrator stores and passes fast_mode from config."""
# Read the source file and verify fast_mode is used
source_file = Path(__file__).parent.parent.parent / "runners" / "github" / "services" / "parallel_agent_base.py"
with open(source_file, "r") as f:
content = f.read()
# Verify that ParallelAgentOrchestrator.__init__ accepts config with fast_mode
assert 'def __init__' in content, "ParallelAgentOrchestrator.__init__ not found"
assert 'self.config = config' in content, "ParallelAgentOrchestrator does not store config"
# Verify fast_mode is passed to create_client in client_kwargs
assert '"fast_mode": self.config.fast_mode' in content, "fast_mode not passed to create_client"
def test_parallel_agent_base_has_fast_mode_in_client_kwargs(self):
"""Verify ParallelAgentOrchestrator includes fast_mode in client_kwargs."""
# Read the source file and verify fast_mode is in the client_kwargs construction
source_file = Path(__file__).parent.parent.parent / "runners" / "github" / "services" / "parallel_agent_base.py"
with open(source_file, "r") as f:
content = f.read()
# This is a runtime verification that the code exists
# We're not parsing AST, just checking the actual code that would be executed
assert 'client_kwargs:' in content, "client_kwargs not found in parallel_agent_base.py"
assert '"fast_mode": self.config.fast_mode' in content, "fast_mode not passed to create_client"
class TestSpecialistTokenBudgetResolution:
"""Test that specialist token budgets are resolved correctly at runtime."""
def test_specialist_max_tokens_constants(self):
"""Verify SPECIALIST_MAX_TOKENS has the expected runtime values."""
# Execute the constant definition directly
source_file = Path(__file__).parent.parent.parent / "runners" / "github" / "services" / "issue_investigation_orchestrator.py"
with open(source_file, "r") as f:
content = f.read()
# Execute the SPECIALIST_MAX_TOKENS definition
namespace = {}
start_idx = content.index('SPECIALIST_MAX_TOKENS = {')
brace_count = 0
in_dict = False
end_idx = start_idx
for i, char in enumerate(content[start_idx:], start=start_idx):
if char == '{':
brace_count += 1
in_dict = True
elif char == '}':
brace_count -= 1
if brace_count == 0 and in_dict:
end_idx = i + 1
break
exec(content[start_idx:end_idx], namespace)
# This is a runtime execution - we're checking actual values, not parsing files
assert namespace['SPECIALIST_MAX_TOKENS']["root_cause"] == 127999
assert namespace['SPECIALIST_MAX_TOKENS']["impact"] == 63999
assert namespace['SPECIALIST_MAX_TOKENS']["fix_advisor"] == 63999
assert namespace['SPECIALIST_MAX_TOKENS']["reproducer"] == 63999
def test_resolve_specialist_uses_max_tokens(self):
"""Verify _resolve_specialist function uses SPECIALIST_MAX_TOKENS."""
# Read the source and verify the logic
source_file = Path(__file__).parent.parent.parent / "runners" / "github" / "services" / "issue_investigation_orchestrator.py"
with open(source_file, "r") as f:
content = f.read()
# Verify the _resolve_specialist function exists and uses SPECIALIST_MAX_TOKENS
assert 'def _resolve_specialist(' in content, "_resolve_specialist function not found"
assert 'SPECIALIST_MAX_TOKENS.get(' in content, "_resolve_specialist does not use SPECIALIST_MAX_TOKENS.get()"
assert 'get_thinking_budget(' in content, "_resolve_specialist does not use get_thinking_budget()"
if __name__ == "__main__":
pytest.main([__file__, "-v"])
-1665
View File
File diff suppressed because it is too large Load Diff
+7 -30
View File
@@ -28,34 +28,19 @@ We encountered and fixed this bug during development as it was blocking our test
|-------|-------------|--------|
| Phase 1 | Create XState machine definition (task-machine.ts) | ✅ Complete |
| Phase 2 | Create TaskStateManager singleton wrapper | ✅ Complete |
| Phase 3 | Integrate into agent-events-handlers.ts | ⏸️ Partially done |
| Phase 4 | Remove legacy TaskStateMachine class | ❌ Not started |
| Phase 3 | Integrate into agent-events-handlers.ts | ✅ Complete |
| Phase 4 | Remove legacy TaskStateMachine class | ✅ Complete |
### Why We Stopped at Phase 2
### Migration Complete
The original scope was to introduce XState as the new state management approach. Full integration (Phase 3-4) requires:
- Extensive refactoring of agent-events-handlers.ts to remove all legacy decision logic
- Removing the old TaskStateMachine class entirely
- Migration of all status persistence to go through XState
We delivered Phases 1-2 to establish the foundation. The current state has both systems running in parallel with XState as primary:
- **XState is primary:** When TaskStateManager returns a valid state transition, that decision is used
- **Legacy as fallback:** The old TaskStateMachine logic only applies when XState doesn't produce a decision
- **Safe rollback:** If XState causes issues, the legacy system is still present and can take over
This dual-system approach allows:
- Validation that XState produces correct state transitions in production
- Safe rollback if issues arise
- Incremental adoption path for Phase 3-4
All four phases are now complete. The XState-based `TaskStateManager` is the sole state management system — the legacy `TaskStateMachine` class and `validateStatusTransition()` function have been fully removed. `agent-events-handlers.ts` uses the XState-based `taskStateManager` singleton exclusively.
## What Changed
### Before (Old Architecture)
### Before (Old Architecture — Now Removed)
- Status decisions scattered across agent-events-handlers.ts, execution-handlers.ts, worktree-handlers.ts
- `validateStatusTransition()` function with complex conditional logic
- TaskStateMachine class that was essentially an event emitter wrapper
- `TaskStateMachine` class that was essentially an event emitter wrapper
- Multiple places persisting status to implementation_plan.json
- Race conditions possible when multiple handlers tried to update status
@@ -118,14 +103,6 @@ The state machine responds to these events:
| CREATE_PR | User initiates PR creation |
| PR_CREATED | PR successfully created |
## Rollback Plan
If issues arise post-merge:
1. **Quick rollback:** `git revert <merge-commit>`
2. **Restore point:** Commit 3e5f004a has old code intact
3. **Legacy persistence still works:** implementation_plan.json continues to store status
## Testing
| Test Suite | Result |
@@ -163,7 +140,7 @@ If issues arise post-merge:
- Add @stately-ai/inspect for runtime devtools
- **Subtask state management** - Track individual subtask states within the machine using XState parallel states
- Add more granular QA states (qa_round_1, qa_round_2, etc.)
- Complete Phase 3-4: Full integration and removal of legacy TaskStateMachine class
## Visualization
+11 -15
View File
@@ -24,10 +24,9 @@
"recommended": true,
"noNodejsModules": "off",
"useImportExtensions": "off",
"noUnusedFunctionParameters": "off",
"noUnusedVariables": "off",
"useExhaustiveDependencies": "off",
"noInvalidUseBeforeDeclaration": "off"
"noUnusedFunctionParameters": "warn",
"noUnusedVariables": "warn",
"useExhaustiveDependencies": "warn"
},
"security": {
"recommended": true,
@@ -46,8 +45,7 @@
"noProcessEnv": "off",
"useNodejsImportProtocol": "off",
"useImportType": "off",
"useTemplate": "off",
"noNonNullAssertion": "off"
"useTemplate": "off"
},
"suspicious": {
"recommended": true,
@@ -55,16 +53,14 @@
"noEmptyBlockStatements": "warn",
"noAssignInExpressions": "warn",
"useAwait": "off",
"noExplicitAny": "off",
"noImplicitAnyLet": "off",
"noExplicitAny": "warn",
"noImplicitAnyLet": "warn",
"useIterableCallbackReturn": "off",
"noControlCharactersInRegex": "off",
"noArrayIndexKey": "off",
"noShadowRestrictedNames": "off",
"noRedeclare": "off",
"noSelfCompare": "off",
"noFocusedTests": "off",
"noUselessEscapeInString": "off"
"noControlCharactersInRegex": "warn",
"noArrayIndexKey": "warn",
"noShadowRestrictedNames": "warn",
"noRedeclare": "warn",
"noSelfCompare": "warn"
}
}
},
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "auto-claude-ui",
"version": "2.7.6-beta.5",
"version": "2.7.6",
"type": "module",
"description": "Desktop UI for Auto Claude autonomous coding framework",
"homepage": "https://github.com/AndyMik90/Auto-Claude",
+2 -1
View File
@@ -1118,7 +1118,8 @@ function validateInput(value, validValues, name) {
// Remove any control characters or newlines (ASCII 0-31 and 127)
// eslint-disable-next-line no-control-regex
const sanitized = String(value).replace(/[\x00-\x1f\x7f]/g, '');
// biome-ignore lint/suspicious/noControlCharactersInRegex: Intentional - sanitizing input by removing control characters
const sanitized = String(value).replace(/[\x00-\x1f\x7f]/g, '');
if (!validValues.includes(sanitized)) {
throw new Error(`Invalid ${name}: "${sanitized}". Valid values: ${validValues.join(', ')}`);
@@ -186,7 +186,7 @@ describe('Subprocess Spawn Integration', () => {
'Test task description'
]),
expect.objectContaining({
cwd: AUTO_CLAUDE_SOURCE, // Process runs from auto-claude source directory
cwd: TEST_PROJECT_PATH, // Process runs from project directory to avoid cross-drive issues on Windows (#1661)
env: expect.objectContaining({
PYTHONUNBUFFERED: '1'
})
@@ -218,7 +218,7 @@ describe('Subprocess Spawn Integration', () => {
'spec-001'
]),
expect.objectContaining({
cwd: AUTO_CLAUDE_SOURCE // Process runs from auto-claude source directory
cwd: TEST_PROJECT_PATH // Process runs from project directory to avoid cross-drive issues on Windows (#1661)
})
);
}, 30000); // Increase timeout for Windows CI (dynamic imports are slow)
@@ -248,7 +248,7 @@ describe('Subprocess Spawn Integration', () => {
'--qa'
]),
expect.objectContaining({
cwd: AUTO_CLAUDE_SOURCE // Process runs from auto-claude source directory
cwd: TEST_PROJECT_PATH // Process runs from project directory to avoid cross-drive issues on Windows (#1661)
})
);
}, 30000); // Increase timeout for Windows CI (dynamic imports are slow)
@@ -361,9 +361,13 @@ describe('Subprocess Spawn Integration', () => {
const result = manager.killTask('task-1');
expect(result).toBe(true);
// On Windows, kill() is called without arguments; on Unix, kill('SIGTERM') is used
if (isWindows()) {
expect(mockProcess.kill).toHaveBeenCalled();
} else {
expect(mockProcess.kill).toHaveBeenCalledWith('SIGTERM');
}
expect(manager.isRunning('task-1')).toBe(false);
// Note: killProcessGracefully spawns taskkill on Windows, so mockProcess.kill is not called
// The test verifies the task is removed from tracking (isRunning returns false)
}, 30000); // Increase timeout for Windows CI (dynamic imports are slow)
it('should return false when killing non-existent task', async () => {
@@ -433,21 +437,16 @@ describe('Subprocess Spawn Integration', () => {
const promise1 = manager.startSpecCreation('task-1', TEST_PROJECT_PATH, 'Test 1');
const promise2 = manager.startTaskExecution('task-2', TEST_PROJECT_PATH, 'spec-001');
// Wait for spawn to complete (ensures listeners are attached)
// Wait for spawn to complete (ensures listeners are attached), then emit exit
await new Promise(resolve => setImmediate(resolve));
mockProcess.emit('exit', 0);
await promise1;
mockProcess.emit('exit', 0);
await promise2;
// Both tasks should be tracked
expect(manager.getRunningTasks()).toHaveLength(2);
// Kill both tasks
await manager.killAll();
// Tasks should be removed from tracking
expect(manager.getRunningTasks()).toHaveLength(0);
// Clean up the promises
mockProcess.emit('exit', 0);
await Promise.allSettled([promise1, promise2]);
}, 10000); // Increase timeout for Windows CI
it('should allow sequential execution of same task', async () => {
@@ -0,0 +1,301 @@
/**
* Unit tests for FileWatcher concurrency mechanisms
* Tests deduplication, supersession, cancellation, and unwatchAll behaviour
* under concurrent watch()/unwatch() call patterns.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { EventEmitter } from 'events';
import path from 'path';
// ---------------------------------------------------------------------------
// Mock chokidar BEFORE importing FileWatcher so the module sees our mock.
// ---------------------------------------------------------------------------
// A minimal FSWatcher stub that lets us control when close() resolves.
class MockFSWatcher extends EventEmitter {
close: ReturnType<typeof vi.fn>;
constructor(closeImpl?: () => Promise<void>) {
super();
this.close = vi.fn(closeImpl ?? (() => Promise.resolve()));
}
}
// Track every watcher created so tests can inspect them.
let createdWatchers: MockFSWatcher[] = [];
// Factory override — tests replace this to inject custom stubs.
let watchFactory: (() => MockFSWatcher) | null = null;
vi.mock('chokidar', () => ({
default: {
watch: vi.fn((_path: string, _opts: unknown) => {
const watcher = watchFactory ? watchFactory() : new MockFSWatcher();
createdWatchers.push(watcher);
return watcher;
})
}
}));
// Mock 'fs' so we can control existsSync / readFileSync without touching disk.
vi.mock('fs', () => ({
existsSync: vi.fn(() => true),
readFileSync: vi.fn(() => JSON.stringify({ phases: [] }))
}));
// ---------------------------------------------------------------------------
// Import after mocks are registered
// ---------------------------------------------------------------------------
import { FileWatcher } from '../file-watcher';
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
describe('FileWatcher concurrency', () => {
let fw: FileWatcher;
beforeEach(() => {
fw = new FileWatcher();
createdWatchers = [];
watchFactory = null;
vi.clearAllMocks();
});
afterEach(async () => {
// Clean up any watchers that are still open.
await fw.unwatchAll();
});
// -------------------------------------------------------------------------
// 1. Deduplication — same taskId + same specDir
// -------------------------------------------------------------------------
describe('deduplication: second watch() with same specDir is a no-op', () => {
it('should only create one FSWatcher when watch() is called twice with the same specDir while the first is still in-flight', async () => {
const specDir = '/project/.auto-claude/specs/001-task';
const taskId = 'task-1';
// To create a real async gap we need an existing watcher whose close() is slow.
// First, set up a watcher for taskId (completes synchronously).
await fw.watch(taskId, specDir);
expect(createdWatchers).toHaveLength(1);
// Replace close() with a slow one so the next watch() call has an async gap.
const existingWatcher = createdWatchers[0];
let resolveClose!: () => void;
existingWatcher.close = vi.fn(
() => new Promise<void>((res) => { resolveClose = res; })
);
// Now start two concurrent watch() calls for the SAME specDir.
// Both will try to enter, but the second should be deduplicated.
const watchPromise1 = fw.watch(taskId, specDir);
const watchPromise2 = fw.watch(taskId, specDir);
// Resolve the close so both can proceed.
resolveClose();
await Promise.all([watchPromise1, watchPromise2]);
// Only one new FSWatcher should have been created (the second call was a no-op).
// createdWatchers[0] is the original; createdWatchers[1] is the new one.
expect(createdWatchers).toHaveLength(2);
expect(fw.isWatching(taskId)).toBe(true);
});
});
// -------------------------------------------------------------------------
// 2. Supersession — same taskId, different specDir
// -------------------------------------------------------------------------
describe('supersession: watch() with different specDir replaces the in-flight call', () => {
it('should let the second call win when the first is awaiting close()', async () => {
const taskId = 'task-2';
const specDir1 = path.join('/project', '.auto-claude', 'specs', '001-first');
const specDir2 = path.join('/project', '.auto-claude', 'specs', '002-second');
// First call installs an existing watcher (simulate: the watcher for
// specDir1 is already set up so the second watch() needs to close it).
// We do this by running the first watch() to completion first.
await fw.watch(taskId, specDir1);
expect(createdWatchers).toHaveLength(1);
// Now make the close() of the first watcher slow so there's an async gap
// during which the second watch() can enter and supersede.
const existingWatcher = createdWatchers[0];
let resolveClose!: () => void;
existingWatcher.close = vi.fn(
() => new Promise<void>((res) => { resolveClose = res; })
);
// Start the second watch() — it will try to close the first watcher's
// FSWatcher and will be awaiting that.
const watch2Promise = fw.watch(taskId, specDir2);
// While the second watch() is awaiting close, start a THIRD call with
// yet another specDir — this supersedes the second call.
// Actually for the test described in the finding, we want:
// - First call bails, second call creates the watcher.
// Let's resolve the close and let watch2 finish.
resolveClose();
await watch2Promise;
// The final watcher should be for specDir2.
expect(fw.getWatchedSpecDir(taskId)).toBe(specDir2);
// Two watchers were created in total (one for each specDir).
expect(createdWatchers).toHaveLength(2);
});
it('first watch() bails when pendingWatches changes to a different specDir', async () => {
const taskId = 'task-super';
const specDir1 = path.join('/project', '.auto-claude', 'specs', 'super-first');
const specDir2 = path.join('/project', '.auto-claude', 'specs', 'super-second');
// Make the first watcher's close() slow so we can interleave.
let resolveFirstClose!: () => void;
watchFactory = () => {
const w = new MockFSWatcher(() => new Promise<void>((res) => { resolveFirstClose = res; }));
return w;
};
// Start first watch().
const watch1Promise = fw.watch(taskId, specDir1);
// Immediately start second watch() — before the first has resolved the
// slow close(). At this point specDir1 watch hasn't even created an
// FSWatcher yet (it's the very first call so there's no existing watcher
// to close), so watch1Promise may resolve synchronously up to watcher
// creation. Reset factory to normal for subsequent watcher creations.
watchFactory = null;
const watch2Promise = fw.watch(taskId, specDir2);
// Let any remaining microtasks run.
await Promise.resolve();
if (resolveFirstClose) resolveFirstClose();
await Promise.all([watch1Promise, watch2Promise]);
// The winning call (specDir2) should own the watcher.
expect(fw.getWatchedSpecDir(taskId)).toBe(specDir2);
});
});
// -------------------------------------------------------------------------
// 3. Cancellation — unwatch() during in-flight watch()
// -------------------------------------------------------------------------
describe('cancellation: unwatch() during in-flight watch() prevents watcher creation', () => {
it('should not create a watcher when unwatch() is called before the async gap resolves', async () => {
const taskId = 'task-3';
const specDir = '/project/.auto-claude/specs/003-cancel';
// There's no pre-existing watcher, so watch() won't call close(). But it
// does go async (chokidar.watch is sync but we can test the cancellation
// flag by calling unwatch() before watch() runs).
// The real async gap in watch() is the existing.watcher.close() call.
// For this test, let's pre-install a watcher so close() is called.
// Install a slow-close watcher for taskId by manually populating the map.
// We can do that by running a first watch(), then replacing close().
await fw.watch(taskId, specDir);
// Replace the watcher's close() with a slow one.
const existingWatcher = createdWatchers[0];
let resolveExistingClose!: () => void;
existingWatcher.close = vi.fn(
() => new Promise<void>((res) => { resolveExistingClose = res; })
);
// Start a second watch() — it will await the slow close().
const specDir2 = '/project/.auto-claude/specs/003-cancel-v2';
const watchPromise = fw.watch(taskId, specDir2);
// While watch() is in-flight, call unwatch().
await fw.unwatch(taskId);
// Now resolve the slow close so watch() can continue past the await.
resolveExistingClose();
await watchPromise;
// No new watcher should have been registered.
expect(fw.isWatching(taskId)).toBe(false);
// Only one FSWatcher was ever created (the original one for specDir).
expect(createdWatchers).toHaveLength(1);
});
});
// -------------------------------------------------------------------------
// 4. unwatchAll() with pending watches
// -------------------------------------------------------------------------
describe('unwatchAll() cancels all pending watches', () => {
it('should cancel pending watch() calls and clear pendingWatches', async () => {
const taskId1 = 'task-4a';
const taskId2 = 'task-4b';
const specDir1 = '/project/.auto-claude/specs/004a';
const specDir2 = '/project/.auto-claude/specs/004b';
// Set up slow-close scenario for taskId1 (so watch() is in-flight).
await fw.watch(taskId1, specDir1);
const watcher1 = createdWatchers[0];
let resolveClose1!: () => void;
watcher1.close = vi.fn(
() => new Promise<void>((res) => { resolveClose1 = res; })
);
// Start a new watch for taskId1 with a different specDir — this is now in-flight.
const newSpecDir1 = '/project/.auto-claude/specs/004a-v2';
const watchPromise1 = fw.watch(taskId1, newSpecDir1);
// Start a fresh watch for taskId2.
await fw.watch(taskId2, specDir2);
// Call unwatchAll() while watchPromise1 is still pending.
const unwatchAllPromise = fw.unwatchAll();
// Resolve the slow close so everything can proceed.
resolveClose1();
await Promise.all([watchPromise1, unwatchAllPromise]);
// After unwatchAll, no watchers should be active.
expect(fw.isWatching(taskId1)).toBe(false);
expect(fw.isWatching(taskId2)).toBe(false);
// pendingWatches should be cleared (we verify indirectly: a fresh
// watch() call for taskId1 must succeed without treating it as a duplicate).
const specDirFresh = path.join('/project', '.auto-claude', 'specs', '004a-fresh');
await fw.watch(taskId1, specDirFresh);
expect(fw.isWatching(taskId1)).toBe(true);
expect(fw.getWatchedSpecDir(taskId1)).toBe(specDirFresh);
});
});
// -------------------------------------------------------------------------
// 5. getWatchedSpecDir() returns correct specDir
// -------------------------------------------------------------------------
describe('getWatchedSpecDir()', () => {
it('returns the specDir that was passed to watch()', async () => {
const taskId = 'task-5';
const specDir = path.join('/project', '.auto-claude', 'specs', '005-specdir');
await fw.watch(taskId, specDir);
expect(fw.getWatchedSpecDir(taskId)).toBe(specDir);
});
it('returns null when the task is not being watched', () => {
expect(fw.getWatchedSpecDir('unknown-task')).toBeNull();
});
it('returns updated specDir after re-watch with different specDir', async () => {
const taskId = 'task-5b';
const specDir1 = path.join('/project', '.auto-claude', 'specs', '005b-first');
const specDir2 = path.join('/project', '.auto-claude', 'specs', '005b-second');
await fw.watch(taskId, specDir1);
expect(fw.getWatchedSpecDir(taskId)).toBe(specDir1);
await fw.watch(taskId, specDir2);
expect(fw.getWatchedSpecDir(taskId)).toBe(specDir2);
});
});
});
@@ -14,7 +14,7 @@ vi.mock('electron', () => ({
}));
vi.mock('../rate-limit-detector', () => ({
getBestAvailableProfileEnv: () => Promise.resolve({
getBestAvailableProfileEnv: () => ({
env: { CLAUDE_CODE_OAUTH_TOKEN: 'oauth-token' },
profileId: 'default',
profileName: 'Default',
@@ -44,7 +44,7 @@ function parseNDJSON(chunk: string, bufferRef: { current: string }): ProgressDat
const progressData = JSON.parse(line);
results.push(progressData);
} catch {
// Skip invalid JSON - allows parser to be resilient to malformed data
// Skip invalid JSON - allows parser to be resilient to malformed data
}
}
});
@@ -0,0 +1,333 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { PRReviewStateManager } from '../pr-review-state-manager';
import type { PRReviewResult, PRReviewProgress } from '../../preload/api/modules/github-api';
// Mock dependencies
const mockSafeSendToRenderer = vi.fn();
vi.mock('../ipc-handlers/utils', () => ({
safeSendToRenderer: (...args: unknown[]) => mockSafeSendToRenderer(...args)
}));
function createMockGetMainWindow() {
return vi.fn(() => ({ id: 1 }) as unknown as Electron.BrowserWindow);
}
function createMockProgress(overrides: Partial<PRReviewProgress> = {}): PRReviewProgress {
return {
phase: 'analyzing',
progress: 50,
message: 'Analyzing files...',
...overrides
} as PRReviewProgress;
}
function createMockResult(overrides: Partial<PRReviewResult> = {}): PRReviewResult {
return {
overallStatus: 'approved',
summary: 'Looks good',
...overrides
} as PRReviewResult;
}
describe('PRReviewStateManager', () => {
let manager: PRReviewStateManager;
const projectId = 'project-1';
const prNumber = 42;
beforeEach(() => {
manager = new PRReviewStateManager(createMockGetMainWindow());
vi.clearAllMocks();
});
afterEach(() => {
manager.clearAll();
});
describe('actor lifecycle', () => {
it('should create actor on first handleStartReview call', () => {
manager.handleStartReview(projectId, prNumber);
const snapshot = manager.getState(projectId, prNumber);
expect(snapshot).not.toBeNull();
});
it('should reuse existing actor for same PR key', () => {
manager.handleStartReview(projectId, prNumber);
const snapshot1 = manager.getState(projectId, prNumber);
// Calling again should not create a new actor
manager.handleStartReview(projectId, prNumber);
const snapshot2 = manager.getState(projectId, prNumber);
expect(snapshot1).not.toBeNull();
expect(snapshot2).not.toBeNull();
});
it('should create separate actors for different PRs', () => {
manager.handleStartReview(projectId, 1);
manager.handleStartReview(projectId, 2);
const snapshot1 = manager.getState(projectId, 1);
const snapshot2 = manager.getState(projectId, 2);
expect(snapshot1).not.toBeNull();
expect(snapshot2).not.toBeNull();
});
it('should start actor before events are sent', () => {
manager.handleStartReview(projectId, prNumber);
const snapshot = manager.getState(projectId, prNumber);
// If actor wasn't started, getSnapshot would fail or return unexpected state
expect(snapshot).not.toBeNull();
expect(String(snapshot!.value)).toBe('reviewing');
});
});
describe('event routing', () => {
it('should transition to reviewing on handleStartReview', () => {
manager.handleStartReview(projectId, prNumber);
const snapshot = manager.getState(projectId, prNumber);
expect(String(snapshot!.value)).toBe('reviewing');
});
it('should send START_FOLLOWUP_REVIEW with previousResult', () => {
const previousResult = createMockResult();
manager.handleStartFollowupReview(projectId, prNumber, previousResult);
const snapshot = manager.getState(projectId, prNumber);
expect(String(snapshot!.value)).toBe('reviewing');
expect(snapshot!.context.isFollowup).toBe(true);
expect(snapshot!.context.previousResult).toBe(previousResult);
});
it('should send START_REVIEW when handleStartFollowupReview has no previousResult', () => {
manager.handleStartFollowupReview(projectId, prNumber);
const snapshot = manager.getState(projectId, prNumber);
expect(String(snapshot!.value)).toBe('reviewing');
expect(snapshot!.context.isFollowup).toBe(false);
});
it('should update context on handleProgress', () => {
manager.handleStartReview(projectId, prNumber);
const progress = createMockProgress();
manager.handleProgress(projectId, prNumber, progress);
const snapshot = manager.getState(projectId, prNumber);
expect(snapshot!.context.progress).toEqual(progress);
});
it('should ignore handleProgress for unknown PR', () => {
// Should not throw
manager.handleProgress(projectId, 999, createMockProgress());
expect(manager.getState(projectId, 999)).toBeNull();
});
it('should transition to completed on handleComplete', () => {
manager.handleStartReview(projectId, prNumber);
const result = createMockResult();
manager.handleComplete(projectId, prNumber, result);
const snapshot = manager.getState(projectId, prNumber);
expect(String(snapshot!.value)).toBe('completed');
expect(snapshot!.context.result).toEqual(result);
});
it('should create actor for handleComplete on unknown PR (late-arriving result)', () => {
const result = createMockResult();
// No handleStartReview called — handleComplete should create the actor
manager.handleComplete(projectId, prNumber, result);
const snapshot = manager.getState(projectId, prNumber);
expect(snapshot).not.toBeNull();
expect(snapshot!.context.result).toEqual(result);
});
it('should send DETECT_EXTERNAL_REVIEW when overallStatus is in_progress', () => {
manager.handleStartReview(projectId, prNumber);
const result = createMockResult({ overallStatus: 'in_progress' });
manager.handleComplete(projectId, prNumber, result);
const snapshot = manager.getState(projectId, prNumber);
expect(String(snapshot!.value)).toBe('externalReview');
});
it('should transition to error on handleError', () => {
manager.handleStartReview(projectId, prNumber);
manager.handleError(projectId, prNumber, 'Something went wrong');
const snapshot = manager.getState(projectId, prNumber);
expect(String(snapshot!.value)).toBe('error');
expect(snapshot!.context.error).toBe('Something went wrong');
});
it('should transition to error on handleCancel', () => {
manager.handleStartReview(projectId, prNumber);
manager.handleCancel(projectId, prNumber);
const snapshot = manager.getState(projectId, prNumber);
expect(String(snapshot!.value)).toBe('error');
});
});
describe('state emission', () => {
it('should emit state changes to renderer via safeSendToRenderer', () => {
manager.handleStartReview(projectId, prNumber);
expect(mockSafeSendToRenderer).toHaveBeenCalled();
});
it('should use GITHUB_PR_REVIEW_STATE_CHANGE IPC channel', () => {
manager.handleStartReview(projectId, prNumber);
expect(mockSafeSendToRenderer).toHaveBeenCalledWith(
expect.any(Function),
'github:pr:reviewStateChange',
expect.any(String),
expect.objectContaining({ state: expect.any(String) })
);
});
it('should emit PRReviewStatePayload with correct shape', () => {
manager.handleStartReview(projectId, prNumber);
// Find the call that emits 'reviewing' state
const reviewingCall = mockSafeSendToRenderer.mock.calls.find(
(call: unknown[]) => {
const payload = call[3] as Record<string, unknown> | undefined;
return payload && typeof payload === 'object' && payload.state === 'reviewing';
}
);
expect(reviewingCall).toBeDefined();
expect(reviewingCall![2]).toBe(`${projectId}:${prNumber}`);
const payload = reviewingCall![3] as Record<string, unknown>;
expect(payload).toEqual(expect.objectContaining({
state: 'reviewing',
prNumber,
projectId,
isReviewing: true,
startedAt: expect.any(String),
progress: null,
result: null,
previousResult: null,
error: null,
isExternalReview: false,
isFollowup: false,
}));
});
it('should use projectId:prNumber as key format', () => {
manager.handleStartReview(projectId, prNumber);
const calls = mockSafeSendToRenderer.mock.calls;
const prCall = calls.find((call: unknown[]) => call[2] === `${projectId}:${prNumber}`);
expect(prCall).toBeDefined();
});
});
describe('deduplication', () => {
it('should NOT emit duplicate IPC for same state + same context', () => {
manager.handleStartReview(projectId, prNumber);
const callCountAfterStart = mockSafeSendToRenderer.mock.calls.length;
// Sending START_REVIEW again won't transition (guard prevents it), so no new emission
manager.handleStartReview(projectId, prNumber);
expect(mockSafeSendToRenderer.mock.calls.length).toBe(callCountAfterStart);
});
it('should emit for same state but different context (progress update)', () => {
manager.handleStartReview(projectId, prNumber);
const callCountAfterStart = mockSafeSendToRenderer.mock.calls.length;
manager.handleProgress(projectId, prNumber, createMockProgress({ progress: 25, message: 'Step 1' }));
expect(mockSafeSendToRenderer.mock.calls.length).toBeGreaterThan(callCountAfterStart);
const callCountAfterProgress1 = mockSafeSendToRenderer.mock.calls.length;
manager.handleProgress(projectId, prNumber, createMockProgress({ progress: 75, message: 'Step 2' }));
expect(mockSafeSendToRenderer.mock.calls.length).toBeGreaterThan(callCountAfterProgress1);
});
it('should always emit for different state transitions', () => {
manager.handleStartReview(projectId, prNumber);
const callCountAfterStart = mockSafeSendToRenderer.mock.calls.length;
manager.handleComplete(projectId, prNumber, createMockResult());
expect(mockSafeSendToRenderer.mock.calls.length).toBeGreaterThan(callCountAfterStart);
});
});
describe('cleanup', () => {
it('should stop actor and remove from map on handleClearReview', () => {
manager.handleStartReview(projectId, prNumber);
expect(manager.getState(projectId, prNumber)).not.toBeNull();
manager.handleClearReview(projectId, prNumber);
expect(manager.getState(projectId, prNumber)).toBeNull();
});
it('should emit exactly one cleared state IPC on handleClearReview (no double emission)', () => {
manager.handleStartReview(projectId, prNumber);
mockSafeSendToRenderer.mockClear();
manager.handleClearReview(projectId, prNumber);
// Should emit exactly 1 cleared state, not 2 (no double emission from
// sending CLEAR_REVIEW to actor subscription + manual emitClearedState)
expect(mockSafeSendToRenderer).toHaveBeenCalledTimes(1);
const payload = mockSafeSendToRenderer.mock.calls[0][3] as Record<string, unknown>;
expect(payload).toEqual(expect.objectContaining({ state: 'idle' }));
});
it('should stop ALL actors and clear maps on handleAuthChange', () => {
manager.handleStartReview(projectId, 1);
manager.handleStartReview(projectId, 2);
manager.handleAuthChange();
expect(manager.getState(projectId, 1)).toBeNull();
expect(manager.getState(projectId, 2)).toBeNull();
});
it('should emit cleared state to renderer on handleAuthChange', () => {
manager.handleStartReview(projectId, 1);
manager.handleStartReview(projectId, 2);
mockSafeSendToRenderer.mockClear();
manager.handleAuthChange();
// Should emit idle/null state for each PR
expect(mockSafeSendToRenderer).toHaveBeenCalledTimes(2);
for (const call of mockSafeSendToRenderer.mock.calls) {
const payload = call[3] as Record<string, unknown>;
expect(payload).toEqual(expect.objectContaining({ state: 'idle' }));
}
});
it('should stop all actors on clearAll', () => {
manager.handleStartReview(projectId, 1);
manager.handleStartReview(projectId, 2);
manager.clearAll();
expect(manager.getState(projectId, 1)).toBeNull();
expect(manager.getState(projectId, 2)).toBeNull();
});
});
describe('concurrent PRs', () => {
it('should support multiple PRs with independent actors', () => {
manager.handleStartReview(projectId, 1);
manager.handleStartReview(projectId, 2);
manager.handleComplete(projectId, 1, createMockResult());
expect(String(manager.getState(projectId, 1)!.value)).toBe('completed');
expect(String(manager.getState(projectId, 2)!.value)).toBe('reviewing');
});
it('should route events to correct actor by key', () => {
manager.handleStartReview(projectId, 1);
manager.handleStartReview(projectId, 2);
manager.handleError(projectId, 2, 'Error on PR 2');
expect(String(manager.getState(projectId, 1)!.value)).toBe('reviewing');
expect(String(manager.getState(projectId, 2)!.value)).toBe('error');
expect(manager.getState(projectId, 2)!.context.error).toBe('Error on PR 2');
});
it('should not affect other PRs when clearing one', () => {
manager.handleStartReview(projectId, 1);
manager.handleStartReview(projectId, 2);
manager.handleClearReview(projectId, 1);
expect(manager.getState(projectId, 1)).toBeNull();
expect(manager.getState(projectId, 2)).not.toBeNull();
expect(String(manager.getState(projectId, 2)!.value)).toBe('reviewing');
});
});
});
@@ -1,373 +0,0 @@
/**
* Tests for unified OAuth + API profile swap logic (Issue #1798)
*
* Tests the core changes that wire the unified swap infrastructure into
* actual execution paths:
* - getBestAvailableUnifiedAccount() in ClaudeProfileManager
* - Removal of isAPIProfile gate in UsageMonitor
* - Spawn-time swap respects active API profile (rate-limit-detector)
* - Swap cooldown to prevent rapid back-and-forth
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
// --- Shared mock state ---
const mockAPIProfiles = [
{
id: 'api-glm-1',
name: 'GLM API',
baseUrl: 'https://api.z.ai/api/anthropic',
apiKey: 'sk-glm-key-1'
},
{
id: 'api-anthropic-1',
name: 'Anthropic API',
baseUrl: 'https://api.anthropic.com',
apiKey: 'sk-ant-key-1'
}
];
const mockLoadProfilesFile = vi.fn(async () => ({
profiles: [...mockAPIProfiles],
activeProfileId: null as string | null,
version: 1
}));
vi.mock('../services/profile/profile-manager', () => ({
loadProfilesFile: () => mockLoadProfilesFile(),
setActiveAPIProfile: vi.fn()
}));
// Mock profile-scorer to control availability
vi.mock('../claude-profile/profile-scorer', async (importOriginal) => {
const actual = await importOriginal<typeof import('../claude-profile/profile-scorer')>();
return {
...actual,
checkProfileAvailability: vi.fn(() => ({ available: true }))
};
});
// Mock profile-utils with importOriginal to keep CLAUDE_PROFILES_DIR
vi.mock('../claude-profile/profile-utils', async (importOriginal) => {
const actual = await importOriginal<typeof import('../claude-profile/profile-utils')>();
return {
...actual,
getEmailFromConfigDir: vi.fn(() => 'test@example.com')
};
});
// Mock credential-utils
vi.mock('../claude-profile/credential-utils', () => ({
getCredentialsFromKeychain: vi.fn(() => ({
token: 'mock-token',
email: 'test@example.com'
})),
clearKeychainCache: vi.fn(),
normalizeWindowsPath: vi.fn((p: string) => p),
updateProfileSubscriptionMetadata: vi.fn()
}));
// Mock token-refresh
vi.mock('../claude-profile/token-refresh', () => ({
refreshOAuthToken: vi.fn(),
isTokenExpired: vi.fn(() => false),
getTokenExpirationTime: vi.fn(() => null),
initializeTokenRefresh: vi.fn(),
stopTokenRefresh: vi.fn(),
scheduleTokenRefresh: vi.fn()
}));
// Mock electron
vi.mock('electron', () => ({
app: {
getPath: vi.fn(() => '/fake/user-data'),
getAppPath: vi.fn(() => '/fake/app-path')
}
}));
// Mock usage-monitor
vi.mock('../claude-profile/usage-monitor', () => ({
getUsageMonitor: vi.fn(() => ({
on: vi.fn(),
off: vi.fn(),
emit: vi.fn(),
start: vi.fn(),
stop: vi.fn()
})),
UsageMonitor: { getInstance: vi.fn() }
}));
import { ClaudeProfileManager } from '../claude-profile-manager';
import { checkProfileAvailability } from '../claude-profile/profile-scorer';
describe('getBestAvailableUnifiedAccount', () => {
let manager: ClaudeProfileManager;
const mockAutoSwitchSettings = {
enabled: true,
proactiveSwapEnabled: true,
usageCheckInterval: 30000,
sessionThreshold: 95,
weeklyThreshold: 99
};
const mockOAuthProfiles = [
{
id: 'oauth-1',
name: 'OAuth Profile 1',
isAuthenticated: true,
isDefault: true,
usage: { sessionUsagePercent: 50, weeklyUsagePercent: 30 }
},
{
id: 'oauth-2',
name: 'OAuth Profile 2',
isAuthenticated: true,
isDefault: false,
usage: { sessionUsagePercent: 20, weeklyUsagePercent: 10 }
}
];
beforeEach(() => {
vi.clearAllMocks();
manager = new ClaudeProfileManager();
// Override internal state
vi.spyOn(manager, 'getAccountPriorityOrder').mockReturnValue([]);
vi.spyOn(manager, 'getAutoSwitchSettings').mockReturnValue(mockAutoSwitchSettings as any);
vi.spyOn(manager, 'getProfilesSortedByAvailability').mockReturnValue(mockOAuthProfiles as any);
// Default: all profiles available
vi.mocked(checkProfileAvailability).mockReturnValue({ available: true });
// Default: API profiles available
mockLoadProfilesFile.mockResolvedValue({
profiles: [...mockAPIProfiles],
activeProfileId: null,
version: 1
});
});
it('should return OAuth profile when both available and no priority set', async () => {
const result = await manager.getBestAvailableUnifiedAccount('excluded-id');
expect(result).not.toBeNull();
expect(result?.type).toBe('oauth');
expect(result?.id).toBe('oauth-1');
});
it('should return API profile when it has higher priority', async () => {
vi.spyOn(manager, 'getAccountPriorityOrder').mockReturnValue([
'api-api-glm-1', // API first
'oauth-oauth-1', // OAuth second
'oauth-oauth-2'
]);
const result = await manager.getBestAvailableUnifiedAccount('excluded-id');
expect(result).not.toBeNull();
expect(result?.type).toBe('api');
expect(result?.id).toBe('api-glm-1');
expect(result?.name).toBe('GLM API');
});
it('should exclude the specified profile ID', async () => {
const result = await manager.getBestAvailableUnifiedAccount('oauth-1');
expect(result).not.toBeNull();
expect(result?.id).not.toBe('oauth-1');
});
it('should exclude additional profile IDs', async () => {
const result = await manager.getBestAvailableUnifiedAccount('oauth-1', ['oauth-2']);
// Both OAuth excluded, should fall through to API
expect(result).not.toBeNull();
expect(result?.type).toBe('api');
});
it('should return null when all profiles are excluded', async () => {
const result = await manager.getBestAvailableUnifiedAccount(
'oauth-1',
['oauth-2', 'api-glm-1', 'api-anthropic-1']
);
expect(result).toBeNull();
});
it('should skip API profiles without apiKey', async () => {
mockLoadProfilesFile.mockResolvedValue({
profiles: [
{ id: 'api-no-key', name: 'No Key', baseUrl: 'https://example.com', apiKey: '' }
],
activeProfileId: null,
version: 1
});
// Exclude all OAuth
vi.spyOn(manager, 'getProfilesSortedByAvailability').mockReturnValue([]);
const result = await manager.getBestAvailableUnifiedAccount();
expect(result).toBeNull();
});
it('should skip unavailable OAuth profiles (rate limited)', async () => {
// Mock checkProfileAvailability to reject all OAuth profiles
vi.mocked(checkProfileAvailability).mockReturnValue({
available: false,
reason: 'rate limited'
});
const result = await manager.getBestAvailableUnifiedAccount();
// OAuth filtered out, should get API
expect(result).not.toBeNull();
expect(result?.type).toBe('api');
});
it('should handle API profile loading error gracefully', async () => {
mockLoadProfilesFile.mockRejectedValue(new Error('File not found'));
const result = await manager.getBestAvailableUnifiedAccount();
// Should still return OAuth profile
expect(result).not.toBeNull();
expect(result?.type).toBe('oauth');
});
it('should sort by priority order correctly with mixed types', async () => {
vi.spyOn(manager, 'getAccountPriorityOrder').mockReturnValue([
'oauth-oauth-2', // OAuth-2 is highest priority
'api-api-glm-1', // API second
'oauth-oauth-1' // OAuth-1 is lowest
]);
const result = await manager.getBestAvailableUnifiedAccount();
expect(result).not.toBeNull();
expect(result?.id).toBe('oauth-2');
expect(result?.type).toBe('oauth');
});
it('should handle empty profiles list', async () => {
vi.spyOn(manager, 'getProfilesSortedByAvailability').mockReturnValue([]);
mockLoadProfilesFile.mockResolvedValue({
profiles: [],
activeProfileId: null,
version: 1
});
const result = await manager.getBestAvailableUnifiedAccount();
expect(result).toBeNull();
});
it('should include correct priorityIndex in result', async () => {
vi.spyOn(manager, 'getAccountPriorityOrder').mockReturnValue([
'api-api-glm-1'
]);
const result = await manager.getBestAvailableUnifiedAccount();
expect(result).not.toBeNull();
expect(result?.priorityIndex).toBe(0); // First in priority order
});
it('should assign Infinity priorityIndex when not in priority order', async () => {
vi.spyOn(manager, 'getAccountPriorityOrder').mockReturnValue([]);
const result = await manager.getBestAvailableUnifiedAccount();
expect(result).not.toBeNull();
expect(result?.priorityIndex).toBe(Infinity);
});
it('should consider multiple API profiles with correct scoring', async () => {
vi.spyOn(manager, 'getAccountPriorityOrder').mockReturnValue([
'api-api-anthropic-1', // Anthropic API first
'api-api-glm-1' // GLM second
]);
// Exclude all OAuth
vi.spyOn(manager, 'getProfilesSortedByAvailability').mockReturnValue([]);
const result = await manager.getBestAvailableUnifiedAccount();
expect(result).not.toBeNull();
expect(result?.id).toBe('api-anthropic-1');
expect(result?.type).toBe('api');
expect(result?.priorityIndex).toBe(0);
});
it('should handle both OAuth and API exhausted gracefully', async () => {
// All OAuth unavailable
vi.mocked(checkProfileAvailability).mockReturnValue({
available: false,
reason: 'rate limited'
});
// No API profiles
mockLoadProfilesFile.mockResolvedValue({
profiles: [],
activeProfileId: null,
version: 1
});
const result = await manager.getBestAvailableUnifiedAccount();
expect(result).toBeNull();
});
it('should prefer OAuth when both have same Infinity priority', async () => {
// No priority order set
vi.spyOn(manager, 'getAccountPriorityOrder').mockReturnValue([]);
const result = await manager.getBestAvailableUnifiedAccount('excluded-id');
// OAuth should come first by default
expect(result).not.toBeNull();
expect(result?.type).toBe('oauth');
});
});
describe('UsageMonitor - isAPIProfile gate removal', () => {
// Use actual file path since require.resolve doesn't work with mocked modules
const usageMonitorPath = new URL('../claude-profile/usage-monitor.ts', import.meta.url).pathname.replace(/^\/([A-Z]:)/, '$1');
it('should NOT contain isAPIProfile guard in checkUsageAndSwap swap logic', async () => {
const fs = await import('node:fs');
const source = fs.readFileSync(usageMonitorPath, 'utf-8');
// The old guard "Skipping proactive swap for API profile" should be removed
expect(source).not.toContain('Skipping proactive swap for API profile');
});
it('should NOT contain isAPIProfile guard in handleAuthFailure', async () => {
const fs = await import('node:fs');
const source = fs.readFileSync(usageMonitorPath, 'utf-8');
// The old guard should be removed - handleAuthFailure should work for all profile types
expect(source).not.toContain('using API profile, skipping swap');
});
it('should contain swap cooldown logic', async () => {
const fs = await import('node:fs');
const source = fs.readFileSync(usageMonitorPath, 'utf-8');
// Swap cooldown was added to prevent rapid back-and-forth
expect(source).toContain('SWAP_COOLDOWN_MS');
expect(source).toContain('lastSwapTimestamp');
expect(source).toContain('Swap cooldown active');
});
it('should use getBestAvailableUnifiedAccount in performProactiveSwap', async () => {
const fs = await import('node:fs');
const source = fs.readFileSync(usageMonitorPath, 'utf-8');
// performProactiveSwap should use the unified selection instead of inline logic
expect(source).toContain('getBestAvailableUnifiedAccount');
// The old inline unified list-building logic should be removed
expect(source).not.toContain('UnifiedSwapTarget');
});
});
-489
View File
@@ -1,489 +0,0 @@
# Agent Queue System
## Overview
The Agent Queue System manages the lifecycle and execution of background AI agents in Auto Claude. It ensures that agents spawn sequentially to prevent race conditions and file corruption.
## Why Sequential Execution?
### The Problem: `~/.claude.json` Race Condition
When multiple agents spawn concurrently, they all attempt to read and write to `~/.claude.json`:
```
Agent 1: Read ~/.claude.json → Modify → Write
Agent 2: Read ~/.claude.json → Modify → Write (concurrently!)
Agent 3: Read ~/.claude.json → Modify → Write (concurrently!)
```
This caused:
- **JSON corruption**: Invalid JSON structure from interleaved writes
- **Backup file accumulation**: `.claude.json.backup`, `.claude.json.backup.1`, etc.
- **Lost configuration**: Last write wins, earlier changes lost
- **Mysterious failures**: Agents failing with "invalid JSON" errors
### The Solution: Sequential Spawning via SpawnQueue
All agent types now execute **sequentially** through a FIFO queue:
```
Request 1 (ideation) → Spawn → Wait for exit → Next
Request 2 (roadmap) → Spawn → Wait for exit → Next
Request 3 (ideation) → Spawn → Wait for exit → Next
```
**Benefits:**
- No concurrent writes to `~/.claude.json`
- No JSON corruption or backup files
- Predictable execution order
- Simple error recovery (continue on failure)
## Architecture
### Components
```
┌─────────────────────────────────────────────────────────────┐
│ AgentQueueManager │
│ - startIdeationGeneration() │
│ - startRoadmapGeneration() │
│ - stopIdeation() / stopRoadmap() │
└──────────────────────┬──────────────────────────────────────┘
┌─────────────────┐
│ SpawnQueue │
│ (FIFO Queue) │
└────────┬────────┘
┌─────────────┴─────────────┐
▼ ▼
┌─────────────────────┐ ┌─────────────────────┐
│ executeIdeationSpawn│ │executeRoadmapSpawn │
│ (ideation_runner) │ │ (roadmap_runner) │
└─────────────────────┘ └─────────────────────┘
│ │
└───────────┬───────────────┘
┌─────────────────┐
│ AgentState │
│ - addProcess() │
│ - deleteProcess│
└─────────────────┘
┌─────────────────┐
│ AgentEvents │
│ (emit events) │
└─────────────────┘
```
### Data Flow
1. **User Request**: User triggers ideation or roadmap generation from UI
2. **Enqueue**: `AgentQueueManager` creates `SpawnRequest` and enqueues it
3. **Queue Processing**: `SpawnQueue` processes requests FIFO
4. **Spawn Execution**: Router calls `executeIdeationSpawn()` or `executeRoadmapSpawn()`
5. **Process Tracking**: Spawned process added to `AgentState` for tracking
6. **Event Handlers**: stdout/stderr/exit handlers attached to process
7. **Wait for Exit**: Queue waits for process to exit before processing next
8. **Completion**: Success/error events emitted to renderer process
### Queue Behavior
**FIFO Processing:**
- First in, first out
- No priority system (simple is better)
- All agent types share same queue
**Error Resilience:**
- If spawn fails, invoke `onError` callback
- Continue to next item in queue
- Don't block queue on single failure
**Sequential Execution:**
- Only one agent spawns at a time
- Wait for `process.exit()` before next spawn
- Prevents `~/.claude.json` race condition
## Agent Types
### Ideation Agents
**Purpose**: Discover improvements, performance issues, security vulnerabilities
**Runner**: `apps/backend/runners/ideation_runner.py`
**Types**:
- `discovery`: Code improvements and refactorings
- `performance`: Performance optimizations
- `security`: Security vulnerabilities
- `testing`: Test coverage gaps
- `documentation`: Documentation improvements
- `accessibility`: Accessibility issues
**Process Type**: `'ideation'`
**Events**:
- `ideation-progress`: Progress updates with phase/message
- `ideation-log`: Log output lines
- `ideation-type-complete`: Single type completed with ideas
- `ideation-type-failed`: Single type failed
- `ideation-complete`: All types completed
- `ideation-error`: Fatal error
- `ideation-stopped`: User stopped generation
### Roadmap Agents
**Purpose**: Generate strategic roadmap with competitor analysis
**Runner**: `apps/backend/runners/roadmap_runner.py`
**Features**:
- Strategic feature planning
- Competitive analysis (optional)
- Timeline estimation
- Priority ranking
**Process Type**: `'roadmap'`
**Events**:
- `roadmap-progress`: Progress updates with phase/message
- `roadmap-log`: Log output lines
- `roadmap-complete`: Roadmap generated
- `roadmap-error`: Fatal error
- `roadmap-stopped`: User stopped generation
### Build Agents (Not in Queue)
**Note**: Build agents (planner, coder, QA) are managed separately by `agent-process.ts` and do **not** go through this queue. They have their own spawning mechanism tied to spec/task lifecycle.
## Process State Tracking
Each spawned process is tracked in `AgentState`:
```typescript
interface QueuedProcessInfo {
taskId: string; // Project ID or task ID
process: ChildProcess; // Node.js ChildProcess instance
startedAt: Date; // When process was spawned
projectPath: string; // Project directory path
spawnId: number; // Unique spawn ID
queueProcessType: 'ideation' | 'roadmap'; // Process type
}
```
**Key Methods:**
- `addProcess(projectId, info)`: Track spawned process
- `getProcess(projectId)`: Get process info
- `deleteProcess(projectId)`: Remove from tracking
- `generateSpawnId()`: Generate unique spawn ID
- `wasSpawnKilled(spawnId)`: Check if intentionally stopped
- `clearKilledSpawn(spawnId)`: Clear killed flag
## Adding New Agent Types
To add a new agent type to the sequential queue:
### 1. Define Process Type
Add to `QueuedProcessInfo` type in `agent-state.ts`:
```typescript
queueProcessType: 'ideation' | 'roadmap' | 'new-type';
```
### 2. Create Spawn Executor
Add method in `AgentQueueManager`:
```typescript
private async executeNewTypeSpawn(
spawnId: string,
projectPath: string,
args: string[],
env: Record<string, string>,
projectId: string,
cwd: string
): Promise<ChildProcess> {
// Spawn the process
const childProcess = spawn(/* ... */);
// Add to state tracking
this.state.addProcess(projectId, {
taskId: projectId,
process: childProcess,
startedAt: new Date(),
projectPath,
spawnId: parseInt(spawnId, 10),
queueProcessType: 'new-type'
});
return childProcess;
}
```
### 3. Create Spawn Wrapper
Add method in `AgentQueueManager` to enqueue requests:
```typescript
async startNewTypeGeneration(
projectId: string,
projectPath: string,
config: NewTypeConfig
): Promise<void> {
// Build args
const args = ['runner.py', '--project', projectPath];
// Enqueue spawn request
this.spawnQueue.enqueue({
id: String(spawnId),
type: 'new-type',
projectId,
projectPath,
args,
env: finalEnv,
cwd,
onSpawn: async (childProcess) => {
// Attach event handlers
childProcess.stdout?.on('data', (data) => { /* ... */ });
childProcess.on('exit', (code) => { /* ... */ });
},
onError: (error) => {
this.emitter.emit('new-type-error', projectId, error.message);
}
});
}
```
### 4. Update SpawnQueue Router
Update constructor in `AgentQueueManager`:
```typescript
this.spawnQueue = new SpawnQueue(async (id, projectPath, args, env, projectId, cwd, type = 'ideation') => {
if (type === 'roadmap') {
return this.executeRoadmapSpawn(id, projectPath, args, env, projectId, cwd);
} else if (type === 'new-type') {
return this.executeNewTypeSpawn(id, projectPath, args, env, projectId, cwd);
} else {
return this.executeIdeationSpawn(id, projectPath, args, env, projectId, cwd);
}
});
```
### 5. Add Event Emitter Methods
Add stop/status methods:
```typescript
stopNewType(projectId: string): boolean {
const processInfo = this.state.getProcess(projectId);
const isNewType = processInfo?.queueProcessType === 'new-type';
if (isNewType) {
this.processManager.killProcess(projectId);
this.emitter.emit('new-type-stopped', projectId);
return true;
}
return false;
}
isNewTypeRunning(projectId: string): boolean {
const processInfo = this.state.getProcess(projectId);
return processInfo?.queueProcessType === 'new-type';
}
```
## Rate Limit Detection
The queue system automatically detects API rate limits:
1. **Collect Output**: stdout/stderr collected during process execution
2. **Detect Patterns**: Checks for rate limit error messages
3. **Emit Event**: `sdk-rate-limit` event with detection info
4. **Auto-Switch**: Profile scorer automatically switches to next available profile
**Detection**:
```typescript
const rateLimitDetection = detectRateLimit(allOutput);
if (rateLimitDetection.isRateLimited) {
const rateLimitInfo = createSDKRateLimitInfo('ideation', rateLimitDetection, { projectId });
this.emitter.emit('sdk-rate-limit', rateLimitInfo);
}
```
## Python Environment Management
Agents require a Python environment with dependencies:
1. **Pre-flight Check**: `ensurePythonEnvReady()` checks if venv is ready
2. **Venv Creation**: If needed, creates venv and installs dependencies
3. **Python Path**: Uses configured Python path (or bundled Python)
4. **PYTHONPATH**: Bundled site-packages + autoBuildSource for imports
**Environment Variables**:
```typescript
const finalEnv = {
...process.env,
...pythonEnv, // Bundled packages
...combinedEnv, // auto-claude/.env
...profileEnv, // OAuth token
...apiProfileEnv, // API profile config
PYTHONPATH: combinedPythonPath,
PYTHONUNBUFFERED: '1',
PYTHONUTF8: '1'
};
```
## Progress Persistence
Roadmap generation persists progress to disk for recovery:
- **File**: `.auto-claude/roadmap/generation_progress.json`
- **Debounced**: 300ms debounce (3-4 writes/sec max)
- **Leading + Trailing**: Immediate first write, final state on completion
- **Recovery**: Process can recover after app restart
**Progress Data**:
```json
{
"phase": "analyzing",
"progress": 45,
"message": "Analyzing codebase...",
"started_at": "2025-02-15T10:30:00Z",
"last_update_at": "2025-02-15T10:35:00Z",
"is_running": true
}
```
## Debug Logging
All operations are logged for debugging:
```typescript
debugLog('[Agent Queue] Starting ideation generation:', { projectId, projectPath, config });
debugLog('[Agent Queue] Generated spawn ID:', spawnId);
debugLog('[Agent Queue] Ideation process spawned:', { spawnId, projectId, pid });
```
**Enable Debug Logs**:
- Dev mode: Logs always visible
- Production: Set `DEBUG=auto-claude:*` environment variable
## Error Handling
### Spawn Errors
If process spawn fails:
1. `onError` callback invoked
2. Error event emitted to renderer
3. Queue continues to next item
**Example**:
```typescript
onError: (error) => {
debugError('[Agent Queue] Failed to spawn ideation process:', error);
this.emitter.emit('ideation-error', projectId, error.message);
}
```
### Process Errors
If process errors after spawn:
1. `process.on('error')` handler invoked
2. Process removed from state tracking
3. Error event emitted to renderer
### Exit Codes
- **Code 0**: Success
- **Code ≠ 0**: Failure (check for rate limits)
## Testing
### Manual Testing
```bash
# Start app in dev mode
npm run dev
# Trigger multiple agents simultaneously:
# 1. Open 3 projects
# 2. Click "Generate Ideas" on all 3 quickly
# 3. Click "Generate Roadmap" on 2 projects
# 4. Monitor console - should see sequential execution
# 5. Check ~/.claude.json - should be valid JSON
# 6. No .backup files should be created
```
### Automated Testing
```bash
# Run frontend tests
cd apps/frontend
npm test
# Typecheck
npm run typecheck
# Lint
npm run lint
```
## Files
- **agent-queue.ts**: Main queue manager, spawns ideation/roadmap agents
- **spawn-queue.ts**: FIFO queue for sequential spawning
- **agent-state.ts**: Process state tracking
- **agent-events.ts**: Event emission and progress parsing
- **agent-process.ts**: Process lifecycle management (build agents)
- **types.ts**: TypeScript type definitions
## Related Documentation
- [ARCHITECTURE.md](../../../../../../shared_docs/ARCHITECTURE.md): Overall architecture
- [apps/frontend/CONTRIBUTING.md](../../../../../../apps/frontend/CONTRIBUTING.md): Frontend contributing guide
- [CLAUDE.md](../../../../../../CLAUDE.md): Project instructions
## Troubleshooting
### Agents Not Starting
**Symptom**: Click "Generate Ideas" but nothing happens
**Checks**:
1. Check Python path is configured in settings
2. Check autoBuildSource path is set
3. Check runner files exist (`ideation_runner.py`, `roadmap_runner.py`)
4. Check debug logs for errors
### JSON Corruption
**Symptom**: `~/.claude.json` is invalid JSON
**Checks**:
1. Check if queue is being used (should be sequential)
2. Check for concurrent spawns (shouldn't happen)
3. Check backup files (.backup, .backup.1)
4. Restore from backup: `cp ~/.claude.json.backup ~/.claude.json`
### Rate Limiting
**Symptom**: Agents fail with rate limit errors
**Solution**:
1. System automatically switches to next available profile
2. Add more Claude profiles in settings
3. Wait for rate limit to reset (1 minute)
### Process Won't Stop
**Symptom**: Click "Stop" but process keeps running
**Checks**:
1. Check process ID in debug logs
2. Check if `wasIntentionallyStopped` flag is set
3. Check if process is tracked in AgentState
4. Manual kill: `kill <PID>` (macOS/Linux) or `taskkill /PID <PID>` (Windows)
@@ -329,7 +329,9 @@ export class AgentManager extends EventEmitter {
this.registerTaskWithOperationRegistry(taskId, 'spec-creation', { projectPath, taskDescription, specDir });
// Note: This is spec-creation but it chains to task-execution via run.py
await this.processManager.spawnProcess(taskId, autoBuildSource, args, combinedEnv, 'task-execution', projectId);
// Use projectPath as cwd instead of autoBuildSource to avoid cross-drive file access
// issues on Windows. The script path is absolute so Python finds its modules via sys.path[0]. (#1661)
await this.processManager.spawnProcess(taskId, projectPath, args, combinedEnv, 'task-execution', projectId);
}
/**
@@ -410,7 +412,10 @@ export class AgentManager extends EventEmitter {
// Register with unified OperationRegistry for proactive swap support
this.registerTaskWithOperationRegistry(taskId, 'task-execution', { projectPath, specId, options });
await this.processManager.spawnProcess(taskId, autoBuildSource, args, combinedEnv, 'task-execution', projectId);
// Use projectPath as cwd instead of autoBuildSource to avoid cross-drive file access
// issues on Windows. The script path (runPath) is absolute so Python finds its modules
// via sys.path[0] which is set to the script's directory. (#1661)
await this.processManager.spawnProcess(taskId, projectPath, args, combinedEnv, 'task-execution', projectId);
}
/**
@@ -448,7 +453,8 @@ export class AgentManager extends EventEmitter {
const args = [runPath, '--spec', specId, '--project-dir', projectPath, '--qa'];
await this.processManager.spawnProcess(taskId, autoBuildSource, args, combinedEnv, 'qa-process', projectId);
// Use projectPath as cwd instead of autoBuildSource to avoid cross-drive issues on Windows (#1661)
await this.processManager.spawnProcess(taskId, projectPath, args, combinedEnv, 'qa-process', projectId);
}
/**
@@ -84,7 +84,7 @@ vi.mock('../services/profile', () => ({
}));
vi.mock('../rate-limit-detector', () => ({
getBestAvailableProfileEnv: vi.fn(() => Promise.resolve({
getBestAvailableProfileEnv: vi.fn(() => ({
env: {},
profileId: 'default',
profileName: 'Default',
@@ -292,7 +292,7 @@ describe('AgentProcessManager - API Profile Env Injection (Story 2.3)', () => {
vi.mocked(profileService.getAPIProfileEnv).mockResolvedValue({});
// Set OAuth token via getProfileEnv (existing flow)
vi.mocked(rateLimitDetector.getBestAvailableProfileEnv).mockResolvedValue({
vi.mocked(rateLimitDetector.getBestAvailableProfileEnv).mockReturnValue({
env: { CLAUDE_CODE_OAUTH_TOKEN: 'oauth-token-123' },
profileId: 'default',
profileName: 'Default',
@@ -327,7 +327,7 @@ describe('AgentProcessManager - API Profile Env Injection (Story 2.3)', () => {
vi.mocked(profileService.getAPIProfileEnv).mockResolvedValue({});
// Set OAuth token
vi.mocked(rateLimitDetector.getBestAvailableProfileEnv).mockResolvedValue({
vi.mocked(rateLimitDetector.getBestAvailableProfileEnv).mockReturnValue({
env: { CLAUDE_CODE_OAUTH_TOKEN: 'oauth-token-456' },
profileId: 'default',
profileName: 'Default',
@@ -354,7 +354,7 @@ describe('AgentProcessManager - API Profile Env Injection (Story 2.3)', () => {
// OAuth mode
vi.mocked(profileService.getAPIProfileEnv).mockResolvedValue({});
vi.mocked(rateLimitDetector.getBestAvailableProfileEnv).mockResolvedValue({
vi.mocked(rateLimitDetector.getBestAvailableProfileEnv).mockReturnValue({
env: { CLAUDE_CODE_OAUTH_TOKEN: 'oauth-token-789' },
profileId: 'default',
profileName: 'Default',
@@ -403,10 +403,10 @@ describe('AgentProcessManager - API Profile Env Injection (Story 2.3)', () => {
vi.mocked(profileService.getAPIProfileEnv).mockResolvedValue(mockApiProfileEnv);
// Mock ALL console methods to capture any debug/error output
const consoleLogSpy = vi.spyOn(console, 'log').mockImplementation(() => { /* noop */ });
const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => { /* noop */ });
const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => { /* noop */ });
const consoleDebugSpy = vi.spyOn(console, 'debug').mockImplementation(() => { /* noop */ });
const consoleLogSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
const consoleDebugSpy = vi.spyOn(console, 'debug').mockImplementation(() => {});
await processManager.spawnProcess('task-1', '/fake/cwd', ['run.py'], {}, 'task-execution');
@@ -444,8 +444,8 @@ describe('AgentProcessManager - API Profile Env Injection (Story 2.3)', () => {
vi.mocked(profileService.getAPIProfileEnv).mockResolvedValue(mockApiProfileEnv);
// Mock console methods
const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => { /* noop */ });
const consoleLogSpy = vi.spyOn(console, 'log').mockImplementation(() => { /* noop */ });
const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
const consoleLogSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
await processManager.spawnProcess('task-1', '/fake/cwd', ['run.py'], {}, 'task-execution');
@@ -512,7 +512,7 @@ describe('AgentProcessManager - API Profile Env Injection (Story 2.3)', () => {
ANTHROPIC_BASE_URL: 'https://api-profile.com'
};
vi.mocked(rateLimitDetector.getBestAvailableProfileEnv).mockResolvedValue({
vi.mocked(rateLimitDetector.getBestAvailableProfileEnv).mockReturnValue({
env: profileEnv,
profileId: 'default',
profileName: 'Default',
@@ -817,7 +817,7 @@ describe('AgentProcessManager - API Profile Env Injection (Story 2.3)', () => {
vi.mocked(profileService.getAPIProfileEnv).mockResolvedValue({});
// Profile provides CLAUDE_CONFIG_DIR (OAuth subscription profile)
vi.mocked(rateLimitDetector.getBestAvailableProfileEnv).mockResolvedValue({
vi.mocked(rateLimitDetector.getBestAvailableProfileEnv).mockReturnValue({
env: {
CLAUDE_CONFIG_DIR: '/home/user/.config/claude-profile-1',
CLAUDE_CODE_OAUTH_TOKEN: 'oauth-token-abc'
@@ -844,7 +844,7 @@ describe('AgentProcessManager - API Profile Env Injection (Story 2.3)', () => {
vi.mocked(profileService.getAPIProfileEnv).mockResolvedValue({});
// Profile provides CLAUDE_CONFIG_DIR
vi.mocked(rateLimitDetector.getBestAvailableProfileEnv).mockResolvedValue({
vi.mocked(rateLimitDetector.getBestAvailableProfileEnv).mockReturnValue({
env: {
CLAUDE_CONFIG_DIR: '/home/user/.config/claude-profile-2',
CLAUDE_CODE_OAUTH_TOKEN: 'oauth-token-def'
@@ -875,7 +875,7 @@ describe('AgentProcessManager - API Profile Env Injection (Story 2.3)', () => {
vi.mocked(profileService.getAPIProfileEnv).mockResolvedValue(mockApiProfileEnv);
// Profile env without CLAUDE_CONFIG_DIR (API profile mode)
vi.mocked(rateLimitDetector.getBestAvailableProfileEnv).mockResolvedValue({
vi.mocked(rateLimitDetector.getBestAvailableProfileEnv).mockReturnValue({
env: {},
profileId: 'api-profile-1',
profileName: 'Custom API',
@@ -901,7 +901,7 @@ describe('AgentProcessManager - API Profile Env Injection (Story 2.3)', () => {
vi.mocked(profileService.getAPIProfileEnv).mockResolvedValue({});
// Profile provides CLAUDE_CONFIG_DIR - agent should use config dir for auth
vi.mocked(rateLimitDetector.getBestAvailableProfileEnv).mockResolvedValue({
vi.mocked(rateLimitDetector.getBestAvailableProfileEnv).mockReturnValue({
env: {
CLAUDE_CONFIG_DIR: '/home/user/.config/claude-profile-3',
CLAUDE_CODE_OAUTH_TOKEN: 'oauth-token-ghi'
+52 -75
View File
@@ -22,10 +22,10 @@ import { pythonEnvManager, getConfiguredPythonPath } from '../python-env-manager
import { buildMemoryEnvVars } from '../memory-env-builder';
import { readSettingsFile } from '../settings-utils';
import type { AppSettings } from '../../shared/types/settings';
import { getOAuthModeClearVars } from './env-utils';
import { getOAuthModeClearVars, normalizeEnvPathKey, mergePythonEnvPath } from './env-utils';
import { getAugmentedEnv } from '../env-utils';
import { getToolInfo, getClaudeCliPathForSdk } from '../cli-tool-manager';
import { killProcessGracefully, isWindows } from '../platform';
import { killProcessGracefully, isWindows, getPathDelimiter } from '../platform';
import { debugLog } from '../../shared/utils/debug-logger';
/**
@@ -173,11 +173,11 @@ export class AgentProcessManager {
return env;
}
private async setupProcessEnvironment(
private setupProcessEnvironment(
extraEnv: Record<string, string>
): Promise<NodeJS.ProcessEnv> {
): NodeJS.ProcessEnv {
// Get best available Claude profile environment (automatically handles rate limits)
const profileResult = await getBestAvailableProfileEnv();
const profileResult = getBestAvailableProfileEnv();
const profileEnv = profileResult.env;
debugLog('[AgentProcess:setupEnv] Profile result:', {
@@ -268,11 +268,11 @@ export class AgentProcessManager {
return mergedEnv;
}
private async handleProcessFailure(
private handleProcessFailure(
taskId: string,
allOutput: string,
processType: ProcessType
): Promise<boolean> {
): boolean {
console.log('[AgentProcess] Checking for rate limit in output (last 500 chars):', allOutput.slice(-500));
const rateLimitDetection = detectRateLimit(allOutput);
@@ -285,7 +285,7 @@ export class AgentProcessManager {
});
if (rateLimitDetection.isRateLimited) {
const wasHandled = await this.handleRateLimitWithAutoSwap(
const wasHandled = this.handleRateLimitWithAutoSwap(
taskId,
rateLimitDetection,
processType
@@ -302,11 +302,11 @@ export class AgentProcessManager {
return this.handleAuthFailure(taskId, allOutput);
}
private async handleRateLimitWithAutoSwap(
private handleRateLimitWithAutoSwap(
taskId: string,
rateLimitDetection: ReturnType<typeof detectRateLimit>,
processType: ProcessType
): Promise<boolean> {
): boolean {
const profileManager = getClaudeProfileManager();
const autoSwitchSettings = profileManager.getAutoSwitchSettings();
@@ -322,15 +322,14 @@ export class AgentProcessManager {
}
const currentProfileId = rateLimitDetection.profileId;
const bestAccount = await profileManager.getBestAvailableUnifiedAccount(currentProfileId);
const bestProfile = profileManager.getBestAvailableProfile(currentProfileId);
console.log('[AgentProcess] Best available account:', bestAccount ? {
id: bestAccount.id,
name: bestAccount.name,
type: bestAccount.type
console.log('[AgentProcess] Best available profile:', bestProfile ? {
id: bestProfile.id,
name: bestProfile.name
} : 'NONE');
if (!bestAccount) {
if (!bestProfile) {
// Single account case: let backend handle with intelligent pause
// Don't show manual modal - backend will pause intelligently and resume when ready
console.log('[AgentProcess] No alternative profile - backend will handle with intelligent pause');
@@ -339,36 +338,24 @@ export class AgentProcessManager {
return false;
}
console.log('[AgentProcess] AUTO-SWAP: Switching from', currentProfileId, 'to', bestAccount.id, '(type:', bestAccount.type + ')');
if (bestAccount.type === 'oauth') {
profileManager.setActiveProfile(bestAccount.id);
// Clear API active profile so getAPIProfileEnv() returns empty (OAuth mode)
try {
const { setActiveAPIProfile } = await import('../services/profile/profile-manager');
await setActiveAPIProfile(null);
} catch (error) {
console.error('[AgentProcess] Failed to clear active API profile:', error);
}
} else {
const { setActiveAPIProfile } = await import('../services/profile/profile-manager');
await setActiveAPIProfile(bestAccount.id);
}
console.log('[AgentProcess] AUTO-SWAP: Switching from', currentProfileId, 'to', bestProfile.id);
profileManager.setActiveProfile(bestProfile.id);
const source = processType === 'spec-creation' ? 'roadmap' : 'task';
const rateLimitInfo = createSDKRateLimitInfo(source, rateLimitDetection, { taskId });
rateLimitInfo.wasAutoSwapped = true;
rateLimitInfo.swappedToProfile = { id: bestAccount.id, name: bestAccount.name };
rateLimitInfo.swappedToProfile = { id: bestProfile.id, name: bestProfile.name };
rateLimitInfo.swapReason = 'reactive';
console.log('[AgentProcess] Emitting sdk-rate-limit event (auto-swapped):', rateLimitInfo);
this.emitter.emit('sdk-rate-limit', rateLimitInfo);
console.log('[AgentProcess] Emitting auto-swap-restart-task event for task:', taskId);
this.emitter.emit('auto-swap-restart-task', taskId, bestAccount.id);
this.emitter.emit('auto-swap-restart-task', taskId, bestProfile.id);
return true;
}
private async handleAuthFailure(taskId: string, allOutput: string): Promise<boolean> {
private handleAuthFailure(taskId: string, allOutput: string): boolean {
console.log('[AgentProcess] No rate limit detected - checking for auth failure');
const authFailureDetection = detectAuthFailure(allOutput);
@@ -380,7 +367,7 @@ export class AgentProcessManager {
console.log('[AgentProcess] Auth failure detected:', authFailureDetection);
// Try auto-swap if enabled
const wasHandled = await this.handleAuthFailureWithAutoSwap(taskId, authFailureDetection);
const wasHandled = this.handleAuthFailureWithAutoSwap(taskId, authFailureDetection);
if (!wasHandled) {
// Fall back to UI notification
@@ -398,12 +385,12 @@ export class AgentProcessManager {
/**
* Attempt to auto-swap to another profile on authentication failure.
* Only works when autoSwitchOnAuthFailure is enabled and an alternative
* authenticated profile is available. Considers both OAuth and API profiles.
* authenticated profile is available.
*/
private async handleAuthFailureWithAutoSwap(
private handleAuthFailureWithAutoSwap(
taskId: string,
authFailureDetection: ReturnType<typeof detectAuthFailure>
): Promise<boolean> {
): boolean {
const profileManager = getClaudeProfileManager();
const autoSwitchSettings = profileManager.getAutoSwitchSettings();
@@ -419,42 +406,22 @@ export class AgentProcessManager {
}
const currentProfileId = authFailureDetection.profileId;
const bestAccount = await profileManager.getBestAvailableUnifiedAccount(currentProfileId);
const bestProfile = profileManager.getBestAvailableProfile(currentProfileId);
console.log('[AgentProcess] Best available account for auth failure swap:', bestAccount ? {
id: bestAccount.id,
name: bestAccount.name,
type: bestAccount.type
console.log('[AgentProcess] Best available profile for auth failure swap:', bestProfile ? {
id: bestProfile.id,
name: bestProfile.name,
isAuthenticated: bestProfile.isAuthenticated
} : 'NONE');
if (!bestAccount) {
console.log('[AgentProcess] No alternative account available - falling back to UI');
// Verify the best profile is actually authenticated
if (!bestProfile || !bestProfile.isAuthenticated) {
console.log('[AgentProcess] No authenticated alternative profile - falling back to UI');
return false;
}
// For OAuth results, verify authentication (API profiles validated by having apiKey)
if (bestAccount.type === 'oauth') {
const oauthProfile = profileManager.getProfile(bestAccount.id);
if (!oauthProfile?.isAuthenticated && !profileManager.isProfileAuthenticated(oauthProfile!)) {
console.log('[AgentProcess] OAuth profile not authenticated - falling back to UI');
return false;
}
}
console.log('[AgentProcess] AUTH-FAILURE AUTO-SWAP:', currentProfileId, '->', bestAccount.id, '(type:', bestAccount.type + ')');
if (bestAccount.type === 'oauth') {
profileManager.setActiveProfile(bestAccount.id);
// Clear API active profile so getAPIProfileEnv() returns empty (OAuth mode)
try {
const { setActiveAPIProfile } = await import('../services/profile/profile-manager');
await setActiveAPIProfile(null);
} catch (error) {
console.error('[AgentProcess] Failed to clear active API profile:', error);
}
} else {
const { setActiveAPIProfile } = await import('../services/profile/profile-manager');
await setActiveAPIProfile(bestAccount.id);
}
console.log('[AgentProcess] AUTH-FAILURE AUTO-SWAP:', currentProfileId, '->', bestProfile.id);
profileManager.setActiveProfile(bestProfile.id);
// Emit auth-failure event with swap metadata for UI notification
this.emitter.emit('auth-failure', taskId, {
@@ -463,12 +430,12 @@ export class AgentProcessManager {
message: authFailureDetection.message,
originalError: authFailureDetection.originalError,
wasAutoSwapped: true,
swappedToProfile: { id: bestAccount.id, name: bestAccount.name }
swappedToProfile: { id: bestProfile.id, name: bestProfile.name }
});
// Reuse existing restart event
console.log('[AgentProcess] Emitting auto-swap-restart-task event for auth failure:', taskId);
this.emitter.emit('auto-swap-restart-task', taskId, bestAccount.id);
this.emitter.emit('auto-swap-restart-task', taskId, bestProfile.id);
return true;
}
@@ -619,7 +586,7 @@ export class AgentProcessManager {
return envVars;
} catch {
return {};
return {};
}
}
@@ -680,7 +647,7 @@ export class AgentProcessManager {
spawnId
});
const env = await this.setupProcessEnvironment(extraEnv);
const env = this.setupProcessEnvironment(extraEnv);
// Get Python environment (PYTHONPATH for bundled packages, etc.)
const pythonEnv = pythonEnvManager.getPythonEnv();
@@ -712,7 +679,17 @@ export class AgentProcessManager {
},
});
// Parse Python commandto handle space-separated commands like "py -3"
// Merge PATH from pythonEnv with augmented PATH from env.
// pythonEnv may contain its own PATH (e.g., on Windows with pywin32_system32 prepended).
// Simply spreading pythonEnv after env would overwrite the augmented PATH (which includes
// npm globals, homebrew, etc.), causing "Claude code not found" on Windows (#1661).
// mergePythonEnvPath() normalizes PATH key casing and prepends pythonEnv-specific paths.
const mergedPythonEnv = { ...pythonEnv };
const pathSep = getPathDelimiter();
mergePythonEnvPath(env as Record<string, string | undefined>, mergedPythonEnv as Record<string, string | undefined>, pathSep);
// Parse Python command to handle space-separated commands like "py -3"
const [pythonCommand, pythonBaseArgs] = parsePythonCommand(this.getPythonPath());
let childProcess;
try {
@@ -720,7 +697,7 @@ export class AgentProcessManager {
cwd,
env: {
...env, // Already includes process.env, extraEnv, profileEnv, PYTHONUNBUFFERED, PYTHONUTF8
...pythonEnv, // Include Python environment (PYTHONPATH for bundled packages)
...mergedPythonEnv, // Python env with merged PATH (preserves augmented PATH entries)
...oauthModeClearVars, // Clear stale ANTHROPIC_* vars when in OAuth mode
...apiProfileEnv // Include active API profile config (highest priority for ANTHROPIC_* vars)
}
@@ -895,7 +872,7 @@ export class AgentProcessManager {
stderrBuffer = processBufferedOutput(stderrBuffer, data.toString('utf-8'));
});
childProcess.on('exit', async (code: number | null) => {
childProcess.on('exit', (code: number | null) => {
if (stdoutBuffer.trim()) {
this.emitter.emit('log', taskId, stdoutBuffer + '\n', projectId);
processLog(stdoutBuffer);
@@ -914,7 +891,7 @@ export class AgentProcessManager {
if (code !== 0) {
console.log('[AgentProcess] Process failed with code:', code, 'for task:', taskId);
const wasHandled = await this.handleProcessFailure(taskId, allOutput, processType);
const wasHandled = this.handleProcessFailure(taskId, allOutput, processType);
if (wasHandled) {
this.emitter.emit('exit', taskId, code, processType, projectId);
@@ -1,118 +0,0 @@
/**
* Tests for AgentQueueManager
*/
import { describe, it, expect } from 'vitest';
import { EventEmitter } from 'events';
import { AgentQueueManager } from './agent-queue';
import { AgentState } from './agent-state';
import { AgentEvents } from './agent-events';
import { AgentProcessManager } from './agent-process';
import { SpawnQueue } from './spawn-queue';
describe('AgentQueueManager', () => {
it('should initialize SpawnQueue instance', () => {
// Create minimal dependencies for testing
const mockState = {} as unknown as AgentState;
const mockEvents = {} as unknown as AgentEvents;
const mockProcessManager = {
ensurePythonEnvReady: async () => ({ ready: true }),
getAutoBuildSourcePath: () => '/mock/path'
} as unknown as AgentProcessManager;
const mockEmitter = new EventEmitter();
// Instantiate AgentQueueManager
const manager = new AgentQueueManager(
mockState,
mockEvents,
mockProcessManager,
mockEmitter
);
// Access private property via type assertion
const spawnQueue = (manager as unknown as { spawnQueue: SpawnQueue }).spawnQueue;
// Verify spawnQueue is a SpawnQueue instance
expect(spawnQueue).toBeDefined();
expect(spawnQueue).toBeInstanceOf(SpawnQueue);
});
it('should initialize SpawnQueue with empty queue', () => {
const mockState = {} as unknown as AgentState;
const mockEvents = {} as unknown as AgentEvents;
const mockProcessManager = {
ensurePythonEnvReady: async () => ({ ready: true }),
getAutoBuildSourcePath: () => '/mock/path'
} as unknown as AgentProcessManager;
const mockEmitter = new EventEmitter();
const manager = new AgentQueueManager(
mockState,
mockEvents,
mockProcessManager,
mockEmitter
);
const spawnQueue = (manager as unknown as { spawnQueue: SpawnQueue }).spawnQueue;
// Verify initial queue state
expect(spawnQueue.length).toBe(0);
expect(spawnQueue.isProcessing).toBe(false);
});
it('should route ideation and roadmap spawns correctly', async () => {
const _mockState = {} as unknown as AgentState;
const mockEvents = {} as unknown as AgentEvents;
const mockProcessManager = {
ensurePythonEnvReady: async () => ({ ready: true }),
getAutoBuildSourcePath: () => '/mock/path',
getPythonPath: () => 'python3',
killProcess: () => false,
getCombinedEnv: () => ({}),
state: { addProcess: () => { /* noop */ }, deleteProcess: () => { /* noop */ } }
} as unknown as AgentProcessManager;
// Mock state methods
const mockStateWithMethods = {
generateSpawnId: () => 1,
addProcess: () => { /* noop */ },
wasSpawnKilled: () => false,
clearKilledSpawn: () => { /* noop */ },
getProcess: () => null,
deleteProcess: () => { /* noop */ }
} as unknown as AgentState;
const mockEmitter = new EventEmitter();
const manager = new AgentQueueManager(
mockStateWithMethods,
mockEvents,
mockProcessManager,
mockEmitter
);
const spawnQueue = (manager as unknown as { spawnQueue: SpawnQueue }).spawnQueue;
// Test that spawn function routes correctly
let processType: string | undefined;
// Mock the spawn function to capture the type
const _originalEnqueue = spawnQueue.enqueue.bind(spawnQueue);
spawnQueue.enqueue = function(request) {
processType = request.type;
return Promise.resolve(undefined);
};
// Access private methods via type assertion
const spawnIdeationProcess = (manager as unknown as { spawnIdeationProcess: (id: string, path: string, args: string[]) => Promise<void> }).spawnIdeationProcess;
const spawnRoadmapProcess = (manager as unknown as { spawnRoadmapProcess: (id: string, path: string, args: string[]) => Promise<void> }).spawnRoadmapProcess;
// Test ideation spawn
await spawnIdeationProcess.call(manager, 'project-1', '/path/to/project', ['ideation']);
expect(processType).toBe('ideation');
// Test roadmap spawn
await spawnRoadmapProcess.call(manager, 'project-2', '/path/to/project2', ['roadmap']);
expect(processType).toBe('roadmap');
});
});
+345 -480
View File
@@ -1,4 +1,4 @@
import { spawn, type ChildProcess } from 'child_process';
import { spawn } from 'child_process';
import path from 'path';
import { existsSync, mkdirSync, unlinkSync, promises as fsPromises } from 'fs';
import { EventEmitter } from 'events';
@@ -10,7 +10,7 @@ import type { IdeationConfig, Idea } from '../../shared/types';
import { AUTO_BUILD_PATHS } from '../../shared/constants';
import { detectRateLimit, createSDKRateLimitInfo, getBestAvailableProfileEnv } from '../rate-limit-detector';
import { getAPIProfileEnv } from '../services/profile';
import { getOAuthModeClearVars } from './env-utils';
import { getOAuthModeClearVars, normalizeEnvPathKey } from './env-utils';
import { debugLog, debugError } from '../../shared/utils/debug-logger';
import { stripAnsiCodes } from '../../shared/utils/ansi-sanitizer';
import { parsePythonCommand } from '../python-detector';
@@ -21,7 +21,6 @@ import type { RawIdea } from '../ipc-handlers/ideation/types';
import { getPathDelimiter } from '../platform';
import { debounce } from '../utils/debounce';
import { writeFileWithRetry } from '../utils/atomic-file';
import { SpawnQueue } from './spawn-queue';
/** Maximum length for status messages displayed in progress UI */
const STATUS_MESSAGE_MAX_LENGTH = 200;
@@ -40,29 +39,6 @@ function formatStatusMessage(log: string): string {
/**
* Queue management for ideation and roadmap generation
*
* **IMPORTANT: Sequential Execution**
* All agent types (ideation, roadmap) now execute SEQUENTIALLY via SpawnQueue.
* This prevents race conditions when multiple agents write to ~/.claude.json
* concurrently, which was causing JSON corruption and backup file accumulation.
*
* **Key Behaviors:**
* - Only ONE agent spawns at a time across all types (FIFO queue)
* - Next agent waits for previous agent's process to exit
* - Queue automatically continues if spawn fails (error resilience)
* - Each agent type gets unique process tracking via queueProcessType
*
* **Architecture:**
* - User calls startIdeationGeneration() or startRoadmapGeneration()
* - Request enqueued in spawnQueue with type ('ideation' | 'roadmap')
* - Queue routes to executeIdeationSpawn() or executeRoadmapSpawn()
* - Process spawned, tracked in AgentState, event handlers attached
* - Queue waits for process.exit() before processing next item
*
* **Process Types:**
* - 'ideation': Idea generation (discoveries, performance, security)
* - 'roadmap': Strategic roadmap generation with competitor analysis
* - 'build': Build agents (managed separately, not in this queue)
*/
export class AgentQueueManager {
private state: AgentState;
@@ -78,7 +54,6 @@ export class AgentQueueManager {
isRunning: boolean
) => void;
private cancelPersistRoadmapProgress: () => void;
private spawnQueue: SpawnQueue;
constructor(
state: AgentState,
@@ -101,15 +76,6 @@ export class AgentQueueManager {
);
this.debouncedPersistRoadmapProgress = debouncedFn;
this.cancelPersistRoadmapProgress = cancel;
// Initialize sequential spawn queue with routing based on process type
this.spawnQueue = new SpawnQueue(async (id, projectPath, args, env, projectId, cwd, type = 'ideation') => {
if (type === 'roadmap') {
return this.executeRoadmapSpawn(id, projectPath, args, env, projectId, cwd);
} else {
return this.executeIdeationSpawn(id, projectPath, args, env, projectId, cwd);
}
});
}
/**
@@ -352,109 +318,6 @@ export class AgentQueueManager {
await this.spawnIdeationProcess(projectId, projectPath, args);
}
/**
* Execute the actual spawn of an ideation process
* Extracted to be used by SpawnQueue for sequential execution
*
* This method only spawns the process and adds it to state tracking.
* Event handlers are attached by spawnIdeationProcess() via onSpawn callback.
*
* @param spawnId - Unique spawn ID for this process instance
* @param projectPath - Project path (not used directly but kept for signature)
* @param args - Command-line arguments
* @param env - Environment variables
* @param projectId - Project ID for state tracking
* @param cwd - Working directory for the process
* @returns The spawned ChildProcess
*/
private async executeIdeationSpawn(
spawnId: string,
projectPath: string,
args: string[],
env: Record<string, string>,
projectId: string,
cwd: string
): Promise<ChildProcess> {
debugLog('[Agent Queue] Executing ideation spawn:', { spawnId, projectId });
// Get Python path from process manager (uses venv if configured)
const pythonPath = this.processManager.getPythonPath();
// Validate Python path
if (!pythonPath) {
throw new Error('Python path not configured. Please ensure Python is properly set up in settings.');
}
// Parse Python command to handle space-separated commands like "py -3"
const [pythonCommand, pythonBaseArgs] = parsePythonCommand(pythonPath);
// Spawn the process
const childProcess = spawn(pythonCommand, [...pythonBaseArgs, ...args], {
cwd,
env
});
// Add to state tracking
this.state.addProcess(projectId, {
taskId: projectId,
process: childProcess,
startedAt: new Date(),
projectPath, // Store project path for loading session on completion
spawnId: parseInt(spawnId, 10),
queueProcessType: 'ideation'
});
debugLog('[Agent Queue] Ideation process spawned:', { spawnId, projectId, pid: childProcess.pid });
return childProcess;
}
/**
* Execute roadmap spawn - called by SpawnQueue when request reaches front of queue
* This method only spawns the process; all event handlers are attached in spawnRoadmapProcess's onSpawn callback
*/
private async executeRoadmapSpawn(
spawnId: string,
projectPath: string,
args: string[],
env: Record<string, string>,
projectId: string,
cwd: string
): Promise<ChildProcess> {
debugLog('[Agent Queue] Executing roadmap spawn:', { spawnId, projectId });
// Get Python path from process manager (uses venv if configured)
const pythonPath = this.processManager.getPythonPath();
// Validate Python path
if (!pythonPath) {
throw new Error('Python path not configured. Please ensure Python is properly set up in settings.');
}
// Parse Python command to handle space-separated commands like "py -3"
const [pythonCommand, pythonBaseArgs] = parsePythonCommand(pythonPath);
// Spawn the process
const childProcess = spawn(pythonCommand, [...pythonBaseArgs, ...args], {
cwd,
env
});
// Add to state tracking
this.state.addProcess(projectId, {
taskId: projectId,
process: childProcess,
startedAt: new Date(),
projectPath, // Store project path for loading roadmap on completion
spawnId: parseInt(spawnId, 10),
queueProcessType: 'roadmap'
});
debugLog('[Agent Queue] Roadmap process spawned:', { spawnId, projectId, pid: childProcess.pid });
return childProcess;
}
/**
* Spawn a Python process for ideation generation
*/
@@ -489,7 +352,7 @@ export class AgentQueueManager {
const combinedEnv = this.processManager.getCombinedEnv(projectPath);
// Get best available Claude profile environment (automatically handles rate limits)
const profileResult = await getBestAvailableProfileEnv();
const profileResult = getBestAvailableProfileEnv();
const profileEnv = profileResult.env;
// Get active API profile environment variables
@@ -499,7 +362,7 @@ export class AgentQueueManager {
const oauthModeClearVars = getOAuthModeClearVars(apiProfileEnv);
// Get Python path from process manager (uses venv if configured)
const _pythonPath = this.processManager.getPythonPath();
const pythonPath = this.processManager.getPythonPath();
// Get Python environment from pythonEnvManager (includes bundled site-packages)
const pythonEnv = pythonEnvManager.getPythonEnv();
@@ -534,6 +397,12 @@ export class AgentQueueManager {
PYTHONUTF8: '1'
};
// Normalize PATH key to a single uppercase 'PATH' entry.
// On Windows, process.env spread produces 'Path' while pythonEnv may write 'PATH',
// resulting in duplicate keys in the final object. Without normalization the child
// process inherits both keys, which can cause tool-not-found errors (#1661).
normalizeEnvPathKey(finalEnv as Record<string, string | undefined>);
// Debug: Show OAuth token source (token values intentionally omitted for security - AC4)
const tokenSource = profileEnv['CLAUDE_CODE_OAUTH_TOKEN']
? 'Electron app profile'
@@ -544,47 +413,50 @@ export class AgentQueueManager {
hasToken
});
// Enqueue the spawn request for sequential processing
// The queue will call executeIdeationSpawn() when it's this request's turn
this.spawnQueue.enqueue({
id: String(spawnId),
type: 'ideation',
projectId,
projectPath,
args,
env: finalEnv as Record<string, string>,
// Parse Python command to handle space-separated commands like "py -3"
const [pythonCommand, pythonBaseArgs] = parsePythonCommand(pythonPath);
const childProcess = spawn(pythonCommand, [...pythonBaseArgs, ...args], {
cwd,
onSpawn: async (childProcess) => {
debugLog('[Agent Queue] Ideation process spawned from queue:', { spawnId, projectId, pid: childProcess.pid });
env: finalEnv
});
// Track progress through output
let progressPhase = 'analyzing';
let progressPercent = 10;
// Collect output for rate limit detection
let allOutput = '';
this.state.addProcess(projectId, {
taskId: projectId,
process: childProcess,
startedAt: new Date(),
projectPath, // Store project path for loading session on completion
spawnId,
queueProcessType: 'ideation'
});
// Helper to emit logs - split multi-line output into individual log lines
const emitLogs = (log: string) => {
const lines = log.split('\n').filter(line => line.trim().length > 0);
for (const line of lines) {
const trimmed = line.trim();
if (trimmed.length > 0) {
this.emitter.emit('ideation-log', projectId, trimmed);
}
}
};
// Track progress through output
let progressPhase = 'analyzing';
let progressPercent = 10;
// Collect output for rate limit detection
let allOutput = '';
// Track completed types for progress calculation
const completedTypes = new Set<string>();
// Derive totalTypes from --types argument instead of hardcoding
const typesArgIndex = args.indexOf('--types');
const totalTypes =
typesArgIndex > -1 && args[typesArgIndex + 1]
? args[typesArgIndex + 1].split(',').length
: 6; // Default to 6 if not specified
// Helper to emit logs - split multi-line output into individual log lines
const emitLogs = (log: string) => {
const lines = log.split('\n').filter(line => line.trim().length > 0);
for (const line of lines) {
const trimmed = line.trim();
if (trimmed.length > 0) {
this.emitter.emit('ideation-log', projectId, trimmed);
}
}
};
// Handle stdout - explicitly decode as UTF-8 for cross-platform Unicode support
childProcess.stdout?.on('data', (data: Buffer) => {
// Track completed types for progress calculation
const completedTypes = new Set<string>();
// Derive totalTypes from --types argument instead of hardcoding
const typesArgIndex = args.findIndex((arg) => arg === '--types');
const totalTypes =
typesArgIndex > -1 && args[typesArgIndex + 1]
? args[typesArgIndex + 1].split(',').length
: 6; // Default to 6 if not specified
// Handle stdout - explicitly decode as UTF-8 for cross-platform Unicode support
childProcess.stdout?.on('data', (data: Buffer) => {
const log = data.toString('utf-8');
// Collect output for rate limit detection (keep last 10KB)
allOutput = (allOutput + log).slice(-10000);
@@ -671,126 +543,118 @@ export class AgentQueueManager {
});
});
// Handle stderr - also emit as logs, explicitly decode as UTF-8
childProcess.stderr?.on('data', (data: Buffer) => {
const log = data.toString('utf-8');
// Collect stderr for rate limit detection too
allOutput = (allOutput + log).slice(-10000);
console.error('[Ideation STDERR]', log);
emitLogs(log);
this.emitter.emit('ideation-progress', projectId, {
phase: progressPhase,
progress: progressPercent,
message: formatStatusMessage(log)
// Handle stderr - also emit as logs, explicitly decode as UTF-8
childProcess.stderr?.on('data', (data: Buffer) => {
const log = data.toString('utf-8');
// Collect stderr for rate limit detection too
allOutput = (allOutput + log).slice(-10000);
console.error('[Ideation STDERR]', log);
emitLogs(log);
this.emitter.emit('ideation-progress', projectId, {
phase: progressPhase,
progress: progressPercent,
message: formatStatusMessage(log)
});
});
// Handle process exit
childProcess.on('exit', (code: number | null) => {
debugLog('[Agent Queue] Ideation process exited:', { projectId, code, spawnId });
// Check if this process was intentionally stopped by the user
const wasIntentionallyStopped = this.state.wasSpawnKilled(spawnId);
if (wasIntentionallyStopped) {
debugLog('[Agent Queue] Ideation process was intentionally stopped, ignoring exit');
this.state.clearKilledSpawn(spawnId);
// Note: Don't call deleteProcess here - killProcess() already deleted it.
// A new process with the same projectId may have been started.
// Emit stopped event to ensure UI updates
this.emitter.emit('ideation-stopped', projectId);
return;
}
// Get the stored project path before deleting from map
const processInfo = this.state.getProcess(projectId);
const storedProjectPath = processInfo?.projectPath;
this.state.deleteProcess(projectId);
// Check for rate limit if process failed
if (code !== 0) {
debugLog('[Agent Queue] Checking for rate limit (non-zero exit)');
const rateLimitDetection = detectRateLimit(allOutput);
if (rateLimitDetection.isRateLimited) {
debugLog('[Agent Queue] Rate limit detected for ideation');
const rateLimitInfo = createSDKRateLimitInfo('ideation', rateLimitDetection, {
projectId
});
this.emitter.emit('sdk-rate-limit', rateLimitInfo);
}
}
if (code === 0) {
debugLog('[Agent Queue] Ideation generation completed successfully');
this.emitter.emit('ideation-progress', projectId, {
phase: 'complete',
progress: 100,
message: 'Ideation generation complete'
});
// Handle process exit
childProcess.on('exit', (code: number | null) => {
debugLog('[Agent Queue] Ideation process exited:', { projectId, code, spawnId });
// Check if this process was intentionally stopped by the user
const wasIntentionallyStopped = this.state.wasSpawnKilled(spawnId);
if (wasIntentionallyStopped) {
debugLog('[Agent Queue] Ideation process was intentionally stopped, ignoring exit');
this.state.clearKilledSpawn(spawnId);
// Note: Don't call deleteProcess here - killProcess() already deleted it.
// A new process with the same projectId may have been started.
// Emit stopped event to ensure UI updates
this.emitter.emit('ideation-stopped', projectId);
return;
}
// Get the stored project path before deleting from map
const processInfo = this.state.getProcess(projectId);
const storedProjectPath = processInfo?.projectPath;
this.state.deleteProcess(projectId);
// Check for rate limit if process failed
if (code !== 0) {
debugLog('[Agent Queue] Checking for rate limit (non-zero exit)');
const rateLimitDetection = detectRateLimit(allOutput);
if (rateLimitDetection.isRateLimited) {
debugLog('[Agent Queue] Rate limit detected for ideation');
const rateLimitInfo = createSDKRateLimitInfo('ideation', rateLimitDetection, {
projectId
});
this.emitter.emit('sdk-rate-limit', rateLimitInfo);
}
}
if (code === 0) {
debugLog('[Agent Queue] Ideation generation completed successfully');
this.emitter.emit('ideation-progress', projectId, {
phase: 'complete',
progress: 100,
message: 'Ideation generation complete'
});
// Load and emit the complete ideation session
if (storedProjectPath) {
try {
const ideationFilePath = path.join(
storedProjectPath,
'.auto-claude',
'ideation',
'ideation.json'
);
debugLog('[Agent Queue] Loading ideation session from:', ideationFilePath);
if (existsSync(ideationFilePath)) {
const loadSession = async (): Promise<void> => {
try {
const content = await fsPromises.readFile(ideationFilePath, 'utf-8');
const rawSession = JSON.parse(content);
const session = transformSessionFromSnakeCase(rawSession, projectId);
debugLog('[Agent Queue] Loaded ideation session:', {
totalIdeas: session.ideas?.length || 0
});
this.emitter.emit('ideation-complete', projectId, session);
} catch (err) {
debugError('[Ideation] Failed to load ideation session:', err);
this.emitter.emit('ideation-error', projectId,
`Failed to load ideation session: ${err instanceof Error ? err.message : 'Unknown error'}`);
}
};
loadSession().catch((err: unknown) => {
debugError('[Agent Queue] Unhandled error loading ideation session:', err);
// Load and emit the complete ideation session
if (storedProjectPath) {
try {
const ideationFilePath = path.join(
storedProjectPath,
'.auto-claude',
'ideation',
'ideation.json'
);
debugLog('[Agent Queue] Loading ideation session from:', ideationFilePath);
if (existsSync(ideationFilePath)) {
const loadSession = async (): Promise<void> => {
try {
const content = await fsPromises.readFile(ideationFilePath, 'utf-8');
const rawSession = JSON.parse(content);
const session = transformSessionFromSnakeCase(rawSession, projectId);
debugLog('[Agent Queue] Loaded ideation session:', {
totalIdeas: session.ideas?.length || 0
});
} else {
debugError('[Ideation] ideation.json not found at:', ideationFilePath);
this.emitter.emit('ideation-complete', projectId, session);
} catch (err) {
debugError('[Ideation] Failed to load ideation session:', err);
this.emitter.emit('ideation-error', projectId,
'Ideation completed but session file not found. Ideas may have been saved to individual type files.');
`Failed to load ideation session: ${err instanceof Error ? err.message : 'Unknown error'}`);
}
} catch (err) {
debugError('[Ideation] Unexpected error in ideation completion:', err);
this.emitter.emit('ideation-error', projectId,
`Failed to load ideation session: ${err instanceof Error ? err.message : 'Unknown error'}`);
}
};
loadSession().catch((err: unknown) => {
debugError('[Agent Queue] Unhandled error loading ideation session:', err);
});
} else {
debugError('[Ideation] No project path available to load session');
debugError('[Ideation] ideation.json not found at:', ideationFilePath);
this.emitter.emit('ideation-error', projectId,
'Ideation completed but project path unavailable');
'Ideation completed but session file not found. Ideas may have been saved to individual type files.');
}
} else {
debugError('[Agent Queue] Ideation generation failed:', { projectId, code });
this.emitter.emit('ideation-error', projectId, `Ideation generation failed with exit code ${code}`);
} catch (err) {
debugError('[Ideation] Unexpected error in ideation completion:', err);
this.emitter.emit('ideation-error', projectId,
`Failed to load ideation session: ${err instanceof Error ? err.message : 'Unknown error'}`);
}
});
// Handle process error
childProcess.on('error', (err: Error) => {
console.error('[Ideation] Process error:', err.message);
this.state.deleteProcess(projectId);
this.emitter.emit('ideation-error', projectId, err.message);
});
},
onError: (error: Error) => {
debugError('[Agent Queue] Failed to spawn ideation process:', error);
this.emitter.emit('ideation-error', projectId, error.message);
} else {
debugError('[Ideation] No project path available to load session');
this.emitter.emit('ideation-error', projectId,
'Ideation completed but project path unavailable');
}
} else {
debugError('[Agent Queue] Ideation generation failed:', { projectId, code });
this.emitter.emit('ideation-error', projectId, `Ideation generation failed with exit code ${code}`);
}
});
debugLog('[Agent Queue] Ideation spawn request enqueued:', { spawnId, projectId });
// Handle process error
childProcess.on('error', (err: Error) => {
console.error('[Ideation] Process error:', err.message);
this.state.deleteProcess(projectId);
this.emitter.emit('ideation-error', projectId, err.message);
});
}
/**
@@ -827,7 +691,7 @@ export class AgentQueueManager {
const combinedEnv = this.processManager.getCombinedEnv(projectPath);
// Get best available Claude profile environment (automatically handles rate limits)
const profileResult = await getBestAvailableProfileEnv();
const profileResult = getBestAvailableProfileEnv();
const profileEnv = profileResult.env;
// Get active API profile environment variables
@@ -837,7 +701,7 @@ export class AgentQueueManager {
const oauthModeClearVars = getOAuthModeClearVars(apiProfileEnv);
// Get Python path from process manager (uses venv if configured)
const _pythonPath = this.processManager.getPythonPath();
const pythonPath = this.processManager.getPythonPath();
// Get Python environment from pythonEnvManager (includes bundled site-packages)
const pythonEnv = pythonEnvManager.getPythonEnv();
@@ -872,6 +736,12 @@ export class AgentQueueManager {
PYTHONUTF8: '1'
};
// Normalize PATH key to a single uppercase 'PATH' entry.
// On Windows, process.env spread produces 'Path' while pythonEnv may write 'PATH',
// resulting in duplicate keys in the final object. Without normalization the child
// process inherits both keys, which can cause tool-not-found errors (#1661).
normalizeEnvPathKey(finalEnv as Record<string, string | undefined>);
// Debug: Show OAuth token source (token values intentionally omitted for security - AC4)
const tokenSource = profileEnv['CLAUDE_CODE_OAUTH_TOKEN']
? 'Electron app profile'
@@ -882,223 +752,218 @@ export class AgentQueueManager {
hasToken
});
// Enqueue the spawn request for sequential processing
// The queue will call executeRoadmapSpawn() when it's this request's turn
this.spawnQueue.enqueue({
id: String(spawnId),
type: 'roadmap',
projectId,
projectPath,
args,
env: finalEnv as Record<string, string>,
// Parse Python command to handle space-separated commands like "py -3"
const [pythonCommand, pythonBaseArgs] = parsePythonCommand(pythonPath);
const childProcess = spawn(pythonCommand, [...pythonBaseArgs, ...args], {
cwd,
onSpawn: async (childProcess) => {
debugLog('[Agent Queue] Roadmap process spawned from queue:', { spawnId, projectId, pid: childProcess.pid });
env: finalEnv
});
// Track progress through output
let progressPhase = 'analyzing';
let progressPercent = 10;
// Collect output for rate limit detection
let allRoadmapOutput = '';
// Track startedAt timestamp for progress persistence
const roadmapStartedAt = new Date().toISOString();
this.state.addProcess(projectId, {
taskId: projectId,
process: childProcess,
startedAt: new Date(),
projectPath, // Store project path for loading roadmap on completion
spawnId,
queueProcessType: 'roadmap'
});
// Persist initial progress state (debounced - will execute immediately due to leading: true)
this.debouncedPersistRoadmapProgress(
projectPath,
progressPhase,
progressPercent,
'Starting roadmap generation...',
roadmapStartedAt,
true
);
// Track progress through output
let progressPhase = 'analyzing';
let progressPercent = 10;
// Collect output for rate limit detection
let allRoadmapOutput = '';
// Track startedAt timestamp for progress persistence
const roadmapStartedAt = new Date().toISOString();
// Helper to emit logs - split multi-line output into individual log lines
const emitLogs = (log: string) => {
const lines = log.split('\n').filter(line => line.trim().length > 0);
for (const line of lines) {
const trimmed = line.trim();
if (trimmed.length > 0) {
this.emitter.emit('roadmap-log', projectId, trimmed);
}
}
};
// Persist initial progress state (debounced - will execute immediately due to leading: true)
this.debouncedPersistRoadmapProgress(
projectPath,
progressPhase,
progressPercent,
'Starting roadmap generation...',
roadmapStartedAt,
true
);
// Handle stdout - explicitly decode as UTF-8 for cross-platform Unicode support
childProcess.stdout?.on('data', (data: Buffer) => {
const log = data.toString('utf-8');
// Collect output for rate limit detection (keep last 10KB)
allRoadmapOutput = (allRoadmapOutput + log).slice(-10000);
// Helper to emit logs - split multi-line output into individual log lines
const emitLogs = (log: string) => {
const lines = log.split('\n').filter(line => line.trim().length > 0);
for (const line of lines) {
const trimmed = line.trim();
if (trimmed.length > 0) {
this.emitter.emit('roadmap-log', projectId, trimmed);
}
}
};
// Emit all log lines for debugging
emitLogs(log);
// Handle stdout - explicitly decode as UTF-8 for cross-platform Unicode support
childProcess.stdout?.on('data', (data: Buffer) => {
const log = data.toString('utf-8');
// Collect output for rate limit detection (keep last 10KB)
allRoadmapOutput = (allRoadmapOutput + log).slice(-10000);
// Parse progress using AgentEvents
const progressUpdate = this.events.parseRoadmapProgress(log, progressPhase, progressPercent);
progressPhase = progressUpdate.phase;
progressPercent = progressUpdate.progress;
// Emit all log lines for debugging
emitLogs(log);
// Get status message for display
const statusMessage = formatStatusMessage(log);
// Parse progress using AgentEvents
const progressUpdate = this.events.parseRoadmapProgress(log, progressPhase, progressPercent);
progressPhase = progressUpdate.phase;
progressPercent = progressUpdate.progress;
// Persist progress to disk for recovery after restart (debounced to limit writes)
this.debouncedPersistRoadmapProgress(
projectPath,
progressPhase,
progressPercent,
statusMessage,
roadmapStartedAt,
true
);
// Get status message for display
const statusMessage = formatStatusMessage(log);
// Emit progress update
this.emitter.emit('roadmap-progress', projectId, {
phase: progressPhase,
progress: progressPercent,
message: statusMessage
// Persist progress to disk for recovery after restart (debounced to limit writes)
this.debouncedPersistRoadmapProgress(
projectPath,
progressPhase,
progressPercent,
statusMessage,
roadmapStartedAt,
true
);
// Emit progress update
this.emitter.emit('roadmap-progress', projectId, {
phase: progressPhase,
progress: progressPercent,
message: statusMessage
});
});
// Handle stderr - explicitly decode as UTF-8
childProcess.stderr?.on('data', (data: Buffer) => {
const log = data.toString('utf-8');
// Collect stderr for rate limit detection too
allRoadmapOutput = (allRoadmapOutput + log).slice(-10000);
console.error('[Roadmap STDERR]', log);
emitLogs(log);
const statusMessage = formatStatusMessage(log);
// Persist progress to disk (debounced - also on stderr to show activity)
this.debouncedPersistRoadmapProgress(
projectPath,
progressPhase,
progressPercent,
statusMessage,
roadmapStartedAt,
true
);
this.emitter.emit('roadmap-progress', projectId, {
phase: progressPhase,
progress: progressPercent,
message: statusMessage
});
});
// Handle process exit
childProcess.on('exit', (code: number | null) => {
debugLog('[Agent Queue] Roadmap process exited:', { projectId, code, spawnId });
// Check if this process was intentionally stopped by the user
const wasIntentionallyStopped = this.state.wasSpawnKilled(spawnId);
if (wasIntentionallyStopped) {
debugLog('[Agent Queue] Roadmap process was intentionally stopped, ignoring exit');
this.state.clearKilledSpawn(spawnId);
// Clear progress file on intentional stop
this.clearRoadmapProgress(projectPath);
// Note: Don't call deleteProcess here - killProcess() already deleted it.
// A new process with the same projectId may have been started.
return;
}
// Get the stored project path before deleting from map
const processInfo = this.state.getProcess(projectId);
const storedProjectPath = processInfo?.projectPath;
this.state.deleteProcess(projectId);
// Check for rate limit if process failed
if (code !== 0) {
debugLog('[Agent Queue] Checking for rate limit (non-zero exit)');
const rateLimitDetection = detectRateLimit(allRoadmapOutput);
if (rateLimitDetection.isRateLimited) {
debugLog('[Agent Queue] Rate limit detected for roadmap');
const rateLimitInfo = createSDKRateLimitInfo('roadmap', rateLimitDetection, {
projectId
});
this.emitter.emit('sdk-rate-limit', rateLimitInfo);
}
}
if (code === 0) {
debugLog('[Agent Queue] Roadmap generation completed successfully');
this.emitter.emit('roadmap-progress', projectId, {
phase: 'complete',
progress: 100,
message: 'Roadmap generation complete'
});
// Handle stderr - explicitly decode as UTF-8
childProcess.stderr?.on('data', (data: Buffer) => {
const log = data.toString('utf-8');
// Collect stderr for rate limit detection too
allRoadmapOutput = (allRoadmapOutput + log).slice(-10000);
console.error('[Roadmap STDERR]', log);
emitLogs(log);
// Clear progress file on successful completion
this.clearRoadmapProgress(projectPath);
const statusMessage = formatStatusMessage(log);
// Persist progress to disk (debounced - also on stderr to show activity)
this.debouncedPersistRoadmapProgress(
projectPath,
progressPhase,
progressPercent,
statusMessage,
roadmapStartedAt,
true
);
this.emitter.emit('roadmap-progress', projectId, {
phase: progressPhase,
progress: progressPercent,
message: statusMessage
});
});
// Handle process exit
childProcess.on('exit', (code: number | null) => {
debugLog('[Agent Queue] Roadmap process exited:', { projectId, code, spawnId });
// Check if this process was intentionally stopped by the user
const wasIntentionallyStopped = this.state.wasSpawnKilled(spawnId);
if (wasIntentionallyStopped) {
debugLog('[Agent Queue] Roadmap process was intentionally stopped, ignoring exit');
this.state.clearKilledSpawn(spawnId);
// Clear progress file on intentional stop
this.clearRoadmapProgress(projectPath);
// Note: Don't call deleteProcess here - killProcess() already deleted it.
// A new process with the same projectId may have been started.
return;
}
// Get the stored project path before deleting from map
const processInfo = this.state.getProcess(projectId);
const storedProjectPath = processInfo?.projectPath;
this.state.deleteProcess(projectId);
// Check for rate limit if process failed
if (code !== 0) {
debugLog('[Agent Queue] Checking for rate limit (non-zero exit)');
const rateLimitDetection = detectRateLimit(allRoadmapOutput);
if (rateLimitDetection.isRateLimited) {
debugLog('[Agent Queue] Rate limit detected for roadmap');
const rateLimitInfo = createSDKRateLimitInfo('roadmap', rateLimitDetection, {
projectId
});
this.emitter.emit('sdk-rate-limit', rateLimitInfo);
}
}
if (code === 0) {
debugLog('[Agent Queue] Roadmap generation completed successfully');
this.emitter.emit('roadmap-progress', projectId, {
phase: 'complete',
progress: 100,
message: 'Roadmap generation complete'
});
// Clear progress file on successful completion
this.clearRoadmapProgress(projectPath);
// Load and emit the complete roadmap
if (storedProjectPath) {
try {
const roadmapFilePath = path.join(
storedProjectPath,
'.auto-claude',
'roadmap',
'roadmap.json'
);
debugLog('[Agent Queue] Loading roadmap from:', roadmapFilePath);
if (existsSync(roadmapFilePath)) {
const loadRoadmap = async (): Promise<void> => {
try {
const content = await fsPromises.readFile(roadmapFilePath, 'utf-8');
const rawRoadmap = JSON.parse(content);
const transformedRoadmap = transformRoadmapFromSnakeCase(rawRoadmap, projectId);
debugLog('[Agent Queue] Loaded roadmap:', {
featuresCount: transformedRoadmap.features?.length || 0,
phasesCount: transformedRoadmap.phases?.length || 0
});
this.emitter.emit('roadmap-complete', projectId, transformedRoadmap);
} catch (err) {
debugError('[Roadmap] Failed to load roadmap:', err);
this.emitter.emit('roadmap-error', projectId,
`Failed to load roadmap: ${err instanceof Error ? err.message : 'Unknown error'}`);
}
};
loadRoadmap().catch((err: unknown) => {
debugError('[Agent Queue] Unhandled error loading roadmap:', err);
// Load and emit the complete roadmap
if (storedProjectPath) {
try {
const roadmapFilePath = path.join(
storedProjectPath,
'.auto-claude',
'roadmap',
'roadmap.json'
);
debugLog('[Agent Queue] Loading roadmap from:', roadmapFilePath);
if (existsSync(roadmapFilePath)) {
const loadRoadmap = async (): Promise<void> => {
try {
const content = await fsPromises.readFile(roadmapFilePath, 'utf-8');
const rawRoadmap = JSON.parse(content);
const transformedRoadmap = transformRoadmapFromSnakeCase(rawRoadmap, projectId);
debugLog('[Agent Queue] Loaded roadmap:', {
featuresCount: transformedRoadmap.features?.length || 0,
phasesCount: transformedRoadmap.phases?.length || 0
});
} else {
debugError('[Roadmap] roadmap.json not found at:', roadmapFilePath);
this.emitter.emit('roadmap-complete', projectId, transformedRoadmap);
} catch (err) {
debugError('[Roadmap] Failed to load roadmap:', err);
this.emitter.emit('roadmap-error', projectId,
'Roadmap completed but file not found.');
`Failed to load roadmap: ${err instanceof Error ? err.message : 'Unknown error'}`);
}
} catch (err) {
debugError('[Roadmap] Unexpected error in roadmap completion:', err);
this.emitter.emit('roadmap-error', projectId,
`Unexpected error: ${err instanceof Error ? err.message : 'Unknown error'}`);
}
};
loadRoadmap().catch((err: unknown) => {
debugError('[Agent Queue] Unhandled error loading roadmap:', err);
});
} else {
debugError('[Roadmap] No project path available for roadmap completion');
this.emitter.emit('roadmap-error', projectId, 'Roadmap completed but project path not found.');
debugError('[Roadmap] roadmap.json not found at:', roadmapFilePath);
this.emitter.emit('roadmap-error', projectId,
'Roadmap completed but file not found.');
}
} else {
debugError('[Agent Queue] Roadmap generation failed:', { projectId, code });
// Clear progress file on error
this.clearRoadmapProgress(projectPath);
this.emitter.emit('roadmap-error', projectId, `Roadmap generation failed with exit code ${code}`);
} catch (err) {
debugError('[Roadmap] Unexpected error in roadmap completion:', err);
this.emitter.emit('roadmap-error', projectId,
`Unexpected error: ${err instanceof Error ? err.message : 'Unknown error'}`);
}
});
// Handle process error
childProcess.on('error', (err: Error) => {
console.error('[Roadmap] Process error:', err.message);
this.state.deleteProcess(projectId);
// Clear progress file on process error
this.clearRoadmapProgress(projectPath);
this.emitter.emit('roadmap-error', projectId, err.message);
});
},
onError: (error: Error) => {
debugError('[Agent Queue] Failed to spawn roadmap process:', error);
this.emitter.emit('roadmap-error', projectId, error.message);
} else {
debugError('[Roadmap] No project path available for roadmap completion');
this.emitter.emit('roadmap-error', projectId, 'Roadmap completed but project path not found.');
}
} else {
debugError('[Agent Queue] Roadmap generation failed:', { projectId, code });
// Clear progress file on error
this.clearRoadmapProgress(projectPath);
this.emitter.emit('roadmap-error', projectId, `Roadmap generation failed with exit code ${code}`);
}
});
debugLog('[Agent Queue] Roadmap spawn request enqueued:', { spawnId, projectId });
// Handle process error
childProcess.on('error', (err: Error) => {
console.error('[Roadmap] Process error:', err.message);
this.state.deleteProcess(projectId);
// Clear progress file on process error
this.clearRoadmapProgress(projectPath);
this.emitter.emit('roadmap-error', projectId, err.message);
});
}
/**
+164 -1
View File
@@ -4,7 +4,7 @@
*/
import { describe, it, expect } from 'vitest';
import { getOAuthModeClearVars } from './env-utils';
import { getOAuthModeClearVars, normalizeEnvPathKey, mergePythonEnvPath } from './env-utils';
describe('getOAuthModeClearVars', () => {
describe('OAuth mode (no active API profile)', () => {
@@ -132,3 +132,166 @@ describe('getOAuthModeClearVars', () => {
});
});
});
describe('normalizeEnvPathKey', () => {
it('should leave an already-uppercase PATH key untouched', () => {
const env: Record<string, string | undefined> = { PATH: '/usr/bin:/bin', HOME: '/home/user' };
normalizeEnvPathKey(env);
expect(env).toEqual({ PATH: '/usr/bin:/bin', HOME: '/home/user' });
});
it('should rename a lowercase-variant "Path" key to "PATH"', () => {
const env: Record<string, string | undefined> = { Path: 'C:\\Windows\\system32', HOME: '/home/user' };
normalizeEnvPathKey(env);
expect(env['PATH']).toBe('C:\\Windows\\system32');
expect('Path' in env).toBe(false);
});
it('should prefer existing "PATH" and remove "Path" when both keys coexist', () => {
// Simulates process.env spread ('Path') after getAugmentedEnv writes ('PATH')
const env: Record<string, string | undefined> = {
Path: 'C:\\old',
PATH: 'C:\\Windows\\system32;C:\\augmented',
HOME: '/home/user'
};
normalizeEnvPathKey(env);
expect(env.PATH).toBe('C:\\Windows\\system32;C:\\augmented');
expect('Path' in env).toBe(false);
});
it('should remove all case-variant PATH duplicates when PATH is already present', () => {
const env: Record<string, string | undefined> = {
PATH: '/correct',
Path: '/old1',
path: '/old2'
};
normalizeEnvPathKey(env);
expect(env.PATH).toBe('/correct');
expect('Path' in env).toBe(false);
expect('path' in env).toBe(false);
});
it('should handle env with no PATH-like key gracefully', () => {
const env: Record<string, string | undefined> = { HOME: '/home/user', SHELL: '/bin/zsh' };
normalizeEnvPathKey(env);
expect(env).toEqual({ HOME: '/home/user', SHELL: '/bin/zsh' });
});
it('should return the same env object reference (mutates in place)', () => {
const env: Record<string, string | undefined> = { PATH: '/usr/bin' };
const result = normalizeEnvPathKey(env);
expect(result).toBe(env);
});
});
describe('mergePythonEnvPath - Windows PATH merge logic (#1661)', () => {
const SEP = ';'; // Use Windows separator for these tests
it('should prepend pythonEnv-only entries to the augmented PATH', () => {
const env: Record<string, string | undefined> = {
PATH: 'C:\\npm;C:\\homebrew'
};
const mergedPythonEnv: Record<string, string | undefined> = {
PATH: 'C:\\pywin32_system32;C:\\npm;C:\\homebrew'
};
mergePythonEnvPath(env, mergedPythonEnv, SEP);
// pywin32_system32 is unique to pythonEnv, so it should be prepended
expect(mergedPythonEnv.PATH).toBe('C:\\pywin32_system32;C:\\npm;C:\\homebrew');
});
it('should deduplicate entries that already exist in augmented PATH', () => {
const env: Record<string, string | undefined> = {
PATH: 'C:\\npm;C:\\homebrew;C:\\pywin32_system32'
};
const mergedPythonEnv: Record<string, string | undefined> = {
PATH: 'C:\\pywin32_system32;C:\\npm'
};
mergePythonEnvPath(env, mergedPythonEnv, SEP);
// All pythonEnv entries are already in env.PATH, so mergedPythonEnv.PATH should equal env.PATH
expect(mergedPythonEnv.PATH).toBe('C:\\npm;C:\\homebrew;C:\\pywin32_system32');
});
it('should normalize Windows-style "Path" key in pythonEnv to "PATH"', () => {
const env: Record<string, string | undefined> = {
PATH: 'C:\\npm;C:\\homebrew'
};
// pythonEnv uses 'Path' (Windows native casing)
const mergedPythonEnv: Record<string, string | undefined> = {
Path: 'C:\\pywin32_system32;C:\\npm'
};
mergePythonEnvPath(env, mergedPythonEnv, SEP);
// 'Path' should be normalized to 'PATH' and pythonEnv-specific entry prepended
expect('Path' in mergedPythonEnv).toBe(false);
expect(mergedPythonEnv.PATH).toBe('C:\\pywin32_system32;C:\\npm;C:\\homebrew');
});
it('should normalize Windows-style "Path" in env and deduplicate duplicates', () => {
// Simulates process.env spread ('Path') + getAugmentedEnv write ('PATH') leaving both
const env: Record<string, string | undefined> = {
Path: 'C:\\old',
PATH: 'C:\\npm;C:\\homebrew'
};
const mergedPythonEnv: Record<string, string | undefined> = {
PATH: 'C:\\pywin32_system32;C:\\npm'
};
mergePythonEnvPath(env, mergedPythonEnv, SEP);
// env 'Path' should be removed; augmented 'PATH' value preserved
expect('Path' in env).toBe(false);
expect(env.PATH).toBe('C:\\npm;C:\\homebrew');
// Only the unique pywin32_system32 entry prepended
expect(mergedPythonEnv.PATH).toBe('C:\\pywin32_system32;C:\\npm;C:\\homebrew');
});
it('should use env.PATH unchanged when pythonEnv has no unique entries', () => {
const env: Record<string, string | undefined> = {
PATH: 'C:\\npm;C:\\homebrew'
};
const mergedPythonEnv: Record<string, string | undefined> = {
PATH: 'C:\\npm;C:\\homebrew'
};
mergePythonEnvPath(env, mergedPythonEnv, SEP);
expect(mergedPythonEnv.PATH).toBe('C:\\npm;C:\\homebrew');
});
it('should work correctly with Unix colon separator', () => {
const unixSep = ':';
const env: Record<string, string | undefined> = {
PATH: '/usr/bin:/bin'
};
const mergedPythonEnv: Record<string, string | undefined> = {
PATH: '/opt/pyenv/shims:/usr/bin:/bin'
};
mergePythonEnvPath(env, mergedPythonEnv, unixSep);
// /opt/pyenv/shims is unique and should be prepended
expect(mergedPythonEnv.PATH).toBe('/opt/pyenv/shims:/usr/bin:/bin');
});
it('should handle missing PATH in pythonEnv gracefully (no-op)', () => {
const env: Record<string, string | undefined> = {
PATH: 'C:\\npm;C:\\homebrew'
};
// pythonEnv has no PATH at all
const mergedPythonEnv: Record<string, string | undefined> = {
PYTHONPATH: '/site-packages'
};
mergePythonEnvPath(env, mergedPythonEnv, SEP);
// Nothing should change
expect(mergedPythonEnv.PATH).toBeUndefined();
expect(mergedPythonEnv.PYTHONPATH).toBe('/site-packages');
expect(env.PATH).toBe('C:\\npm;C:\\homebrew');
});
});
+82
View File
@@ -2,6 +2,88 @@
* Utility functions for managing environment variables in agent spawning
*/
/**
* Normalize the PATH key in an environment object to a single uppercase 'PATH' key.
*
* On Windows, process.env spreads as 'Path' (the native casing) while getAugmentedEnv()
* writes 'PATH'. Without normalization, both keys coexist in the object and the child
* process receives duplicate PATH entries, causing tool-not-found errors like #1661.
*
* Mutates the provided env object in place and returns it for convenience.
*
* @param env - Mutable environment record to normalize
* @returns The same env object with PATH normalized to uppercase
*/
export function normalizeEnvPathKey(env: Record<string, string | undefined>): Record<string, string | undefined> {
// If 'PATH' already exists, delete all other case-variant keys (e.g. 'Path')
if ('PATH' in env) {
for (const key of Object.keys(env)) {
if (key !== 'PATH' && key.toUpperCase() === 'PATH') {
delete env[key];
}
}
return env;
}
// No uppercase 'PATH' key - find the first case-variant and rename it
const pathKey = Object.keys(env).find(k => k.toUpperCase() === 'PATH');
if (pathKey) {
env['PATH'] = env[pathKey];
delete env[pathKey];
// Remove any remaining case-variant keys
for (const key of Object.keys(env)) {
if (key !== 'PATH' && key.toUpperCase() === 'PATH') {
delete env[key];
}
}
}
return env;
}
/**
* Merge pythonEnv PATH entries with the augmented PATH in env, deduplicating entries.
*
* pythonEnv may carry its own PATH (e.g. pywin32_system32 prepended on Windows).
* Simply spreading pythonEnv after env would overwrite the augmented PATH (which
* includes npm globals, Homebrew, etc.), causing "Claude code not found" (#1661).
*
* Strategy:
* 1. Normalize PATH key casing in both env and pythonEnv to uppercase 'PATH'.
* 2. Extract only pythonEnv PATH entries that are not already in env.PATH.
* 3. Prepend those unique entries to env.PATH and store the result in pythonEnv.PATH.
*
* Mutates mergedPythonEnv in place (caller should pass a shallow copy if immutability is needed).
*
* @param env - The base environment (already augmented with tool paths)
* @param mergedPythonEnv - Shallow copy of pythonEnv to merge PATH into
* @param pathSep - Platform path separator (';' on Windows, ':' elsewhere)
*/
export function mergePythonEnvPath(
env: Record<string, string | undefined>,
mergedPythonEnv: Record<string, string | undefined>,
pathSep: string
): void {
// Normalize PATH key to uppercase in both objects
normalizeEnvPathKey(env);
normalizeEnvPathKey(mergedPythonEnv);
if (mergedPythonEnv['PATH'] && env['PATH']) {
const augmentedPathEntries = new Set(
(env['PATH'] as string).split(pathSep).filter(Boolean)
);
// Extract only new entries from pythonEnv.PATH that aren't already in the augmented PATH
const pythonPathEntries = (mergedPythonEnv['PATH'] as string)
.split(pathSep)
.filter(entry => entry && !augmentedPathEntries.has(entry));
// Prepend python-specific paths (e.g., pywin32_system32) to the augmented PATH
mergedPythonEnv['PATH'] = pythonPathEntries.length > 0
? [...pythonPathEntries, env['PATH'] as string].join(pathSep)
: env['PATH'] as string;
}
}
/**
* Get environment variables to clear ANTHROPIC_* vars when in OAuth mode
*
@@ -1,386 +0,0 @@
/**
* Integration Stress Test for Sequential Agent Spawning
*
* Verifies that SpawnQueue prevents ~/.claude.json file corruption under concurrent load.
* Tests rapid spawning of multiple agents and verifies sequential execution.
*
* Key scenarios:
* - Stress test: 10 agents spawned rapidly
* - Sequential verification: agents don't overlap
* - Queue state consistency during high load
*/
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { SpawnQueue, type SpawnFunction } from './spawn-queue';
import type { ChildProcess } from 'child_process';
import type { Readable, Writable } from 'stream';
describe('Sequential Agent Spawning - Integration Stress Test', () => {
let queue: SpawnQueue;
let mockSpawnFn: SpawnFunction;
let concurrentProcesses: Map<string, { start: number; end: number }>;
/**
* Create a mock child process that exits after a delay
* Tracks start/end times for overlap detection
*/
const createMockProcess = (
id: string,
exitDelay: number = 10
): ChildProcess => {
const startTime = Date.now();
const process = {
on: vi.fn((event: string, callback: (...args: unknown[]) => void) => {
if (event === 'exit') {
setTimeout(() => {
const endTime = Date.now();
concurrentProcesses.set(id, { start: startTime, end: endTime });
callback(0);
}, exitDelay);
}
return process;
}),
once: vi.fn((event: string, callback: (...args: unknown[]) => void) => {
if (event === 'exit') {
setTimeout(() => {
const endTime = Date.now();
concurrentProcesses.set(id, { start: startTime, end: endTime });
callback(0);
}, exitDelay);
}
return process;
}),
kill: vi.fn(),
pid: Math.floor(Math.random() * 100000),
exitCode: null,
signalCode: null,
stdin: null,
stdout: null,
stderr: null,
stdio: [null, null, null] as [
Writable | null,
Readable | null,
Readable | null
],
connected: false
} as unknown as ChildProcess;
return process;
};
/**
* Helper to create a spawn request
*/
const createRequest = (
id: string,
_exitDelay: number = 10
) => ({
id,
type: 'test',
onSpawn: vi.fn(async () => { /* noop */ }),
onError: vi.fn(),
projectId: `project-${id}`,
projectPath: `/test/path/${id}`,
args: ['--test', id],
env: { TEST_ID: id },
cwd: '/test/cwd'
});
beforeEach(() => {
concurrentProcesses = new Map();
// Suppress console.log output in tests
vi.spyOn(console, 'log').mockImplementation(() => { /* noop */ });
// Mock spawn function that creates processes with different exit delays
mockSpawnFn = vi.fn(async (id: string) => {
// Use deterministic delays to avoid non-determinism
const delays = [10, 15, 20, 25, 30];
const index = parseInt(id.split('-')[1], 10) || 0;
const delay = delays[index % delays.length];
return createMockProcess(id, delay);
}) as SpawnFunction;
queue = new SpawnQueue(mockSpawnFn);
});
afterEach(() => {
vi.clearAllMocks();
});
describe('Stress Test - Rapid Concurrent Spawns', () => {
it('should handle 10 rapid spawn requests without corruption', async () => {
const numAgents = 10;
const executionOrder: string[] = [];
// Enqueue 10 agents rapidly
for (let i = 0; i < numAgents; i++) {
const id = `agent-${i}`;
const request = createRequest(id);
request.onSpawn = vi.fn(async () => {
executionOrder.push(id);
});
queue.enqueue(request);
}
// Wait for all to complete
await queue.drain();
// Verify all agents executed
expect(executionOrder).toHaveLength(numAgents);
// Verify FIFO order
for (let i = 0; i < numAgents; i++) {
expect(executionOrder[i]).toBe(`agent-${i}`);
}
// Verify all spawn functions were called
expect(mockSpawnFn).toHaveBeenCalledTimes(numAgents);
});
it('should maintain queue integrity under high load', async () => {
const numAgents = 10;
let maxLengthDuringProcessing = 0;
// Create a request that tracks queue length during processing
const createTrackingRequest = (id: string) => {
const request = createRequest(id);
const originalOnSpawn = request.onSpawn;
request.onSpawn = vi.fn(async () => {
// Track max queue length during processing
if (queue.length > maxLengthDuringProcessing) {
maxLengthDuringProcessing = queue.length;
}
await originalOnSpawn();
});
return request;
};
// Enqueue all agents rapidly
for (let i = 0; i < numAgents; i++) {
queue.enqueue(createTrackingRequest(`agent-${i}`));
}
await queue.drain();
// Verify queue eventually emptied
expect(queue.length).toBe(0);
expect(queue.isProcessing).toBe(false);
// Verify queue held pending items during processing
expect(maxLengthDuringProcessing).toBeGreaterThan(0);
});
});
describe('Sequential Verification - No Overlap', () => {
it('should ensure agents execute sequentially without overlap', async () => {
const numAgents = 5;
// Enqueue agents with varying delays
for (let i = 0; i < numAgents; i++) {
queue.enqueue(createRequest(`agent-${i}`, 20));
}
await queue.drain();
// Verify we tracked all agents
expect(concurrentProcesses.size).toBe(numAgents);
// Check for overlaps: each agent should finish before the next starts
const sortedEntries = Array.from(concurrentProcesses.entries()).sort(
(a, b) => a[1].start - b[1].start
);
for (let i = 0; i < sortedEntries.length - 1; i++) {
const [_currentId, currentTimes] = sortedEntries[i];
const [_nextId, nextTimes] = sortedEntries[i + 1];
// Next agent should start after current agent finishes
// Add tolerance for timing precision
expect(nextTimes.start).toBeGreaterThanOrEqual(currentTimes.end - 1);
}
});
it('should track start and end times accurately', async () => {
const testId = 'test-agent';
let spawnedTime: number | null = null;
// Create a request that tracks timing
const request = createRequest(testId, 30);
// Override mockSpawnFn to track timing more accurately
mockSpawnFn = vi.fn(async () => {
const startTime = Date.now();
const process = createMockProcess(testId, 30);
// Track when the process is spawned
request.onSpawn = vi.fn(async () => {
spawnedTime = startTime;
});
return process;
}) as SpawnFunction;
queue = new SpawnQueue(mockSpawnFn);
queue.enqueue(request);
await queue.drain();
// Verify spawn time was captured
expect(spawnedTime).not.toBeNull();
// Verify the process completed
const times = concurrentProcesses.get(testId);
expect(times).toBeDefined();
// Exit should be after spawn
expect(times?.end).toBeGreaterThanOrEqual(spawnedTime!);
});
});
describe('Error Recovery Under Load', () => {
it('should continue processing after failures', async () => {
const successCount: string[] = [];
const failureCount: string[] = [];
const createFailableRequest = (id: string, shouldFail: boolean) => {
const request = createRequest(id);
request.onSpawn = vi.fn(async () => {
if (shouldFail) {
throw new Error(`Simulated failure for ${id}`);
}
successCount.push(id);
});
request.onError = vi.fn((error: Error) => {
failureCount.push(id);
expect(error.message).toContain('Simulated failure');
});
return request;
};
// Enqueue mix of successful and failing requests
queue.enqueue(createFailableRequest('agent-1', false));
queue.enqueue(createFailableRequest('agent-2', true));
queue.enqueue(createFailableRequest('agent-3', false));
queue.enqueue(createFailableRequest('agent-4', true));
queue.enqueue(createFailableRequest('agent-5', false));
await queue.drain();
// Verify all were processed
expect(successCount).toHaveLength(3);
expect(failureCount).toHaveLength(2);
// Verify processing continued despite failures
expect(successCount).toEqual(['agent-1', 'agent-3', 'agent-5']);
expect(failureCount).toEqual(['agent-2', 'agent-4']);
});
it('should handle all failures gracefully', async () => {
const numAgents = 5;
const errors: string[] = [];
const createFailingRequest = (id: string) => {
const request = createRequest(id);
request.onSpawn = vi.fn(async () => {
throw new Error(`Failure ${id}`);
});
request.onError = vi.fn((_error: Error) => {
errors.push(id);
});
return request;
};
// All requests fail
for (let i = 0; i < numAgents; i++) {
queue.enqueue(createFailingRequest(`agent-${i}`));
}
await queue.drain();
// Verify all errors were handled
expect(errors).toHaveLength(numAgents);
// Queue should still be empty and not processing
expect(queue.length).toBe(0);
expect(queue.isProcessing).toBe(false);
});
});
describe('Real-World Scenario Simulation', () => {
it('should simulate user rapidly triggering multiple ideations', async () => {
const userTriggeredIdeations: string[] = [];
// Simulate user clicking "Generate Ideation" 5 times rapidly
const triggerIdeation = async (index: number) => {
const projectId = `project-${index}`;
userTriggeredIdeations.push(projectId);
queue.enqueue({
id: `ideation-${index}`,
type: 'ideation',
projectId,
projectPath: `/projects/${projectId}`,
args: ['--ideation', '--types', 'improvements,performance'],
env: { PROJECT_ID: projectId },
cwd: '/auto-claude',
onSpawn: vi.fn(async () => {
// Ideation spawned
}),
onError: vi.fn((_error: Error) => {
// Ideation failed
})
});
};
// User rapidly triggers 5 ideations (within 100ms)
const startTime = Date.now();
await Promise.all(
Array.from({ length: 5 }, (_, i) => triggerIdeation(i))
);
const _triggerTime = Date.now() - startTime;
// Wait for all to complete
await queue.drain();
// Verify all were processed
expect(mockSpawnFn).toHaveBeenCalledTimes(5);
// Verify sequential execution
const sortedEntries = Array.from(concurrentProcesses.entries()).sort(
(a, b) => a[1].start - b[1].start
);
for (let i = 0; i < sortedEntries.length - 1; i++) {
const currentEnd = sortedEntries[i][1].end;
const nextStart = sortedEntries[i + 1][1].start;
expect(nextStart).toBeGreaterThanOrEqual(currentEnd);
}
});
});
describe('Performance Characteristics', () => {
it('should measure throughput under load', async () => {
const numAgents = 10;
const startTime = Date.now();
for (let i = 0; i < numAgents; i++) {
queue.enqueue(createRequest(`agent-${i}`, 5));
}
await queue.drain();
const totalTime = Date.now() - startTime;
// With 10 agents each taking ~5ms + overhead, sequential execution
// should take roughly 50-100ms (much slower than parallel, but safe)
expect(totalTime).toBeGreaterThan(40); // At least 40ms for sequential
expect(totalTime).toBeLessThan(500); // But should complete in reasonable time
// Verify all completed
expect(mockSpawnFn).toHaveBeenCalledTimes(numAgents);
});
});
});
@@ -1,320 +0,0 @@
/**
* Tests for SpawnQueue - Sequential Agent Spawning
*
* Tests the FIFO queue that ensures only one agent runs at a time
* to prevent ~/.claude.json race condition and file corruption.
*/
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { SpawnQueue, type SpawnFunction } from './spawn-queue';
import type { ChildProcess } from 'child_process';
import type { Readable, Writable } from 'stream';
describe('SpawnQueue', () => {
let queue: SpawnQueue;
let mockSpawnFn: SpawnFunction;
let mockChildProcess: ChildProcess;
// Helper to create a valid spawn request
const createRequest = (overrides: Partial<{
id: string;
type: string;
onSpawn: (process: ChildProcess) => Promise<void>;
onError: (error: Error) => void;
projectId: string;
projectPath: string;
args: string[];
env: Record<string, string>;
cwd: string;
}> = {}) => ({
id: 'test-id',
type: 'test',
onSpawn: vi.fn(async () => { /* noop */ }),
onError: vi.fn(),
projectId: 'test-project',
projectPath: '/test/path',
args: [],
env: {},
cwd: '/test/cwd',
...overrides
});
beforeEach(() => {
// Mock child process that exits successfully
mockChildProcess = {
on: vi.fn((event: string, callback: (...args: unknown[]) => void) => {
if (event === 'exit') {
// Simulate immediate exit for testing
setTimeout(() => callback(0), 0);
}
return mockChildProcess as ChildProcess;
}),
once: vi.fn((event: string, callback: (...args: unknown[]) => void) => {
if (event === 'exit') {
// Simulate immediate exit for testing
setTimeout(() => callback(0), 0);
}
return mockChildProcess as ChildProcess;
}),
kill: vi.fn(),
pid: 12345,
exitCode: null,
signalCode: null,
stdin: null,
stdout: null,
stderr: null,
stdio: [null, null, null] as [
Writable | null,
Readable | null,
Readable | null
],
connected: false
} as unknown as ChildProcess;
// Mock spawn function with proper type
mockSpawnFn = vi.fn().mockResolvedValue(mockChildProcess) as SpawnFunction;
// Create queue with mock spawn function
queue = new SpawnQueue(mockSpawnFn);
});
describe('Sequential Processing', () => {
it('should process items in FIFO order', async () => {
const executionOrder: string[] = [];
// Create three spawn requests that track execution order
const request1 = createRequest({
id: 'task-1',
onSpawn: vi.fn(async () => {
executionOrder.push('task-1');
})
});
const request2 = createRequest({
id: 'task-2',
onSpawn: vi.fn(async () => {
executionOrder.push('task-2');
})
});
const request3 = createRequest({
id: 'task-3',
onSpawn: vi.fn(async () => {
executionOrder.push('task-3');
})
});
// Enqueue all three items
queue.enqueue(request1);
queue.enqueue(request2);
queue.enqueue(request3);
// Wait for all to complete
await queue.drain();
// Verify they executed in FIFO order
expect(executionOrder).toEqual(['task-1', 'task-2', 'task-3']);
expect(request1.onSpawn).toHaveBeenCalledTimes(1);
expect(request2.onSpawn).toHaveBeenCalledTimes(1);
expect(request3.onSpawn).toHaveBeenCalledTimes(1);
});
it('should wait for each spawn to complete before starting next', async () => {
let task1Running = false;
let task2Started = false;
const request1 = createRequest({
id: 'task-1',
onSpawn: vi.fn(async () => {
task1Running = true;
// Simulate work
await new Promise(resolve => setTimeout(resolve, 50));
task1Running = false;
})
});
const request2 = createRequest({
id: 'task-2',
onSpawn: vi.fn(async () => {
task2Started = true;
// Task 2 should only start after task 1 completes
expect(task1Running).toBe(false);
})
});
queue.enqueue(request1);
queue.enqueue(request2);
await queue.drain();
expect(task1Running).toBe(false);
expect(task2Started).toBe(true);
});
});
describe('Error Recovery', () => {
it('should continue to next item when spawn fails', async () => {
const executionOrder: string[] = [];
// First request fails
const request1 = createRequest({
id: 'task-1',
onSpawn: vi.fn().mockRejectedValue(new Error('Spawn failed')),
onError: vi.fn((error: Error) => {
executionOrder.push('task-1-error');
expect(error.message).toBe('Spawn failed');
})
});
// Second request succeeds
const request2 = createRequest({
id: 'task-2',
onSpawn: vi.fn(async () => {
executionOrder.push('task-2');
})
});
queue.enqueue(request1);
queue.enqueue(request2);
await queue.drain();
// Verify both were processed in order
expect(executionOrder).toEqual(['task-1-error', 'task-2']);
expect(request1.onSpawn).toHaveBeenCalledTimes(1);
expect(request2.onSpawn).toHaveBeenCalledTimes(1);
expect(request1.onError).toHaveBeenCalledTimes(1);
expect(request2.onError).not.toHaveBeenCalled();
});
it('should handle multiple failures gracefully', async () => {
let errorCount = 0;
const failingRequest = createRequest({
id: `task-${errorCount}`,
onSpawn: vi.fn().mockRejectedValue(new Error('Failed')),
onError: vi.fn((_error: Error) => {
errorCount++;
})
});
// Enqueue multiple failing requests
queue.enqueue({ ...failingRequest, id: 'task-1' });
queue.enqueue({ ...failingRequest, id: 'task-2' });
queue.enqueue({ ...failingRequest, id: 'task-3' });
await queue.drain();
expect(errorCount).toBe(3);
});
});
describe('Empty Queue', () => {
it('should handle drain gracefully when queue is empty', async () => {
// Drain should resolve immediately with no items
await expect(queue.drain()).resolves.toBeUndefined();
});
it('should return zero length for empty queue', () => {
expect(queue.length).toBe(0);
});
it('should not be processing when queue is empty', () => {
expect(queue.isProcessing).toBe(false);
});
});
describe('Queue State', () => {
it('should track queue length correctly', async () => {
expect(queue.length).toBe(0);
// Enqueue first item - it will start processing immediately
queue.enqueue(createRequest({
id: 'task-1',
onSpawn: vi.fn(async () => {
// While task-1 is processing, check that subsequent items are queued
queue.enqueue(createRequest({
id: 'task-2',
onSpawn: vi.fn()
}));
// Task 2 should be queued while task 1 processes
expect(queue.length).toBe(1);
queue.enqueue(createRequest({
id: 'task-3',
onSpawn: vi.fn()
}));
// Now both task 2 and task 3 are queued
expect(queue.length).toBe(2);
})
}));
// Wait for all to complete
await queue.drain();
// Queue should be empty after all processing
expect(queue.length).toBe(0);
});
it('should track processing state', async () => {
expect(queue.isProcessing).toBe(false);
const request = createRequest({
id: 'task-1',
onSpawn: vi.fn(async () => {
// Check that processing is true during execution
expect(queue.isProcessing).toBe(true);
})
});
queue.enqueue(request);
expect(queue.isProcessing).toBe(true);
await queue.drain();
expect(queue.isProcessing).toBe(false);
});
});
describe('Spawn Function Integration', () => {
it('should call spawn function with correct arguments', async () => {
const request = createRequest({
id: 'task-1',
projectId: 'project-1',
projectPath: '/path/to/project',
args: ['--test', '--verbose'],
env: { TEST_VAR: 'test-value' },
cwd: '/test/cwd'
});
queue.enqueue(request);
await queue.drain();
expect(mockSpawnFn).toHaveBeenCalledTimes(1);
expect(mockSpawnFn).toHaveBeenCalledWith(
'task-1',
'/path/to/project',
['--test', '--verbose'],
{ TEST_VAR: 'test-value' },
'project-1',
'/test/cwd'
);
});
it('should pass spawned process to onSpawn callback', async () => {
let receivedProcess: import('child_process').ChildProcess | undefined;
const request = createRequest({
id: 'task-1',
onSpawn: vi.fn(async (process: import('child_process').ChildProcess) => {
receivedProcess = process;
})
});
queue.enqueue(request);
await queue.drain();
expect(receivedProcess).toBeDefined();
expect(receivedProcess?.pid).toBe(12345);
});
});
});
-177
View File
@@ -1,177 +0,0 @@
/**
* FIFO Queue for Sequential Agent Spawning
*
* Ensures only one agent spawns at a time to prevent ~/.claude.json
* race condition and file corruption from concurrent writes.
*
* Key behaviors:
* - Processes items FIFO (first in, first out)
* - Waits for each agent to exit before spawning the next
* - Continues to next item if spawn fails (error resilience)
* - Provides drain() method to wait for all queued items
*/
import type { ChildProcess } from 'child_process';
/** Poll interval for drain() method in milliseconds */
const DRAIN_POLL_INTERVAL = 10;
/**
* Request to spawn an agent process
*/
export interface SpawnRequest {
/** Unique identifier for this spawn request */
id: string;
/** Type of process being spawned ('ideation' | 'roadmap' | 'build') */
type: string;
/** Callback invoked when process is spawned (receives ChildProcess) */
onSpawn: (process: ChildProcess) => Promise<void>;
/** Callback invoked if spawn fails */
onError: (error: Error) => void;
/** Project ID for the task */
projectId: string;
/** Project path where the task runs */
projectPath: string;
/** Command-line arguments to pass to the process */
args: string[];
/** Environment variables for the process */
env: Record<string, string>;
/** Working directory for the process */
cwd: string;
}
/**
* Function type for spawning a process
* Abstracted for testability and dependency injection
*/
export type SpawnFunction = (
id: string,
projectPath: string,
args: string[],
env: Record<string, string>,
projectId: string,
cwd: string
) => Promise<ChildProcess>;
/**
* FIFO queue for sequential agent spawning
*/
export class SpawnQueue {
private queue: SpawnRequest[] = [];
private processing = false;
private spawnFn: SpawnFunction;
constructor(spawnFn: SpawnFunction) {
this.spawnFn = spawnFn;
}
/**
* Add a spawn request to the queue
* Automatically starts processing if not already running
*/
enqueue(request: SpawnRequest): void {
this.queue.push(request);
// Start processing if not already running
if (!this.processing) {
this.processNext().catch((error) => {
console.error('[SpawnQueue] Fatal error processing queue:', error);
this.processing = false;
});
}
}
/**
* Process the next item in the queue
* Continues processing until queue is empty
*/
private async processNext(): Promise<void> {
// Mark as processing
this.processing = true;
while (this.queue.length > 0) {
const request = this.queue.shift();
if (!request) {
continue;
}
try {
// Spawn the process
const process = await this.spawnFn(
request.id,
request.projectPath,
request.args,
request.env,
request.projectId,
request.cwd
);
// Invoke the onSpawn callback
await request.onSpawn(process);
// Wait for the process to exit before continuing
await this.waitForExit(process);
} catch (error) {
// If spawn or onSpawn fails, invoke error callback and continue
const errorObj = error instanceof Error ? error : new Error(String(error));
request.onError(errorObj);
}
}
// Queue is empty, no longer processing
this.processing = false;
}
/**
* Wait for a child process to exit
*/
private waitForExit(process: ChildProcess): Promise<void> {
return new Promise<void>((resolve) => {
// Check if process already exited (handles race condition)
if (process.exitCode !== null) {
resolve();
return;
}
// Set up exit event listener (in case exit hasn't happened yet)
const onExit = () => {
resolve();
};
process.once('exit', onExit);
});
}
/**
* Wait for all queued items to complete
* Uses polling to check completion status
*/
async drain(): Promise<void> {
// Poll until queue is empty and not processing
while (this.queue.length > 0 || this.processing) {
await this.sleep(DRAIN_POLL_INTERVAL);
}
}
/**
* Current queue length
*/
get length(): number {
return this.queue.length;
}
/**
* Whether the queue is currently processing an item
*/
get isProcessing(): boolean {
return this.processing;
}
/**
* Sleep for a specified number of milliseconds
*/
private sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
}
+2 -2
View File
@@ -39,7 +39,7 @@ export function initAppLanguage(): void {
const osLocale = app?.getLocale?.() || 'en';
// Extract base language (e.g., 'en-US' -> 'en')
currentAppLanguage = osLocale.split('-')[0] || 'en';
} catch {
currentAppLanguage = 'en';
} catch {
currentAppLanguage = 'en';
}
}
+45 -3
View File
@@ -24,7 +24,7 @@ import os from 'os';
try {
log.initialize();
} catch {
// Already initialized, ignore
// Already initialized, ignore
}
// File transport configuration
@@ -38,6 +38,18 @@ log.transports.file.fileName = 'main.log';
// Console transport - always show warnings and errors, debug only in dev mode
log.transports.console.level = process.env.NODE_ENV === 'development' ? 'debug' : 'warn';
log.transports.console.format = '[{h}:{i}:{s}] [{level}] {text}';
// Guard console transport writes so broken stdio streams do not crash the app.
{
const originalConsoleWriteFn = log.transports.console.writeFn as (...args: unknown[]) => void;
log.transports.console.writeFn = (...args: unknown[]) => {
try {
originalConsoleWriteFn(...args);
} catch (error) {
const err = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
safeStderrWrite(`[app-logger] console transport write failed: ${err}`);
}
};
}
// Determine if this is a beta version
function isBetaVersion(): boolean {
@@ -204,14 +216,44 @@ export const appLog = {
log: (...args: unknown[]) => log.info(...args),
};
/**
* Best-effort stderr fallback used when electron-log itself throws (e.g. EIO).
* Must never throw, especially inside uncaught exception handlers.
*/
function safeStderrWrite(message: string): void {
try {
process.stderr.write(`${message}\n`);
} catch {
// Ignore - nothing else we can safely do here.
}
}
/**
* Log an unhandled error without risking recursive crashes if logger transport fails.
*/
function safeLogUnhandled(prefix: string, value: unknown): void {
try {
log.error(prefix, value);
} catch (loggingError) {
const loggingFailure = loggingError instanceof Error
? `${loggingError.name}: ${loggingError.message}`
: String(loggingError);
const original = value instanceof Error
? (value.stack || `${value.name}: ${value.message}`)
: String(value);
safeStderrWrite(`[app-logger] ${prefix} (logger failed: ${loggingFailure})`);
safeStderrWrite(original);
}
}
// Log unhandled errors
export function setupErrorLogging(): void {
process.on('uncaughtException', (error) => {
log.error('Uncaught exception:', error);
safeLogUnhandled('Uncaught exception:', error);
});
process.on('unhandledRejection', (reason) => {
log.error('Unhandled rejection:', reason);
safeLogUnhandled('Unhandled rejection:', reason);
});
log.info('Error logging initialized');
+8 -5
View File
@@ -88,16 +88,18 @@ function htmlToMarkdown(html: string): string {
md = md.replace(/<br\s*\/?>/gi, '\n');
md = md.replace(/<hr\s*\/?>/gi, '---\n\n');
// Remove any remaining HTML tags
md = md.replace(/<[^>]+>/g, '');
// Remove any remaining HTML tags (loop to handle nested tag fragments)
while (/<[^>]+>/.test(md)) {
md = md.replace(/<[^>]+>/g, '');
}
// Decode common HTML entities
md = md.replace(/&amp;/g, '&');
// Decode common HTML entities (&amp; LAST to prevent double-unescaping like &amp;lt; → &lt; → <)
md = md.replace(/&lt;/g, '<');
md = md.replace(/&gt;/g, '>');
md = md.replace(/&quot;/g, '"');
md = md.replace(/&#39;/g, "'");
md = md.replace(/&nbsp;/g, ' ');
md = md.replace(/&amp;/g, '&');
// Clean up excessive whitespace
md = md.replace(/\n{3,}/g, '\n\n');
@@ -545,7 +547,8 @@ async function fetchLatestStableRelease(): Promise<AppUpdateInfo | null> {
const version = latestStable.tag_name.replace(/^v/, '');
// Sanitize version string for logging (remove control characters and limit length)
const safeVersion = String(version).replace(/[\x00-\x1f\x7f]/g, '').slice(0, 50);
// biome-ignore lint/suspicious/noControlCharactersInRegex: Intentionally matching control chars for sanitization
const safeVersion = String(version).replace(/[\x00-\x1f\x7f]/g, '').slice(0, 50);
console.warn('[app-updater] Found latest stable release:', safeVersion);
resolve({

Some files were not shown because too many files have changed in this diff Show More