Compare commits

..

3 Commits

Author SHA1 Message Date
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 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
50 changed files with 1572 additions and 1896 deletions
-231
View File
@@ -1,234 +1,3 @@
## 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
-2
View File
@@ -40,8 +40,6 @@ Auto Claude is a desktop application (+ CLI) where users describe a goal and AI
**PR target** — Always target the `develop` branch for PRs to AndyMik90/Auto-Claude, NOT `main`.
**No console.log for debugging production issues**`console.log` output is not visible in bundled/packaged versions of the Electron app. Use Sentry for error tracking and diagnostics in production. Reserve `console.log` for development only.
## Work Approach
**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.
+14 -14
View File
@@ -17,18 +17,18 @@
### Stable Release
<!-- STABLE_VERSION_BADGE -->
[![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](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_VERSION_BADGE_END -->
<!-- STABLE_DOWNLOADS -->
| Platform | Download |
|----------|----------|
| **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) |
| **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) |
<!-- 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.6-orange?style=flat-square)](https://github.com/AndyMik90/Auto-Claude/releases/tag/v2.7.6-beta.6)
[![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_VERSION_BADGE_END -->
<!-- BETA_DOWNLOADS -->
| Platform | Download |
|----------|----------|
| **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) |
| **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) |
<!-- BETA_DOWNLOADS_END -->
> All releases include SHA256 checksums and VirusTotal scan results for security verification.
+1 -1
View File
@@ -19,5 +19,5 @@ Quick Start:
See README.md for full documentation.
"""
__version__ = "2.7.6"
__version__ = "2.7.6-beta.5"
__author__ = "Auto Claude Team"
+445 -5
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,
@@ -84,6 +86,7 @@ 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,
@@ -97,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.
@@ -136,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)}",
@@ -685,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"]
@@ -719,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",
@@ -812,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:
@@ -871,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",
@@ -1230,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 -2
View File
@@ -14,7 +14,6 @@ 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
@@ -491,7 +490,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 safe_receive_messages(client, caller="session"):
async for msg in client.receive_response():
msg_type = type(msg).__name__
message_count += 1
debug_detailed(
+1 -107
View File
@@ -29,89 +29,6 @@ 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
# =============================================================================
@@ -904,31 +821,8 @@ 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}"
if not was_truncated:
print(" - CLAUDE.md: included in system prompt")
print(" - CLAUDE.md: included in system prompt")
else:
print(" - CLAUDE.md: not found in project root")
else:
-68
View File
@@ -6,17 +6,7 @@ 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:
@@ -128,61 +118,3 @@ 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
+4 -1
View File
@@ -454,8 +454,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
-6
View File
@@ -1211,9 +1211,6 @@ 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
@@ -1384,9 +1381,6 @@ 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
+1 -7
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 (some may not exist for greenfield/empty projects)
# Read all input files
cat project_index.json
cat requirements.json
cat context.json
@@ -35,12 +35,6 @@ 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
+2 -6
View File
@@ -15,11 +15,7 @@ from pathlib import Path
from agents.base import sanitize_error_message
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,
safe_receive_messages,
)
from core.error_utils import is_rate_limit_error, is_tool_concurrency_error
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 (
@@ -145,7 +141,7 @@ async def run_qa_fixer_session(
response_text = ""
debug("qa_fixer", "Starting to receive response stream...")
async for msg in safe_receive_messages(client, caller="qa_fixer"):
async for msg in client.receive_response():
msg_type = type(msg).__name__
message_count += 1
debug_detailed(
+2 -6
View File
@@ -16,11 +16,7 @@ from pathlib import Path
from agents.base import sanitize_error_message
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,
safe_receive_messages,
)
from core.error_utils import is_rate_limit_error, is_tool_concurrency_error
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
@@ -199,7 +195,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 safe_receive_messages(client, caller="qa_reviewer"):
async for msg in client.receive_response():
msg_type = type(msg).__name__
message_count += 1
debug_detailed(
+3 -4
View File
@@ -1,8 +1,7 @@
# Auto-Build Framework Dependencies
# 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
# 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
python-dotenv>=1.0.0
# TOML parsing fallback for Python < 3.11
+4 -46
View File
@@ -6,54 +6,18 @@ Phases for spec document creation and quality assurance.
"""
import json
from pathlib import Path
from typing import TYPE_CHECKING
from .. import validator, writer
from ..discovery import get_project_index_stats
from .models import MAX_RETRIES, PhaseResult
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
"""
if TYPE_CHECKING:
pass
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"
@@ -65,8 +29,6 @@ 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(
@@ -80,7 +42,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
@@ -118,9 +80,6 @@ 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(
@@ -129,7 +88,6 @@ Create:
success, output = await self.run_agent_fn(
"spec_writer.md",
additional_context=greenfield_ctx,
phase_name="spec_writing",
)
+1 -2
View File
@@ -12,7 +12,6 @@ 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 (
@@ -163,7 +162,7 @@ class AgentRunner:
response_text = ""
debug("agent_runner", "Starting to receive response stream...")
async for msg in safe_receive_messages(client, caller="agent_runner"):
async for msg in client.receive_response():
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) -> Path:
def rename_spec_dir_from_requirements(spec_dir: Path) -> bool:
"""Rename spec directory based on requirements.json task description.
Args:
spec_dir: The current spec directory
Returns:
The new spec directory path (or the original if no rename was needed/possible).
Tuple of (success, new_spec_dir). If success is False, new_spec_dir is the original.
"""
requirements_file = spec_dir / "requirements.json"
if not requirements_file.exists():
return spec_dir
return False
try:
with open(requirements_file, encoding="utf-8") as f:
@@ -223,7 +223,7 @@ def rename_spec_dir_from_requirements(spec_dir: Path) -> Path:
task_desc = req.get("task_description", "")
if not task_desc:
return spec_dir
return False
# Generate new name
new_name = generate_spec_name(task_desc)
@@ -240,11 +240,11 @@ def rename_spec_dir_from_requirements(spec_dir: Path) -> Path:
# Don't rename if it's already a good name (not "pending")
if "pending" not in current_name:
return spec_dir
return True
# Don't rename if target already exists
if new_spec_dir.exists():
return spec_dir
return True
# 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) -> Path:
update_task_logger_path(new_spec_dir)
print_status(f"Spec folder: {highlight(new_dir_name)}", "success")
return new_spec_dir
return True
except (json.JSONDecodeError, OSError) as e:
print_status(f"Could not rename spec folder: {e}", "warning")
return spec_dir
return False
# Phase display configuration
+19 -104
View File
@@ -6,7 +6,6 @@ Main orchestration logic for spec creation with dynamic complexity adaptation.
"""
import json
import types
from collections.abc import Callable
from pathlib import Path
@@ -19,7 +18,6 @@ from review import run_review_checkpoint
from task_logger import (
LogEntryType,
LogPhase,
TaskLogger,
get_task_logger,
)
from ui import (
@@ -240,47 +238,6 @@ 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"
@@ -334,11 +291,9 @@ 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")
@@ -350,26 +305,17 @@ 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
# 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
rename_spec_dir_from_requirements(self.spec_dir)
# Update task description from requirements
req = requirements.load_requirements(self.spec_dir)
@@ -389,11 +335,9 @@ 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
@@ -452,22 +396,17 @@ 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"
)
@@ -699,25 +638,6 @@ 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.
@@ -741,8 +661,9 @@ class SpecOrchestrator:
print_status("Build will not proceed without approval.", "warning")
return False
except SystemExit:
# Review checkpoint may call sys.exit(); treat any exit as unapproved
except SystemExit as e:
if e.code != 0:
return False
return False
except KeyboardInterrupt:
print()
@@ -775,25 +696,19 @@ class SpecOrchestrator:
The functionality has been moved to models.rename_spec_dir_from_requirements.
Returns:
True if successful or not needed, False if prerequisites are missing
True if successful or not needed, False on error
"""
# 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
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
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "auto-claude-ui",
"version": "2.7.6",
"version": "2.7.6-beta.5",
"type": "module",
"description": "Desktop UI for Auto Claude autonomous coding framework",
"homepage": "https://github.com/AndyMik90/Auto-Claude",
@@ -186,7 +186,7 @@ describe('Subprocess Spawn Integration', () => {
'Test task description'
]),
expect.objectContaining({
cwd: TEST_PROJECT_PATH, // Process runs from project directory to avoid cross-drive issues on Windows (#1661)
cwd: AUTO_CLAUDE_SOURCE, // Process runs from auto-claude source directory
env: expect.objectContaining({
PYTHONUNBUFFERED: '1'
})
@@ -218,7 +218,7 @@ describe('Subprocess Spawn Integration', () => {
'spec-001'
]),
expect.objectContaining({
cwd: TEST_PROJECT_PATH // Process runs from project directory to avoid cross-drive issues on Windows (#1661)
cwd: AUTO_CLAUDE_SOURCE // Process runs from auto-claude source directory
})
);
}, 30000); // Increase timeout for Windows CI (dynamic imports are slow)
@@ -248,7 +248,7 @@ describe('Subprocess Spawn Integration', () => {
'--qa'
]),
expect.objectContaining({
cwd: TEST_PROJECT_PATH // Process runs from project directory to avoid cross-drive issues on Windows (#1661)
cwd: AUTO_CLAUDE_SOURCE // Process runs from auto-claude source directory
})
);
}, 30000); // Increase timeout for Windows CI (dynamic imports are slow)
@@ -1,301 +0,0 @@
/**
* 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);
});
});
});
@@ -329,9 +329,7 @@ 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
// 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);
await this.processManager.spawnProcess(taskId, autoBuildSource, args, combinedEnv, 'task-execution', projectId);
}
/**
@@ -412,10 +410,7 @@ export class AgentManager extends EventEmitter {
// Register with unified OperationRegistry for proactive swap support
this.registerTaskWithOperationRegistry(taskId, 'task-execution', { projectPath, specId, options });
// 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);
await this.processManager.spawnProcess(taskId, autoBuildSource, args, combinedEnv, 'task-execution', projectId);
}
/**
@@ -453,8 +448,7 @@ export class AgentManager extends EventEmitter {
const args = [runPath, '--spec', specId, '--project-dir', projectPath, '--qa'];
// 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);
await this.processManager.spawnProcess(taskId, autoBuildSource, args, combinedEnv, 'qa-process', projectId);
}
/**
+4 -14
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, normalizeEnvPathKey, mergePythonEnvPath } from './env-utils';
import { getOAuthModeClearVars } from './env-utils';
import { getAugmentedEnv } from '../env-utils';
import { getToolInfo, getClaudeCliPathForSdk } from '../cli-tool-manager';
import { killProcessGracefully, isWindows, getPathDelimiter } from '../platform';
import { killProcessGracefully, isWindows } from '../platform';
import { debugLog } from '../../shared/utils/debug-logger';
/**
@@ -679,17 +679,7 @@ export class AgentProcessManager {
},
});
// 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"
// Parse Python commandto handle space-separated commands like "py -3"
const [pythonCommand, pythonBaseArgs] = parsePythonCommand(this.getPythonPath());
let childProcess;
try {
@@ -697,7 +687,7 @@ export class AgentProcessManager {
cwd,
env: {
...env, // Already includes process.env, extraEnv, profileEnv, PYTHONUNBUFFERED, PYTHONUTF8
...mergedPythonEnv, // Python env with merged PATH (preserves augmented PATH entries)
...pythonEnv, // Include Python environment (PYTHONPATH for bundled packages)
...oauthModeClearVars, // Clear stale ANTHROPIC_* vars when in OAuth mode
...apiProfileEnv // Include active API profile config (highest priority for ANTHROPIC_* vars)
}
+1 -13
View File
@@ -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, normalizeEnvPathKey } from './env-utils';
import { getOAuthModeClearVars } from './env-utils';
import { debugLog, debugError } from '../../shared/utils/debug-logger';
import { stripAnsiCodes } from '../../shared/utils/ansi-sanitizer';
import { parsePythonCommand } from '../python-detector';
@@ -397,12 +397,6 @@ 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'
@@ -736,12 +730,6 @@ 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'
+1 -164
View File
@@ -4,7 +4,7 @@
*/
import { describe, it, expect } from 'vitest';
import { getOAuthModeClearVars, normalizeEnvPathKey, mergePythonEnvPath } from './env-utils';
import { getOAuthModeClearVars } from './env-utils';
describe('getOAuthModeClearVars', () => {
describe('OAuth mode (no active API profile)', () => {
@@ -132,166 +132,3 @@ 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,88 +2,6 @@
* 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
*
+4 -6
View File
@@ -88,18 +88,16 @@ 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 (loop to handle nested tag fragments)
while (/<[^>]+>/.test(md)) {
md = md.replace(/<[^>]+>/g, '');
}
// Remove any remaining HTML tags
md = md.replace(/<[^>]+>/g, '');
// Decode common HTML entities (&amp; LAST to prevent double-unescaping like &amp;lt; → &lt; → <)
// Decode common HTML entities
md = md.replace(/&amp;/g, '&');
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');
+41 -126
View File
@@ -15,122 +15,64 @@ interface WatcherInfo {
*/
export class FileWatcher extends EventEmitter {
private watchers: Map<string, WatcherInfo> = new Map();
// Maps taskId -> specDir for the in-flight watch() call.
// Allows re-watch calls with a different specDir to proceed while
// still preventing duplicate calls for the exact same specDir.
private pendingWatches: Map<string, string> = new Map();
// Tracks taskIds that had unwatch() called while watch() was in-flight.
// Checked after each await point in watch() to avoid creating a leaked watcher.
private cancelledWatches: Set<string> = new Set();
/**
* Start watching a task's implementation plan
*/
async watch(taskId: string, specDir: string): Promise<void> {
// Prevent overlapping watch() calls for the same taskId + specDir combination.
// Since watch() is async, rapid-fire callers could enter concurrently
// before the first call updates state, creating duplicate watchers.
// A call with a different specDir is a legitimate re-watch and is allowed through.
const pendingSpecDir = this.pendingWatches.get(taskId);
if (pendingSpecDir !== undefined && pendingSpecDir === specDir) {
// Stop any existing watcher for this task
await this.unwatch(taskId);
const planPath = path.join(specDir, 'implementation_plan.json');
// Check if plan file exists
if (!existsSync(planPath)) {
this.emit('error', taskId, `Plan file not found: ${planPath}`);
return;
}
this.pendingWatches.set(taskId, specDir);
try {
// Close any existing watcher for this task.
// Delete from the map BEFORE awaiting close so that a concurrent watch()
// call entering after the await cannot obtain the same FSWatcher reference
// and attempt a second close() on the same object.
const existing = this.watchers.get(taskId);
if (existing) {
this.watchers.delete(taskId);
await existing.watcher.close();
// Create watcher with settings to handle frequent writes
const watcher = chokidar.watch(planPath, {
persistent: true,
ignoreInitial: true,
awaitWriteFinish: {
stabilityThreshold: 300,
pollInterval: 100
}
});
// Check if a newer watch() call has superseded this one while we were awaiting.
// If the pending specDir changed, another concurrent watch() took over — bail out
// to avoid overwriting the watcher it is about to create.
if (this.pendingWatches.get(taskId) !== specDir) {
return;
}
// Store watcher info
this.watchers.set(taskId, {
taskId,
watcher,
planPath
});
// Check if unwatch() was called while we were awaiting above.
if (this.cancelledWatches.has(taskId)) {
this.cancelledWatches.delete(taskId);
return;
}
const planPath = path.join(specDir, 'implementation_plan.json');
// Check if plan file exists
if (!existsSync(planPath)) {
this.emit('error', taskId, `Plan file not found: ${planPath}`);
return;
}
// Create watcher with settings to handle frequent writes
const watcher = chokidar.watch(planPath, {
persistent: true,
ignoreInitial: true,
awaitWriteFinish: {
stabilityThreshold: 300,
pollInterval: 100
}
});
// Check again after the synchronous watcher creation (no await, but defensive).
if (this.cancelledWatches.has(taskId)) {
this.cancelledWatches.delete(taskId);
await watcher.close();
return;
}
// Store watcher info
this.watchers.set(taskId, {
taskId,
watcher,
planPath
});
// Handle file changes
watcher.on('change', () => {
try {
const content = readFileSync(planPath, 'utf-8');
const plan: ImplementationPlan = JSON.parse(content);
this.emit('progress', taskId, plan);
} catch {
// File might be in the middle of being written
// Ignore parse errors, next change event will have complete file
}
});
// Handle errors
watcher.on('error', (error: unknown) => {
const message = error instanceof Error ? error.message : String(error);
this.emit('error', taskId, message);
});
// Read and emit initial state
// Handle file changes
watcher.on('change', () => {
try {
const content = readFileSync(planPath, 'utf-8');
const plan: ImplementationPlan = JSON.parse(content);
this.emit('progress', taskId, plan);
} catch {
// Initial read failed - not critical
}
} finally {
// Only clean up if this call still owns the entry. If a superseding
// concurrent watch() call has already updated pendingWatches with a
// different specDir, leave that entry intact so the superseding call
// can proceed correctly.
if (this.pendingWatches.get(taskId) === specDir) {
this.pendingWatches.delete(taskId);
// The delete above guarantees has() is now false, so there is no
// longer any in-flight watch() for this taskId. Clear the
// cancellation flag so it doesn't linger for future watch() calls.
this.cancelledWatches.delete(taskId);
// File might be in the middle of being written
// Ignore parse errors, next change event will have complete file
}
});
// Handle errors
watcher.on('error', (error: unknown) => {
const message = error instanceof Error ? error.message : String(error);
this.emit('error', taskId, message);
});
// Read and emit initial state
try {
const content = readFileSync(planPath, 'utf-8');
const plan: ImplementationPlan = JSON.parse(content);
this.emit('progress', taskId, plan);
} catch {
// Initial read failed - not critical
}
}
@@ -138,13 +80,6 @@ export class FileWatcher extends EventEmitter {
* Stop watching a task
*/
async unwatch(taskId: string): Promise<void> {
// If watch() is currently in-flight for this taskId, it is already closing the
// existing watcher. Just set the cancellation flag and return to avoid a
// double-close of the same FSWatcher.
if (this.pendingWatches.has(taskId)) {
this.cancelledWatches.add(taskId);
return;
}
const watcherInfo = this.watchers.get(taskId);
if (watcherInfo) {
await watcherInfo.watcher.close();
@@ -156,17 +91,6 @@ export class FileWatcher extends EventEmitter {
* Stop all watchers
*/
async unwatchAll(): Promise<void> {
// Cancel any in-flight watch() calls so they don't create new watchers
// after this cleanup completes.
for (const taskId of this.pendingWatches.keys()) {
this.cancelledWatches.add(taskId);
}
this.pendingWatches.clear();
// Clear cancellation flags now that pendingWatches is empty: the in-flight
// calls will bail via the supersession check (pendingWatches.get() returns
// undefined) and will not clean up cancelledWatches themselves. Clearing
// here ensures the instance is fully reset for subsequent use.
this.cancelledWatches.clear();
const closePromises = Array.from(this.watchers.values()).map(
async (info) => {
await info.watcher.close();
@@ -183,15 +107,6 @@ export class FileWatcher extends EventEmitter {
return this.watchers.has(taskId);
}
/**
* Get the spec directory currently being watched for a task
*/
getWatchedSpecDir(taskId: string): string | null {
const watcherInfo = this.watchers.get(taskId);
if (!watcherInfo) return null;
return path.dirname(watcherInfo.planPath);
}
/**
* Get current plan state for a task
*/
@@ -98,23 +98,7 @@ export function registerAgenteventsHandlers(
// Send final plan state to renderer BEFORE unwatching
// This ensures the renderer has the final subtask data (fixes 0/0 subtask bug)
// Try the file watcher's current path first, then fall back to worktree path
let finalPlan = fileWatcher.getCurrentPlan(taskId);
if (!finalPlan && exitTask && exitProject) {
// File watcher may have been watching the wrong path (main vs worktree)
// Try reading directly from the worktree
const worktreePath = findTaskWorktree(exitProject.path, exitTask.specId);
if (worktreePath) {
const specsBaseDir = getSpecsDir(exitProject.autoBuildPath);
const worktreePlanPath = path.join(worktreePath, specsBaseDir, exitTask.specId, AUTO_BUILD_PATHS.IMPLEMENTATION_PLAN);
try {
const content = readFileSync(worktreePlanPath, 'utf-8');
finalPlan = JSON.parse(content);
} catch {
// Worktree plan file not readable - not critical
}
}
}
const finalPlan = fileWatcher.getCurrentPlan(taskId);
if (finalPlan) {
safeSendToRenderer(
getMainWindow,
@@ -125,9 +109,7 @@ export function registerAgenteventsHandlers(
);
}
fileWatcher.unwatch(taskId).catch((err) => {
console.error(`[agent-events-handlers] Failed to unwatch for ${taskId}:`, err);
});
fileWatcher.unwatch(taskId);
if (processType === "spec-creation") {
console.warn(`[Task ${taskId}] Spec creation completed with code ${code}`);
@@ -229,26 +211,15 @@ export function registerAgenteventsHandlers(
const worktreePath = findTaskWorktree(project.path, task.specId);
if (worktreePath) {
const specsBaseDir = getSpecsDir(project.autoBuildPath);
const worktreeSpecDir = path.join(worktreePath, specsBaseDir, task.specId);
const worktreePlanPath = path.join(
worktreeSpecDir,
worktreePath,
specsBaseDir,
task.specId,
AUTO_BUILD_PATHS.IMPLEMENTATION_PLAN
);
if (existsSync(worktreePlanPath)) {
persistPlanPhaseSync(worktreePlanPath, progress.phase, project.id);
}
// Re-watch the worktree path if the file watcher is still watching the main project path.
// This handles the case where the task started before the worktree existed:
// the initial watch fell back to the main project spec dir, but now the worktree
// is available and implementation_plan.json is being written there.
const currentWatchDir = fileWatcher.getWatchedSpecDir(taskId);
if (currentWatchDir && currentWatchDir !== worktreeSpecDir && existsSync(worktreePlanPath)) {
console.warn(`[agent-events-handlers] Re-watching worktree path for ${taskId}: ${worktreeSpecDir}`);
fileWatcher.watch(taskId, worktreeSpecDir).catch((err) => {
console.error(`[agent-events-handlers] Failed to re-watch worktree for ${taskId}:`, err);
});
}
}
} else if (xstateInTerminalState && progress.phase) {
console.debug(`[agent-events-handlers] Skipping persistPlanPhaseSync for ${taskId}: XState in '${currentXState}', not overwriting with phase '${progress.phase}'`);
@@ -1499,19 +1499,6 @@ async function runPRReview(
// Build environment with project settings
const subprocessEnv = await getRunnerEnv(getClaudeMdEnv(project));
safeBreadcrumb({
category: 'github.pr-review',
message: `Subprocess env for PR #${prNumber} review`,
level: 'info',
data: {
prNumber,
hasGITHUB_CLI_PATH: !!subprocessEnv.GITHUB_CLI_PATH,
GITHUB_CLI_PATH: subprocessEnv.GITHUB_CLI_PATH ?? 'NOT SET',
hasGITHUB_TOKEN: !!subprocessEnv.GITHUB_TOKEN,
hasPYTHONPATH: !!subprocessEnv.PYTHONPATH,
},
});
// Create operation ID for this review
const reviewKey = getReviewKey(project.id, prNumber);
@@ -2041,7 +2028,7 @@ export function registerPRHandlers(getMainWindow: () => BrowserWindow | null): v
},
projectId
);
sendError({ prNumber, error: error instanceof Error ? error.message : "Failed to run PR review" });
sendError(error instanceof Error ? error.message : "Failed to run PR review");
}
});
@@ -3028,19 +3015,6 @@ export function registerPRHandlers(getMainWindow: () => BrowserWindow | null): v
// Build environment with project settings
const followupEnv = await getRunnerEnv(getClaudeMdEnv(project));
safeBreadcrumb({
category: 'github.pr-review',
message: `Subprocess env for PR #${prNumber} follow-up review`,
level: 'info',
data: {
prNumber,
hasGITHUB_CLI_PATH: !!followupEnv.GITHUB_CLI_PATH,
GITHUB_CLI_PATH: followupEnv.GITHUB_CLI_PATH ?? 'NOT SET',
hasGITHUB_TOKEN: !!followupEnv.GITHUB_TOKEN,
hasPYTHONPATH: !!followupEnv.PYTHONPATH,
},
});
const { process: childProcess, promise } = runPythonSubprocess<PRReviewResult>({
pythonPath: getPythonPath(backendPath),
args,
@@ -30,15 +30,6 @@ vi.mock('../../utils', () => ({
getGitHubTokenForSubprocess: () => mockGetGitHubTokenForSubprocess(),
}));
vi.mock('../../../../cli-tool-manager', () => ({
getToolInfo: () => ({ found: false, path: undefined, source: undefined }),
}));
vi.mock('../../../../sentry', () => ({
getSentryEnvForSubprocess: () => ({}),
safeBreadcrumb: () => {},
}));
import { getRunnerEnv } from '../runner-env';
describe('getRunnerEnv', () => {
@@ -3,8 +3,7 @@ import { getAPIProfileEnv } from '../../../services/profile';
import { getBestAvailableProfileEnv } from '../../../rate-limit-detector';
import { pythonEnvManager } from '../../../python-env-manager';
import { getGitHubTokenForSubprocess } from '../utils';
import { getSentryEnvForSubprocess, safeBreadcrumb } from '../../../sentry';
import { getToolInfo } from '../../../cli-tool-manager';
import { getSentryEnvForSubprocess } from '../../../sentry';
/**
* Get environment variables for Python runner subprocesses.
@@ -44,30 +43,12 @@ export async function getRunnerEnv(
const githubToken = await getGitHubTokenForSubprocess();
const githubEnv: Record<string, string> = githubToken ? { GITHUB_TOKEN: githubToken } : {};
// Resolve gh CLI path so Python subprocess can find it in bundled apps
// (bundled Electron apps have a stripped PATH that doesn't include Homebrew etc.)
const ghInfo = getToolInfo('gh');
const ghCliEnv: Record<string, string> = ghInfo.found && ghInfo.path ? { GITHUB_CLI_PATH: ghInfo.path } : {};
safeBreadcrumb({
category: 'github.runner-env',
message: `gh CLI for subprocess: found=${ghInfo.found}, path=${ghInfo.path ?? 'none'}, source=${ghInfo.source ?? 'none'}`,
level: ghInfo.found ? 'info' : 'warning',
data: {
found: ghInfo.found,
path: ghInfo.path ?? null,
source: ghInfo.source ?? null,
willSetGITHUB_CLI_PATH: !!(ghInfo.found && ghInfo.path),
hasGITHUB_TOKEN: !!githubToken,
},
});
return {
...pythonEnv, // Python environment including PYTHONPATH (fixes #139)
...apiProfileEnv,
...oauthModeClearVars,
...profileEnv, // OAuth token from profile manager (fixes #563, rate-limit aware)
...githubEnv, // Fresh GitHub token from gh CLI (fixes #151)
...ghCliEnv, // gh CLI path for bundled apps (Python backend uses GITHUB_CLI_PATH)
...getSentryEnvForSubprocess(), // Sentry DSN + sample rates for Python subprocess
...extraEnv, // extraEnv last so callers can still override
};
@@ -20,8 +20,7 @@ import { isWindows, isMacOS } from '../../../platform';
import { getEffectiveSourcePath } from '../../../updater/path-resolver';
import { pythonEnvManager, getConfiguredPythonPath } from '../../../python-env-manager';
import { getTaskkillExePath, getWhereExePath } from '../../../utils/windows-paths';
import { safeCaptureException, safeBreadcrumb } from '../../../sentry';
import { getToolInfo } from '../../../cli-tool-manager';
import { safeCaptureException } from '../../../sentry';
const execAsync = promisify(exec);
const execFileAsync = promisify(execFile);
@@ -560,7 +559,6 @@ export interface GitHubModuleValidation {
pythonEnvValid: boolean;
error?: string;
backendPath?: string;
ghCliPath?: string;
}
/**
@@ -624,36 +622,33 @@ export async function validateGitHubModule(project: Project): Promise<GitHubModu
return result;
}
// 2. Check gh CLI installation (uses CLI tool manager for bundled app compatibility)
const ghInfo = getToolInfo('gh');
safeBreadcrumb({
category: 'github.validation',
message: `gh CLI lookup: found=${ghInfo.found}, path=${ghInfo.path ?? 'none'}, source=${ghInfo.source ?? 'none'}`,
level: ghInfo.found ? 'info' : 'warning',
data: { found: ghInfo.found, path: ghInfo.path ?? null, source: ghInfo.source ?? null },
});
if (ghInfo.found && ghInfo.path) {
// 2. Check gh CLI installation (cross-platform)
try {
if (isWindows()) {
await execFileAsync(getWhereExePath(), ['gh'], { timeout: 5000 });
} else {
await execAsync('which gh');
}
result.ghCliInstalled = true;
result.ghCliPath = ghInfo.path;
} else {
} catch (error: unknown) {
result.ghCliInstalled = false;
const installInstructions = isWindows()
? 'winget install --id GitHub.cli'
: isMacOS()
? 'brew install gh'
: 'See https://cli.github.com/';
result.error = `GitHub CLI (gh) is not installed. Install it with:\n ${installInstructions}`;
safeCaptureException(new Error('gh CLI not found in bundled app'), {
tags: { component: 'github-validation' },
extra: { ghInfo, isPackaged: require('electron').app?.isPackaged ?? 'unknown' },
});
const errCode = (error as NodeJS.ErrnoException).code;
if (errCode === 'ENOENT' && isWindows()) {
result.error = `System utility 'where.exe' not found. Check Windows installation.`;
} else {
const installInstructions = isWindows()
? 'winget install --id GitHub.cli'
: isMacOS()
? 'brew install gh'
: 'See https://cli.github.com/';
result.error = `GitHub CLI (gh) is not installed. Install it with:\n ${installInstructions}`;
}
return result;
}
// 3. Check gh authentication (use resolved path for bundled app compatibility)
// 3. Check gh authentication
try {
const ghPath = result.ghCliPath || 'gh';
await execAsync(`"${ghPath}" auth status 2>&1`);
await execAsync('gh auth status 2>&1');
result.ghAuthenticated = true;
} catch (error: any) {
// gh auth status returns non-zero when not authenticated
@@ -153,24 +153,16 @@ function getGitBranchesWithInfo(projectPath: string): GitBranchDetail[] {
.map(b => b.trim())
// Remove HEAD pointer entries like "origin/HEAD"
.filter(b => !b.endsWith('/HEAD'))
.map(fullName => {
// Strip "origin/" prefix so branch names are clean for PR targets etc.
const name = fullName.replace(/^origin\//, '');
return {
name,
type: 'remote' as const,
displayName: name,
isCurrent: false
};
});
.map(name => ({
name,
type: 'remote' as const,
displayName: name,
isCurrent: false
}));
} catch {
// Remote branches may not exist, continue with local only
}
// Deduplicate: if a branch exists locally and remotely, keep only the local entry
const localNames = new Set(localBranches.map(b => b.name));
remoteBranches = remoteBranches.filter(b => !localNames.has(b.name));
// Combine and sort: local branches first, then remote branches, alphabetically within each group
const allBranches = [...localBranches, ...remoteBranches];
@@ -81,22 +81,6 @@ async function ensureProfileManagerInitialized(): Promise<
}
}
/**
* Get the spec directory for file watching, preferring the worktree path if it exists.
* When a task runs in a worktree, implementation_plan.json is written there,
* not in the main project's spec directory.
*/
function getSpecDirForWatcher(projectPath: string, specsBaseDir: string, specId: string): string {
const worktreePath = findTaskWorktree(projectPath, specId);
if (worktreePath) {
const worktreeSpecDir = path.join(worktreePath, specsBaseDir, specId);
if (existsSync(path.join(worktreeSpecDir, 'implementation_plan.json'))) {
return worktreeSpecDir;
}
}
return path.join(projectPath, specsBaseDir, specId);
}
/**
* Register task execution handlers (start, stop, review, status management, recovery)
*/
@@ -177,31 +161,6 @@ export function registerTaskExecutionHandlers(
console.warn('[TASK_START] Found task:', task.specId, 'status:', task.status, 'reviewReason:', task.reviewReason, 'subtasks:', task.subtasks.length);
// Clear stale tracking state from any previous execution so that:
// - terminalEventSeen doesn't suppress future PROCESS_EXITED events
// - lastSequenceByTask doesn't drop events from the new process
taskStateManager.prepareForRestart(taskId);
// Check if implementation_plan.json has valid subtasks BEFORE XState handling.
// This is more reliable than task.subtasks.length which may not be loaded yet.
const specsBaseDir = getSpecsDir(project.autoBuildPath);
const specDir = path.join(
project.path,
specsBaseDir,
task.specId
);
const planFilePath = path.join(specDir, AUTO_BUILD_PATHS.IMPLEMENTATION_PLAN);
let planHasSubtasks = false;
const planContent = safeReadFileSync(planFilePath);
if (planContent) {
try {
const plan = JSON.parse(planContent);
planHasSubtasks = checkSubtasksCompletion(plan).totalCount > 0;
} catch {
// Invalid/corrupt plan file - treat as no subtasks
}
}
// Immediately mark as started so the UI moves the card to In Progress.
// Use XState actor state as source of truth (if actor exists), with task data as fallback.
// - plan_review: User approved the plan, send PLAN_APPROVED to transition to coding
@@ -214,11 +173,6 @@ export function registerTaskExecutionHandlers(
// XState says plan_review - send PLAN_APPROVED
console.warn('[TASK_START] XState: plan_review -> coding via PLAN_APPROVED');
taskStateManager.handleUiEvent(taskId, { type: 'PLAN_APPROVED' }, task, project);
} else if (currentXState === 'error' && !planHasSubtasks) {
// FIX (#1562): Task crashed during planning (no subtasks yet).
// Uses planHasSubtasks from implementation_plan.json (more reliable than task.subtasks.length).
console.warn('[TASK_START] XState: error with no plan subtasks -> planning via PLANNING_STARTED');
taskStateManager.handleUiEvent(taskId, { type: 'PLANNING_STARTED' }, task, project);
} else if (currentXState === 'human_review' || currentXState === 'error') {
// XState says human_review or error - send USER_RESUMED
console.warn('[TASK_START] XState:', currentXState, '-> coding via USER_RESUMED');
@@ -232,11 +186,6 @@ export function registerTaskExecutionHandlers(
// No XState actor - fallback to task data (e.g., after app restart)
console.warn('[TASK_START] No XState actor, task data: plan_review -> coding via PLAN_APPROVED');
taskStateManager.handleUiEvent(taskId, { type: 'PLAN_APPROVED' }, task, project);
} else if (task.status === 'error' && !planHasSubtasks) {
// FIX (#1562): No XState actor, task crashed during planning (no subtasks).
// Uses planHasSubtasks from implementation_plan.json (more reliable than task.subtasks.length).
console.warn('[TASK_START] No XState actor, error with no plan subtasks -> planning via PLANNING_STARTED');
taskStateManager.handleUiEvent(taskId, { type: 'PLANNING_STARTED' }, task, project);
} else if (task.status === 'human_review' || task.status === 'error') {
// No XState actor - fallback to task data for resuming
console.warn('[TASK_START] No XState actor, task data:', task.status, '-> coding via USER_RESUMED');
@@ -256,27 +205,24 @@ export function registerTaskExecutionHandlers(
}
// Start file watcher for this task
// Use worktree path if it exists, since the backend writes implementation_plan.json there
const watchSpecDir = getSpecDirForWatcher(project.path, specsBaseDir, task.specId);
fileWatcher.watch(taskId, watchSpecDir).catch((err) => {
console.error(`[TASK_START] Failed to watch spec dir for ${taskId}:`, err);
});
const specsBaseDir = getSpecsDir(project.autoBuildPath);
const specDir = path.join(
project.path,
specsBaseDir,
task.specId
);
fileWatcher.watch(taskId, specDir);
// Check if spec.md exists (indicates spec creation was already done or in progress)
// Check main project path for spec file (spec is created before worktree)
const specFilePath = path.join(specDir, AUTO_BUILD_PATHS.SPEC_FILE);
const hasSpec = existsSync(specFilePath);
// Check if this task needs spec creation first (no spec file = not yet created)
// OR if it has a spec but no implementation plan subtasks (spec created, needs planning/building)
const needsSpecCreation = !hasSpec;
// FIX (#1562): Check actual plan file for subtasks, not just task.subtasks.length.
// When a task crashes during planning, it may have spec.md but an empty/missing
// implementation_plan.json. Previously, this path would call startTaskExecution
// (run.py) which expects subtasks to exist. Now we check the actual plan file.
const needsImplementation = hasSpec && !planHasSubtasks;
const needsImplementation = hasSpec && task.subtasks.length === 0;
console.warn('[TASK_START] hasSpec:', hasSpec, 'planHasSubtasks:', planHasSubtasks, 'needsSpecCreation:', needsSpecCreation, 'needsImplementation:', needsImplementation);
console.warn('[TASK_START] hasSpec:', hasSpec, 'needsSpecCreation:', needsSpecCreation, 'needsImplementation:', needsImplementation);
// Get base branch: task-level override takes precedence over project settings
const baseBranch = task.metadata?.baseBranch || project.settings?.mainBranch;
@@ -291,12 +237,18 @@ export function registerTaskExecutionHandlers(
// Also pass baseBranch so worktrees are created from the correct branch
agentManager.startSpecCreation(taskId, project.path, taskDescription, specDir, task.metadata, baseBranch, project.id);
} else if (needsImplementation) {
// Spec exists but no valid subtasks in implementation plan
// FIX (#1562): Use startTaskExecution (run.py) which will create the planner
// agent session to generate the implementation plan. run.py handles the case
// where implementation_plan.json is missing or has no subtasks - the planner
// agent will generate the plan before the coder starts.
console.warn('[TASK_START] Starting task execution (no valid subtasks in plan) for:', task.specId);
// Spec exists but no subtasks - run run.py to create implementation plan and execute
// Read the spec.md to get the task description
const _taskDescription = task.description || task.title;
try {
readFileSync(specFilePath, 'utf-8');
} catch {
// Use default description
}
console.warn('[TASK_START] Starting task execution (no subtasks) for:', task.specId);
// Start task execution which will create the implementation plan
// Note: No parallel mode for planning phase - parallel only makes sense with multiple subtasks
agentManager.startTaskExecution(
taskId,
project.path,
@@ -337,9 +289,7 @@ export function registerTaskExecutionHandlers(
*/
ipcMain.on(IPC_CHANNELS.TASK_STOP, (_, taskId: string) => {
agentManager.killTask(taskId);
fileWatcher.unwatch(taskId).catch((err) => {
console.error('[TASK_STOP] Failed to unwatch:', err);
});
fileWatcher.unwatch(taskId);
// Find task and project to emit USER_STOPPED with plan context
const { task, project } = findTaskAndProject(taskId);
@@ -365,9 +315,6 @@ export function registerTaskExecutionHandlers(
task,
project
);
// Clear stale tracking state so a subsequent restart works correctly
taskStateManager.prepareForRestart(taskId);
});
/**
@@ -537,9 +484,6 @@ export function registerTaskExecutionHandlers(
return { success: false, error: 'Failed to write QA fix request file' };
}
// Clear stale tracking state before starting new QA process
taskStateManager.prepareForRestart(taskId);
// Restart QA process - use worktree path if it exists, otherwise main project
// The QA process needs to run where the implementation_plan.json with completed subtasks is
const qaProjectPath = hasWorktree ? worktreePath : project.path;
@@ -714,8 +658,6 @@ export function registerTaskExecutionHandlers(
// Auto-start task when status changes to 'in_progress' and no process is running
if (status === 'in_progress' && !agentManager.isRunning(taskId)) {
// Clear stale tracking state before starting a new process
taskStateManager.prepareForRestart(taskId);
const mainWindow = getMainWindow();
// Check git status before auto-starting
@@ -768,29 +710,13 @@ export function registerTaskExecutionHandlers(
}
// Start file watcher for this task
// Use worktree path if it exists, since the backend writes implementation_plan.json there
const watchSpecDir = getSpecDirForWatcher(project.path, specsBaseDir, task.specId);
fileWatcher.watch(taskId, watchSpecDir).catch((err) => {
console.error(`[TASK_UPDATE_STATUS] Failed to watch spec dir for ${taskId}:`, err);
});
fileWatcher.watch(taskId, specDir);
// Check if spec.md exists
const specFilePath = path.join(specDir, AUTO_BUILD_PATHS.SPEC_FILE);
const hasSpec = existsSync(specFilePath);
const needsSpecCreation = !hasSpec;
// FIX (#1562): Check actual plan file for subtasks, not just task.subtasks.length
const updatePlanFilePath = path.join(specDir, AUTO_BUILD_PATHS.IMPLEMENTATION_PLAN);
let updatePlanHasSubtasks = false;
const updatePlanContent = safeReadFileSync(updatePlanFilePath);
if (updatePlanContent) {
try {
const plan = JSON.parse(updatePlanContent);
updatePlanHasSubtasks = checkSubtasksCompletion(plan).totalCount > 0;
} catch {
// Invalid/corrupt plan file - treat as no subtasks
}
}
const needsImplementation = hasSpec && !updatePlanHasSubtasks;
const needsImplementation = hasSpec && task.subtasks.length === 0;
console.warn('[TASK_UPDATE_STATUS] hasSpec:', hasSpec, 'needsSpecCreation:', needsSpecCreation, 'needsImplementation:', needsImplementation);
@@ -1136,18 +1062,60 @@ export function registerTaskExecutionHandlers(
}
console.log(`[Recovery] Total ${totalResetCount} subtask(s) reset across all locations`);
// Clear attempt_history.json to break infinite recovery loops.
// Without this, the backend re-reads stuck markers from attempt_history
// and immediately re-stucks the same subtasks after recovery.
const specDirsToClean = new Set<string>([specDir]);
if (mainSpecDir !== specDir) specDirsToClean.add(mainSpecDir);
if (worktreeSpecDir && worktreeSpecDir !== specDir) specDirsToClean.add(worktreeSpecDir);
for (const dir of specDirsToClean) {
const attemptHistoryPath = path.join(dir, 'memory', 'attempt_history.json');
const historyContent = safeReadFileSync(attemptHistoryPath);
if (!historyContent) continue;
try {
const history = JSON.parse(historyContent);
// Collect stuck subtask IDs before clearing
const stuckIds = new Set<string>(
(history.stuck_subtasks || [])
.map((s: { subtask_id?: string }) => s.subtask_id)
.filter((id: string | undefined): id is string => Boolean(id))
);
// Clear stuck_subtasks array
history.stuck_subtasks = [];
// Reset attempt entries for previously-stuck subtasks
if (history.subtasks && stuckIds.size > 0) {
for (const stuckId of stuckIds) {
if (history.subtasks[stuckId]) {
history.subtasks[stuckId] = { attempts: [], status: 'pending' };
}
}
}
history.metadata = {
...history.metadata,
last_updated: new Date().toISOString()
};
writeFileAtomicSync(attemptHistoryPath, JSON.stringify(history, null, 2));
console.log(`[Recovery] Cleared attempt_history.json at: ${dir} (reset ${stuckIds.size} stuck entries)`);
} catch (historyErr) {
console.warn(`[Recovery] Could not parse attempt_history at ${dir}:`, historyErr);
}
}
}
// Stop file watcher if it was watching this task
fileWatcher.unwatch(taskId).catch((err) => {
console.error('[TASK_RECOVER_STUCK] Failed to unwatch:', err);
});
fileWatcher.unwatch(taskId);
// Auto-restart the task if requested
let autoRestarted = false;
if (autoRestart) {
// Clear stale tracking state before restarting
taskStateManager.prepareForRestart(taskId);
// Check git status before auto-restarting
const gitStatusForRestart = checkGitStatus(project.path);
if (!gitStatusForRestart.isGitRepo || !gitStatusForRestart.hasCommits) {
@@ -1224,16 +1192,12 @@ export function registerTaskExecutionHandlers(
// Start the task execution
// Start file watcher for this task
// Use worktree path if it exists, since the backend writes implementation_plan.json there
const watchSpecDir = getSpecDirForWatcher(project.path, specsBaseDir, task.specId);
fileWatcher.watch(taskId, watchSpecDir).catch((err) => {
console.error(`[Recovery] Failed to watch spec dir for ${taskId}:`, err);
});
const specsBaseDir = getSpecsDir(project.autoBuildPath);
const specDirForWatcher = path.join(project.path, specsBaseDir, task.specId);
fileWatcher.watch(taskId, specDirForWatcher);
// Check if spec.md exists to determine whether to run spec creation or task execution
// Check main project path for spec file (spec is created before worktree)
// mainSpecDir is declared earlier in the handler scope
const specFilePath = path.join(mainSpecDir, AUTO_BUILD_PATHS.SPEC_FILE);
const specFilePath = path.join(specDirForWatcher, AUTO_BUILD_PATHS.SPEC_FILE);
const hasSpec = existsSync(specFilePath);
const needsSpecCreation = !hasSpec;
@@ -1244,7 +1208,7 @@ export function registerTaskExecutionHandlers(
// No spec file - need to run spec_runner.py to create the spec
const taskDescription = task.description || task.title;
console.warn(`[Recovery] Starting spec creation for: ${task.specId}`);
agentManager.startSpecCreation(taskId, project.path, taskDescription, mainSpecDir, task.metadata, baseBranchForRecovery, project.id);
agentManager.startSpecCreation(taskId, project.path, taskDescription, specDirForWatcher, task.metadata, baseBranchForRecovery, project.id);
} else {
// Spec exists - run task execution
console.warn(`[Recovery] Starting task execution for: ${task.specId}`);
@@ -1370,9 +1370,7 @@ function getTaskBaseBranch(specDir: string): string | undefined {
if (metadata.baseBranch &&
metadata.baseBranch !== '__project_default__' &&
GIT_BRANCH_REGEX.test(metadata.baseBranch)) {
// Strip remote prefix if present (e.g., "origin/feat/x" → "feat/x")
const branch = metadata.baseBranch.replace(/^origin\//, '');
return branch;
return metadata.baseBranch;
}
}
} catch (e) {
+11 -5
View File
@@ -6,7 +6,6 @@ import { app } from 'electron';
import { findPythonCommand, getBundledPythonPath } from './python-detector';
import { isLinux, isWindows, getPathDelimiter } from './platform';
import { getIsolatedGitEnv } from './utils/git-isolation';
import { normalizeEnvPathKey } from './agent/env-utils';
export interface PythonEnvStatus {
ready: boolean;
@@ -727,10 +726,17 @@ if sys.version_info >= (3, 12):
const pywin32System32 = path.join(this.sitePackagesPath, 'pywin32_system32');
// Add pywin32_system32 to PATH for DLL loading
// Normalize to single 'PATH' key before reading/writing, using the shared utility.
// This prevents duplicate 'Path'/'PATH' keys that cause DLL-load failures on Windows.
normalizeEnvPathKey(baseEnv);
const currentPath = baseEnv['PATH'] ?? '';
// Fix PATH case sensitivity: On Windows, env vars are case-insensitive but Node.js
// preserves case. If we have both 'PATH' and 'Path', Node.js lexicographically sorts
// and uses the first match, causing issues. Normalize to single 'PATH' key.
// See: https://github.com/nodejs/node/issues/9157
const pathKey = Object.keys(baseEnv).find(k => k.toUpperCase() === 'PATH');
const currentPath = pathKey ? baseEnv[pathKey] : '';
// Remove any existing PATH variants to avoid duplicates
if (pathKey && pathKey !== 'PATH') {
delete baseEnv[pathKey];
}
if (currentPath && !currentPath.includes(pywin32System32)) {
windowsEnv['PATH'] = `${pywin32System32};${currentPath}`;
@@ -169,18 +169,6 @@ export class TaskStateManager {
return this.getCurrentState(taskId) === 'plan_review';
}
/**
* Reset tracking state for a task that is about to be restarted.
* Clears terminalEventSeen (so process exits aren't swallowed) and
* lastSequenceByTask (so events from the new process aren't dropped
* as duplicates). Does NOT stop or remove the XState actor, since
* the caller may still need to send events to it.
*/
prepareForRestart(taskId: string): void {
this.terminalEventSeen.delete(taskId);
this.lastSequenceByTask.delete(taskId);
}
clearTask(taskId: string): void {
this.lastSequenceByTask.delete(taskId);
this.lastStateByTask.delete(taskId);
@@ -68,7 +68,6 @@ export function GitHubPRs({ onOpenSettings, isActive = false }: GitHubPRsProps)
isReviewing,
isExternalReview,
previousReviewResult,
reviewError,
hasMore,
selectPR,
runReview,
@@ -272,7 +271,6 @@ export function GitHubPRs({ onOpenSettings, isActive = false }: GitHubPRsProps)
startedAt={startedAt}
isReviewing={isReviewing}
isExternalReview={isExternalReview}
reviewError={reviewError}
initialNewCommitsCheck={storedNewCommitsCheck}
isActive={isActive}
isLoadingFiles={isLoadingPRDetails}
@@ -46,7 +46,6 @@ interface PRDetailProps {
startedAt: string | null;
isReviewing: boolean;
isExternalReview?: boolean;
reviewError?: string | null;
initialNewCommitsCheck?: NewCommitsCheck | null;
isActive?: boolean;
isLoadingFiles?: boolean;
@@ -82,7 +81,6 @@ export function PRDetail({
startedAt,
isReviewing,
isExternalReview = false,
reviewError: reviewErrorProp,
initialNewCommitsCheck,
isActive: _isActive = false,
isLoadingFiles = false,
@@ -723,16 +721,6 @@ export function PRDetail({
};
}
if (reviewErrorProp && !reviewResult?.success) {
return {
status: 'not_reviewed',
label: t('prReview.reviewFailed'),
description: reviewErrorProp,
icon: <AlertCircle className="h-5 w-5" />,
color: 'bg-destructive/20 text-destructive border-destructive/50',
};
}
if (!reviewResult || !reviewResult.success) {
return {
status: 'not_reviewed',
@@ -875,7 +863,7 @@ export function PRDetail({
icon: <MessageSquare className="h-5 w-5" />,
color: 'bg-primary/20 text-primary border-primary/50',
};
}, [isReviewing, reviewProgress, reviewResult, reviewErrorProp, postedFindingIds, isReadyToMerge, newCommitsCheck, t]);
}, [isReviewing, reviewProgress, reviewResult, postedFindingIds, isReadyToMerge, newCommitsCheck, t]);
const handlePostReview = async () => {
const idsToPost = Array.from(selectedFindingIds);
@@ -1140,7 +1128,6 @@ ${t('prReview.blockedStatusMessageFooter')}`;
reviewResult={reviewResult}
previousReviewResult={previousReviewResult}
postedCount={new Set([...postedFindingIds, ...(reviewResult?.postedFindingIds ?? [])]).size}
reviewError={reviewErrorProp}
onRunReview={onRunReview}
onRunFollowupReview={onRunFollowupReview}
onCancelReview={onCancelReview}
@@ -1,5 +1,5 @@
import { useState } from 'react';
import { AlertCircle, CheckCircle, Circle, CircleDot, Play, RefreshCw } from 'lucide-react';
import { CheckCircle, Circle, CircleDot, Play, RefreshCw } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { Button } from '../../ui/button';
import { cn } from '../../../lib/utils';
@@ -26,7 +26,6 @@ export interface ReviewStatusTreeProps {
reviewResult: PRReviewResult | null;
previousReviewResult: PRReviewResult | null;
postedCount: number;
reviewError?: string | null;
onRunReview: () => void;
onRunFollowupReview: () => void;
onCancelReview: () => void;
@@ -46,7 +45,6 @@ export function ReviewStatusTree({
reviewResult,
previousReviewResult,
postedCount,
reviewError,
onRunReview,
onRunFollowupReview,
onCancelReview,
@@ -59,26 +57,8 @@ export function ReviewStatusTree({
// Determine if this is a follow-up review in progress (for edge case handling)
const isFollowupInProgress = isReviewing && (previousReviewResult !== null || reviewResult?.isFollowupReview);
// If not reviewed, show simple status (with error if present)
// If not reviewed, show simple status
if (status === 'not_reviewed' && !isReviewing) {
if (reviewError) {
return (
<div className="flex flex-wrap items-center justify-between gap-y-3 p-4 border rounded-lg bg-card shadow-sm border-destructive/30">
<div className="flex items-center gap-3 min-w-0">
<div className="h-2.5 w-2.5 shrink-0 rounded-full bg-destructive" />
<div className="min-w-0">
<span className="font-medium text-destructive truncate block">{t('prReview.reviewFailed')}</span>
<span className="text-xs text-muted-foreground truncate block mt-0.5">{reviewError}</span>
</div>
</div>
<Button onClick={onRunReview} size="sm" variant="outline" className="gap-2 shrink-0 ml-auto sm:ml-0">
<RefreshCw className="h-3.5 w-3.5" />
{t('prReview.retryReview')}
</Button>
</div>
);
}
return (
<div className="flex flex-wrap items-center justify-between gap-y-3 p-4 border rounded-lg bg-card shadow-sm">
<div className="flex items-center gap-3 min-w-0">
@@ -34,7 +34,6 @@ interface UseGitHubPRsResult {
isReviewing: boolean;
isExternalReview: boolean;
previousReviewResult: PRReviewResult | null;
reviewError: string | null;
isConnected: boolean;
repoFullName: string | null;
activePRReviews: number[]; // PR numbers currently being reviewed
@@ -118,7 +117,6 @@ export function useGitHubPRs(
const isExternalReview = selectedPRReviewState?.isExternalReview ?? false;
const previousReviewResult = selectedPRReviewState?.previousResult ?? null;
const startedAt = selectedPRReviewState?.startedAt ?? null;
const reviewError = selectedPRReviewState?.error ?? null;
// Get list of PR numbers currently being reviewed
const activePRReviews = useMemo(() => {
@@ -733,7 +731,6 @@ export function useGitHubPRs(
isReviewing,
isExternalReview,
previousReviewResult,
reviewError,
isConnected,
repoFullName,
activePRReviews,
@@ -362,7 +362,6 @@
"followup": "Follow-up",
"initial": "Initial",
"rerunFollowup": "Re-run follow-up review",
"retryReview": "Retry Review",
"rerunReview": "Re-run review",
"updateBranch": "Update Branch",
"updatingBranch": "Updating...",
@@ -371,7 +371,6 @@
"followup": "Suivi",
"initial": "Initial",
"rerunFollowup": "Relancer la revue de suivi",
"retryReview": "Réessayer la revue",
"rerunReview": "Relancer la revue",
"updateBranch": "Mettre à jour la branche",
"updatingBranch": "Mise à jour...",
@@ -126,16 +126,12 @@ export const taskMachine = createMachine(
on: {
CREATE_PR: 'creating_pr',
MARK_DONE: 'done',
USER_RESUMED: { target: 'coding', actions: 'clearReviewReason' },
// Allow restarting planning from human_review (e.g., incomplete task with no subtasks)
PLANNING_STARTED: { target: 'planning', actions: 'clearReviewReason' }
USER_RESUMED: { target: 'coding', actions: 'clearReviewReason' }
}
},
error: {
on: {
USER_RESUMED: { target: 'coding', actions: 'clearReviewReason' },
// Allow restarting from error back to planning (e.g., spec creation crashed)
PLANNING_STARTED: { target: 'planning', actions: 'clearReviewReason' },
MARK_DONE: 'done'
}
},
+3 -3
View File
@@ -1,12 +1,12 @@
{
"name": "auto-claude",
"version": "2.7.6-beta.6",
"version": "2.7.6-beta.3",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "auto-claude",
"version": "2.7.6-beta.6",
"version": "2.7.6-beta.3",
"license": "AGPL-3.0",
"workspaces": [
"apps/*",
@@ -25,7 +25,7 @@
},
"apps/frontend": {
"name": "auto-claude-ui",
"version": "2.7.6-beta.6",
"version": "2.7.6-beta.3",
"hasInstallScript": true,
"license": "AGPL-3.0",
"dependencies": {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "auto-claude",
"version": "2.7.6",
"version": "2.7.6-beta.5",
"description": "Autonomous multi-agent coding framework powered by Claude AI",
"license": "AGPL-3.0",
"author": "Auto Claude Team",
+877
View File
@@ -0,0 +1,877 @@
#!/usr/bin/env python3
"""
Tests for File Path Self-Healing in the Coder Pipeline
=======================================================
Tests cover:
- _find_correct_path: fuzzy file path matching (basename, index.{ext} pattern)
- _find_correct_path_indexed: same logic using pre-built index
- _build_file_index: file indexing with directory pruning
- _auto_correct_subtask_files: end-to-end correction with plan persistence
- _validate_plan_file_paths: post-planning validation of all file paths
- Phase dependency fix: stuck subtasks unblock downstream phases
"""
import json
import sys
from pathlib import Path
import pytest
# Ensure backend is on path
sys.path.insert(0, str(Path(__file__).parent.parent / "apps" / "backend"))
from agents.coder import (
_auto_correct_subtask_files,
_build_file_index,
_find_correct_path,
_find_correct_path_indexed,
_validate_plan_file_paths,
validate_subtask_files,
)
# =============================================================================
# FIXTURES
# =============================================================================
@pytest.fixture
def project_tree(tmp_path):
"""
Create a realistic project structure for path matching tests.
Structure:
src/
renderer/
components/
Button.tsx
Modal.tsx
stores/
task-store.ts
preload/
api/
index.ts <- the index.{ext} pattern
bridge/
index.ts
shared/
utils/
helpers.ts
format.ts
types/
common.ts
apps/
frontend/
src/
main/
agent/
agent-queue.ts
tests/
helpers.ts <- duplicate basename of shared/utils/helpers.ts
node_modules/
react/
index.ts <- should be excluded
.git/
config <- should be excluded
"""
# Source files
(tmp_path / "src/renderer/components").mkdir(parents=True)
(tmp_path / "src/renderer/components/Button.tsx").write_text("export {}")
(tmp_path / "src/renderer/components/Modal.tsx").write_text("export {}")
(tmp_path / "src/renderer/stores").mkdir(parents=True)
(tmp_path / "src/renderer/stores/task-store.ts").write_text("export {}")
(tmp_path / "src/preload/api").mkdir(parents=True)
(tmp_path / "src/preload/api/index.ts").write_text("export {}")
(tmp_path / "src/preload/bridge").mkdir(parents=True)
(tmp_path / "src/preload/bridge/index.ts").write_text("export {}")
(tmp_path / "src/shared/utils").mkdir(parents=True)
(tmp_path / "src/shared/utils/helpers.ts").write_text("export {}")
(tmp_path / "src/shared/utils/format.ts").write_text("export {}")
(tmp_path / "src/shared/types").mkdir(parents=True)
(tmp_path / "src/shared/types/common.ts").write_text("export {}")
(tmp_path / "apps/frontend/src/main/agent").mkdir(parents=True)
(tmp_path / "apps/frontend/src/main/agent/agent-queue.ts").write_text("export {}")
(tmp_path / "tests").mkdir(parents=True)
(tmp_path / "tests/helpers.ts").write_text("export {}")
# Excluded directories (should never match)
(tmp_path / "node_modules/react").mkdir(parents=True)
(tmp_path / "node_modules/react/index.ts").write_text("export {}")
(tmp_path / ".git").mkdir(parents=True)
(tmp_path / ".git/config").write_text("[core]")
return tmp_path
@pytest.fixture
def spec_dir_with_plan(tmp_path):
"""Create a spec directory with an implementation plan containing wrong paths."""
spec_dir = tmp_path / "spec"
spec_dir.mkdir()
plan = {
"feature": "test feature",
"phases": [
{
"id": "phase-1",
"name": "Phase 1",
"subtasks": [
{
"id": "task-1",
"description": "Fix the API",
"status": "pending",
"files_to_modify": [
"src/preload/api.ts", # Wrong: should be src/preload/api/index.ts
"src/renderer/components/Button.tsx", # Correct
],
},
{
"id": "task-2",
"description": "Update store",
"status": "pending",
"files_to_modify": [
"src/renderer/stores/task-store.ts", # Correct
],
},
],
}
],
}
(spec_dir / "implementation_plan.json").write_text(json.dumps(plan, indent=2))
return spec_dir
# =============================================================================
# _find_correct_path TESTS
# =============================================================================
class TestFindCorrectPath:
"""Tests for the _find_correct_path fuzzy file matcher."""
def test_index_pattern_match(self, project_tree):
"""preload/api.ts -> preload/api/index.ts (the core spec-232 scenario)."""
result = _find_correct_path("src/preload/api.ts", project_tree)
assert result is not None
assert Path(result) == Path("src/preload/api/index.ts")
def test_index_pattern_with_different_dir(self, project_tree):
"""preload/bridge.ts -> preload/bridge/index.ts."""
result = _find_correct_path("src/preload/bridge.ts", project_tree)
assert result is not None
assert Path(result) == Path("src/preload/bridge/index.ts")
def test_basename_match_in_different_dir(self, project_tree):
"""When file exists but in wrong directory, finds it by basename."""
result = _find_correct_path("src/utils/format.ts", project_tree)
assert result is not None
assert Path(result) == Path("src/shared/utils/format.ts")
def test_exact_basename_with_shared_parents_wins(self, project_tree):
"""Score prefers candidates sharing more parent directory segments."""
result = _find_correct_path("src/renderer/components/Modal.tsx", project_tree)
# File exists at the exact path, but _find_correct_path is only called
# for missing paths. Let's test a wrong parent instead.
result = _find_correct_path("src/components/Modal.tsx", project_tree)
assert result is not None
assert Path(result) == Path("src/renderer/components/Modal.tsx")
def test_no_match_for_nonexistent_file(self, project_tree):
"""Returns None when no file with matching basename or index pattern exists."""
result = _find_correct_path("src/does-not-exist.ts", project_tree)
assert result is None
def test_no_match_without_extension(self, project_tree):
"""Returns None for paths without file extension."""
result = _find_correct_path("src/preload/api", project_tree)
assert result is None
def test_excluded_dirs_not_matched(self, project_tree):
"""Files in node_modules/.git are never returned as matches."""
# The only index.ts files are in src/preload/api/ and src/preload/bridge/
# and node_modules/react/. A search for "react.ts" should not match
# node_modules/react/index.ts because node_modules is excluded.
result = _find_correct_path("react.ts", project_tree)
assert result is None
def test_ambiguous_match_returns_none(self, project_tree):
"""When two candidates have similar scores, returns None (ambiguous)."""
# "helpers.ts" exists at both:
# src/shared/utils/helpers.ts
# tests/helpers.ts
# With parent "foo/" (no shared segments), both score 10.0 with slight
# depth differences. The gap should be < 3.0 so it's ambiguous.
result = _find_correct_path("foo/helpers.ts", project_tree)
assert result is None
def test_unambiguous_basename_match_with_shared_parents(self, project_tree):
"""When one candidate clearly shares more parent path, it wins."""
# "helpers.ts" at src/shared/utils/helpers.ts vs tests/helpers.ts
# Searching for "src/shared/helpers.ts":
# src/shared/utils/helpers.ts: 10.0 + 3.0(src) + 3.0(shared) - 0.5 = 15.5
# tests/helpers.ts: 10.0 + 0 - 1.0 = 9.0
# Gap = 6.5 >= 3.0, so src/shared/utils/helpers.ts wins
result = _find_correct_path("src/shared/helpers.ts", project_tree)
assert result is not None
assert Path(result) == Path("src/shared/utils/helpers.ts")
def test_deeply_nested_path_still_matches(self, project_tree):
"""Files deep in the tree can be found when path is partially wrong."""
result = _find_correct_path(
"apps/frontend/src/main/agent-queue.ts", project_tree
)
assert result is not None
assert "agent-queue.ts" in result
# =============================================================================
# _build_file_index + _find_correct_path_indexed TESTS
# =============================================================================
class TestBuildFileIndex:
"""Tests for the file index builder."""
def test_indexes_files_by_basename(self, project_tree):
index = _build_file_index(project_tree, {".ts"})
assert "format.ts" in index
assert len(index["format.ts"]) == 1
def test_indexes_index_files_by_dir_stem(self, project_tree):
index = _build_file_index(project_tree, {".ts"})
# api/index.ts should be indexed under __dir_stem__:api.ts
key = "__dir_stem__:api.ts"
assert key in index
assert len(index[key]) == 1
assert "api/index.ts" in index[key][0][0]
def test_excludes_node_modules(self, project_tree):
index = _build_file_index(project_tree, {".ts"})
# node_modules/react/index.ts should NOT appear
for entries in index.values():
for rel_str, _ in entries:
assert "node_modules" not in rel_str
def test_excludes_git_dir(self, project_tree):
index = _build_file_index(project_tree, {".ts", ""})
for entries in index.values():
for rel_str, _ in entries:
assert ".git" not in rel_str
def test_multiple_suffixes(self, project_tree):
index = _build_file_index(project_tree, {".ts", ".tsx"})
assert "Button.tsx" in index
assert "format.ts" in index
def test_only_requested_suffixes(self, project_tree):
index = _build_file_index(project_tree, {".tsx"})
# .ts files should not be in the index
assert "format.ts" not in index
assert "Button.tsx" in index
class TestFindCorrectPathIndexed:
"""Tests for the indexed path finder (same logic, uses pre-built index)."""
def test_index_pattern_match(self, project_tree):
"""Same as _find_correct_path but using indexed version."""
index = _build_file_index(project_tree, {".ts"})
result = _find_correct_path_indexed(
"src/preload/api.ts", ("src", "preload"), index
)
assert result is not None
assert Path(result) == Path("src/preload/api/index.ts")
def test_basename_match(self, project_tree):
index = _build_file_index(project_tree, {".ts"})
result = _find_correct_path_indexed(
"src/shared/format.ts", ("src", "shared"), index
)
assert result is not None
assert Path(result) == Path("src/shared/utils/format.ts")
def test_no_match(self, project_tree):
index = _build_file_index(project_tree, {".ts"})
result = _find_correct_path_indexed(
"nonexistent.ts", (), index
)
assert result is None
def test_ambiguous_returns_none(self, project_tree):
index = _build_file_index(project_tree, {".ts"})
# "helpers.ts" has two matches with no shared parent context
result = _find_correct_path_indexed(
"foo/helpers.ts", ("foo",), index
)
assert result is None
# =============================================================================
# _auto_correct_subtask_files TESTS
# =============================================================================
class TestAutoCorrectSubtaskFiles:
"""Tests for auto-correcting file paths in a subtask."""
def test_corrects_index_pattern_and_persists(self, project_tree, tmp_path):
"""Corrects api.ts -> api/index.ts and writes to plan file."""
spec_dir = tmp_path / "spec"
spec_dir.mkdir()
plan = {
"phases": [
{
"id": "p1",
"subtasks": [
{
"id": "t1",
"status": "pending",
"files_to_modify": [
"src/preload/api.ts",
"src/renderer/components/Button.tsx",
],
}
],
}
]
}
(spec_dir / "implementation_plan.json").write_text(json.dumps(plan))
subtask = {
"id": "t1",
"files_to_modify": [
"src/preload/api.ts",
"src/renderer/components/Button.tsx",
],
}
still_missing = _auto_correct_subtask_files(
subtask, ["src/preload/api.ts"], project_tree, spec_dir
)
# No files should remain missing
assert still_missing == []
# In-memory subtask should be updated
assert "src/preload/api/index.ts" in subtask["files_to_modify"]
assert "src/preload/api.ts" not in subtask["files_to_modify"]
# Plan file should be persisted with correction
saved_plan = json.loads(
(spec_dir / "implementation_plan.json").read_text()
)
saved_files = saved_plan["phases"][0]["subtasks"][0]["files_to_modify"]
assert "src/preload/api/index.ts" in saved_files
assert "src/preload/api.ts" not in saved_files
def test_uncorrectable_files_returned(self, project_tree, tmp_path):
"""Files with no match are returned as still missing."""
spec_dir = tmp_path / "spec"
spec_dir.mkdir()
plan = {"phases": [{"id": "p1", "subtasks": [{"id": "t1", "status": "pending", "files_to_modify": ["nonexistent.ts"]}]}]}
(spec_dir / "implementation_plan.json").write_text(json.dumps(plan))
subtask = {"id": "t1", "files_to_modify": ["nonexistent.ts"]}
still_missing = _auto_correct_subtask_files(
subtask, ["nonexistent.ts"], project_tree, spec_dir
)
assert still_missing == ["nonexistent.ts"]
def test_no_corrections_skips_write(self, project_tree, tmp_path):
"""When nothing can be corrected, plan file is not rewritten."""
spec_dir = tmp_path / "spec"
spec_dir.mkdir()
original_content = json.dumps({"phases": [{"id": "p1", "subtasks": [{"id": "t1", "status": "pending", "files_to_modify": ["gone.ts"]}]}]})
plan_file = spec_dir / "implementation_plan.json"
plan_file.write_text(original_content)
mtime_before = plan_file.stat().st_mtime
subtask = {"id": "t1", "files_to_modify": ["gone.ts"]}
_auto_correct_subtask_files(subtask, ["gone.ts"], project_tree, spec_dir)
# File should not have been rewritten (mtime unchanged)
assert plan_file.stat().st_mtime == mtime_before
def test_corrects_in_memory_without_plan_file(self, project_tree, tmp_path):
"""When implementation_plan.json does not exist, corrections still apply in-memory."""
spec_dir = tmp_path / "spec"
spec_dir.mkdir()
# Deliberately do NOT create implementation_plan.json
subtask = {
"id": "t1",
"files_to_modify": [
"src/preload/api.ts",
"src/renderer/components/Button.tsx",
],
}
still_missing = _auto_correct_subtask_files(
subtask, ["src/preload/api.ts"], project_tree, spec_dir
)
# All correctable files should be resolved
assert still_missing == []
# In-memory subtask should be updated with corrected path
assert "src/preload/api/index.ts" in subtask["files_to_modify"]
assert "src/preload/api.ts" not in subtask["files_to_modify"]
# Uncorrected file should remain unchanged
assert "src/renderer/components/Button.tsx" in subtask["files_to_modify"]
# Plan file should still not exist (no side-effect creation)
assert not (spec_dir / "implementation_plan.json").exists()
def test_corrects_in_memory_with_corrupt_plan_file(self, project_tree, tmp_path):
"""When implementation_plan.json contains invalid JSON, corrections still apply in-memory."""
spec_dir = tmp_path / "spec"
spec_dir.mkdir()
# Write corrupt plan file
plan_file = spec_dir / "implementation_plan.json"
plan_file.write_text("not valid json")
subtask = {
"id": "t1",
"files_to_modify": [
"src/preload/api.ts",
"src/renderer/components/Button.tsx",
],
}
still_missing = _auto_correct_subtask_files(
subtask, ["src/preload/api.ts"], project_tree, spec_dir
)
# All correctable files should be resolved
assert still_missing == []
# In-memory subtask should be updated with corrected path
assert "src/preload/api/index.ts" in subtask["files_to_modify"]
assert "src/preload/api.ts" not in subtask["files_to_modify"]
# Corrupt plan file should be left unchanged (not overwritten or deleted)
assert plan_file.read_text() == "not valid json"
# =============================================================================
# validate_subtask_files (with auto-correction integration) TESTS
# =============================================================================
class TestValidateSubtaskFilesWithCorrection:
"""Tests for validate_subtask_files with auto-correction enabled."""
def test_passes_when_all_files_exist(self, project_tree):
subtask = {
"files_to_modify": [
"src/renderer/components/Button.tsx",
"src/shared/utils/format.ts",
]
}
result = validate_subtask_files(subtask, project_tree)
assert result["success"] is True
def test_fails_without_spec_dir(self, project_tree):
"""Without spec_dir, auto-correction is skipped and validation fails."""
subtask = {"files_to_modify": ["src/preload/api.ts"]}
result = validate_subtask_files(subtask, project_tree)
assert result["success"] is False
assert "src/preload/api.ts" in result["missing_files"]
def test_auto_corrects_with_spec_dir(self, project_tree, tmp_path):
"""With spec_dir, auto-correction fixes the path and passes."""
spec_dir = tmp_path / "spec"
spec_dir.mkdir()
plan = {
"phases": [
{
"id": "p1",
"subtasks": [
{"id": "t1", "status": "pending", "files_to_modify": ["src/preload/api.ts"]}
],
}
]
}
(spec_dir / "implementation_plan.json").write_text(json.dumps(plan))
subtask = {"id": "t1", "files_to_modify": ["src/preload/api.ts"]}
result = validate_subtask_files(subtask, project_tree, spec_dir)
assert result["success"] is True
def test_rejects_path_traversal(self, project_tree):
"""Paths that resolve outside project are rejected."""
subtask = {"files_to_modify": ["../../etc/passwd"]}
result = validate_subtask_files(subtask, project_tree)
assert result["success"] is False
assert len(result["invalid_paths"]) > 0
# =============================================================================
# _validate_plan_file_paths TESTS
# =============================================================================
class TestValidatePlanFilePaths:
"""Tests for post-planning file path validation."""
def test_all_paths_valid_returns_none(self, project_tree, tmp_path):
"""When all paths exist, returns None (no issues)."""
spec_dir = tmp_path / "spec"
spec_dir.mkdir()
plan = {
"phases": [
{
"id": "p1",
"subtasks": [
{
"id": "t1",
"status": "pending",
"files_to_modify": [
"src/renderer/components/Button.tsx",
"src/shared/utils/format.ts",
],
}
],
}
]
}
(spec_dir / "implementation_plan.json").write_text(json.dumps(plan))
result = _validate_plan_file_paths(spec_dir, project_tree)
assert result is None
def test_auto_corrects_and_returns_none(self, project_tree, tmp_path):
"""Correctable paths are fixed, plan persisted, returns None."""
spec_dir = tmp_path / "spec"
spec_dir.mkdir()
plan = {
"phases": [
{
"id": "p1",
"subtasks": [
{
"id": "t1",
"status": "pending",
"files_to_modify": ["src/preload/api.ts"],
}
],
}
]
}
(spec_dir / "implementation_plan.json").write_text(json.dumps(plan))
result = _validate_plan_file_paths(spec_dir, project_tree)
assert result is None
# Verify plan was updated on disk
saved = json.loads((spec_dir / "implementation_plan.json").read_text())
assert saved["phases"][0]["subtasks"][0]["files_to_modify"] == [
"src/preload/api/index.ts"
]
def test_uncorrectable_returns_retry_context(self, project_tree, tmp_path):
"""Returns retry context string when paths can't be corrected."""
spec_dir = tmp_path / "spec"
spec_dir.mkdir()
plan = {
"phases": [
{
"id": "p1",
"subtasks": [
{
"id": "t1",
"status": "pending",
"files_to_modify": ["totally/fake/path.ts"],
}
],
}
]
}
(spec_dir / "implementation_plan.json").write_text(json.dumps(plan))
result = _validate_plan_file_paths(spec_dir, project_tree)
assert result is not None
assert "FILE PATH VALIDATION ERRORS" in result
assert "totally/fake/path.ts" in result
def test_mixed_valid_invalid_correctable(self, project_tree, tmp_path):
"""Mix of correct, correctable, and uncorrectable paths across subtasks."""
spec_dir = tmp_path / "spec"
spec_dir.mkdir()
plan = {
"phases": [
{
"id": "p1",
"subtasks": [
{
"id": "t1",
"status": "pending",
"files_to_modify": [
"src/renderer/components/Button.tsx", # valid
"src/preload/api.ts", # correctable
],
},
{
"id": "t2",
"status": "pending",
"files_to_modify": [
"nonexistent/file.xyz", # uncorrectable
],
},
],
}
]
}
(spec_dir / "implementation_plan.json").write_text(json.dumps(plan))
result = _validate_plan_file_paths(spec_dir, project_tree)
assert result is not None
assert "nonexistent/file.xyz" in result
# api.ts should have been corrected
assert "api.ts" not in result
def test_no_plan_file_returns_none(self, tmp_path):
"""Returns None if implementation_plan.json doesn't exist."""
spec_dir = tmp_path / "spec"
spec_dir.mkdir()
result = _validate_plan_file_paths(spec_dir, tmp_path)
assert result is None
def test_subtask_without_files_to_modify(self, project_tree, tmp_path):
"""Subtasks with no files_to_modify are gracefully skipped."""
spec_dir = tmp_path / "spec"
spec_dir.mkdir()
plan = {
"phases": [
{
"id": "p1",
"subtasks": [
{"id": "t1", "status": "pending", "description": "No files"},
],
}
]
}
(spec_dir / "implementation_plan.json").write_text(json.dumps(plan))
result = _validate_plan_file_paths(spec_dir, project_tree)
assert result is None
# =============================================================================
# PHASE DEPENDENCY FIX (progress.py get_next_subtask) TESTS
# =============================================================================
class TestStuckSubtasksUnblockPhases:
"""Tests that stuck subtasks in a phase allow downstream phases to proceed."""
def _write_plan(self, spec_dir, plan):
(spec_dir / "implementation_plan.json").write_text(json.dumps(plan))
def _write_stuck(self, spec_dir, stuck_ids):
memory_dir = spec_dir / "memory"
memory_dir.mkdir(parents=True, exist_ok=True)
history = {
"subtasks": {},
"stuck_subtasks": [
{"subtask_id": sid, "reason": "test"} for sid in stuck_ids
],
"metadata": {"created_at": "2025-01-01", "last_updated": "2025-01-01"},
}
(memory_dir / "attempt_history.json").write_text(json.dumps(history))
def test_stuck_in_phase1_unblocks_phase2(self, tmp_path):
"""When all non-completed subtasks in phase 1 are stuck, phase 2 proceeds."""
from progress import get_next_subtask
spec_dir = tmp_path / "spec"
spec_dir.mkdir()
plan = {
"phases": [
{
"id": "1",
"name": "Phase 1",
"subtasks": [
{"id": "1.1", "status": "completed"},
{"id": "1.2", "status": "pending"}, # This one is stuck
],
},
{
"id": "2",
"name": "Phase 2",
"depends_on": ["1"],
"subtasks": [
{"id": "2.1", "status": "pending"},
],
},
]
}
self._write_plan(spec_dir, plan)
self._write_stuck(spec_dir, ["1.2"])
result = get_next_subtask(spec_dir)
assert result is not None
assert result["id"] == "2.1", "Phase 2 should be unblocked since 1.2 is stuck"
def test_completed_plus_stuck_unblocks(self, tmp_path):
"""Phase with mix of completed and stuck subtasks counts as resolved."""
from progress import get_next_subtask
spec_dir = tmp_path / "spec"
spec_dir.mkdir()
plan = {
"phases": [
{
"id": "1",
"name": "Phase 1",
"subtasks": [
{"id": "1.1", "status": "completed"},
{"id": "1.2", "status": "completed"},
{"id": "1.3", "status": "pending"}, # stuck
],
},
{
"id": "2",
"name": "Phase 2",
"depends_on": ["1"],
"subtasks": [
{"id": "2.1", "status": "pending"},
],
},
]
}
self._write_plan(spec_dir, plan)
self._write_stuck(spec_dir, ["1.3"])
result = get_next_subtask(spec_dir)
assert result is not None
assert result["id"] == "2.1"
def test_pending_non_stuck_blocks_phase(self, tmp_path):
"""Phase with a pending (non-stuck) subtask still blocks dependents."""
from progress import get_next_subtask
spec_dir = tmp_path / "spec"
spec_dir.mkdir()
plan = {
"phases": [
{
"id": "1",
"name": "Phase 1",
"subtasks": [
{"id": "1.1", "status": "completed"},
{"id": "1.2", "status": "pending"}, # stuck
{"id": "1.3", "status": "pending"}, # NOT stuck
],
},
{
"id": "2",
"name": "Phase 2",
"depends_on": ["1"],
"subtasks": [
{"id": "2.1", "status": "pending"},
],
},
]
}
self._write_plan(spec_dir, plan)
self._write_stuck(spec_dir, ["1.2"])
result = get_next_subtask(spec_dir)
assert result is not None
# Should pick 1.3 (pending, not stuck) from phase 1, NOT 2.1
assert result["id"] == "1.3"
def test_all_phases_stuck_returns_none(self, tmp_path):
"""When every pending subtask across all phases is stuck, returns None."""
from progress import get_next_subtask
spec_dir = tmp_path / "spec"
spec_dir.mkdir()
plan = {
"phases": [
{
"id": "1",
"name": "Phase 1",
"subtasks": [
{"id": "1.1", "status": "pending"},
],
},
{
"id": "2",
"name": "Phase 2",
"depends_on": ["1"],
"subtasks": [
{"id": "2.1", "status": "pending"},
],
},
]
}
self._write_plan(spec_dir, plan)
self._write_stuck(spec_dir, ["1.1", "2.1"])
result = get_next_subtask(spec_dir)
assert result is None
def test_chain_of_three_phases_with_stuck(self, tmp_path):
"""Phase 1 stuck -> phase 2 stuck -> phase 3 can still run."""
from progress import get_next_subtask
spec_dir = tmp_path / "spec"
spec_dir.mkdir()
plan = {
"phases": [
{
"id": "1",
"name": "Phase 1",
"subtasks": [
{"id": "1.1", "status": "pending"},
],
},
{
"id": "2",
"name": "Phase 2",
"depends_on": ["1"],
"subtasks": [
{"id": "2.1", "status": "pending"},
],
},
{
"id": "3",
"name": "Phase 3",
"depends_on": ["2"],
"subtasks": [
{"id": "3.1", "status": "pending"},
],
},
]
}
self._write_plan(spec_dir, plan)
self._write_stuck(spec_dir, ["1.1", "2.1"])
result = get_next_subtask(spec_dir)
assert result is not None
assert result["id"] == "3.1"
-130
View File
@@ -337,136 +337,6 @@ class TestGitHubCLIInvocation:
assert result["success"] is True
class TestGitHubOriginPrefixStripping:
"""Test that origin/ prefix is stripped from target_branch in create_pull_request."""
def test_origin_prefix_stripped_from_target_branch(self, tmp_path):
"""Test that 'origin/develop' becomes 'develop' in --base argument to gh CLI."""
# Setup
project_dir = tmp_path / "project"
project_dir.mkdir()
spec_dir = tmp_path / "spec"
spec_dir.mkdir()
# Create .auto-claude directories
auto_claude_dir = project_dir / ".auto-claude"
auto_claude_dir.mkdir(exist_ok=True)
# Create WorktreeManager
manager = WorktreeManager(
project_dir=project_dir,
base_branch="main",
)
# Mock get_worktree_info to return a valid WorktreeInfo
mock_worktree_info = WorktreeInfo(
path=spec_dir,
branch="auto-claude/001-test-spec",
spec_name="001-test-spec",
base_branch="main",
is_active=True,
)
# Mock subprocess result
mock_subprocess_result = MagicMock(
returncode=0,
stdout="https://github.com/user/repo/pull/123\n",
stderr="",
)
# Import the actual module to patch it directly
import core.worktree as worktree_module
with (
patch.object(manager, "get_worktree_info", return_value=mock_worktree_info),
patch.object(
worktree_module, "get_gh_executable", return_value="/usr/bin/gh"
),
patch.object(
worktree_module.subprocess, "run", return_value=mock_subprocess_result
) as mock_run,
patch.object(manager, "_extract_spec_summary", return_value="Test PR body"),
):
result = manager.create_pull_request(
spec_name="001-test-spec",
target_branch="origin/develop",
title="Test PR Title",
draft=False,
)
# Verify gh CLI received "develop" (not "origin/develop") as --base
assert mock_run.called
call_args = mock_run.call_args[0][0]
base_idx = call_args.index("--base")
assert call_args[base_idx + 1] == "develop", (
f"Expected 'develop' after --base, got '{call_args[base_idx + 1]}'"
)
assert result["success"] is True
def test_target_branch_without_origin_prefix_unchanged(self, tmp_path):
"""Test that 'develop' (no prefix) is passed through unchanged to gh CLI."""
# Setup
project_dir = tmp_path / "project"
project_dir.mkdir()
spec_dir = tmp_path / "spec"
spec_dir.mkdir()
# Create .auto-claude directories
auto_claude_dir = project_dir / ".auto-claude"
auto_claude_dir.mkdir(exist_ok=True)
# Create WorktreeManager
manager = WorktreeManager(
project_dir=project_dir,
base_branch="main",
)
# Mock get_worktree_info to return a valid WorktreeInfo
mock_worktree_info = WorktreeInfo(
path=spec_dir,
branch="auto-claude/001-test-spec",
spec_name="001-test-spec",
base_branch="main",
is_active=True,
)
# Mock subprocess result
mock_subprocess_result = MagicMock(
returncode=0,
stdout="https://github.com/user/repo/pull/123\n",
stderr="",
)
# Import the actual module to patch it directly
import core.worktree as worktree_module
with (
patch.object(manager, "get_worktree_info", return_value=mock_worktree_info),
patch.object(
worktree_module, "get_gh_executable", return_value="/usr/bin/gh"
),
patch.object(
worktree_module.subprocess, "run", return_value=mock_subprocess_result
) as mock_run,
patch.object(manager, "_extract_spec_summary", return_value="Test PR body"),
):
result = manager.create_pull_request(
spec_name="001-test-spec",
target_branch="develop",
title="Test PR Title",
draft=False,
)
# Verify gh CLI received "develop" as --base
assert mock_run.called
call_args = mock_run.call_args[0][0]
base_idx = call_args.index("--base")
assert call_args[base_idx + 1] == "develop", (
f"Expected 'develop' after --base, got '{call_args[base_idx + 1]}'"
)
assert result["success"] is True
class TestGitHubErrorHandling:
"""Test that GitHub error handling still works correctly."""
-112
View File
@@ -270,118 +270,6 @@ class TestCreateMergeRequest:
assert result["pr_url"] == "https://gitlab.com/user/repo/-/merge_requests/44"
class TestGitLabOriginPrefixStripping:
"""Test that origin/ prefix is stripped from target_branch in create_merge_request."""
def test_origin_prefix_stripped_from_target_branch(
self, worktree_manager, temp_project_dir
):
"""Test that 'origin/develop' becomes 'develop' in --target-branch argument to glab CLI."""
import core.worktree as worktree_module
spec_name = "test-feature"
mock_worktree_info = WorktreeInfo(
path=temp_project_dir / ".auto-claude" / "worktrees" / "tasks" / spec_name,
branch=f"auto-claude/{spec_name}",
spec_name=spec_name,
base_branch="main",
is_active=True,
)
mock_subprocess_result = MagicMock(
returncode=0,
stdout="https://gitlab.com/user/repo/-/merge_requests/42\n",
stderr="",
)
with (
patch.object(
worktree_manager, "get_worktree_info", return_value=mock_worktree_info
),
patch.object(
worktree_module,
"get_glab_executable",
return_value="/usr/local/bin/glab",
),
patch.object(
worktree_module.subprocess, "run", return_value=mock_subprocess_result
) as mock_run,
patch.object(
worktree_manager, "_extract_spec_summary", return_value="Test MR body"
),
):
result = worktree_manager.create_merge_request(
spec_name=spec_name,
target_branch="origin/develop",
title="Test MR",
draft=False,
)
# Verify glab CLI received "develop" (not "origin/develop") as --target-branch
assert mock_run.called
call_args = mock_run.call_args[0][0]
target_idx = call_args.index("--target-branch")
assert call_args[target_idx + 1] == "develop", (
f"Expected 'develop' after --target-branch, got '{call_args[target_idx + 1]}'"
)
assert result["success"] is True
def test_target_branch_without_origin_prefix_unchanged(
self, worktree_manager, temp_project_dir
):
"""Test that 'develop' (no prefix) is passed through unchanged to glab CLI."""
import core.worktree as worktree_module
spec_name = "test-feature"
mock_worktree_info = WorktreeInfo(
path=temp_project_dir / ".auto-claude" / "worktrees" / "tasks" / spec_name,
branch=f"auto-claude/{spec_name}",
spec_name=spec_name,
base_branch="main",
is_active=True,
)
mock_subprocess_result = MagicMock(
returncode=0,
stdout="https://gitlab.com/user/repo/-/merge_requests/43\n",
stderr="",
)
with (
patch.object(
worktree_manager, "get_worktree_info", return_value=mock_worktree_info
),
patch.object(
worktree_module,
"get_glab_executable",
return_value="/usr/local/bin/glab",
),
patch.object(
worktree_module.subprocess, "run", return_value=mock_subprocess_result
) as mock_run,
patch.object(
worktree_manager, "_extract_spec_summary", return_value="Test MR body"
),
):
result = worktree_manager.create_merge_request(
spec_name=spec_name,
target_branch="develop",
title="Test MR",
draft=False,
)
# Verify glab CLI received "develop" as --target-branch
assert mock_run.called
call_args = mock_run.call_args[0][0]
target_idx = call_args.index("--target-branch")
assert call_args[target_idx + 1] == "develop", (
f"Expected 'develop' after --target-branch, got '{call_args[target_idx + 1]}'"
)
assert result["success"] is True
class TestPushAndCreatePR:
"""Test push_and_create_pr method with provider detection."""