Compare commits

..

2 Commits

Author SHA1 Message Date
AndyMik90 31c6c27c52 fix: singleton services + comprehensive test suite for MCP server
- Fix ExecutionService singleton: build_stop/get_progress/get_logs now
  share state with build_start via module-level lazy singleton
- Fix MemoryService singleton: cached Graphiti connection preserved
  across tool calls instead of re-initializing each time
- Fix MemoryService private API: use public get_relevant_context()
  instead of private _search attribute
- Add 380 tests across 12 test files covering all MCP server modules:
  config, operations, server, tasks, specs, execution, QA, workspace,
  project, ops, github, and feature tools (insights/roadmap/ideation/memory)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-16 08:47:37 +01:00
AndyMik90 8ab939e11e feat: add MCP server control plane for Auto Claude pipeline
Implements a FastMCP-based MCP server that exposes the full Auto Claude
backend as 43 tools across 12 categories. Any MCP client (Claude Code,
Claude Desktop, future web app) can now manage the autonomous coding
pipeline programmatically.

Architecture:
- FastMCP server with stdio/SSE/HTTP transport options
- Service layer wrapping existing backend modules (no duplication)
- Long-running operation tracker with polling pattern
- Stdout isolation to prevent MCP protocol corruption

Tool categories (43 total):
- Project (4): set_active, get_status, list_specs, get_index
- Tasks (6): list, create, get, update, delete, update_status
- Specs (4): create, get_status, get_content, list
- Execution (4): build_start/stop/progress/logs
- QA (3): start_review, get_report, approve
- Workspace (5): list, diff, merge, discard, create_pr
- GitHub (5): review_pr, list_issues, auto_fix, get_review, triage
- Insights (2): ask, suggest_tasks
- Roadmap (3): generate, get, refresh
- Ideation (2): generate, get
- Memory (3): search, add_episode, get_recent
- Operations (2): get_status, cancel

Usage:
  python -m mcp_server --project-dir /path/to/project

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-15 20:23:11 +01:00
222 changed files with 10788 additions and 13100 deletions
-1
View File
@@ -3,7 +3,6 @@ name: Discord Release Notification
on:
release:
types: [published]
workflow_dispatch:
jobs:
discord-notification:
+1 -1
View File
@@ -620,7 +620,7 @@ jobs:
draft: false
prerelease: ${{ contains(github.ref, 'beta') || contains(github.ref, 'alpha') }}
env:
GITHUB_TOKEN: ${{ secrets.PAT_TOKEN || secrets.GITHUB_TOKEN }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
# Update README with new version after successful release
update-readme:
+1 -1
View File
@@ -13,7 +13,7 @@ jobs:
issues: write
pull-requests: write
steps:
- uses: actions/first-interaction@v3
- uses: actions/first-interaction@v1
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
issue-message: |
-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
+11 -39
View File
@@ -30,55 +30,27 @@ Auto Claude is a desktop application (+ CLI) where users describe a goal and AI
## Critical Rules
**Claude Agent SDK only** — All AI interactions use `claude-agent-sdk` because it handles security hooks, tool permissions, and MCP server integration. Use `create_client()` from `core.client`, not `anthropic.Anthropic()` directly.
**Claude Agent SDK only** — All AI interactions use `claude-agent-sdk`. NEVER use `anthropic.Anthropic()` directly. Always use `create_client()` from `core.client`.
**i18n required** — All frontend user-facing text uses `react-i18next` translation keys. Hardcoded strings in JSX/TSX break localization for non-English users. Add keys to both `en/*.json` and `fr/*.json`.
**i18n required** — All frontend user-facing text MUST use `react-i18next` translation keys. Never hardcode strings in JSX/TSX. Add keys to both `en/*.json` and `fr/*.json`.
**Platform abstraction**Use the platform modules in `apps/frontend/src/main/platform/` or `apps/backend/core/platform/` instead of `process.platform` directly. CI tests all three platforms, and raw platform checks cause failures.
**Platform abstraction**Never use `process.platform` directly. Import from `apps/frontend/src/main/platform/` or `apps/backend/core/platform/`. CI tests all three platforms.
**No time estimates**Provide priority-based ordering instead of duration predictions.
**No time estimates**Never provide duration predictions. Use priority-based ordering instead.
**PR target** — Always target the `develop` branch for PRs, not `main`. Main is reserved for releases.
**PR target** — Always target the `develop` branch for PRs to AndyMik90/Auto-Claude, NOT `main`.
**No console.log in production code**`console.log` output is invisible in bundled Electron apps. Use Sentry for error tracking in production; reserve `console.log` for development only.
## Work Approach
## Work Approach: Orchestrator-First
**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.
You are an orchestrator. Your primary role is to understand what needs to be done, break it into workstreams, and delegate execution to agent teams. This keeps your context window focused on coordination and decision-making rather than filling up with implementation details.
**Spawn agents for complex tasks** — When tackling complex tasks, spawn sub-agents/agent teams immediately rather than trying to handle everything in a single context window. Never attempt to analyze large codebases or multiple features monolithically.
<orchestrator_pattern>
When given a task, follow this pattern:
1. **Investigate first** — Read the actual code before forming any hypothesis. Use targeted searches (Glob, Grep, Read) for simple lookups. For broader exploration, spawn an Explore agent.
2. **Plan the approach** — Identify what needs to change, which files are involved, and whether work can be parallelized. For multi-step tasks, create a task list to track workstreams.
3. **Delegate execution** — Spawn agent teams to do the implementation work. Each agent gets a clear, self-contained assignment with all the context it needs: relevant file paths, the specific change to make, and acceptance criteria. Run independent workstreams in parallel.
4. **Verify and integrate** — Review agent outputs, run tests, and ensure changes work together. Fix integration issues or spawn follow-up agents as needed.
</orchestrator_pattern>
**When to delegate vs. do directly:**
- Delegate: multi-file changes, research across the codebase, independent parallel workstreams, tasks that would consume significant context
- Do directly: single-file edits, simple bug fixes, quick lookups, tasks where you already have the context
**Giving agents good assignments** — Each agent works with a fresh context. Include: the specific goal, relevant file paths, code patterns to follow, and what "done" looks like. Agents perform better with explicit, complete instructions than with vague references to "the current task."
**Minimal changes only** — Prefer the simplest approach (e.g., prompt-only changes, single guard clause) before suggesting multi-component solutions. If the user asks for X, implement X — don't bundle additional fixes they didn't request.
**Default to action** — When the user's intent implies making changes, implement them rather than only suggesting. If something is unclear, read the relevant code to fill in the gaps rather than asking. Only ask when genuine ambiguity remains about what the user wants.
## Context Management
Your context window will be automatically compacted as it approaches its limit, allowing you to continue working indefinitely. Do not stop tasks early due to context concerns — instead, persist progress and keep going.
**For long-running tasks:** Use git commits, task lists, and structured notes to track state. When context compacts, review git log and any progress files to re-orient. Focus on incremental progress — complete one component before moving to the next, and commit working states along the way.
**Parallel tool calls** — When reading multiple files, running independent searches, or executing unrelated commands, make all calls in parallel rather than sequentially. This significantly speeds up investigation and implementation.
**Minimal fixes only** — Prefer the simplest approach (e.g., prompt-only changes, single guard clause) before suggesting multi-component solutions. If the user asks for X, implement X — don't bundle additional fixes they didn't request.
## Known Gotchas
**Electron path resolution** — For bug fixes in the Electron app, check path resolution differences between dev and production builds (`app.isPackaged`, `process.resourcesPath`). Paths that work in dev often break when Electron is bundled for production — verify both contexts.
**Electron path resolution** — For bug fixes in the Electron app, always check path resolution differences between dev and production builds (`app.isPackaged`, `process.resourcesPath`). Paths that work in dev often break when Electron is bundled for production — verify both contexts.
### Resetting PR Review State
@@ -304,7 +276,7 @@ Supports Windows, macOS, Linux. CI tests all three.
| `findExecutable(name)` | Cross-platform executable lookup |
| `requiresShell(command)` | `.cmd/.bat` shell detection (Win) |
Use `findExecutable()` and `joinPaths()` instead of hardcoded paths. See [ARCHITECTURE.md](shared_docs/ARCHITECTURE.md#cross-platform-development) for extended guide.
Never hardcode paths. Use `findExecutable()` and `joinPaths()`. See [ARCHITECTURE.md](shared_docs/ARCHITECTURE.md#cross-platform-development) for extended guide.
## E2E Testing (Electron MCP)
+14 -14
View File
@@ -17,18 +17,18 @@
### Stable Release
<!-- STABLE_VERSION_BADGE -->
[![Stable](https://img.shields.io/badge/stable-2.7.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"
+5 -445
View File
@@ -13,9 +13,7 @@ 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,
@@ -86,7 +84,6 @@ 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,
@@ -100,383 +97,8 @@ 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 _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:
def validate_subtask_files(subtask: dict, project_dir: Path) -> dict:
"""
Validate all files_to_modify exist before subtask execution.
@@ -514,15 +136,6 @@ def validate_subtask_files(
}
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)}",
@@ -1072,10 +685,7 @@ 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
# Pass spec_dir to enable auto-correction of wrong paths
validation_result = validate_subtask_files(
next_subtask, project_dir, spec_dir
)
validation_result = validate_subtask_files(next_subtask, project_dir)
if not validation_result["success"]:
# File validation failed - record error and skip session
error_msg = validation_result["error"]
@@ -1109,11 +719,6 @@ 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",
@@ -1207,28 +812,8 @@ async def run_autonomous_agent(
if is_planning_phase and status != "error":
valid, errors = _validate_and_fix_implementation_plan()
if valid:
# 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
plan_validated = True
planning_retry_context = None
else:
planning_validation_failures += 1
if planning_validation_failures >= max_planning_validation_retries:
@@ -1286,11 +871,6 @@ 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",
@@ -1650,24 +1230,4 @@ async def run_autonomous_agent(
if completed == total:
status_manager.update(state=BuildState.COMPLETE)
else:
# 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)
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(
+2 -6
View File
@@ -101,12 +101,8 @@ def handle_qa_command(
print("\n✅ Build already approved by QA.")
else:
completed, total = count_subtasks(spec_dir)
print(
f"\n❌ Build not ready for QA ({completed}/{total} subtasks completed)."
)
print(
"All subtasks must reach a terminal state (completed, failed, or stuck) before running QA."
)
print(f"\n❌ Build not complete ({completed}/{total} subtasks).")
print("Complete all subtasks before running QA validation.")
return
if has_human_feedback:
+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
+17 -64
View File
@@ -115,65 +115,6 @@ def is_build_complete(spec_dir: Path) -> bool:
return total > 0 and completed == total
def _load_stuck_subtask_ids(spec_dir: Path) -> set[str]:
"""Load IDs of subtasks marked as stuck from attempt_history.json."""
stuck_subtask_ids: set[str] = set()
attempt_history_file = spec_dir / "memory" / "attempt_history.json"
if attempt_history_file.exists():
try:
with open(attempt_history_file, encoding="utf-8") as f:
attempt_history = json.load(f)
for entry in attempt_history.get("stuck_subtasks", []):
if "subtask_id" in entry:
stuck_subtask_ids.add(entry["subtask_id"])
except (OSError, json.JSONDecodeError, UnicodeDecodeError):
# Corrupted attempt history is non-fatal; skip stuck-subtask filtering
pass
return stuck_subtask_ids
def is_build_ready_for_qa(spec_dir: Path) -> bool:
"""
Check if the build is ready for QA validation.
Unlike is_build_complete() which requires all subtasks to be "completed",
this function considers the build ready when all subtasks have reached
a terminal state: completed, failed, or stuck (exhausted retries in attempt_history.json).
Args:
spec_dir: Directory containing implementation_plan.json
Returns:
True if all subtasks are in a terminal state, False otherwise
"""
plan_file = spec_dir / "implementation_plan.json"
if not plan_file.exists():
return False
stuck_subtask_ids = _load_stuck_subtask_ids(spec_dir)
try:
with open(plan_file, encoding="utf-8") as f:
plan = json.load(f)
total = 0
terminal = 0
for phase in plan.get("phases", []):
for subtask in phase.get("subtasks", []):
total += 1
status = subtask.get("status", "pending")
subtask_id = subtask.get("id")
if status in ("completed", "failed") or subtask_id in stuck_subtask_ids:
terminal += 1
return total > 0 and terminal == total
except (OSError, json.JSONDecodeError, UnicodeDecodeError):
return False
def get_progress_percentage(spec_dir: Path) -> float:
"""
Get the progress as a percentage.
@@ -479,7 +420,22 @@ def get_next_subtask(spec_dir: Path) -> dict | None:
if not plan_file.exists():
return None
stuck_subtask_ids = _load_stuck_subtask_ids(spec_dir)
# Load stuck subtasks from recovery manager's attempt history
stuck_subtask_ids = set()
attempt_history_file = spec_dir / "memory" / "attempt_history.json"
if attempt_history_file.exists():
try:
with open(attempt_history_file, encoding="utf-8") as f:
attempt_history = json.load(f)
# Collect IDs of subtasks marked as stuck
stuck_subtask_ids = {
entry["subtask_id"]
for entry in attempt_history.get("stuck_subtasks", [])
if "subtask_id" in entry
}
except (OSError, json.JSONDecodeError, UnicodeDecodeError):
# If we can't read the file, continue without stuck checking
pass
try:
with open(plan_file, encoding="utf-8") as f:
@@ -498,11 +454,8 @@ 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" or s.get("id") in stuck_subtask_ids
for s in subtasks
s.get("status") == "completed" for s in subtasks
)
# Find next available subtask
@@ -9,10 +9,9 @@ Each dependency ecosystem has different constraints:
- **node_modules**: Safe to symlink. Node's resolution algorithm follows symlinks
correctly, and the directory is self-contained.
- **venv / .venv**: Symlinked for fast worktree creation. CPython bug #106045
(pyvenv.cfg symlink resolution) does not affect typical usage (running scripts,
imports, pip). A health check after symlinking verifies usability; if it fails,
the caller falls back to recreating the venv.
- **venv / .venv**: Must be recreated. Python's ``pyvenv.cfg`` discovery walks the
real directory hierarchy without resolving symlinks (CPython bug #106045), so a
symlinked venv resolves paths relative to the *target*, not the worktree.
- **vendor (PHP)**: Safe to symlink. Composer's autoloader uses ``__DIR__``-relative
paths that resolve correctly through symlinks.
@@ -43,9 +42,9 @@ from .models import DependencyShareConfig, DependencyStrategy
DEFAULT_STRATEGY_MAP: dict[str, DependencyStrategy] = {
# JavaScript / Node.js — symlink is safe and fast
"node_modules": DependencyStrategy.SYMLINK,
# Python — symlink for fast worktree creation (health check + fallback to recreate)
"venv": DependencyStrategy.SYMLINK,
".venv": DependencyStrategy.SYMLINK,
# Python — venvs MUST be recreated (pyvenv.cfg symlink bug)
"venv": DependencyStrategy.RECREATE,
".venv": DependencyStrategy.RECREATE,
# PHP — Composer vendor dir is safe to symlink
"vendor_php": DependencyStrategy.SYMLINK,
# Ruby — Bundler vendor/bundle is safe to symlink
+6 -5
View File
@@ -278,11 +278,12 @@ class SpecNumberLock:
class DependencyStrategy(Enum):
"""Strategy for sharing dependency directories across worktrees.
SYMLINK is fast and now safe for Python venvs with runtime health checks.
A post-symlink health check validates the venv is usable, automatically
falling back to RECREATE if the symlink is broken. This works around
CPython's pyvenv.cfg discovery issue (CPython bug #106045) while maintaining
fast worktree creation in the common case where symlinking succeeds.
SYMLINK is fast but unsafe for certain ecosystems. Notably, Python venv
breaks when symlinked because CPython's pyvenv.cfg discovery walks the
real directory hierarchy without resolving symlinks first
(CPython bug #106045). This means a symlinked venv resolves its home
path relative to the symlink target's parent, not the worktree, causing
import failures and broken interpreters.
"""
SYMLINK = "symlink" # Create a symlink to the source (fast, works for node_modules)
+26 -140
View File
@@ -50,10 +50,6 @@ _git_hook_check_done = False
MODULE = "workspace.setup"
# Marker file written inside a recreated venv to indicate setup completed successfully.
# If the marker is absent, the venv is treated as incomplete and will be rebuilt.
VENV_SETUP_COMPLETE_MARKER = ".setup_complete"
def choose_workspace(
project_dir: Path,
@@ -628,52 +624,9 @@ def setup_worktree_dependencies(
results[strategy_name] = []
try:
performed = False
performed = True
if config.strategy == DependencyStrategy.SYMLINK:
performed = _apply_symlink_strategy(project_dir, worktree_path, config)
# For venvs, verify the symlink is usable — fall back to recreate
# Run health check whenever a venv symlink exists (not just on creation)
if config.dep_type in ("venv", ".venv"):
venv_path = worktree_path / config.source_rel_path
# Check if venv exists (symlinked or otherwise)
if venv_path.exists() or venv_path.is_symlink():
if is_windows():
python_bin = str(venv_path / "Scripts" / "python.exe")
else:
python_bin = str(venv_path / "bin" / "python")
try:
subprocess.run(
[python_bin, "-c", "import sys; print(sys.prefix)"],
capture_output=True,
text=True,
timeout=10,
check=True,
)
debug(
MODULE,
f"Symlinked venv health check passed: {config.source_rel_path}",
)
except (subprocess.SubprocessError, OSError):
debug_warning(
MODULE,
f"Symlinked venv health check failed, falling back to recreate: {config.source_rel_path}",
)
# Remove the broken symlink and recreate
try:
if venv_path.is_symlink():
venv_path.unlink()
elif venv_path.exists():
shutil.rmtree(venv_path, ignore_errors=True)
except OSError:
pass # Best-effort removal; recreate strategy handles existing paths
performed = _apply_recreate_strategy(
project_dir, worktree_path, config
)
# Update strategy name to reflect fallback
if performed:
strategy_name = "recreate"
# Ensure the key exists for the fallback strategy
results.setdefault(strategy_name, [])
elif config.strategy == DependencyStrategy.RECREATE:
performed = _apply_recreate_strategy(project_dir, worktree_path, config)
elif config.strategy == DependencyStrategy.COPY:
@@ -754,54 +707,6 @@ def _apply_symlink_strategy(
return False
def _popen_with_cleanup(
cmd: list[str],
timeout: int,
label: str,
) -> tuple[int, str, str]:
"""Run a command via Popen with proper process cleanup on timeout.
On timeout: terminate wait(10) kill wait(5) to ensure file locks
are released before any cleanup (e.g. shutil.rmtree).
Returns (returncode, stdout, stderr).
Raises subprocess.TimeoutExpired if the command exceeds the given timeout (after cleanup is attempted).
"""
proc = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
)
try:
stdout, stderr = proc.communicate(timeout=timeout)
return proc.returncode, stdout, stderr
except subprocess.TimeoutExpired:
debug_warning(MODULE, f"{label} timed out, terminating process")
proc.terminate()
try:
proc.communicate(timeout=10)
except subprocess.TimeoutExpired:
debug_warning(MODULE, f"{label} did not terminate, killing process")
proc.kill()
try:
proc.communicate(timeout=5)
except subprocess.TimeoutExpired:
# Final cleanup attempt if kill() also hangs
debug_warning(MODULE, f"{label} could not be stopped even after kill()")
raise
finally:
# Ensure pipes are closed and process is reaped to avoid zombie processes
if proc.stdout:
proc.stdout.close()
if proc.stderr:
proc.stderr.close()
try:
proc.wait(timeout=0.1)
except subprocess.TimeoutExpired:
pass # Process still running, already logged warning above
def _apply_recreate_strategy(
project_dir: Path,
worktree_path: Path,
@@ -812,25 +717,10 @@ def _apply_recreate_strategy(
Returns True if the venv was successfully created, False if skipped or failed.
"""
venv_path = worktree_path / config.source_rel_path
marker_path = venv_path / VENV_SETUP_COMPLETE_MARKER
# Check for broken symlinks that exists() would miss
if venv_path.is_symlink() and not venv_path.exists():
debug(MODULE, f"Removing broken symlink at {config.source_rel_path}")
try:
venv_path.unlink()
except OSError:
pass # Best-effort removal
elif venv_path.exists():
if marker_path.exists():
debug(
MODULE,
f"Skipping recreate {config.source_rel_path} - already complete (marker present)",
)
return False
# Venv exists but marker is missing — incomplete, remove and rebuild
debug(MODULE, f"Removing incomplete venv {config.source_rel_path} (no marker)")
shutil.rmtree(venv_path, ignore_errors=True)
if venv_path.exists():
debug(MODULE, f"Skipping recreate {config.source_rel_path} - already exists")
return False
# Detect Python executable from the source venv or fall back to sys.executable
source_venv = project_dir / config.source_rel_path
@@ -847,34 +737,29 @@ def _apply_recreate_strategy(
# Create the venv
try:
debug(MODULE, f"Creating venv at {venv_path}")
returncode, _, stderr = _popen_with_cleanup(
result = subprocess.run(
[python_exec, "-m", "venv", str(venv_path)],
capture_output=True,
text=True,
timeout=120,
label=f"venv creation ({config.source_rel_path})",
)
if returncode != 0:
debug_warning(MODULE, f"venv creation failed: {stderr}")
if result.returncode != 0:
debug_warning(MODULE, f"venv creation failed: {result.stderr}")
print_status(
f"Warning: Could not create venv at {config.source_rel_path}",
"warning",
)
# Clean up partial venv so retries aren't blocked
if venv_path.exists():
shutil.rmtree(venv_path, ignore_errors=True)
return False
except subprocess.TimeoutExpired:
debug_warning(MODULE, f"venv creation timed out for {config.source_rel_path}")
print_status(
f"Warning: venv creation timed out for {config.source_rel_path}",
"warning",
)
if venv_path.exists():
shutil.rmtree(venv_path, ignore_errors=True)
return False
except OSError as e:
debug_warning(MODULE, f"venv creation failed: {e}")
print_status(
f"Warning: Could not create venv at {config.source_rel_path}",
"warning",
)
# Clean up partial venv so retries aren't blocked
if venv_path.exists():
shutil.rmtree(venv_path, ignore_errors=True)
return False
@@ -915,45 +800,46 @@ def _apply_recreate_strategy(
if install_cmd:
try:
debug(MODULE, f"Installing deps from {req_file}")
returncode, _, stderr = _popen_with_cleanup(
pip_result = subprocess.run(
install_cmd,
timeout=300,
label=f"pip install ({req_file})",
capture_output=True,
text=True,
timeout=120,
)
if returncode != 0:
if pip_result.returncode != 0:
debug_warning(
MODULE,
f"pip install failed (exit {returncode}): {stderr}",
f"pip install failed (exit {pip_result.returncode}): "
f"{pip_result.stderr}",
)
print_status(
f"Warning: Dependency install failed for {req_file}",
"warning",
)
# Clean up broken venv so retries aren't blocked
if venv_path.exists():
shutil.rmtree(venv_path, ignore_errors=True)
return False
except subprocess.TimeoutExpired:
debug_warning(
MODULE,
f"pip install timed out for {req_file}",
)
print_status(
f"Warning: Dependency install timed out for {req_file}",
"warning",
)
# Clean up broken venv so retries aren't blocked
if venv_path.exists():
shutil.rmtree(venv_path, ignore_errors=True)
return False
except OSError as e:
debug_warning(MODULE, f"pip install failed: {e}")
# Clean up broken venv so retries aren't blocked
if venv_path.exists():
shutil.rmtree(venv_path, ignore_errors=True)
return False
# Write completion marker so future runs know this venv is complete
try:
marker_path.touch()
except OSError as e:
debug_warning(
MODULE, f"Failed to write completion marker at {marker_path}: {e}"
)
debug(MODULE, f"Recreated venv at {config.source_rel_path}")
return True
-6
View File
@@ -1211,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
+3 -13
View File
@@ -635,20 +635,10 @@ def get_graphiti_status() -> dict:
try:
# Attempt to import the main graphiti_memory module
import graphiti_core # noqa: F401
from graphiti_core.driver.falkordb_driver import FalkorDriver # noqa: F401
# Try LadybugDB first (preferred for Python 3.12+), fall back to kuzu
try:
import real_ladybug # noqa: F401
except ImportError:
try:
import kuzu # noqa: F401
except ImportError:
status["available"] = False
status["reason"] = (
"Graph database backend not installed (need real_ladybug or kuzu)"
)
return status
status["available"] = True
# If we got here, packages are importable
status["available"] = True # pragma: no cover
except ImportError as e:
status["available"] = False
status["reason"] = f"Graphiti packages not installed: {e}"
@@ -81,16 +81,16 @@ def mock_graphiti_core():
@pytest.fixture
def mock_kuzu_driver():
"""Mock graphiti_core.driver.kuzu_driver.KuzuDriver.
def mock_falkor_driver():
"""Mock graphiti_core.driver.falkordb_driver.FalkorDriver.
Prevents actual LadybugDB/kuzu connections during tests.
Prevents actual FalkorDB connections during tests.
Yields:
tuple: (mock_driver_class, mock_driver_instance)
"""
with patch(
"integrations.graphiti.queries_pkg.graphiti.graphiti_core.driver.kuzu_driver.KuzuDriver"
"integrations.graphiti.queries_pkg.graphiti.graphiti_core.driver.falkordb_driver.FalkorDriver"
) as mock_driver:
mock_instance = MagicMock()
mock_driver.return_value = mock_instance
@@ -15,7 +15,7 @@ Tests cover:
import json
import os
from pathlib import Path
from unittest.mock import MagicMock, patch
from unittest.mock import patch
import pytest
from integrations.graphiti.config import (
@@ -1054,48 +1054,20 @@ class TestModuleLevelFunctions:
assert "OPENAI_API_KEY" in status["errors"][0]
def test_get_graphiti_status_invalid_config_sets_reason(self, clean_env):
"""Test get_graphiti_status with validation errors (embedder misconfigured).
"""Test get_graphiti_status sets reason when config is invalid.
When packages are installed but embedder config has errors, available should
still be True (embedder is optional - keyword search fallback exists).
Validation errors are reported in the errors list for informational purposes.
This tests lines 628-629 where the reason is set from validation errors.
"""
os.environ["GRAPHITI_ENABLED"] = "true"
os.environ["GRAPHITI_EMBEDDER_PROVIDER"] = "voyage"
# Mock imports to ensure test is independent of environment
with patch.dict(
"sys.modules",
{"graphiti_core": MagicMock(), "real_ladybug": MagicMock()},
):
status = get_graphiti_status()
assert status["enabled"] is True
# available depends on whether mocked packages are resolved correctly;
# sys.modules patching should make imports succeed, but guard against
# environment quirks (consistent with test_get_graphiti_status_enabled)
assert status["available"] is True
assert len(status["errors"]) > 0
assert "VOYAGE_API_KEY" in status["errors"][0]
def test_get_graphiti_status_no_graph_backend(self, clean_env):
"""Test get_graphiti_status when graphiti_core exists but no graph DB backend.
This tests the error path in config.py lines 645-650 where graphiti_core
imports successfully but neither real_ladybug nor kuzu is available.
"""
os.environ["GRAPHITI_ENABLED"] = "true"
# Mock graphiti_core as present, but ensure real_ladybug and kuzu are absent
with patch.dict(
"sys.modules",
{"graphiti_core": MagicMock(), "real_ladybug": None, "kuzu": None},
):
status = get_graphiti_status()
status = get_graphiti_status()
assert status["enabled"] is True
assert status["available"] is False
assert "real_ladybug or kuzu" in status["reason"]
# When config is invalid, reason should be set from errors
assert status["reason"] != ""
assert len(status["errors"]) > 0
@pytest.mark.slow
def test_get_graphiti_status_with_graphiti_installed(self, clean_env):
@@ -1117,9 +1089,9 @@ class TestModuleLevelFunctions:
assert "reason" in status
assert "errors" in status
# Note: Line 644 (status["available"] = True) requires LadybugDB/kuzu to be installed.
# Since LadybugDB/kuzu may not be installed in all test environments, that line
# may be marked with pragma: no cover. The except clause is tested here.
# Note: Line 641 (status["available"] = True) requires falkordb to be installed.
# Since falkordb is not installed in the test environment, that line is marked
# with pragma: no cover. The except clause (lines 642-644) is tested here.
def test_get_available_providers_empty(self, clean_env):
"""Test get_available_providers with no credentials."""
@@ -264,7 +264,7 @@ class TestTestGraphitiConnection:
# Mock graphiti_core imports to succeed
mock_graphiti = MagicMock()
mock_kuzu_driver = MagicMock()
mock_falkordb_driver = MagicMock()
# Mock provider creation to raise ProviderError
with patch("graphiti_providers.create_llm_client") as mock_create_llm:
@@ -275,7 +275,7 @@ class TestTestGraphitiConnection:
{
"graphiti_core": MagicMock(Graphiti=mock_graphiti),
"graphiti_core.driver": MagicMock(),
"graphiti_core.driver.kuzu_driver": mock_kuzu_driver,
"graphiti_core.driver.falkordb_driver": mock_falkordb_driver,
"graphiti_providers": MagicMock(
ProviderError=ProviderError,
create_embedder=MagicMock(),
@@ -160,7 +160,7 @@ class TestTestGraphitiConnection:
"""Tests for the test_graphiti_connection async function.
Note: The function now uses embedded LadybugDB via patched KuzuDriver
instead of remote database with host/port credentials.
instead of remote FalkorDB with host/port credentials.
"""
@pytest.mark.asyncio
+9
View File
@@ -0,0 +1,9 @@
"""
Auto Claude MCP Server
======================
Control plane for the Auto Claude autonomous coding pipeline.
Exposes all backend capabilities via the Model Context Protocol (MCP).
"""
__version__ = "0.1.0"
+95
View File
@@ -0,0 +1,95 @@
"""
Auto Claude MCP Server Entry Point
===================================
Usage:
python -m mcp_server --project-dir /path/to/project
python -m mcp_server --project-dir /path/to/project --transport sse --port 8642
"""
from __future__ import annotations
import argparse
import logging
import sys
# Configure logging to stderr (stdout is reserved for MCP protocol over stdio)
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(name)s] %(levelname)s: %(message)s",
stream=sys.stderr,
)
logger = logging.getLogger("mcp_server")
def main() -> None:
parser = argparse.ArgumentParser(
description="Auto Claude MCP Server - control plane for the autonomous coding pipeline",
)
parser.add_argument(
"--project-dir",
required=True,
help="Path to the project directory to manage",
)
parser.add_argument(
"--transport",
choices=["stdio", "sse", "streamable-http"],
default="stdio",
help="MCP transport to use (default: stdio)",
)
parser.add_argument(
"--port",
type=int,
default=8642,
help="Port for SSE/HTTP transport (default: 8642)",
)
parser.add_argument(
"--host",
default="127.0.0.1",
help="Host for SSE/HTTP transport (default: 127.0.0.1)",
)
parser.add_argument(
"--debug",
action="store_true",
help="Enable debug logging",
)
args = parser.parse_args()
if args.debug:
logging.getLogger().setLevel(logging.DEBUG)
# Initialize project context (adds backend to sys.path, loads .env)
from mcp_server.config import initialize
initialize(args.project_dir)
# Import server and register tools AFTER initialization
# (tools need backend modules on sys.path)
from mcp_server.server import mcp, register_all_tools
register_all_tools()
logger.info(
"Starting Auto Claude MCP server (transport=%s, project=%s)",
args.transport,
args.project_dir,
)
# For stdio transport, redirect any stray stdout prints to stderr
# to prevent corrupting the MCP JSON-RPC protocol
if args.transport == "stdio":
# Capture any prints from backend modules that write to stdout
_original_stdout = sys.stdout
sys.stdout = sys.stderr
# Run the server
if args.transport == "stdio":
mcp.run(transport="stdio")
elif args.transport == "sse":
mcp.run(transport="sse", host=args.host, port=args.port)
elif args.transport == "streamable-http":
mcp.run(transport="streamable-http", host=args.host, port=args.port)
if __name__ == "__main__":
main()
+114
View File
@@ -0,0 +1,114 @@
"""
MCP Server Configuration
========================
Manages project context and backend initialization for the MCP server.
The project directory is set once at startup and used by all tools.
"""
from __future__ import annotations
import json
import logging
import sys
from pathlib import Path
logger = logging.getLogger(__name__)
# Global project context - set once at server startup
_project_dir: Path | None = None
_auto_claude_dir: Path | None = None
def initialize(project_dir: str | Path) -> None:
"""Initialize the MCP server with a project directory.
This sets up the Python path so backend modules can be imported,
loads the .env file, and validates the project structure.
Args:
project_dir: Path to the user's project directory
"""
global _project_dir, _auto_claude_dir
_project_dir = Path(project_dir).resolve()
if not _project_dir.is_dir():
raise ValueError(f"Project directory does not exist: {_project_dir}")
# Add backend to sys.path so existing modules can be imported
backend_dir = Path(__file__).parent.parent
if str(backend_dir) not in sys.path:
sys.path.insert(0, str(backend_dir))
# Load .env if present
try:
from cli.utils import import_dotenv
load_dotenv = import_dotenv()
env_file = backend_dir / ".env"
if env_file.exists():
load_dotenv(env_file)
except Exception:
logger.debug("Could not load .env file (non-critical)")
# Determine .auto-claude directory
auto_claude = _project_dir / ".auto-claude"
if not auto_claude.is_dir():
# Also check legacy 'auto-claude' (no dot prefix)
alt = _project_dir / "auto-claude"
if alt.is_dir():
auto_claude = alt
else:
logger.warning(
"No .auto-claude directory found in %s. "
"Some tools may not work until the project is initialized.",
_project_dir,
)
_auto_claude_dir = auto_claude
logger.info("MCP server initialized for project: %s", _project_dir)
def get_project_dir() -> Path:
"""Get the active project directory. Raises if not initialized."""
if _project_dir is None:
raise RuntimeError(
"MCP server not initialized. Call config.initialize() first."
)
return _project_dir
def get_auto_claude_dir() -> Path:
"""Get the .auto-claude directory for the active project."""
if _auto_claude_dir is None:
raise RuntimeError(
"MCP server not initialized. Call config.initialize() first."
)
return _auto_claude_dir
def get_specs_dir() -> Path:
"""Get the specs directory for the active project."""
return get_auto_claude_dir() / "specs"
def get_project_index() -> dict:
"""Load and return the project index if available."""
index_path = get_auto_claude_dir() / "project_index.json"
if not index_path.exists():
return {}
try:
with open(index_path, encoding="utf-8") as f:
return json.load(f)
except (json.JSONDecodeError, OSError) as e:
logger.warning("Failed to load project index: %s", e)
return {}
def is_initialized() -> bool:
"""Check if the project has been initialized with .auto-claude."""
try:
ac_dir = get_auto_claude_dir()
return ac_dir.is_dir()
except RuntimeError:
return False
+158
View File
@@ -0,0 +1,158 @@
"""
Long-Running Operation Tracker
===============================
Tracks async operations (spec creation, builds, QA, etc.) so MCP clients
can poll for progress. Tools that start long-running work return an
operation_id immediately; clients poll operation_get_status() for updates.
"""
from __future__ import annotations
import asyncio
import logging
import time
import uuid
from dataclasses import dataclass, field
from enum import Enum
from typing import Any
logger = logging.getLogger(__name__)
class OperationStatus(str, Enum):
PENDING = "pending"
RUNNING = "running"
COMPLETED = "completed"
FAILED = "failed"
CANCELLED = "cancelled"
@dataclass
class Operation:
"""Represents a long-running operation."""
id: str
type: str # e.g. "spec_create", "build", "qa_review"
status: OperationStatus = OperationStatus.PENDING
progress: int = 0 # 0-100
message: str = ""
result: Any = None
error: str | None = None
created_at: float = field(default_factory=time.time)
updated_at: float = field(default_factory=time.time)
_task: asyncio.Task | None = field(default=None, repr=False)
def to_dict(self) -> dict:
"""Serialize for MCP response."""
return {
"id": self.id,
"type": self.type,
"status": self.status.value,
"progress": self.progress,
"message": self.message,
"result": self.result,
"error": self.error,
"created_at": self.created_at,
"updated_at": self.updated_at,
"elapsed_seconds": round(time.time() - self.created_at, 1),
}
class OperationTracker:
"""Manages the lifecycle of long-running operations."""
def __init__(self, max_completed: int = 100):
self._operations: dict[str, Operation] = {}
self._max_completed = max_completed
def create(self, operation_type: str, message: str = "") -> Operation:
"""Create a new operation and return it."""
op = Operation(
id=str(uuid.uuid4()),
type=operation_type,
status=OperationStatus.PENDING,
message=message or f"Starting {operation_type}...",
)
self._operations[op.id] = op
self._cleanup_old()
return op
def get(self, operation_id: str) -> Operation | None:
"""Get an operation by ID."""
return self._operations.get(operation_id)
def update(
self,
operation_id: str,
*,
status: OperationStatus | None = None,
progress: int | None = None,
message: str | None = None,
result: Any = None,
error: str | None = None,
) -> Operation | None:
"""Update an operation's state."""
op = self._operations.get(operation_id)
if op is None:
return None
if status is not None:
op.status = status
if progress is not None:
op.progress = max(0, min(100, progress))
if message is not None:
op.message = message
if result is not None:
op.result = result
if error is not None:
op.error = error
op.updated_at = time.time()
return op
def cancel(self, operation_id: str) -> bool:
"""Cancel a running operation."""
op = self._operations.get(operation_id)
if op is None:
return False
if op.status in (OperationStatus.COMPLETED, OperationStatus.FAILED):
return False
# Cancel the asyncio task if it exists
if op._task and not op._task.done():
op._task.cancel()
op.status = OperationStatus.CANCELLED
op.message = "Operation cancelled by user"
op.updated_at = time.time()
return True
def list_active(self) -> list[Operation]:
"""List all active (non-terminal) operations."""
return [
op
for op in self._operations.values()
if op.status in (OperationStatus.PENDING, OperationStatus.RUNNING)
]
def _cleanup_old(self) -> None:
"""Remove old completed operations to prevent memory growth."""
completed = [
op
for op in self._operations.values()
if op.status
in (
OperationStatus.COMPLETED,
OperationStatus.FAILED,
OperationStatus.CANCELLED,
)
]
if len(completed) > self._max_completed:
# Sort by created_at, remove oldest
completed.sort(key=lambda o: o.created_at)
for op in completed[: len(completed) - self._max_completed]:
del self._operations[op.id]
# Global singleton
tracker = OperationTracker()
+56
View File
@@ -0,0 +1,56 @@
"""
Auto Claude MCP Server
======================
FastMCP server instance with all tool registrations.
Tools are organized into modules under mcp_server/tools/.
Each module's register() function adds tools to the server.
"""
from __future__ import annotations
import logging
from fastmcp import FastMCP
logger = logging.getLogger(__name__)
# Create the FastMCP server instance
mcp = FastMCP(
"Auto Claude",
instructions=(
"Auto Claude is an autonomous multi-agent coding framework. "
"Use these tools to manage tasks, create specs, run builds, "
"perform QA reviews, manage workspaces, and more. "
"Long-running operations return an operation_id - "
"poll with operation_get_status() for progress."
),
)
def register_all_tools() -> None:
"""Register all tool modules with the MCP server.
Each tool module defines functions decorated with @mcp.tool()
that are imported here to trigger registration.
"""
# Phase 1: Project & Task management
# Phase 2: Core autonomous pipeline
# Phase 3: Feature tools
# Operations management (poll long-running ops)
from mcp_server.tools import (
execution, # noqa: F401
github, # noqa: F401
ideation, # noqa: F401
insights, # noqa: F401
memory, # noqa: F401
ops, # noqa: F401
project, # noqa: F401
qa, # noqa: F401
roadmap, # noqa: F401
specs, # noqa: F401
tasks, # noqa: F401
workspace, # noqa: F401
)
logger.info("All MCP tools registered successfully")
@@ -0,0 +1 @@
"""Service layer - thin adapters wrapping existing backend modules."""
@@ -0,0 +1,337 @@
"""
Execution Service
==================
Service layer for spawning and managing build processes.
Wraps the run.py subprocess and parses task events from stdout.
"""
from __future__ import annotations
import asyncio
import json
import logging
import sys
from pathlib import Path
logger = logging.getLogger(__name__)
# Matches core/task_event.py
TASK_EVENT_PREFIX = "__TASK_EVENT__:"
# Module-level singleton
_instance: ExecutionService | None = None
def get_execution_service(project_dir: Path) -> ExecutionService:
"""Return a lazily-created singleton ExecutionService.
If project_dir changes (e.g. user switches projects), a new instance
is created so in-memory state matches the active project.
"""
global _instance
if _instance is None or _instance.project_dir != project_dir:
_instance = ExecutionService(project_dir)
return _instance
class ExecutionService:
"""Manages build execution as a subprocess of run.py."""
def __init__(self, project_dir: Path):
self.project_dir = project_dir
self._processes: dict[str, asyncio.subprocess.Process] = {}
self._logs: dict[str, list[str]] = {}
self._events: dict[str, list[dict]] = {}
async def start_build(
self,
spec_id: str,
model: str = "sonnet",
thinking_level: str = "medium",
) -> asyncio.subprocess.Process:
"""Spawn a build subprocess for the given spec.
Args:
spec_id: The spec folder name
model: Model shorthand
thinking_level: Thinking level
Returns:
The subprocess handle
Raises:
RuntimeError: If a build is already running for this spec
"""
if spec_id in self._processes:
proc = self._processes[spec_id]
if proc.returncode is None:
raise RuntimeError(
f"Build already running for spec '{spec_id}'. "
"Stop it first with build_stop()."
)
backend_dir = Path(__file__).parent.parent.parent # apps/backend/
run_py = backend_dir / "run.py"
if not run_py.exists():
raise FileNotFoundError(f"run.py not found at {run_py}")
cmd = [
sys.executable,
str(run_py),
"--spec",
spec_id,
"--project-dir",
str(self.project_dir),
"--model",
model,
"--thinking",
thinking_level,
]
proc = await asyncio.create_subprocess_exec(
*cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
cwd=str(backend_dir),
)
self._processes[spec_id] = proc
self._logs[spec_id] = []
self._events[spec_id] = []
# Start background reader for stdout
asyncio.create_task(self._read_output(spec_id, proc))
return proc
async def _read_output(
self, spec_id: str, proc: asyncio.subprocess.Process
) -> None:
"""Read stdout from the build process, parsing task events.
Args:
spec_id: The spec being built
proc: The subprocess to read from
"""
if proc.stdout is None:
return
try:
while True:
line_bytes = await proc.stdout.readline()
if not line_bytes:
break
line = line_bytes.decode("utf-8", errors="replace").rstrip("\n")
# Store the log line
log_list = self._logs.get(spec_id)
if log_list is not None:
log_list.append(line)
# Cap stored logs to prevent unbounded growth
if len(log_list) > 5000:
del log_list[:1000]
# Parse task events
event = self.parse_event(line)
if event is not None:
events_list = self._events.get(spec_id)
if events_list is not None:
events_list.append(event)
except Exception as e:
logger.warning("Error reading build output for %s: %s", spec_id, e)
def parse_event(self, line: str) -> dict | None:
"""Parse a task event line from build stdout.
Args:
line: A line of stdout output
Returns:
Parsed event dict or None if not an event line
"""
if not line.startswith(TASK_EVENT_PREFIX):
return None
try:
return json.loads(line[len(TASK_EVENT_PREFIX) :])
except (json.JSONDecodeError, ValueError):
return None
def stop_build(self, spec_id: str) -> dict:
"""Stop a running build process.
Args:
spec_id: The spec being built
Returns:
Status dict
"""
proc = self._processes.get(spec_id)
if proc is None:
return {"success": False, "error": f"No build found for spec '{spec_id}'"}
if proc.returncode is not None:
return {
"success": False,
"error": f"Build for '{spec_id}' already finished (exit code {proc.returncode})",
}
try:
proc.terminate()
return {"success": True, "message": f"Build for '{spec_id}' terminated"}
except ProcessLookupError:
return {"success": False, "error": "Process already exited"}
def get_progress(self, spec_id: str) -> dict:
"""Get progress of a build by inspecting events and process state.
Args:
spec_id: The spec being built
Returns:
Dict with status, events, and process info
"""
proc = self._processes.get(spec_id)
events = self._events.get(spec_id, [])
if proc is None:
# Check if there's a completed implementation plan on disk
return self._get_disk_progress(spec_id)
is_running = proc.returncode is None
latest_event = events[-1] if events else None
return {
"spec_id": spec_id,
"running": is_running,
"exit_code": proc.returncode,
"event_count": len(events),
"latest_event": latest_event,
"log_lines": len(self._logs.get(spec_id, [])),
}
def get_logs(self, spec_id: str, tail: int = 50) -> dict:
"""Get recent build logs.
Args:
spec_id: The spec being built
tail: Number of recent lines to return
Returns:
Dict with log lines
"""
logs = self._logs.get(spec_id, [])
if not logs:
# Try to find logs on disk
return self._get_disk_logs(spec_id, tail)
return {
"spec_id": spec_id,
"total_lines": len(logs),
"lines": logs[-tail:],
}
def _get_disk_progress(self, spec_id: str) -> dict:
"""Check on-disk state for build progress when no process is tracked.
Args:
spec_id: The spec folder name
Returns:
Progress dict from disk state
"""
specs_dir = self.project_dir / ".auto-claude" / "specs"
spec_dir = self._resolve_spec_dir(specs_dir, spec_id)
if spec_dir is None:
return {"error": f"Spec '{spec_id}' not found"}
plan_file = spec_dir / "implementation_plan.json"
if not plan_file.exists():
return {
"spec_id": spec_id,
"running": False,
"status": "no_plan",
"message": "No implementation plan found. Create a spec first.",
}
try:
with open(plan_file, encoding="utf-8") as f:
plan = json.load(f)
except (json.JSONDecodeError, OSError):
return {
"spec_id": spec_id,
"running": False,
"status": "error",
"message": "Could not read implementation plan",
}
subtasks = plan.get("subtasks", [])
completed = sum(1 for s in subtasks if s.get("status") == "completed")
total = len(subtasks)
qa_signoff = plan.get("qa_signoff")
if qa_signoff and qa_signoff.get("status") == "approved":
status = "qa_approved"
elif qa_signoff and qa_signoff.get("status") == "rejected":
status = "qa_rejected"
elif completed == total and total > 0:
status = "build_complete"
elif completed > 0:
status = "building"
else:
status = "not_started"
return {
"spec_id": spec_id,
"running": False,
"status": status,
"subtasks_completed": completed,
"subtasks_total": total,
"qa_signoff": qa_signoff,
}
def _get_disk_logs(self, spec_id: str, tail: int) -> dict:
"""Try to find build logs on disk.
Args:
spec_id: The spec folder name
tail: Number of lines to return
Returns:
Dict with log content
"""
specs_dir = self.project_dir / ".auto-claude" / "specs"
spec_dir = self._resolve_spec_dir(specs_dir, spec_id)
if spec_dir is None:
return {"error": f"Spec '{spec_id}' not found", "lines": []}
# Check for task log file
log_file = spec_dir / "task_log.jsonl"
if not log_file.exists():
return {
"spec_id": spec_id,
"lines": [],
"message": "No build logs found",
}
try:
lines = log_file.read_text(encoding="utf-8").strip().split("\n")
return {
"spec_id": spec_id,
"total_lines": len(lines),
"lines": lines[-tail:],
}
except OSError as e:
return {"error": str(e), "lines": []}
def _resolve_spec_dir(self, specs_dir: Path, spec_id: str) -> Path | None:
"""Resolve spec_id to directory with prefix matching."""
exact = specs_dir / spec_id
if exact.is_dir():
return exact
if specs_dir.is_dir():
for item in specs_dir.iterdir():
if item.is_dir() and item.name.startswith(spec_id):
return item
return None
@@ -0,0 +1,202 @@
"""
GitHub Service
==============
Wraps the backend GitHubOrchestrator for MCP tool access.
Handles repo detection, config creation, and result serialization.
"""
from __future__ import annotations
import json
import logging
import subprocess
from pathlib import Path
logger = logging.getLogger(__name__)
class GitHubService:
"""Service layer for GitHub automation features."""
def __init__(self, project_dir: Path):
self.project_dir = project_dir
self.github_dir = project_dir / ".auto-claude" / "github"
def _detect_repo(self) -> str | None:
"""Detect owner/repo from git remote origin."""
try:
result = subprocess.run(
["git", "remote", "get-url", "origin"],
capture_output=True,
text=True,
cwd=str(self.project_dir),
timeout=10,
)
if result.returncode != 0:
return None
url = result.stdout.strip()
# Handle SSH: git@github.com:owner/repo.git
if url.startswith("git@"):
parts = url.split(":")[-1]
return parts.removesuffix(".git")
# Handle HTTPS: https://github.com/owner/repo.git
if "github.com" in url:
parts = url.split("github.com/")[-1]
return parts.removesuffix(".git")
return None
except Exception as e:
logger.warning("Failed to detect repo from git remote: %s", e)
return None
def _get_repo(self, repo: str | None) -> str:
"""Get repo string, falling back to auto-detection."""
if repo:
return repo
detected = self._detect_repo()
if not detected:
raise ValueError(
"Could not detect repository. Provide 'repo' parameter "
"in owner/repo format, or ensure a GitHub remote is configured."
)
return detected
def _create_config(self, repo: str, model: str = "sonnet"):
"""Create a GitHubRunnerConfig with sensible defaults."""
# Get GitHub token from environment
import os
from runners.github.models import GitHubRunnerConfig
token = os.environ.get("GITHUB_TOKEN", "")
if not token:
# Try gh CLI auth token
try:
result = subprocess.run(
["gh", "auth", "token"],
capture_output=True,
text=True,
timeout=10,
)
if result.returncode == 0:
token = result.stdout.strip()
except Exception:
pass
return GitHubRunnerConfig(
token=token,
repo=repo,
model=model,
thinking_level="medium",
pr_review_enabled=True,
triage_enabled=True,
)
async def review_pr(
self, pr_number: int, repo: str | None = None, model: str = "sonnet"
) -> dict:
"""Review a pull request with AI."""
try:
from runners.github.orchestrator import GitHubOrchestrator
resolved_repo = self._get_repo(repo)
config = self._create_config(resolved_repo, model)
orchestrator = GitHubOrchestrator(
project_dir=self.project_dir, config=config
)
result = await orchestrator.review_pr(pr_number)
return {"success": True, "data": result.to_dict()}
except ImportError:
return {"error": "GitHub runner module not available"}
except Exception as e:
return {"error": str(e)}
async def list_issues(
self, state: str = "open", limit: int = 30, repo: str | None = None
) -> dict:
"""List GitHub issues using gh CLI."""
try:
resolved_repo = self._get_repo(repo)
cmd = [
"gh",
"issue",
"list",
"--repo",
resolved_repo,
"--state",
state,
"--limit",
str(limit),
"--json",
"number,title,state,labels,author,createdAt,updatedAt",
]
result = subprocess.run(
cmd,
capture_output=True,
text=True,
cwd=str(self.project_dir),
timeout=30,
)
if result.returncode != 0:
return {"error": f"gh CLI failed: {result.stderr.strip()}"}
issues = json.loads(result.stdout)
return {"success": True, "issues": issues, "count": len(issues)}
except Exception as e:
return {"error": str(e)}
async def auto_fix_issue(self, issue_number: int, repo: str | None = None) -> dict:
"""Auto-fix a GitHub issue."""
try:
from runners.github.orchestrator import GitHubOrchestrator
resolved_repo = self._get_repo(repo)
config = self._create_config(resolved_repo)
config.auto_fix_enabled = True
orchestrator = GitHubOrchestrator(
project_dir=self.project_dir, config=config
)
state = await orchestrator.auto_fix_issue(issue_number)
return {"success": True, "data": state.to_dict()}
except ImportError:
return {"error": "GitHub runner module not available"}
except Exception as e:
return {"error": str(e)}
def get_review(self, pr_number: int) -> dict:
"""Get the most recent review result for a PR."""
try:
from runners.github.models import PRReviewResult
result = PRReviewResult.load(self.github_dir, pr_number)
if result is None:
return {"error": f"No review found for PR #{pr_number}"}
return {"success": True, "data": result.to_dict()}
except ImportError:
return {"error": "GitHub runner module not available"}
except Exception as e:
return {"error": str(e)}
async def triage_issues(
self, issue_numbers: list[int], repo: str | None = None
) -> dict:
"""Triage and classify GitHub issues."""
try:
from runners.github.orchestrator import GitHubOrchestrator
resolved_repo = self._get_repo(repo)
config = self._create_config(resolved_repo)
config.triage_enabled = True
orchestrator = GitHubOrchestrator(
project_dir=self.project_dir, config=config
)
results = await orchestrator.triage_issues(issue_numbers=issue_numbers)
return {
"success": True,
"data": [r.to_dict() for r in results],
"count": len(results),
}
except ImportError:
return {"error": "GitHub runner module not available"}
except Exception as e:
return {"error": str(e)}
@@ -0,0 +1,82 @@
"""
Ideation Service
=================
Wraps the backend IdeationOrchestrator for MCP tool access.
"""
from __future__ import annotations
import json
import logging
from pathlib import Path
logger = logging.getLogger(__name__)
# Valid ideation types
VALID_IDEATION_TYPES = [
"low_hanging_fruit",
"ui_ux_improvements",
"high_value_features",
]
class IdeationService:
"""Service layer for AI-powered ideation generation."""
def __init__(self, project_dir: Path):
self.project_dir = project_dir
self.ideation_dir = project_dir / ".auto-claude" / "ideation"
async def generate(
self,
types: list[str] | None = None,
refresh: bool = False,
model: str = "sonnet",
thinking_level: str = "medium",
) -> dict:
"""Generate ideas for project improvements."""
try:
from ideation import IdeationOrchestrator
# Validate types
enabled_types = types or VALID_IDEATION_TYPES
invalid = [t for t in enabled_types if t not in VALID_IDEATION_TYPES]
if invalid:
return {
"error": f"Invalid ideation types: {invalid}. "
f"Valid types: {VALID_IDEATION_TYPES}"
}
orchestrator = IdeationOrchestrator(
project_dir=self.project_dir,
enabled_types=enabled_types,
model=model,
thinking_level=thinking_level,
refresh=refresh,
)
success = await orchestrator.run()
if success:
return self.get_ideation()
return {"error": "Ideation generation failed. Check logs for details."}
except ImportError:
return {"error": "Ideation module not available"}
except Exception as e:
return {"error": str(e)}
def get_ideation(self) -> dict:
"""Get previously generated ideation results from disk."""
ideation_file = self.ideation_dir / "ideation.json"
if not ideation_file.exists():
return {
"success": True,
"data": None,
"message": "No ideation data yet. Use ideation_generate first.",
}
try:
with open(ideation_file, encoding="utf-8") as f:
ideation = json.load(f)
return {"success": True, "data": ideation}
except (json.JSONDecodeError, OSError) as e:
return {"error": f"Failed to load ideation data: {e}"}
@@ -0,0 +1,116 @@
"""
Insights Service
=================
Wraps the backend InsightsRunner for MCP tool access.
Captures stdout output since run_with_sdk prints to stdout.
"""
from __future__ import annotations
import contextlib
import io
import json
import logging
from pathlib import Path
logger = logging.getLogger(__name__)
class InsightsService:
"""Service layer for codebase insights / AI chat."""
def __init__(self, project_dir: Path):
self.project_dir = project_dir
async def ask(
self,
question: str,
history: list | None = None,
model: str = "sonnet",
thinking_level: str = "medium",
) -> dict:
"""Ask an AI question about the codebase.
IMPORTANT: run_with_sdk prints to stdout, so we capture it.
"""
try:
from runners.insights_runner import run_with_sdk
history = history or []
captured = io.StringIO()
with contextlib.redirect_stdout(captured):
await run_with_sdk(
project_dir=str(self.project_dir),
message=question,
history=history,
model=model,
thinking_level=thinking_level,
)
output = captured.getvalue()
# Parse out any task suggestions from the output
task_suggestions = []
response_lines = []
for line in output.split("\n"):
if line.startswith("__TASK_SUGGESTION__:"):
try:
suggestion_json = line.split("__TASK_SUGGESTION__:", 1)[1]
task_suggestions.append(json.loads(suggestion_json))
except (json.JSONDecodeError, IndexError):
pass
elif line.startswith("__TOOL_START__:") or line.startswith(
"__TOOL_END__:"
):
# Skip tool markers - they're for the Electron UI
pass
else:
response_lines.append(line)
response_text = "\n".join(response_lines).strip()
return {
"success": True,
"response": response_text,
"task_suggestions": task_suggestions,
}
except ImportError:
return {"error": "Insights runner module not available"}
except Exception as e:
return {"error": str(e)}
def suggest_tasks(self) -> dict:
"""Get AI-suggested tasks based on project analysis.
Reads the most recent ideation/insights data if available.
"""
try:
ideation_file = (
self.project_dir / ".auto-claude" / "ideation" / "ideation.json"
)
if ideation_file.exists():
with open(ideation_file, encoding="utf-8") as f:
ideation = json.load(f)
ideas = ideation.get("ideas", [])
# Convert top ideas to task suggestions
suggestions = []
for idea in ideas[:10]:
suggestions.append(
{
"title": idea.get("title", ""),
"description": idea.get("description", ""),
"category": idea.get("type", "feature"),
"impact": idea.get("impact", "medium"),
"effort": idea.get("effort", "medium"),
}
)
return {"success": True, "suggestions": suggestions}
return {
"success": True,
"suggestions": [],
"message": "No ideation data available. Run ideation_generate first.",
}
except Exception as e:
return {"error": str(e)}
@@ -0,0 +1,161 @@
"""
Memory Service
===============
Wraps the Graphiti memory system for MCP tool access.
Gracefully handles the case where Graphiti is not enabled/configured.
"""
from __future__ import annotations
import logging
import os
from pathlib import Path
logger = logging.getLogger(__name__)
# Module-level singleton
_instance: MemoryService | None = None
def get_memory_service(project_dir: Path) -> MemoryService:
"""Return a lazily-created singleton MemoryService.
Preserves the cached Graphiti connection across tool calls.
If project_dir changes, a new instance is created.
"""
global _instance
if _instance is None or _instance.project_dir != project_dir:
_instance = MemoryService(project_dir)
return _instance
def _is_graphiti_enabled() -> bool:
"""Check if Graphiti memory is enabled via environment variable."""
return os.environ.get("GRAPHITI_ENABLED", "").lower() in ("true", "1")
class MemoryService:
"""Service layer for Graphiti-based semantic memory."""
def __init__(self, project_dir: Path):
self.project_dir = project_dir
self._memory = None
def _get_disabled_message(self) -> dict:
"""Return a helpful error when Graphiti is not enabled."""
return {
"error": "Graphiti memory is not enabled. "
"Set GRAPHITI_ENABLED=true in your .env file and configure "
"the required provider settings (LLM and embedder). "
"See the project documentation for setup instructions."
}
async def _get_memory(self):
"""Lazily initialize and return a GraphitiMemory instance."""
if self._memory is not None:
return self._memory
if not _is_graphiti_enabled():
return None
try:
from integrations.graphiti.memory import (
GraphitiMemory,
GroupIdMode,
)
# Use a dummy spec_dir since we're in project-wide mode
spec_dir = self.project_dir / ".auto-claude" / "mcp_memory"
spec_dir.mkdir(parents=True, exist_ok=True)
memory = GraphitiMemory(
spec_dir=spec_dir,
project_dir=self.project_dir,
group_id_mode=GroupIdMode.PROJECT,
)
if not await memory.initialize():
logger.warning("Failed to initialize Graphiti memory")
return None
self._memory = memory
return memory
except ImportError:
logger.warning("Graphiti modules not available")
return None
except Exception as e:
logger.warning("Failed to create Graphiti memory: %s", e)
return None
async def search(self, query: str, limit: int = 10) -> dict:
"""Search the project's semantic memory."""
if not _is_graphiti_enabled():
return self._get_disabled_message()
try:
memory = await self._get_memory()
if memory is None:
return {"error": "Could not initialize Graphiti memory"}
results = await memory.get_relevant_context(
query=query,
num_results=limit,
)
return {
"success": True,
"results": results,
"count": len(results),
}
except Exception as e:
return {"error": f"Memory search failed: {e}"}
async def add_episode(self, content: str, source: str = "mcp") -> dict:
"""Add a new episode/fact to the project's memory."""
if not _is_graphiti_enabled():
return self._get_disabled_message()
try:
memory = await self._get_memory()
if memory is None:
return {"error": "Could not initialize Graphiti memory"}
success = await memory.save_session_insights(
session_num=0,
insights={
"content": content,
"source": source,
"type": "mcp_episode",
},
)
if success:
return {"success": True, "message": "Episode added to memory"}
return {"error": "Failed to save episode to memory"}
except Exception as e:
return {"error": f"Failed to add episode: {e}"}
async def get_recent(self, limit: int = 10) -> dict:
"""Get recent memory entries."""
if not _is_graphiti_enabled():
return self._get_disabled_message()
try:
memory = await self._get_memory()
if memory is None:
return {"error": "Could not initialize Graphiti memory"}
# Use a broad search to get recent entries
results = await memory.get_relevant_context(
query="recent project activity and insights",
num_results=limit,
)
return {
"success": True,
"results": results,
"count": len(results),
}
except Exception as e:
return {"error": f"Failed to get recent memory: {e}"}
@@ -0,0 +1,236 @@
"""
QA Service
===========
Service layer wrapping the backend QA reviewer for MCP tool consumption.
Handles client creation, stdout isolation, and error management.
"""
from __future__ import annotations
import contextlib
import io
import json
import logging
from pathlib import Path
logger = logging.getLogger(__name__)
class QAService:
"""Wraps QA review and approval operations for MCP server use."""
def __init__(self, project_dir: Path):
self.project_dir = project_dir
async def start_review(
self,
spec_id: str,
model: str = "sonnet",
thinking_level: str = "medium",
max_iterations: int = 3,
) -> dict:
"""Run a QA review session for a completed build.
Args:
spec_id: The spec folder name
model: Model shorthand
thinking_level: Thinking level
max_iterations: Maximum QA loop iterations
Returns:
Dict with review outcome (approved/rejected/error)
"""
spec_dir = self._resolve_spec_dir(spec_id)
if spec_dir is None:
return {"error": f"Spec '{spec_id}' not found"}
# Verify the build is complete before starting QA
plan_file = spec_dir / "implementation_plan.json"
if not plan_file.exists():
return {
"error": "No implementation plan found. Build the spec first.",
}
try:
from core.client import create_client
from qa.reviewer import run_qa_agent_session
except ImportError as e:
logger.error("Failed to import QA modules: %s", e)
return {"error": f"Backend module not available: {e}"}
try:
# Determine QA session number from existing state
qa_session = self._get_next_qa_session(spec_dir)
# Create a Claude SDK client for the QA agent
captured = io.StringIO()
with contextlib.redirect_stdout(captured):
client = create_client(
project_dir=self.project_dir,
spec_dir=spec_dir,
model=model,
phase="qa_reviewer",
)
status, response_text, error_info = await run_qa_agent_session(
client=client,
project_dir=self.project_dir,
spec_dir=spec_dir,
qa_session=qa_session,
max_iterations=max_iterations,
)
return {
"spec_id": spec_id,
"status": status,
"qa_session": qa_session,
"response_preview": response_text[:1000] if response_text else "",
"error_info": error_info if error_info else None,
"output": captured.getvalue()[-1000:] if captured.getvalue() else "",
}
except Exception as e:
logger.exception("QA review failed for %s", spec_id)
return {
"spec_id": spec_id,
"status": "error",
"error": str(e),
}
def get_report(self, spec_id: str) -> dict:
"""Get the QA report for a spec.
Args:
spec_id: The spec folder name
Returns:
Dict with QA report content and status
"""
spec_dir = self._resolve_spec_dir(spec_id)
if spec_dir is None:
return {"error": f"Spec '{spec_id}' not found"}
result: dict = {"spec_id": spec_id}
# Read qa_report.md
qa_report = spec_dir / "qa_report.md"
if qa_report.exists():
try:
result["report"] = qa_report.read_text(encoding="utf-8")
except OSError as e:
result["report_error"] = str(e)
# Read QA fix request if present
fix_request = spec_dir / "QA_FIX_REQUEST.md"
if fix_request.exists():
try:
result["fix_request"] = fix_request.read_text(encoding="utf-8")
except OSError as e:
result["fix_request_error"] = str(e)
# Read qa_signoff from implementation plan
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)
qa_signoff = plan.get("qa_signoff")
if qa_signoff:
result["qa_signoff"] = qa_signoff
except (json.JSONDecodeError, OSError):
pass
if "report" not in result and "qa_signoff" not in result:
result["message"] = "No QA report found. Run QA review first."
return result
def approve(self, spec_id: str) -> dict:
"""Manually approve a spec's QA status.
Args:
spec_id: The spec folder name
Returns:
Dict with approval result
"""
spec_dir = self._resolve_spec_dir(spec_id)
if spec_dir is None:
return {"error": f"Spec '{spec_id}' not found"}
plan_file = spec_dir / "implementation_plan.json"
if not plan_file.exists():
return {"error": "No implementation plan found"}
try:
with open(plan_file, encoding="utf-8") as f:
plan = json.load(f)
except (json.JSONDecodeError, OSError) as e:
return {"error": f"Could not read implementation plan: {e}"}
from datetime import datetime, timezone
plan["qa_signoff"] = {
"status": "approved",
"timestamp": datetime.now(timezone.utc).isoformat(),
"qa_session": plan.get("qa_signoff", {}).get("qa_session", 0),
"verified_by": "manual_approval",
"note": "Manually approved via MCP tool",
}
try:
with open(plan_file, "w", encoding="utf-8") as f:
json.dump(plan, f, indent=2)
except OSError as e:
return {"error": f"Could not write implementation plan: {e}"}
return {
"success": True,
"spec_id": spec_id,
"message": "Spec manually approved",
}
def _get_next_qa_session(self, spec_dir: Path) -> int:
"""Get the next QA session number.
Args:
spec_dir: Path to the spec directory
Returns:
Next session number (1-based)
"""
plan_file = spec_dir / "implementation_plan.json"
if not plan_file.exists():
return 1
try:
with open(plan_file, encoding="utf-8") as f:
plan = json.load(f)
qa_signoff = plan.get("qa_signoff", {})
current = qa_signoff.get("qa_session", 0)
return current + 1
except (json.JSONDecodeError, OSError):
return 1
def _resolve_spec_dir(self, spec_id: str) -> Path | None:
"""Resolve spec_id to its directory path.
Args:
spec_id: Full or prefix spec identifier
Returns:
Path to spec directory or None
"""
specs_dir = self.project_dir / ".auto-claude" / "specs"
# Direct match
exact = specs_dir / spec_id
if exact.is_dir():
return exact
# Prefix match
if specs_dir.is_dir():
for item in specs_dir.iterdir():
if item.is_dir() and item.name.startswith(spec_id):
return item
return None
@@ -0,0 +1,65 @@
"""
Roadmap Service
================
Wraps the backend RoadmapOrchestrator for MCP tool access.
"""
from __future__ import annotations
import json
import logging
from pathlib import Path
logger = logging.getLogger(__name__)
class RoadmapService:
"""Service layer for roadmap generation features."""
def __init__(self, project_dir: Path):
self.project_dir = project_dir
self.roadmap_dir = project_dir / ".auto-claude" / "roadmap"
async def generate(
self,
refresh: bool = False,
model: str = "sonnet",
thinking_level: str = "medium",
) -> dict:
"""Generate a strategic roadmap for the project."""
try:
from runners.roadmap.orchestrator import RoadmapOrchestrator
orchestrator = RoadmapOrchestrator(
project_dir=self.project_dir,
model=model,
thinking_level=thinking_level,
refresh=refresh,
)
success = await orchestrator.run()
if success:
# Load and return the generated roadmap
return self.get_roadmap()
return {"error": "Roadmap generation failed. Check logs for details."}
except ImportError:
return {"error": "Roadmap runner module not available"}
except Exception as e:
return {"error": str(e)}
def get_roadmap(self) -> dict:
"""Get the current roadmap data from disk."""
roadmap_file = self.roadmap_dir / "roadmap.json"
if not roadmap_file.exists():
return {
"success": True,
"data": None,
"message": "No roadmap generated yet. Use roadmap_generate first.",
}
try:
with open(roadmap_file, encoding="utf-8") as f:
roadmap = json.load(f)
return {"success": True, "data": roadmap}
except (json.JSONDecodeError, OSError) as e:
return {"error": f"Failed to load roadmap: {e}"}
@@ -0,0 +1,242 @@
"""
Spec Service
=============
Service layer wrapping the backend SpecOrchestrator for MCP tool consumption.
Handles stdout isolation and error management.
"""
from __future__ import annotations
import contextlib
import io
import json
import logging
from pathlib import Path
logger = logging.getLogger(__name__)
class SpecService:
"""Wraps backend spec creation pipeline for MCP server use."""
def __init__(self, project_dir: Path):
self.project_dir = project_dir
async def create_spec(
self,
task_description: str,
model: str = "sonnet",
thinking_level: str = "medium",
complexity_override: str | None = None,
) -> dict:
"""Create a spec using the SpecOrchestrator.
Redirects stdout to prevent protocol corruption when running
under stdio transport.
Args:
task_description: Description of the task to spec out
model: Model shorthand (sonnet, opus, etc.)
thinking_level: Thinking level (low, medium, high)
complexity_override: Force a specific complexity level
Returns:
Dict with success status, spec_dir, spec_id, and any captured output
"""
try:
from spec.pipeline.orchestrator import SpecOrchestrator
except ImportError as e:
logger.error("Failed to import SpecOrchestrator: %s", e)
return {
"success": False,
"error": f"Backend module not available: {e}",
}
try:
captured = io.StringIO()
with contextlib.redirect_stdout(captured):
orchestrator = SpecOrchestrator(
project_dir=self.project_dir,
task_description=task_description,
model=model,
thinking_level=thinking_level,
complexity_override=complexity_override,
use_ai_assessment=True,
)
# Run non-interactively with auto-approve for MCP
success = await orchestrator.run(interactive=False, auto_approve=True)
spec_dir = orchestrator.spec_dir
return {
"success": success,
"spec_dir": str(spec_dir),
"spec_id": spec_dir.name,
"output": captured.getvalue()[-2000:] if captured.getvalue() else "",
}
except Exception as e:
logger.exception("Spec creation failed")
return {
"success": False,
"error": str(e),
}
def get_spec_status(self, spec_id: str) -> dict:
"""Get the status of a spec by checking which phase files exist.
Args:
spec_id: The spec folder name (e.g. '001-my-feature')
Returns:
Dict describing which phases are complete and current state
"""
specs_dir = self.project_dir / ".auto-claude" / "specs"
spec_dir = self._resolve_spec_dir(specs_dir, spec_id)
if spec_dir is None:
return {"error": f"Spec '{spec_id}' not found"}
phases = {
"discovery": (spec_dir / "discovery.md").exists(),
"requirements": (spec_dir / "requirements.json").exists(),
"complexity_assessment": (spec_dir / "complexity_assessment.json").exists(),
"spec": (spec_dir / "spec.md").exists(),
"implementation_plan": (spec_dir / "implementation_plan.json").exists(),
}
# Determine overall status
if phases["implementation_plan"]:
plan = self._load_json(spec_dir / "implementation_plan.json")
qa_signoff = plan.get("qa_signoff") if plan else None
if qa_signoff and qa_signoff.get("status") == "approved":
status = "qa_approved"
elif qa_signoff and qa_signoff.get("status") == "rejected":
status = "qa_rejected"
elif (spec_dir / "qa_report.md").exists():
status = "qa_reviewed"
else:
status = "ready_to_build"
elif phases["spec"]:
status = "spec_complete"
elif phases["requirements"]:
status = "requirements_gathered"
elif phases["discovery"]:
status = "discovery_complete"
else:
status = "pending"
return {
"spec_id": spec_dir.name,
"spec_dir": str(spec_dir),
"status": status,
"phases": phases,
}
def get_spec_content(self, spec_id: str) -> dict:
"""Get the full content of a spec.
Args:
spec_id: The spec folder name
Returns:
Dict with spec.md content, requirements, implementation plan, etc.
"""
specs_dir = self.project_dir / ".auto-claude" / "specs"
spec_dir = self._resolve_spec_dir(specs_dir, spec_id)
if spec_dir is None:
return {"error": f"Spec '{spec_id}' not found"}
content: dict = {
"spec_id": spec_dir.name,
"spec_dir": str(spec_dir),
}
# Read spec.md
spec_md = spec_dir / "spec.md"
if spec_md.exists():
try:
content["spec_md"] = spec_md.read_text(encoding="utf-8")
except OSError as e:
content["spec_md_error"] = str(e)
# Read requirements.json
req = self._load_json(spec_dir / "requirements.json")
if req is not None:
content["requirements"] = req
# Read implementation_plan.json
plan = self._load_json(spec_dir / "implementation_plan.json")
if plan is not None:
content["implementation_plan"] = plan
# Read complexity_assessment.json
assessment = self._load_json(spec_dir / "complexity_assessment.json")
if assessment is not None:
content["complexity_assessment"] = assessment
# Read QA report if present
qa_report = spec_dir / "qa_report.md"
if qa_report.exists():
try:
content["qa_report"] = qa_report.read_text(encoding="utf-8")
except OSError:
pass
return content
def list_specs(self) -> list[dict]:
"""List all specs in the project.
Returns:
List of spec summary dicts
"""
specs_dir = self.project_dir / ".auto-claude" / "specs"
if not specs_dir.is_dir():
return []
specs = []
for item in sorted(specs_dir.iterdir()):
if item.is_dir() and not item.name.startswith("."):
status_info = self.get_spec_status(item.name)
specs.append(status_info)
return specs
def _resolve_spec_dir(self, specs_dir: Path, spec_id: str) -> Path | None:
"""Resolve a spec_id to its directory, supporting prefix matching.
Args:
specs_dir: Parent specs directory
spec_id: Full or prefix spec identifier
Returns:
Path to spec directory or None
"""
# Direct match
exact = specs_dir / spec_id
if exact.is_dir():
return exact
# Prefix match (e.g. '001' matches '001-my-feature')
if specs_dir.is_dir():
for item in specs_dir.iterdir():
if item.is_dir() and item.name.startswith(spec_id):
return item
return None
def _load_json(self, path: Path) -> dict | None:
"""Safely load a JSON file.
Args:
path: Path to the JSON file
Returns:
Parsed dict or None
"""
if not path.exists():
return None
try:
with open(path, encoding="utf-8") as f:
return json.load(f)
except (json.JSONDecodeError, OSError) as e:
logger.warning("Failed to load %s: %s", path, e)
return None
@@ -0,0 +1,429 @@
"""
Task Service
=============
Loads, creates, updates, and deletes tasks by scanning spec directories.
Ported from the TypeScript ProjectStore.loadTasksFromSpecsDir() logic.
"""
from __future__ import annotations
import json
import logging
import re
import shutil
from datetime import datetime, timezone
from pathlib import Path
logger = logging.getLogger(__name__)
# Valid task statuses used by the backend pipeline
VALID_STATUSES = frozenset(
{
"pending",
"spec_creating",
"planning",
"in_progress",
"qa_review",
"qa_fixing",
"human_review",
"done",
"failed",
"cancelled",
}
)
# Status priority for deduplication (higher = more "complete")
_STATUS_PRIORITY: dict[str, int] = {
"done": 100,
"human_review": 80,
"qa_fixing": 70,
"qa_review": 65,
"in_progress": 50,
"planning": 40,
"spec_creating": 35,
"pending": 20,
"cancelled": 15,
"failed": 10,
}
def _slugify(text: str) -> str:
"""Convert a title into a filesystem-safe slug."""
slug = text.lower().strip()
slug = re.sub(r"[^\w\s-]", "", slug)
slug = re.sub(r"[\s_]+", "-", slug)
slug = re.sub(r"-+", "-", slug)
return slug.strip("-")[:80]
def _safe_read_json(path: Path) -> dict | None:
"""Read a JSON file, returning None on any error."""
try:
return json.loads(path.read_text(encoding="utf-8"))
except (json.JSONDecodeError, OSError, ValueError):
return None
def _extract_spec_heading(spec_path: Path) -> str | None:
"""Extract the first markdown heading from a spec.md file."""
try:
content = spec_path.read_text(encoding="utf-8")
match = re.search(
r"^#\s+(?:Quick Spec:|Specification:)?\s*(.+)$", content, re.MULTILINE
)
if match:
return match.group(1).strip()
except OSError:
pass
return None
def _extract_spec_overview(spec_path: Path) -> str | None:
"""Extract the Overview section from a spec.md file."""
try:
content = spec_path.read_text(encoding="utf-8")
match = re.search(r"## Overview\s*\n+([\s\S]*?)(?=\n#{1,6}\s|$)", content)
if match:
return match.group(1).strip()
except OSError:
pass
return None
class TaskService:
"""Manages task lifecycle by reading/writing spec directories."""
def __init__(self, project_dir: Path) -> None:
self.project_dir = project_dir
self.specs_dir = project_dir / ".auto-claude" / "specs"
self.worktrees_dir = project_dir / ".auto-claude" / "worktrees" / "tasks"
# ------------------------------------------------------------------
# Read operations
# ------------------------------------------------------------------
def list_tasks(self) -> list[dict]:
"""Scan spec directories and build a deduplicated task list.
Scans both the main project specs dir and worktree specs dirs.
Main project tasks take priority over worktree duplicates.
"""
all_tasks: list[dict] = []
main_spec_ids: set[str] = set()
# 1. Scan main project specs
if self.specs_dir.is_dir():
main_tasks = self._load_tasks_from_specs_dir(self.specs_dir, "main")
all_tasks.extend(main_tasks)
main_spec_ids = {t["spec_id"] for t in main_tasks}
# 2. Scan worktree specs (only include if spec exists in main)
if self.worktrees_dir.is_dir():
try:
for worktree_dir in sorted(self.worktrees_dir.iterdir()):
if not worktree_dir.is_dir():
continue
wt_specs = worktree_dir / ".auto-claude" / "specs"
if wt_specs.is_dir():
wt_tasks = self._load_tasks_from_specs_dir(wt_specs, "worktree")
valid = [t for t in wt_tasks if t["spec_id"] in main_spec_ids]
all_tasks.extend(valid)
except OSError as exc:
logger.warning("Error scanning worktrees: %s", exc)
# 3. Deduplicate — prefer main over worktree
task_map: dict[str, dict] = {}
for task in all_tasks:
existing = task_map.get(task["spec_id"])
if existing is None:
task_map[task["spec_id"]] = task
else:
existing_is_main = existing.get("location") == "main"
new_is_main = task.get("location") == "main"
if existing_is_main and not new_is_main:
# Keep existing main
continue
elif not existing_is_main and new_is_main:
# Replace worktree with main
task_map[task["spec_id"]] = task
else:
# Same location — use status priority
ep = _STATUS_PRIORITY.get(existing.get("status", ""), 0)
np = _STATUS_PRIORITY.get(task.get("status", ""), 0)
if np > ep:
task_map[task["spec_id"]] = task
return list(task_map.values())
def get_task(self, spec_id: str) -> dict | None:
"""Get full details for a single task by spec_id."""
spec_dir = self.specs_dir / spec_id
if not spec_dir.is_dir():
# Try worktrees
spec_dir = self._find_spec_dir_in_worktrees(spec_id)
if spec_dir is None:
return None
return self._load_single_task(spec_dir, "main")
def create_task(self, title: str, description: str) -> dict:
"""Create a new spec directory with initial files.
Returns the created task dict.
"""
self.specs_dir.mkdir(parents=True, exist_ok=True)
next_num = self._next_spec_number()
slug = _slugify(title)
dir_name = f"{next_num:03d}-{slug}" if slug else f"{next_num:03d}"
spec_dir = self.specs_dir / dir_name
spec_dir.mkdir(parents=True, exist_ok=True)
now = datetime.now(timezone.utc).isoformat()
# Write requirements.json
requirements = {"task_description": description}
(spec_dir / "requirements.json").write_text(
json.dumps(requirements, indent=2), encoding="utf-8"
)
# Write implementation_plan.json
plan = {
"feature": title,
"title": title,
"description": description,
"status": "pending",
"phases": [],
"created_at": now,
"updated_at": now,
}
(spec_dir / "implementation_plan.json").write_text(
json.dumps(plan, indent=2), encoding="utf-8"
)
# Write task_metadata.json
metadata = {
"created_at": now,
"source": "mcp",
}
(spec_dir / "task_metadata.json").write_text(
json.dumps(metadata, indent=2), encoding="utf-8"
)
return self._load_single_task(spec_dir, "main") or {
"spec_id": dir_name,
"title": title,
"description": description,
"status": "pending",
}
def update_task(
self,
spec_id: str,
*,
title: str | None = None,
description: str | None = None,
status: str | None = None,
) -> dict | None:
"""Update task metadata/plan fields."""
spec_dir = self.specs_dir / spec_id
if not spec_dir.is_dir():
return None
plan_path = spec_dir / "implementation_plan.json"
plan = _safe_read_json(plan_path) or {}
changed = False
if title is not None:
plan["feature"] = title
plan["title"] = title
changed = True
if description is not None:
plan["description"] = description
# Also update requirements
req_path = spec_dir / "requirements.json"
reqs = _safe_read_json(req_path) or {}
reqs["task_description"] = description
req_path.write_text(json.dumps(reqs, indent=2), encoding="utf-8")
changed = True
if status is not None:
if status not in VALID_STATUSES:
return None
plan["status"] = status
changed = True
if changed:
plan["updated_at"] = datetime.now(timezone.utc).isoformat()
plan_path.write_text(json.dumps(plan, indent=2), encoding="utf-8")
return self._load_single_task(spec_dir, "main")
def delete_task(self, spec_id: str) -> bool:
"""Delete a spec directory. Returns True if deleted."""
spec_dir = self.specs_dir / spec_id
if not spec_dir.is_dir():
return False
# Safety: ensure it's actually within specs_dir (prevent traversal)
try:
spec_dir.resolve().relative_to(self.specs_dir.resolve())
except ValueError:
logger.error("Path traversal detected for spec_id: %s", spec_id)
return False
shutil.rmtree(spec_dir)
return True
def update_status(self, spec_id: str, status: str) -> dict | None:
"""Update just the status field in implementation_plan.json."""
if status not in VALID_STATUSES:
return None
return self.update_task(spec_id, status=status)
# ------------------------------------------------------------------
# Internal helpers
# ------------------------------------------------------------------
def _next_spec_number(self) -> int:
"""Find the highest existing spec number and return next."""
max_num = 0
if self.specs_dir.is_dir():
for entry in self.specs_dir.iterdir():
if entry.is_dir():
match = re.match(r"^(\d{3})-", entry.name)
if match:
max_num = max(max_num, int(match.group(1)))
return max_num + 1
def _find_spec_dir_in_worktrees(self, spec_id: str) -> Path | None:
"""Search worktree directories for a spec."""
if not self.worktrees_dir.is_dir():
return None
for wt_dir in self.worktrees_dir.iterdir():
if not wt_dir.is_dir():
continue
candidate = wt_dir / ".auto-claude" / "specs" / spec_id
if candidate.is_dir():
return candidate
return None
def _load_tasks_from_specs_dir(self, specs_dir: Path, location: str) -> list[dict]:
"""Load all tasks from a specs directory."""
tasks: list[dict] = []
try:
entries = sorted(specs_dir.iterdir())
except OSError as exc:
logger.warning("Error reading specs directory %s: %s", specs_dir, exc)
return []
for entry in entries:
if not entry.is_dir() or entry.name == ".gitkeep":
continue
try:
task = self._load_single_task(entry, location)
if task:
tasks.append(task)
except Exception as exc:
logger.warning("Error loading spec %s: %s", entry.name, exc)
return tasks
def _load_single_task(self, spec_dir: Path, location: str) -> dict | None:
"""Load a single task from its spec directory."""
dir_name = spec_dir.name
# Read implementation plan
plan = _safe_read_json(spec_dir / "implementation_plan.json")
# Read requirements
requirements = _safe_read_json(spec_dir / "requirements.json")
# Read metadata
metadata = _safe_read_json(spec_dir / "task_metadata.json")
# Determine title (priority: plan.feature > plan.title > dir name)
title = (plan or {}).get("feature") or (plan or {}).get("title") or dir_name
# If title looks like a spec ID (e.g. "054-some-slug"), try spec.md heading
if re.match(r"^\d{3}-", title):
spec_heading = _extract_spec_heading(spec_dir / "spec.md")
if spec_heading:
title = spec_heading
# Determine description (priority: plan.description > requirements.task_description > spec.md overview)
description = ""
if plan and plan.get("description"):
description = plan["description"]
if not description and requirements and requirements.get("task_description"):
description = requirements["task_description"]
if not description:
overview = _extract_spec_overview(spec_dir / "spec.md")
if overview:
description = overview
# Determine status
status = "pending"
if plan and plan.get("status"):
raw_status = plan["status"]
# Map frontend-style statuses to valid backend statuses
status_map: dict[str, str] = {
"pending": "pending",
"backlog": "pending",
"queue": "pending",
"queued": "pending",
"spec_creating": "spec_creating",
"planning": "planning",
"coding": "in_progress",
"in_progress": "in_progress",
"review": "qa_review",
"ai_review": "qa_review",
"qa_review": "qa_review",
"qa_fixing": "qa_fixing",
"human_review": "human_review",
"completed": "done",
"done": "done",
"pr_created": "done",
"error": "failed",
"failed": "failed",
"cancelled": "cancelled",
}
status = status_map.get(raw_status, "pending")
# Extract subtasks from plan phases
subtasks: list[dict] = []
if plan and plan.get("phases"):
for phase in plan["phases"]:
items = phase.get("subtasks") or phase.get("chunks") or []
for st in items:
subtasks.append(
{
"id": st.get("id", ""),
"title": st.get("description", ""),
"status": st.get("status", "pending"),
}
)
# Build result
created_at = (plan or {}).get("created_at", "")
updated_at = (plan or {}).get("updated_at", "")
return {
"spec_id": dir_name,
"title": title,
"description": description,
"status": status,
"subtasks": subtasks,
"metadata": metadata,
"location": location,
"specs_path": str(spec_dir),
"has_spec": (spec_dir / "spec.md").exists(),
"has_plan": (spec_dir / "implementation_plan.json").exists(),
"has_qa_report": (spec_dir / "qa_report.md").exists(),
"created_at": created_at,
"updated_at": updated_at,
}
@@ -0,0 +1,245 @@
"""
Workspace Service
==================
Service layer wrapping the backend WorktreeManager for MCP tool consumption.
Handles git worktree operations: list, diff, merge, discard, and PR creation.
"""
from __future__ import annotations
import contextlib
import io
import logging
from pathlib import Path
logger = logging.getLogger(__name__)
class WorkspaceService:
"""Wraps WorktreeManager operations for MCP server use."""
def __init__(self, project_dir: Path):
self.project_dir = project_dir
def _get_manager(self):
"""Lazily create a WorktreeManager instance.
Returns:
WorktreeManager instance
Raises:
ImportError: If backend module is not available
"""
from core.worktree import WorktreeManager
return WorktreeManager(self.project_dir)
def list_worktrees(self) -> dict:
"""List all active git worktrees for the project.
Returns:
Dict with list of worktree info dicts
"""
try:
manager = self._get_manager()
except ImportError as e:
return {"error": f"Backend module not available: {e}"}
try:
captured = io.StringIO()
with contextlib.redirect_stdout(captured):
worktrees = manager.list_all_worktrees()
result = []
for wt in worktrees:
entry = {
"spec_name": wt.spec_name,
"branch": wt.branch,
"path": str(wt.path),
"base_branch": wt.base_branch,
"is_active": wt.is_active,
"commit_count": wt.commit_count,
"files_changed": wt.files_changed,
"additions": wt.additions,
"deletions": wt.deletions,
}
if wt.days_since_last_commit is not None:
entry["days_since_last_commit"] = wt.days_since_last_commit
if wt.last_commit_date is not None:
entry["last_commit_date"] = wt.last_commit_date.isoformat()
result.append(entry)
return {"worktrees": result, "count": len(result)}
except Exception as e:
logger.exception("Failed to list worktrees")
return {"error": str(e)}
def get_diff(self, spec_id: str) -> dict:
"""Get the git diff for a spec's worktree.
Args:
spec_id: The spec folder name
Returns:
Dict with diff content and change summary
"""
try:
manager = self._get_manager()
except ImportError as e:
return {"error": f"Backend module not available: {e}"}
try:
captured = io.StringIO()
with contextlib.redirect_stdout(captured):
info = manager.get_worktree_info(spec_id)
if info is None:
return {"error": f"No worktree found for spec '{spec_id}'"}
# Get changed files
files = manager.get_changed_files(spec_id)
summary = manager.get_change_summary(spec_id)
# Get actual diff content
from core.git_executable import run_git
diff_result = run_git(
["diff", f"{info.base_branch}...HEAD"],
cwd=info.path,
)
diff_content = ""
if diff_result.returncode == 0:
diff_content = diff_result.stdout
# Truncate very large diffs
if len(diff_content) > 50000:
diff_content = (
diff_content[:50000]
+ "\n\n... (diff truncated, total length: "
+ str(len(diff_result.stdout))
+ " chars)"
)
return {
"spec_id": spec_id,
"branch": info.branch,
"base_branch": info.base_branch,
"changed_files": [
{"status": status, "path": path} for status, path in files
],
"summary": summary,
"diff": diff_content,
}
except Exception as e:
logger.exception("Failed to get diff for %s", spec_id)
return {"error": str(e)}
async def merge(self, spec_id: str, strategy: str = "auto") -> dict:
"""Merge a spec's worktree changes back to the main branch.
Args:
spec_id: The spec folder name
strategy: Merge strategy - 'auto' (git merge), 'no-commit' (stage only)
Returns:
Dict with merge result
"""
try:
manager = self._get_manager()
except ImportError as e:
return {"error": f"Backend module not available: {e}"}
try:
no_commit = strategy == "no-commit"
captured = io.StringIO()
with contextlib.redirect_stdout(captured):
success = manager.merge_worktree(
spec_id,
delete_after=False,
no_commit=no_commit,
)
return {
"success": success,
"spec_id": spec_id,
"strategy": strategy,
"output": captured.getvalue()[-2000:] if captured.getvalue() else "",
}
except Exception as e:
logger.exception("Failed to merge worktree for %s", spec_id)
return {"success": False, "error": str(e)}
def discard(self, spec_id: str) -> dict:
"""Discard a spec's worktree and optionally its branch.
Args:
spec_id: The spec folder name
Returns:
Dict with discard result
"""
try:
manager = self._get_manager()
except ImportError as e:
return {"error": f"Backend module not available: {e}"}
try:
captured = io.StringIO()
with contextlib.redirect_stdout(captured):
manager.remove_worktree(spec_id, delete_branch=True)
return {
"success": True,
"spec_id": spec_id,
"message": f"Worktree and branch for '{spec_id}' removed",
"output": captured.getvalue() if captured.getvalue() else "",
}
except Exception as e:
logger.exception("Failed to discard worktree for %s", spec_id)
return {"success": False, "error": str(e)}
async def create_pr(
self,
spec_id: str,
title: str | None = None,
body: str | None = None,
) -> dict:
"""Push branch and create a pull request from a spec's worktree.
Automatically detects the git provider (GitHub/GitLab).
Args:
spec_id: The spec folder name
title: PR title (defaults to spec name)
body: PR body (defaults to spec summary)
Returns:
Dict with PR URL and status
"""
try:
manager = self._get_manager()
except ImportError as e:
return {"error": f"Backend module not available: {e}"}
try:
captured = io.StringIO()
with contextlib.redirect_stdout(captured):
result = manager.push_and_create_pr(
spec_name=spec_id,
title=title,
)
return {
"success": result.get("success", False),
"spec_id": spec_id,
"pr_url": result.get("pr_url"),
"branch": result.get("branch"),
"provider": result.get("provider"),
"already_exists": result.get("already_exists", False),
"error": result.get("error"),
"output": captured.getvalue()[-1000:] if captured.getvalue() else "",
}
except Exception as e:
logger.exception("Failed to create PR for %s", spec_id)
return {"success": False, "error": str(e)}
@@ -0,0 +1 @@
"""MCP tool modules - each module registers tools with the FastMCP server."""
+159
View File
@@ -0,0 +1,159 @@
"""
Execution Tools
================
MCP tools for starting, stopping, and monitoring builds.
"""
from __future__ import annotations
import asyncio
import logging
from mcp_server.config import get_project_dir
from mcp_server.operations import OperationStatus, tracker
from mcp_server.server import mcp
logger = logging.getLogger(__name__)
@mcp.tool()
async def build_start(
spec_id: str,
model: str = "sonnet",
thinking_level: str = "medium",
) -> dict:
"""Start building/implementing a spec. This is a long-running operation.
Spawns the autonomous coding pipeline which creates a worktree, runs
the planner, then executes each subtask with parallel agents.
Args:
spec_id: Spec folder name or prefix (e.g. '001' or '001-my-feature')
model: Model to use - 'sonnet' (fast), 'opus' (thorough)
thinking_level: Reasoning depth - 'low', 'medium', 'high'
Returns:
An operation_id to poll with operation_get_status() for progress
"""
op = tracker.create("build", f"Building spec: {spec_id}")
async def _run() -> None:
try:
from mcp_server.services.execution_service import get_execution_service
service = get_execution_service(get_project_dir())
tracker.update(
op.id,
status=OperationStatus.RUNNING,
progress=5,
message="Spawning build process...",
)
proc = await service.start_build(
spec_id=spec_id,
model=model,
thinking_level=thinking_level,
)
tracker.update(
op.id,
status=OperationStatus.RUNNING,
progress=10,
message="Build process started, waiting for completion...",
)
# Wait for the process to complete
await proc.wait()
if proc.returncode == 0:
progress_info = service.get_progress(spec_id)
tracker.update(
op.id,
status=OperationStatus.COMPLETED,
progress=100,
message="Build completed successfully",
result=progress_info,
)
else:
logs = service.get_logs(spec_id, tail=20)
tracker.update(
op.id,
status=OperationStatus.FAILED,
error=f"Build exited with code {proc.returncode}",
result={
"exit_code": proc.returncode,
"tail_logs": logs.get("lines", []),
},
)
except Exception as e:
logger.exception("build_start operation failed")
tracker.update(
op.id,
status=OperationStatus.FAILED,
error=str(e),
)
op._task = asyncio.create_task(_run())
return {
"operation_id": op.id,
"message": "Build started. Poll operation_get_status() for progress.",
}
@mcp.tool()
def build_stop(spec_id: str) -> dict:
"""Stop a running build.
Terminates the build subprocess. The worktree and any partial changes
are preserved so the build can be resumed later.
Args:
spec_id: Spec folder name or prefix
Returns:
Whether the build was successfully stopped
"""
from mcp_server.services.execution_service import get_execution_service
service = get_execution_service(get_project_dir())
return service.stop_build(spec_id)
@mcp.tool()
def build_get_progress(spec_id: str) -> dict:
"""Get progress of a running or completed build.
Shows subtask completion status, QA state, and whether the build
is still running.
Args:
spec_id: Spec folder name or prefix
Returns:
Build progress including subtask completion and QA status
"""
from mcp_server.services.execution_service import get_execution_service
service = get_execution_service(get_project_dir())
return service.get_progress(spec_id)
@mcp.tool()
def build_get_logs(spec_id: str, tail: int = 50) -> dict:
"""Get recent build logs for a spec.
Returns the most recent log lines from the build process output.
Args:
spec_id: Spec folder name or prefix
tail: Number of recent lines to return (default 50)
Returns:
Recent log lines from the build
"""
from mcp_server.services.execution_service import get_execution_service
service = get_execution_service(get_project_dir())
return service.get_logs(spec_id, tail=tail)
+208
View File
@@ -0,0 +1,208 @@
"""
GitHub Tools
=============
MCP tools for GitHub automation: PR review, issue triage, auto-fix.
Long-running operations return an operation_id for polling.
"""
from __future__ import annotations
import asyncio
from mcp_server.config import get_project_dir
from mcp_server.operations import OperationStatus, tracker
from mcp_server.server import mcp
from mcp_server.services.github_service import GitHubService
def _get_service() -> GitHubService:
return GitHubService(get_project_dir())
@mcp.tool()
async def github_review_pr(
pr_number: int, repo: str | None = None, model: str = "sonnet"
) -> dict:
"""Review a pull request with AI. Long-running operation - returns operation_id.
Performs a multi-pass AI code review including security, quality,
structural analysis, and AI comment triage.
Args:
pr_number: The PR number to review
repo: Repository in owner/repo format (auto-detected from git remote if omitted)
model: Model to use (haiku, sonnet, opus)
Returns:
Operation ID to poll with operation_get_status()
"""
service = _get_service()
op = tracker.create("github_review_pr", f"Starting review of PR #{pr_number}...")
async def _run():
try:
tracker.update(
op.id,
status=OperationStatus.RUNNING,
progress=10,
message=f"Reviewing PR #{pr_number}...",
)
result = await service.review_pr(pr_number, repo, model)
if "error" in result:
tracker.update(
op.id, status=OperationStatus.FAILED, error=result["error"]
)
else:
tracker.update(
op.id,
status=OperationStatus.COMPLETED,
progress=100,
message="Review complete",
result=result,
)
except Exception as e:
tracker.update(op.id, status=OperationStatus.FAILED, error=str(e))
op._task = asyncio.create_task(_run())
return {
"operation_id": op.id,
"message": f"PR #{pr_number} review started. Poll operation_get_status() for progress.",
}
@mcp.tool()
async def github_list_issues(
state: str = "open", limit: int = 30, repo: str | None = None
) -> dict:
"""List GitHub issues for the project.
Args:
state: Issue state filter: open, closed, or all
limit: Maximum number of issues to return
repo: Repository in owner/repo format (auto-detected if omitted)
Returns:
List of issues with number, title, state, labels, author
"""
service = _get_service()
return await service.list_issues(state, limit, repo)
@mcp.tool()
async def github_auto_fix(issue_number: int, repo: str | None = None) -> dict:
"""Automatically fix a GitHub issue by creating a spec and building it. Long-running.
Creates a specification from the issue, builds it through the autonomous
pipeline (planner -> coder -> QA), and optionally creates a PR.
Args:
issue_number: The issue number to auto-fix
repo: Repository in owner/repo format (auto-detected if omitted)
Returns:
Operation ID to poll with operation_get_status()
"""
service = _get_service()
op = tracker.create(
"github_auto_fix", f"Starting auto-fix for issue #{issue_number}..."
)
async def _run():
try:
tracker.update(
op.id,
status=OperationStatus.RUNNING,
progress=10,
message=f"Auto-fixing issue #{issue_number}...",
)
result = await service.auto_fix_issue(issue_number, repo)
if "error" in result:
tracker.update(
op.id, status=OperationStatus.FAILED, error=result["error"]
)
else:
tracker.update(
op.id,
status=OperationStatus.COMPLETED,
progress=100,
message="Auto-fix complete",
result=result,
)
except Exception as e:
tracker.update(op.id, status=OperationStatus.FAILED, error=str(e))
op._task = asyncio.create_task(_run())
return {
"operation_id": op.id,
"message": f"Auto-fix for issue #{issue_number} started. Poll operation_get_status() for progress.",
}
@mcp.tool()
def github_get_review(pr_number: int) -> dict:
"""Get the most recent review result for a PR.
Returns the saved review data including findings, verdict, and summary.
Args:
pr_number: The PR number to get the review for
Returns:
Review result with findings, verdict, blockers, and summary
"""
service = _get_service()
return service.get_review(pr_number)
@mcp.tool()
async def github_triage_issues(
issue_numbers: list[int], repo: str | None = None
) -> dict:
"""Triage and classify GitHub issues. Long-running.
Analyzes issues for duplicates, spam, feature creep, and assigns
categories, priority, and suggested labels.
Args:
issue_numbers: List of issue numbers to triage
repo: Repository in owner/repo format (auto-detected if omitted)
Returns:
Operation ID to poll with operation_get_status()
"""
service = _get_service()
op = tracker.create(
"github_triage_issues",
f"Starting triage of {len(issue_numbers)} issues...",
)
async def _run():
try:
tracker.update(
op.id,
status=OperationStatus.RUNNING,
progress=10,
message=f"Triaging {len(issue_numbers)} issues...",
)
result = await service.triage_issues(issue_numbers, repo)
if "error" in result:
tracker.update(
op.id, status=OperationStatus.FAILED, error=result["error"]
)
else:
tracker.update(
op.id,
status=OperationStatus.COMPLETED,
progress=100,
message=f"Triaged {result.get('count', 0)} issues",
result=result,
)
except Exception as e:
tracker.update(op.id, status=OperationStatus.FAILED, error=str(e))
op._task = asyncio.create_task(_run())
return {
"operation_id": op.id,
"message": f"Triage of {len(issue_numbers)} issues started. Poll operation_get_status() for progress.",
}
+87
View File
@@ -0,0 +1,87 @@
"""
Ideation Tools
===============
MCP tools for AI-powered project ideation and improvement discovery.
"""
from __future__ import annotations
import asyncio
from mcp_server.config import get_project_dir
from mcp_server.operations import OperationStatus, tracker
from mcp_server.server import mcp
from mcp_server.services.ideation_service import IdeationService
def _get_service() -> IdeationService:
return IdeationService(get_project_dir())
@mcp.tool()
async def ideation_generate(
types: list[str] | None = None,
refresh: bool = False,
model: str = "sonnet",
) -> dict:
"""Generate ideas for project improvements. Long-running.
Analyzes the codebase and generates actionable improvement ideas
across multiple categories.
Args:
types: Ideation types to generate. Options: low_hanging_fruit,
ui_ux_improvements, high_value_features. Defaults to all.
refresh: Force regeneration of existing ideation data
model: Model to use (haiku, sonnet, opus)
Returns:
Operation ID to poll with operation_get_status()
"""
service = _get_service()
op = tracker.create("ideation_generate", "Starting ideation generation...")
async def _run():
try:
tracker.update(
op.id,
status=OperationStatus.RUNNING,
progress=10,
message="Analyzing project for improvement ideas...",
)
result = await service.generate(types=types, refresh=refresh, model=model)
if "error" in result:
tracker.update(
op.id, status=OperationStatus.FAILED, error=result["error"]
)
else:
tracker.update(
op.id,
status=OperationStatus.COMPLETED,
progress=100,
message="Ideation complete",
result=result,
)
except Exception as e:
tracker.update(op.id, status=OperationStatus.FAILED, error=str(e))
op._task = asyncio.create_task(_run())
return {
"operation_id": op.id,
"message": "Ideation generation started. Poll operation_get_status() for progress.",
}
@mcp.tool()
def ideation_get() -> dict:
"""Get previously generated ideation results.
Returns all generated ideas with their categories, priorities,
effort estimates, and implementation suggestions.
Returns:
Ideation data with ideas grouped by type and priority
"""
service = _get_service()
return service.get_ideation()
+84
View File
@@ -0,0 +1,84 @@
"""
Insights Tools
===============
MCP tools for AI-powered codebase insights and Q&A.
"""
from __future__ import annotations
import asyncio
from mcp_server.config import get_project_dir
from mcp_server.operations import OperationStatus, tracker
from mcp_server.server import mcp
from mcp_server.services.insights_service import InsightsService
def _get_service() -> InsightsService:
return InsightsService(get_project_dir())
@mcp.tool()
async def insights_ask(
question: str, history: list | None = None, model: str = "sonnet"
) -> dict:
"""Ask an AI question about the codebase. Long-running operation.
The AI agent has access to the codebase and can read files, search,
and explore to answer questions about architecture, patterns, bugs, etc.
Args:
question: The question to ask about the codebase
history: Optional conversation history as list of {role, content} dicts
model: Model to use (haiku, sonnet, opus)
Returns:
Operation ID to poll with operation_get_status()
"""
service = _get_service()
op = tracker.create("insights_ask", "Processing question...")
async def _run():
try:
tracker.update(
op.id,
status=OperationStatus.RUNNING,
progress=10,
message="AI is exploring the codebase...",
)
result = await service.ask(question, history, model)
if "error" in result:
tracker.update(
op.id, status=OperationStatus.FAILED, error=result["error"]
)
else:
tracker.update(
op.id,
status=OperationStatus.COMPLETED,
progress=100,
message="Question answered",
result=result,
)
except Exception as e:
tracker.update(op.id, status=OperationStatus.FAILED, error=str(e))
op._task = asyncio.create_task(_run())
return {
"operation_id": op.id,
"message": "Insights query started. Poll operation_get_status() for the answer.",
}
@mcp.tool()
def insights_suggest_tasks() -> dict:
"""Get AI-suggested tasks based on recent insights conversations.
Returns task suggestions derived from ideation data or previous
insights conversations.
Returns:
List of task suggestions with title, description, category, impact
"""
service = _get_service()
return service.suggest_tasks()
+71
View File
@@ -0,0 +1,71 @@
"""
Memory Tools
=============
MCP tools for Graphiti-based semantic memory (knowledge graph).
Requires GRAPHITI_ENABLED=true in the environment.
"""
from __future__ import annotations
from mcp_server.config import get_project_dir
from mcp_server.server import mcp
from mcp_server.services.memory_service import get_memory_service
@mcp.tool()
async def memory_search(query: str, limit: int = 10) -> dict:
"""Search the project's semantic memory (Graphiti knowledge graph).
Finds relevant stored knowledge including codebase discoveries,
session insights, patterns, gotchas, and task outcomes.
Requires GRAPHITI_ENABLED=true in environment.
Args:
query: Search query describing what you're looking for
limit: Maximum number of results to return (default 10)
Returns:
List of relevant memory entries with content and relevance scores
"""
service = get_memory_service(get_project_dir())
return await service.search(query, limit)
@mcp.tool()
async def memory_add_episode(content: str, source: str = "mcp") -> dict:
"""Add a new episode/fact to the project's memory.
Stores information in the knowledge graph for future retrieval.
Use this to record insights, patterns, or important findings.
Requires GRAPHITI_ENABLED=true in environment.
Args:
content: The information to store (insight, pattern, discovery, etc.)
source: Source identifier for the episode (default: mcp)
Returns:
Confirmation of successful storage
"""
service = get_memory_service(get_project_dir())
return await service.add_episode(content, source)
@mcp.tool()
async def memory_get_recent(limit: int = 10) -> dict:
"""Get recent memory entries.
Retrieves the most recent entries from the project's knowledge graph.
Requires GRAPHITI_ENABLED=true in environment.
Args:
limit: Maximum number of entries to return (default 10)
Returns:
List of recent memory entries
"""
service = get_memory_service(get_project_dir())
return await service.get_recent(limit)
+52
View File
@@ -0,0 +1,52 @@
"""
Operations Management Tools
============================
Tools for polling long-running operation status and cancelling operations.
"""
from __future__ import annotations
from mcp_server.operations import tracker
from mcp_server.server import mcp
@mcp.tool()
def operation_get_status(operation_id: str) -> dict:
"""Get the status of a long-running operation.
Use this to poll for progress on operations started by tools like
spec_create, build_start, qa_start_review, etc.
Args:
operation_id: The operation ID returned by the tool that started the operation
Returns:
Operation status including progress (0-100), message, and result when complete
"""
op = tracker.get(operation_id)
if op is None:
return {"error": f"Operation {operation_id} not found"}
return op.to_dict()
@mcp.tool()
def operation_cancel(operation_id: str) -> dict:
"""Cancel a running operation.
Args:
operation_id: The operation ID to cancel
Returns:
Whether the cancellation was successful
"""
success = tracker.cancel(operation_id)
if not success:
op = tracker.get(operation_id)
if op is None:
return {"success": False, "error": "Operation not found"}
return {
"success": False,
"error": f"Cannot cancel operation in {op.status.value} state",
}
return {"success": True, "message": "Operation cancelled"}
+148
View File
@@ -0,0 +1,148 @@
"""
Project Management Tools
=========================
MCP tools for managing the active project: switching projects,
getting status, listing specs, and reading the project index.
"""
from __future__ import annotations
import logging
from mcp_server import config
from mcp_server.server import mcp
logger = logging.getLogger(__name__)
@mcp.tool()
def project_set_active(project_dir: str) -> dict:
"""Switch the MCP server to a different project directory.
Re-initializes the server to point at a new project.
All subsequent tool calls will operate on this project.
Args:
project_dir: Absolute path to the project directory
"""
try:
config.initialize(project_dir)
project_path = config.get_project_dir()
initialized = config.is_initialized()
return {
"success": True,
"project_dir": str(project_path),
"initialized": initialized,
"message": f"Active project set to {project_path}",
}
except (ValueError, RuntimeError) as exc:
return {"success": False, "error": str(exc)}
@mcp.tool()
def project_get_status() -> dict:
"""Get the current project status.
Returns the active project directory, initialization state,
specs count, and project index summary.
"""
try:
project_dir = config.get_project_dir()
except RuntimeError:
return {
"initialized": False,
"error": "No project set. Use project_set_active() first.",
}
initialized = config.is_initialized()
specs_count = 0
if initialized:
specs_dir = config.get_specs_dir()
if specs_dir.is_dir():
specs_count = sum(
1
for entry in specs_dir.iterdir()
if entry.is_dir() and entry.name != ".gitkeep"
)
index = config.get_project_index()
return {
"project_dir": str(project_dir),
"initialized": initialized,
"specs_count": specs_count,
"has_project_index": bool(index),
"project_name": index.get("name", project_dir.name),
}
@mcp.tool()
def project_list_specs() -> dict:
"""List all spec directories with their basic info.
Returns each spec's name, whether it has a plan/spec file,
and status from the implementation plan.
"""
try:
specs_dir = config.get_specs_dir()
except RuntimeError:
return {"error": "No project set. Use project_set_active() first.", "specs": []}
if not specs_dir.is_dir():
return {"specs": [], "message": "No specs directory found."}
specs: list[dict] = []
for entry in sorted(specs_dir.iterdir()):
if not entry.is_dir() or entry.name == ".gitkeep":
continue
has_plan = (entry / "implementation_plan.json").exists()
has_spec = (entry / "spec.md").exists()
status = "pending"
title = entry.name
if has_plan:
try:
import json
plan = json.loads(
(entry / "implementation_plan.json").read_text(encoding="utf-8")
)
status = plan.get("status", "pending")
title = plan.get("feature") or plan.get("title") or entry.name
except (json.JSONDecodeError, OSError):
pass
specs.append(
{
"name": entry.name,
"title": title,
"has_plan": has_plan,
"has_spec": has_spec,
"has_qa_report": (entry / "qa_report.md").exists(),
"status": status,
}
)
return {"specs": specs, "count": len(specs)}
@mcp.tool()
def project_get_index() -> dict:
"""Return the full project_index.json content.
The project index contains metadata about the project
such as file summaries, dependency info, and analysis results.
"""
try:
index = config.get_project_index()
except RuntimeError:
return {"error": "No project set. Use project_set_active() first."}
if not index:
return {"message": "No project index found. Run indexing first.", "index": {}}
return {"index": index}
+125
View File
@@ -0,0 +1,125 @@
"""
QA Tools
=========
MCP tools for running QA reviews, getting reports, and manual approval.
"""
from __future__ import annotations
import asyncio
import logging
from mcp_server.config import get_project_dir
from mcp_server.operations import OperationStatus, tracker
from mcp_server.server import mcp
logger = logging.getLogger(__name__)
@mcp.tool()
async def qa_start_review(spec_id: str) -> dict:
"""Start QA review for a completed build. This is a long-running operation.
Runs the QA reviewer agent which validates the implementation against
the spec's acceptance criteria. The agent reads code, runs tests, and
produces a detailed QA report.
Args:
spec_id: Spec folder name or prefix (e.g. '001' or '001-my-feature')
Returns:
An operation_id to poll with operation_get_status() for progress
"""
op = tracker.create("qa_review", f"QA review for: {spec_id}")
async def _run() -> None:
try:
from mcp_server.services.qa_service import QAService
service = QAService(get_project_dir())
tracker.update(
op.id,
status=OperationStatus.RUNNING,
progress=10,
message="Starting QA review session...",
)
result = await service.start_review(spec_id=spec_id)
status = result.get("status", "error")
if status == "approved":
tracker.update(
op.id,
status=OperationStatus.COMPLETED,
progress=100,
message="QA approved - all acceptance criteria validated",
result=result,
)
elif status == "rejected":
tracker.update(
op.id,
status=OperationStatus.COMPLETED,
progress=100,
message="QA rejected - issues found, see report",
result=result,
)
else:
tracker.update(
op.id,
status=OperationStatus.FAILED,
error=result.get("error", "QA review failed"),
result=result,
)
except Exception as e:
logger.exception("qa_start_review operation failed")
tracker.update(
op.id,
status=OperationStatus.FAILED,
error=str(e),
)
op._task = asyncio.create_task(_run())
return {
"operation_id": op.id,
"message": "QA review started. Poll operation_get_status() for progress.",
}
@mcp.tool()
def qa_get_report(spec_id: str) -> dict:
"""Get the QA report for a spec.
Returns the full QA report including validation results, issues found,
and the qa_signoff status from the implementation plan.
Args:
spec_id: Spec folder name or prefix
Returns:
QA report content, fix requests, and signoff status
"""
from mcp_server.services.qa_service import QAService
service = QAService(get_project_dir())
return service.get_report(spec_id)
@mcp.tool()
def qa_approve(spec_id: str) -> dict:
"""Manually approve a spec that's in QA review.
Use this to bypass the automated QA review and mark a spec as approved.
This updates the implementation_plan.json qa_signoff status.
Args:
spec_id: Spec folder name or prefix
Returns:
Whether the approval was successful
"""
from mcp_server.services.qa_service import QAService
service = QAService(get_project_dir())
return service.approve(spec_id)
+128
View File
@@ -0,0 +1,128 @@
"""
Roadmap Tools
==============
MCP tools for AI-powered strategic roadmap generation.
"""
from __future__ import annotations
import asyncio
from mcp_server.config import get_project_dir
from mcp_server.operations import OperationStatus, tracker
from mcp_server.server import mcp
from mcp_server.services.roadmap_service import RoadmapService
def _get_service() -> RoadmapService:
return RoadmapService(get_project_dir())
@mcp.tool()
async def roadmap_generate(refresh: bool = False, model: str = "sonnet") -> dict:
"""Generate a strategic roadmap for the project. Long-running.
Analyzes the project structure, existing features, and codebase to
generate a phased roadmap with prioritized features.
Args:
refresh: Force regeneration even if a roadmap already exists
model: Model to use (haiku, sonnet, opus)
Returns:
Operation ID to poll with operation_get_status()
"""
service = _get_service()
op = tracker.create("roadmap_generate", "Starting roadmap generation...")
async def _run():
try:
tracker.update(
op.id,
status=OperationStatus.RUNNING,
progress=10,
message="Analyzing project for roadmap generation...",
)
result = await service.generate(refresh=refresh, model=model)
if "error" in result:
tracker.update(
op.id, status=OperationStatus.FAILED, error=result["error"]
)
else:
tracker.update(
op.id,
status=OperationStatus.COMPLETED,
progress=100,
message="Roadmap generated",
result=result,
)
except Exception as e:
tracker.update(op.id, status=OperationStatus.FAILED, error=str(e))
op._task = asyncio.create_task(_run())
return {
"operation_id": op.id,
"message": "Roadmap generation started. Poll operation_get_status() for progress.",
}
@mcp.tool()
def roadmap_get() -> dict:
"""Get the current roadmap data.
Returns the previously generated roadmap including vision, phases,
features with priorities, and implementation details.
Returns:
Roadmap data with vision, phases, features, and priority breakdown
"""
service = _get_service()
return service.get_roadmap()
@mcp.tool()
async def roadmap_refresh(model: str = "sonnet") -> dict:
"""Refresh/regenerate the roadmap. Long-running.
Forces a complete regeneration of the roadmap, analyzing current
project state and creating updated phases and features.
Args:
model: Model to use (haiku, sonnet, opus)
Returns:
Operation ID to poll with operation_get_status()
"""
service = _get_service()
op = tracker.create("roadmap_refresh", "Starting roadmap refresh...")
async def _run():
try:
tracker.update(
op.id,
status=OperationStatus.RUNNING,
progress=10,
message="Refreshing roadmap...",
)
result = await service.generate(refresh=True, model=model)
if "error" in result:
tracker.update(
op.id, status=OperationStatus.FAILED, error=result["error"]
)
else:
tracker.update(
op.id,
status=OperationStatus.COMPLETED,
progress=100,
message="Roadmap refreshed",
result=result,
)
except Exception as e:
tracker.update(op.id, status=OperationStatus.FAILED, error=str(e))
op._task = asyncio.create_task(_run())
return {
"operation_id": op.id,
"message": "Roadmap refresh started. Poll operation_get_status() for progress.",
}
+149
View File
@@ -0,0 +1,149 @@
"""
Spec Tools
===========
MCP tools for creating and inspecting specifications.
"""
from __future__ import annotations
import asyncio
import logging
from mcp_server.config import get_project_dir
from mcp_server.operations import OperationStatus, tracker
from mcp_server.server import mcp
logger = logging.getLogger(__name__)
@mcp.tool()
async def spec_create(
task_description: str,
model: str = "sonnet",
thinking_level: str = "medium",
) -> dict:
"""Create a specification for a task. This is a long-running operation.
The spec creation pipeline runs multiple AI phases (discovery, requirements,
complexity assessment, spec writing, planning) to produce a complete
implementation-ready specification.
Args:
task_description: What you want to build (be specific and detailed)
model: Model to use - 'sonnet' (fast), 'opus' (thorough)
thinking_level: How much the AI reasons - 'low', 'medium', 'high'
Returns:
An operation_id to poll with operation_get_status() for progress
"""
op = tracker.create("spec_create", f"Creating spec for: {task_description[:80]}")
async def _run() -> None:
try:
from mcp_server.services.spec_service import SpecService
tracker.update(
op.id,
status=OperationStatus.RUNNING,
progress=5,
message="Initializing spec pipeline...",
)
service = SpecService(get_project_dir())
tracker.update(
op.id,
status=OperationStatus.RUNNING,
progress=10,
message="Running spec creation phases...",
)
result = await service.create_spec(
task_description=task_description,
model=model,
thinking_level=thinking_level,
)
if result.get("success"):
tracker.update(
op.id,
status=OperationStatus.COMPLETED,
progress=100,
message="Spec created successfully",
result=result,
)
else:
tracker.update(
op.id,
status=OperationStatus.FAILED,
progress=100,
message="Spec creation failed",
error=result.get("error", "Unknown error"),
result=result,
)
except Exception as e:
logger.exception("spec_create operation failed")
tracker.update(
op.id,
status=OperationStatus.FAILED,
error=str(e),
)
op._task = asyncio.create_task(_run())
return {
"operation_id": op.id,
"message": "Spec creation started. Poll operation_get_status() for progress.",
}
@mcp.tool()
def spec_get_status(spec_id: str) -> dict:
"""Get the current status of a spec (which phases have completed).
Shows whether discovery, requirements, spec writing, and planning
phases are complete, and the overall readiness state.
Args:
spec_id: Spec folder name or prefix (e.g. '001' or '001-my-feature')
Returns:
Status including completed phases and overall state
"""
from mcp_server.services.spec_service import SpecService
service = SpecService(get_project_dir())
return service.get_spec_status(spec_id)
@mcp.tool()
def spec_get_content(spec_id: str) -> dict:
"""Get the full content of a spec including spec.md, requirements, and plan.
Returns the complete specification content so you can understand what
will be built and how.
Args:
spec_id: Spec folder name or prefix (e.g. '001' or '001-my-feature')
Returns:
Full spec content including spec.md, requirements.json, implementation_plan.json
"""
from mcp_server.services.spec_service import SpecService
service = SpecService(get_project_dir())
return service.get_spec_content(spec_id)
@mcp.tool()
def spec_list() -> dict:
"""List all specs in the project with their status.
Returns:
List of specs with their current status and phase completion
"""
from mcp_server.services.spec_service import SpecService
service = SpecService(get_project_dir())
specs = service.list_specs()
return {"specs": specs, "count": len(specs)}
+179
View File
@@ -0,0 +1,179 @@
"""
Task Management Tools
======================
MCP tools for CRUD operations on tasks (specs).
Tasks are stored as spec directories under .auto-claude/specs/.
"""
from __future__ import annotations
import logging
from mcp_server import config
from mcp_server.server import mcp
from mcp_server.services.task_service import VALID_STATUSES, TaskService
logger = logging.getLogger(__name__)
def _get_task_service() -> TaskService:
"""Get a TaskService instance for the active project."""
return TaskService(config.get_project_dir())
@mcp.tool()
def task_list() -> dict:
"""List all tasks with id, title, status, and description preview.
Scans both the main project and worktree spec directories,
deduplicating with main project taking priority.
"""
try:
service = _get_task_service()
except RuntimeError as exc:
return {"error": str(exc), "tasks": []}
tasks = service.list_tasks()
# Return a concise view for listing
summary = []
for t in tasks:
desc = t.get("description", "")
preview = (desc[:200] + "...") if len(desc) > 200 else desc
summary.append(
{
"spec_id": t["spec_id"],
"title": t["title"],
"status": t["status"],
"description_preview": preview,
"has_spec": t.get("has_spec", False),
"has_plan": t.get("has_plan", False),
"subtask_count": len(t.get("subtasks", [])),
}
)
return {"tasks": summary, "count": len(summary)}
@mcp.tool()
def task_create(title: str, description: str) -> dict:
"""Create a new task (spec directory) with initial files.
Generates the next spec number automatically and creates
the directory with requirements.json, implementation_plan.json,
and task_metadata.json.
Args:
title: The task title (used for the directory name slug)
description: Full description of what needs to be done
"""
try:
service = _get_task_service()
except RuntimeError as exc:
return {"error": str(exc)}
if not title or not title.strip():
return {"error": "Title is required"}
if not description or not description.strip():
return {"error": "Description is required"}
task = service.create_task(title.strip(), description.strip())
return {"success": True, "task": task}
@mcp.tool()
def task_get(spec_id: str) -> dict:
"""Get full task details including subtasks, metadata, and file info.
Args:
spec_id: The spec directory name (e.g., "001-my-feature")
"""
try:
service = _get_task_service()
except RuntimeError as exc:
return {"error": str(exc)}
task = service.get_task(spec_id)
if task is None:
return {"error": f"Task '{spec_id}' not found"}
return {"task": task}
@mcp.tool()
def task_update(
spec_id: str,
title: str | None = None,
description: str | None = None,
status: str | None = None,
) -> dict:
"""Update task metadata (title, description, and/or status).
Args:
spec_id: The spec directory name (e.g., "001-my-feature")
title: New title (optional)
description: New description (optional)
status: New status (optional) - must be a valid status
"""
try:
service = _get_task_service()
except RuntimeError as exc:
return {"error": str(exc)}
if status is not None and status not in VALID_STATUSES:
return {"error": f"Invalid status '{status}'. Valid: {sorted(VALID_STATUSES)}"}
task = service.update_task(
spec_id, title=title, description=description, status=status
)
if task is None:
return {"error": f"Task '{spec_id}' not found or invalid update"}
return {"success": True, "task": task}
@mcp.tool()
def task_delete(spec_id: str) -> dict:
"""Delete a task by removing its spec directory.
WARNING: This permanently deletes the spec directory and all its contents.
Args:
spec_id: The spec directory name (e.g., "001-my-feature")
"""
try:
service = _get_task_service()
except RuntimeError as exc:
return {"error": str(exc)}
deleted = service.delete_task(spec_id)
if not deleted:
return {"error": f"Task '{spec_id}' not found"}
return {"success": True, "message": f"Task '{spec_id}' deleted"}
@mcp.tool()
def task_update_status(spec_id: str, status: str) -> dict:
"""Update just the status field of a task.
Args:
spec_id: The spec directory name (e.g., "001-my-feature")
status: New status value. Valid statuses: pending, spec_creating,
planning, in_progress, qa_review, qa_fixing, human_review,
done, failed, cancelled
"""
try:
service = _get_task_service()
except RuntimeError as exc:
return {"error": str(exc)}
if status not in VALID_STATUSES:
return {"error": f"Invalid status '{status}'. Valid: {sorted(VALID_STATUSES)}"}
task = service.update_status(spec_id, status)
if task is None:
return {"error": f"Task '{spec_id}' not found"}
return {"success": True, "task": task}
+159
View File
@@ -0,0 +1,159 @@
"""
Workspace Tools
================
MCP tools for managing git worktrees: list, diff, merge, discard, and PR creation.
"""
from __future__ import annotations
import asyncio
import logging
from mcp_server.config import get_project_dir
from mcp_server.operations import OperationStatus, tracker
from mcp_server.server import mcp
logger = logging.getLogger(__name__)
@mcp.tool()
def workspace_list() -> dict:
"""List all active git worktrees for the project.
Each spec gets its own isolated worktree. This shows all active
worktrees with their branch, change stats, and age.
Returns:
List of worktrees with branch, stats, and age information
"""
from mcp_server.services.workspace_service import WorkspaceService
service = WorkspaceService(get_project_dir())
return service.list_worktrees()
@mcp.tool()
def workspace_diff(spec_id: str) -> dict:
"""Get the git diff for a spec's worktree.
Shows all changes made in the spec's branch compared to the base branch,
including a file-level summary and the full diff content.
Args:
spec_id: Spec folder name or prefix (e.g. '001' or '001-my-feature')
Returns:
Changed files summary and full diff content
"""
from mcp_server.services.workspace_service import WorkspaceService
service = WorkspaceService(get_project_dir())
return service.get_diff(spec_id)
@mcp.tool()
async def workspace_merge(spec_id: str, strategy: str = "auto") -> dict:
"""Merge a spec's worktree changes back to the main branch.
Args:
spec_id: Spec folder name or prefix
strategy: 'auto' for standard git merge, 'no-commit' to stage without committing
Returns:
Whether the merge was successful
"""
from mcp_server.services.workspace_service import WorkspaceService
service = WorkspaceService(get_project_dir())
return await service.merge(spec_id, strategy=strategy)
@mcp.tool()
def workspace_discard(spec_id: str) -> dict:
"""Discard a spec's worktree and its branch.
Permanently removes the worktree directory and deletes the associated
git branch. This cannot be undone.
Args:
spec_id: Spec folder name or prefix
Returns:
Whether the discard was successful
"""
from mcp_server.services.workspace_service import WorkspaceService
service = WorkspaceService(get_project_dir())
return service.discard(spec_id)
@mcp.tool()
async def workspace_create_pr(
spec_id: str,
title: str | None = None,
body: str | None = None,
) -> dict:
"""Create a pull request from a spec's worktree branch.
Pushes the branch to origin and creates a PR/MR on the detected
git hosting provider (GitHub or GitLab). This is a long-running operation.
Args:
spec_id: Spec folder name or prefix
title: PR title (defaults to spec name)
body: PR body (defaults to spec summary)
Returns:
An operation_id to poll with operation_get_status() for progress
"""
op = tracker.create("create_pr", f"Creating PR for: {spec_id}")
async def _run() -> None:
try:
from mcp_server.services.workspace_service import WorkspaceService
service = WorkspaceService(get_project_dir())
tracker.update(
op.id,
status=OperationStatus.RUNNING,
progress=20,
message="Pushing branch and creating PR...",
)
result = await service.create_pr(
spec_id=spec_id,
title=title,
body=body,
)
if result.get("success"):
pr_url = result.get("pr_url", "")
tracker.update(
op.id,
status=OperationStatus.COMPLETED,
progress=100,
message=f"PR created: {pr_url}" if pr_url else "PR created",
result=result,
)
else:
tracker.update(
op.id,
status=OperationStatus.FAILED,
error=result.get("error", "PR creation failed"),
result=result,
)
except Exception as e:
logger.exception("workspace_create_pr operation failed")
tracker.update(
op.id,
status=OperationStatus.FAILED,
error=str(e),
)
op._task = asyncio.create_task(_run())
return {
"operation_id": op.id,
"message": "PR creation started. Poll operation_get_status() for progress.",
}
-2
View File
@@ -14,7 +14,6 @@ from core.progress import (
get_plan_summary,
get_progress_percentage,
is_build_complete,
is_build_ready_for_qa,
print_build_complete_banner,
print_paused_banner,
print_progress_summary,
@@ -30,7 +29,6 @@ __all__ = [
"get_plan_summary",
"get_progress_percentage",
"is_build_complete",
"is_build_ready_for_qa",
"print_build_complete_banner",
"print_paused_banner",
"print_progress_summary",
+1 -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
+3 -3
View File
@@ -8,7 +8,7 @@ Manages acceptance criteria validation and status tracking.
import json
from pathlib import Path
from progress import is_build_ready_for_qa
from progress import is_build_complete
# =============================================================================
# IMPLEMENTATION PLAN I/O
@@ -95,10 +95,10 @@ def should_run_qa(spec_dir: Path) -> bool:
Determine if QA validation should run.
QA should run when:
- All subtasks have reached a terminal state (completed, failed, or stuck)
- All subtasks are completed
- QA has not yet approved
"""
if not is_build_ready_for_qa(spec_dir):
if not is_build_complete(spec_dir):
return False
if is_qa_approved(spec_dir):
+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(
+13 -20
View File
@@ -28,7 +28,7 @@ from phase_config import (
get_phase_model_betas,
)
from phase_event import ExecutionPhase, emit_phase
from progress import count_subtasks, is_build_ready_for_qa
from progress import count_subtasks, is_build_complete
from security.constants import PROJECT_DIR_ENV_VAR
from task_logger import (
LogPhase,
@@ -114,25 +114,14 @@ async def run_qa_validation_loop(
# Initialize task logger for the validation phase
task_logger = get_task_logger(spec_dir)
# Check if there's pending human feedback that needs to be processed
fix_request_file = spec_dir / "QA_FIX_REQUEST.md"
has_human_feedback = fix_request_file.exists()
# Human feedback takes priority — if the user explicitly asked to proceed,
# skip the build completeness gate entirely
if not has_human_feedback:
# Verify build is ready for QA (all subtasks in terminal state)
if not is_build_ready_for_qa(spec_dir):
debug_warning(
"qa_loop", "Build is not ready for QA - subtasks still in progress"
)
print("\n❌ Build is not ready for QA validation.")
completed, total = count_subtasks(spec_dir)
debug("qa_loop", "Build progress", completed=completed, total=total)
print(
f" Progress: {completed}/{total} subtasks in terminal state (completed/failed/stuck)"
)
return False
# Verify build is complete
if not is_build_complete(spec_dir):
debug_warning("qa_loop", "Build is not complete, cannot run QA")
print("\n❌ Build is not complete. Cannot run QA validation.")
completed, total = count_subtasks(spec_dir)
debug("qa_loop", "Build progress", completed=completed, total=total)
print(f" Progress: {completed}/{total} subtasks completed")
return False
# Emit phase event at start of QA validation (before any early returns)
emit_phase(ExecutionPhase.QA_REVIEW, "Starting QA validation")
@@ -147,6 +136,10 @@ async def run_qa_validation_loop(
f"[Fast Mode] {'ENABLED' if fast_mode else 'disabled'} for QA validation",
)
# Check if there's pending human feedback that needs to be processed
fix_request_file = spec_dir / "QA_FIX_REQUEST.md"
has_human_feedback = fix_request_file.exists()
# Check if already approved - but if there's human feedback, we need to process it first
if is_qa_approved(spec_dir) and not has_human_feedback:
debug_success("qa_loop", "Build already approved by QA")
+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
@@ -886,8 +886,7 @@ Analyze this follow-up review context and provide your structured response.
"""Attempt a short SDK call with minimal schema to recover review data.
This is the extraction recovery step when full structured output validation fails.
Uses FollowupExtractionResponse (small schema with ExtractedFindingSummary nesting)
which has near-100% success rate.
Uses FollowupExtractionResponse (~6 flat fields) which has near-100% success rate.
Uses create_client() + process_sdk_stream() for proper OAuth handling,
matching the pattern in parallel_followup_reviewer.py.
@@ -901,8 +900,7 @@ Analyze this follow-up review context and provide your structured response.
extraction_prompt = (
"Extract the key review data from the following AI analysis output. "
"Return the verdict, reasoning, resolved finding IDs, unresolved finding IDs, "
"structured summaries of any new findings (including severity, description, file path, and line number), "
"and counts of confirmed/dismissed findings.\n\n"
"one-line summaries of any new findings, and counts of confirmed/dismissed findings.\n\n"
f"--- AI ANALYSIS OUTPUT ---\n{text[:8000]}\n--- END ---"
)
@@ -948,16 +946,9 @@ Analyze this follow-up review context and provide your structured response.
# Convert extraction to internal format with reconstructed findings
new_findings = []
for i, summary_obj in enumerate(extracted.new_finding_summaries):
for i, summary in enumerate(extracted.new_finding_summaries):
new_findings.append(
create_finding_from_summary(
summary=summary_obj.description,
index=i,
id_prefix="FR",
severity_override=summary_obj.severity,
file=summary_obj.file,
line=summary_obj.line,
)
create_finding_from_summary(summary, i, id_prefix="FR")
)
# Build finding_resolutions from extraction data for _apply_ai_resolutions
@@ -1129,8 +1129,7 @@ The SDK will run invoked agents in parallel automatically.
"""Attempt a short SDK call with a minimal schema to recover review data.
This is the Tier 2 recovery step when full structured output validation fails.
Uses FollowupExtractionResponse (small schema with ExtractedFindingSummary nesting)
which has near-100% success rate.
Uses FollowupExtractionResponse (~6 flat fields) which has near-100% success rate.
Returns parsed result dict on success, None on failure.
"""
@@ -1147,8 +1146,7 @@ The SDK will run invoked agents in parallel automatically.
extraction_prompt = (
"Extract the key review data from the following AI analysis output. "
"Return the verdict, reasoning, resolved finding IDs, unresolved finding IDs, "
"structured summaries of any new findings (including severity, description, file path, and line number), "
"and counts of confirmed/dismissed findings.\n\n"
"one-line summaries of any new findings, and counts of confirmed/dismissed findings.\n\n"
f"--- AI ANALYSIS OUTPUT ---\n{text[:8000]}\n--- END ---"
)
@@ -1207,17 +1205,10 @@ The SDK will run invoked agents in parallel automatically.
findings = []
new_finding_ids = []
# 1. Convert new_finding_summaries to PRReviewFinding objects
# ExtractedFindingSummary objects carry file/line from extraction
for i, summary_obj in enumerate(extracted.new_finding_summaries):
finding = create_finding_from_summary(
summary=summary_obj.description,
index=i,
id_prefix="FU",
severity_override=summary_obj.severity,
file=summary_obj.file,
line=summary_obj.line,
)
# 1. Convert new_finding_summaries to minimal PRReviewFinding objects
# Uses shared helper for "SEVERITY: description" parsing and ID generation
for i, summary in enumerate(extracted.new_finding_summaries):
finding = create_finding_from_summary(summary, i, id_prefix="FU")
new_finding_ids.append(finding.id)
findings.append(finding)
@@ -1289,30 +1289,12 @@ The SDK will run invoked agents in parallel automatically.
f"{len(filtered_findings)} filtered"
)
# Separate active findings (drive verdict) from dismissed (shown in UI only)
active_findings = []
dismissed_findings = []
for f in validated_findings:
if f.validation_status == "dismissed_false_positive":
dismissed_findings.append(f)
else:
active_findings.append(f)
# No confidence routing - validation is binary via finding-validator
unique_findings = validated_findings
logger.info(f"[PRReview] Final findings: {len(unique_findings)} validated")
safe_print(
f"[ParallelOrchestrator] Final: {len(active_findings)} active, "
f"{len(dismissed_findings)} disputed by validator",
flush=True,
)
logger.info(
f"[PRReview] Final findings: {len(active_findings)} active, "
f"{len(dismissed_findings)} disputed"
)
# All findings (active + dismissed) go in the result for UI display
all_review_findings = validated_findings
logger.info(
f"[ParallelOrchestrator] Review complete: {len(all_review_findings)} findings "
f"({len(active_findings)} active, {len(dismissed_findings)} disputed)"
f"[ParallelOrchestrator] Review complete: {len(unique_findings)} findings"
)
# Fetch CI status for verdict consideration
@@ -1322,9 +1304,9 @@ The SDK will run invoked agents in parallel automatically.
f"{ci_status.get('failing', 0)} failing, {ci_status.get('pending', 0)} pending"
)
# Generate verdict from ACTIVE findings only (dismissed don't affect verdict)
# Generate verdict (includes merge conflict check, branch-behind check, and CI status)
verdict, verdict_reasoning, blockers = self._generate_verdict(
active_findings,
unique_findings,
has_merge_conflicts=context.has_merge_conflicts,
merge_state_status=context.merge_state_status,
ci_status=ci_status,
@@ -1335,7 +1317,7 @@ The SDK will run invoked agents in parallel automatically.
verdict=verdict,
verdict_reasoning=verdict_reasoning,
blockers=blockers,
findings=all_review_findings,
findings=unique_findings,
agents_invoked=agents_invoked,
)
@@ -1380,7 +1362,7 @@ The SDK will run invoked agents in parallel automatically.
pr_number=context.pr_number,
repo=self.config.repo,
success=True,
findings=all_review_findings,
findings=unique_findings,
summary=summary,
overall_status=overall_status,
verdict=verdict,
@@ -1955,38 +1937,12 @@ For EACH finding above:
validated_findings.append(finding)
elif validation.validation_status == "dismissed_false_positive":
# Protect cross-validated findings from dismissal —
# if multiple specialists independently found the same issue,
# a single validator should not override that consensus
if finding.cross_validated:
finding.validation_status = "confirmed_valid"
finding.validation_evidence = validation.code_evidence
finding.validation_explanation = (
f"[Auto-kept: cross-validated by {len(finding.source_agents)} agents] "
f"{validation.explanation}"
)
validated_findings.append(finding)
safe_print(
f"[FindingValidator] Kept cross-validated finding '{finding.title}' "
f"despite dismissal (agents={finding.source_agents})",
flush=True,
)
else:
# Keep finding but mark as dismissed (user can see it in UI)
finding.validation_status = "dismissed_false_positive"
finding.validation_evidence = validation.code_evidence
finding.validation_explanation = validation.explanation
validated_findings.append(finding)
dismissed_count += 1
safe_print(
f"[FindingValidator] Disputed '{finding.title}': "
f"{validation.explanation} (file={finding.file}:{finding.line})",
flush=True,
)
logger.info(
f"[PRReview] Disputed {finding.id}: "
f"{validation.explanation[:200]}"
)
# Dismiss - do not include
dismissed_count += 1
logger.info(
f"[PRReview] Dismissed {finding.id} as false positive: "
f"{validation.explanation[:100]}"
)
elif validation.validation_status == "needs_human_review":
# Keep but flag
@@ -2171,16 +2127,11 @@ For EACH finding above:
sev = f.severity.value
emoji = severity_emoji.get(sev, "")
is_disputed = f.validation_status == "dismissed_false_positive"
# Finding header with location
line_range = f"L{f.line}"
if f.end_line and f.end_line != f.line:
line_range = f"L{f.line}-L{f.end_line}"
if is_disputed:
lines.append(f"#### ⚪ [DISPUTED] ~~{f.title}~~")
else:
lines.append(f"#### {emoji} [{sev.upper()}] {f.title}")
lines.append(f"#### {emoji} [{sev.upper()}] {f.title}")
lines.append(f"**File:** `{f.file}` ({line_range})")
# Cross-validation badge
@@ -2210,7 +2161,6 @@ For EACH finding above:
status_label = {
"confirmed_valid": "Confirmed",
"needs_human_review": "Needs human review",
"dismissed_false_positive": "Disputed by validator",
}.get(f.validation_status, f.validation_status)
lines.append("")
lines.append(f"**Validation:** {status_label}")
@@ -2232,27 +2182,18 @@ For EACH finding above:
lines.append("")
# Findings count summary (exclude dismissed from active count)
active_count = 0
dismissed_count = 0
# Findings count summary
by_severity: dict[str, int] = {}
for f in findings:
if f.validation_status == "dismissed_false_positive":
dismissed_count += 1
continue
active_count += 1
sev = f.severity.value
by_severity[sev] = by_severity.get(sev, 0) + 1
summary_parts = []
for sev in ["critical", "high", "medium", "low"]:
if sev in by_severity:
summary_parts.append(f"{by_severity[sev]} {sev}")
count_text = (
f"**Total:** {active_count} finding(s) ({', '.join(summary_parts)})"
lines.append(
f"**Total:** {len(findings)} finding(s) ({', '.join(summary_parts)})"
)
if dismissed_count > 0:
count_text += f" + {dismissed_count} disputed"
lines.append(count_text)
lines.append("")
lines.append("---")
@@ -533,26 +533,10 @@ class FindingValidationResponse(BaseModel):
# =============================================================================
class ExtractedFindingSummary(BaseModel):
"""Per-finding summary with file location for extraction recovery."""
severity: str = Field(description="Severity level: LOW, MEDIUM, HIGH, or CRITICAL")
description: str = Field(description="One-line description of the finding")
file: str = Field(
default="unknown", description="File path where the issue was found"
)
line: int = Field(default=0, description="Line number in the file (0 if unknown)")
@field_validator("severity", mode="before")
@classmethod
def _normalize_severity(cls, v: str) -> str:
return _normalize_severity(v)
class FollowupExtractionResponse(BaseModel):
"""Minimal extraction schema for recovering data when full structured output fails.
Uses ExtractedFindingSummary for new findings to preserve file/line information.
Deliberately kept small (~6 fields, no nesting) for near-100% validation success.
Used as an intermediate recovery step before falling back to raw text parsing.
"""
@@ -568,9 +552,9 @@ class FollowupExtractionResponse(BaseModel):
default_factory=list,
description="IDs of previous findings that remain unresolved",
)
new_finding_summaries: list[ExtractedFindingSummary] = Field(
new_finding_summaries: list[str] = Field(
default_factory=list,
description="Structured summary of each new finding with file location",
description="One-line summary of each new finding (e.g. 'HIGH: cleanup deletes QA-rejected specs in batch_commands.py')",
)
confirmed_finding_count: int = Field(
0, description="Number of findings confirmed as valid"
@@ -80,9 +80,6 @@ def create_finding_from_summary(
summary: str,
index: int,
id_prefix: str = "FR",
severity_override: str | None = None,
file: str = "unknown",
line: int = 0,
) -> PRReviewFinding:
"""Create a PRReviewFinding from an extraction summary string.
@@ -93,20 +90,11 @@ def create_finding_from_summary(
summary: Raw summary string, e.g. "HIGH: Missing null check in parser.py"
index: The index of the finding in the extraction list.
id_prefix: ID prefix for traceability. Default "FR" (Followup Recovery).
severity_override: If provided, use this severity instead of parsing from summary.
file: File path where the issue was found (default "unknown").
line: Line number in the file (default 0).
Returns:
A PRReviewFinding with parsed severity, generated ID, and description.
"""
severity, description = parse_severity_from_summary(summary)
# Use severity_override if provided
if severity_override is not None:
severity_map = {k.rstrip(":"): v for k, v in _EXTRACTION_SEVERITY_MAP}
severity = severity_map.get(severity_override.upper(), severity)
finding_id = generate_recovery_finding_id(index, description, prefix=id_prefix)
return PRReviewFinding(
@@ -115,6 +103,6 @@ def create_finding_from_summary(
category=ReviewCategory.QUALITY,
title=description[:80],
description=f"[Recovered via extraction] {description}",
file=file,
line=line,
file="unknown",
line=0,
)
+7 -155
View File
@@ -8,10 +8,8 @@ about a codebase. It can also suggest tasks based on the conversation.
import argparse
import asyncio
import base64
import json
import sys
import tempfile
from pathlib import Path
# Add auto-claude to path
@@ -113,107 +111,6 @@ def load_project_context(project_dir: str) -> str:
)
ALLOWED_MIME_TYPES = frozenset(
["image/png", "image/jpeg", "image/jpg", "image/gif", "image/webp"]
)
MAX_IMAGE_FILE_SIZE = 10 * 1024 * 1024 # 10 MB (aligned with frontend MAX_IMAGE_SIZE)
def load_images_from_manifest(manifest_path: str) -> list[dict]:
"""Load images from a manifest JSON file.
The manifest contains an array of objects with 'path' and 'mimeType' fields.
Each image file is read as binary and encoded to base64.
Returns a list of dicts with 'media_type' and 'data' (base64-encoded) fields.
"""
images = []
tmp_dir = Path(tempfile.gettempdir()).resolve()
try:
with open(manifest_path, encoding="utf-8") as f:
manifest = json.load(f)
for entry in manifest:
image_path = entry.get("path")
mime_type = entry.get("mimeType", "image/png")
if not image_path:
debug_error(
"insights_runner",
"Image entry missing path field",
)
continue
# Validate path is within temp directory before checking existence
try:
resolved = Path(image_path).resolve()
if not resolved.is_relative_to(tmp_dir):
debug_error(
"insights_runner",
f"Image path outside temp directory, skipping: {image_path}",
)
continue
except (ValueError, OSError):
debug_error(
"insights_runner",
f"Invalid image path, skipping: {image_path}",
)
continue
if not resolved.exists():
debug_error(
"insights_runner",
f"Image file not found: {image_path}",
)
continue
# Validate MIME type against allowlist
if mime_type not in ALLOWED_MIME_TYPES:
debug_error(
"insights_runner",
f"Invalid MIME type '{mime_type}', skipping: {image_path}",
)
continue
# Validate file size
file_size = resolved.stat().st_size
if file_size > MAX_IMAGE_FILE_SIZE:
debug_error(
"insights_runner",
f"Image too large ({file_size} bytes), skipping: {image_path}",
)
continue
try:
with open(resolved, "rb") as img_f:
image_data = base64.b64encode(img_f.read()).decode("utf-8")
images.append(
{
"media_type": mime_type,
"data": image_data,
}
)
debug(
"insights_runner",
"Loaded image",
path=image_path,
mime_type=mime_type,
size_bytes=file_size,
)
except Exception as e:
debug_error(
"insights_runner",
f"Failed to read image {image_path}: {e}",
)
except (json.JSONDecodeError, OSError) as e:
debug_error("insights_runner", f"Failed to load images manifest: {e}")
return images
def build_system_prompt(project_dir: str) -> str:
"""Build the system prompt for the insights agent."""
context = load_project_context(project_dir)
@@ -246,12 +143,11 @@ async def run_with_sdk(
history: list,
model: str = "sonnet", # Shorthand - resolved via API Profile if configured
thinking_level: str = "medium",
images: list[dict] | None = None,
) -> None:
"""Run the chat using Claude SDK with streaming."""
if not SDK_AVAILABLE:
print("Claude SDK not available, falling back to simple mode", file=sys.stderr)
run_simple(project_dir, message, history, images)
run_simple(project_dir, message, history)
return
if not get_auth_token():
@@ -259,7 +155,7 @@ async def run_with_sdk(
"No authentication token found, falling back to simple mode",
file=sys.stderr,
)
run_simple(project_dir, message, history, images)
run_simple(project_dir, message, history)
return
# Ensure SDK can find the token
@@ -309,24 +205,8 @@ Current question: {message}"""
# Use async context manager pattern
async with client:
# Build the query - images are stored for reference but SDK doesn't support multi-modal input yet
if images:
debug(
"insights_runner",
"Images attached but SDK does not support multi-modal input",
image_count=len(images),
)
# TODO: When the SDK adds support for multi-modal content blocks, update this.
image_note = f"\n\n[Note: The user attached {len(images)} image(s), but the current SDK version does not support multi-modal input. Please ask the user to describe the image content instead.]"
print(
"Warning: Image attachments cannot be sent to the model in SDK mode. Sending text-only query.",
file=sys.stderr,
)
await client.query(full_prompt + image_note)
else:
# Send the query as plain text
await client.query(full_prompt)
# Send the query
await client.query(full_prompt)
# Stream the response
response_text = ""
@@ -400,21 +280,13 @@ Current question: {message}"""
import traceback
traceback.print_exc(file=sys.stderr)
run_simple(project_dir, message, history, images)
run_simple(project_dir, message, history)
def run_simple(
project_dir: str, message: str, history: list, images: list[dict] | None = None
) -> None:
def run_simple(project_dir: str, message: str, history: list) -> None:
"""Simple fallback mode without SDK - uses subprocess to call claude CLI."""
import subprocess
if images:
print(
"Warning: Image attachments are not supported in simple mode and will be skipped.",
file=sys.stderr,
)
system_prompt = build_system_prompt(project_dir)
# Build conversation context
@@ -483,10 +355,6 @@ def main():
default="medium",
help="Thinking level for extended reasoning (low, medium, high)",
)
parser.add_argument(
"--images-file",
help="Path to JSON manifest file listing image file paths and MIME types",
)
args = parser.parse_args()
# Validate and sanitize thinking level (handles legacy values like 'ultrathink')
@@ -530,25 +398,9 @@ def main():
debug_error("insights_runner", f"Failed to load history: {e}")
history = []
# Load images from manifest file if provided
images = None
if args.images_file:
debug("insights_runner", "Loading images from manifest", file=args.images_file)
images = load_images_from_manifest(args.images_file)
if images:
debug(
"insights_runner",
"Loaded images for multi-modal query",
image_count=len(images),
)
else:
debug("insights_runner", "No valid images loaded from manifest")
# Run the async SDK function
debug("insights_runner", "Running SDK query")
asyncio.run(
run_with_sdk(project_dir, user_message, history, model, thinking_level, images)
)
asyncio.run(run_with_sdk(project_dir, user_message, history, model, thinking_level))
debug_success("insights_runner", "Query completed")
@@ -31,7 +31,6 @@ class CompetitorAnalyzer:
self.refresh = refresh
self.agent_executor = agent_executor
self.analysis_file = output_dir / "competitor_analysis.json"
self.manual_competitors_file = output_dir / "manual_competitors.json"
self.discovery_file = output_dir / "roadmap_discovery.json"
self.project_index_file = output_dir / "project_index.json"
@@ -43,10 +42,7 @@ class CompetitorAnalyzer:
"""
if not enabled:
print_status("Competitor analysis not enabled, skipping", "info")
manual_competitors = self._get_manual_competitors()
self._create_disabled_analysis_file()
if manual_competitors:
self._merge_manual_competitors(manual_competitors)
return RoadmapPhaseResult(
"competitor_analysis", True, [str(self.analysis_file)], [], 0
)
@@ -57,9 +53,6 @@ class CompetitorAnalyzer:
"competitor_analysis", True, [str(self.analysis_file)], [], 0
)
# Preserve manual competitors before any path that overwrites the file
manual_competitors = self._get_manual_competitors()
if not self.discovery_file.exists():
print_status(
"Discovery file not found, skipping competitor analysis", "warning"
@@ -67,8 +60,6 @@ class CompetitorAnalyzer:
self._create_error_analysis_file(
"Discovery file not found - cannot analyze competitors without project context"
)
if manual_competitors:
self._merge_manual_competitors(manual_competitors)
return RoadmapPhaseResult(
"competitor_analysis",
True,
@@ -93,8 +84,6 @@ class CompetitorAnalyzer:
if success and self.analysis_file.exists():
validation_result = self._validate_analysis()
if validation_result is not None:
if manual_competitors:
self._merge_manual_competitors(manual_competitors)
return validation_result
errors.append(f"Attempt {attempt + 1}: Validation failed")
else:
@@ -111,82 +100,12 @@ class CompetitorAnalyzer:
print(f" {muted('Error:')} {err}")
self._create_error_analysis_file("Analysis failed after retries", errors)
if manual_competitors:
self._merge_manual_competitors(manual_competitors)
# Return success=True for graceful degradation (don't block roadmap generation)
return RoadmapPhaseResult(
"competitor_analysis", True, [str(self.analysis_file)], errors, MAX_RETRIES
)
def _get_manual_competitors(self) -> list[dict]:
"""Extract manually-added competitors from the dedicated manual file and analysis file.
Reads from manual_competitors.json (primary, never overwritten by agent) and
falls back to competitor_analysis.json. Deduplicates by competitor ID.
Returns a list of competitor dicts where source == 'manual'.
"""
competitors_by_id: dict[str, dict] = {}
# Primary source: dedicated manual competitors file (never overwritten by agent)
if self.manual_competitors_file.exists():
try:
with open(self.manual_competitors_file, encoding="utf-8") as f:
data = json.load(f)
for c in data.get("competitors", []):
if isinstance(c, dict) and c.get("id"):
competitors_by_id[c["id"]] = c
except (json.JSONDecodeError, OSError) as e:
print_status(
f"Warning: could not read manual competitors file: {e}", "warning"
)
# Fallback: also check analysis file for manual competitors
if self.analysis_file.exists():
try:
with open(self.analysis_file, encoding="utf-8") as f:
data = json.load(f)
for c in data.get("competitors", []):
if (
isinstance(c, dict)
and c.get("source") == "manual"
and c.get("id")
and c["id"] not in competitors_by_id
):
competitors_by_id[c["id"]] = c
except (json.JSONDecodeError, OSError) as e:
print_status(
f"Warning: could not read manual competitors from analysis: {e}",
"warning",
)
return list(competitors_by_id.values())
def _merge_manual_competitors(self, manual_competitors: list[dict]) -> None:
"""Merge manual competitors back into the newly-generated analysis file.
Appends manual competitors that don't already exist (by ID) in the file.
"""
if not manual_competitors:
return
try:
with open(self.analysis_file, encoding="utf-8") as f:
data = json.load(f)
except (json.JSONDecodeError, OSError) as e:
print_status(f"Warning: failed to merge manual competitors: {e}", "warning")
return
existing_ids = {
c.get("id") for c in data.get("competitors", []) if isinstance(c, dict)
}
for competitor in manual_competitors:
if competitor.get("id") not in existing_ids:
data.setdefault("competitors", []).append(competitor)
write_json_atomic(self.analysis_file, data, indent=2)
def _build_context(self) -> str:
"""Build context string for the competitor analysis agent."""
return f"""
@@ -221,11 +140,8 @@ Output your findings to competitor_analysis.json.
"competitor_analysis", True, [str(self.analysis_file)], [], 0
)
except json.JSONDecodeError as e:
print_status(
f"Warning: competitor analysis file is not valid JSON: {e}",
"warning",
)
except json.JSONDecodeError:
pass
return None
@@ -2,6 +2,11 @@
"project_root": "/Users/andremikalsen/Documents/Coding/autonomous-coding",
"project_type": "single",
"services": {},
"infrastructure": {},
"infrastructure": {
"docker_compose": "docker-compose.yml",
"docker_services": [
"falkordb"
]
},
"conventions": {}
}
+1 -1
View File
@@ -136,7 +136,7 @@ Examples:
python spec_runner.py --task "Update text" --complexity simple
# Complex integration (auto-detected)
python spec_runner.py --task "Add Graphiti memory integration with LadybugDB"
python spec_runner.py --task "Add Graphiti memory integration with FalkorDB"
# Interactive mode
python spec_runner.py --interactive
-32
View File
@@ -21,8 +21,6 @@ from datetime import datetime, timedelta, timezone
from enum import Enum
from pathlib import Path
from core.file_utils import write_json_atomic
# Recovery manager configuration
ATTEMPT_WINDOW_SECONDS = 7200 # Only count attempts within last 2 hours
MAX_ATTEMPT_HISTORY_PER_SUBTASK = 50 # Cap stored attempts per subtask
@@ -516,36 +514,6 @@ class RecoveryManager:
self._save_attempt_history(history)
# Also update the subtask status in implementation_plan.json
# so that other callers (like is_build_ready_for_qa) see accurate status
try:
plan_file = self.spec_dir / "implementation_plan.json"
if plan_file.exists():
with open(plan_file, encoding="utf-8") as f:
plan = json.load(f)
updated = False
for phase in plan.get("phases", []):
for subtask in phase.get("subtasks", []):
if subtask.get("id") == subtask_id:
subtask["status"] = "failed"
stuck_note = f"Marked as stuck: {reason}"
existing = subtask.get("actual_output", "")
subtask["actual_output"] = (
f"{stuck_note}\n{existing}" if existing else stuck_note
)
updated = True
break
if updated:
break
if updated:
write_json_atomic(plan_file, plan, indent=2)
except (OSError, json.JSONDecodeError, UnicodeDecodeError) as e:
logger.warning(
f"Failed to update implementation_plan.json for stuck subtask {subtask_id}: {e}"
)
def get_stuck_subtasks(self) -> list[dict]:
"""
Get all subtasks marked as stuck.
+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
+30 -7
View File
@@ -28,19 +28,34 @@ We encountered and fixed this bug during development as it was blocking our test
|-------|-------------|--------|
| Phase 1 | Create XState machine definition (task-machine.ts) | ✅ Complete |
| Phase 2 | Create TaskStateManager singleton wrapper | ✅ Complete |
| Phase 3 | Integrate into agent-events-handlers.ts | ✅ Complete |
| Phase 4 | Remove legacy TaskStateMachine class | ✅ Complete |
| Phase 3 | Integrate into agent-events-handlers.ts | ⏸️ Partially done |
| Phase 4 | Remove legacy TaskStateMachine class | ❌ Not started |
### Migration Complete
### Why We Stopped at Phase 2
All four phases are now complete. The XState-based `TaskStateManager` is the sole state management system — the legacy `TaskStateMachine` class and `validateStatusTransition()` function have been fully removed. `agent-events-handlers.ts` uses the XState-based `taskStateManager` singleton exclusively.
The original scope was to introduce XState as the new state management approach. Full integration (Phase 3-4) requires:
- Extensive refactoring of agent-events-handlers.ts to remove all legacy decision logic
- Removing the old TaskStateMachine class entirely
- Migration of all status persistence to go through XState
We delivered Phases 1-2 to establish the foundation. The current state has both systems running in parallel with XState as primary:
- **XState is primary:** When TaskStateManager returns a valid state transition, that decision is used
- **Legacy as fallback:** The old TaskStateMachine logic only applies when XState doesn't produce a decision
- **Safe rollback:** If XState causes issues, the legacy system is still present and can take over
This dual-system approach allows:
- Validation that XState produces correct state transitions in production
- Safe rollback if issues arise
- Incremental adoption path for Phase 3-4
## What Changed
### Before (Old Architecture — Now Removed)
### Before (Old Architecture)
- Status decisions scattered across agent-events-handlers.ts, execution-handlers.ts, worktree-handlers.ts
- `validateStatusTransition()` function with complex conditional logic
- `TaskStateMachine` class that was essentially an event emitter wrapper
- TaskStateMachine class that was essentially an event emitter wrapper
- Multiple places persisting status to implementation_plan.json
- Race conditions possible when multiple handlers tried to update status
@@ -103,6 +118,14 @@ The state machine responds to these events:
| CREATE_PR | User initiates PR creation |
| PR_CREATED | PR successfully created |
## Rollback Plan
If issues arise post-merge:
1. **Quick rollback:** `git revert <merge-commit>`
2. **Restore point:** Commit 3e5f004a has old code intact
3. **Legacy persistence still works:** implementation_plan.json continues to store status
## Testing
| Test Suite | Result |
@@ -140,7 +163,7 @@ The state machine responds to these events:
- Add @stately-ai/inspect for runtime devtools
- **Subtask state management** - Track individual subtask states within the machine using XState parallel states
- Add more granular QA states (qa_round_1, qa_round_2, etc.)
- Complete Phase 3-4: Full integration and removal of legacy TaskStateMachine class
## Visualization
+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);
});
});
});
@@ -1,333 +0,0 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { PRReviewStateManager } from '../pr-review-state-manager';
import type { PRReviewResult, PRReviewProgress } from '../../preload/api/modules/github-api';
// Mock dependencies
const mockSafeSendToRenderer = vi.fn();
vi.mock('../ipc-handlers/utils', () => ({
safeSendToRenderer: (...args: unknown[]) => mockSafeSendToRenderer(...args)
}));
function createMockGetMainWindow() {
return vi.fn(() => ({ id: 1 }) as unknown as Electron.BrowserWindow);
}
function createMockProgress(overrides: Partial<PRReviewProgress> = {}): PRReviewProgress {
return {
phase: 'analyzing',
progress: 50,
message: 'Analyzing files...',
...overrides
} as PRReviewProgress;
}
function createMockResult(overrides: Partial<PRReviewResult> = {}): PRReviewResult {
return {
overallStatus: 'approved',
summary: 'Looks good',
...overrides
} as PRReviewResult;
}
describe('PRReviewStateManager', () => {
let manager: PRReviewStateManager;
const projectId = 'project-1';
const prNumber = 42;
beforeEach(() => {
manager = new PRReviewStateManager(createMockGetMainWindow());
vi.clearAllMocks();
});
afterEach(() => {
manager.clearAll();
});
describe('actor lifecycle', () => {
it('should create actor on first handleStartReview call', () => {
manager.handleStartReview(projectId, prNumber);
const snapshot = manager.getState(projectId, prNumber);
expect(snapshot).not.toBeNull();
});
it('should reuse existing actor for same PR key', () => {
manager.handleStartReview(projectId, prNumber);
const snapshot1 = manager.getState(projectId, prNumber);
// Calling again should not create a new actor
manager.handleStartReview(projectId, prNumber);
const snapshot2 = manager.getState(projectId, prNumber);
expect(snapshot1).not.toBeNull();
expect(snapshot2).not.toBeNull();
});
it('should create separate actors for different PRs', () => {
manager.handleStartReview(projectId, 1);
manager.handleStartReview(projectId, 2);
const snapshot1 = manager.getState(projectId, 1);
const snapshot2 = manager.getState(projectId, 2);
expect(snapshot1).not.toBeNull();
expect(snapshot2).not.toBeNull();
});
it('should start actor before events are sent', () => {
manager.handleStartReview(projectId, prNumber);
const snapshot = manager.getState(projectId, prNumber);
// If actor wasn't started, getSnapshot would fail or return unexpected state
expect(snapshot).not.toBeNull();
expect(String(snapshot!.value)).toBe('reviewing');
});
});
describe('event routing', () => {
it('should transition to reviewing on handleStartReview', () => {
manager.handleStartReview(projectId, prNumber);
const snapshot = manager.getState(projectId, prNumber);
expect(String(snapshot!.value)).toBe('reviewing');
});
it('should send START_FOLLOWUP_REVIEW with previousResult', () => {
const previousResult = createMockResult();
manager.handleStartFollowupReview(projectId, prNumber, previousResult);
const snapshot = manager.getState(projectId, prNumber);
expect(String(snapshot!.value)).toBe('reviewing');
expect(snapshot!.context.isFollowup).toBe(true);
expect(snapshot!.context.previousResult).toBe(previousResult);
});
it('should send START_REVIEW when handleStartFollowupReview has no previousResult', () => {
manager.handleStartFollowupReview(projectId, prNumber);
const snapshot = manager.getState(projectId, prNumber);
expect(String(snapshot!.value)).toBe('reviewing');
expect(snapshot!.context.isFollowup).toBe(false);
});
it('should update context on handleProgress', () => {
manager.handleStartReview(projectId, prNumber);
const progress = createMockProgress();
manager.handleProgress(projectId, prNumber, progress);
const snapshot = manager.getState(projectId, prNumber);
expect(snapshot!.context.progress).toEqual(progress);
});
it('should ignore handleProgress for unknown PR', () => {
// Should not throw
manager.handleProgress(projectId, 999, createMockProgress());
expect(manager.getState(projectId, 999)).toBeNull();
});
it('should transition to completed on handleComplete', () => {
manager.handleStartReview(projectId, prNumber);
const result = createMockResult();
manager.handleComplete(projectId, prNumber, result);
const snapshot = manager.getState(projectId, prNumber);
expect(String(snapshot!.value)).toBe('completed');
expect(snapshot!.context.result).toEqual(result);
});
it('should create actor for handleComplete on unknown PR (late-arriving result)', () => {
const result = createMockResult();
// No handleStartReview called — handleComplete should create the actor
manager.handleComplete(projectId, prNumber, result);
const snapshot = manager.getState(projectId, prNumber);
expect(snapshot).not.toBeNull();
expect(snapshot!.context.result).toEqual(result);
});
it('should send DETECT_EXTERNAL_REVIEW when overallStatus is in_progress', () => {
manager.handleStartReview(projectId, prNumber);
const result = createMockResult({ overallStatus: 'in_progress' });
manager.handleComplete(projectId, prNumber, result);
const snapshot = manager.getState(projectId, prNumber);
expect(String(snapshot!.value)).toBe('externalReview');
});
it('should transition to error on handleError', () => {
manager.handleStartReview(projectId, prNumber);
manager.handleError(projectId, prNumber, 'Something went wrong');
const snapshot = manager.getState(projectId, prNumber);
expect(String(snapshot!.value)).toBe('error');
expect(snapshot!.context.error).toBe('Something went wrong');
});
it('should transition to error on handleCancel', () => {
manager.handleStartReview(projectId, prNumber);
manager.handleCancel(projectId, prNumber);
const snapshot = manager.getState(projectId, prNumber);
expect(String(snapshot!.value)).toBe('error');
});
});
describe('state emission', () => {
it('should emit state changes to renderer via safeSendToRenderer', () => {
manager.handleStartReview(projectId, prNumber);
expect(mockSafeSendToRenderer).toHaveBeenCalled();
});
it('should use GITHUB_PR_REVIEW_STATE_CHANGE IPC channel', () => {
manager.handleStartReview(projectId, prNumber);
expect(mockSafeSendToRenderer).toHaveBeenCalledWith(
expect.any(Function),
'github:pr:reviewStateChange',
expect.any(String),
expect.objectContaining({ state: expect.any(String) })
);
});
it('should emit PRReviewStatePayload with correct shape', () => {
manager.handleStartReview(projectId, prNumber);
// Find the call that emits 'reviewing' state
const reviewingCall = mockSafeSendToRenderer.mock.calls.find(
(call: unknown[]) => {
const payload = call[3] as Record<string, unknown> | undefined;
return payload && typeof payload === 'object' && payload.state === 'reviewing';
}
);
expect(reviewingCall).toBeDefined();
expect(reviewingCall![2]).toBe(`${projectId}:${prNumber}`);
const payload = reviewingCall![3] as Record<string, unknown>;
expect(payload).toEqual(expect.objectContaining({
state: 'reviewing',
prNumber,
projectId,
isReviewing: true,
startedAt: expect.any(String),
progress: null,
result: null,
previousResult: null,
error: null,
isExternalReview: false,
isFollowup: false,
}));
});
it('should use projectId:prNumber as key format', () => {
manager.handleStartReview(projectId, prNumber);
const calls = mockSafeSendToRenderer.mock.calls;
const prCall = calls.find((call: unknown[]) => call[2] === `${projectId}:${prNumber}`);
expect(prCall).toBeDefined();
});
});
describe('deduplication', () => {
it('should NOT emit duplicate IPC for same state + same context', () => {
manager.handleStartReview(projectId, prNumber);
const callCountAfterStart = mockSafeSendToRenderer.mock.calls.length;
// Sending START_REVIEW again won't transition (guard prevents it), so no new emission
manager.handleStartReview(projectId, prNumber);
expect(mockSafeSendToRenderer.mock.calls.length).toBe(callCountAfterStart);
});
it('should emit for same state but different context (progress update)', () => {
manager.handleStartReview(projectId, prNumber);
const callCountAfterStart = mockSafeSendToRenderer.mock.calls.length;
manager.handleProgress(projectId, prNumber, createMockProgress({ progress: 25, message: 'Step 1' }));
expect(mockSafeSendToRenderer.mock.calls.length).toBeGreaterThan(callCountAfterStart);
const callCountAfterProgress1 = mockSafeSendToRenderer.mock.calls.length;
manager.handleProgress(projectId, prNumber, createMockProgress({ progress: 75, message: 'Step 2' }));
expect(mockSafeSendToRenderer.mock.calls.length).toBeGreaterThan(callCountAfterProgress1);
});
it('should always emit for different state transitions', () => {
manager.handleStartReview(projectId, prNumber);
const callCountAfterStart = mockSafeSendToRenderer.mock.calls.length;
manager.handleComplete(projectId, prNumber, createMockResult());
expect(mockSafeSendToRenderer.mock.calls.length).toBeGreaterThan(callCountAfterStart);
});
});
describe('cleanup', () => {
it('should stop actor and remove from map on handleClearReview', () => {
manager.handleStartReview(projectId, prNumber);
expect(manager.getState(projectId, prNumber)).not.toBeNull();
manager.handleClearReview(projectId, prNumber);
expect(manager.getState(projectId, prNumber)).toBeNull();
});
it('should emit exactly one cleared state IPC on handleClearReview (no double emission)', () => {
manager.handleStartReview(projectId, prNumber);
mockSafeSendToRenderer.mockClear();
manager.handleClearReview(projectId, prNumber);
// Should emit exactly 1 cleared state, not 2 (no double emission from
// sending CLEAR_REVIEW to actor subscription + manual emitClearedState)
expect(mockSafeSendToRenderer).toHaveBeenCalledTimes(1);
const payload = mockSafeSendToRenderer.mock.calls[0][3] as Record<string, unknown>;
expect(payload).toEqual(expect.objectContaining({ state: 'idle' }));
});
it('should stop ALL actors and clear maps on handleAuthChange', () => {
manager.handleStartReview(projectId, 1);
manager.handleStartReview(projectId, 2);
manager.handleAuthChange();
expect(manager.getState(projectId, 1)).toBeNull();
expect(manager.getState(projectId, 2)).toBeNull();
});
it('should emit cleared state to renderer on handleAuthChange', () => {
manager.handleStartReview(projectId, 1);
manager.handleStartReview(projectId, 2);
mockSafeSendToRenderer.mockClear();
manager.handleAuthChange();
// Should emit idle/null state for each PR
expect(mockSafeSendToRenderer).toHaveBeenCalledTimes(2);
for (const call of mockSafeSendToRenderer.mock.calls) {
const payload = call[3] as Record<string, unknown>;
expect(payload).toEqual(expect.objectContaining({ state: 'idle' }));
}
});
it('should stop all actors on clearAll', () => {
manager.handleStartReview(projectId, 1);
manager.handleStartReview(projectId, 2);
manager.clearAll();
expect(manager.getState(projectId, 1)).toBeNull();
expect(manager.getState(projectId, 2)).toBeNull();
});
});
describe('concurrent PRs', () => {
it('should support multiple PRs with independent actors', () => {
manager.handleStartReview(projectId, 1);
manager.handleStartReview(projectId, 2);
manager.handleComplete(projectId, 1, createMockResult());
expect(String(manager.getState(projectId, 1)!.value)).toBe('completed');
expect(String(manager.getState(projectId, 2)!.value)).toBe('reviewing');
});
it('should route events to correct actor by key', () => {
manager.handleStartReview(projectId, 1);
manager.handleStartReview(projectId, 2);
manager.handleError(projectId, 2, 'Error on PR 2');
expect(String(manager.getState(projectId, 1)!.value)).toBe('reviewing');
expect(String(manager.getState(projectId, 2)!.value)).toBe('error');
expect(manager.getState(projectId, 2)!.context.error).toBe('Error on PR 2');
});
it('should not affect other PRs when clearing one', () => {
manager.handleStartReview(projectId, 1);
manager.handleStartReview(projectId, 2);
manager.handleClearReview(projectId, 1);
expect(manager.getState(projectId, 1)).toBeNull();
expect(manager.getState(projectId, 2)).not.toBeNull();
expect(String(manager.getState(projectId, 2)!.value)).toBe('reviewing');
});
});
});
@@ -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
*
+2 -44
View File
@@ -38,18 +38,6 @@ log.transports.file.fileName = 'main.log';
// Console transport - always show warnings and errors, debug only in dev mode
log.transports.console.level = process.env.NODE_ENV === 'development' ? 'debug' : 'warn';
log.transports.console.format = '[{h}:{i}:{s}] [{level}] {text}';
// Guard console transport writes so broken stdio streams do not crash the app.
{
const originalConsoleWriteFn = log.transports.console.writeFn as (...args: unknown[]) => void;
log.transports.console.writeFn = (...args: unknown[]) => {
try {
originalConsoleWriteFn(...args);
} catch (error) {
const err = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
safeStderrWrite(`[app-logger] console transport write failed: ${err}`);
}
};
}
// Determine if this is a beta version
function isBetaVersion(): boolean {
@@ -216,44 +204,14 @@ export const appLog = {
log: (...args: unknown[]) => log.info(...args),
};
/**
* Best-effort stderr fallback used when electron-log itself throws (e.g. EIO).
* Must never throw, especially inside uncaught exception handlers.
*/
function safeStderrWrite(message: string): void {
try {
process.stderr.write(`${message}\n`);
} catch {
// Ignore - nothing else we can safely do here.
}
}
/**
* Log an unhandled error without risking recursive crashes if logger transport fails.
*/
function safeLogUnhandled(prefix: string, value: unknown): void {
try {
log.error(prefix, value);
} catch (loggingError) {
const loggingFailure = loggingError instanceof Error
? `${loggingError.name}: ${loggingError.message}`
: String(loggingError);
const original = value instanceof Error
? (value.stack || `${value.name}: ${value.message}`)
: String(value);
safeStderrWrite(`[app-logger] ${prefix} (logger failed: ${loggingFailure})`);
safeStderrWrite(original);
}
}
// Log unhandled errors
export function setupErrorLogging(): void {
process.on('uncaughtException', (error) => {
safeLogUnhandled('Uncaught exception:', error);
log.error('Uncaught exception:', error);
});
process.on('unhandledRejection', (reason) => {
safeLogUnhandled('Unhandled rejection:', reason);
log.error('Unhandled rejection:', reason);
});
log.info('Error logging initialized');
+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');
@@ -6,8 +6,7 @@
* and can be copied between profiles to enable session continuity after profile switches.
*/
import { existsSync } from 'fs';
import { mkdir, copyFile, cp, unlink } from 'fs/promises';
import { existsSync, mkdirSync, copyFileSync, cpSync, unlinkSync } from 'fs';
import { join, dirname } from 'path';
import { homedir } from 'os';
import { isNodeError } from '../utils/type-guards';
@@ -96,12 +95,12 @@ export interface SessionMigrationResult {
* @param sessionId - The session UUID to migrate
* @returns Migration result with success status and details
*/
export async function migrateSession(
export function migrateSession(
sourceConfigDir: string,
targetConfigDir: string,
cwd: string,
sessionId: string
): Promise<SessionMigrationResult> {
): SessionMigrationResult {
const result: SessionMigrationResult = {
success: false,
sessionId,
@@ -119,14 +118,13 @@ export async function migrateSession(
try {
// Ensure target directory exists (do this first, before any file operations)
const targetParentDir = dirname(targetFile);
await mkdir(targetParentDir, { recursive: true });
mkdirSync(targetParentDir, { recursive: true });
console.warn('[SessionUtils] Ensured target directory exists:', targetParentDir);
// Attempt to copy the session .jsonl file
// This will throw if source doesn't exist or target cannot be written
// Note: copyFile silently overwrites by default (no COPYFILE_EXCL flag)
try {
await copyFile(sourceFile, targetFile);
copyFileSync(sourceFile, targetFile);
result.filesCopied++;
console.warn('[SessionUtils] Copied session file:', sourceFile, '->', targetFile);
} catch (copyError) {
@@ -134,6 +132,12 @@ export async function migrateSession(
if (isNodeError(copyError)) {
if (copyError.code === 'ENOENT') {
result.error = `Source session file not found: ${sourceFile}`;
} else if (copyError.code === 'EEXIST') {
// Target already exists - this is OK, treat as successful skip
console.warn('[SessionUtils] Session already exists in target profile, skipping copy');
result.success = true;
result.filesCopied = 0;
return result;
} else {
result.error = `Failed to copy session file: ${copyError.message}`;
}
@@ -149,7 +153,7 @@ export async function migrateSession(
// Attempt to copy the session directory (tool-results) if it exists
// Use try-catch instead of existsSync to avoid TOCTOU race
try {
await cp(sourceDir, targetDir, { recursive: true });
cpSync(sourceDir, targetDir, { recursive: true });
result.filesCopied++;
console.warn('[SessionUtils] Copied session directory:', sourceDir, '->', targetDir);
} catch (dirCopyError) {
@@ -178,7 +182,7 @@ export async function migrateSession(
// Clean up partially migrated session file to enable retry
// Use try-catch instead of existsSync to avoid TOCTOU race
try {
await unlink(targetFile);
unlinkSync(targetFile);
console.warn('[SessionUtils] Cleaned up partial migration file:', targetFile);
} catch (cleanupError) {
// If file doesn't exist during cleanup, that's fine
+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
*/
+1 -11
View File
@@ -49,7 +49,7 @@ import { initializeAppUpdater, stopPeriodicUpdates } from './app-updater';
import { DEFAULT_APP_SETTINGS, IPC_CHANNELS, SPELL_CHECK_LANGUAGE_MAP, DEFAULT_SPELL_CHECK_LANGUAGE, ADD_TO_DICTIONARY_LABELS } from '../shared/constants';
import { getAppLanguage, initAppLanguage } from './app-language';
import { readSettingsFile } from './settings-utils';
import { appLog, setupErrorLogging } from './app-logger';
import { setupErrorLogging } from './app-logger';
import { initSentryMain } from './sentry';
import { preWarmToolCache } from './cli-tool-manager';
import { initializeClaudeProfileManager, getClaudeProfileManager } from './claude-profile-manager';
@@ -143,11 +143,6 @@ let mainWindow: BrowserWindow | null = null;
let agentManager: AgentManager | null = null;
let terminalManager: TerminalManager | null = null;
// Capture child process exits (renderer/GPU/utility) for crash diagnostics.
app.on('child-process-gone', (_event, details) => {
appLog.error('[main] child-process-gone:', details);
});
// Re-entrancy guard for before-quit handler.
// The first before-quit call pauses quit for async cleanup, then calls app.quit() again.
// The second call sees isQuitting=true and allows quit to proceed immediately.
@@ -219,11 +214,6 @@ function createWindow(): void {
mainWindow?.show();
});
// Capture renderer process crashes/termination reasons for diagnostics.
mainWindow.webContents.on('render-process-gone', (_event, details) => {
appLog.error('[main] render-process-gone:', details);
});
// Configure initial spell check languages with proper fallback logic
// Uses shared constant for consistency with the IPC handler
const defaultLanguage = 'en';
+11 -65
View File
@@ -3,10 +3,8 @@ import type {
InsightsSession,
InsightsSessionSummary,
InsightsChatMessage,
InsightsModelConfig,
ImageAttachment
InsightsModelConfig
} from '../shared/types';
import { MAX_IMAGES_PER_TASK } from '../shared/constants';
import { InsightsConfig } from './insights/config';
import { InsightsPaths } from './insights/paths';
import { SessionStorage } from './insights/session-storage';
@@ -72,8 +70,8 @@ export class InsightsService extends EventEmitter {
/**
* List all sessions for a project
*/
listSessions(projectPath: string, includeArchived = false): InsightsSessionSummary[] {
return this.sessionManager.listSessions(projectPath, includeArchived);
listSessions(projectPath: string): InsightsSessionSummary[] {
return this.sessionManager.listSessions(projectPath);
}
/**
@@ -97,34 +95,6 @@ export class InsightsService extends EventEmitter {
return this.sessionManager.deleteSession(projectId, projectPath, sessionId);
}
/**
* Archive a session
*/
archiveSession(projectId: string, projectPath: string, sessionId: string): boolean {
return this.sessionManager.archiveSession(projectId, projectPath, sessionId);
}
/**
* Unarchive a session
*/
unarchiveSession(projectPath: string, sessionId: string): boolean {
return this.sessionManager.unarchiveSession(projectPath, sessionId);
}
/**
* Delete multiple sessions
*/
deleteSessions(projectId: string, projectPath: string, sessionIds: string[]): { deletedIds: string[]; failedIds: string[] } {
return this.sessionManager.deleteSessions(projectId, projectPath, sessionIds);
}
/**
* Archive multiple sessions
*/
archiveSessions(projectId: string, projectPath: string, sessionIds: string[]): { archivedIds: string[]; failedIds: string[] } {
return this.sessionManager.archiveSessions(projectId, projectPath, sessionIds);
}
/**
* Rename a session
*/
@@ -146,8 +116,7 @@ export class InsightsService extends EventEmitter {
projectId: string,
projectPath: string,
message: string,
modelConfig?: InsightsModelConfig,
images?: ImageAttachment[]
modelConfig?: InsightsModelConfig
): Promise<void> {
// Cancel any existing session
this.executor.cancelSession(projectId);
@@ -170,44 +139,22 @@ export class InsightsService extends EventEmitter {
session.title = this.storage.generateTitle(message);
}
// Guard: cap images to MAX_IMAGES_PER_TASK
if (images && images.length > MAX_IMAGES_PER_TASK) {
images = images.slice(0, MAX_IMAGES_PER_TASK);
}
// Add user message (store thumbnails only for persistence, strip full data)
const persistImages = images?.map(img => ({
...img,
data: undefined
}));
// Add user message
const userMessage: InsightsChatMessage = {
id: `msg-${Date.now()}`,
role: 'user',
content: message,
timestamp: new Date(),
images: persistImages && persistImages.length > 0 ? persistImages : undefined
timestamp: new Date()
};
session.messages.push(userMessage);
session.updatedAt = new Date();
this.sessionManager.saveSession(projectPath, session);
// Build conversation history for context
// Add notation when images are present so the AI has context
// For historical messages (all but the last), use past tense to avoid confusion
const conversationHistory = session.messages.map((m, index) => {
const imageCount = m.images?.length ?? 0;
const isLastMessage = index === session.messages.length - 1;
let imageNotation = '';
if (imageCount > 0 && m.role === 'user') {
imageNotation = isLastMessage
? `\n[User attached ${imageCount} image(s)]`
: `\n[User previously attached ${imageCount} image(s) - not visible in this context]`;
}
return {
role: m.role,
content: imageNotation ? m.content + imageNotation : m.content
};
});
const conversationHistory = session.messages.map(m => ({
role: m.role,
content: m.content
}));
// Use provided modelConfig or fall back to session's config
const configToUse = modelConfig || session.modelConfig;
@@ -219,8 +166,7 @@ export class InsightsService extends EventEmitter {
projectPath,
message,
conversationHistory,
configToUse,
images
configToUse
);
// Add assistant message to session
@@ -1,7 +1,5 @@
import { spawn, ChildProcess } from 'child_process';
import { existsSync, unlinkSync } from 'fs';
import { writeFile } from 'fs/promises';
import { randomBytes } from 'crypto';
import { existsSync, writeFileSync, unlinkSync } from 'fs';
import path from 'path';
import os from 'os';
import { EventEmitter } from 'events';
@@ -10,23 +8,12 @@ import type {
InsightsChatStatus,
InsightsStreamChunk,
InsightsToolUsage,
InsightsModelConfig,
ImageAttachment
InsightsModelConfig
} from '../../shared/types';
import { MODEL_ID_MAP, MAX_IMAGES_PER_TASK, MAX_IMAGE_SIZE } from '../../shared/constants';
import { MODEL_ID_MAP } from '../../shared/constants';
import { InsightsConfig } from './config';
import { detectRateLimit, createSDKRateLimitInfo } from '../rate-limit-detector';
// Safe extension map for image MIME types — prevents path traversal via crafted mimeType
// SVG excluded: contains active script content and is unsupported by Claude Vision API
const SAFE_EXT_MAP: Record<string, string> = {
'image/png': 'png',
'image/jpeg': 'jpg',
'image/jpg': 'jpg',
'image/gif': 'gif',
'image/webp': 'webp'
};
/**
* Message processor result
*/
@@ -76,8 +63,7 @@ export class InsightsExecutor extends EventEmitter {
projectPath: string,
message: string,
conversationHistory: Array<{ role: string; content: string }>,
modelConfig?: InsightsModelConfig,
images?: ImageAttachment[]
modelConfig?: InsightsModelConfig
): Promise<ProcessorResult> {
// Cancel any existing session
this.cancelSession(projectId);
@@ -104,80 +90,18 @@ export class InsightsExecutor extends EventEmitter {
// Write conversation history to temp file to avoid Windows command-line length limit
const historyFile = path.join(
os.tmpdir(),
`insights-history-${projectId}-${Date.now()}-${randomBytes(8).toString('hex')}.json`
`insights-history-${projectId}-${Date.now()}.json`
);
let historyFileCreated = false;
try {
await writeFile(historyFile, JSON.stringify(conversationHistory), { encoding: 'utf-8', mode: 0o600 });
writeFileSync(historyFile, JSON.stringify(conversationHistory), 'utf-8');
historyFileCreated = true;
} catch (err) {
console.error('[Insights] Failed to write history file:', err);
throw new Error('Failed to write conversation history to temp file');
}
// Write image files and manifest if images are provided
const imagesTempFiles: string[] = [];
let imagesManifestFile: string | undefined;
// Defense-in-depth: cap image count and filter oversized images in the executor
if (images && images.length > MAX_IMAGES_PER_TASK) {
images = images.slice(0, MAX_IMAGES_PER_TASK);
}
if (images) {
images = images.filter(img => !img.data || Buffer.byteLength(img.data, 'base64') <= MAX_IMAGE_SIZE);
}
if (images && images.length > 0) {
try {
const manifest: Array<{ path: string; mimeType: string }> = [];
const timestamp = Date.now();
for (let i = 0; i < images.length; i++) {
const image = images[i];
if (!image.data) continue;
// Validate mimeType against allowlist (defense-in-depth for main process)
const ext = SAFE_EXT_MAP[image.mimeType];
if (!ext) {
console.warn(`[Insights] Skipping image with invalid mimeType: ${image.mimeType}`);
continue;
}
const imagePath = path.join(
os.tmpdir(),
`insights-image-${projectId}-${timestamp}-${i}-${randomBytes(8).toString('hex')}.${ext}`
);
await writeFile(imagePath, Buffer.from(image.data, 'base64'), { mode: 0o600 });
imagesTempFiles.push(imagePath);
manifest.push({ path: imagePath, mimeType: image.mimeType });
}
// Only write manifest file if we actually wrote any images
if (manifest.length > 0) {
imagesManifestFile = path.join(
os.tmpdir(),
`insights-images-manifest-${projectId}-${timestamp}-${randomBytes(8).toString('hex')}.json`
);
imagesTempFiles.push(imagesManifestFile); // Push before writeFile for cleanup on failure
await writeFile(imagesManifestFile, JSON.stringify(manifest), { encoding: 'utf-8', mode: 0o600 });
}
} catch (err) {
// Clean up any already-written image files
for (const tmpFile of imagesTempFiles) {
try {
if (existsSync(tmpFile)) unlinkSync(tmpFile);
} catch { /* ignore cleanup errors */ }
}
// Also clean up the history file (cleanupTempFiles isn't defined yet at this point)
if (existsSync(historyFile)) {
try { unlinkSync(historyFile); } catch { /* ignore */ }
}
console.error('[Insights] Failed to write image files:', err);
throw new Error('Failed to write image files to temp directory');
}
}
// Build command arguments
const args = [
runnerPath,
@@ -186,11 +110,6 @@ export class InsightsExecutor extends EventEmitter {
'--history-file', historyFile
];
// Add images manifest file if images were provided
if (imagesManifestFile) {
args.push('--images-file', imagesManifestFile);
}
// Add model config if provided
if (modelConfig) {
const modelId = MODEL_ID_MAP[modelConfig.model] || MODEL_ID_MAP['sonnet'];
@@ -206,27 +125,6 @@ export class InsightsExecutor extends EventEmitter {
this.activeSessions.set(projectId, proc);
// Shared cleanup for temp files used across close/error handlers
let cleanedUp = false;
const cleanupTempFiles = () => {
if (cleanedUp) return;
cleanedUp = true;
if (historyFileCreated && existsSync(historyFile)) {
try {
unlinkSync(historyFile);
} catch (cleanupErr) {
console.error('[Insights] Failed to cleanup history file:', cleanupErr);
}
}
for (const tmpFile of imagesTempFiles) {
try {
if (existsSync(tmpFile)) unlinkSync(tmpFile);
} catch (cleanupErr) {
console.error('[Insights] Failed to cleanup image temp file:', cleanupErr);
}
}
};
return new Promise((resolve, reject) => {
let fullResponse = '';
const suggestedTasks: InsightsChatMessage['suggestedTasks'] = [];
@@ -272,7 +170,15 @@ export class InsightsExecutor extends EventEmitter {
proc.on('close', (code) => {
this.activeSessions.delete(projectId);
cleanupTempFiles();
// Cleanup temp file
if (historyFileCreated && existsSync(historyFile)) {
try {
unlinkSync(historyFile);
} catch (cleanupErr) {
console.error('[Insights] Failed to cleanup history file:', cleanupErr);
}
}
// Check for rate limit if process failed
if (code !== 0) {
@@ -311,7 +217,15 @@ export class InsightsExecutor extends EventEmitter {
proc.on('error', (err) => {
this.activeSessions.delete(projectId);
cleanupTempFiles();
// Cleanup temp file
if (historyFileCreated && existsSync(historyFile)) {
try {
unlinkSync(historyFile);
} catch (cleanupErr) {
console.error('[Insights] Failed to cleanup history file:', cleanupErr);
}
}
this.emit('error', projectId, err.message);
reject(err);
-11
View File
@@ -23,21 +23,10 @@ export class InsightsPaths {
return path.join(this.getInsightsDir(projectPath), SESSIONS_DIR);
}
/**
* Validate that a session ID matches the expected safe pattern.
* Prevents path traversal attacks via crafted session IDs.
*/
private validateSessionId(sessionId: string): void {
if (!/^session-\d{1,20}$/.test(sessionId)) {
throw new Error('Invalid session ID format');
}
}
/**
* Get session file path for a specific session
*/
getSessionPath(projectPath: string, sessionId: string): string {
this.validateSessionId(sessionId);
return path.join(this.getSessionsDir(projectPath), `${sessionId}.json`);
}
@@ -20,9 +20,8 @@ export class SessionManager {
*/
loadSession(projectId: string, projectPath: string): InsightsSession | null {
// Check in-memory cache first
const cachedSession = this.sessions.get(projectId);
if (cachedSession) {
return cachedSession;
if (this.sessions.has(projectId)) {
return this.sessions.get(projectId)!;
}
// Migrate old format if needed
@@ -41,10 +40,10 @@ export class SessionManager {
/**
* List all sessions for a project
*/
listSessions(projectPath: string, includeArchived = false): InsightsSessionSummary[] {
listSessions(projectPath: string): InsightsSessionSummary[] {
// Migrate old format if needed
this.storage.migrateOldSession(projectPath);
return this.storage.listSessions(projectPath, includeArchived);
return this.storage.listSessions(projectPath);
}
/**
@@ -106,80 +105,6 @@ export class SessionManager {
return true;
}
/**
* Archive a session
*/
archiveSession(projectId: string, projectPath: string, sessionId: string): boolean {
const success = this.storage.archiveSession(projectPath, sessionId);
if (!success) return false;
// If this was the current session, auto-switch
const currentSession = this.sessions.get(projectId);
if (currentSession?.id === sessionId) {
this.sessions.delete(projectId);
const remaining = this.listSessions(projectPath);
if (remaining.length > 0) {
this.switchSession(projectId, projectPath, remaining[0].id);
} else {
this.storage.clearCurrentSessionId(projectPath);
}
}
return true;
}
/**
* Unarchive a session
*/
unarchiveSession(projectPath: string, sessionId: string): boolean {
return this.storage.unarchiveSession(projectPath, sessionId);
}
/**
* Delete multiple sessions
*/
deleteSessions(projectId: string, projectPath: string, sessionIds: string[]): { deletedIds: string[]; failedIds: string[] } {
const result = this.storage.deleteSessions(projectPath, sessionIds);
// Check if current cached session was among deleted
const currentSession = this.sessions.get(projectId);
if (currentSession && result.deletedIds.includes(currentSession.id)) {
this.sessions.delete(projectId);
const remaining = this.listSessions(projectPath);
if (remaining.length > 0) {
this.switchSession(projectId, projectPath, remaining[0].id);
} else {
this.storage.clearCurrentSessionId(projectPath);
}
}
return result;
}
/**
* Archive multiple sessions
*/
archiveSessions(projectId: string, projectPath: string, sessionIds: string[]): { archivedIds: string[]; failedIds: string[] } {
const result = this.storage.archiveSessions(projectPath, sessionIds);
// Check if current cached session was among archived
const currentSession = this.sessions.get(projectId);
if (currentSession && result.archivedIds.includes(currentSession.id)) {
this.sessions.delete(projectId);
const remaining = this.listSessions(projectPath);
if (remaining.length > 0) {
this.switchSession(projectId, projectPath, remaining[0].id);
} else {
this.storage.clearCurrentSessionId(projectPath);
}
}
return result;
}
/**
* Rename a session
*/
@@ -190,17 +115,6 @@ export class SessionManager {
session.title = newTitle;
session.updatedAt = new Date();
this.storage.saveSession(projectPath, session);
// Update cache if this session is cached
for (const [projectId, cachedSession] of this.sessions) {
if (cachedSession.id === sessionId) {
cachedSession.title = newTitle;
cachedSession.updatedAt = session.updatedAt;
this.sessions.set(projectId, cachedSession);
break;
}
}
return true;
}
@@ -219,7 +133,7 @@ export class SessionManager {
for (const [projectId, cachedSession] of this.sessions) {
if (cachedSession.id === sessionId) {
cachedSession.modelConfig = modelConfig;
cachedSession.updatedAt = session.updatedAt;
cachedSession.updatedAt = new Date();
this.sessions.set(projectId, cachedSession);
break;
}
@@ -1,6 +1,6 @@
import { existsSync, readFileSync, writeFileSync, mkdirSync, readdirSync, unlinkSync } from 'fs';
import path from 'path';
import type { InsightsSession, InsightsSessionSummary, ImageAttachment } from '../../shared/types';
import type { InsightsSession, InsightsSessionSummary } from '../../shared/types';
import { InsightsPaths } from './paths';
/**
@@ -27,18 +27,15 @@ export class SessionStorage {
* Load a specific session from disk
*/
loadSessionById(projectPath: string, sessionId: string): InsightsSession | null {
try {
const sessionPath = this.paths.getSessionPath(projectPath, sessionId);
if (!existsSync(sessionPath)) return null;
const sessionPath = this.paths.getSessionPath(projectPath, sessionId);
if (!existsSync(sessionPath)) return null;
try {
const content = readFileSync(sessionPath, 'utf-8');
const session = JSON.parse(content) as InsightsSession;
// Convert date strings back to Date objects
session.createdAt = new Date(session.createdAt);
session.updatedAt = new Date(session.updatedAt);
if (session.archivedAt) {
session.archivedAt = new Date(session.archivedAt);
}
session.messages = session.messages.map(m => ({
...m,
timestamp: new Date(m.timestamp),
@@ -58,98 +55,23 @@ export class SessionStorage {
* Save session to disk
*/
saveSession(projectPath: string, session: InsightsSession): void {
try {
const sessionsDir = this.paths.getSessionsDir(projectPath);
if (!existsSync(sessionsDir)) {
mkdirSync(sessionsDir, { recursive: true });
}
const sessionPath = this.paths.getSessionPath(projectPath, session.id);
writeFileSync(sessionPath, JSON.stringify(session, null, 2), 'utf-8');
} catch (error) {
console.error(`[SessionStorage] Failed to save session ${session.id}:`, error);
throw error;
}
}
/**
* Archive a session
*/
archiveSession(projectPath: string, sessionId: string): boolean {
const session = this.loadSessionById(projectPath, sessionId);
if (!session) return false;
try {
session.archivedAt = new Date();
this.saveSession(projectPath, session);
return true;
} catch (error) {
console.error(`[SessionStorage] Failed to archive session ${sessionId}:`, error);
return false;
}
}
/**
* Unarchive a session
*/
unarchiveSession(projectPath: string, sessionId: string): boolean {
const session = this.loadSessionById(projectPath, sessionId);
if (!session) return false;
try {
delete session.archivedAt;
this.saveSession(projectPath, session);
return true;
} catch (error) {
console.error(`[SessionStorage] Failed to unarchive session ${sessionId}:`, error);
return false;
}
}
/**
* Delete multiple sessions
*/
deleteSessions(projectPath: string, sessionIds: string[]): { deletedIds: string[]; failedIds: string[] } {
const deletedIds: string[] = [];
const failedIds: string[] = [];
for (const sessionId of sessionIds) {
if (this.deleteSession(projectPath, sessionId)) {
deletedIds.push(sessionId);
} else {
failedIds.push(sessionId);
}
const sessionsDir = this.paths.getSessionsDir(projectPath);
if (!existsSync(sessionsDir)) {
mkdirSync(sessionsDir, { recursive: true });
}
return { deletedIds, failedIds };
}
/**
* Archive multiple sessions
*/
archiveSessions(projectPath: string, sessionIds: string[]): { archivedIds: string[]; failedIds: string[] } {
const archivedIds: string[] = [];
const failedIds: string[] = [];
for (const sessionId of sessionIds) {
if (this.archiveSession(projectPath, sessionId)) {
archivedIds.push(sessionId);
} else {
failedIds.push(sessionId);
}
}
return { archivedIds, failedIds };
const sessionPath = this.paths.getSessionPath(projectPath, session.id);
writeFileSync(sessionPath, JSON.stringify(session, null, 2), 'utf-8');
}
/**
* Delete a session from disk
*/
deleteSession(projectPath: string, sessionId: string): boolean {
try {
const sessionPath = this.paths.getSessionPath(projectPath, sessionId);
if (!existsSync(sessionPath)) return false;
const sessionPath = this.paths.getSessionPath(projectPath, sessionId);
if (!existsSync(sessionPath)) return false;
try {
unlinkSync(sessionPath);
return true;
} catch {
@@ -160,7 +82,7 @@ export class SessionStorage {
/**
* List all sessions for a project
*/
listSessions(projectPath: string, includeArchived = false): InsightsSessionSummary[] {
listSessions(projectPath: string): InsightsSessionSummary[] {
const sessionsDir = this.paths.getSessionsDir(projectPath);
if (!existsSync(sessionsDir)) return [];
@@ -182,20 +104,13 @@ export class SessionStorage {
: 'Untitled Conversation';
}
// Skip archived sessions unless explicitly included
if (!includeArchived && session.archivedAt) {
continue;
}
sessions.push({
id: session.id,
projectId: session.projectId,
title: title || 'New Conversation',
messageCount: session.messages.length,
modelConfig: session.modelConfig,
createdAt: new Date(session.createdAt),
updatedAt: new Date(session.updatedAt),
...(session.archivedAt ? { archivedAt: new Date(session.archivedAt) } : {})
updatedAt: new Date(session.updatedAt)
});
} catch {
// Skip invalid session files
@@ -250,23 +165,6 @@ export class SessionStorage {
}
}
/**
* Strip full-resolution image data from a session for persistence.
* Keeps only thumbnail, id, filename, mimeType, and size to prevent bloated JSON files.
*/
private stripImageDataForPersistence(session: InsightsSession): InsightsSession {
return {
...session,
messages: session.messages.map(m => {
if (!m.images || m.images.length === 0) return m;
return {
...m,
images: m.images.map(({ data, path: _path, ...rest }: ImageAttachment) => rest)
};
})
};
}
/**
* Migrate old session format to new multi-session format
*/
@@ -7,25 +7,19 @@ import type {
AuthFailureInfo,
ImplementationPlan,
} from "../../shared/types";
import { XSTATE_SETTLED_STATES, XSTATE_ACTIVE_STATES, XSTATE_TO_PHASE, mapStateToLegacy } from "../../shared/state-machines";
import { XSTATE_SETTLED_STATES, XSTATE_TO_PHASE, mapStateToLegacy } from "../../shared/state-machines";
import { AgentManager } from "../agent";
import type { ProcessType, ExecutionProgressData } from "../agent";
import { titleGenerator } from "../title-generator";
import { fileWatcher } from "../file-watcher";
import { notificationService } from "../notification-service";
import { persistPlanLastEventSync, getPlanPath, persistPlanPhaseSync, persistPlanStatusAndReasonSync, hasPlanWithSubtasks } from "./task/plan-file-utils";
import { persistPlanLastEventSync, getPlanPath, persistPlanPhaseSync, persistPlanStatusAndReasonSync } from "./task/plan-file-utils";
import { findTaskWorktree } from "../worktree-paths";
import { findTaskAndProject } from "./task/shared";
import { safeSendToRenderer } from "./utils";
import { getClaudeProfileManager } from "../claude-profile-manager";
import { taskStateManager } from "../task-state-manager";
// Timeout for fallback safety net to check if task is still stuck after process exit
const STUCK_TASK_FALLBACK_TIMEOUT_MS = 500;
// Map to store active fallback timers so they can be cancelled on task restart
const fallbackTimers = new Map<string, NodeJS.Timeout>();
/**
* Register all agent-events-related IPC handlers
*/
@@ -102,53 +96,9 @@ export function registerAgenteventsHandlers(
taskStateManager.handleProcessExited(taskId, code, exitTask, exitProject);
// Fallback safety net: If XState failed to transition the task out of an active state,
// force it to human_review after a short delay. This prevents tasks from getting stuck
// when the process exits without XState properly handling it.
// We check XState's current state directly to avoid stale cache issues from projectStore.
// Store timer reference so it can be cancelled if task restarts within the window.
const timer = setTimeout(() => {
const currentState = taskStateManager.getCurrentState(taskId);
if (currentState && XSTATE_ACTIVE_STATES.has(currentState)) {
const { task: checkTask, project: checkProject } = findTaskAndProject(taskId, projectId);
if (checkTask && checkProject) {
// Use shared utility to determine if a valid implementation plan exists
const hasPlan = hasPlanWithSubtasks(checkProject, checkTask);
console.warn(
`[agent-events-handlers] Task ${taskId} still in XState ${currentState} ` +
`${STUCK_TASK_FALLBACK_TIMEOUT_MS}ms after exit, forcing USER_STOPPED (hasPlan: ${hasPlan})`
);
taskStateManager.handleUiEvent(taskId, { type: 'USER_STOPPED', hasPlan }, checkTask, checkProject);
}
}
// Clean up timer reference after it fires
fallbackTimers.delete(taskId);
}, STUCK_TASK_FALLBACK_TIMEOUT_MS);
// Store timer reference for potential cancellation
fallbackTimers.set(taskId, timer);
// 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,
@@ -159,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}`);
@@ -263,46 +211,25 @@ 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}'`);
}
// Skip sending execution-progress to renderer when XState has settled,
// UNLESS this is a final phase update (complete/failed) AND the task is still in_progress.
// This prevents UI flicker where a failed phase arrives after the status has already changed to human_review.
const isFinalPhaseUpdate = progress.phase === 'complete' || progress.phase === 'failed';
// Skip sending execution-progress to renderer when XState has settled.
// XState's emitPhaseFromState already sent the correct phase to the renderer.
if (xstateInTerminalState) {
if (!isFinalPhaseUpdate) {
console.debug(`[agent-events-handlers] Skipping execution-progress to renderer for ${taskId}: XState in '${currentXState}', ignoring phase '${progress.phase}'`);
return;
}
// For final phase updates, only send if task is still in_progress to prevent flicker
const { task } = findTaskAndProject(taskId, taskProjectId);
if (task && task.status !== 'in_progress') {
console.debug(`[agent-events-handlers] Skipping final phase '${progress.phase}' for ${taskId}: task status is '${task.status}', not 'in_progress'`);
return;
}
console.debug(`[agent-events-handlers] Skipping execution-progress to renderer for ${taskId}: XState in '${currentXState}', ignoring phase '${progress.phase}'`);
return;
}
safeSendToRenderer(
getMainWindow,
@@ -358,17 +285,3 @@ export function registerAgenteventsHandlers(
safeSendToRenderer(getMainWindow, IPC_CHANNELS.TASK_ERROR, taskId, error, project?.id);
});
}
/**
* Cancel any pending fallback timer for a task.
* Should be called when a task is restarted to prevent the stale timer
* from incorrectly stopping the new process.
*/
export function cancelFallbackTimer(taskId: string): void {
const timer = fallbackTimers.get(taskId);
if (timer) {
clearTimeout(timer);
fallbackTimers.delete(taskId);
console.debug(`[agent-events-handlers] Cancelled fallback timer for task ${taskId}`);
}
}
@@ -51,10 +51,6 @@ function sendAuthChangedToRenderer(oldUsername: string | null, newUsername: stri
for (const win of windows) {
win.webContents.send(IPC_CHANNELS.GITHUB_AUTH_CHANGED, payload);
}
// Uses EventEmitter.emit (not IPC send) so main-process listeners can react.
// The listener (PRReviewStateManager) intentionally ignores all args — it only
// needs the event signal, not the payload.
ipcMain.emit(IPC_CHANNELS.GITHUB_AUTH_CHANGED, payload);
}
/**
@@ -26,7 +26,7 @@ import { getMemoryService, getDefaultDbPath } from "../../memory-service";
import type { Project, AppSettings } from "../../../shared/types";
import { createContextLogger } from "./utils/logger";
import { withProjectOrNull } from "./utils/project-middleware";
import { PRReviewStateManager } from "../../pr-review-state-manager";
import { createIPCCommunicators } from "./utils/ipc-communicator";
import { getRunnerEnv } from "./utils/runner-env";
import {
runPythonSubprocess,
@@ -268,10 +268,6 @@ export interface PRReviewFinding {
endLine?: number;
suggestedFix?: string;
fixable: boolean;
validationStatus?: "confirmed_valid" | "dismissed_false_positive" | "needs_human_review" | null;
validationExplanation?: string;
sourceAgents?: string[];
crossValidated?: boolean;
}
/**
@@ -1345,10 +1341,6 @@ function getReviewResult(project: Project, prNumber: number): PRReviewResult | n
endLine: f.end_line,
suggestedFix: f.suggested_fix,
fixable: f.fixable ?? false,
validationStatus: f.validation_status ?? null,
validationExplanation: f.validation_explanation ?? undefined,
sourceAgents: f.source_agents ?? [],
crossValidated: f.cross_validated ?? false,
})) ?? [],
summary: data.summary ?? "",
overallStatus: data.overall_status ?? "comment",
@@ -1384,7 +1376,7 @@ function sendReviewStateUpdate(
project: Project,
prNumber: number,
projectId: string,
prReviewStateManager: PRReviewStateManager,
getMainWindow: () => BrowserWindow | null,
context: string
): void {
try {
@@ -1393,8 +1385,18 @@ function sendReviewStateUpdate(
debugLog("Could not retrieve updated review result for UI notification", { prNumber, context });
return;
}
// Route through state manager so the XState actor emits the state change
prReviewStateManager.handleComplete(projectId, prNumber, updatedResult);
const mainWindow = getMainWindow();
if (!mainWindow) return;
const { sendComplete } = createIPCCommunicators<PRReviewProgress, PRReviewResult>(
mainWindow,
{
progress: IPC_CHANNELS.GITHUB_PR_REVIEW_PROGRESS,
error: IPC_CHANNELS.GITHUB_PR_REVIEW_ERROR,
complete: IPC_CHANNELS.GITHUB_PR_REVIEW_COMPLETE,
},
projectId
);
sendComplete(updatedResult);
debugLog(`Sent PR review state update ${context}`, { prNumber });
} catch (uiError) {
debugLog("Failed to send UI update (non-critical)", {
@@ -1435,8 +1437,7 @@ function getGitHubPRSettings(): { model: string; thinkingLevel: string } {
async function runPRReview(
project: Project,
prNumber: number,
mainWindow: BrowserWindow,
prReviewStateManager: PRReviewStateManager
mainWindow: BrowserWindow
): Promise<PRReviewResult> {
// Comprehensive validation of GitHub module
const validation = await validateGitHubModule(project);
@@ -1447,9 +1448,15 @@ async function runPRReview(
const backendPath = validation.backendPath!;
const sendProgress = (progress: PRReviewProgress): void => {
prReviewStateManager.handleProgress(project.id, prNumber, progress);
};
const { sendProgress } = createIPCCommunicators<PRReviewProgress, PRReviewResult>(
mainWindow,
{
progress: IPC_CHANNELS.GITHUB_PR_REVIEW_PROGRESS,
error: IPC_CHANNELS.GITHUB_PR_REVIEW_ERROR,
complete: IPC_CHANNELS.GITHUB_PR_REVIEW_COMPLETE,
},
project.id
);
const { model, thinkingLevel } = getGitHubPRSettings();
const args = buildRunnerArgs(
@@ -1484,19 +1491,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);
@@ -1680,32 +1674,6 @@ async function fetchPRsFromGraphQL(
export function registerPRHandlers(getMainWindow: () => BrowserWindow | null): void {
debugLog("Registering PR handlers");
// Create the XState-based PR review state manager
const prReviewStateManager = new PRReviewStateManager(getMainWindow);
// Clear all PR review actors when GitHub auth changes (account swap)
ipcMain.on(IPC_CHANNELS.GITHUB_AUTH_CHANGED, () => {
// Cancel all running review subprocesses and CI wait controllers
for (const [reviewKey, entry] of runningReviews) {
if (entry === CI_WAIT_PLACEHOLDER) {
const abortController = ciWaitAbortControllers.get(reviewKey);
if (abortController) {
abortController.abort();
ciWaitAbortControllers.delete(reviewKey);
}
} else {
try {
entry.kill("SIGTERM");
} catch {
// Process may have already exited
}
}
}
runningReviews.clear();
ciWaitAbortControllers.clear();
prReviewStateManager.handleAuthChange();
});
// List open PRs - fetches up to 100 open PRs at once, returns hasNextPage and endCursor from API
ipcMain.handle(
IPC_CHANNELS.GITHUB_PR_LIST,
@@ -1913,27 +1881,31 @@ export function registerPRHandlers(getMainWindow: () => BrowserWindow | null): v
try {
await withProjectOrNull(projectId, async (project) => {
const sendProgress = (progress: PRReviewProgress): void => {
prReviewStateManager.handleProgress(projectId, prNumber, progress);
};
const { sendProgress, sendComplete } = createIPCCommunicators<
PRReviewProgress,
PRReviewResult
>(
mainWindow,
{
progress: IPC_CHANNELS.GITHUB_PR_REVIEW_PROGRESS,
error: IPC_CHANNELS.GITHUB_PR_REVIEW_ERROR,
complete: IPC_CHANNELS.GITHUB_PR_REVIEW_COMPLETE,
},
projectId
);
// Check if already running — notify renderer so it can display ongoing logs
if (runningReviews.has(reviewKey)) {
debugLog("Review already running, notifying renderer", { reviewKey });
const currentSnapshot = prReviewStateManager.getState(projectId, prNumber);
const currentProgress = currentSnapshot?.context?.progress?.progress ?? 50;
sendProgress({
phase: "analyzing",
prNumber,
progress: currentProgress,
progress: 50,
message: "Review is already in progress. Reconnecting to ongoing review...",
});
return;
}
// Notify state manager that review is starting (after duplicate check)
prReviewStateManager.handleStartReview(projectId, prNumber);
// Register as running BEFORE CI wait to prevent race conditions
// Use CI_WAIT_PLACEHOLDER sentinel until real process is spawned
runningReviews.set(reviewKey, CI_WAIT_PLACEHOLDER);
@@ -1998,18 +1970,31 @@ export function registerPRHandlers(getMainWindow: () => BrowserWindow | null): v
message: "Fetching PR data...",
});
const result = await runPRReview(project, prNumber, mainWindow, prReviewStateManager);
const result = await runPRReview(project, prNumber, mainWindow);
if (result.overallStatus === "in_progress") {
// Review is already running externally (detected by BotDetector).
// Send the result as-is so the renderer can activate external review polling.
debugLog("PR review already in progress externally", { prNumber });
sendProgress({
phase: "complete",
prNumber,
progress: 100,
message: "Review already in progress",
});
sendComplete(result);
return;
}
debugLog("PR review completed", { prNumber, findingsCount: result.findings.length });
sendProgress({
phase: "complete",
prNumber,
progress: 100,
message: result.overallStatus === "in_progress" ? "Review already in progress" : "Review complete!",
message: "Review complete!",
});
// Route through manager — handles external review detection internally
prReviewStateManager.handleComplete(projectId, prNumber, result);
sendComplete(result);
} finally {
// Clean up in case we exit before runPRReview was called (e.g., cancelled during CI wait)
// runPRReview also has its own cleanup, but delete is idempotent
@@ -2026,7 +2011,16 @@ export function registerPRHandlers(getMainWindow: () => BrowserWindow | null): v
prNumber,
error: error instanceof Error ? error.message : error,
});
prReviewStateManager.handleError(projectId, prNumber, error instanceof Error ? error.message : "Failed to run PR review");
const { sendError } = createIPCCommunicators<PRReviewProgress, PRReviewResult>(
mainWindow,
{
progress: IPC_CHANNELS.GITHUB_PR_REVIEW_PROGRESS,
error: IPC_CHANNELS.GITHUB_PR_REVIEW_ERROR,
complete: IPC_CHANNELS.GITHUB_PR_REVIEW_COMPLETE,
},
projectId
);
sendError(error instanceof Error ? error.message : "Failed to run PR review");
}
});
@@ -2231,7 +2225,7 @@ export function registerPRHandlers(getMainWindow: () => BrowserWindow | null): v
}
// Send state update event to refresh UI immediately (non-blocking)
sendReviewStateUpdate(project, prNumber, projectId, prReviewStateManager, "after posting");
sendReviewStateUpdate(project, prNumber, projectId, getMainWindow, "after posting");
return true;
} catch (error) {
@@ -2270,7 +2264,7 @@ export function registerPRHandlers(getMainWindow: () => BrowserWindow | null): v
debugLog("Marked review as posted", { prNumber });
// Send state update event to refresh UI immediately (non-blocking)
sendReviewStateUpdate(project, prNumber, projectId, prReviewStateManager, "after marking posted");
sendReviewStateUpdate(project, prNumber, projectId, getMainWindow, "after marking posted");
return true;
} catch (error) {
@@ -2388,7 +2382,7 @@ export function registerPRHandlers(getMainWindow: () => BrowserWindow | null): v
}
// Send state update event to refresh UI immediately (non-blocking)
sendReviewStateUpdate(project, prNumber, projectId, prReviewStateManager, "after deletion");
sendReviewStateUpdate(project, prNumber, projectId, getMainWindow, "after deletion");
return true;
} catch (error) {
@@ -2500,8 +2494,6 @@ export function registerPRHandlers(getMainWindow: () => BrowserWindow | null): v
ciWaitAbortControllers.delete(reviewKey);
}
runningReviews.delete(reviewKey);
// Notify state manager of cancellation
prReviewStateManager.handleCancel(projectId, prNumber);
debugLog("CI wait cancelled", { reviewKey });
return true;
}
@@ -2522,8 +2514,6 @@ export function registerPRHandlers(getMainWindow: () => BrowserWindow | null): v
// Clean up the registry
runningReviews.delete(reviewKey);
// Notify state manager of cancellation
prReviewStateManager.handleCancel(projectId, prNumber);
debugLog("Review process cancelled", { reviewKey });
return true;
} catch (error) {
@@ -2536,21 +2526,6 @@ export function registerPRHandlers(getMainWindow: () => BrowserWindow | null): v
}
);
// Notify main process about external review completion or timeout
// Called by renderer when its polling detects an external review has finished on disk
ipcMain.handle(
IPC_CHANNELS.GITHUB_PR_NOTIFY_EXTERNAL_REVIEW_COMPLETE,
async (_, projectId: string, prNumber: number, result: PRReviewResult | null): Promise<void> => {
debugLog("notifyExternalReviewComplete handler called", { projectId, prNumber, hasResult: !!result });
if (result) {
prReviewStateManager.handleComplete(projectId, prNumber, result);
} else {
// Timeout — no result found within polling window
prReviewStateManager.handleError(projectId, prNumber, "External review timed out after 30 minutes");
}
}
);
// Check for new commits since last review
ipcMain.handle(
IPC_CHANNELS.GITHUB_PR_CHECK_NEW_COMMITS,
@@ -2936,40 +2911,34 @@ export function registerPRHandlers(getMainWindow: () => BrowserWindow | null): v
try {
await withProjectOrNull(projectId, async (project) => {
const sendProgress = (progress: PRReviewProgress): void => {
prReviewStateManager.handleProgress(projectId, prNumber, progress);
};
const reviewKey = getReviewKey(projectId, prNumber);
// Check if already running — notify renderer so it can display ongoing logs
if (runningReviews.has(reviewKey)) {
debugLog("Follow-up review already running, notifying renderer", { reviewKey });
const currentSnapshot = prReviewStateManager.getState(projectId, prNumber);
const currentProgress = currentSnapshot?.context?.progress?.progress ?? 50;
sendProgress({
phase: "analyzing",
prNumber,
progress: currentProgress,
message: "Follow-up review is already in progress. Reconnecting to ongoing review...",
});
return;
}
// Get previous result for followup context
const previousResult = getReviewResult(project, prNumber) ?? undefined;
// Notify state manager that followup review is starting (after duplicate check)
prReviewStateManager.handleStartFollowupReview(projectId, prNumber, previousResult);
const { sendProgress, sendError, sendComplete } = createIPCCommunicators<
PRReviewProgress,
PRReviewResult
>(
mainWindow,
{
progress: IPC_CHANNELS.GITHUB_PR_REVIEW_PROGRESS,
error: IPC_CHANNELS.GITHUB_PR_REVIEW_ERROR,
complete: IPC_CHANNELS.GITHUB_PR_REVIEW_COMPLETE,
},
projectId
);
// Comprehensive validation of GitHub module
const validation = await validateGitHubModule(project);
if (!validation.valid) {
prReviewStateManager.handleError(projectId, prNumber, validation.error || "GitHub module validation failed");
sendError({ prNumber, error: validation.error || "GitHub module validation failed" });
return;
}
const backendPath = validation.backendPath!;
const reviewKey = getReviewKey(projectId, prNumber);
// Check if already running
if (runningReviews.has(reviewKey)) {
debugLog("Follow-up review already running", { reviewKey });
return;
}
// Register as running BEFORE CI wait to prevent race conditions
// Use CI_WAIT_PLACEHOLDER sentinel until real process is spawned
@@ -3038,19 +3007,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,
@@ -3139,8 +3095,7 @@ export function registerPRHandlers(getMainWindow: () => BrowserWindow | null): v
message: "Follow-up review complete!",
});
// Route through state manager
prReviewStateManager.handleComplete(projectId, prNumber, result.data!);
sendComplete(result.data!);
} finally {
// Always clean up registry, whether we exit normally or via error
runningReviews.delete(reviewKey);
@@ -3153,7 +3108,19 @@ export function registerPRHandlers(getMainWindow: () => BrowserWindow | null): v
prNumber,
error: error instanceof Error ? error.message : error,
});
prReviewStateManager.handleError(projectId, prNumber, error instanceof Error ? error.message : "Failed to run follow-up review");
const { sendError } = createIPCCommunicators<PRReviewProgress, PRReviewResult>(
mainWindow,
{
progress: IPC_CHANNELS.GITHUB_PR_REVIEW_PROGRESS,
error: IPC_CHANNELS.GITHUB_PR_REVIEW_ERROR,
complete: IPC_CHANNELS.GITHUB_PR_REVIEW_COMPLETE,
},
projectId
);
sendError({
prNumber,
error: error instanceof Error ? error.message : "Failed to run follow-up review",
});
}
}
);
@@ -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
@@ -16,7 +16,6 @@ import type {
InsightsSession,
InsightsSessionSummary,
InsightsModelConfig,
ImageAttachment,
Task,
TaskMetadata,
AppSettings,
@@ -82,7 +81,7 @@ export function registerInsightsHandlers(getMainWindow: () => BrowserWindow | nu
ipcMain.on(
IPC_CHANNELS.INSIGHTS_SEND_MESSAGE,
async (_, projectId: string, message: string, modelConfig?: InsightsModelConfig, images?: ImageAttachment[]) => {
async (_, projectId: string, message: string, modelConfig?: InsightsModelConfig) => {
const project = projectStore.getProject(projectId);
if (!project) {
safeSendToRenderer(
@@ -113,7 +112,7 @@ export function registerInsightsHandlers(getMainWindow: () => BrowserWindow | nu
// the handler returns. This fixes race conditions on Windows where
// environment setup wouldn't complete before process spawn.
try {
await insightsService.sendMessage(projectId, project.path, message, configWithSettings, images);
await insightsService.sendMessage(projectId, project.path, message, configWithSettings);
} catch (error) {
// Errors during sendMessage (executor errors) are already emitted via
// the 'error' event, but we catch here to prevent unhandled rejection
@@ -250,95 +249,17 @@ export function registerInsightsHandlers(getMainWindow: () => BrowserWindow | nu
// List all sessions for a project
ipcMain.handle(
IPC_CHANNELS.INSIGHTS_LIST_SESSIONS,
async (_, projectId: string, includeArchived?: boolean): Promise<IPCResult<InsightsSessionSummary[]>> => {
async (_, projectId: string): Promise<IPCResult<InsightsSessionSummary[]>> => {
const project = projectStore.getProject(projectId);
if (!project) {
return { success: false, error: "Project not found" };
}
const sessions = insightsService.listSessions(project.path, includeArchived ?? false);
const sessions = insightsService.listSessions(project.path);
return { success: true, data: sessions };
}
);
// Delete multiple sessions
ipcMain.handle(
IPC_CHANNELS.INSIGHTS_DELETE_SESSIONS,
async (_, projectId: string, sessionIds: string[]): Promise<IPCResult<{ deletedIds: string[]; failedIds: string[] }>> => {
if (!Array.isArray(sessionIds) || sessionIds.length === 0) {
return { success: false, error: "No sessions specified" };
}
const project = projectStore.getProject(projectId);
if (!project) {
return { success: false, error: "Project not found" };
}
const result = insightsService.deleteSessions(projectId, project.path, sessionIds);
return {
success: result.failedIds.length === 0,
data: result,
...(result.failedIds.length > 0 && { error: `Failed to delete ${result.failedIds.length} session(s)` })
};
}
);
// Archive a session
ipcMain.handle(
IPC_CHANNELS.INSIGHTS_ARCHIVE_SESSION,
async (_, projectId: string, sessionId: string): Promise<IPCResult> => {
const project = projectStore.getProject(projectId);
if (!project) {
return { success: false, error: "Project not found" };
}
const success = insightsService.archiveSession(projectId, project.path, sessionId);
if (success) {
return { success: true };
}
return { success: false, error: "Failed to archive session" };
}
);
// Archive multiple sessions
ipcMain.handle(
IPC_CHANNELS.INSIGHTS_ARCHIVE_SESSIONS,
async (_, projectId: string, sessionIds: string[]): Promise<IPCResult<{ archivedIds: string[]; failedIds: string[] }>> => {
if (!Array.isArray(sessionIds) || sessionIds.length === 0) {
return { success: false, error: "No sessions specified" };
}
const project = projectStore.getProject(projectId);
if (!project) {
return { success: false, error: "Project not found" };
}
const result = insightsService.archiveSessions(projectId, project.path, sessionIds);
return {
success: result.failedIds.length === 0,
data: result,
...(result.failedIds.length > 0 && { error: `Failed to archive ${result.failedIds.length} session(s)` })
};
}
);
// Unarchive a session
ipcMain.handle(
IPC_CHANNELS.INSIGHTS_UNARCHIVE_SESSION,
async (_, projectId: string, sessionId: string): Promise<IPCResult> => {
const project = projectStore.getProject(projectId);
if (!project) {
return { success: false, error: "Project not found" };
}
const success = insightsService.unarchiveSession(project.path, sessionId);
if (success) {
return { success: true };
}
return { success: false, error: "Failed to unarchive session" };
}
);
// Create a new session
ipcMain.handle(
IPC_CHANNELS.INSIGHTS_NEW_SESSION,
@@ -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];

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