Compare commits

...

158 Commits

Author SHA1 Message Date
AndyMik90 a20b8cf12a Enhance task status handling to allow 'done' status in limbo state. Added worktree existence check to enforce merge workflow unless no worktree is found, enabling direct status updates in specific scenarios. 2025-12-18 16:24:40 +01:00
AndyMik90 0ed6afb805 Improvement/Worktree needs to be manually deleted for early access safety (not delete work that has introduced spend) 2025-12-18 16:18:05 +01:00
AndyMik90 914a09d0da feat/claude account oauth implementation on onboarding instead of manual token 2025-12-18 16:06:43 +01:00
AndyMik90 e44202a066 Better handling of lock files from worktress upon merging 2025-12-18 16:00:30 +01:00
AndyMik90 42496446bc new oauth github integration upon onboarding. 2025-12-18 16:00:17 +01:00
AndyMik90 b0fc497583 lock update 2025-12-18 15:57:32 +01:00
AndyMik90 462edcdd93 improved readme and build process 2025-12-18 15:07:25 +01:00
AndyMik90 affbc48cbe fix ESLint warnings and failing tests 2025-12-18 14:49:07 +01:00
AndyMik90 d7fd1a24da Big upgrade to windows and linux compability, also introduced a auto upgrading functionality to work cross platform with also the posiblity for Git init on app startup and checking when adding new projects. 2025-12-18 13:41:57 +01:00
AndyMik90 96dd04d411 feat: Add debug logging to app updater
Improved logging for app updates to help diagnose update issues:

- Added DEBUG_UPDATER env var for verbose electron-updater logging

- Better console output showing update check status

- Clear message when running in dev mode (updates disabled)

- Option to force updater init in dev mode for testing logs
2025-12-18 11:21:13 +01:00
AndyMik90 1d0566fce7 feat: Auto-open settings to updates section when app update is ready
When an app update is downloaded and ready to install, automatically opens the Settings dialog to the Updates section so users can easily install the update.

Changes:

- App.tsx: Listen for onAppUpdateDownloaded event and open settings

- AdvancedSettings.tsx: Add Electron app update UI with download/install buttons

- ipc.ts: Add app update methods to ElectronAPI interface

- settings-mock.ts: Add browser mocks for app update methods
2025-12-18 10:59:25 +01:00
AndyMik90 7f3cd5969d feat: Add integrated release workflow with AI version suggestion
Adds a streamlined release workflow that uses AI (Claude Haiku) to analyze git commits and suggest semantic version bumps (major/minor/patch). Automatically updates package.json, commits, and pushes using a safe git workflow that preserves user's current work.

New features:

- RELEASE_SUGGEST_VERSION IPC for AI-powered version suggestions

- bumpVersion() with safe git workflow (stash/checkout/commit/restore)

- VersionSuggestion type with bumpType and reasoning

- Updated ReleaseProgress to include bumping_version stage

Also replaces VERSION file detection with requirements.txt across the codebase.
2025-12-18 10:32:55 +01:00
AndyMik90 0ef0e1588b fix for fixing windows/linux python handling 2025-12-18 10:18:34 +01:00
AndyMik90 efc112a313 Implement Electron app auto-updater (Phase 1 & 2)
Phase 1: Update Notifications & Download
- Install electron-updater dependency
- Add GitHub publish configuration to package.json

Phase 2: Auto-Download & Install
- Backend: Main process auto-updater with electron-updater
- Frontend: AppUpdateNotification UI component
- IPC: Full update workflow (check/download/install/events)

Backend Implementation:
- Created app-updater.ts with autoUpdater configuration
- Auto-download enabled, checks every 4 hours
- Events: update-available, update-downloaded, download-progress
- Created app-update-handlers.ts with IPC handlers
- Integrated into main/index.ts (production only)

Frontend Implementation:
- Created AppUpdateNotification.tsx with modal dialog
- Shows version, release notes, download progress
- Download workflow: Available → Downloading → Downloaded → Install
- Created app-update-api.ts preload bindings
- Integrated into App.tsx root level

Configuration:
- Added 8 IPC channels: APP_UPDATE_* operations & events
- Created AppUpdateInfo, AppUpdateProgress, AppUpdate*Event types
- GitHub release publishing: provider=github, repo=Auto-Claude

Features:
 Automatic update checking (3s after launch, every 4 hours)
 Auto-download updates in background with progress bar
 User notification with version & release notes
 One-click install and restart
 Dismissible with "Remind Me Later"
 Error handling & visual feedback
 Production-only (disabled in dev mode)

Non-technical users can now update the Electron app with one click!

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-18 09:38:20 +01:00
AndyMik90 d33a0aaff6 Fix Windows/Linux source path detection
- Enhanced detectAutoBuildSourcePath() to work across all platforms
- Separated dev vs production mode path resolution
- Added comprehensive path checking for Windows/Linux packaged apps
- Added debug logging (enable with AUTO_CLAUDE_DEBUG=1)
- Updated both settings-handlers.ts and project-handlers.ts
- Fixes 'Source path not configured' error on Windows/Linux

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-18 09:24:44 +01:00
AndyMik90 2fa3c51659 Update README.md to include git repository initialization and folder structure explanations
- Added instructions for initializing a git repository as a prerequisite for using Auto Claude.
- Included a section detailing the purpose of various folders created during the Auto Claude process, enhancing user understanding of the framework's structure.
2025-12-17 22:47:09 +01:00
AndyMik90 59b091a79f V 2.3.2 2025-12-17 22:37:52 +01:00
AndyMik90 a0c775f690 Merge branch 'auto-claude/028-fix-kanban-view-task-display-styling' 2025-12-17 22:19:09 +01:00
AndyMik90 9babdc23c1 fix to spec runner paths 2025-12-17 22:18:11 +01:00
AndyMik90 dc886dce44 auto-claude: subtask-1-1 - Restructure SortableFeatureCard badge layout
- Reorganize layout for better visual hierarchy: title first, then description, then metadata
- Make badges more compact with smaller text (text-[10px]) and reduced padding (px-1.5 py-0)
- Separate priority badge in header from complexity/impact badges in footer
- Replace competitor insight text with icon-only badge (with tooltip)
- Reduce card padding from p-4 to p-3
- Change title from truncate to line-clamp-2 for better readability
- Move complexity and impact badges to dedicated metadata row at bottom
- Remove " impact" text suffix for cleaner look
- Shorten "Go to Task" button text to "Task"

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-17 22:04:47 +01:00
AndyMik90 32760348ae Fix to linux path issue 2025-12-17 21:42:53 +01:00
AndyMik90 395ba60098 Improvement/Terminal session persistence over app restart 2025-12-17 18:23:47 +01:00
AndyMik90 d85a1b4f63 V2.3.0 release for terminals 2025-12-17 17:28:02 +01:00
AndyMik90 43a593c1e1 Bug fix: dont let tasks slip by human review if the task was set as done. 2025-12-17 17:21:55 +01:00
AndyMik90 5078191d74 Added a release title for the github format - changelog functionality 2025-12-17 17:15:28 +01:00
AndyMik90 99850512e6 Implement PTY Daemon and Buffer Management
- Introduced a new PTY Daemon to handle terminal processes, ensuring session continuity and efficient resource management.
- Added session persistence for terminal states, allowing recovery across app restarts.
- Implemented buffer management to optimize terminal output handling, reducing React re-renders.
- Enhanced flow control and scroll management for better user experience during high-velocity terminal output.
- Refactored terminal store to utilize the new buffer manager, improving performance and memory management.
- Added WebGL context management for enhanced rendering capabilities in terminals.

This update significantly improves terminal performance and reliability, especially during intensive operations.
2025-12-17 17:05:37 +01:00
AndyMik90 f92fcfa075 Version 2.2.0 2025-12-17 16:23:00 +01:00
AndyMik90 f201f7e3a8 hotfix/spec-runner path location 2025-12-17 16:19:49 +01:00
AndyMik90 0da4bc4a84 Remove unnecessary dynamic imports of getUsageMonitor in terminal-handlers.ts to streamline usage monitoring logic. 2025-12-17 15:59:20 +01:00
AndyMik90 a0d142ba95 Improve changelog feature, version tracking, markdown/preview, persistent styling options 2025-12-17 15:32:58 +01:00
AndyMik90 473b04530a Refactor code for improved readability and maintainability
- Updated function calls in build_commands.py for better parameter alignment.
- Enhanced merge conflict checks in workspace_commands.py and workspace.py for clarity.
- Improved logging and output formatting in worktree.py and other files.
- Added proactive swap information to rate-limit-detector.ts and profile-storage.ts.
- Updated usage monitoring methods in usage-monitor.ts and IPC types for better integration.
2025-12-17 13:25:38 +01:00
AndyMik90 e5b9488a86 Enhance AgentManager to manage task context cleanup and preserve swapCount on restarts. Update UsageMonitor to delay profile usage checks to prevent cascading swaps. 2025-12-17 12:52:14 +01:00
AndyMik90 de33b2c7c3 Feat/Usage-monitoring 2025-12-17 12:10:49 +01:00
AndyMik90 eb77915879 Merge branch 'auto-claude/023-fix-overlapping-close-button-styling' 2025-12-17 11:29:33 +01:00
AndyMik90 7e09739f17 option to stash changes before merge 2025-12-17 11:25:00 +01:00
AndyMik90 e6d6cea9e4 Refactor merge conflict check to use branch names instead of commit hashes
- Updated _check_git_conflicts function to utilize branch names for the merge-tree command, improving clarity and correctness in conflict resolution.
2025-12-17 10:54:32 +01:00
AndyMik90 dfb5cf9c50 fix worktree merge logic 2025-12-17 10:46:56 +01:00
AndyMik90 34631c38ea qa: Sign off - all verification passed
- Unit tests: 280/280 passing
- Build: succeeded
- Security review: passed
- No regressions found
- Implementation matches spec requirements

🤖 QA Agent Session 1

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-17 10:35:54 +01:00
AndyMik90 7c327ed007 auto-claude: subtask-1-2 - Pass hideCloseButton={showFileExplorer} to DialogContent
Hide the modal's close button when the file explorer drawer is open
to prevent visual overlap with the drawer's close button.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-17 10:35:54 +01:00
AndyMik90 5f9653a961 auto-claude: subtask-1-1 - Add hideCloseButton prop to DialogContent component
- Added DialogContentProps interface extending base Radix dialog props
- Added optional hideCloseButton boolean prop
- Conditionally render close button based on hideCloseButton value
- When hideCloseButton is true, the built-in close button is hidden
2025-12-17 10:35:54 +01:00
AndyMik90 2d2a8131cc Fix branch logic for merge AI 2025-12-17 10:34:13 +01:00
AndyMik90 ce9c2cddc1 Fix spec_runner.py path resolution after move to runners/ directory
- spec_runner.py: Update sys.path to add parent directory (auto-claude/)
  instead of current directory (runners/) so imports work correctly
- spec_runner.py: Fix .env file path resolution for the new location
- analyzer.py: Add CLI entry point to shim so it works when run as script

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-17 00:15:52 +01:00
AndyMik90 460c76de42 Better handling of lock files during merge conflicts 2025-12-16 23:50:56 +01:00
AndyMik90 4eb66f5004 Fix Discord release webhook failing on large changelogs
- Pin action to v1.19.0 for stability
- Add remove_github_reference_links to strip commit hash section
- Fixes embed validation error from oversized release notes

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-16 23:42:00 +01:00
AndyMik90 788b8d0e3e Update CHANGELOG with new features, improvements, bug fixes, and other changes
- Added GitHub OAuth integration, roadmap feature management, AI model selection during task creation, and file explorer integration.
- Improved merge conflict resolution, refactored components for maintainability, and enhanced onboarding wizard logic.
- Fixed TypeScript compilation errors and improved handling of merge lock file conflicts.
- General code cleanup and updated CI workflows.
2025-12-16 23:37:42 +01:00
AndyMik90 957746e09c Enhance merge conflict handling by excluding lock files
- Updated the handle_merge_preview_command to exclude lock files from the list of git conflicts, ensuring they are handled automatically.
- Introduced a utility function to identify lock files and updated the conflict summary to reflect only non-lock-file conflicts.
- Added a new entry in the response to include excluded lock files for UI display purposes.
2025-12-16 23:37:36 +01:00
AndyMik90 36338f3546 Refactor IdeationHeader and update handleDeleteSelected logic
- Simplified the IdeationHeader component by removing the Tooltip wrapper around the Delete button for a cleaner UI.
- Updated handleDeleteSelected to fetch the latest selected IDs from the store, ensuring it operates on the current state.
2025-12-16 23:20:51 +01:00
AndyMik90 36a69fcf0d ideation improvements and linting 2025-12-16 23:04:45 +01:00
AndyMik90 afeb54fc2c New github oauth integration 2025-12-16 22:53:18 +01:00
AndyMik90 6aea4bb830 linting gods pleased now? 2025-12-16 21:57:45 +01:00
AndyMik90 140f11fccd Linting and test fixes 2025-12-16 21:53:01 +01:00
AndyMik90 11fcdf42f3 Big backend refactor for upcoming features 2025-12-16 21:37:12 +01:00
AndyMik90 87f353c3af Remove .auto-claude from tracking (already in .gitignore)
These files were committed before the .gitignore entry was added.
2025-12-16 20:44:24 +01:00
AndyMik90 feb0d4e686 Refactoring for better codebase 2025-12-16 20:43:55 +01:00
AndyMik90 31e4e87869 Add Referenced Files Section and File Explorer Integration in Task Creation Wizard
- Introduced a new ReferencedFilesSection component to display and manage referenced files in the task creation process.
- Implemented drag-and-drop functionality for adding files from the file explorer to the referenced files section.
- Enhanced TaskCreationWizard to include a file explorer drawer for easy file selection and management.
- Updated task draft state to include referenced files, ensuring persistence across sessions.
- Refactored constants for better organization and maintainability, including the addition of MAX_REFERENCED_FILES limit.
2025-12-16 20:34:12 +01:00
AndyMik90 d8e57845c3 Refactor Roadmap component to utilize RoadmapGenerationProgress for better status display
- Replaced the inline generation status display in the Roadmap component with a new RoadmapGenerationProgress component.
- Added RoadmapGenerationProgress component to handle the rendering of generation phases, progress, and error messages.
- Introduced unit tests for the RoadmapGenerationProgress component to ensure correct phase rendering and animation logic.
2025-12-16 18:07:25 +01:00
AndyMik90 d735c5c303 Agent profiles, be able to select model on task creation 2025-12-16 18:05:51 +01:00
AndyMik90 a891225b4e improve merge conflicts for lock files 2025-12-16 18:02:04 +01:00
AndyMik90 9403230ef0 Implement roadmap feature management kanban with drag-and-drop support 2025-12-16 17:49:35 +01:00
AndyMik90 131ec4cb62 refactoring components for better future maintence and more rapid coding 2025-12-16 17:46:14 +01:00
AndyMik90 2e151acc0e Update parallel merge conflict resolution metrics in workspace.py
- Changed the key for tracking parallel AI merges from a boolean to an integer count of files needing AI merge.
- This adjustment enhances clarity in reporting the number of files involved in parallel AI merge operations.
2025-12-16 15:19:35 +01:00
AndyMik90 08dc24cc99 Enhance RouteDetector to exclude specific directories from route detection
- Introduced a mechanism to exclude certain directories (e.g., node_modules, .venv) from route detection in the RouteDetector class.
- Added a new method, _should_include_file, to filter files based on the exclusion criteria.
- Updated route detection methods to utilize the new filtering logic for various frameworks (FastAPI, Flask, Django, Express, Go, Rust).
2025-12-16 15:19:28 +01:00
AndyMik90 f00aa33cda parallell merge conflict resolution 2025-12-16 15:14:58 +01:00
AndyMik90 ddf47ae5ec Roadmap competitor analysis 2025-12-16 15:02:16 +01:00
AndyMik90 9d9cf163ec test for ai merge AI 2025-12-16 15:00:19 +01:00
AndyMik90 3eb2eadaf1 Introduce electron mcp for electron debugging/validation 2025-12-16 14:50:05 +01:00
AndyMik90 56ff586c4d improvement to speed of merge conflict resolution 2025-12-16 14:48:42 +01:00
AndyMik90 e409ae825d improve context sending to merge agent 2025-12-16 14:35:45 +01:00
AndyMik90 01e801aace Integrate profile environment for OAuth token in task handlers
- Added functionality to retrieve and include the active Claude profile environment, specifically the OAuth token, in the task handlers for AI merge resolution.
- Enhanced debugging output to log the presence of the OAuth token and configuration directory during the merge process.
- Ensured consistency by applying the profile environment in both the merge and preview processes.
2025-12-16 14:19:39 +01:00
AndyMik90 579ea40bd2 Refactor AI resolver to use async context manager for client connection
- Updated the AI resolver to utilize an async context manager for handling client connections, improving resource management and consistency with the codebase.
- Maintained existing functionality for querying and processing AI responses while enhancing error handling.
2025-12-16 14:19:30 +01:00
AndyMik90 bf787ade0b Enhance AI resolver and debugging output
- Added logging for AI response content in workspace.py to aid in debugging, including previews of responses and handling of empty responses.
- Refactored the AI resolver's merge function for clarity and improved error logging, ensuring consistent error messages are printed to stderr.
- Updated the maximum turns for AI responses to streamline the merge process.
2025-12-16 14:07:59 +01:00
AndyMik90 4cd7500e96 Remove _bmad-output from git tracking 2025-12-16 13:47:34 +01:00
AndyMik90 4bba9d1aa7 Use claude sdk pattern for ai resolver 2025-12-16 13:45:01 +01:00
AndyMik90 dbe27f0157 Add _bmad-output to .gitignore
- Updated the .gitignore file to include the _bmad-output directory, ensuring that generated output files are not tracked by Git.
2025-12-16 13:44:41 +01:00
AndyMik90 1d830ba59e Update AI resolver to use Claude Opus model and improve error logging
- Changed the model used in the Claude CLI from "claude-sonnet-4-5-20250514" to "claude-opus-4-5-20251101" for enhanced merge resolution quality.
- Improved error handling by printing stderr and stdout to logs when the Claude CLI returns a non-zero exit code.
2025-12-16 13:36:52 +01:00
AndyMik90 7f6456facc Add BMM workflow status tracking and project scan report
- Introduced a new YAML file for tracking the BMM workflow status, detailing phases, required actions, and agent responsibilities.
- Added a JSON report for the initial project scan, capturing workflow version, timestamps, and findings.
- Enhanced conflict checking in the workspace by utilizing git merge-tree for in-memory conflict detection without modifying the working directory.
- Updated AI resolver to use the Claude CLI for non-interactive merge resolution, improving integration with the merge process.
2025-12-16 13:30:09 +01:00
AndyMik90 901e83ac61 resolve claude agent sdk 2025-12-16 13:23:03 +01:00
AndyMik90 65937e198f better conflict handling in the frontend app for merge contlicts (better UX) 2025-12-16 13:12:04 +01:00
AndyMik90 b94eb6589b Getting ready for BMAD integration 2025-12-16 13:07:57 +01:00
AndyMik90 c5d33cd8b1 merge logic v0.3 2025-12-16 12:48:36 +01:00
AndyMik90 e08ab62acb Electron UI fix for merge orcehstrator 2025-12-16 11:05:43 +01:00
AndyMik90 e8b6669d92 merge orcehestrator logic 2025-12-16 10:54:17 +01:00
AndyMik90 d8ba532beb Merge-orchestrator 2025-12-16 10:14:59 +01:00
AndyMik90 488bbfa2c9 Frontend lints 2025-12-15 22:18:20 +01:00
AndyMik90 2ac00a9d8f feat: Add functionality to manage .gitignore entries during project initialization
- Implemented ensureGitignoreEntries function to check and add necessary entries to the project's .gitignore file.
- Automatically creates .gitignore if it doesn't exist and appends entries for the .auto-claude data directory.
- Enhanced project initialization process to ensure proper exclusion of auto-generated files.
2025-12-15 22:06:46 +01:00
AndyMik90 3b832db0ec refactor: Update changelog formatter for GitHub Release compatibility
- Enhanced FORMAT_TEMPLATES to include structured sections for "What's New" and "What's Changed".
- Improved getEmojiInstructions function to accommodate format-specific emoji usage.
- Updated buildChangelogPrompt and buildGitPrompt to include author information and format-specific instructions for better clarity in changelog generation.
2025-12-15 21:49:10 +01:00
AndyMik90 43a338ca11 chore: Update Python versions in CI workflows
- Changed Python version matrix from ['3.11', '3.12'] to ['3.12', '3.13'] in both ci.yml and test-on-tag.yml.
- Refactored print statement in requirements.py for improved readability by using a variable for the edit hint.
2025-12-15 21:39:47 +01:00
AndyMik90 3fc1592ce6 Linting gods are happy 2025-12-15 21:10:27 +01:00
AndyMik90 142cd67c88 Getting ready for the lint gods 2025-12-15 19:49:58 +01:00
AndyMik90 d8ad17dbfa CLI testing/linting 2025-12-15 19:31:21 +01:00
AndyMik90 7c01638a81 refactor: Enhance onboarding wizard completion logic
- Updated the skipWizard and finishWizard functions to save onboarding completion status to disk using the electronAPI, ensuring both local state and persistent storage are updated.
- Improved comments for clarity on the new behavior of saving settings.
2025-12-15 19:31:12 +01:00
AndyMik90 a5a1eb1431 refactor: Update GraphitiStep to proceed to the next step after successful configuration save
- Changed behavior to call onNext() immediately after a successful save of the Graphiti configuration, enhancing user experience by streamlining the onboarding process.
- Removed the previous setSuccess() call to avoid confusion regarding the step transition.
- Remove task creation from onboarding
2025-12-15 19:31:04 +01:00
AndyMik90 39dc91a12c Merge branch 'auto-claude/011-interactive-onboarding-wizard' 2025-12-15 19:19:59 +01:00
AndyMik90 9a59b7ebfe CLI and tests 2025-12-15 19:02:39 +01:00
AndyMik90 4b242c4a64 Version 2.0.1 2025-12-15 18:28:59 +01:00
AndyMik90 f9ef7eae09 Revise README.md to enhance clarity and focus on Auto Claude's capabilities, emphasizing its role as an AI coding companion, and updating feature descriptions for better understanding. 2025-12-15 18:28:33 +01:00
AndyMik90 b3f48037c1 qa: Sign off - all verification passed
- Unit tests: 126/156 passing (30 pre-existing failures, no regressions)
- Integration tests: N/A
- E2E tests: N/A
- Browser verification: complete
- Security review: passed
- Pattern compliance: verified
- Previous critical issue (onRerunWizard prop) fixed and verified

All acceptance criteria met:
- Wizard launches on first app start
- Welcome step displays clear value proposition
- OAuth token setup works correctly
- Optional Graphiti/FalkorDB configuration functions properly
- First spec creation is guided with assistance
- Skip option works at all steps
- Wizard can be re-run from settings

🤖 QA Agent Session 2
2025-12-15 17:57:56 +01:00
AndyMik90 555a46f68d chore: Update implementation_plan.json - fixes applied
Updated qa_signoff status to "fixes_applied" after implementing
the onRerunWizard prop fix in App.tsx.

Ready for QA re-validation.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-15 17:53:13 +01:00
AndyMik90 6b5b7146c7 fix: Add onRerunWizard prop to AppSettingsDialog (qa-requested)
Fixes:
- Missing onRerunWizard prop in App.tsx

The AppSettingsDialog component accepts an onRerunWizard callback prop,
but this prop was not being passed when rendering the component in App.tsx.
This caused the "Re-run Wizard" button to never appear in Settings.

The fix adds the onRerunWizard callback that:
1. Resets onboardingCompleted to false (so wizard shows)
2. Closes the settings dialog
3. Opens the onboarding wizard

Verified:
- TypeScript compilation passes (no new errors)
- All tests pass (existing failures are pre-existing infrastructure issues)
- No regressions introduced

QA Fix Session: 1

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-15 17:52:47 +01:00
AndyMik90 5e56890f78 qa: Rejected - fixes required
Issues found:
- Critical: Missing onRerunWizard prop in App.tsx

The "Re-run Wizard" button will not appear in Settings because
the callback is not passed to AppSettingsDialog.

See QA_FIX_REQUEST.md for details.

🤖 QA Agent Session 1
2025-12-15 17:50:58 +01:00
AndyMik90 5f989a4774 auto-claude: subtask-6-2 - Run existing tests to verify no regressions
Verified test suite results - all failures are pre-existing infrastructure
issues, NOT regressions from the onboarding wizard implementation:

- Electron mock missing getAppPath method (affects ipc-handlers tests)
- Missing @testing-library/react dependency
- Flaky integration tests with timing/mocking issues

No test failures reference onboarding components. The onboarding wizard
implementation does NOT cause any test regressions.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-15 17:45:34 +01:00
AndyMik90 f90fa80278 auto-claude: subtask-6-1 - TypeScript compilation check - fix GraphitiStep type error
Fixed TypeScript error in GraphitiStep.tsx where setDockerAvailable was
receiving `boolean | undefined` instead of the expected `boolean | null`.
Changed the ternary expression to explicitly return `true` or `false`.

All onboarding wizard components now compile without TypeScript errors.
Note: Pre-existing errors in terminal-name-generator.ts, Terminal.tsx,
useVirtualizedTree.test.ts, and browser-mock.ts are outside the scope
of this feature.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-15 17:40:41 +01:00
AndyMik90 50f22dad14 auto-claude: subtask-5-2 - Enhance OAuthStep to detect and display if token is already configured
- Enhanced success state to differentiate between existing token detection
  and newly configured token
- Shows 'Token already configured' message for existing tokens vs
  'Token configured successfully' for new configurations
- Updated reconfigure button text to 'Reconfigure token' when existing
  token is detected
- Provides clearer guidance that users can continue or reconfigure
2025-12-15 17:36:54 +01:00
AndyMik90 f57c28e5d8 auto-claude: subtask-5-1 - Add settings migration logic - set onboardingCompleted
Add migration logic in settings-store.ts to automatically set
onboardingCompleted=true for existing users. The migration checks if:
- globalClaudeOAuthToken is configured
- autoBuildPath is configured

If either condition is true, the user is considered an existing user
and will skip the onboarding wizard. New users (no tokens or paths
configured) will have onboardingCompleted set to false.

The migration runs during loadSettings() and persists the change
if the onboardingCompleted value was previously undefined.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-15 17:34:28 +01:00
AndyMik90 9144e7fa86 auto-claude: subtask-4-1 - Add 'Re-run Wizard' button to AppSettings navigation
- Added onRerunWizard callback prop to AppSettingsDialogProps
- Added 'Re-run Wizard' button in Application section sidebar
- Button uses Sparkles icon and dashed border for visual distinction
- Closes settings dialog and triggers wizard re-run on click

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-15 17:31:45 +01:00
AndyMik90 779e36fb2b auto-claude: subtask-3-1 - Add first-run detection to App.tsx
- Import OnboardingWizard component from onboarding module
- Add isOnboardingWizardOpen state to track wizard visibility
- Add useEffect to detect first run (onboardingCompleted === false)
- Wire OnboardingWizard with callbacks for task creator and settings

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-15 17:29:41 +01:00
AndyMik90 b0af2dc2a7 auto-claude: subtask-2-8 - Create index.ts barrel export for onboarding components 2025-12-15 17:27:12 +01:00
AndyMik90 3de8928a5a auto-claude: subtask-2-7 - Create OnboardingWizard component
Add main wizard container with step management, navigation, and FullScreenDialog pattern:
- Step-by-step wizard flow (Welcome → OAuth → Graphiti → First Spec → Completion)
- WizardProgress indicator integration
- Navigation handlers (next, back, skip)
- Persists onboardingCompleted flag to settings store
- Integrates all step components with proper callbacks
- Handles task creator and settings opening from within wizard

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-15 17:24:56 +01:00
AndyMik90 aa0f608210 auto-claude: subtask-2-6 - Create CompletionStep component - success message
🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-15 17:22:19 +01:00
AndyMik90 32f17a10fb auto-claude: subtask-2-5 - Create FirstSpecStep component - guided first spec
Create FirstSpecStep.tsx component for the onboarding wizard that guides users
through creating their first task/spec with helpful tips and an 'Open Task Creator'
action. Features include:

- Header with icon, title, and description
- 4 tip cards: Be Descriptive, Start Small, Include Context, Let AI Help
- Example task description card for reference
- 'Open Task Creator' primary action button
- Success state when task creator has been opened
- Standard navigation buttons (Back, Skip, Continue)

Follows patterns from OAuthStep and GraphitiStep components.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-15 17:20:04 +01:00
AndyMik90 61184b0469 auto-claude: subtask-2-4 - Create GraphitiStep component - optional Graphiti/FalkorDB configuration
- Created GraphitiStep component for optional Graphiti memory backend configuration
- Features Docker/infrastructure detection to warn if Docker is not running
- Includes toggle switch to enable/disable Graphiti memory
- Shows configuration fields (FalkorDB URI, OpenAI API key) when enabled
- Saves OpenAI API key to global app settings
- Provides informational content about Graphiti benefits
- Implements proper loading/saving/success/error states
- Follows same patterns as OAuthStep and WelcomeStep components

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-15 17:18:05 +01:00
AndyMik90 79d622eeb9 auto-claude: subtask-2-3 - Create OAuthStep component - Claude OAuth token configuration step
- Created OAuthStep.tsx for the onboarding wizard OAuth token setup
- Reuses patterns from EnvConfigModal.tsx for token validation flow
- Implements loading, success, and error states
- Shows existing token detection with option to reconfigure
- Provides instructions for getting a token with copy command button
- Navigation with Back, Skip, and Continue buttons

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-15 17:14:14 +01:00
AndyMik90 a97f697762 auto-claude: subtask-2-2 - Create WelcomeStep component
Create welcome step component for the onboarding wizard with:
- Welcome message and description
- Feature overview grid with 4 key features (AI-powered dev, spec-driven workflow, memory & context, parallel execution)
- Get Started and Skip Setup action buttons
- Responsive layout following WelcomeScreen.tsx patterns

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-15 17:11:16 +01:00
AndyMik90 b6e604cfbb auto-claude: subtask-2-1 - Create WizardProgress component - step progress indicator
- Added WizardProgress.tsx component with numbered circles and connecting lines
- Supports completed, current, and upcoming step visual states
- Uses Check icon from lucide-react for completed steps
- Follows existing patterns from AppSettings.tsx and progress.tsx
- Exported WizardStep interface for use by other wizard components

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-15 17:09:09 +01:00
AndyMik90 c5a0331d3f auto-claude: subtask-1-2 - Add onboardingCompleted to DEFAULT_APP_SETTINGS
- Added onboardingCompleted: false to DEFAULT_APP_SETTINGS constant
- This provides the default value for the new onboarding tracking field

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-15 17:06:21 +01:00
AndyMik90 7c24b48ed8 auto-claude: subtask-1-1 - Add onboardingCompleted to AppSettings type interface
Add optional onboardingCompleted boolean field to AppSettings interface
to track whether the user has completed the onboarding wizard.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-15 17:04:21 +01:00
AndyMik90 bb5c744613 Update container name for FalkorDB service in docker-compose.yml 2025-12-15 15:42:24 +01:00
AndyMik90 03e6e84333 New infrastructure status for docker 2025-12-15 15:40:02 +01:00
AndyMik90 146e32a1e4 improvements to readme 2025-12-15 15:39:26 +01:00
AndyMik90 e8b53d5a93 improved readme and dedicated CLI documentation 2025-12-15 15:32:25 +01:00
AndyMik90 c7d571fc4a Enhance update check functionality by adding release URL and improving IPC handlers for external links. Update project settings to reflect new LLM provider name and implement a markdown renderer for release notes in advanced settings. 2025-12-15 15:03:30 +01:00
AndyMik90 2f9aa64b55 readme + udpate + discord relase workflow 2025-12-15 15:03:22 +01:00
AndyMik90 982c5e6063 Refactor App component to simplify project selection display by removing unnecessary wrapper div and keeping only the project name visible. 2025-12-15 14:39:54 +01:00
AndyMik90 cfeb15726e terminal name generator 2025-12-15 14:06:52 +01:00
AndyMik90 92998dedd6 cleanup 2025-12-15 14:06:43 +01:00
AndyMik90 b9133c1ba5 Update project-store.ts to use Dirent type for specDirs variable 2025-12-15 12:56:45 +01:00
AndyMik90 e85d5e8db6 Fix project settings bug 2025-12-15 12:55:17 +01:00
AndyMik90 74ada6e4c4 Merge branch 'auto-claude/002-update-task-conversion-button-to-go-to-task' 2025-12-15 12:51:48 +01:00
AndyMik90 0b5617be6e roadmap functionality 2025-12-15 12:33:38 +01:00
AndyMik90 dbc568a26b auto-claude: subtask-1-3 - Update IdeaCard and IdeaDetailPanel to show Go to Task button
- Added ExternalLink icon import to both components
- Updated IdeaCard to destructure onGoToTask prop
- Added Go to Task button in IdeaCard when idea is converted and has taskId
- Updated IdeaDetailPanel to destructure onGoToTask prop
- Added Go to Task button in IdeaDetailPanel when idea is converted and has taskId

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-15 11:06:53 +01:00
AndyMik90 3bc16a5011 auto-claude: subtask-1-2 - Update useIdeation hook and wire onGoToTask callback
- Add UseIdeationOptions interface with onGoToTask callback
- Update handleConvertToTask to store taskId using setIdeaTaskId
- Add handleGoToTask callback that wraps the provided onGoToTask
- Update Ideation component to accept onGoToTask prop
- Wire onGoToTask through to IdeaCard, IdeaDetailPanel, GenerationProgressScreen
- Add handleGoToTask in App.tsx to navigate to kanban and select task
- Update component interfaces to accept optional onGoToTask prop

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-15 11:04:23 +01:00
AndyMik90 b40f2de36b auto-claude: subtask-1-1 - Add taskId field to IdeaBase type and update store
- Add optional taskId field to IdeaBase interface to store the created
  task ID when an idea is converted to a task
- Add setIdeaTaskId action to ideation store that sets the taskId and
  updates the status to 'converted' in a single operation

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-15 11:00:01 +01:00
AndyMik90 ec48ef420e Merge branch 'auto-claude/001-implement-virtualization-for-filetree-component-in' 2025-12-15 10:57:55 +01:00
AndyMik90 e309713a6b Refcator for better code quality 2025-12-15 10:56:29 +01:00
AndyMik90 d536b4ad94 auto-claude: subtask-3-1 - Create unit tests for useVirtualizedTree hook
Add comprehensive unit tests for the useVirtualizedTree hook and flattenTree
function. Tests cover:
- Basic flattenTree functionality (empty input, single/multiple nodes)
- Expansion and loading state handling
- Nested tree flattening with various scenarios
- Depth calculation
- Hook integration with file-explorer-store
- Memoization behavior
- Complex scenarios (mixed files/directories, partial expansion)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-15 10:40:35 +01:00
AndyMik90 cc843771f4 auto-claude: subtask-2-3 - Update FileTreeItem to work with flat list structure
- Remove children prop from FileTreeItemProps interface
- Remove children parameter from component function
- Remove recursive children rendering section
- Simplify wrapper div structure (no longer needs nested divs)
- Component now works with flat virtualized list structure

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-15 10:37:12 +01:00
AndyMik90 ef229826cf auto-claude: subtask-2-2 - Refactor FileTree component to use virtualization
Replace recursive FileTreeNode with flat virtualized list using
@tanstack/react-virtual's useVirtualizer hook.

Changes:
- Remove recursive FileTreeNode component
- Add useVirtualizer for efficient rendering of visible items only
- Integrate with useVirtualizedTree hook for flat node list
- Set estimated item height (28px) and overscan (10 items)
- Maintain all existing functionality: lazy loading, expand/collapse, drag-drop

This significantly reduces DOM nodes for large directories by only
rendering visible items plus a small overscan buffer.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-15 10:35:05 +01:00
AndyMik90 4944a9e7df auto-claude: subtask-2-1 - Add efficient visible items computation selectors
Add three new selectors to file-explorer-store for efficient virtualization:
- getAllExpandedFiles: Returns a copy of expanded folders Set
- getVisibleFiles: Recursively collects all visible FileNodes from a root path
- computeVisibleItems: Returns visible nodes array with count for virtualized rendering

These selectors support the virtualized FileTree component by efficiently
computing which items should be rendered based on expanded folder state.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-15 10:32:25 +01:00
AndyMik90 3df7691e70 auto-claude: subtask-1-2 - Create useVirtualizedTree hook with flattenTree utility
Add useVirtualizedTree hook that converts hierarchical FileNode[] to flat
array with depth and expansion state for virtualized rendering.

Exports:
- FlattenedNode interface with node, depth, isExpanded, isLoading, key
- flattenTree utility function for recursive tree flattening
- useVirtualizedTree hook integrating with file-explorer-store

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-15 10:30:07 +01:00
AndyMik90 db7573ba49 auto-claude: subtask-1-1 - Install @tanstack/react-virtual as a dependency
Add @tanstack/react-virtual ^3.13.2 to auto-claude-ui dependencies
for implementing virtualized rendering in the FileTree component.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-15 10:27:28 +01:00
AndyMik90 08ed7d3298 Auto Claude V2 2025-12-14 22:23:05 +01:00
AndyMik90 c7f8d98c19 Improvement to let claude code decide parallell agents 2025-12-14 11:46:55 +01:00
AndyMik90 d192bc2e6b Improve terminal experience with task feature and visual feedback 2025-12-14 11:12:07 +01:00
AndyMik90 e9159be69c Removed worktree-worker logic, rely on claude code internal agent system 2025-12-14 11:08:53 +01:00
AndyMik90 9bf6b19a75 terminal improvements and progress changing 2025-12-14 11:08:14 +01:00
AndyMik90 fc01a9e368 feat(file-explorer): Implement file explorer panel and directory listing
- Added a file explorer panel that allows users to browse project files.
- Integrated drag-and-drop functionality for file paths into the terminal.
- Implemented directory listing with caching and loading states.
- Introduced a rate limit modal to inform users when usage limits are reached.
- Enhanced task logging with expandable detail views for better error and result visibility.

This update improves user experience by providing a visual representation of project files and enhancing task management capabilities.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
2025-12-14 00:12:24 +01:00
AndyMik90 569129ea3f feat(terminal): Add task selection dropdown with auto-context loading
- Add associatedTaskId field to Terminal interface in terminal-store.ts
- Add setAssociatedTask action to update terminal task association
- Update TerminalGrid to pass tasks from task store to Terminal components
- Add task selection dropdown in Terminal header (shows when Claude active)
- Add tooltip showing task description when hovering over terminal title
- Implement handleTaskSelect callback that:
  - Updates terminal title to match selected task
  - Associates task with terminal
  - Sends formatted context message to Claude

The dropdown filters to only show tasks in 'backlog' (Planning) status.
When a task is selected, Claude receives a message with the task context
and prompts for confirmation.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-13 22:51:49 +01:00
AndyMik90 c38a1bd25c feat: ensure Python environment readiness before task execution
- Added checks to verify if the Python environment is ready before proceeding with task execution.
- If the environment is not ready, attempts to initialize it using the effective source path.
- Returns appropriate error messages if the environment cannot be prepared, enhancing robustness in task handling.
2025-12-13 22:26:36 +01:00
AndyMik90 06e47bc8be Merge branch 'auto-claude/001-add-contributing-md-with-development-guidelines' 2025-12-13 22:07:42 +01:00
AndyMik90 df6ecdbb2a fixing kanban and terminal work 2025-12-13 22:07:23 +01:00
AndyMik90 e79f609d52 docs: Add CONTRIBUTING.md with development guidelines
Adds comprehensive contribution guidelines for human contributors covering:
- Prerequisites (Python 3.8+, Node.js 18+, pnpm, uv)
- Development setup for Python backend and Electron frontend
- Code style conventions (Python/TypeScript)
- Testing requirements and commands
- Git workflow (branch naming, commit messages)
- Pull request process
- Issue reporting guidelines
- Architecture overview with references to CLAUDE.md

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-13 21:20:59 +01:00
AndyMik90 eb6451abd7 fix insight UI sidebar 2025-12-13 20:44:30 +01:00
AndyMik90 e054411932 auto detect python env 2025-12-13 20:06:48 +01:00
AndyMik90 07b766e92f clearner version system 2025-12-13 19:24:21 +01:00
AndyMik90 39f85f9c3a memory debugging when debug=true and simpler project inlitliazation 2025-12-13 19:20:02 +01:00
AndyMik90 05b900d28f Removal of dev mode 2025-12-13 19:15:08 +01:00
AndyMik90 93e0066391 chore: remove obsolete .auto-claude-security.json file and update Phase class to handle missing fields
- Deleted the .auto-claude-security.json file as it is no longer needed.
- Updated the Phase class's from_dict method to use default values for missing 'phase' and 'name' fields, improving robustness.
- Adjusted the ImplementationPlan class to ensure phases are indexed correctly when created from a dictionary.
- Updated the Linear SDK client model version for improved performance.
- Increased timeout duration for title generation in the TitleGenerator class and enhanced error logging for better diagnostics.
2025-12-13 15:55:01 +01:00
AndyMik90 b0b5d71076 feat: introduce task archiving and Graphiti MCP server integration
- Added functionality to archive and unarchive tasks, allowing users to manage task visibility effectively.
- Implemented Graphiti MCP server integration, enabling agents to access and manipulate knowledge graphs directly.
- Enhanced project settings to include options for enabling the Graphiti MCP server and configuring its URL.
- Updated the Kanban board to filter and display archived tasks, improving task management.
- Introduced a changelog version suggestion feature based on task changes, streamlining release note generation.

These updates enhance task management capabilities and provide a more robust integration with knowledge graph functionalities.
2025-12-13 15:23:53 +01:00
1029 changed files with 188788 additions and 54887 deletions
+166
View File
@@ -0,0 +1,166 @@
# App.tsx Refactoring Summary
## Overview
Successfully refactored the monolithic App.tsx file (2,217 lines) into a well-organized, modular structure with 488 lines in the main App.tsx file - a **78% reduction** in file size.
## File Size Comparison
- **Original**: 2,217 lines
- **Refactored**: 488 lines
- **Reduction**: 1,729 lines (78%)
## New Directory Structure
```
src/
├── animations/
│ ├── constants.ts # Animation variants and transition presets
│ └── index.ts
├── components/
│ ├── Avatar.tsx # Avatar and AvatarGroup components
│ ├── Badge.tsx # Badge component with variants
│ ├── Button.tsx # Button component with sizes and variants
│ ├── Card.tsx # Card container component
│ ├── Input.tsx # Input field component
│ ├── ProgressCircle.tsx # Circular progress indicator
│ ├── Toggle.tsx # Toggle switch component
│ └── index.ts
├── demo-cards/
│ ├── CalendarCard.tsx # Calendar widget demo
│ ├── IntegrationsCard.tsx # Integrations panel demo
│ ├── MilestoneCard.tsx # Milestone tracking demo
│ ├── NotificationsCard.tsx # Notifications panel demo
│ ├── ProfileCard.tsx # User profile card demo
│ ├── ProjectStatusCard.tsx # Project status demo
│ ├── TeamMembersCard.tsx # Team members list demo
│ └── index.ts
├── theme/
│ ├── constants.ts # Theme definitions (7 color themes)
│ ├── ThemeSelector.tsx # Theme dropdown and mode toggle UI
│ ├── types.ts # TypeScript interfaces for themes
│ ├── useTheme.ts # Custom hook for theme management
│ └── index.ts
├── lib/
│ └── utils.ts # Utility functions (cn helper)
├── sections/
│ └── (empty - ready for future section extractions)
└── App.tsx # Main application entry point (488 lines)
```
## Extracted Modules
### 1. Theme System (`theme/`)
- **types.ts**: ColorTheme, Mode, ThemeConfig, ThemePreviewColors, ColorThemeDefinition
- **constants.ts**: COLOR_THEMES array with 7 themes (default, dusk, lime, ocean, retro, neo, forest)
- **useTheme.ts**: Custom React hook for theme state management with localStorage persistence
- **ThemeSelector.tsx**: UI component for theme switching with dropdown and light/dark toggle
### 2. Base Components (`components/`)
All reusable UI components extracted with proper TypeScript interfaces:
- **Button**: 5 variants (primary, secondary, ghost, success, danger), 3 sizes, pill option
- **Badge**: 6 variants (default, primary, success, warning, error, outline)
- **Avatar**: 6 sizes (xs, sm, md, lg, xl, 2xl), with AvatarGroup for multiple avatars
- **Card**: Container with optional padding
- **Input**: Text input with focus states and disabled support
- **Toggle**: Switch component with checked state
- **ProgressCircle**: SVG-based circular progress indicator with 3 sizes
### 3. Demo Cards (`demo-cards/`)
Feature showcase components demonstrating the design system:
- **ProfileCard**: User profile with avatar, name, role, and skill badges
- **NotificationsCard**: Notification list with actions
- **CalendarCard**: Interactive calendar widget
- **TeamMembersCard**: Team member list with payment integrations
- **ProjectStatusCard**: Project progress with team avatars
- **MilestoneCard**: Milestone tracker with progress and assignees
- **IntegrationsCard**: Integration toggles for Slack, Google Meet, GitHub
### 4. Animations (`animations/`)
- **constants.ts**: Animation variants (fadeIn, scaleIn, slideUp, slideDown, slideLeft, slideRight, pop, bounce)
- **constants.ts**: Transition presets (instant, fast, normal, slow, spring variants, easing functions)
## Benefits of Refactoring
### 1. Improved Maintainability
- Each component is in its own file with clear responsibility
- Easy to locate and modify specific functionality
- Reduced cognitive load when working with the codebase
### 2. Better Code Organization
- Logical grouping of related functionality
- Clear separation of concerns (theme, components, demos, animations)
- Consistent file naming conventions
### 3. Enhanced Reusability
- Components can be easily imported and reused
- Type definitions are shared across modules
- Theme system can be used independently
### 4. Easier Testing
- Individual components can be tested in isolation
- Smaller files are easier to unit test
- Mock dependencies are simpler to manage
### 5. Better TypeScript Support
- Explicit type definitions in separate files
- Improved IDE autocomplete and IntelliSense
- Type safety across module boundaries
### 6. Scalability
- Easy to add new components without cluttering App.tsx
- Ready for future extractions (animations section, themes section)
- Clear pattern for organizing new features
## What Remains in App.tsx
The refactored App.tsx now only contains:
1. Import statements for all extracted modules
2. Main App component with:
- Section navigation state
- Theme hook integration
- Header with ThemeSelector
- Section content (overview, colors, typography, components, animations, themes)
- Inline section rendering (can be further extracted if needed)
## Build Verification
The refactored code successfully builds with no errors:
```
✓ 1723 modules transformed
✓ built in 1.38s
```
All functionality remains intact with the same user experience.
## Future Improvements
The codebase is now ready for additional refactoring:
1. **Section Components**: Extract remaining inline sections:
- `ColorsSection.tsx`
- `TypographySection.tsx`
- `ComponentsSection.tsx`
- `AnimationsSection.tsx` (with all animation demos)
- `ThemesSection.tsx`
2. **Animation Demos**: Extract individual animation demo components:
- `HoverCardDemo`, `ButtonPressDemo`, `StaggeredListDemo`
- `ToastDemo`, `ModalDemo`, `CounterDemo`
- `LoadingDemo`, `DragDemo`, `ProgressAnimationDemo`
- `IconAnimationsDemo`, `AccordionDemo`
3. **Utilities**: Additional helper functions as the codebase grows
4. **Hooks**: Extract more custom hooks for common patterns
5. **Types**: Centralized type definitions file if needed
## Migration Notes
- Original file backed up as `App.tsx.original` and `App.tsx.backup`
- All imports updated to use new module structure
- No breaking changes to external API
- Build process remains unchanged
## Conclusion
This refactoring significantly improves code quality and maintainability while preserving all functionality. The new modular structure makes the codebase easier to understand, test, and extend.
+191 -1919
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,75 @@
export const animationVariants = {
// Fade animations
fadeIn: {
initial: { opacity: 0 },
animate: { opacity: 1 },
exit: { opacity: 0 }
},
// Scale animations
scaleIn: {
initial: { opacity: 0, scale: 0.9 },
animate: { opacity: 1, scale: 1 },
exit: { opacity: 0, scale: 0.9 }
},
// Slide animations
slideUp: {
initial: { opacity: 0, y: 20 },
animate: { opacity: 1, y: 0 },
exit: { opacity: 0, y: -20 }
},
slideDown: {
initial: { opacity: 0, y: -20 },
animate: { opacity: 1, y: 0 },
exit: { opacity: 0, y: 20 }
},
slideLeft: {
initial: { opacity: 0, x: 20 },
animate: { opacity: 1, x: 0 },
exit: { opacity: 0, x: -20 }
},
slideRight: {
initial: { opacity: 0, x: -20 },
animate: { opacity: 1, x: 0 },
exit: { opacity: 0, x: 20 }
},
// Spring pop
pop: {
initial: { opacity: 0, scale: 0.5 },
animate: {
opacity: 1,
scale: 1,
transition: { type: 'spring', stiffness: 500, damping: 25 }
},
exit: { opacity: 0, scale: 0.5 }
},
// Bounce
bounce: {
initial: { opacity: 0, y: -50 },
animate: {
opacity: 1,
y: 0,
transition: { type: 'spring', stiffness: 300, damping: 10 }
}
}
}
// Transition presets
export const transitions = {
instant: { duration: 0.05 },
fast: { duration: 0.15 },
normal: { duration: 0.25 },
slow: { duration: 0.4 },
spring: { type: 'spring' as const, stiffness: 400, damping: 25 },
springBouncy: { type: 'spring' as const, stiffness: 300, damping: 10 },
springSmooth: { type: 'spring' as const, stiffness: 200, damping: 20 },
easeOut: { duration: 0.25, ease: [0, 0, 0.2, 1] as [number, number, number, number] },
easeIn: { duration: 0.25, ease: [0.4, 0, 1, 1] as [number, number, number, number] },
easeInOut: { duration: 0.25, ease: [0.4, 0, 0.2, 1] as [number, number, number, number] }
}
+1
View File
@@ -0,0 +1 @@
export * from './constants'
+67
View File
@@ -0,0 +1,67 @@
import React from 'react'
import { cn } from '../lib/utils'
export interface AvatarProps {
src?: string
name?: string
size?: 'xs' | 'sm' | 'md' | 'lg' | 'xl' | '2xl'
color?: string
}
export function Avatar({ src, name = 'User', size = 'md', color }: AvatarProps) {
const sizes = {
xs: 'w-6 h-6 text-[10px]',
sm: 'w-8 h-8 text-xs',
md: 'w-10 h-10 text-sm',
lg: 'w-14 h-14 text-base',
xl: 'w-20 h-20 text-xl',
'2xl': 'w-[120px] h-[120px] text-3xl'
}
const initials = name.split(' ').map(n => n[0]).join('').slice(0, 2).toUpperCase()
// Default to neutral gray, can be overridden with color prop
const bgStyle = color
? { backgroundColor: color }
: {}
return (
<div
className={cn(
'rounded-full flex items-center justify-center font-semibold border-2 border-(--color-surface-card) overflow-hidden',
!color && 'bg-(--color-border-default)',
sizes[size]
)}
style={bgStyle}
>
{src ? (
<img src={src} alt={name} className="w-full h-full object-cover" />
) : (
<span className={cn(color ? 'text-white' : 'text-(--color-text-primary)')}>{initials}</span>
)}
</div>
)
}
interface AvatarGroupProps {
avatars: { name: string; src?: string }[]
max?: number
}
export function AvatarGroup({ avatars, max = 4 }: AvatarGroupProps) {
const visible = avatars.slice(0, max)
const remaining = avatars.length - max
return (
<div className="flex -space-x-2">
{visible.map((avatar, i) => (
<Avatar key={i} {...avatar} size="sm" />
))}
{remaining > 0 && (
<div className="w-8 h-8 rounded-full bg-(--color-background-secondary) flex items-center justify-center text-xs font-medium text-(--color-text-secondary) border-2 border-(--color-surface-card)">
+{remaining}
</div>
)}
</div>
)
}
+27
View File
@@ -0,0 +1,27 @@
import React from 'react'
import { cn } from '../lib/utils'
export interface BadgeProps {
children: React.ReactNode
variant?: 'default' | 'primary' | 'success' | 'warning' | 'error' | 'outline'
}
export function Badge({ children, variant = 'default' }: BadgeProps) {
const variants = {
default: 'bg-(--color-background-secondary) text-(--color-text-secondary)',
primary: 'bg-(--color-accent-primary-light) text-(--color-accent-primary)',
success: 'bg-(--color-semantic-success-light) text-(--color-semantic-success)',
warning: 'bg-(--color-semantic-warning-light) text-(--color-semantic-warning)',
error: 'bg-(--color-semantic-error-light) text-(--color-semantic-error)',
outline: 'bg-transparent border border-(--color-border-default) text-(--color-text-secondary)'
}
return (
<span className={cn(
'inline-flex items-center px-3 py-1 rounded-full text-label-small',
variants[variant]
)}>
{children}
</span>
)
}
+44
View File
@@ -0,0 +1,44 @@
import React from 'react'
import { cn } from '../lib/utils'
export interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
variant?: 'primary' | 'secondary' | 'ghost' | 'success' | 'danger'
size?: 'sm' | 'md' | 'lg'
pill?: boolean
}
export function Button({
children,
variant = 'primary',
size = 'md',
pill = false,
className,
...props
}: ButtonProps) {
const baseStyles = 'inline-flex items-center justify-center font-medium transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-offset-2'
const variants = {
primary: 'bg-(--color-accent-primary) text-(--color-text-inverse) hover:bg-(--color-accent-primary-hover) focus:ring-(--color-accent-primary)',
secondary: 'bg-transparent border border-(--color-border-default) text-(--color-text-primary) hover:bg-(--color-background-secondary)',
ghost: 'bg-transparent text-(--color-text-secondary) hover:bg-(--color-background-secondary)',
success: 'bg-(--color-semantic-success) text-white hover:opacity-90',
danger: 'bg-(--color-semantic-error) text-white hover:opacity-90'
}
const sizes = {
sm: 'h-8 px-3 text-xs',
md: 'h-10 px-4 text-sm',
lg: 'h-12 px-6 text-base'
}
const radius = pill ? 'rounded-full' : 'rounded-md'
return (
<button
className={cn(baseStyles, variants[variant], sizes[size], radius, className)}
{...props}
>
{children}
</button>
)
}
+24
View File
@@ -0,0 +1,24 @@
import React from 'react'
import { cn } from '../lib/utils'
export interface CardProps {
children: React.ReactNode
className?: string
padding?: boolean
}
export function Card({
children,
className,
padding = true
}: CardProps) {
return (
<div className={cn(
'bg-(--color-surface-card) rounded-xl shadow-md',
padding && 'p-6',
className
)}>
{children}
</div>
)
}
+24
View File
@@ -0,0 +1,24 @@
import React from 'react'
import { cn } from '../lib/utils'
export function Input({
placeholder,
className,
...props
}: React.InputHTMLAttributes<HTMLInputElement>) {
return (
<input
className={cn(
'h-10 w-full px-4 rounded-md border border-(--color-border-default)',
'bg-(--color-surface-card) text-(--color-text-primary) text-sm',
'focus:outline-none focus:border-(--color-accent-primary) focus:ring-2 focus:ring-(--color-accent-primary)/20',
'placeholder:text-(--color-text-tertiary)',
'transition-all duration-200',
'disabled:bg-(--color-background-secondary) disabled:opacity-60',
className
)}
placeholder={placeholder}
{...props}
/>
)
}
@@ -0,0 +1,55 @@
import React from 'react'
import { cn } from '../lib/utils'
export interface ProgressCircleProps {
value: number
size?: 'sm' | 'md' | 'lg'
color?: string
}
export function ProgressCircle({
value,
size = 'md',
color = 'var(--color-accent-primary)'
}: ProgressCircleProps) {
const sizes = {
sm: { width: 40, stroke: 4, fontSize: 'text-[10px]' },
md: { width: 56, stroke: 5, fontSize: 'text-xs' },
lg: { width: 80, stroke: 6, fontSize: 'text-base' }
}
const { width, stroke, fontSize } = sizes[size]
const radius = (width - stroke) / 2
const circumference = 2 * Math.PI * radius
const offset = circumference - (value / 100) * circumference
return (
<div className="relative inline-flex items-center justify-center">
<svg width={width} height={width} className="-rotate-90">
<circle
cx={width / 2}
cy={width / 2}
r={radius}
fill="none"
stroke="var(--color-border-default)"
strokeWidth={stroke}
/>
<circle
cx={width / 2}
cy={width / 2}
r={radius}
fill="none"
stroke={color}
strokeWidth={stroke}
strokeDasharray={circumference}
strokeDashoffset={offset}
strokeLinecap="round"
className="transition-all duration-500"
/>
</svg>
<span className={cn('absolute font-semibold', fontSize)}>
{value}%
</span>
</div>
)
}
+28
View File
@@ -0,0 +1,28 @@
import React from 'react'
import { cn } from '../lib/utils'
export interface ToggleProps {
checked: boolean
onChange: (checked: boolean) => void
}
export function Toggle({ checked, onChange }: ToggleProps) {
return (
<button
role="switch"
aria-checked={checked}
onClick={() => onChange(!checked)}
className={cn(
'relative inline-flex h-6 w-11 items-center rounded-full transition-colors duration-200',
checked ? 'bg-(--color-accent-primary)' : 'bg-(--color-border-default)'
)}
>
<span
className={cn(
'inline-block h-5 w-5 rounded-full bg-white shadow-sm transition-transform duration-200',
checked ? 'translate-x-[22px]' : 'translate-x-[2px]'
)}
/>
</button>
)
}
+7
View File
@@ -0,0 +1,7 @@
export * from './Button'
export * from './Badge'
export * from './Avatar'
export * from './Card'
export * from './Input'
export * from './Toggle'
export * from './ProgressCircle'
@@ -0,0 +1,56 @@
import { ChevronLeft, ChevronRight } from 'lucide-react'
import { cn } from '../lib/utils'
import { Card } from '../components'
export function CalendarCard() {
const days = ['M', 'T', 'W', 'T', 'F', 'S', 'S']
const dates = [
[29, 30, 31, 1, 2, 3, 4],
[5, 6, 7, 8, 9, 10, 11],
[12, 13, 14, 15, 16, 17, 18],
[19, 20, 21, 22, 23, 24, 25],
[26, 27, 28, 29, 30, 31, 1]
]
return (
<Card className="w-[300px]">
<div className="flex items-center justify-between mb-4">
<button className="p-1 hover:bg-(--color-background-secondary) rounded transition-colors">
<ChevronLeft className="w-5 h-5 text-(--color-text-tertiary)" />
</button>
<h3 className="text-heading-small">February, 2021</h3>
<button className="p-1 hover:bg-(--color-background-secondary) rounded transition-colors">
<ChevronRight className="w-5 h-5 text-(--color-text-tertiary)" />
</button>
</div>
<div className="grid grid-cols-7 gap-1 text-center">
{days.map((day, i) => (
<div key={i} className="text-label-small text-(--color-text-tertiary) py-2">
{day}
</div>
))}
{dates.flat().map((date, i) => {
const isCurrentMonth = (i < 3 && date > 20) || (i > 30 && date < 10) ? false : true
const isSelected = date === 26 && isCurrentMonth
const isToday = date === 16 && isCurrentMonth
return (
<button
key={i}
className={cn(
'w-9 h-9 rounded-md text-body-medium transition-colors',
!isCurrentMonth && 'text-(--color-text-tertiary)',
isSelected && 'bg-(--color-accent-primary) text-(--color-text-inverse) rounded-full',
isToday && !isSelected && 'text-(--color-accent-primary) font-semibold',
!isSelected && 'hover:bg-(--color-background-secondary)'
)}
>
{date}
</button>
)
})}
</div>
</Card>
)
}
@@ -0,0 +1,39 @@
import { useState } from 'react'
import { Slack, Video, Github } from 'lucide-react'
import { Card, Toggle } from '../components'
export function IntegrationsCard() {
const [slack, setSlack] = useState(true)
const [meet, setMeet] = useState(true)
const [github, setGithub] = useState(false)
const integrations = [
{ icon: Slack, name: 'Slack', desc: 'Used as a main source of communication', enabled: slack, toggle: setSlack, color: '#E91E63' },
{ icon: Video, name: 'Google meet', desc: 'Used for all types of calls', enabled: meet, toggle: setMeet, color: '#00897B' },
{ icon: Github, name: 'Github', desc: 'Enables automated workflows, code synchronization', enabled: github, toggle: setGithub, color: '#333' }
]
return (
<Card className="w-[320px]">
<h3 className="text-heading-medium mb-4">Integrations</h3>
<div className="space-y-4">
{integrations.map((int, i) => (
<div key={i} className="flex items-center gap-3">
<div
className="w-10 h-10 rounded-lg flex items-center justify-center"
style={{ backgroundColor: `${int.color}15` }}
>
<int.icon className="w-5 h-5" style={{ color: int.color }} />
</div>
<div className="flex-1 min-w-0">
<p className="text-heading-small">{int.name}</p>
<p className="text-body-small text-(--color-text-secondary) truncate">{int.desc}</p>
</div>
<Toggle checked={int.enabled} onChange={int.toggle} />
</div>
))}
</div>
</Card>
)
}
@@ -0,0 +1,35 @@
import { Card, Button, ProgressCircle, AvatarGroup } from '../components'
export function MilestoneCard() {
return (
<Card className="w-[380px]">
<div className="flex items-center justify-between mb-4">
<h3 className="text-heading-medium">Wireframes milestone</h3>
<Button variant="secondary" size="sm" pill>View details</Button>
</div>
<div className="flex items-center gap-6">
<div>
<p className="text-body-small text-(--color-text-secondary)">Due date:</p>
<p className="text-heading-small">March 20th</p>
</div>
<ProgressCircle value={39} size="lg" />
<div>
<p className="text-body-small text-(--color-text-secondary)">Asignees:</p>
<AvatarGroup
avatars={[
{ name: 'A' },
{ name: 'B' },
{ name: 'C' },
{ name: 'D' },
{ name: 'E' }
]}
max={4}
/>
</div>
</div>
</Card>
)
}
@@ -0,0 +1,63 @@
import { MoreVertical, Check, X } from 'lucide-react'
import { Card, Avatar, Badge, Button } from '../components'
export function NotificationsCard() {
return (
<Card className="w-[320px]" padding={false}>
<div className="p-4 border-b border-(--color-border-default)">
<div className="flex items-center justify-between">
<h3 className="text-heading-small">Notifications</h3>
<Badge variant="primary">6</Badge>
</div>
<p className="text-body-small text-(--color-text-tertiary) mt-1">Unread</p>
</div>
<div className="divide-y divide-(--color-border-default)">
<div className="p-4 flex gap-3">
<Avatar size="sm" name="Ashlynn George" />
<div className="flex-1 min-w-0">
<p className="text-body-small">
<span className="font-semibold">Ashlynn George</span>
<span className="text-(--color-text-tertiary)"> · 1h</span>
</p>
<p className="text-body-small text-(--color-text-secondary)">
has invited you to access "Magma project"
</p>
<div className="flex gap-2 mt-2">
<Button size="sm" variant="success" pill>
<Check className="w-3 h-3 mr-1" /> Accept
</Button>
<Button size="sm" variant="secondary" pill>
<X className="w-3 h-3 mr-1" /> Deny request
</Button>
</div>
</div>
<button className="p-1 hover:bg-(--color-background-secondary) rounded self-start transition-colors">
<MoreVertical className="w-4 h-4 text-(--color-text-tertiary)" />
</button>
</div>
<div className="p-4 flex gap-3">
<Avatar size="sm" name="Ashlynn George" />
<div className="flex-1">
<p className="text-body-small">
<span className="font-semibold">Ashlynn George</span>
<span className="text-(--color-text-tertiary)"> · 1h</span>
</p>
<p className="text-body-small text-(--color-text-secondary)">
changed status of task in "Magma project"
</p>
</div>
<button className="p-1 hover:bg-(--color-background-secondary) rounded self-start transition-colors">
<MoreVertical className="w-4 h-4 text-(--color-text-tertiary)" />
</button>
</div>
</div>
<div className="p-4 flex gap-2 border-t border-(--color-border-default)">
<Button variant="secondary" className="flex-1" pill>Mark all as read</Button>
<Button variant="primary" className="flex-1" pill>View all</Button>
</div>
</Card>
)
}
@@ -0,0 +1,24 @@
import { MoreVertical } from 'lucide-react'
import { Card, Avatar, Badge } from '../components'
export function ProfileCard() {
return (
<Card className="w-[280px]">
<div className="flex justify-end mb-4">
<button className="p-1 hover:bg-(--color-background-secondary) rounded transition-colors">
<MoreVertical className="w-5 h-5 text-(--color-text-tertiary)" />
</button>
</div>
<div className="flex flex-col items-center text-center">
<Avatar size="2xl" name="Christine Thompson" />
<h3 className="text-heading-large mt-4">Christine Thompson</h3>
<p className="text-body-medium text-(--color-text-secondary)">Project manager</p>
<div className="flex flex-wrap gap-2 mt-4 justify-center">
<Badge variant="outline">UI/UX Design</Badge>
<Badge variant="outline">Project management</Badge>
<Badge variant="outline">Agile methodologies</Badge>
</div>
</div>
</Card>
)
}
@@ -0,0 +1,31 @@
import { MoreVertical } from 'lucide-react'
import { Card, ProgressCircle, AvatarGroup } from '../components'
export function ProjectStatusCard() {
return (
<Card className="w-[380px]">
<div className="flex justify-between items-start mb-4">
<ProgressCircle value={43} size="md" />
<button className="p-1 hover:bg-(--color-background-secondary) rounded transition-colors">
<MoreVertical className="w-5 h-5 text-(--color-text-tertiary)" />
</button>
</div>
<h3 className="text-heading-large mb-2">Amber website redesign</h3>
<p className="text-body-medium text-(--color-text-secondary) mb-4">
In today's fast-paced digital landscape, our mission is to transform our website into a more intuitive, engaging, and user-friendly platfor...
</p>
<AvatarGroup
avatars={[
{ name: 'User 1' },
{ name: 'User 2' },
{ name: 'User 3' },
{ name: 'User 4' },
{ name: 'User 5' }
]}
max={4}
/>
</Card>
)
}
@@ -0,0 +1,40 @@
import { MoreVertical, MessageSquare } from 'lucide-react'
import { Card, Avatar } from '../components'
export function TeamMembersCard() {
const members = [
{ name: 'Julie Andrews', role: 'Project manager' },
{ name: 'Kevin Conroy', role: 'Project manager' },
{ name: 'Jim Connor', role: 'Project manager' },
{ name: 'Tom Kinley', role: 'Project manager' }
]
return (
<Card className="w-[320px]" padding={false}>
<div className="divide-y divide-(--color-border-default)">
{members.map((member, i) => (
<div key={i} className="p-4 flex items-center gap-3">
<Avatar name={member.name} />
<div className="flex-1">
<p className="text-heading-small">{member.name}</p>
<p className="text-body-small text-(--color-text-secondary)">{member.role}</p>
</div>
<button className="p-1 hover:bg-(--color-background-secondary) rounded transition-colors">
<MoreVertical className="w-4 h-4 text-(--color-text-tertiary)" />
</button>
<button className="p-2 bg-(--color-semantic-error-light) text-(--color-semantic-error) rounded-md hover:opacity-80 transition-opacity">
<MessageSquare className="w-4 h-4" />
</button>
</div>
))}
</div>
<div className="p-4 border-t border-(--color-border-default) flex justify-center gap-3">
<img src="https://upload.wikimedia.org/wikipedia/commons/b/ba/Stripe_Logo%2C_revised_2016.svg" alt="Stripe" className="h-6" />
<div className="px-3 py-1 bg-[#1A1F71] text-white text-sm font-bold rounded">VISA</div>
<div className="px-2 py-1 bg-[#003087] text-white text-xs font-bold rounded">PayPal</div>
<div className="w-8 h-8 bg-gradient-to-r from-red-500 to-yellow-500 rounded-full" />
</div>
</Card>
)
}
+7
View File
@@ -0,0 +1,7 @@
export * from './ProfileCard'
export * from './NotificationsCard'
export * from './CalendarCard'
export * from './TeamMembersCard'
export * from './ProjectStatusCard'
export * from './MilestoneCard'
export * from './IntegrationsCard'
+6
View File
@@ -0,0 +1,6 @@
import { type ClassValue, clsx } from 'clsx'
import { twMerge } from 'tailwind-merge'
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
+104
View File
@@ -0,0 +1,104 @@
import { useState } from 'react'
import { ChevronLeft, Check, Sun, Moon } from 'lucide-react'
import { cn } from '../lib/utils'
import { ColorTheme, Mode, ColorThemeDefinition } from './types'
interface ThemeSelectorProps {
colorTheme: ColorTheme
mode: Mode
onColorThemeChange: (theme: ColorTheme) => void
onModeToggle: () => void
themes: ColorThemeDefinition[]
}
export function ThemeSelector({
colorTheme,
mode,
onColorThemeChange,
onModeToggle,
themes
}: ThemeSelectorProps) {
const [isOpen, setIsOpen] = useState(false)
// Find theme with fallback to first theme (default)
const currentTheme = themes.find(t => t.id === colorTheme) || themes[0]
return (
<div className="flex items-center gap-3">
{/* Color Theme Dropdown */}
<div className="relative">
<button
onClick={() => setIsOpen(!isOpen)}
className="flex items-center gap-2 px-3 py-2 rounded-lg bg-(--color-background-secondary) hover:bg-(--color-border-default) transition-colors"
>
<div
className="w-4 h-4 rounded-full border-2 border-white shadow-sm"
style={{ backgroundColor: mode === 'dark' ? currentTheme.previewColors.accent : currentTheme.previewColors.bg }}
/>
<span className="text-body-medium font-medium">{currentTheme.name}</span>
<ChevronLeft className={cn(
"w-4 h-4 text-(--color-text-tertiary) transition-transform",
isOpen ? "rotate-90" : "-rotate-90"
)} />
</button>
{isOpen && (
<>
<div
className="fixed inset-0 z-40"
onClick={() => setIsOpen(false)}
/>
<div className="absolute top-full right-0 mt-2 w-64 p-2 bg-(--color-surface-card) rounded-lg shadow-lg border border-(--color-border-default) z-50">
{themes.map((theme) => (
<button
key={theme.id}
onClick={() => {
onColorThemeChange(theme.id)
setIsOpen(false)
}}
className={cn(
"w-full flex items-center gap-3 px-3 py-2 rounded-md transition-colors text-left",
colorTheme === theme.id
? "bg-(--color-accent-primary-light)"
: "hover:bg-(--color-background-secondary)"
)}
>
<div className="flex -space-x-1">
<div
className="w-5 h-5 rounded-full border-2 border-white shadow-sm"
style={{ backgroundColor: theme.previewColors.bg }}
/>
<div
className="w-5 h-5 rounded-full border-2 border-white shadow-sm"
style={{ backgroundColor: theme.previewColors.accent }}
/>
</div>
<div className="flex-1 min-w-0">
<p className="text-body-medium font-medium">{theme.name}</p>
<p className="text-body-small text-(--color-text-tertiary) truncate">{theme.description}</p>
</div>
{colorTheme === theme.id && (
<Check className="w-4 h-4 text-(--color-accent-primary)" />
)}
</button>
))}
</div>
</>
)}
</div>
{/* Light/Dark Toggle */}
<button
onClick={onModeToggle}
className="p-2 rounded-lg bg-(--color-background-secondary) hover:bg-(--color-border-default) transition-colors"
aria-label={`Switch to ${mode === 'light' ? 'dark' : 'light'} mode`}
>
{mode === 'light' ? (
<Moon className="w-5 h-5 text-(--color-text-secondary)" />
) : (
<Sun className="w-5 h-5 text-(--color-text-secondary)" />
)}
</button>
</div>
)
}
+46
View File
@@ -0,0 +1,46 @@
import { ColorThemeDefinition } from './types'
export const COLOR_THEMES: ColorThemeDefinition[] = [
{
id: 'default',
name: 'Default',
description: 'Oscura-inspired with pale yellow accent',
previewColors: { bg: '#F2F2ED', accent: '#E6E7A3', darkBg: '#0B0B0F', darkAccent: '#E6E7A3' }
},
{
id: 'dusk',
name: 'Dusk',
description: 'Warmer variant with slightly lighter dark mode',
previewColors: { bg: '#F5F5F0', accent: '#E6E7A3', darkBg: '#131419', darkAccent: '#E6E7A3' }
},
{
id: 'lime',
name: 'Lime',
description: 'Fresh, energetic lime with purple accents',
previewColors: { bg: '#E8F5A3', accent: '#7C3AED', darkBg: '#0F0F1A' }
},
{
id: 'ocean',
name: 'Ocean',
description: 'Calm, professional blue tones',
previewColors: { bg: '#E0F2FE', accent: '#0284C7', darkBg: '#082F49' }
},
{
id: 'retro',
name: 'Retro',
description: 'Warm, nostalgic amber vibes',
previewColors: { bg: '#FEF3C7', accent: '#D97706', darkBg: '#1C1917' }
},
{
id: 'neo',
name: 'Neo',
description: 'Modern cyberpunk pink/magenta',
previewColors: { bg: '#FDF4FF', accent: '#D946EF', darkBg: '#0F0720' }
},
{
id: 'forest',
name: 'Forest',
description: 'Natural, earthy green tones',
previewColors: { bg: '#DCFCE7', accent: '#16A34A', darkBg: '#052E16' }
}
]
+4
View File
@@ -0,0 +1,4 @@
export * from './types'
export * from './constants'
export * from './useTheme'
export * from './ThemeSelector'
+21
View File
@@ -0,0 +1,21 @@
export type ColorTheme = 'default' | 'dusk' | 'lime' | 'ocean' | 'retro' | 'neo' | 'forest'
export type Mode = 'light' | 'dark'
export interface ThemeConfig {
colorTheme: ColorTheme
mode: Mode
}
export interface ThemePreviewColors {
bg: string
accent: string
darkBg: string
darkAccent?: string
}
export interface ColorThemeDefinition {
id: ColorTheme
name: string
description: string
previewColors: ThemePreviewColors
}
+64
View File
@@ -0,0 +1,64 @@
import { useState, useEffect } from 'react'
import { ThemeConfig, ColorTheme, Mode } from './types'
import { COLOR_THEMES } from './constants'
export function useTheme() {
const [config, setConfig] = useState<ThemeConfig>(() => {
if (typeof window !== 'undefined') {
const stored = localStorage.getItem('design-system-theme-config')
if (stored) {
try {
const parsed = JSON.parse(stored)
// Validate that the stored theme still exists
const themeExists = COLOR_THEMES.some(t => t.id === parsed.colorTheme)
if (themeExists) {
return parsed
}
// Fall back to default if theme was removed
return {
colorTheme: 'default' as ColorTheme,
mode: parsed.mode || 'light'
}
} catch {}
}
return {
colorTheme: 'default' as ColorTheme,
mode: window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
}
}
return { colorTheme: 'default', mode: 'light' }
})
useEffect(() => {
const root = document.documentElement
// Set color theme
if (config.colorTheme === 'default') {
root.removeAttribute('data-theme')
} else {
root.setAttribute('data-theme', config.colorTheme)
}
// Set mode
if (config.mode === 'dark') {
root.classList.add('dark')
} else {
root.classList.remove('dark')
}
localStorage.setItem('design-system-theme-config', JSON.stringify(config))
}, [config])
const setColorTheme = (colorTheme: ColorTheme) => setConfig(c => ({ ...c, colorTheme }))
const setMode = (mode: Mode) => setConfig(c => ({ ...c, mode }))
const toggleMode = () => setConfig(c => ({ ...c, mode: c.mode === 'light' ? 'dark' : 'light' }))
return {
colorTheme: config.colorTheme,
mode: config.mode,
setColorTheme,
setMode,
toggleMode,
themes: COLOR_THEMES
}
}
+103
View File
@@ -0,0 +1,103 @@
name: Bug Report
description: Report a bug or unexpected behavior
labels: ["bug", "triage"]
body:
- type: markdown
attributes:
value: |
Thanks for taking the time to report a bug! Please fill out the sections below.
- type: textarea
id: description
attributes:
label: Bug Description
description: A clear and concise description of the bug.
placeholder: What happened?
validations:
required: true
- type: textarea
id: expected
attributes:
label: Expected Behavior
description: What did you expect to happen?
placeholder: What should have happened?
validations:
required: true
- type: textarea
id: reproduce
attributes:
label: Steps to Reproduce
description: Steps to reproduce the behavior.
placeholder: |
1. Run command '...'
2. Click on '...'
3. See error
validations:
required: true
- type: textarea
id: logs
attributes:
label: Error Messages / Logs
description: If applicable, paste any error messages or logs.
render: shell
- type: textarea
id: screenshots
attributes:
label: Screenshots
description: If applicable, add screenshots to help explain the problem.
- type: dropdown
id: component
attributes:
label: Component
description: Which part of Auto Claude is affected?
options:
- Python Backend (auto-claude/)
- Electron UI (auto-claude-ui/)
- Both
- Not sure
validations:
required: true
- type: input
id: version
attributes:
label: Auto Claude Version
description: What version are you running? (check package.json or git tag)
placeholder: "v2.0.1"
- type: dropdown
id: os
attributes:
label: Operating System
options:
- macOS
- Windows
- Linux
- Other
validations:
required: true
- type: input
id: python-version
attributes:
label: Python Version
description: Output of `python --version`
placeholder: "3.12.0"
- type: input
id: node-version
attributes:
label: Node.js Version (for UI issues)
description: Output of `node --version`
placeholder: "20.10.0"
- type: textarea
id: additional
attributes:
label: Additional Context
description: Any other context about the problem.
+8
View File
@@ -0,0 +1,8 @@
blank_issues_enabled: false
contact_links:
- name: Questions & Discussions
url: https://github.com/AndyMik90/Auto-Claude/discussions
about: Ask questions and discuss ideas with the community
- name: Documentation
url: https://github.com/AndyMik90/Auto-Claude#readme
about: Check the documentation before opening an issue
@@ -0,0 +1,70 @@
name: Feature Request
description: Suggest a new feature or enhancement
labels: ["enhancement", "triage"]
body:
- type: markdown
attributes:
value: |
Thanks for suggesting a feature! Please describe your idea below.
- type: textarea
id: problem
attributes:
label: Problem Statement
description: What problem does this feature solve? Is this related to a frustration?
placeholder: I'm always frustrated when...
validations:
required: true
- type: textarea
id: solution
attributes:
label: Proposed Solution
description: Describe the solution you'd like to see.
placeholder: I would like Auto Claude to...
validations:
required: true
- type: textarea
id: alternatives
attributes:
label: Alternatives Considered
description: Have you considered any alternative solutions or workarounds?
placeholder: I've tried...
- type: dropdown
id: component
attributes:
label: Component
description: Which part of Auto Claude would this affect?
options:
- Python Backend (auto-claude/)
- Electron UI (auto-claude-ui/)
- Both
- New component
- Not sure
validations:
required: true
- type: dropdown
id: priority
attributes:
label: How important is this feature to you?
options:
- Nice to have
- Important for my workflow
- Critical / Blocking my use
- type: checkboxes
id: contribution
attributes:
label: Contribution
description: Would you be willing to help implement this?
options:
- label: I'm willing to submit a PR for this feature
- type: textarea
id: additional
attributes:
label: Additional Context
description: Add any other context, mockups, or screenshots about the feature request.
+44
View File
@@ -0,0 +1,44 @@
## Summary
<!-- Brief description of what this PR does -->
## Type of Change
- [ ] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing functionality to change)
- [ ] Documentation update
- [ ] Refactoring (no functional changes)
- [ ] Tests (adding or updating tests)
## Related Issues
<!-- Link any related issues: Fixes #123, Closes #456 -->
## Changes Made
<!-- List the main changes in this PR -->
-
-
-
## Screenshots
<!-- If applicable, add screenshots for UI changes -->
## Checklist
- [ ] I have run `pre-commit run --all-files` and fixed any issues
- [ ] I have added tests for my changes (if applicable)
- [ ] All existing tests pass locally
- [ ] I have updated documentation (if applicable)
- [ ] My code follows the project's code style
## Testing
<!-- Describe how you tested these changes -->
## Additional Notes
<!-- Any additional context or notes for reviewers -->
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 834 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.7 MiB

+83
View File
@@ -0,0 +1,83 @@
name: CI
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
# Python tests
test-python:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ['3.12', '3.13']
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
- name: Install uv
uses: astral-sh/setup-uv@v4
with:
version: "latest"
- name: Install dependencies
working-directory: auto-claude
run: |
uv venv
uv pip install -r requirements.txt
uv pip install -r ../tests/requirements-test.txt
- name: Run tests
working-directory: auto-claude
run: |
source .venv/bin/activate
pytest ../tests/ -v --tb=short -x
- name: Run tests with coverage
if: matrix.python-version == '3.12'
working-directory: auto-claude
run: |
source .venv/bin/activate
pytest ../tests/ -v --cov=. --cov-report=xml --cov-report=term-missing
- name: Upload coverage reports
if: matrix.python-version == '3.12'
uses: codecov/codecov-action@v4
with:
file: ./auto-claude/coverage.xml
fail_ci_if_error: false
env:
CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
# Frontend tests
test-frontend:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
- name: Setup pnpm
uses: pnpm/action-setup@v4
with:
version: 9
- name: Install dependencies
working-directory: auto-claude-ui
run: pnpm install --frozen-lockfile --ignore-scripts
- name: Run tests
working-directory: auto-claude-ui
run: pnpm test
+25
View File
@@ -0,0 +1,25 @@
name: Discord Release Notification
on:
release:
types: [published]
jobs:
discord-notification:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Send to Discord
uses: SethCohen/github-releases-to-discord@v1.19.0
with:
webhook_url: ${{ secrets.DISCORD_WEBHOOK_URL }}
color: "5793266"
username: "Auto Claude Releases"
avatar_url: "https://github.githubassets.com/images/modules/logos_page/GitHub-Mark.png"
footer_title: "Auto Claude Changelog"
footer_timestamp: true
reduce_headings: true
remove_github_reference_links: true
+58
View File
@@ -0,0 +1,58 @@
name: Lint
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
# Python linting
python:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: '3.12'
- name: Install ruff
run: pip install ruff
- name: Run ruff check
run: ruff check auto-claude/ --output-format=github
- name: Run ruff format check
run: ruff format auto-claude/ --check --diff
# TypeScript/React linting
frontend:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
- name: Setup pnpm
uses: pnpm/action-setup@v4
with:
version: 9
- name: Install dependencies
working-directory: auto-claude-ui
run: pnpm install --frozen-lockfile --ignore-scripts
- name: Run ESLint
working-directory: auto-claude-ui
run: pnpm lint
- name: Run TypeScript check
working-directory: auto-claude-ui
run: pnpm typecheck
+66
View File
@@ -0,0 +1,66 @@
name: Test on Tag
on:
push:
tags:
- 'v*'
jobs:
# Python tests
test-python:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ['3.12', '3.13']
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
- name: Install uv
uses: astral-sh/setup-uv@v4
with:
version: "latest"
- name: Install dependencies
working-directory: auto-claude
run: |
uv venv
uv pip install -r requirements.txt
uv pip install -r ../tests/requirements-test.txt
- name: Run tests
working-directory: auto-claude
run: |
source .venv/bin/activate
pytest ../tests/ -v --tb=short
# Frontend tests
test-frontend:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
- name: Setup pnpm
uses: pnpm/action-setup@v4
with:
version: 9
- name: Install dependencies
working-directory: auto-claude-ui
run: pnpm install --frozen-lockfile --ignore-scripts
- name: Run tests
working-directory: auto-claude-ui
run: pnpm test
+14 -3
View File
@@ -2,6 +2,10 @@
.DS_Store
Thumbs.db
# Environment files (contain API keys)
.env
.env.local
# Git worktrees (used by auto-build parallel mode)
.worktrees/
@@ -33,8 +37,8 @@ dist/
downloads/
eggs/
.eggs/
lib/
lib64/
/lib/
/lib64/
parts/
sdist/
var/
@@ -74,4 +78,11 @@ dmypy.json
# Development of Auto Build with Auto Build
dev/
.auto-claude/
.auto-claude/
/docs
_bmad
_bmad-output
.claude
+6
View File
@@ -0,0 +1,6 @@
#!/bin/sh
# Run lint-staged in auto-claude-ui if there are staged files there
if git diff --cached --name-only | grep -q "^auto-claude-ui/"; then
cd auto-claude-ui && pnpm exec lint-staged
fi
+36
View File
@@ -0,0 +1,36 @@
repos:
# Python linting (auto-claude/)
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.8.3
hooks:
- id: ruff
args: [--fix]
files: ^auto-claude/
- id: ruff-format
files: ^auto-claude/
# Frontend linting (auto-claude-ui/)
- repo: local
hooks:
- id: eslint
name: ESLint
entry: bash -c 'cd auto-claude-ui && pnpm lint'
language: system
files: ^auto-claude-ui/.*\.(ts|tsx|js|jsx)$
pass_filenames: false
- id: typecheck
name: TypeScript Check
entry: bash -c 'cd auto-claude-ui && pnpm typecheck'
language: system
files: ^auto-claude-ui/.*\.(ts|tsx)$
pass_filenames: false
# General checks
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v5.0.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: check-yaml
- id: check-added-large-files
+310
View File
@@ -0,0 +1,310 @@
## 2.3.2 - UI Polish & Build Improvements
### 🛠️ Improvements
- Restructured SortableFeatureCard badge layout for improved visual presentation
Bug Fixes:
- Fixed spec runner path configuration for more reliable task execution
---
## What's Changed
- fix: fix to spec runner paths by @AndyMik90 in 9babdc2
- feat: auto-claude: subtask-1-1 - Restructure SortableFeatureCard badge layout by @AndyMik90 in dc886dc
## 2.3.1 - Linux Compatibility Fix
### 🐛 Bug Fixes
- Resolved path handling issues on Linux systems for improved cross-platform compatibility
---
## What's Changed
- fix: Fix to linux path issue by @AndyMik90 in 3276034
## 2.2.0 - 2025-12-17
### ✨ New Features
- Add usage monitoring with profile swap detection to prevent cascading resource issues
- Option to stash changes before merge operations for safer branch integration
- Add hideCloseButton prop to DialogContent component for improved UI flexibility
### 🛠️ Improvements
- Enhance AgentManager to manage task context cleanup and preserve swapCount on restarts
- Improve changelog feature with version tracking, markdown/preview, and persistent styling options
- Refactor merge conflict handling to use branch names instead of commit hashes for better clarity
- Streamline usage monitoring logic by removing unnecessary dynamic imports
- Better handling of lock files during merge conflicts
- Refactor code for improved readability and maintainability
- Refactor IdeationHeader and update handleDeleteSelected logic
### 🐛 Bug Fixes
- Fix worktree merge logic to correctly handle branch operations
- Fix spec_runner.py path resolution after move to runners/ directory
- Fix Discord release webhook failing on large changelogs
- Fix branch logic for merge AI operations
- Hotfix for spec-runner path location
---
## What's Changed
- fix: hotfix/spec-runner path location by @AndyMik90 in f201f7e
- refactor: Remove unnecessary dynamic imports of getUsageMonitor in terminal-handlers.ts to streamline usage monitoring logic by @AndyMik90 in 0da4bc4
- feat: Improve changelog feature, version tracking, markdown/preview, persistent styling options by @AndyMik90 in a0d142b
- refactor: Refactor code for improved readability and maintainability by @AndyMik90 in 473b045
- feat: Enhance AgentManager to manage task context cleanup and preserve swapCount on restarts. Update UsageMonitor to delay profile usage checks to prevent cascading swaps by @AndyMik90 in e5b9488
- feat: Usage-monitoring by @AndyMik90 in de33b2c
- feat: option to stash changes before merge by @AndyMik90 in 7e09739
- refactor: Refactor merge conflict check to use branch names instead of commit hashes by @AndyMik90 in e6d6cea
- fix: worktree merge logic by @AndyMik90 in dfb5cf9
- test: Sign off - all verification passed by @AndyMik90 in 34631c3
- feat: Pass hideCloseButton={showFileExplorer} to DialogContent by @AndyMik90 in 7c327ed
- feat: Add hideCloseButton prop to DialogContent component by @AndyMik90 in 5f9653a
- fix: branch logic for merge AI by @AndyMik90 in 2d2a813
- fix: spec_runner.py path resolution after move to runners/ directory by @AndyMik90 in ce9c2cd
- refactor: Better handling of lock files during merge conflicts by @AndyMik90 in 460c76d
- fix: Discord release webhook failing on large changelogs by @AndyMik90 in 4eb66f5
- chore: Update CHANGELOG with new features, improvements, bug fixes, and other changes by @AndyMik90 in 788b8d0
- refactor: Enhance merge conflict handling by excluding lock files by @AndyMik90 in 957746e
- refactor: Refactor IdeationHeader and update handleDeleteSelected logic by @AndyMik90 in 36338f3
## What's New
### ✨ New Features
- Added GitHub OAuth integration for seamless authentication
- Implemented roadmap feature management with kanban board and drag-and-drop support
- Added ability to select AI model during task creation with agent profiles
- Introduced file explorer integration and referenced files section in task creation wizard
- Added .gitignore entry management during project initialization
- Created comprehensive onboarding wizard with OAuth configuration, Graphiti setup, and first spec guidance
- Introduced Electron MCP for debugging and validation support
- Added BMM workflow status tracking and project scan reporting
### 🛠️ Improvements
- Refactored IdeationHeader component and improved deleteSelected logic
- Refactored backend for upcoming features with improved architecture
- Enhanced RouteDetector to exclude specific directories from route detection
- Improved merge conflict resolution with parallel processing and AI-assisted resolution
- Optimized merge conflict resolution performance and context sending
- Refactored AI resolver to use async context manager and Claude SDK patterns
- Enhanced merge orchestrator logic and frontend UX for conflict handling
- Refactored components for better maintainability and faster development
- Refactored changelog formatter for GitHub Release compatibility
- Enhanced onboarding wizard completion logic and step progression
- Updated README to clarify Auto Claude's role as an AI coding companion
### 🐛 Bug Fixes
- Fixed GraphitiStep TypeScript compilation error
- Added missing onRerunWizard prop to AppSettingsDialog
- Improved merge lock file conflict handling
### 🔧 Other Changes
- Removed .auto-claude and _bmad-output from git tracking (already in .gitignore)
- Updated Python versions in CI workflows
- General linting improvements and code cleanup
---
## What's Changed
- feat: New github oauth integration by @AndyMik90 in afeb54f
- feat: Implement roadmap feature management kanban with drag-and-drop support by @AndyMik90 in 9403230
- feat: Agent profiles, be able to select model on task creation by @AndyMik90 in d735c5c
- feat: Add Referenced Files Section and File Explorer Integration in Task Creation Wizard by @AndyMik90 in 31e4e87
- feat: Add functionality to manage .gitignore entries during project initialization by @AndyMik90 in 2ac00a9
- feat: Introduce electron mcp for electron debugging/validation by @AndyMik90 in 3eb2ead
- feat: Add BMM workflow status tracking and project scan report by @AndyMik90 in 7f6456f
- refactor: Refactor IdeationHeader and update handleDeleteSelected logic by @AndyMik90 in 36338f3
- refactor: Big backend refactor for upcoming features by @AndyMik90 in 11fcdf4
- refactor: Refactoring for better codebase by @AndyMik90 in feb0d4e
- refactor: Refactor Roadmap component to utilize RoadmapGenerationProgress for better status display by @AndyMik90 in d8e5784
- refactor: refactoring components for better future maintence and more rapid coding by @AndyMik90 in 131ec4c
- refactor: Enhance RouteDetector to exclude specific directories from route detection by @AndyMik90 in 08dc24c
- refactor: Update AI resolver to use Claude Opus model and improve error logging by @AndyMik90 in 1d830ba
- refactor: Use claude sdk pattern for ai resolver by @AndyMik90 in 4bba9d1
- refactor: Refactor AI resolver to use async context manager for client connection by @AndyMik90 in 579ea40
- refactor: Update changelog formatter for GitHub Release compatibility by @AndyMik90 in 3b832db
- refactor: Enhance onboarding wizard completion logic by @AndyMik90 in 7c01638
- refactor: Update GraphitiStep to proceed to the next step after successful configuration save by @AndyMik90 in a5a1eb1
- fix: Add onRerunWizard prop to AppSettingsDialog (qa-requested) by @AndyMik90 in 6b5b714
- fix: Add first-run detection to App.tsx by @AndyMik90 in 779e36f
- fix: Add TypeScript compilation check - fix GraphitiStep type error by @AndyMik90 in f90fa80
- improve: ideation improvements and linting by @AndyMik90 in 36a69fc
- improve: improve merge conflicts for lock files by @AndyMik90 in a891225
- improve: Roadmap competitor analysis by @AndyMik90 in ddf47ae
- improve: parallell merge conflict resolution by @AndyMik90 in f00aa33
- improve: improvement to speed of merge conflict resolution by @AndyMik90 in 56ff586
- improve: improve context sending to merge agent by @AndyMik90 in e409ae8
- improve: better conflict handling in the frontend app for merge contlicts (better UX) by @AndyMik90 in 65937e1
- improve: resolve claude agent sdk by @AndyMik90 in 901e83a
- improve: Getting ready for BMAD integration by @AndyMik90 in b94eb65
- improve: Enhance AI resolver and debugging output by @AndyMik90 in bf787ad
- improve: Integrate profile environment for OAuth token in task handlers by @AndyMik90 in 01e801a
- chore: Remove .auto-claude from tracking (already in .gitignore) by @AndyMik90 in 87f353c
- chore: Update Python versions in CI workflows by @AndyMik90 in 43a338c
- chore: Linting gods pleased now? by @AndyMik90 in 6aea4bb
- chore: Linting and test fixes by @AndyMik90 in 140f11f
- chore: Remove _bmad-output from git tracking by @AndyMik90 in 4cd7500
- chore: Add _bmad-output to .gitignore by @AndyMik90 in dbe27f0
- chore: Linting gods are happy by @AndyMik90 in 3fc1592
- chore: Getting ready for the lint gods by @AndyMik90 in 142cd67
- chore: CLI testing/linting by @AndyMik90 in d8ad17d
- chore: CLI and tests by @AndyMik90 in 9a59b7e
- chore: Update implementation_plan.json - fixes applied by @AndyMik90 in 555a46f
- chore: Update parallel merge conflict resolution metrics in workspace.py by @AndyMik90 in 2e151ac
- chore: merge logic v0.3 by @AndyMik90 in c5d33cd
- chore: merge orcehestrator logic by @AndyMik90 in e8b6669
- chore: Merge-orchestrator by @AndyMik90 in d8ba532
- chore: merge orcehstrator logic by @AndyMik90 in e8b6669
- chore: Electron UI fix for merge orcehstrator by @AndyMik90 in e08ab62
- chore: Frontend lints by @AndyMik90 in 488bbfa
- docs: Revise README.md to enhance clarity and focus on Auto Claude's capabilities by @AndyMik90 in f9ef7ea
- qa: Sign off - all verification passed by @AndyMik90 in b3f4803
- qa: Rejected - fixes required by @AndyMik90 in 5e56890
- qa: subtask-6-2 - Run existing tests to verify no regressions by @AndyMik90 in 5f989a4
- qa: subtask-5-2 - Enhance OAuthStep to detect and display if token is already configured by @AndyMik90 in 50f22da
- qa: subtask-5-1 - Add settings migration logic - set onboardingCompleted by @AndyMik90 in f57c28e
- qa: subtask-4-1 - Add 'Re-run Wizard' button to AppSettings navigation by @AndyMik90 in 9144e7f
- qa: subtask-3-1 - Add first-run detection to App.tsx by @AndyMik90 in 779e36f
- qa: subtask-2-8 - Create index.ts barrel export for onboarding components by @AndyMik90 in b0af2dc
- qa: subtask-2-7 - Create OnboardingWizard component by @AndyMik90 in 3de8928
- qa: subtask-2-6 - Create CompletionStep component - success message by @AndyMik90 in aa0f608
- qa: subtask-2-5 - Create FirstSpecStep component - guided first spec by @AndyMik90 in 32f17a1
- qa: subtask-2-4 - Create GraphitiStep component - optional Graphiti/FalkorDB configuration by @AndyMik90 in 61184b0
- qa: subtask-2-3 - Create OAuthStep component - Claude OAuth token configuration step by @AndyMik90 in 79d622e
- qa: subtask-2-2 - Create WelcomeStep component by @AndyMik90 in a97f697
- qa: subtask-2-1 - Create WizardProgress component - step progress indicator by @AndyMik90 in b6e604c
- qa: subtask-1-2 - Add onboardingCompleted to DEFAULT_APP_SETTINGS by @AndyMik90 in c5a0331
- qa: subtask-1-1 - Add onboardingCompleted to AppSettings type interface by @AndyMik90 in 7c24b48
- chore: Version 2.0.1 by @AndyMik90 in 4b242c4
- test: Merge-orchestrator by @AndyMik90 in d8ba532
- test: test for ai merge AI by @AndyMik90 in 9d9cf16
## What's New in 2.0.1
### 🚀 New Features
- **Update Check with Release URLs**: Enhanced update checking functionality to include release URLs, allowing users to easily access release information
- **Markdown Renderer for Release Notes**: Added markdown renderer in advanced settings to properly display formatted release notes
- **Terminal Name Generator**: New feature for generating terminal names
### 🔧 Improvements
- **LLM Provider Naming**: Updated project settings to reflect new LLM provider name
- **IPC Handlers**: Improved IPC handlers for external link management
- **UI Simplification**: Refactored App component to simplify project selection display by removing unnecessary wrapper elements
- **Docker Infrastructure**: Updated FalkorDB service container naming in docker-compose configuration
- **Documentation**: Improved README with dedicated CLI documentation and infrastructure status information
### 📚 Documentation
- Enhanced README with comprehensive CLI documentation and setup instructions
- Added Docker infrastructure status documentation
## What's New in v2.0.0
### New Features
- **Task Integration**: Connected ideas to tasks with "Go to Task" functionality across the UI
- **File Explorer Panel**: Implemented file explorer panel with directory listing capabilities
- **Terminal Task Selection**: Added task selection dropdown in terminal with auto-context loading
- **Task Archiving**: Introduced task archiving functionality
- **Graphiti MCP Server Integration**: Added support for Graphiti memory integration
- **Roadmap Functionality**: New roadmap visualization and management features
### Improvements
- **File Tree Virtualization**: Refactored FileTree component to use efficient virtualization for improved performance with large file structures
- **Agent Parallelization**: Improved Claude Code agent decision-making for parallel task execution
- **Terminal Experience**: Enhanced terminal with task features and visual feedback for better user experience
- **Python Environment Detection**: Auto-detect Python environment readiness before task execution
- **Version System**: Cleaner version management system
- **Project Initialization**: Simpler project initialization process
### Bug Fixes
- Fixed project settings bug
- Fixed insight UI sidebar
- Resolved Kanban and terminal integration issues
### Changed
- Updated project-store.ts to use proper Dirent type for specDirs variable
- Refactored codebase for better code quality
- Removed worktree-worker logic in favor of Claude Code's internal agent system
- Removed obsolete security configuration file (.auto-claude-security.json)
### Documentation
- Added CONTRIBUTING.md with development guidelines
## What's New in v1.1.0
### New Features
- **Follow-up Tasks**: Continue working on completed specs by adding new tasks to existing implementations. The system automatically re-enters planning mode and integrates with your existing documentation and context.
- **Screenshot Support for Feedback**: Attach screenshots to your change requests when reviewing tasks, providing visual context for your feedback alongside text comments.
- **Unified Task Editing**: The Edit Task dialog now includes all the same options as the New Task dialog—classification metadata, image attachments, and review settings—giving you full control when modifying tasks.
### Improvements
- **Enhanced Kanban Board**: Improved visual design and interaction patterns for task cards, making it easier to scan status, understand progress, and work with tasks efficiently.
- **Screenshot Handling**: Paste screenshots directly into task descriptions using Ctrl+V (Cmd+V on Mac) for faster documentation.
- **Draft Auto-Save**: Task creation state is now automatically saved when you navigate away, preventing accidental loss of work-in-progress.
### Bug Fixes
- Fixed task editing to support the same comprehensive options available in new task creation
+37 -38
View File
@@ -33,9 +33,6 @@ python auto-claude/spec_runner.py --task "Fix button" --complexity simple
# Run autonomous build
python auto-claude/run.py --spec 001
# Run with parallel workers
python auto-claude/run.py --spec 001 --parallel 2
# List all specs
python auto-claude/run.py --list
```
@@ -63,17 +60,20 @@ python auto-claude/run.py --spec 001 --qa-status
### Testing
```bash
# Run all tests
pytest tests/ -v
# Install test dependencies (required first time)
cd auto-claude && uv pip install -r ../tests/requirements-test.txt
# Run all tests (use virtual environment pytest)
auto-claude/.venv/bin/pytest tests/ -v
# Run single test file
pytest tests/test_security.py -v
auto-claude/.venv/bin/pytest tests/test_security.py -v
# Run specific test
pytest tests/test_security.py::test_bash_command_validation -v
auto-claude/.venv/bin/pytest tests/test_security.py::test_bash_command_validation -v
# Skip slow tests
pytest tests/ -m "not slow"
auto-claude/.venv/bin/pytest tests/ -m "not slow"
```
### Spec Validation
@@ -91,8 +91,8 @@ python auto-claude/validate_spec.py --spec-dir auto-claude/specs/001-feature --c
- COMPLEX (8 phases): Full pipeline with Research and Self-Critique phases
**Implementation (run.py → agent.py)** - Multi-session build:
1. Planner Agent creates chunk-based implementation plan
2. Coder Agent implements chunks one-by-one
1. Planner Agent creates subtask-based implementation plan
2. Coder Agent implements subtasks (can spawn subagents for parallel work)
3. QA Reviewer validates acceptance criteria
4. QA Fixer resolves issues in a loop
@@ -100,8 +100,7 @@ python auto-claude/validate_spec.py --spec-dir auto-claude/specs/001-feature --c
- **client.py** - Claude SDK client with security hooks and tool permissions
- **security.py** + **project_analyzer.py** - Dynamic command allowlisting based on detected project stack
- **worktree.py** - Git worktree isolation for safe parallel builds
- **coordinator.py** - Parallel execution coordinator
- **worktree.py** - Git worktree isolation for safe feature development
- **memory.py** - File-based session memory (primary, always-available storage)
- **graphiti_memory.py** - Optional graph-based cross-session memory with semantic search
- **graphiti_providers.py** - Multi-provider factory for Graphiti (OpenAI, Anthropic, Azure, Ollama)
@@ -112,9 +111,9 @@ python auto-claude/validate_spec.py --spec-dir auto-claude/specs/001-feature --c
| Prompt | Purpose |
|--------|---------|
| planner.md | Creates implementation plan with chunks |
| coder.md | Implements individual chunks |
| coder_recovery.md | Recovers from stuck/failed chunks |
| planner.md | Creates implementation plan with subtasks |
| coder.md | Implements individual subtasks |
| coder_recovery.md | Recovers from stuck/failed subtasks |
| qa_reviewer.md | Validates acceptance criteria |
| qa_fixer.md | Fixes QA-reported issues |
| spec_gatherer.md | Collects user requirements |
@@ -129,7 +128,7 @@ Each spec in `auto-claude/specs/XXX-name/` contains:
- `spec.md` - Feature specification
- `requirements.json` - Structured user requirements
- `context.json` - Discovered codebase context
- `implementation_plan.json` - Chunk-based plan with status tracking
- `implementation_plan.json` - Subtask-based plan with status tracking
- `qa_report.md` - QA validation results
- `QA_FIX_REQUEST.md` - Issues to fix (when rejected)
@@ -137,32 +136,22 @@ Each spec in `auto-claude/specs/XXX-name/` contains:
Auto Claude uses git worktrees for isolated builds. All branches stay LOCAL until user explicitly pushes:
**Single Worker Mode:**
```
main (user's branch)
└── auto-claude/{spec-name} ← staging branch (isolated worktree)
```
**Parallel Worker Mode:**
```
main (user's branch)
└── auto-claude/{spec-name} ← staging branch (accumulates all work)
├── worker-1/{chunk-id} ← temporary (merges to staging, then deleted)
├── worker-2/{chunk-id} ← temporary (merges to staging, then deleted)
└── worker-3/{chunk-id} ← temporary (merges to staging, then deleted)
└── auto-claude/{spec-name} ← spec branch (isolated worktree)
```
**Key principles:**
- ONE unified staging branch per spec (`auto-claude/{spec-name}`)
- Worker branches are temporary and LOCAL only
- ONE branch per spec (`auto-claude/{spec-name}`)
- Parallel work uses subagents (agent decides when to spawn)
- NO automatic pushes to GitHub - user controls when to push
- User reviews in staging worktree (`.worktrees/auto-claude/`)
- Final merge: staging → main (after user approval)
- User reviews in spec worktree (`.worktrees/{spec-name}/`)
- Final merge: spec branch → main (after user approval)
**Workflow:**
1. Build runs in isolated worktree on staging branch
2. Parallel workers create temp branches, merge to staging, then delete
3. User tests feature in `.worktrees/auto-claude/`
1. Build runs in isolated worktree on spec branch
2. Agent implements subtasks (can spawn subagents for parallel work)
3. User tests feature in `.worktrees/{spec-name}/`
4. User runs `--merge` to add to their project
5. User pushes to remote when ready
@@ -193,10 +182,20 @@ Dual-layer memory architecture:
Enable with: `GRAPHITI_ENABLED=true` + provider credentials. See `.env.example`.
## Development Mode
## Project Structure
Use `--dev` flag to work in `dev/auto-claude/specs/` (gitignored) when developing the framework itself:
Auto Claude can be used in two ways:
**As a standalone CLI tool** (original project):
```bash
python auto-claude/spec_runner.py --dev --task "Test feature"
python auto-claude/run.py --dev --spec 001
python auto-claude/run.py --spec 001
```
**With the optional Electron frontend** (`auto-claude-ui/`):
- Provides a GUI for task management and progress tracking
- Wraps the CLI commands - the backend works independently
**Directory layout:**
- `auto-claude/` - Python backend/CLI (the framework code)
- `auto-claude-ui/` - Optional Electron frontend
- `.auto-claude/specs/` - Per-project data (specs, plans, QA reports) - gitignored
+427
View File
@@ -0,0 +1,427 @@
# Contributing to Auto Claude
Thank you for your interest in contributing to Auto Claude! This document provides guidelines and instructions for contributing to the project.
## Table of Contents
- [Prerequisites](#prerequisites)
- [Development Setup](#development-setup)
- [Python Backend](#python-backend)
- [Electron Frontend](#electron-frontend)
- [Pre-commit Hooks](#pre-commit-hooks)
- [Code Style](#code-style)
- [Testing](#testing)
- [Continuous Integration](#continuous-integration)
- [Git Workflow](#git-workflow)
- [Branch Naming](#branch-naming)
- [Commit Messages](#commit-messages)
- [Pull Request Process](#pull-request-process)
- [Issue Reporting](#issue-reporting)
- [Architecture Overview](#architecture-overview)
## Prerequisites
Before contributing, ensure you have the following installed:
- **Python 3.8+** - For the backend framework
- **Node.js 18+** - For the Electron frontend
- **pnpm** - Package manager for the frontend (`npm install -g pnpm`)
- **uv** (recommended) or **pip** - Python package manager
- **Git** - Version control
- **Docker** (optional) - For running FalkorDB if using Graphiti memory
## Development Setup
The project consists of two main components:
1. **Python Backend** (`auto-claude/`) - The core autonomous coding framework
2. **Electron Frontend** (`auto-claude-ui/`) - Optional desktop UI
### Python Backend
```bash
# Navigate to the auto-claude directory
cd auto-claude
# Create virtual environment (using uv - recommended)
uv venv
source .venv/bin/activate # On Windows: .venv\Scripts\activate
uv pip install -r requirements.txt
# Or using standard Python
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
# Install test dependencies
pip install -r ../tests/requirements-test.txt
# Set up environment
cp .env.example .env
# Edit .env and add your CLAUDE_CODE_OAUTH_TOKEN (get it via: claude setup-token)
```
### Electron Frontend
```bash
# Navigate to the UI directory
cd auto-claude-ui
# Install dependencies
pnpm install
# Start development server
pnpm dev
# Build for production
pnpm build
# Package for distribution
pnpm package
```
## Pre-commit Hooks
We use [pre-commit](https://pre-commit.com/) to run linting and formatting checks before each commit. This ensures code quality and consistency across the project.
### Setup
```bash
# Install pre-commit
pip install pre-commit
# Install the git hooks (run once after cloning)
pre-commit install
```
### What Runs on Commit
When you commit, the following checks run automatically:
| Check | Scope | Description |
|-------|-------|-------------|
| **ruff** | `auto-claude/` | Python linter with auto-fix |
| **ruff-format** | `auto-claude/` | Python code formatter |
| **eslint** | `auto-claude-ui/` | TypeScript/React linter |
| **typecheck** | `auto-claude-ui/` | TypeScript type checking |
| **trailing-whitespace** | All files | Removes trailing whitespace |
| **end-of-file-fixer** | All files | Ensures files end with newline |
| **check-yaml** | All files | Validates YAML syntax |
| **check-added-large-files** | All files | Prevents large file commits |
### Running Manually
```bash
# Run all checks on all files
pre-commit run --all-files
# Run a specific hook
pre-commit run ruff --all-files
# Skip hooks temporarily (not recommended)
git commit --no-verify -m "message"
```
### If a Check Fails
1. **Ruff auto-fixes**: Some issues are fixed automatically. Stage the changes and commit again.
2. **ESLint errors**: Fix the reported issues in your code.
3. **Type errors**: Resolve TypeScript type issues before committing.
## Code Style
### Python
- Follow PEP 8 style guidelines
- Use type hints for function signatures
- Use docstrings for public functions and classes
- Keep functions focused and under 50 lines when possible
- Use meaningful variable and function names
```python
# Good
def get_next_chunk(spec_dir: Path) -> dict | None:
"""
Find the next pending chunk in the implementation plan.
Args:
spec_dir: Path to the spec directory
Returns:
The next chunk dict or None if all chunks are complete
"""
...
# Avoid
def gnc(sd):
...
```
### TypeScript/React
- Use TypeScript strict mode
- Follow the existing component patterns in `auto-claude-ui/src/`
- Use functional components with hooks
- Prefer named exports over default exports
- Use the UI components from `src/renderer/components/ui/`
```typescript
// Good
export function TaskCard({ task, onEdit }: TaskCardProps) {
const [isEditing, setIsEditing] = useState(false);
...
}
// Avoid
export default function(props) {
...
}
```
### General
- No trailing whitespace
- Use 2 spaces for indentation in TypeScript/JSON, 4 spaces in Python
- End files with a newline
- Keep line length under 100 characters when practical
## Testing
### Python Tests
```bash
# Run all tests
pytest tests/ -v
# Run a specific test file
pytest tests/test_security.py -v
# Run a specific test
pytest tests/test_security.py::test_bash_command_validation -v
# Skip slow tests
pytest tests/ -m "not slow"
# Run with coverage
pytest tests/ --cov=auto-claude --cov-report=html
```
Test configuration is in `tests/pytest.ini`.
### Frontend Tests
```bash
cd auto-claude-ui
# Run unit tests
pnpm test
# Run tests in watch mode
pnpm test:watch
# Run with coverage
pnpm test:coverage
# Run E2E tests (requires built app)
pnpm build
pnpm test:e2e
# Run linting
pnpm lint
# Run type checking
pnpm typecheck
```
### Testing Requirements
Before submitting a PR:
1. **All existing tests must pass**
2. **New features should include tests**
3. **Bug fixes should include a regression test**
4. **Test coverage should not decrease significantly**
## Continuous Integration
All pull requests and pushes to `main` trigger automated CI checks via GitHub Actions.
### Workflows
| Workflow | Trigger | What it checks |
|----------|---------|----------------|
| **CI** | Push to `main`, PRs | Python tests (3.11 & 3.12), Frontend tests |
| **Lint** | Push to `main`, PRs | Ruff (Python), ESLint + TypeScript (Frontend) |
| **Test on Tag** | Version tags (`v*`) | Full test suite before release |
### PR Requirements
Before a PR can be merged:
1. All CI checks must pass (green checkmarks)
2. Python tests pass on both Python 3.11 and 3.12
3. Frontend tests pass
4. Linting passes (no ruff or eslint errors)
5. TypeScript type checking passes
### Running CI Checks Locally
```bash
# Python tests
cd auto-claude
source .venv/bin/activate
pytest ../tests/ -v
# Frontend tests
cd auto-claude-ui
pnpm test
pnpm lint
pnpm typecheck
```
## Git Workflow
### Branch Naming
Use descriptive branch names with a prefix indicating the type of change:
| Prefix | Purpose | Example |
|--------|---------|---------|
| `feature/` | New feature | `feature/add-dark-mode` |
| `fix/` | Bug fix | `fix/memory-leak-in-worker` |
| `docs/` | Documentation | `docs/update-readme` |
| `refactor/` | Code refactoring | `refactor/simplify-auth-flow` |
| `test/` | Test additions/fixes | `test/add-integration-tests` |
| `chore/` | Maintenance tasks | `chore/update-dependencies` |
### Commit Messages
Write clear, concise commit messages that explain the "why" behind changes:
```bash
# Good
git commit -m "Add retry logic for failed API calls
Implements exponential backoff for transient failures.
Fixes #123"
# Avoid
git commit -m "fix stuff"
git commit -m "WIP"
```
**Format:**
```
<type>: <subject>
<body>
<footer>
```
- **type**: feat, fix, docs, style, refactor, test, chore
- **subject**: Short description (50 chars max, imperative mood)
- **body**: Detailed explanation if needed (wrap at 72 chars)
- **footer**: Reference issues, breaking changes
## Pull Request Process
1. **Fork the repository** and create your branch from `main`
2. **Make your changes** following the code style guidelines
3. **Test thoroughly**:
```bash
# Python
pytest tests/ -v
# Frontend
cd auto-claude-ui && pnpm test && pnpm lint && pnpm typecheck
```
4. **Update documentation** if your changes affect:
- Public APIs
- Configuration options
- User-facing behavior
5. **Create the Pull Request**:
- Use a clear, descriptive title
- Reference any related issues
- Describe what changes you made and why
- Include screenshots for UI changes
- List any breaking changes
6. **PR Title Format**:
```
<type>: <description>
```
Examples:
- `feat: Add support for custom prompts`
- `fix: Resolve memory leak in worker process`
- `docs: Update installation instructions`
7. **Review Process**:
- Address reviewer feedback promptly
- Keep the PR focused on a single concern
- Squash commits if requested
## Issue Reporting
### Bug Reports
When reporting a bug, include:
1. **Clear title** describing the issue
2. **Environment details**:
- OS and version
- Python version
- Node.js version (for UI issues)
- Auto Claude version
3. **Steps to reproduce** the issue
4. **Expected behavior** vs **actual behavior**
5. **Error messages** or logs (if applicable)
6. **Screenshots** (for UI issues)
### Feature Requests
When requesting a feature:
1. **Describe the problem** you're trying to solve
2. **Explain your proposed solution**
3. **Consider alternatives** you've thought about
4. **Provide context** on your use case
## Architecture Overview
Auto Claude consists of two main parts:
### Python Backend (`auto-claude/`)
The core autonomous coding framework:
- **Entry Points**: `run.py` (build runner), `spec_runner.py` (spec creator)
- **Agent System**: `agent.py`, `client.py`, `prompts/`
- **Execution**: `coordinator.py` (parallel), `worktree.py` (isolation)
- **Memory**: `memory.py` (file-based), `graphiti_memory.py` (graph-based)
- **QA**: `qa_loop.py`, `prompts/qa_*.md`
### Electron Frontend (`auto-claude-ui/`)
Optional desktop interface:
- **Main Process**: `src/main/` - Electron main process, IPC handlers
- **Renderer**: `src/renderer/` - React UI components
- **Shared**: `src/shared/` - Types and utilities
For detailed architecture information, see [CLAUDE.md](CLAUDE.md).
---
## Questions?
If you have questions about contributing, feel free to:
1. Open a GitHub issue with the `question` label
2. Review existing issues and discussions
Thank you for contributing to Auto Claude!
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+225 -318
View File
@@ -1,49 +1,87 @@
# Auto Claude
A production-ready framework for autonomous multi-session AI coding. Build complete applications or add features to existing projects through coordinated AI agent sessions.
Your AI coding companion. Build features, fix bugs, and ship faster — with autonomous agents that plan, code, and validate for you.
## What It Does
![Auto Claude Kanban Board](.github/assets/Auto-Claude-Kanban.png)
Auto Claude uses a **multi-agent pattern** to build software autonomously:
[![Discord](https://img.shields.io/badge/Discord-Join%20Community-5865F2?style=for-the-badge&logo=discord&logoColor=white)](https://discord.gg/maj9EWmY)
### Spec Creation Pipeline (8 phases)
1. **Discovery** - Analyzes project structure
2. **Requirements Gatherer** - Collects user requirements interactively
3. **Research Agent** - Validates external integrations against documentation
4. **Context Discovery** - Finds relevant files in codebase
5. **Spec Writer** - Creates comprehensive spec.md
6. **Spec Critic** - Uses ultrathink to find and fix issues before implementation
7. **Planner** - Creates chunk-based implementation plan
8. **Validation** - Ensures all outputs are valid
## What It Does ✨
### Implementation Pipeline
1. **Planner Agent** (Session 1) - Analyzes spec, creates chunk-based implementation plan
2. **Coder Agent** (Sessions 2+) - Implements chunks one-by-one with verification
3. **QA Reviewer Agent** - Validates all acceptance criteria before sign-off
4. **QA Fixer Agent** - Fixes issues found by QA in a self-validating loop
**Auto Claude is a desktop app that supercharges your AI coding workflow.** Whether you're a vibe coder just getting started or an experienced developer, Auto Claude meets you where you are.
Each session runs with a fresh context window. Progress is tracked via `implementation_plan.json` and Git commits.
- **Autonomous Tasks** — Describe what you want to build, and agents handle planning, coding, and validation while you focus on other work
- **Agent Terminals** — Run Claude Code in up to 12 terminals with a clean layout, smart naming based on context, and one-click task context injection
- **Safe by Default** — All work happens in git worktrees, keeping your main branch undisturbed until you're ready to merge
- **Self-Validating** — Built-in QA agents check their own work before you review
## Quick Start
**The result?** 10x your output while maintaining code quality.
## Key Features
- **Parallel Agents**: Run multiple builds simultaneously while you focus on other work
- **Context Engineering**: Agents understand your codebase structure before writing code
- **Self-Validating**: Built-in QA loop catches issues before you review
- **Isolated Workspaces**: All work happens in git worktrees — your code stays safe
- **AI Merge Resolution**: Intelligent conflict resolution when merging back to main — no manual conflict fixing
- **Memory Layer**: Agents remember insights across sessions for smarter decisions
- **Cross-Platform**: Desktop app runs on Mac, Windows, and Linux
- **Any Project Type**: Build web apps, APIs, CLIs — works with any software project
## 🚀 Quick Start (Desktop UI)
The Desktop UI is the recommended way to use Auto Claude. It provides visual task management, real-time progress tracking, and a Kanban board interface.
### Prerequisites
- Python 3.8+
- Claude Code CLI (`npm install -g @anthropic-ai/claude-code`)
1. **Node.js 18+** - [Download Node.js](https://nodejs.org/)
2. **Python 3.9+** - [Download Python](https://www.python.org/downloads/)
3. **Docker Desktop** - Required for the Memory Layer
4. **Claude Code CLI** - `npm install -g @anthropic-ai/claude-code`
5. **Claude Subscription** - Requires [Claude Pro or Max](https://claude.ai/upgrade) for Claude Code access
6. **Git Repository** - Your project must be initialized as a git repository
### Setup
### Git Initialization
**Step 1:** Copy the `auto-claude` folder into your project
```bash
# Copy the auto-claude folder to your project root
cp -r auto-claude /path/to/your/project/
```
**Step 2:** Set up Python environment
**Auto Claude requires a git repository** to create isolated worktrees for safe parallel development. If your project isn't a git repo yet:
```bash
cd your-project
git init
git add .
git commit -m "Initial commit"
```
> **Why git?** Auto Claude uses git branches and worktrees to isolate each task in its own workspace, keeping your main branch clean until you're ready to merge. This allows you to work on multiple features simultaneously without conflicts.
---
### Installing Docker Desktop
Docker runs the FalkorDB database that powers Auto Claude's cross-session memory.
| Operating System | Download Link |
|------------------|---------------|
| **Mac (Apple Silicon M1/M2/M3/M4)** | [Download for Apple Chip](https://desktop.docker.com/mac/main/arm64/Docker.dmg) |
| **Mac (Intel)** | [Download for Intel Chip](https://desktop.docker.com/mac/main/amd64/Docker.dmg) |
| **Windows** | [Download for Windows](https://desktop.docker.com/win/main/amd64/Docker%20Desktop%20Installer.exe) |
| **Linux** | [Installation Guide](https://docs.docker.com/desktop/install/linux-install/) |
> **Not sure which Mac?** Click the Apple menu (🍎) → "About This Mac". Look for "Chip" - M1/M2/M3/M4 = Apple Silicon, otherwise Intel.
**After installing:** Open Docker Desktop and wait for the whale icon (🐳) to appear in your menu bar/system tray.
> **Using the Desktop UI?** It automatically detects Docker status and offers one-click FalkorDB setup. No terminal commands needed!
📚 **For detailed installation steps, troubleshooting, and advanced configuration, see [guides/DOCKER-SETUP.md](guides/DOCKER-SETUP.md)**
---
### Step 1: Set Up the Python Backend
The Desktop UI runs Python scripts behind the scenes. Set up the Python environment:
```bash
cd auto-claude
# Using uv (recommended)
@@ -53,373 +91,231 @@ uv venv && uv pip install -r requirements.txt
python3 -m venv .venv && source .venv/bin/activate && pip install -r requirements.txt
```
**Step 3:** Configure environment
### Step 2: Start the Memory Layer
The Auto Claude Memory Layer provides cross-session context retention using a graph database:
```bash
cp .env.example .env
# Get your OAuth token
claude setup-token
# Add the token to .env
# CLAUDE_CODE_OAUTH_TOKEN=your-token-here
# Make sure Docker Desktop is running, then:
docker-compose up -d falkordb
```
**Step 4:** Create a spec using the orchestrator
### Step 3: Install and Launch the Desktop UI
```bash
# Activate the virtual environment
source auto-claude/.venv/bin/activate
cd auto-claude-ui
# Create a spec interactively
python auto-claude/spec_runner.py --interactive
# Install dependencies (pnpm recommended, npm works too)
pnpm install
# or: npm install
# Or with a task description
python auto-claude/spec_runner.py --task "Add user authentication with OAuth"
# Build and start the application
pnpm run build && pnpm run start
# or: npm run build && npm run start
```
The spec orchestrator will:
1. Analyze your project structure
2. Gather requirements interactively
3. **Research external integrations** against documentation
4. Discover relevant codebase context
5. Write the specification
6. **Self-critique using ultrathink** to find and fix issues
7. Generate an implementation plan
8. Validate all outputs
### Step 4: Start Building
**Step 5:** Run the autonomous build
1. Add your project in the UI
2. Create a new task describing what you want to build
3. Watch as Auto Claude creates a spec, plans, and implements your feature
4. Review changes and merge when satisfied
```bash
python auto-claude/run.py --spec 001
```
---
### Managing Specs
## 🎯 Features
```bash
# List all specs and their status
python auto-claude/run.py --list
### Kanban Board
# Run a specific spec
python auto-claude/run.py --spec 001
python auto-claude/run.py --spec 001-feature-name
Plan tasks and let AI handle the planning, coding, and validation — all in a visual interface. Track progress from "Planning" to "Done" while agents work autonomously.
# Run with parallel workers (2-3x speedup for independent phases)
python auto-claude/run.py --spec 001 --parallel 2
python auto-claude/run.py --spec 001 --parallel 3
### Agent Terminals
# Limit iterations for testing
python auto-claude/run.py --spec 001 --max-iterations 5
```
Spawn up to 12 AI-powered terminals for hands-on coding. Inject task context with a click, reference files from your project, and work rapidly across multiple sessions.
### QA Validation
**Power users:** Connect multiple Claude Code subscriptions to run even more agents in parallel — perfect for teams or heavy workloads.
After all chunks are complete, QA validation runs automatically:
![Auto Claude Agent Terminals](.github/assets/Auto-Claude-Agents-terminals.png)
```bash
# QA runs automatically after build completes
# To skip automatic QA:
python auto-claude/run.py --spec 001 --skip-qa
### Insights
# Run QA validation manually on a completed build
python auto-claude/run.py --spec 001 --qa
Have a conversation about your project in a ChatGPT-style interface. Ask questions, get explanations, and explore your codebase through natural dialogue.
# Check QA status
python auto-claude/run.py --spec 001 --qa-status
```
### Roadmap
The QA validation loop:
1. **QA Reviewer** checks all acceptance criteria (unit tests, integration tests, E2E, browser verification, database migrations)
2. If issues found → creates `QA_FIX_REQUEST.md`
3. **QA Fixer** applies fixes
4. Loop repeats until approved (up to 50 iterations)
5. Final sign-off recorded in `implementation_plan.json`
Based on your target audience, AI anticipates and plans the most impactful features you should focus on. Prioritize what matters most to your users.
### Spec Creation Pipeline (Dynamic Complexity)
![Auto Claude Roadmap](.github/assets/Auto-Claude-roadmap.png)
The `spec_runner.py` orchestrator **automatically assesses task complexity** and adapts the number of phases accordingly:
### Ideation
```bash
# Simple task (auto-detected) - runs 3 phases
python auto-claude/spec_runner.py --task "Fix button color in Header"
Let AI help you create a project that shines. Rapidly understand your codebase and discover:
- Code improvements and refactoring opportunities
- Performance bottlenecks
- Security vulnerabilities
- Documentation gaps
- UI/UX enhancements
- Overall code quality issues
# Complex task (auto-detected) - runs 8 phases
python auto-claude/spec_runner.py --task "Add Graphiti memory integration with FalkorDB"
### Changelog
# Force a specific complexity level
python auto-claude/spec_runner.py --task "Update text" --complexity simple
Write professional changelogs effortlessly. Generate release notes from completed Auto Claude tasks or integrate with GitHub to create masterclass changelogs automatically.
# Interactive mode
python auto-claude/spec_runner.py --interactive
### Context
# Continue an interrupted spec
python auto-claude/spec_runner.py --continue 001-feature
```
See exactly what Auto Claude understands about your project — the tech stack, file structure, patterns, and insights it uses to write better code.
**Complexity Tiers:**
### AI Merge Resolution
| Tier | Phases | When Used |
|------|--------|-----------|
| **SIMPLE** | 3 | 1-2 files, single service, no integrations (UI fixes, text changes) |
| **STANDARD** | 6 | 3-10 files, 1-2 services, minimal integrations (features, bug fixes) |
| **COMPLEX** | 8 | 10+ files, multiple services, external integrations (integrations, migrations) |
**Phase Matrix:**
| Phase | Simple | Standard | Complex |
|-------|--------|----------|---------|
| Discovery | ✓ | ✓ | ✓ |
| Requirements | - | ✓ | ✓ |
| **Research** | - | - | ✓ |
| Context | - | ✓ | ✓ |
| Spec Writing | Quick | Full | Full |
| **Self-Critique** | - | - | ✓ |
| Planning | Auto | ✓ | ✓ |
| Validation | ✓ | ✓ | ✓ |
**Complexity Detection Signals:**
- Keywords: "fix", "typo", "color" → Simple | "integrate", "migrate", "oauth" → Complex
- External integrations detected (redis, postgres, graphiti, etc.)
- Number of files/services mentioned
- Infrastructure changes (docker, deploy, schema)
**Manual validation:**
```bash
python auto-claude/validate_spec.py --spec-dir auto-claude/specs/001-feature --checkpoint all
```
### Isolated Worktrees (Safe by Default)
Auto Claude uses Git worktrees to keep your work completely safe. All AI-generated code is built in a separate workspace (`.worktrees/auto-claude/`) - your current files are never touched until you explicitly merge.
When your main branch evolves while a build is in progress, Auto Claude automatically resolves merge conflicts using AI — no manual `<<<<<<< HEAD` fixing required.
**How it works:**
1. **Git Auto-Merge First** — Simple non-conflicting changes merge instantly without AI
2. **Conflict-Only AI** — For actual conflicts, AI receives only the specific conflict regions (not entire files), achieving ~98% prompt reduction
3. **Parallel Processing** — Multiple conflicting files resolve simultaneously for faster merges
4. **Syntax Validation** — Every merge is validated before being applied
1. When you run auto-claude, it creates an isolated workspace
2. All coding happens in `.worktrees/auto-claude/` on its own branch
3. You can `cd` into the worktree to test the feature before accepting
4. Only when you're satisfied, merge the changes into your project
**The result:** A build that was 50+ commits behind main merges in seconds instead of requiring manual conflict resolution.
**After a build completes, you can:**
---
```bash
# Test the feature in the isolated workspace
cd .worktrees/auto-claude/
npm run dev # or your project's run command
## CLI Usage (Terminal-Only)
# See what was changed
python auto-claude/run.py --spec 001 --review
For terminal-based workflows, headless servers, or CI/CD integration, see **[guides/CLI-USAGE.md](guides/CLI-USAGE.md)**.
# Add changes to your project
python auto-claude/run.py --spec 001 --merge
## ⚙️ How It Works
# Discard if you don't like it (requires confirmation)
python auto-claude/run.py --spec 001 --discard
```
Auto Claude focuses on three core principles: **context engineering** (understanding your codebase before writing code), **good coding standards** (following best practices and patterns), and **validation logic** (ensuring code works before you see it).
**Key benefits:**
### The Agent Pipeline
- **Safety**: Your uncommitted work is protected - auto-claude won't touch it
- **Testability**: Run and test the feature before committing to it
- **Easy rollback**: Don't like it? Just discard the worktree
- **Parallel-safe**: Multiple workers can build without conflicts
**Phase 1: Spec Creation** (3-8 phases based on complexity)
If you have uncommitted changes, auto-claude automatically uses isolated mode. With a clean working directory, you can choose between isolated (recommended) or direct mode.
Before any code is written, agents gather context and create a detailed specification:
### Interactive Controls
1. **Discovery** — Analyzes your project structure and tech stack
2. **Requirements** — Gathers what you want to build through interactive conversation
3. **Research** — Validates external integrations against real documentation
4. **Context Discovery** — Finds relevant files in your codebase
5. **Spec Writer** — Creates a comprehensive specification document
6. **Spec Critic** — Self-critiques using extended thinking to find issues early
7. **Planner** — Breaks work into subtasks with dependencies
8. **Validation** — Ensures all outputs are valid before proceeding
While the agent is running, you can:
**Phase 2: Implementation**
```bash
# Pause and optionally add instructions
Ctrl+C (once)
# You'll be prompted to add instructions for the agent
# The agent will read these instructions when you resume
With a validated spec, coding agents execute the plan:
# Exit immediately without prompting
Ctrl+C (twice)
# Press Ctrl+C again during the prompt to exit
```
1. **Planner Agent** — Creates subtask-based implementation plan
2. **Coder Agent** — Implements subtasks one-by-one with verification
3. **QA Reviewer** — Validates all acceptance criteria
4. **QA Fixer** — Fixes issues in a self-healing loop (up to 50 iterations)
**Alternative (file-based):**
```bash
# Create PAUSE file to pause after current session
touch auto-claude/specs/001-name/PAUSE
Each session runs with a fresh context window. Progress is tracked via `implementation_plan.json` and Git commits.
# Manually edit instructions file
echo "Focus on fixing the login bug first" > auto-claude/specs/001-name/HUMAN_INPUT.md
```
**Phase 3: Merge**
When you're ready to merge, AI handles any conflicts that arose while you were working:
1. **Conflict Detection** — Identifies files modified in both main and the build
2. **3-Tier Resolution** — Git auto-merge → Conflict-only AI → Full-file AI (fallback)
3. **Parallel Merge** — Multiple files resolve simultaneously
4. **Staged for Review** — Changes are staged but not committed, so you can review before finalizing
### 🔒 Security Model
Three-layer defense keeps your code safe:
- **OS Sandbox** — Bash commands run in isolation
- **Filesystem Restrictions** — Operations limited to project directory
- **Command Allowlist** — Only approved commands based on your project's stack
### 🧠 Memory Layer
The Memory Layer is a **hybrid RAG system** combining graph nodes with semantic search to deliver the best possible context during AI coding. Agents remember insights from previous sessions, discovered codebase patterns persist and are reusable, and historical context helps agents make smarter decisions.
**Architecture:**
- **Backend**: FalkorDB (graph database) via Docker
- **Library**: Graphiti for knowledge graph operations
- **Providers**: OpenAI, Anthropic, Azure OpenAI, or Ollama (local/offline)
| Setup | LLM | Embeddings | Notes |
|-------|-----|------------|-------|
| **OpenAI** | OpenAI | OpenAI | Simplest - single API key |
| **Anthropic + Voyage** | Anthropic | Voyage AI | High quality |
| **Ollama** | Ollama | Ollama | Fully offline |
| **Azure** | Azure OpenAI | Azure OpenAI | Enterprise |
## Project Structure
```
your-project/
├── .worktrees/ # Created during build (git-ignored)
├── .worktrees/ # Created during build (git-ignored)
│ └── auto-claude/ # Isolated workspace for AI coding
├── auto-claude/
│ ├── run.py # Build entry point
│ ├── spec_runner.py # Spec creation orchestrator (8-phase pipeline)
── validate_spec.py # Spec validation with JSON schemas
├── agent.py # Session orchestration
│ ├── planner.py # Deterministic implementation planner
│ ├── worktree.py # Git worktree management
│ ├── workspace.py # Workspace selection UI
── coordinator.py # Parallel execution coordinator
│ ├── qa_loop.py # QA validation loop
── client.py # Claude SDK configuration
│ ├── memory.py # File-based session memory (primary storage)
│ ├── graphiti_memory.py # Graphiti knowledge graph integration (optional)
│ ├── spec_contract.json # Spec creation contract (required outputs)
│ ├── prompts/
│ │ ├── planner.md # Session 1 - creates implementation plan
│ │ ├── coder.md # Sessions 2+ - implements chunks
│ │ ├── spec_gatherer.md # Requirements gathering agent
│ │ ├── spec_researcher.md # External integration research agent
│ │ ├── spec_writer.md # Spec document creation agent
│ │ ├── spec_critic.md # Self-critique agent (ultrathink)
│ │ ├── qa_reviewer.md # QA validation agent
│ │ └── qa_fixer.md # QA fix agent
│ └── specs/
│ └── 001-feature/ # Each spec in its own folder
│ ├── spec.md
│ ├── requirements.json # User requirements (structured)
│ ├── research.json # External integration research
│ ├── context.json # Codebase context
│ ├── critique_report.json # Self-critique findings
│ ├── implementation_plan.json
│ ├── qa_report.md # QA validation report
│ └── QA_FIX_REQUEST.md # Issues to fix (if rejected)
└── [your project files]
├── .auto-claude/ # Per-project data (specs, plans, QA reports)
│ ├── specs/ # Task specifications
│ ├── roadmap/ # Project roadmap
── ideation/ # Ideas and planning
├── auto-claude/ # Python backend (framework code)
│ ├── run.py # Build entry point
│ ├── spec_runner.py # Spec creation orchestrator
│ ├── prompts/ # Agent prompt templates
── ...
├── auto-claude-ui/ # Electron desktop application
── ...
└── docker-compose.yml # FalkorDB for Memory Layer
```
## Key Features
### Understanding the Folders
- **Domain Agnostic**: Works for any software project (web apps, APIs, CLIs, etc.)
- **Multi-Session**: Unlimited sessions, each with fresh context
- **Research-First Specs**: External integrations validated against documentation before implementation
- **Self-Critique**: Specs are critiqued using ultrathink to find issues before coding begins
- **Parallel Execution**: 2-3x speedup with multiple workers on independent phases
- **Isolated Worktrees**: Build in a separate workspace - your current work is never touched
- **Self-Verifying**: Agents test their work with browser automation before marking complete
- **QA Validation Loop**: Automated QA agent validates all acceptance criteria before sign-off
- **Self-Healing**: QA finds issues → Fixer agent resolves → QA re-validates (up to 50 iterations)
- **8-Phase Spec Pipeline**: Discovery → Requirements → Research → Context → Spec → Critique → Plan → Validate
- **Fix Bugs Immediately**: Agents fix discovered bugs in the same session, not later
- **Defense-in-Depth Security**: OS sandbox, filesystem restrictions, command allowlist
- **Secret Scanning**: Automatic pre-commit scanning blocks secrets with actionable fix instructions
- **Human Intervention**: Pause, add instructions, or stop at any time
- **Multiple Specs**: Track and run multiple specifications independently
- **Graphiti Memory** (Optional): Persistent knowledge graph for cross-session context retention
**You don't create these folders manually** - they serve different purposes:
## Graphiti Memory Integration V2 (Optional)
Auto Claude includes an optional **Graphiti-based persistent memory layer** that enables context retention across coding sessions. This uses FalkorDB as a graph database to store codebase patterns, session insights, and cross-session learnings.
### Why Use Graphiti Memory?
- **Cross-session context**: Agents remember insights from previous sessions
- **Pattern recognition**: Discovered codebase patterns persist and are reusable
- **Smarter agents**: Context retrieval helps agents make better decisions
- **Historical hints**: Spec creation, ideation, and roadmap phases receive relevant historical insights
### Multi-Provider Support (V2)
Graphiti Memory V2 supports multiple LLM and embedding providers:
| LLM Providers | Embedding Providers |
|---------------|---------------------|
| OpenAI (default) | OpenAI (default) |
| Anthropic | Voyage AI |
| Azure OpenAI | Azure OpenAI |
| Ollama (local) | Ollama (local) |
**Provider Combinations:**
- **OpenAI + OpenAI**: Simplest setup, single API key
- **Anthropic + Voyage**: High-quality LLM with specialized embeddings
- **Ollama + Ollama**: Fully offline, no API keys needed
- **Azure OpenAI + Azure OpenAI**: Enterprise deployments
### Setup
**Step 1:** Install the Graphiti dependency
- **`auto-claude/`** - The framework repository itself (clone this once from GitHub)
- **`.auto-claude/`** - Created automatically in YOUR project when you run Auto Claude (stores specs, plans, QA reports)
- **`.worktrees/`** - Temporary isolated workspaces created during builds (git-ignored, deleted after merge)
**When using Auto Claude on your project:**
```bash
# Uncomment the graphiti line in requirements.txt, or install directly:
pip install graphiti-core[falkordb]
cd your-project/ # Your own project directory
python /path/to/auto-claude/run.py --spec 001
# Auto Claude creates .auto-claude/ automatically in your-project/
```
**Step 2:** Start FalkorDB via Docker
**When developing Auto Claude itself:**
```bash
docker-compose up -d falkordb
git clone https://github.com/yourusername/auto-claude
cd auto-claude/ # You're working in the framework repo
```
**Step 3:** Configure environment variables
The `.auto-claude/` directory is gitignored and project-specific - you'll have one per project you use Auto Claude on.
Add to your `.env` file (see `.env.example` for full documentation):
## Environment Variables (CLI Only)
```bash
# Enable Graphiti integration
GRAPHITI_ENABLED=true
# Provider selection (defaults to openai)
GRAPHITI_LLM_PROVIDER=openai
GRAPHITI_EMBEDDER_PROVIDER=openai
# Example 1: OpenAI (simplest)
OPENAI_API_KEY=sk-your-openai-key-here
# Example 2: Anthropic + Voyage (high quality)
# GRAPHITI_LLM_PROVIDER=anthropic
# GRAPHITI_EMBEDDER_PROVIDER=voyage
# ANTHROPIC_API_KEY=sk-ant-xxx
# VOYAGE_API_KEY=pa-xxx
# Example 3: Ollama (fully offline)
# GRAPHITI_LLM_PROVIDER=ollama
# GRAPHITI_EMBEDDER_PROVIDER=ollama
# OLLAMA_LLM_MODEL=deepseek-r1:7b
# OLLAMA_EMBEDDING_MODEL=nomic-embed-text
# OLLAMA_EMBEDDING_DIM=768
```
**Step 4:** Verify it's working
```bash
python auto-claude/run.py --list
# Should show: "Graphiti memory: ENABLED"
# Test the full integration
python auto-claude/test_graphiti_memory.py
```
### When Disabled
When `GRAPHITI_ENABLED` is not set (default), Auto Claude uses file-based memory only. This is the zero-dependency default that works out of the box.
## Environment Variables
> **Desktop UI users:** These are configured through the app settings — no manual setup needed.
| Variable | Required | Description |
|----------|----------|-------------|
| `CLAUDE_CODE_OAUTH_TOKEN` | Yes | OAuth token from `claude setup-token` |
| `AUTO_BUILD_MODEL` | No | Model override (default: claude-opus-4-5-20251101) |
| `GRAPHITI_ENABLED` | No | Set to `true` to enable Graphiti memory |
| `GRAPHITI_LLM_PROVIDER` | No | LLM provider: openai, anthropic, azure_openai, ollama |
| `GRAPHITI_EMBEDDER_PROVIDER` | No | Embedder: openai, voyage, azure_openai, ollama |
| `GRAPHITI_ENABLED` | Recommended | Set to `true` to enable Memory Layer |
| `GRAPHITI_LLM_PROVIDER` | For Memory | LLM provider: openai, anthropic, azure_openai, ollama |
| `GRAPHITI_EMBEDDER_PROVIDER` | For Memory | Embedder: openai, voyage, azure_openai, ollama |
| `OPENAI_API_KEY` | For OpenAI | Required for OpenAI provider |
| `ANTHROPIC_API_KEY` | For Anthropic | Required for Anthropic LLM |
| `VOYAGE_API_KEY` | For Voyage | Required for Voyage embeddings |
See `auto-claude/.env.example` for complete provider configuration options.
See `auto-claude/.env.example` for complete configuration options.
## Documentation
## 💬 Community
For parallel execution details:
- How parallelism works
- Performance analysis
- Best practices
- Troubleshooting
Join our Discord to get help, share what you're building, and connect with other Auto Claude users:
See [auto-claude/PARALLEL_EXECUTION.md](auto-claude/PARALLEL_EXECUTION.md)
[![Discord](https://img.shields.io/badge/Discord-Join%20Community-5865F2?style=for-the-badge&logo=discord&logoColor=white)](https://discord.gg/maj9EWmY)
## 🤝 Contributing
We welcome contributions! Whether it's bug fixes, new features, or documentation improvements.
See **[CONTRIBUTING.md](CONTRIBUTING.md)** for guidelines on how to get started.
## Acknowledgments
@@ -427,4 +323,15 @@ This framework was inspired by Anthropic's [Autonomous Coding Agent](https://git
## License
MIT License
**AGPL-3.0** - GNU Affero General Public License v3.0
This software is licensed under AGPL-3.0, which means:
- **Attribution Required**: You must give appropriate credit, provide a link to the license, and indicate if changes were made. When using Auto Claude, please credit the project.
- **Open Source Required**: If you modify this software and distribute it or run it as a service, you must release your source code under AGPL-3.0.
- **Network Use (Copyleft)**: If you run this software as a network service (e.g., SaaS), users interacting with it over a network must be able to receive the source code.
- **No Closed-Source Usage**: You cannot use this software in proprietary/closed-source projects without open-sourcing your entire project under AGPL-3.0.
**In simple terms**: You can use Auto Claude freely, but if you build on it, your code must also be open source under AGPL-3.0 and attribute this project. Closed-source commercial use requires a separate license.
For commercial licensing inquiries (closed-source usage), please contact the maintainers.
-268
View File
@@ -1,268 +0,0 @@
# Auto-Claude Recovery and Resumption System
## Overview
This document explains how Auto-Claude detects completed planning phases, identifies existing worktrees, and resumes execution after crashes or user interruptions.
## Key State Detection Mechanisms
### 1. Planning Phase Completion Detection
**Primary Indicator: `implementation_plan.json`**
The system determines if planning is complete by checking for the existence and validity of `implementation_plan.json`:
- **Location**: `.auto-claude/specs/{spec-name}/implementation_plan.json`
- **Detection Logic**:
- `prompts.py::is_first_run()` checks if `implementation_plan.json` exists
- `coordinator.py::load_implementation_plan()` raises `FileNotFoundError` if missing
- `agent.py::load_implementation_plan()` returns `None` if file doesn't exist
**Code References:**
```python
# auto-claude/prompts.py:181-192
def is_first_run(spec_dir: Path) -> bool:
plan_file = spec_dir / "implementation_plan.json"
return not plan_file.exists()
# auto-claude/coordinator.py:175-186
def load_implementation_plan(self) -> ImplementationPlan:
plan_file = self.spec_dir / "implementation_plan.json"
if not plan_file.exists():
raise FileNotFoundError("Implementation plan not found")
# ...
```
**Planning Phase Flow:**
1. `spec_runner.py` runs phases: discovery → requirements → complexity → context → spec → planning
2. `phase_planning()` creates `implementation_plan.json` via `planner.py` or planner agent
3. Once `implementation_plan.json` exists and is valid, planning is considered complete
### 2. Worktree Detection
**Staging Worktree Detection**
The system checks for existing worktrees using:
- **Location**: `.worktrees/auto-claude/` (staging worktree)
- **Detection Functions**:
- `workspace.py::get_existing_build_worktree()` - checks if staging worktree exists
- `worktree.py::get_or_create_staging()` - gets existing or creates new staging worktree
- `worktree.py::staging_exists()` - boolean check for staging worktree
**Code References:**
```python
# auto-claude/workspace.py:88-93
def get_existing_build_worktree(project_dir: Path, spec_name: str) -> Optional[Path]:
worktree_path = project_dir / ".worktrees" / STAGING_WORKTREE_NAME
if worktree_path.exists():
return worktree_path
return None
# auto-claude/worktree.py:173-206
def get_or_create_staging(self, spec_name: str) -> WorktreeInfo:
staging_path = self.worktrees_dir / STAGING_WORKTREE_NAME
branch_name = f"auto-claude/{spec_name}"
if staging_path.exists():
# Load existing worktree info
# ...
return info
# Create new staging worktree
return self.create(STAGING_WORKTREE_NAME, branch_name)
```
**Worktree Persistence:**
- Worktrees persist across crashes and app restarts
- Git worktrees are stored in `.worktrees/` directory
- Each worktree has its own branch: `auto-claude/{spec-name}`
- Staging worktree is preserved until explicitly merged or discarded
### 3. Resumption Logic
**Entry Point: `run.py::main()`**
When `run.py` starts, it follows this resumption flow:
1. **Find Spec**: Locates spec directory via `find_spec()`
2. **Check Existing Build**: Calls `get_existing_build_worktree()` to detect staging worktree
3. **User Choice** (if not `--auto-continue`):
- Continue where it left off
- Review what was built
- Merge existing build
- Start fresh (discard)
4. **Workspace Setup**:
- If existing worktree found → uses it
- If not → creates new staging worktree
5. **Execution**:
- **Sequential Mode**: `run_autonomous_agent()` checks for `implementation_plan.json`
- **Parallel Mode**: `SwarmCoordinator` checks for plan, runs planner if missing
**Code Flow:**
```python
# auto-claude/run.py:618-631
if get_existing_build_worktree(project_dir, spec_dir.name):
if args.auto_continue:
print("Auto-continue: Resuming existing build...")
else:
continue_existing = check_existing_build(project_dir, spec_dir.name)
if continue_existing:
# Continue with existing worktree
pass
else:
# User chose to start fresh or merged existing
pass
```
### 4. Planner vs Coder Detection
**Sequential Mode (`agent.py`):**
```python
# auto-claude/agent.py:547-691
async def run_autonomous_agent(...):
# ...
first_run = is_first_run(spec_dir) # Checks for implementation_plan.json
if first_run:
# Run planner session
prompt = generate_planner_prompt(spec_dir)
else:
# Run coder session
next_chunk = get_next_chunk(spec_dir)
prompt = generate_coder_prompt(spec_dir, next_chunk)
```
**Parallel Mode (`coordinator.py`):**
```python
# auto-claude/coordinator.py:304-350
async def run_planner_session(self) -> bool:
"""Run planner if implementation_plan.json doesn't exist"""
plan_file = self.spec_dir / "implementation_plan.json"
if not plan_file.exists():
# Run planner agent session
# ...
```
### 5. Chunk Progress Tracking
**State Storage: `implementation_plan.json`**
Chunk statuses are stored in the plan file:
- `pending` - Not started
- `in_progress` - Currently being worked on
- `completed` - Finished successfully
- `blocked` - Stuck, needs attention
- `failed` - Failed after attempts
**Resumption Logic:**
```python
# auto-claude/progress.py:399-452
def get_next_chunk(spec_dir: Path) -> dict | None:
plan_file = spec_dir / "implementation_plan.json"
# ...
# Find first pending chunk in available phase
for chunk in phase.get("chunks", []):
if chunk.get("status") == "pending":
return chunk
```
**Recovery Handling:**
- `in_progress` chunks are reset to `pending` on recovery (see `ipc-handlers.ts:926`)
- Completed chunks remain `completed` to preserve progress
- Failed chunks can be reset to `pending` for retry
## Recovery Scenarios
### Scenario 1: Planning Complete, No Worktree
**State:**
-`implementation_plan.json` exists
- ❌ No staging worktree exists
**Behavior:**
- System detects plan exists → skips planner
- Creates new staging worktree
- Starts coding phase with first pending chunk
### Scenario 2: Planning Complete, Worktree Exists
**State:**
-`implementation_plan.json` exists
- ✅ Staging worktree exists at `.worktrees/auto-claude/`
**Behavior:**
- System detects both exist
- Prompts user (or auto-continues) to resume
- Uses existing worktree
- Resumes from last incomplete chunk
### Scenario 3: Planning Incomplete
**State:**
-`implementation_plan.json` missing or invalid
- ❌ No staging worktree (or exists but no plan)
**Behavior:**
- System detects missing plan
- Runs planner session first
- Creates `implementation_plan.json`
- Then proceeds to coding phase
### Scenario 4: Crash During Coding
**State:**
-`implementation_plan.json` exists
- ✅ Staging worktree exists
- ⚠️ Some chunks `in_progress` or `failed`
**Behavior:**
- On restart, `in_progress` chunks are reset to `pending`
- System resumes from first `pending` chunk
- Worktree preserves all committed work
- Uncommitted changes may be lost (depends on git state)
## Frontend Integration
**UI State Detection (`auto-claude-ui`):**
The frontend tracks state via:
1. **File Watcher**: Monitors `implementation_plan.json` for changes
2. **Task Store**: Reads plan file to determine task status
3. **Agent Manager**: Parses logs to detect phase transitions
**Recovery Actions:**
- `ipc-handlers.ts::recoverTask()` - Resets stuck tasks
- Resets `in_progress``pending` for interrupted chunks
- Preserves `completed` chunks
## Key Files for State
**State Files:**
- `.auto-claude/specs/{spec}/implementation_plan.json` - Main state file
- `.auto-claude/specs/{spec}/memory/attempt_history.json` - Recovery history
- `.auto-claude/specs/{spec}/memory/build_commits.json` - Git commit tracking
- `.worktrees/auto-claude/` - Staging worktree (git-managed)
**Detection Functions:**
- `is_first_run()` - Checks if planning needed
- `get_existing_build_worktree()` - Checks for worktree
- `get_next_chunk()` - Finds next work item
- `load_implementation_plan()` - Loads plan state
## Summary
The system uses a **file-based state detection** approach:
1. **Planning Complete?** → Check for `implementation_plan.json`
2. **Worktree Exists?** → Check for `.worktrees/auto-claude/`
3. **What's Next?** → Read chunk statuses from `implementation_plan.json`
4. **Resume Point** → First `pending` chunk in available phase
This design ensures:
- ✅ No duplicate planning if plan already exists
- ✅ Work preservation via git worktrees
- ✅ Progress tracking via chunk statuses
- ✅ Safe resumption after crashes
- ✅ User control over continuation vs fresh start
+312
View File
@@ -0,0 +1,312 @@
# Auto Claude Update System Analysis
## Current State
The app has **TWO separate update systems** for different components:
### 1. ✅ Auto Claude Framework Updates (WORKING)
**What it updates:** The Python framework source code (`auto-claude/` directory)
**How it works:**
- Checks GitHub Releases API for new versions
- Downloads release tarball
- Extracts and applies update to the bundled source
- Preserves user configuration files (.env, etc.)
**User Experience:**
- **Settings > Advanced > Updates** section
- Visual update checker with version display
- Release notes rendered in UI
- Progress bar during download
- One-click update button
- Works across all platforms (macOS, Windows, Linux)
**Files:**
- `auto-claude-ui/src/main/auto-claude-updater.ts` - Main updater module
- `auto-claude-ui/src/main/updater/update-checker.ts` - Update checking
- `auto-claude-ui/src/main/updater/update-installer.ts` - Download & install
- `auto-claude-ui/src/main/ipc-handlers/autobuild-source-handlers.ts` - IPC handlers
- `auto-claude-ui/src/renderer/components/settings/AdvancedSettings.tsx` - UI
**Status:****FULLY FUNCTIONAL** - Non-technical users can update the framework with one click!
---
### 2. ❌ Electron App Updates (NOT IMPLEMENTED)
**What it updates:** The Electron application itself (Auto Claude UI)
**Current State:**
- ❌ No `electron-updater` dependency installed
- ❌ No auto-update configuration in electron-builder
- ❌ No update checking in main process
- ❌ No UI for app update notifications
- ❌ Users must manually download new releases from GitHub
**What users currently need to do:**
1. Go to GitHub Releases page
2. Download the appropriate installer (.dmg, .exe, .AppImage, etc.)
3. Run the installer
4. Manually replace the old app
---
## What Needs to Be Implemented
To enable automatic Electron app updates for non-technical users, we need to add:
### 1. Install electron-updater
```bash
npm install electron-updater
```
### 2. Configure electron-builder for Publishing
Add to `package.json` build config:
```json
{
"build": {
"publish": [
{
"provider": "github",
"owner": "AndyMik90",
"repo": "Auto-Claude"
}
]
}
}
```
### 3. Implement Auto-Update Logic in Main Process
Create `auto-claude-ui/src/main/app-updater.ts`:
```typescript
import { autoUpdater } from 'electron-updater';
import { app, BrowserWindow } from 'electron';
export function initializeAppUpdater(mainWindow: BrowserWindow) {
// Configure update checking
autoUpdater.autoDownload = false; // Let user decide
autoUpdater.autoInstallOnAppQuit = true;
// Check for updates on launch (after 3 seconds)
setTimeout(() => {
autoUpdater.checkForUpdates();
}, 3000);
// Check periodically (every 4 hours)
setInterval(() => {
autoUpdater.checkForUpdates();
}, 4 * 60 * 60 * 1000);
// Event handlers
autoUpdater.on('update-available', (info) => {
mainWindow.webContents.send('app-update-available', {
version: info.version,
releaseNotes: info.releaseNotes,
releaseDate: info.releaseDate
});
});
autoUpdater.on('update-downloaded', (info) => {
mainWindow.webContents.send('app-update-downloaded', {
version: info.version
});
});
autoUpdater.on('error', (error) => {
console.error('App update error:', error);
});
autoUpdater.on('download-progress', (progress) => {
mainWindow.webContents.send('app-update-progress', {
percent: progress.percent,
transferred: progress.transferred,
total: progress.total
});
});
}
// IPC handlers
export function registerAppUpdateHandlers() {
ipcMain.handle('app-update-download', async () => {
await autoUpdater.downloadUpdate();
});
ipcMain.handle('app-update-install', () => {
autoUpdater.quitAndInstall();
});
ipcMain.handle('app-update-check', async () => {
return await autoUpdater.checkForUpdates();
});
}
```
### 4. Add UI Notification Component
Create an update banner or modal in the renderer that:
- Shows when app update is available
- Displays version and release notes
- Has "Download Update" button
- Shows download progress
- Has "Install and Restart" button after download
### 5. Update GitHub Release Workflow
Ensure GitHub releases are created with proper assets:
- macOS: `.dmg` and `.zip` files + `latest-mac.yml`
- Windows: `.exe` installer + `latest.yml`
- Linux: `.AppImage` and `.deb` + `latest-linux.yml`
The `latest-*.yml` files are auto-generated by electron-builder and contain update metadata.
---
## Implementation Strategy
### Option A: Full Auto-Update (Recommended)
**Pros:**
- Best user experience
- Automatic background downloads
- One-click install
- Industry standard
**Cons:**
- Requires code signing certificates for production (macOS, Windows)
- Without signing, users get security warnings
### Option B: Update Notification Only
**Pros:**
- Simpler implementation
- No code signing required
- User downloads from GitHub (trusted source)
**Cons:**
- Users still need to manually download and install
- Less convenient than auto-update
**Implementation:**
```typescript
// Just notify, don't auto-download
autoUpdater.autoDownload = false;
autoUpdater.on('update-available', (info) => {
// Show notification with link to GitHub Releases
mainWindow.webContents.send('app-update-available', {
version: info.version,
downloadUrl: `https://github.com/AndyMik90/Auto-Claude/releases/tag/v${info.version}`
});
});
```
---
## Development vs Production
**Important:** `electron-updater` only works in **packaged apps**, not in development mode.
During development:
```typescript
if (app.isPackaged) {
initializeAppUpdater(mainWindow);
} else {
console.log('[Dev] Auto-updater disabled in development mode');
}
```
---
## Code Signing Requirements
For production auto-updates without security warnings:
### macOS
- Requires Apple Developer account ($99/year)
- Code signing certificate
- Notarization with Apple
### Windows
- Requires code signing certificate (~$200-400/year)
- Without: Windows SmartScreen warnings
### Linux
- No code signing required
- Users may need to mark `.AppImage` as executable
---
## Testing Auto-Updates
1. **Local Testing:**
- Build and package: `npm run package`
- Create local update server or use GitHub Releases
- Test with different versions
2. **GitHub Releases Testing:**
- Create a draft release on GitHub
- Publish with version tag (e.g., `v2.4.0`)
- electron-builder automatically uploads assets
- Test with previous version installed
---
## Recommended Next Steps
1. **Phase 1: Add Update Notification** (Quick win)
- Install `electron-updater`
- Add basic update checking
- Show notification with link to GitHub Releases
- No auto-download, users download manually
2. **Phase 2: Enable Auto-Download** (Better UX)
- Add download progress UI
- Enable auto-download of updates
- Add "Install and Restart" button
3. **Phase 3: Code Signing** (Production ready)
- Acquire code signing certificates
- Configure signing in electron-builder
- Notarize macOS builds
- Sign Windows builds
---
## Current Framework Update Flow (Already Working!)
For reference, here's how the existing Auto Claude framework updater works:
1. User opens **Settings > Advanced > Updates**
2. App checks GitHub Releases API
3. If update available, shows version + release notes
4. User clicks "Download Update"
5. Progress bar shows download status
6. Update is extracted and applied to bundled source
7. User configuration (.env) is preserved
8. Done - no restart needed!
**This same UX could be replicated for app updates!**
---
## Summary
| Component | Status | User Experience |
|-----------|--------|-----------------|
| Auto Claude Framework | ✅ Working | One-click update in Settings |
| Electron App (UI) | ❌ Missing | Must download from GitHub manually |
**Recommendation:** Implement electron-updater with update notifications (Phase 1) as a quick win. This will enable non-technical users to update the app without using git or terminal commands.
**Estimated effort:**
- Phase 1 (Notifications): 2-4 hours
- Phase 2 (Auto-download): 2-3 hours
- Phase 3 (Code signing): Varies by platform
The existing framework updater code provides an excellent reference for the UI implementation!
+139
View File
@@ -0,0 +1,139 @@
# Windows/Linux Source Path Detection Fix
## Problem
On Windows and Linux, when initializing a project, users were getting a "Source path not configured" error even though the `auto-claude` source directory exists. This error did not occur on macOS.
## Root Cause
The `detectAutoBuildSourcePath()` function in two files was using path resolution logic that worked on macOS in development mode but failed on Windows/Linux, especially in production/packaged builds. The function was trying to auto-detect where the Auto Claude framework source code (`auto-claude/` directory) is located, but the paths resolved differently across platforms.
## Changes Made
### 1. Enhanced Path Detection Logic
Updated `detectAutoBuildSourcePath()` in two files:
- `auto-claude-ui/src/main/ipc-handlers/settings-handlers.ts`
- `auto-claude-ui/src/main/ipc-handlers/project-handlers.ts`
**Key improvements:**
1. **Platform-aware path detection**: Separates development vs production mode using `is.dev` from `@electron-toolkit/utils`
2. **More comprehensive path checking**:
- **Development mode**: Checks multiple relative paths from `__dirname`, `process.cwd()`, and parent directories
- **Production mode**: Checks paths relative to `app.getAppPath()`, `process.resourcesPath`, and multiple levels up
3. **Debug logging**: Added detailed logging that can be enabled with `AUTO_CLAUDE_DEBUG=1` environment variable
4. **Better error messages**: Console warnings now guide users to enable debug mode if auto-detection fails
## Testing on Windows/Linux
### 1. Run with Debug Logging
Set the environment variable to see detailed path checking:
**Windows (PowerShell):**
```powershell
$env:AUTO_CLAUDE_DEBUG="1"
.\Auto-Claude.exe
```
**Windows (Command Prompt):**
```cmd
set AUTO_CLAUDE_DEBUG=1
Auto-Claude.exe
```
**Linux:**
```bash
AUTO_CLAUDE_DEBUG=1 ./Auto-Claude
```
### 2. Check Console Output
The debug output will show:
- Current platform (win32/linux/darwin)
- Whether running in dev or production mode
- All paths being checked
- Which paths exist and which don't
- Whether auto-detection succeeded
Example debug output:
```
[detectAutoBuildSourcePath] Platform: win32
[detectAutoBuildSourcePath] Is dev: false
[detectAutoBuildSourcePath] __dirname: C:\Program Files\Auto-Claude\resources\app.asar\out\main
[detectAutoBuildSourcePath] app.getAppPath(): C:\Program Files\Auto-Claude\resources\app.asar
[detectAutoBuildSourcePath] process.cwd(): C:\Program Files\Auto-Claude
[detectAutoBuildSourcePath] Checking paths: [...]
[detectAutoBuildSourcePath] Checking C:\Program Files\auto-claude: ✗ not found
[detectAutoBuildSourcePath] Checking C:\auto-claude: ✓ FOUND
[detectAutoBuildSourcePath] Auto-detected source path: C:\auto-claude
```
### 3. Manual Configuration (Fallback)
If auto-detection still fails, users can manually configure the path:
1. Open **App Settings** in Auto Claude UI
2. Go to the **General** tab
3. Set **Auto Claude Source Path** to the location of your `auto-claude` directory
4. Click **Save**
Example paths:
- Windows: `C:\Users\YourName\Projects\autonomous-coding\auto-claude`
- Linux: `/home/yourname/projects/autonomous-coding/auto-claude`
## What Gets Checked
The function now checks these paths in order:
### Development Mode (`is.dev = true`):
1. `__dirname/../../../auto-claude` - From out/main up 3 levels
2. `__dirname/../../auto-claude` - From out/main up 2 levels
3. `process.cwd()/auto-claude` - From current working directory
4. `process.cwd()/../auto-claude` - From parent of cwd
### Production Mode (`is.dev = false`):
1. `app.getAppPath()/../auto-claude` - Sibling to app
2. `app.getAppPath()/../../auto-claude` - Up 2 from app
3. `app.getAppPath()/../../../auto-claude` - Up 3 from app
4. `process.resourcesPath/../auto-claude` - Relative to resources
5. `process.resourcesPath/../../auto-claude` - Up 2 from resources
### All Modes:
- `process.cwd()/auto-claude` - Last resort fallback
## Verification
For each path, the function checks:
1. Does the directory exist?
2. Does `VERSION` file exist inside it?
Both must be true for a path to be considered valid.
## Build Verification
The changes have been compiled and tested:
```
✓ Built successfully with no errors
✓ All TypeScript files compiled
✓ Electron app bundle created
```
## Next Steps
1. **Test on Windows**: Have Windows users test the updated build with `AUTO_CLAUDE_DEBUG=1`
2. **Test on Linux**: Have Linux users test the updated build with `AUTO_CLAUDE_DEBUG=1`
3. **Collect feedback**: If issues persist, the debug output will help identify the correct path patterns
4. **Update documentation**: Add troubleshooting section to main README if needed
## Related Files
- `auto-claude-ui/src/main/ipc-handlers/settings-handlers.ts`
- `auto-claude-ui/src/main/ipc-handlers/project-handlers.ts`
- `auto-claude-ui/src/main/project-initializer.ts`
- `auto-claude-ui/src/renderer/App.tsx` (shows the error dialog)
- `auto-claude-ui/src/renderer/components/Sidebar.tsx` (shows the error dialog)
+661
View File
@@ -0,0 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.
+4
View File
@@ -6,6 +6,10 @@ out/
dist/
build/
# Compiled TypeScript (source files are .ts)
src/**/*.js
src/**/*.js.map
# electron-vite
.vite/
+1
View File
@@ -0,0 +1 @@
pnpm test
+108 -139
View File
@@ -2,161 +2,130 @@
A desktop application for managing AI-driven development tasks using the Auto Claude autonomous coding framework.
## Overview
## Quick Start
Auto Claude UI provides a visual Kanban board interface for creating, monitoring, and managing auto-claude tasks. It replaces the terminal-based workflow with an intuitive GUI while preserving all CLI functionality.
```bash
# 1. Clone the repo (if you haven't already)
git clone https://github.com/AndyMik90/Auto-Claude.git
cd Auto-Claude/auto-claude-ui
# 2. Install dependencies
npm install
# 3. Build the desktop app
npm run package:win # Windows
npm run package:mac # macOS
npm run package:linux # Linux
# 4. Run the app
# Windows: .\dist\win-unpacked\Auto Claude.exe
# macOS: open dist/mac-arm64/Auto\ Claude.app
# Linux: ./dist/linux-unpacked/auto-claude
```
## Prerequisites
- Node.js 18+
- npm or pnpm
- Python 3.10+ (for auto-claude backend)
- **Windows only**: Visual Studio Build Tools 2022 with "Desktop development with C++" workload
- **Windows only**: Developer Mode enabled (Settings → System → For developers)
## How to Run
### Building for Production (Recommended)
Build the Electron desktop app for your platform:
```bash
# Build for Windows
npm run package:win
# Build for macOS
npm run package:mac
# Build for Linux
npm run package:linux
```
### Running the Production Build
After building, run the application from the `dist` folder:
```bash
# Windows - run the executable
.\dist\win-unpacked\Auto Claude.exe
# Windows - or use the installer
.\dist\Auto Claude Setup X.X.X.exe
# macOS
open dist/mac-arm64/Auto\ Claude.app
# Linux
./dist/linux-unpacked/auto-claude
```
### Development Mode
For development with hot reload (optional):
```bash
npm run dev
```
> **Note**: Some features like auto-updates only work in packaged builds.
## Distribution Files
After packaging, the `dist` folder contains:
| Platform | Files |
|----------|-------|
| macOS | `Auto Claude.app`, `.dmg`, `.zip` |
| Windows | `Auto Claude Setup X.X.X.exe` (installer), `.zip`, `win-unpacked/` |
| Linux | `.AppImage`, `.deb`, `linux-unpacked/` |
## Testing
```bash
# Run tests
npm run test
```
## Linting
```bash
# Run ESLint
npm run lint
# Run type checking
npm run typecheck
```
## Features
- **Project Management**: Add, configure, and switch between multiple projects
- **Kanban Board**: Visual task board with columns for Backlog, In Progress, AI Review, Human Review, and Done
- **Task Creation Wizard**: Form-based interface for creating new tasks
- **Real-Time Progress**: Live updates from implementation_plan.json during agent execution
- **Real-Time Progress**: Live updates during agent execution
- **Human Review Workflow**: Review QA results and provide feedback
- **Theme Support**: Light and dark mode with system preference detection
- **Settings**: Per-project and app-wide configuration options
- **Theme Support**: Light and dark mode
- **Auto Updates**: Automatic update notifications
## Tech Stack
- **Framework**: Electron with React 18 (TypeScript)
- **Build Tool**: electron-vite with electron-builder
- **UI Components**: Radix UI primitives (shadcn/ui pattern)
- **Styling**: TailwindCSS with dark mode support
- **Framework**: Electron + React 18 (TypeScript)
- **Build Tool**: electron-vite + electron-builder
- **UI Components**: Radix UI (shadcn/ui pattern)
- **Styling**: TailwindCSS
- **State Management**: Zustand
- **File Watching**: chokidar
## Project Structure
```
auto-claude-ui/
├── src/
│ ├── main/ # Electron main process
│ │ ├── index.ts # App entry point
│ │ ├── agent-manager.ts # Python subprocess management
│ │ ├── file-watcher.ts # Implementation plan watching
│ │ ├── ipc-handlers.ts # IPC message handlers
│ │ └── project-store.ts # JSON project persistence
│ ├── preload/ # Preload scripts
│ │ └── index.ts # Secure contextBridge API
│ ├── renderer/ # React application
│ │ ├── components/ # React components
│ │ │ ├── ui/ # Wrapped Radix UI components
│ │ │ ├── Sidebar.tsx
│ │ │ ├── KanbanBoard.tsx
│ │ │ ├── TaskCard.tsx
│ │ │ ├── TaskDetailPanel.tsx
│ │ │ ├── TaskCreationWizard.tsx
│ │ │ ├── ProjectSettings.tsx
│ │ │ └── AppSettings.tsx
│ │ ├── stores/ # Zustand state stores
│ │ ├── hooks/ # Custom React hooks
│ │ ├── styles/ # Global CSS
│ │ └── App.tsx # Root component
│ └── shared/ # Shared code
│ ├── types.ts # TypeScript interfaces
│ └── constants.ts # Constants and IPC channels
├── electron.vite.config.ts # Build configuration
├── package.json
├── tsconfig.json
├── tailwind.config.js
└── postcss.config.js
```
## Getting Started
### Prerequisites
- Node.js 18+
- npm or pnpm
- Python 3.10+ (for auto-claude backend)
### Installation
```bash
# Navigate to auto-claude-ui directory
cd auto-claude-ui
# Install dependencies
npm install
```
### Development
```bash
# Start development server with hot reload
npm run dev
```
### Build
```bash
# Build for production
npm run build
# Package for macOS
npm run package:mac
# Package for Windows
npm run package:win
# Package for Linux
npm run package:linux
```
### Type Checking
```bash
npm run typecheck
```
### Linting
```bash
npm run lint
```
### Testing
```bash
npm run test
```
## Architecture
### Main Process
The main process handles:
- Window management
- Python subprocess spawning (agent-manager.ts)
- File system watching (file-watcher.ts)
- Project data persistence (project-store.ts)
- IPC communication with renderer
### Preload Script
Provides a secure bridge between main and renderer processes using Electron's contextBridge. All IPC channels are explicitly defined and typed.
### Renderer Process
A React application with:
- Zustand stores for state management
- Custom hooks for IPC event handling
- Radix UI components wrapped in the shadcn/ui pattern
- TailwindCSS for styling
## Security
The application follows Electron security best practices:
- `contextIsolation: true`
- `nodeIntegration: false`
- Minimal API surface via contextBridge
- No direct ipcRenderer exposure
## Environment Variables
- `CLAUDE_CODE_OAUTH_TOKEN`: OAuth token for Claude Code SDK (from auto-claude/.env)
- `FALKORDB_URL`: FalkorDB connection URL (optional, defaults to localhost:6379)
- `FALKORDB_URL`: FalkorDB connection URL (optional)
## License
MIT
AGPL-3.0
+5 -5
View File
@@ -9,7 +9,7 @@
* To run: npx playwright test --config=e2e/playwright.config.ts
*/
import { test, expect, _electron as electron, ElectronApplication, Page } from '@playwright/test';
import { mkdirSync, rmSync, existsSync, writeFileSync } from 'fs';
import { mkdirSync, rmSync, existsSync, writeFileSync, readFileSync } from 'fs';
import path from 'path';
// Test data directory
@@ -269,13 +269,13 @@ test.describe('E2E Flow Verification (Mock-based)', () => {
'implementation_plan.json'
);
const plan = JSON.parse(require('fs').readFileSync(planPath, 'utf-8'));
const plan = JSON.parse(readFileSync(planPath, 'utf-8'));
plan.phases[0].chunks[0].status = 'in_progress';
writeFileSync(planPath, JSON.stringify(plan, null, 2));
// Verify update
const updatedPlan = JSON.parse(require('fs').readFileSync(planPath, 'utf-8'));
const updatedPlan = JSON.parse(readFileSync(planPath, 'utf-8'));
expect(updatedPlan.phases[0].chunks[0].status).toBe('in_progress');
cleanupTestEnvironment();
@@ -298,7 +298,7 @@ test.describe('E2E Flow Verification (Mock-based)', () => {
expect(existsSync(qaReportPath)).toBe(true);
const content = require('fs').readFileSync(qaReportPath, 'utf-8');
const content = readFileSync(qaReportPath, 'utf-8');
expect(content).toContain('APPROVED');
cleanupTestEnvironment();
@@ -324,7 +324,7 @@ test.describe('E2E Flow Verification (Mock-based)', () => {
expect(existsSync(fixRequestPath)).toBe(true);
const content = require('fs').readFileSync(fixRequestPath, 'utf-8');
const content = readFileSync(fixRequestPath, 'utf-8');
expect(content).toContain('REJECTED');
expect(content).toContain('Needs more tests');
+1 -1
View File
@@ -1,7 +1,7 @@
/**
* Playwright configuration for Electron E2E tests
*/
import { defineConfig, devices } from '@playwright/test';
import { defineConfig } from '@playwright/test';
export default defineConfig({
testDir: '.',
+25 -1
View File
@@ -5,13 +5,21 @@ import { resolve } from 'path';
export default defineConfig({
main: {
plugins: [externalizeDepsPlugin({
exclude: []
// Bundle these packages into the main process (they won't be in node_modules in packaged app)
exclude: [
'uuid',
'chokidar',
'ioredis',
'electron-updater',
'@electron-toolkit/utils'
]
})],
build: {
rollupOptions: {
input: {
index: resolve(__dirname, 'src/main/index.ts')
},
// Only node-pty needs to be external (native module rebuilt by electron-builder)
external: ['node-pty']
}
}
@@ -41,6 +49,22 @@ export default defineConfig({
'@': resolve(__dirname, 'src/renderer'),
'@shared': resolve(__dirname, 'src/shared')
}
},
server: {
watch: {
// Ignore directories to prevent HMR conflicts during merge operations
// Using absolute paths and broader patterns
ignored: [
'**/node_modules/**',
'**/.git/**',
'**/.worktrees/**',
'**/.auto-claude/**',
'**/out/**',
// Ignore the parent autonomous-coding directory's worktrees
resolve(__dirname, '../.worktrees/**'),
resolve(__dirname, '../.auto-claude/**'),
]
}
}
}
});
+10 -8
View File
@@ -31,26 +31,26 @@ export default tseslint.config(
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/no-explicit-any': 'warn',
'@typescript-eslint/no-unused-vars': ['warn', { argsIgnorePattern: '^_' }],
'@typescript-eslint/no-empty-object-type': 'off', // Allow empty interfaces for extensibility
'@typescript-eslint/no-unsafe-function-type': 'off', // Allow Function type in mocks
'@typescript-eslint/no-unused-vars': ['warn', { argsIgnorePattern: '^_', varsIgnorePattern: '^_', caughtErrorsIgnorePattern: '^_' }],
'@typescript-eslint/no-empty-object-type': 'off',
'@typescript-eslint/no-unsafe-function-type': 'off',
// React
...react.configs.recommended.rules,
'react/react-in-jsx-scope': 'off',
'react/prop-types': 'off',
'react/display-name': 'off',
'react/no-unescaped-entities': 'off',
// React Hooks
...reactHooks.configs.recommended.rules,
// React Hooks - only classic rules, no compiler rules
'react-hooks/rules-of-hooks': 'error',
'react-hooks/exhaustive-deps': 'warn',
'react-hooks/set-state-in-effect': 'warn', // Downgrade to warning
// General
'no-console': ['warn', { allow: ['warn', 'error'] }],
'prefer-const': 'warn',
'no-unused-expressions': 'warn'
'no-unused-expressions': 'warn',
'@typescript-eslint/no-require-imports': 'warn'
}
},
{
@@ -59,6 +59,9 @@ export default tseslint.config(
globals: {
...globals.node
}
},
rules: {
'@typescript-eslint/no-require-imports': 'off'
}
},
{
@@ -74,4 +77,3 @@ export default tseslint.config(
ignores: ['out/**', 'dist/**', '.eslintrc.cjs', 'eslint.config.mjs', 'node_modules/**']
}
);
+15289
View File
File diff suppressed because it is too large Load Diff
+49 -8
View File
@@ -1,10 +1,10 @@
{
"name": "auto-claude-ui",
"version": "0.1.0",
"version": "2.3.0",
"description": "Desktop UI for Auto Claude autonomous coding framework",
"main": "./out/main/index.js",
"author": "Auto Claude Team",
"license": "MIT",
"license": "AGPL-3.0",
"scripts": {
"postinstall": "electron-rebuild",
"dev": "electron-vite dev",
@@ -15,12 +15,15 @@
"package:mac": "electron-vite build && electron-builder --mac",
"package:win": "electron-vite build && electron-builder --win",
"package:linux": "electron-vite build && electron-builder --linux",
"start:packaged": "open dist/mac-arm64/Auto\\ Claude.app || open dist/mac/Auto\\ Claude.app",
"start:packaged:mac": "open dist/mac-arm64/Auto\\ Claude.app || open dist/mac/Auto\\ Claude.app",
"start:packaged:win": "start \"\" \"dist\\win-unpacked\\Auto Claude.exe\"",
"start:packaged:linux": "./dist/linux-unpacked/auto-claude",
"test": "vitest run",
"test:watch": "vitest",
"test:coverage": "vitest run --coverage",
"test:e2e": "npx playwright test --config=e2e/playwright.config.ts",
"lint": "eslint .",
"lint:fix": "eslint . --fix",
"typecheck": "tsc --noEmit"
},
"dependencies": {
@@ -33,6 +36,7 @@
"@radix-ui/react-dialog": "^1.1.15",
"@radix-ui/react-dropdown-menu": "^2.1.16",
"@radix-ui/react-progress": "^1.1.8",
"@radix-ui/react-radio-group": "^1.3.8",
"@radix-ui/react-scroll-area": "^1.2.10",
"@radix-ui/react-select": "^2.2.6",
"@radix-ui/react-separator": "^1.1.8",
@@ -41,17 +45,26 @@
"@radix-ui/react-tabs": "^1.1.13",
"@radix-ui/react-toast": "^1.2.15",
"@radix-ui/react-tooltip": "^1.2.8",
"@tailwindcss/typography": "^0.5.19",
"@tanstack/react-virtual": "^3.13.13",
"@xterm/addon-fit": "^0.10.0",
"@xterm/addon-serialize": "^0.13.0",
"@xterm/addon-web-links": "^0.11.0",
"@xterm/addon-webgl": "^0.18.0",
"@xterm/xterm": "^5.5.0",
"chokidar": "^5.0.0",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"electron-updater": "^6.6.2",
"ioredis": "^5.8.2",
"lucide-react": "^0.560.0",
"node-pty": "^1.0.0",
"react": "^19.2.1",
"react-dom": "^19.2.1",
"motion": "^12.23.26",
"node-pty": "^1.1.0-beta42",
"react": "^19.2.3",
"react-dom": "^19.2.3",
"react-markdown": "^10.1.0",
"react-resizable-panels": "^3.0.6",
"remark-gfm": "^4.0.1",
"tailwind-merge": "^3.4.0",
"uuid": "^13.0.0",
"zustand": "^5.0.9"
@@ -63,6 +76,8 @@
"@eslint/js": "^9.39.1",
"@playwright/test": "^1.52.0",
"@tailwindcss/postcss": "^4.1.17",
"@testing-library/react": "^16.1.0",
"@types/ioredis": "^4.28.10",
"@types/node": "^25.0.0",
"@types/react": "^19.2.7",
"@types/react-dom": "^19.2.3",
@@ -76,6 +91,9 @@
"eslint-plugin-react": "^7.37.5",
"eslint-plugin-react-hooks": "^7.0.1",
"globals": "^16.5.0",
"husky": "^9.1.7",
"jsdom": "^26.0.0",
"lint-staged": "^16.2.7",
"postcss": "^8.5.6",
"tailwindcss": "^4.1.17",
"typescript": "^5.9.3",
@@ -97,12 +115,30 @@
"build": {
"appId": "com.autoclaude.ui",
"productName": "Auto Claude",
"publish": [
{
"provider": "github",
"owner": "AndyMik90",
"repo": "Auto-Claude"
}
],
"directories": {
"output": "dist",
"buildResources": "resources"
},
"files": [
"out/**/*"
"out/**/*",
"package.json"
],
"extraResources": [
{
"from": "node_modules/node-pty",
"to": "node_modules/node-pty"
},
{
"from": "resources/icon.ico",
"to": "icon.ico"
}
],
"mac": {
"category": "public.app-category.developer-tools",
@@ -113,7 +149,7 @@
]
},
"win": {
"icon": "resources/icon-256.png",
"icon": "resources/icon.ico",
"target": [
"nsis",
"zip"
@@ -127,5 +163,10 @@
],
"category": "Development"
}
},
"lint-staged": {
"*.{ts,tsx}": [
"eslint --fix"
]
}
}
+2113 -360
View File
File diff suppressed because it is too large Load Diff
Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

+1
View File
@@ -14,6 +14,7 @@ export const app = {
};
return paths[name] || '/tmp';
}),
getAppPath: vi.fn(() => '/tmp/test-app'),
getVersion: vi.fn(() => '0.1.0'),
isPackaged: false,
on: vi.fn(),
@@ -36,8 +36,8 @@ function createTestPlan(overrides: Record<string, unknown> = {}): object {
phase: 1,
name: 'Test Phase',
type: 'implementation',
chunks: [
{ id: 'chunk-1', description: 'Chunk 1', status: 'pending' }
subtasks: [
{ id: 'subtask-1', description: 'Subtask 1', status: 'pending' }
]
}
],
@@ -153,8 +153,8 @@ describe('File Watcher Integration', () => {
phase: 1,
name: 'Test Phase',
type: 'implementation',
chunks: [
{ id: 'chunk-1', description: 'Chunk 1', status: 'completed' }
subtasks: [
{ id: 'subtask-1', description: 'Subtask 1', status: 'completed' }
]
}
]
@@ -167,7 +167,7 @@ describe('File Watcher Integration', () => {
expect(progressHandler).toHaveBeenCalledWith('task-1', expect.objectContaining({
phases: expect.arrayContaining([
expect.objectContaining({
chunks: expect.arrayContaining([
subtasks: expect.arrayContaining([
expect.objectContaining({ status: 'completed' })
])
})
@@ -3,7 +3,6 @@
* Tests IPC messages flow between main and renderer
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { EventEmitter } from 'events';
// Mock ipcRenderer for renderer-side tests
const mockIpcRenderer = {
@@ -85,12 +84,12 @@ describe('IPC Bridge Integration', () => {
id: string,
settings: object
) => Promise<unknown>;
await updateProjectSettings('project-id', { parallelEnabled: true });
await updateProjectSettings('project-id', { model: 'sonnet' });
expect(mockIpcRenderer.invoke).toHaveBeenCalledWith(
'project:updateSettings',
'project-id',
{ parallelEnabled: true }
{ model: 'sonnet' }
);
});
});
@@ -115,15 +114,18 @@ describe('IPC Bridge Integration', () => {
const createTask = electronAPI['createTask'] as (
projectId: string,
title: string,
desc: string
desc: string,
metadata?: unknown
) => Promise<unknown>;
await createTask('project-id', 'Task Title', 'Task description');
// Fourth argument is optional metadata (undefined when not provided)
expect(mockIpcRenderer.invoke).toHaveBeenCalledWith(
'task:create',
'project-id',
'Task Title',
'Task description'
'Task description',
undefined
);
});
@@ -282,7 +284,8 @@ describe('IPC Bridge Integration', () => {
const getAppVersion = electronAPI['getAppVersion'] as () => Promise<unknown>;
await getAppVersion();
expect(mockIpcRenderer.invoke).toHaveBeenCalledWith('app:version');
// getAppVersion now uses the app-update channel (from AppUpdateAPI which is spread last)
expect(mockIpcRenderer.invoke).toHaveBeenCalledWith('app-update:get-version');
});
});
});
@@ -29,18 +29,30 @@ vi.mock('child_process', () => ({
spawn: vi.fn(() => mockProcess)
}));
// Auto-claude source path (for getAutoBuildSourcePath to find)
const AUTO_CLAUDE_SOURCE = path.join(TEST_DIR, 'auto-claude-source');
// Setup test directories
function setupTestDirs(): void {
mkdirSync(TEST_PROJECT_PATH, { recursive: true });
mkdirSync(path.join(TEST_PROJECT_PATH, 'auto-claude'), { recursive: true });
// Create mock spec_runner.py
// Create auto-claude source directory that getAutoBuildSourcePath looks for
mkdirSync(AUTO_CLAUDE_SOURCE, { recursive: true });
// Create requirements.txt file (used as marker by getAutoBuildSourcePath)
writeFileSync(path.join(AUTO_CLAUDE_SOURCE, 'requirements.txt'), '# Mock requirements');
// Create runners subdirectory (where spec_runner.py lives after restructure)
mkdirSync(path.join(AUTO_CLAUDE_SOURCE, 'runners'), { recursive: true });
// Create mock spec_runner.py in runners/ subdirectory
writeFileSync(
path.join(TEST_PROJECT_PATH, 'auto-claude', 'spec_runner.py'),
path.join(AUTO_CLAUDE_SOURCE, 'runners', 'spec_runner.py'),
'# Mock spec runner\nprint("Starting spec creation")'
);
// Create mock run.py
writeFileSync(
path.join(TEST_PROJECT_PATH, 'auto-claude', 'run.py'),
path.join(AUTO_CLAUDE_SOURCE, 'run.py'),
'# Mock run.py\nprint("Starting task execution")'
);
}
@@ -72,9 +84,10 @@ describe('Subprocess Spawn Integration', () => {
describe('AgentManager', () => {
it('should spawn Python process for spec creation', async () => {
const { spawn } = await import('child_process');
const { AgentManager } = await import('../../main/agent-manager');
const { AgentManager } = await import('../../main/agent');
const manager = new AgentManager();
manager.configure(undefined, AUTO_CLAUDE_SOURCE);
manager.startSpecCreation('task-1', TEST_PROJECT_PATH, 'Test task description');
expect(spawn).toHaveBeenCalledWith(
@@ -85,7 +98,7 @@ describe('Subprocess Spawn Integration', () => {
'Test task description'
]),
expect.objectContaining({
cwd: TEST_PROJECT_PATH,
cwd: AUTO_CLAUDE_SOURCE, // Process runs from auto-claude source directory
env: expect.objectContaining({
PYTHONUNBUFFERED: '1'
})
@@ -95,25 +108,27 @@ describe('Subprocess Spawn Integration', () => {
it('should spawn Python process for task execution', async () => {
const { spawn } = await import('child_process');
const { AgentManager } = await import('../../main/agent-manager');
const { AgentManager } = await import('../../main/agent');
const manager = new AgentManager();
manager.configure(undefined, AUTO_CLAUDE_SOURCE);
manager.startTaskExecution('task-1', TEST_PROJECT_PATH, 'spec-001');
expect(spawn).toHaveBeenCalledWith(
'python3',
expect.arrayContaining([expect.stringContaining('run.py'), '--spec', 'spec-001']),
expect.objectContaining({
cwd: TEST_PROJECT_PATH
cwd: AUTO_CLAUDE_SOURCE // Process runs from auto-claude source directory
})
);
});
it('should spawn Python process for QA process', async () => {
const { spawn } = await import('child_process');
const { AgentManager } = await import('../../main/agent-manager');
const { AgentManager } = await import('../../main/agent');
const manager = new AgentManager();
manager.configure(undefined, AUTO_CLAUDE_SOURCE);
manager.startQAProcess('task-1', TEST_PROJECT_PATH, 'spec-001');
expect(spawn).toHaveBeenCalledWith(
@@ -125,32 +140,36 @@ describe('Subprocess Spawn Integration', () => {
'--qa'
]),
expect.objectContaining({
cwd: TEST_PROJECT_PATH
cwd: AUTO_CLAUDE_SOURCE // Process runs from auto-claude source directory
})
);
});
it('should include parallel options when specified', async () => {
it('should accept parallel options without affecting spawn args', async () => {
// Note: --parallel was removed from run.py CLI - parallel execution is handled internally by the agent
const { spawn } = await import('child_process');
const { AgentManager } = await import('../../main/agent-manager');
const { AgentManager } = await import('../../main/agent');
const manager = new AgentManager();
manager.configure(undefined, AUTO_CLAUDE_SOURCE);
manager.startTaskExecution('task-1', TEST_PROJECT_PATH, 'spec-001', {
parallel: true,
workers: 4
});
// Should spawn normally - parallel options don't affect CLI args anymore
expect(spawn).toHaveBeenCalledWith(
'python3',
expect.arrayContaining(['--parallel', '4']),
expect.arrayContaining([expect.stringContaining('run.py'), '--spec', 'spec-001']),
expect.any(Object)
);
});
it('should emit log events from stdout', async () => {
const { AgentManager } = await import('../../main/agent-manager');
const { AgentManager } = await import('../../main/agent');
const manager = new AgentManager();
manager.configure(undefined, AUTO_CLAUDE_SOURCE);
const logHandler = vi.fn();
manager.on('log', logHandler);
@@ -163,9 +182,10 @@ describe('Subprocess Spawn Integration', () => {
});
it('should emit log events from stderr', async () => {
const { AgentManager } = await import('../../main/agent-manager');
const { AgentManager } = await import('../../main/agent');
const manager = new AgentManager();
manager.configure(undefined, AUTO_CLAUDE_SOURCE);
const logHandler = vi.fn();
manager.on('log', logHandler);
@@ -178,9 +198,10 @@ describe('Subprocess Spawn Integration', () => {
});
it('should emit exit event when process exits', async () => {
const { AgentManager } = await import('../../main/agent-manager');
const { AgentManager } = await import('../../main/agent');
const manager = new AgentManager();
manager.configure(undefined, AUTO_CLAUDE_SOURCE);
const exitHandler = vi.fn();
manager.on('exit', exitHandler);
@@ -189,13 +210,15 @@ describe('Subprocess Spawn Integration', () => {
// Simulate process exit
mockProcess.emit('exit', 0);
expect(exitHandler).toHaveBeenCalledWith('task-1', 0);
// Exit event includes taskId, exit code, and process type
expect(exitHandler).toHaveBeenCalledWith('task-1', 0, expect.any(String));
});
it('should emit error event when process errors', async () => {
const { AgentManager } = await import('../../main/agent-manager');
const { AgentManager } = await import('../../main/agent');
const manager = new AgentManager();
manager.configure(undefined, AUTO_CLAUDE_SOURCE);
const errorHandler = vi.fn();
manager.on('error', errorHandler);
@@ -208,9 +231,10 @@ describe('Subprocess Spawn Integration', () => {
});
it('should kill task and remove from tracking', async () => {
const { AgentManager } = await import('../../main/agent-manager');
const { AgentManager } = await import('../../main/agent');
const manager = new AgentManager();
manager.configure(undefined, AUTO_CLAUDE_SOURCE);
manager.startSpecCreation('task-1', TEST_PROJECT_PATH, 'Test');
expect(manager.isRunning('task-1')).toBe(true);
@@ -223,7 +247,7 @@ describe('Subprocess Spawn Integration', () => {
});
it('should return false when killing non-existent task', async () => {
const { AgentManager } = await import('../../main/agent-manager');
const { AgentManager } = await import('../../main/agent');
const manager = new AgentManager();
const result = manager.killTask('nonexistent');
@@ -232,9 +256,10 @@ describe('Subprocess Spawn Integration', () => {
});
it('should track running tasks', async () => {
const { AgentManager } = await import('../../main/agent-manager');
const { AgentManager } = await import('../../main/agent');
const manager = new AgentManager();
manager.configure(undefined, AUTO_CLAUDE_SOURCE);
expect(manager.getRunningTasks()).toHaveLength(0);
manager.startSpecCreation('task-1', TEST_PROJECT_PATH, 'Test 1');
@@ -246,10 +271,10 @@ describe('Subprocess Spawn Integration', () => {
it('should use configured Python path', async () => {
const { spawn } = await import('child_process');
const { AgentManager } = await import('../../main/agent-manager');
const { AgentManager } = await import('../../main/agent');
const manager = new AgentManager();
manager.configure('/custom/python3');
manager.configure('/custom/python3', AUTO_CLAUDE_SOURCE);
manager.startSpecCreation('task-1', TEST_PROJECT_PATH, 'Test');
@@ -261,9 +286,10 @@ describe('Subprocess Spawn Integration', () => {
});
it('should kill all running tasks', async () => {
const { AgentManager } = await import('../../main/agent-manager');
const { AgentManager } = await import('../../main/agent');
const manager = new AgentManager();
manager.configure(undefined, AUTO_CLAUDE_SOURCE);
manager.startSpecCreation('task-1', TEST_PROJECT_PATH, 'Test 1');
manager.startTaskExecution('task-2', TEST_PROJECT_PATH, 'spec-001');
@@ -273,9 +299,10 @@ describe('Subprocess Spawn Integration', () => {
});
it('should kill existing process when starting new one for same task', async () => {
const { AgentManager } = await import('../../main/agent-manager');
const { AgentManager } = await import('../../main/agent');
const manager = new AgentManager();
manager.configure(undefined, AUTO_CLAUDE_SOURCE);
manager.startSpecCreation('task-1', TEST_PROJECT_PATH, 'Test 1');
// Start another process for same task
+18 -4
View File
@@ -10,11 +10,25 @@ export const TEST_DATA_DIR = '/tmp/auto-claude-ui-tests';
// Create fresh test directory before each test
beforeEach(() => {
if (existsSync(TEST_DATA_DIR)) {
rmSync(TEST_DATA_DIR, { recursive: true, force: true });
// Use a unique subdirectory per test to avoid race conditions in parallel tests
const testId = `test-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
const _testDir = path.join(TEST_DATA_DIR, testId);
try {
if (existsSync(TEST_DATA_DIR)) {
rmSync(TEST_DATA_DIR, { recursive: true, force: true });
}
} catch {
// Ignore errors if directory is in use by another parallel test
// Each test uses unique subdirectory anyway
}
try {
mkdirSync(TEST_DATA_DIR, { recursive: true });
mkdirSync(path.join(TEST_DATA_DIR, 'store'), { recursive: true });
} catch {
// Ignore errors if directory already exists from another parallel test
}
mkdirSync(TEST_DATA_DIR, { recursive: true });
mkdirSync(path.join(TEST_DATA_DIR, 'store'), { recursive: true });
});
// Clean up test directory after each test
@@ -11,6 +11,34 @@ import path from 'path';
const TEST_DIR = '/tmp/ipc-handlers-test';
const TEST_PROJECT_PATH = path.join(TEST_DIR, 'test-project');
// Mock electron-updater before importing
vi.mock('electron-updater', () => ({
autoUpdater: {
autoDownload: true,
autoInstallOnAppQuit: true,
on: vi.fn(),
checkForUpdates: vi.fn(() => Promise.resolve(null)),
downloadUpdate: vi.fn(() => Promise.resolve()),
quitAndInstall: vi.fn()
}
}));
// Mock @electron-toolkit/utils before importing
vi.mock('@electron-toolkit/utils', () => ({
is: {
dev: true,
windows: process.platform === 'win32',
macos: process.platform === 'darwin',
linux: process.platform === 'linux'
},
electronApp: {
setAppUserModelId: vi.fn()
},
optimizer: {
watchWindowShortcuts: vi.fn()
}
}));
// Mock modules before importing
vi.mock('electron', () => {
const mockIpcMain = new (class extends EventEmitter {
@@ -43,6 +71,7 @@ vi.mock('electron', () => {
if (name === 'userData') return path.join(TEST_DIR, 'userData');
return TEST_DIR;
}),
getAppPath: vi.fn(() => TEST_DIR),
getVersion: vi.fn(() => '0.1.0'),
isPackaged: false
},
@@ -91,6 +120,11 @@ describe('IPC Handlers', () => {
invokeClaude: ReturnType<typeof vi.fn>;
killAll: ReturnType<typeof vi.fn>;
};
let mockPythonEnvManager: {
on: ReturnType<typeof vi.fn>;
initialize: ReturnType<typeof vi.fn>;
getStatus: ReturnType<typeof vi.fn>;
};
beforeEach(async () => {
cleanupTestDirs();
@@ -125,6 +159,12 @@ describe('IPC Handlers', () => {
killAll: vi.fn(() => Promise.resolve())
};
mockPythonEnvManager = {
on: vi.fn(),
initialize: vi.fn(() => Promise.resolve({ ready: true, pythonPath: '/usr/bin/python3', venvExists: true, depsInstalled: true })),
getStatus: vi.fn(() => Promise.resolve({ ready: true, pythonPath: '/usr/bin/python3', venvExists: true, depsInstalled: true }))
};
// Need to reset modules to re-register handlers
vi.resetModules();
});
@@ -137,7 +177,7 @@ describe('IPC Handlers', () => {
describe('project:add handler', () => {
it('should return error for non-existent path', async () => {
const { setupIpcHandlers } = await import('../ipc-handlers');
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never, mockPythonEnvManager as never);
const result = await ipcMain.invokeHandler('project:add', {}, '/nonexistent/path');
@@ -149,7 +189,7 @@ describe('IPC Handlers', () => {
it('should successfully add an existing project', async () => {
const { setupIpcHandlers } = await import('../ipc-handlers');
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never, mockPythonEnvManager as never);
const result = await ipcMain.invokeHandler('project:add', {}, TEST_PROJECT_PATH);
@@ -162,7 +202,7 @@ describe('IPC Handlers', () => {
it('should return existing project if already added', async () => {
const { setupIpcHandlers } = await import('../ipc-handlers');
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never, mockPythonEnvManager as never);
// Add project twice
const result1 = await ipcMain.invokeHandler('project:add', {}, TEST_PROJECT_PATH);
@@ -177,7 +217,7 @@ describe('IPC Handlers', () => {
describe('project:list handler', () => {
it('should return empty array when no projects', async () => {
const { setupIpcHandlers } = await import('../ipc-handlers');
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never, mockPythonEnvManager as never);
const result = await ipcMain.invokeHandler('project:list', {});
@@ -189,7 +229,7 @@ describe('IPC Handlers', () => {
it('should return all added projects', async () => {
const { setupIpcHandlers } = await import('../ipc-handlers');
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never, mockPythonEnvManager as never);
// Add a project
await ipcMain.invokeHandler('project:add', {}, TEST_PROJECT_PATH);
@@ -205,7 +245,7 @@ describe('IPC Handlers', () => {
describe('project:remove handler', () => {
it('should return false for non-existent project', async () => {
const { setupIpcHandlers } = await import('../ipc-handlers');
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never, mockPythonEnvManager as never);
const result = await ipcMain.invokeHandler('project:remove', {}, 'nonexistent-id');
@@ -214,7 +254,7 @@ describe('IPC Handlers', () => {
it('should successfully remove an existing project', async () => {
const { setupIpcHandlers } = await import('../ipc-handlers');
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never, mockPythonEnvManager as never);
// Add a project first
const addResult = await ipcMain.invokeHandler('project:add', {}, TEST_PROJECT_PATH);
@@ -235,13 +275,13 @@ describe('IPC Handlers', () => {
describe('project:updateSettings handler', () => {
it('should return error for non-existent project', async () => {
const { setupIpcHandlers } = await import('../ipc-handlers');
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never, mockPythonEnvManager as never);
const result = await ipcMain.invokeHandler(
'project:updateSettings',
{},
'nonexistent-id',
{ parallelEnabled: true }
{ model: 'sonnet' }
);
expect(result).toEqual({
@@ -252,7 +292,7 @@ describe('IPC Handlers', () => {
it('should successfully update project settings', async () => {
const { setupIpcHandlers } = await import('../ipc-handlers');
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never, mockPythonEnvManager as never);
// Add a project first
const addResult = await ipcMain.invokeHandler('project:add', {}, TEST_PROJECT_PATH);
@@ -263,7 +303,7 @@ describe('IPC Handlers', () => {
'project:updateSettings',
{},
projectId,
{ parallelEnabled: true, maxWorkers: 4 }
{ model: 'sonnet', linearSync: true }
);
expect(result).toEqual({ success: true });
@@ -273,7 +313,7 @@ describe('IPC Handlers', () => {
describe('task:list handler', () => {
it('should return empty array for project with no specs', async () => {
const { setupIpcHandlers } = await import('../ipc-handlers');
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never, mockPythonEnvManager as never);
// Add a project first
const addResult = await ipcMain.invokeHandler('project:add', {}, TEST_PROJECT_PATH);
@@ -289,14 +329,17 @@ describe('IPC Handlers', () => {
it('should return tasks when specs exist', async () => {
const { setupIpcHandlers } = await import('../ipc-handlers');
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never, mockPythonEnvManager as never);
// Add a project first
// Create .auto-claude directory first (before adding project so it gets detected)
mkdirSync(path.join(TEST_PROJECT_PATH, '.auto-claude', 'specs'), { recursive: true });
// Add a project - it will detect .auto-claude
const addResult = await ipcMain.invokeHandler('project:add', {}, TEST_PROJECT_PATH);
const projectId = (addResult as { data: { id: string } }).data.id;
// Create a spec directory with implementation plan
const specDir = path.join(TEST_PROJECT_PATH, 'auto-claude', 'specs', '001-test-feature');
// Create a spec directory with implementation plan in .auto-claude/specs
const specDir = path.join(TEST_PROJECT_PATH, '.auto-claude', 'specs', '001-test-feature');
mkdirSync(specDir, { recursive: true });
writeFileSync(path.join(specDir, 'implementation_plan.json'), JSON.stringify({
feature: 'Test Feature',
@@ -306,7 +349,7 @@ describe('IPC Handlers', () => {
phase: 1,
name: 'Test Phase',
type: 'implementation',
chunks: [{ id: 'chunk-1', description: 'Test chunk', status: 'pending' }]
subtasks: [{ id: 'subtask-1', description: 'Test subtask', status: 'pending' }]
}],
final_acceptance: [],
created_at: new Date().toISOString(),
@@ -325,7 +368,7 @@ describe('IPC Handlers', () => {
describe('task:create handler', () => {
it('should return error for non-existent project', async () => {
const { setupIpcHandlers } = await import('../ipc-handlers');
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never, mockPythonEnvManager as never);
const result = await ipcMain.invokeHandler(
'task:create',
@@ -341,9 +384,12 @@ describe('IPC Handlers', () => {
});
});
it('should create task and start spec creation', async () => {
it('should create task in backlog status', async () => {
const { setupIpcHandlers } = await import('../ipc-handlers');
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never, mockPythonEnvManager as never);
// Create .auto-claude directory first (before adding project so it gets detected)
mkdirSync(path.join(TEST_PROJECT_PATH, '.auto-claude', 'specs'), { recursive: true });
// Add a project first
const addResult = await ipcMain.invokeHandler('project:add', {}, TEST_PROJECT_PATH);
@@ -358,14 +404,16 @@ describe('IPC Handlers', () => {
);
expect(result).toHaveProperty('success', true);
expect(mockAgentManager.startSpecCreation).toHaveBeenCalled();
// Task is created in backlog status, spec creation starts when task:start is called
const task = (result as { data: { status: string } }).data;
expect(task.status).toBe('backlog');
});
});
describe('settings:get handler', () => {
it('should return default settings when no settings file exists', async () => {
const { setupIpcHandlers } = await import('../ipc-handlers');
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never, mockPythonEnvManager as never);
const result = await ipcMain.invokeHandler('settings:get', {});
@@ -378,7 +426,7 @@ describe('IPC Handlers', () => {
describe('settings:save handler', () => {
it('should save settings successfully', async () => {
const { setupIpcHandlers } = await import('../ipc-handlers');
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never, mockPythonEnvManager as never);
const result = await ipcMain.invokeHandler(
'settings:save',
@@ -397,7 +445,7 @@ describe('IPC Handlers', () => {
it('should configure agent manager when paths change', async () => {
const { setupIpcHandlers } = await import('../ipc-handlers');
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never, mockPythonEnvManager as never);
await ipcMain.invokeHandler(
'settings:save',
@@ -412,7 +460,7 @@ describe('IPC Handlers', () => {
describe('app:version handler', () => {
it('should return app version', async () => {
const { setupIpcHandlers } = await import('../ipc-handlers');
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never, mockPythonEnvManager as never);
const result = await ipcMain.invokeHandler('app:version', {});
@@ -423,7 +471,7 @@ describe('IPC Handlers', () => {
describe('Agent Manager event forwarding', () => {
it('should forward log events to renderer', async () => {
const { setupIpcHandlers } = await import('../ipc-handlers');
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never, mockPythonEnvManager as never);
mockAgentManager.emit('log', 'task-1', 'Test log message');
@@ -436,7 +484,7 @@ describe('IPC Handlers', () => {
it('should forward error events to renderer', async () => {
const { setupIpcHandlers } = await import('../ipc-handlers');
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never, mockPythonEnvManager as never);
mockAgentManager.emit('error', 'task-1', 'Test error message');
@@ -449,14 +497,15 @@ describe('IPC Handlers', () => {
it('should forward exit events with status change', async () => {
const { setupIpcHandlers } = await import('../ipc-handlers');
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never, mockPythonEnvManager as never);
mockAgentManager.emit('exit', 'task-1', 0);
// Exit event with task-execution processType should result in human_review status
mockAgentManager.emit('exit', 'task-1', 0, 'task-execution');
expect(mockMainWindow.webContents.send).toHaveBeenCalledWith(
'task:statusChange',
'task-1',
'ai_review'
'human_review'
);
});
});
@@ -83,15 +83,15 @@ describe('ProjectStore', () => {
});
it('should detect auto-claude directory if present', async () => {
// Create auto-claude directory
mkdirSync(path.join(TEST_PROJECT_PATH, 'auto-claude'), { recursive: true });
// Create .auto-claude directory (the data directory, not source code)
mkdirSync(path.join(TEST_PROJECT_PATH, '.auto-claude'), { recursive: true });
const { ProjectStore } = await import('../project-store');
const store = new ProjectStore();
const project = store.addProject(TEST_PROJECT_PATH);
expect(project.autoBuildPath).toBe('auto-claude');
expect(project.autoBuildPath).toBe('.auto-claude');
});
it('should set empty autoBuildPath if not present', async () => {
@@ -208,7 +208,7 @@ describe('ProjectStore', () => {
const { ProjectStore } = await import('../project-store');
const store = new ProjectStore();
const result = store.updateProjectSettings('nonexistent-id', { parallelEnabled: true });
const result = store.updateProjectSettings('nonexistent-id', { model: 'sonnet' });
expect(result).toBeUndefined();
});
@@ -219,13 +219,13 @@ describe('ProjectStore', () => {
const project = store.addProject(TEST_PROJECT_PATH);
const updated = store.updateProjectSettings(project.id, {
parallelEnabled: true,
maxWorkers: 4
model: 'sonnet',
linearSync: true
});
expect(updated).toBeDefined();
expect(updated?.settings.parallelEnabled).toBe(true);
expect(updated?.settings.maxWorkers).toBe(4);
expect(updated?.settings.model).toBe('sonnet');
expect(updated?.settings.linearSync).toBe(true);
});
it('should update updatedAt timestamp', async () => {
@@ -238,7 +238,7 @@ describe('ProjectStore', () => {
// Small delay to ensure timestamp difference
await new Promise((resolve) => setTimeout(resolve, 10));
const updated = store.updateProjectSettings(project.id, { parallelEnabled: true });
const updated = store.updateProjectSettings(project.id, { model: 'haiku' });
expect(updated?.updatedAt.getTime()).toBeGreaterThan(originalUpdatedAt.getTime());
});
@@ -248,12 +248,12 @@ describe('ProjectStore', () => {
const store = new ProjectStore();
const project = store.addProject(TEST_PROJECT_PATH);
store.updateProjectSettings(project.id, { maxWorkers: 8 });
store.updateProjectSettings(project.id, { model: 'sonnet' });
// Read directly from file
const storePath = path.join(USER_DATA_PATH, 'store', 'projects.json');
const content = JSON.parse(readFileSync(storePath, 'utf-8'));
expect(content.projects[0].settings.maxWorkers).toBe(8);
expect(content.projects[0].settings.model).toBe('sonnet');
});
});
@@ -278,8 +278,8 @@ describe('ProjectStore', () => {
});
it('should read tasks from filesystem correctly', async () => {
// Create spec directory structure
const specsDir = path.join(TEST_PROJECT_PATH, 'auto-claude', 'specs', '001-test-feature');
// Create spec directory structure in .auto-claude (the data directory)
const specsDir = path.join(TEST_PROJECT_PATH, '.auto-claude', 'specs', '001-test-feature');
mkdirSync(specsDir, { recursive: true });
const plan = {
@@ -291,9 +291,9 @@ describe('ProjectStore', () => {
phase: 1,
name: 'Phase 1',
type: 'implementation',
chunks: [
{ id: 'chunk-1', description: 'First chunk', status: 'completed' },
{ id: 'chunk-2', description: 'Second chunk', status: 'pending' }
subtasks: [
{ id: 'subtask-1', description: 'First subtask', status: 'completed' },
{ id: 'subtask-2', description: 'Second subtask', status: 'pending' }
]
}
],
@@ -320,12 +320,12 @@ describe('ProjectStore', () => {
expect(tasks).toHaveLength(1);
expect(tasks[0].title).toBe('Test Feature');
expect(tasks[0].specId).toBe('001-test-feature');
expect(tasks[0].chunks).toHaveLength(2);
expect(tasks[0].subtasks).toHaveLength(2);
expect(tasks[0].status).toBe('in_progress'); // Some completed, some pending
});
it('should determine status as backlog when no chunks completed', async () => {
const specsDir = path.join(TEST_PROJECT_PATH, 'auto-claude', 'specs', '002-pending');
it('should determine status as backlog when no subtasks completed', async () => {
const specsDir = path.join(TEST_PROJECT_PATH, '.auto-claude', 'specs', '002-pending');
mkdirSync(specsDir, { recursive: true });
const plan = {
@@ -337,9 +337,9 @@ describe('ProjectStore', () => {
phase: 1,
name: 'Phase 1',
type: 'implementation',
chunks: [
{ id: 'chunk-1', description: 'Chunk 1', status: 'pending' },
{ id: 'chunk-2', description: 'Chunk 2', status: 'pending' }
subtasks: [
{ id: 'subtask-1', description: 'Subtask 1', status: 'pending' },
{ id: 'subtask-2', description: 'Subtask 2', status: 'pending' }
]
}
],
@@ -363,8 +363,8 @@ describe('ProjectStore', () => {
expect(tasks[0].status).toBe('backlog');
});
it('should determine status as ai_review when all chunks completed', async () => {
const specsDir = path.join(TEST_PROJECT_PATH, 'auto-claude', 'specs', '003-complete');
it('should determine status as ai_review when all subtasks completed', async () => {
const specsDir = path.join(TEST_PROJECT_PATH, '.auto-claude', 'specs', '003-complete');
mkdirSync(specsDir, { recursive: true });
const plan = {
@@ -376,9 +376,9 @@ describe('ProjectStore', () => {
phase: 1,
name: 'Phase 1',
type: 'implementation',
chunks: [
{ id: 'chunk-1', description: 'Chunk 1', status: 'completed' },
{ id: 'chunk-2', description: 'Chunk 2', status: 'completed' }
subtasks: [
{ id: 'subtask-1', description: 'Subtask 1', status: 'completed' },
{ id: 'subtask-2', description: 'Subtask 2', status: 'completed' }
]
}
],
@@ -403,7 +403,7 @@ describe('ProjectStore', () => {
});
it('should determine status as human_review when QA report rejected', async () => {
const specsDir = path.join(TEST_PROJECT_PATH, 'auto-claude', 'specs', '004-rejected');
const specsDir = path.join(TEST_PROJECT_PATH, '.auto-claude', 'specs', '004-rejected');
mkdirSync(specsDir, { recursive: true });
const plan = {
@@ -415,8 +415,8 @@ describe('ProjectStore', () => {
phase: 1,
name: 'Phase 1',
type: 'implementation',
chunks: [
{ id: 'chunk-1', description: 'Chunk 1', status: 'completed' }
subtasks: [
{ id: 'subtask-1', description: 'Subtask 1', status: 'completed' }
]
}
],
@@ -445,8 +445,9 @@ describe('ProjectStore', () => {
expect(tasks[0].status).toBe('human_review');
});
it('should determine status as done when QA report approved', async () => {
const specsDir = path.join(TEST_PROJECT_PATH, 'auto-claude', 'specs', '005-approved');
it('should determine status as human_review when QA report approved', async () => {
// QA approval moves task to human_review (user needs to review before marking done)
const specsDir = path.join(TEST_PROJECT_PATH, '.auto-claude', 'specs', '005-approved');
mkdirSync(specsDir, { recursive: true });
const plan = {
@@ -458,8 +459,8 @@ describe('ProjectStore', () => {
phase: 1,
name: 'Phase 1',
type: 'implementation',
chunks: [
{ id: 'chunk-1', description: 'Chunk 1', status: 'completed' }
subtasks: [
{ id: 'subtask-1', description: 'Subtask 1', status: 'completed' }
]
}
],
@@ -485,6 +486,47 @@ describe('ProjectStore', () => {
const project = store.addProject(TEST_PROJECT_PATH);
const tasks = store.getTasks(project.id);
expect(tasks[0].status).toBe('human_review');
expect(tasks[0].reviewReason).toBe('completed');
});
it('should determine status as done when plan status is explicitly done', async () => {
// User explicitly marking task as done via drag-and-drop sets status to done
const specsDir = path.join(TEST_PROJECT_PATH, '.auto-claude', 'specs', '006-done');
mkdirSync(specsDir, { recursive: true });
const plan = {
feature: 'Done Feature',
workflow_type: 'feature',
services_involved: [],
status: 'done', // Explicitly set by user
phases: [
{
phase: 1,
name: 'Phase 1',
type: 'implementation',
subtasks: [
{ id: 'subtask-1', description: 'Subtask 1', status: 'completed' }
]
}
],
final_acceptance: [],
created_at: '2024-01-01T00:00:00Z',
updated_at: '2024-01-01T00:00:00Z',
spec_file: 'spec.md'
};
writeFileSync(
path.join(specsDir, 'implementation_plan.json'),
JSON.stringify(plan)
);
const { ProjectStore } = await import('../project-store');
const store = new ProjectStore();
const project = store.addProject(TEST_PROJECT_PATH);
const tasks = store.getTasks(project.id);
expect(tasks[0].status).toBe('done');
});
});
@@ -501,8 +543,6 @@ describe('ProjectStore', () => {
path: '/test/path',
autoBuildPath: '',
settings: {
parallelEnabled: false,
maxWorkers: 2,
model: 'sonnet',
memoryBackend: 'file',
linearSync: false,
@@ -511,7 +551,9 @@ describe('ProjectStore', () => {
onTaskFailed: true,
onReviewNeeded: true,
sound: false
}
},
graphitiMcpEnabled: true,
graphitiMcpUrl: 'http://localhost:8000/mcp/'
},
createdAt: '2024-01-01T00:00:00Z',
updatedAt: '2024-01-01T00:00:00Z'
+29 -948
View File
@@ -1,951 +1,32 @@
import { spawn, ChildProcess } from 'child_process';
import { EventEmitter } from 'events';
import path from 'path';
import { existsSync, readFileSync } from 'fs';
import { app } from 'electron';
interface AgentProcess {
taskId: string;
process: ChildProcess;
startedAt: Date;
projectPath?: string; // For ideation processes to load session on completion
}
export interface ExecutionProgressData {
phase: 'idle' | 'planning' | 'coding' | 'qa_review' | 'qa_fixing' | 'complete' | 'failed';
phaseProgress: number;
overallProgress: number;
currentChunk?: string;
message?: string;
}
export type ProcessType = 'spec-creation' | 'task-execution' | 'qa-process';
export interface AgentManagerEvents {
log: (taskId: string, log: string) => void;
error: (taskId: string, error: string) => void;
exit: (taskId: string, code: number | null, processType: ProcessType) => void;
'execution-progress': (taskId: string, progress: ExecutionProgressData) => void;
}
/**
* Manages Python subprocess spawning for auto-claude agents
* AgentManager - Slim re-export facade
*
* This file maintains backward compatibility for imports using the old path.
* The actual implementation has been refactored into modular components in ./agent/
*
* For new code, prefer importing directly from './agent':
* import { AgentManager } from './agent'
*
* This facade ensures existing imports continue to work:
* import { AgentManager } from './agent-manager'
*/
export class AgentManager extends EventEmitter {
private processes: Map<string, AgentProcess> = new Map();
private pythonPath: string = 'python3';
private autoBuildSourcePath: string = ''; // Source auto-claude repo location
constructor() {
super();
}
/**
* Configure paths for Python and auto-claude source
*/
configure(pythonPath?: string, autoBuildSourcePath?: string): void {
if (pythonPath) {
this.pythonPath = pythonPath;
}
if (autoBuildSourcePath) {
this.autoBuildSourcePath = autoBuildSourcePath;
}
}
/**
* Get the auto-claude source path (detects automatically if not configured)
*/
private getAutoBuildSourcePath(): string | null {
// If manually configured, use that
if (this.autoBuildSourcePath && existsSync(this.autoBuildSourcePath)) {
return this.autoBuildSourcePath;
}
// Auto-detect from app location
const possiblePaths = [
// Dev mode: from dist/main -> ../../auto-claude (sibling to auto-claude-ui)
path.resolve(__dirname, '..', '..', '..', 'auto-claude'),
// Alternative: from app root
path.resolve(app.getAppPath(), '..', 'auto-claude'),
// If running from repo root
path.resolve(process.cwd(), 'auto-claude')
];
for (const p of possiblePaths) {
if (existsSync(p) && existsSync(path.join(p, 'VERSION'))) {
return p;
}
}
return null;
}
/**
* Load environment variables from auto-claude .env file
*/
private loadAutoBuildEnv(): Record<string, string> {
const autoBuildSource = this.getAutoBuildSourcePath();
if (!autoBuildSource) {
console.log('[loadAutoBuildEnv] No auto-build source path found');
return {};
}
const envPath = path.join(autoBuildSource, '.env');
console.log('[loadAutoBuildEnv] Looking for .env at:', envPath);
if (!existsSync(envPath)) {
console.log('[loadAutoBuildEnv] .env file does not exist');
return {};
}
try {
const envContent = readFileSync(envPath, 'utf-8');
const envVars: Record<string, string> = {};
for (const line of envContent.split('\n')) {
const trimmed = line.trim();
// Skip comments and empty lines
if (!trimmed || trimmed.startsWith('#')) {
continue;
}
const eqIndex = trimmed.indexOf('=');
if (eqIndex > 0) {
const key = trimmed.substring(0, eqIndex).trim();
let value = trimmed.substring(eqIndex + 1).trim();
// Remove quotes if present
if ((value.startsWith('"') && value.endsWith('"')) ||
(value.startsWith("'") && value.endsWith("'"))) {
value = value.slice(1, -1);
}
envVars[key] = value;
}
}
return envVars;
} catch {
return {};
}
}
/**
* Start spec creation process
*/
startSpecCreation(
taskId: string,
projectPath: string,
taskDescription: string,
specDir?: string, // Optional spec directory (when task already has a directory created by UI)
devMode: boolean = false, // Dev mode: use dev/auto-claude/specs/ for framework development
metadata?: { requireReviewBeforeCoding?: boolean } // Task metadata to check for review requirement
): void {
// Use source auto-claude path (the repo), not the project's auto-claude
const autoBuildSource = this.getAutoBuildSourcePath();
if (!autoBuildSource) {
this.emit('error', taskId, 'Auto-build source path not found. Please configure it in App Settings.');
return;
}
const specRunnerPath = path.join(autoBuildSource, 'spec_runner.py');
if (!existsSync(specRunnerPath)) {
this.emit('error', taskId, `Spec runner not found at: ${specRunnerPath}`);
return;
}
// Load environment variables from auto-claude .env file
const autoBuildEnv = this.loadAutoBuildEnv();
// spec_runner.py will auto-start run.py after spec creation completes
const args = [specRunnerPath, '--task', taskDescription, '--project-dir', projectPath];
// Pass spec directory if provided (for UI-created tasks that already have a directory)
if (specDir) {
args.push('--spec-dir', specDir);
}
// Check if user requires review before coding
// If requireReviewBeforeCoding is true, skip auto-approve to trigger review checkpoint
if (!metadata?.requireReviewBeforeCoding) {
// Auto-approve: When user starts a task from the UI without requiring review, that IS their approval
// No need for interactive review checkpoint - user explicitly clicked "Start"
args.push('--auto-approve');
}
// If requireReviewBeforeCoding is true, don't add --auto-approve, allowing the review checkpoint to appear
// Pass --dev flag for framework development mode
if (devMode) {
args.push('--dev');
}
// Note: This is spec-creation but it chains to task-execution via run.py
// So we treat the whole thing as task-execution for status purposes
this.spawnProcess(taskId, autoBuildSource, args, autoBuildEnv, 'task-execution');
}
/**
* Start task execution (run.py)
*/
startTaskExecution(
taskId: string,
projectPath: string,
specId: string,
options: { parallel?: boolean; workers?: number; devMode?: boolean } = {}
): void {
console.log('[AgentManager] startTaskExecution called for:', taskId, specId);
// Use source auto-claude path (the repo), not the project's auto-claude
const autoBuildSource = this.getAutoBuildSourcePath();
if (!autoBuildSource) {
console.log('[AgentManager] ERROR: Auto-build source path not found');
this.emit('error', taskId, 'Auto-build source path not found. Please configure it in App Settings.');
return;
}
const runPath = path.join(autoBuildSource, 'run.py');
console.log('[AgentManager] runPath:', runPath);
if (!existsSync(runPath)) {
console.log('[AgentManager] ERROR: Run script not found at:', runPath);
this.emit('error', taskId, `Run script not found at: ${runPath}`);
return;
}
// Load environment variables from auto-claude .env file
const autoBuildEnv = this.loadAutoBuildEnv();
const args = [runPath, '--spec', specId, '--project-dir', projectPath];
// Always use auto-continue when running from UI (non-interactive)
args.push('--auto-continue');
// Force: When user starts a task from the UI, that IS their approval
// The review checkpoint is for CLI users who need to review before building
// UI users have already seen the spec in the interface before clicking "Start"
args.push('--force');
if (options.parallel && options.workers) {
args.push('--parallel', options.workers.toString());
}
// Pass --dev flag for framework development mode
if (options.devMode) {
args.push('--dev');
}
console.log('[AgentManager] Spawning process with args:', args);
this.spawnProcess(taskId, autoBuildSource, args, autoBuildEnv, 'task-execution');
}
/**
* Start QA process
*/
startQAProcess(
taskId: string,
projectPath: string,
specId: string,
devMode: boolean = false
): void {
// Use source auto-claude path (the repo), not the project's auto-claude
const autoBuildSource = this.getAutoBuildSourcePath();
if (!autoBuildSource) {
this.emit('error', taskId, 'Auto-build source path not found. Please configure it in App Settings.');
return;
}
const runPath = path.join(autoBuildSource, 'run.py');
if (!existsSync(runPath)) {
this.emit('error', taskId, `Run script not found at: ${runPath}`);
return;
}
// Load environment variables from auto-claude .env file
const autoBuildEnv = this.loadAutoBuildEnv();
const args = [runPath, '--spec', specId, '--project-dir', projectPath, '--qa'];
// Pass --dev flag for framework development mode
if (devMode) {
args.push('--dev');
}
this.spawnProcess(taskId, autoBuildSource, args, autoBuildEnv, 'qa-process');
}
/**
* Start roadmap generation process
*/
startRoadmapGeneration(
projectId: string,
projectPath: string,
refresh: boolean = false
): void {
// Use source auto-claude path (the repo), not the project's auto-claude
const autoBuildSource = this.getAutoBuildSourcePath();
if (!autoBuildSource) {
this.emit('roadmap-error', projectId, 'Auto-build source path not found. Please configure it in App Settings.');
return;
}
const roadmapRunnerPath = path.join(autoBuildSource, 'roadmap_runner.py');
if (!existsSync(roadmapRunnerPath)) {
this.emit('roadmap-error', projectId, `Roadmap runner not found at: ${roadmapRunnerPath}`);
return;
}
const args = [roadmapRunnerPath, '--project', projectPath];
if (refresh) {
args.push('--refresh');
}
// Use projectId as taskId for roadmap operations
this.spawnRoadmapProcess(projectId, projectPath, args);
}
/**
* Start ideation generation process
*/
startIdeationGeneration(
projectId: string,
projectPath: string,
config: {
enabledTypes: string[];
includeRoadmapContext: boolean;
includeKanbanContext: boolean;
maxIdeasPerType: number;
append?: boolean;
},
refresh: boolean = false
): void {
// Use source auto-claude path (the repo), not the project's auto-claude
const autoBuildSource = this.getAutoBuildSourcePath();
if (!autoBuildSource) {
this.emit('ideation-error', projectId, 'Auto-build source path not found. Please configure it in App Settings.');
return;
}
const ideationRunnerPath = path.join(autoBuildSource, 'ideation_runner.py');
if (!existsSync(ideationRunnerPath)) {
this.emit('ideation-error', projectId, `Ideation runner not found at: ${ideationRunnerPath}`);
return;
}
const args = [ideationRunnerPath, '--project', projectPath];
// Add enabled types as comma-separated list
if (config.enabledTypes.length > 0) {
args.push('--types', config.enabledTypes.join(','));
}
// Add context flags (script uses --no-roadmap/--no-kanban negative flags)
if (!config.includeRoadmapContext) {
args.push('--no-roadmap');
}
if (!config.includeKanbanContext) {
args.push('--no-kanban');
}
// Add max ideas per type
if (config.maxIdeasPerType) {
args.push('--max-ideas', config.maxIdeasPerType.toString());
}
if (refresh) {
args.push('--refresh');
}
// Add append flag to preserve existing ideas
if (config.append) {
args.push('--append');
}
// Use projectId as taskId for ideation operations
this.spawnIdeationProcess(projectId, projectPath, args);
}
/**
* Spawn a Python process for ideation generation
*/
private spawnIdeationProcess(
projectId: string,
projectPath: string,
args: string[]
): void {
// Kill existing process for this project if any
this.killTask(projectId);
// Run from auto-claude source directory so imports work correctly
const autoBuildSource = this.getAutoBuildSourcePath();
const cwd = autoBuildSource || process.cwd();
// Load environment variables from auto-claude .env file
const autoBuildEnv = this.loadAutoBuildEnv();
const childProcess = spawn(this.pythonPath, args, {
cwd,
env: {
...process.env,
...autoBuildEnv, // Include auto-claude .env variables (like CLAUDE_CODE_OAUTH_TOKEN)
PYTHONUNBUFFERED: '1'
}
});
this.processes.set(projectId, {
taskId: projectId,
process: childProcess,
startedAt: new Date(),
projectPath // Store project path for loading session on completion
});
// Track progress through output
let progressPhase = 'analyzing';
let progressPercent = 10;
// Helper to emit logs - split multi-line output into individual log lines
const emitLogs = (log: string) => {
const lines = log.split('\n').filter(line => line.trim().length > 0);
for (const line of lines) {
const trimmed = line.trim();
if (trimmed.length > 0) {
console.log('[Ideation]', trimmed);
this.emit('ideation-log', projectId, trimmed);
}
}
};
console.log('[Ideation] Starting ideation process with args:', args);
console.log('[Ideation] CWD:', cwd);
console.log('[Ideation] Python path:', this.pythonPath);
console.log('[Ideation] Env vars loaded:', Object.keys(autoBuildEnv));
console.log('[Ideation] Has CLAUDE_CODE_OAUTH_TOKEN:', !!autoBuildEnv['CLAUDE_CODE_OAUTH_TOKEN']);
// Track completed types for progress calculation
const completedTypes = new Set<string>();
const totalTypes = args.filter(a => a !== '--types').length > 0 ? 7 : 7; // Default all types
// Handle stdout
childProcess.stdout?.on('data', (data: Buffer) => {
const log = data.toString();
// Emit all log lines for the activity log
emitLogs(log);
// Check for streaming type completion signals
const typeCompleteMatch = log.match(/IDEATION_TYPE_COMPLETE:(\w+):(\d+)/);
if (typeCompleteMatch) {
const [, ideationType, ideasCount] = typeCompleteMatch;
completedTypes.add(ideationType);
console.log(`[Ideation] Type complete: ${ideationType} with ${ideasCount} ideas`);
// Emit event for UI to load this type's ideas immediately
this.emit('ideation-type-complete', projectId, ideationType, parseInt(ideasCount, 10));
}
const typeFailedMatch = log.match(/IDEATION_TYPE_FAILED:(\w+)/);
if (typeFailedMatch) {
const [, ideationType] = typeFailedMatch;
completedTypes.add(ideationType);
console.log(`[Ideation] Type failed: ${ideationType}`);
this.emit('ideation-type-failed', projectId, ideationType);
}
// Parse progress from output - track phase transitions
if (log.includes('PROJECT INDEX') || log.includes('PROJECT ANALYSIS')) {
progressPhase = 'analyzing';
progressPercent = 10;
} else if (log.includes('CONTEXT GATHERING')) {
progressPhase = 'discovering';
progressPercent = 20;
} else if (log.includes('GENERATING IDEAS (PARALLEL)') || log.includes('Starting') && log.includes('ideation agents in parallel')) {
progressPhase = 'generating';
progressPercent = 30;
} else if (log.includes('MERGE') || log.includes('FINALIZE')) {
progressPhase = 'finalizing';
progressPercent = 90;
} else if (log.includes('IDEATION COMPLETE')) {
progressPhase = 'complete';
progressPercent = 100;
}
// Update progress based on completed types during generation phase
if (progressPhase === 'generating' && completedTypes.size > 0) {
// Progress from 30% to 90% based on completed types
progressPercent = 30 + Math.floor((completedTypes.size / totalTypes) * 60);
}
// Emit progress update with a clean message for the status bar
const statusMessage = log.trim().split('\n')[0].substring(0, 200);
this.emit('ideation-progress', projectId, {
phase: progressPhase,
progress: progressPercent,
message: statusMessage,
completedTypes: Array.from(completedTypes)
});
});
// Handle stderr - also emit as logs
childProcess.stderr?.on('data', (data: Buffer) => {
const log = data.toString();
console.error('[Ideation STDERR]', log);
emitLogs(log);
this.emit('ideation-progress', projectId, {
phase: progressPhase,
progress: progressPercent,
message: log.trim().split('\n')[0].substring(0, 200)
});
});
// Handle process exit
childProcess.on('exit', (code: number | null) => {
console.log('[Ideation] Process exited with code:', code);
// Get the stored project path before deleting from map
const processInfo = this.processes.get(projectId);
const storedProjectPath = processInfo?.projectPath;
this.processes.delete(projectId);
if (code === 0) {
this.emit('ideation-progress', projectId, {
phase: 'complete',
progress: 100,
message: 'Ideation generation complete'
});
// Load and emit the complete ideation session
if (storedProjectPath) {
try {
const ideationFilePath = path.join(
storedProjectPath,
'.auto-claude',
'ideation',
'ideation.json'
);
if (existsSync(ideationFilePath)) {
const content = readFileSync(ideationFilePath, 'utf-8');
const session = JSON.parse(content);
console.log('[Ideation] Emitting ideation-complete with session data');
this.emit('ideation-complete', projectId, session);
} else {
console.warn('[Ideation] ideation.json not found at:', ideationFilePath);
}
} catch (err) {
console.error('[Ideation] Failed to load ideation session:', err);
}
}
} else {
this.emit('ideation-error', projectId, `Ideation generation failed with exit code ${code}`);
}
});
// Handle process error
childProcess.on('error', (err: Error) => {
console.error('[Ideation] Process error:', err.message);
this.processes.delete(projectId);
this.emit('ideation-error', projectId, err.message);
});
}
/**
* Spawn a Python process for roadmap generation
*/
private spawnRoadmapProcess(
projectId: string,
_projectPath: string,
args: string[]
): void {
// Kill existing process for this project if any
this.killTask(projectId);
// Run from auto-claude source directory so imports work correctly
const autoBuildSource = this.getAutoBuildSourcePath();
const cwd = autoBuildSource || process.cwd();
// Load environment variables from auto-claude .env file
const autoBuildEnv = this.loadAutoBuildEnv();
const childProcess = spawn(this.pythonPath, args, {
cwd,
env: {
...process.env,
...autoBuildEnv, // Include auto-claude .env variables (like CLAUDE_CODE_OAUTH_TOKEN)
PYTHONUNBUFFERED: '1'
}
});
this.processes.set(projectId, {
taskId: projectId,
process: childProcess,
startedAt: new Date()
});
// Track progress through output
let progressPhase = 'analyzing';
let progressPercent = 10;
// Handle stdout
childProcess.stdout?.on('data', (data: Buffer) => {
const log = data.toString();
// Parse progress from output
if (log.includes('PROJECT ANALYSIS')) {
progressPhase = 'analyzing';
progressPercent = 20;
} else if (log.includes('PROJECT DISCOVERY')) {
progressPhase = 'discovering';
progressPercent = 40;
} else if (log.includes('FEATURE GENERATION')) {
progressPhase = 'generating';
progressPercent = 70;
} else if (log.includes('ROADMAP GENERATED')) {
progressPhase = 'complete';
progressPercent = 100;
}
// Emit progress update
this.emit('roadmap-progress', projectId, {
phase: progressPhase,
progress: progressPercent,
message: log.trim().substring(0, 200) // Truncate long messages
});
});
// Handle stderr
childProcess.stderr?.on('data', (data: Buffer) => {
const log = data.toString();
this.emit('roadmap-progress', projectId, {
phase: progressPhase,
progress: progressPercent,
message: log.trim().substring(0, 200)
});
});
// Handle process exit
childProcess.on('exit', (code: number | null) => {
this.processes.delete(projectId);
if (code === 0) {
this.emit('roadmap-progress', projectId, {
phase: 'complete',
progress: 100,
message: 'Roadmap generation complete'
});
} else {
this.emit('roadmap-error', projectId, `Roadmap generation failed with exit code ${code}`);
}
});
// Handle process error
childProcess.on('error', (err: Error) => {
this.processes.delete(projectId);
this.emit('roadmap-error', projectId, err.message);
});
}
/**
* Parse log output to detect execution phase transitions
*/
private parseExecutionPhase(
log: string,
currentPhase: ExecutionProgressData['phase'],
isSpecRunner: boolean
): { phase: ExecutionProgressData['phase']; message?: string; currentChunk?: string } | null {
const lowerLog = log.toLowerCase();
// Spec runner phase detection (all part of "planning")
if (isSpecRunner) {
if (lowerLog.includes('discovering') || lowerLog.includes('discovery')) {
return { phase: 'planning', message: 'Discovering project context...' };
}
if (lowerLog.includes('requirements') || lowerLog.includes('gathering')) {
return { phase: 'planning', message: 'Gathering requirements...' };
}
if (lowerLog.includes('writing spec') || lowerLog.includes('spec writer')) {
return { phase: 'planning', message: 'Writing specification...' };
}
if (lowerLog.includes('validating') || lowerLog.includes('validation')) {
return { phase: 'planning', message: 'Validating specification...' };
}
if (lowerLog.includes('spec complete') || lowerLog.includes('specification complete')) {
return { phase: 'planning', message: 'Specification complete' };
}
}
// Run.py phase detection
// Planner agent running
if (lowerLog.includes('planner agent') || lowerLog.includes('creating implementation plan')) {
return { phase: 'planning', message: 'Creating implementation plan...' };
}
// Coder agent running
if (lowerLog.includes('coder agent') || lowerLog.includes('starting coder')) {
return { phase: 'coding', message: 'Implementing code changes...' };
}
// Chunk progress detection
const chunkMatch = log.match(/chunk[:\s]+(\d+(?:\/\d+)?|\w+[-_]\w+)/i);
if (chunkMatch && currentPhase === 'coding') {
return { phase: 'coding', currentChunk: chunkMatch[1], message: `Working on chunk ${chunkMatch[1]}...` };
}
// Chunk completion detection
if (lowerLog.includes('chunk completed') || lowerLog.includes('chunk done')) {
const completedChunk = log.match(/chunk[:\s]+"?([^"]+)"?\s+completed/i);
return {
phase: 'coding',
currentChunk: completedChunk?.[1],
message: `Chunk ${completedChunk?.[1] || ''} completed`
};
}
// QA Review phase
if (lowerLog.includes('qa reviewer') || lowerLog.includes('qa_reviewer') || lowerLog.includes('starting qa')) {
return { phase: 'qa_review', message: 'Running QA review...' };
}
// QA Fixer phase
if (lowerLog.includes('qa fixer') || lowerLog.includes('qa_fixer') || lowerLog.includes('fixing issues')) {
return { phase: 'qa_fixing', message: 'Fixing QA issues...' };
}
// Completion detection - be conservative, require explicit success markers
// The AI agent prints "=== BUILD COMPLETE ===" when truly done (from coder.md)
// Only trust this pattern, not generic "all chunks completed" which could be false positive
if (lowerLog.includes('=== build complete ===') || lowerLog.includes('qa passed')) {
return { phase: 'complete', message: 'Build completed successfully' };
}
// "All chunks completed" is informational - don't change phase based on this alone
// The coordinator may print this even when chunks are blocked, so we stay in coding phase
// and let the actual implementation_plan.json status drive the UI
if (lowerLog.includes('all chunks completed')) {
return { phase: 'coding', message: 'Chunks marked complete' };
}
// Incomplete build detection - when coordinator exits with pending chunks
if (lowerLog.includes('build incomplete') || lowerLog.includes('chunks still pending')) {
return { phase: 'coding', message: 'Build paused - chunks still pending' };
}
// Error/failure detection
if (lowerLog.includes('build failed') || lowerLog.includes('error:') || lowerLog.includes('fatal')) {
return { phase: 'failed', message: log.trim().substring(0, 200) };
}
return null;
}
/**
* Calculate overall progress based on phase and phase progress
*/
private calculateOverallProgress(phase: ExecutionProgressData['phase'], phaseProgress: number): number {
// Phase weight ranges (same as in constants.ts)
const weights: Record<string, { start: number; end: number }> = {
idle: { start: 0, end: 0 },
planning: { start: 0, end: 20 },
coding: { start: 20, end: 80 },
qa_review: { start: 80, end: 95 },
qa_fixing: { start: 80, end: 95 },
complete: { start: 100, end: 100 },
failed: { start: 0, end: 0 }
};
const phaseWeight = weights[phase] || { start: 0, end: 0 };
const phaseRange = phaseWeight.end - phaseWeight.start;
return Math.round(phaseWeight.start + (phaseRange * phaseProgress / 100));
}
/**
* Spawn a Python process
*/
private spawnProcess(
taskId: string,
cwd: string,
args: string[],
extraEnv: Record<string, string> = {},
processType: ProcessType = 'task-execution'
): void {
const isSpecRunner = processType === 'spec-creation';
// Kill existing process for this task if any
this.killTask(taskId);
console.log('[spawnProcess] Spawning with pythonPath:', this.pythonPath);
console.log('[spawnProcess] cwd:', cwd);
console.log('[spawnProcess] processType:', processType);
const childProcess = spawn(this.pythonPath, args, {
cwd,
env: {
...process.env,
...extraEnv,
PYTHONUNBUFFERED: '1' // Ensure real-time output
}
});
console.log('[spawnProcess] Process spawned, pid:', childProcess.pid);
this.processes.set(taskId, {
taskId,
process: childProcess,
startedAt: new Date()
});
// Track execution progress
let currentPhase: ExecutionProgressData['phase'] = isSpecRunner ? 'planning' : 'planning';
let phaseProgress = 0;
let currentChunk: string | undefined;
let lastMessage: string | undefined;
// Emit initial progress
this.emit('execution-progress', taskId, {
phase: currentPhase,
phaseProgress: 0,
overallProgress: this.calculateOverallProgress(currentPhase, 0),
message: isSpecRunner ? 'Starting spec creation...' : 'Starting build process...'
});
const processLog = (log: string) => {
// Parse for phase transitions
const phaseUpdate = this.parseExecutionPhase(log, currentPhase, isSpecRunner);
if (phaseUpdate) {
const phaseChanged = phaseUpdate.phase !== currentPhase;
currentPhase = phaseUpdate.phase;
if (phaseUpdate.currentChunk) {
currentChunk = phaseUpdate.currentChunk;
}
if (phaseUpdate.message) {
lastMessage = phaseUpdate.message;
}
// Reset phase progress on phase change, otherwise increment
if (phaseChanged) {
phaseProgress = 10; // Start new phase at 10%
} else {
phaseProgress = Math.min(90, phaseProgress + 5); // Increment within phase
}
const overallProgress = this.calculateOverallProgress(currentPhase, phaseProgress);
this.emit('execution-progress', taskId, {
phase: currentPhase,
phaseProgress,
overallProgress,
currentChunk,
message: lastMessage
});
}
};
// Handle stdout
childProcess.stdout?.on('data', (data: Buffer) => {
const log = data.toString();
console.log('[spawnProcess] stdout:', log.substring(0, 200));
this.emit('log', taskId, log);
processLog(log);
});
// Handle stderr
childProcess.stderr?.on('data', (data: Buffer) => {
const log = data.toString();
console.log('[spawnProcess] stderr:', log.substring(0, 200));
// Some Python output goes to stderr (like progress bars)
// so we treat it as log, not error
this.emit('log', taskId, log);
processLog(log);
});
// Handle process exit
childProcess.on('exit', (code: number | null) => {
console.log('[spawnProcess] Process exited with code:', code);
this.processes.delete(taskId);
// Emit final progress
const finalPhase = code === 0 ? 'complete' : 'failed';
this.emit('execution-progress', taskId, {
phase: finalPhase,
phaseProgress: 100,
overallProgress: code === 0 ? 100 : this.calculateOverallProgress(currentPhase, phaseProgress),
message: code === 0 ? 'Process completed successfully' : `Process exited with code ${code}`
});
this.emit('exit', taskId, code, processType);
});
// Handle process error
childProcess.on('error', (err: Error) => {
console.log('[spawnProcess] Process error:', err.message);
this.processes.delete(taskId);
this.emit('execution-progress', taskId, {
phase: 'failed',
phaseProgress: 0,
overallProgress: 0,
message: `Error: ${err.message}`
});
this.emit('error', taskId, err.message);
});
}
/**
* Kill a specific task's process
*/
killTask(taskId: string): boolean {
const agentProcess = this.processes.get(taskId);
if (agentProcess) {
try {
// Send SIGTERM first for graceful shutdown
agentProcess.process.kill('SIGTERM');
// Force kill after timeout
setTimeout(() => {
if (!agentProcess.process.killed) {
agentProcess.process.kill('SIGKILL');
}
}, 5000);
this.processes.delete(taskId);
return true;
} catch {
return false;
}
}
return false;
}
/**
* Kill all running processes
*/
async killAll(): Promise<void> {
const killPromises = Array.from(this.processes.keys()).map((taskId) => {
return new Promise<void>((resolve) => {
this.killTask(taskId);
resolve();
});
});
await Promise.all(killPromises);
}
/**
* Check if a task is running
*/
isRunning(taskId: string): boolean {
return this.processes.has(taskId);
}
/**
* Get all running task IDs
*/
getRunningTasks(): string[] {
return Array.from(this.processes.keys());
}
}
export {
AgentManager,
AgentState,
AgentEvents,
AgentProcessManager,
AgentQueueManager
} from './agent';
export type {
AgentProcess,
ExecutionProgressData,
ProcessType,
AgentManagerEvents,
IdeationConfig,
TaskExecutionOptions,
SpecCreationMetadata,
IdeationProgressData,
RoadmapProgressData
} from './agent';
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,182 @@
import { ExecutionProgressData } from './types';
/**
* Event handling and progress parsing logic
*/
export class AgentEvents {
/**
* Parse log output to detect execution phase transitions
*/
parseExecutionPhase(
log: string,
currentPhase: ExecutionProgressData['phase'],
isSpecRunner: boolean
): { phase: ExecutionProgressData['phase']; message?: string; currentSubtask?: string } | null {
const lowerLog = log.toLowerCase();
// Spec runner phase detection (all part of "planning")
if (isSpecRunner) {
if (lowerLog.includes('discovering') || lowerLog.includes('discovery')) {
return { phase: 'planning', message: 'Discovering project context...' };
}
if (lowerLog.includes('requirements') || lowerLog.includes('gathering')) {
return { phase: 'planning', message: 'Gathering requirements...' };
}
if (lowerLog.includes('writing spec') || lowerLog.includes('spec writer')) {
return { phase: 'planning', message: 'Writing specification...' };
}
if (lowerLog.includes('validating') || lowerLog.includes('validation')) {
return { phase: 'planning', message: 'Validating specification...' };
}
if (lowerLog.includes('spec complete') || lowerLog.includes('specification complete')) {
return { phase: 'planning', message: 'Specification complete' };
}
}
// Run.py phase detection
// Planner agent running
if (lowerLog.includes('planner agent') || lowerLog.includes('creating implementation plan')) {
return { phase: 'planning', message: 'Creating implementation plan...' };
}
// Coder agent running
if (lowerLog.includes('coder agent') || lowerLog.includes('starting coder')) {
return { phase: 'coding', message: 'Implementing code changes...' };
}
// Subtask progress detection
const subtaskMatch = log.match(/subtask[:\s]+(\d+(?:\/\d+)?|\w+[-_]\w+)/i);
if (subtaskMatch && currentPhase === 'coding') {
return { phase: 'coding', currentSubtask: subtaskMatch[1], message: `Working on subtask ${subtaskMatch[1]}...` };
}
// Subtask completion detection
if (lowerLog.includes('subtask completed') || lowerLog.includes('subtask done')) {
const completedSubtask = log.match(/subtask[:\s]+"?([^"]+)"?\s+completed/i);
return {
phase: 'coding',
currentSubtask: completedSubtask?.[1],
message: `Subtask ${completedSubtask?.[1] || ''} completed`
};
}
// QA Review phase
if (lowerLog.includes('qa reviewer') || lowerLog.includes('qa_reviewer') || lowerLog.includes('starting qa')) {
return { phase: 'qa_review', message: 'Running QA review...' };
}
// QA Fixer phase
if (lowerLog.includes('qa fixer') || lowerLog.includes('qa_fixer') || lowerLog.includes('fixing issues')) {
return { phase: 'qa_fixing', message: 'Fixing QA issues...' };
}
// Completion detection - be conservative, require explicit success markers
// The AI agent prints "=== BUILD COMPLETE ===" when truly done (from coder.md)
// Only trust this pattern, not generic "all subtasks completed" which could be false positive
if (lowerLog.includes('=== build complete ===') || lowerLog.includes('qa passed')) {
return { phase: 'complete', message: 'Build completed successfully' };
}
// "All subtasks completed" is informational - don't change phase based on this alone
// The coordinator may print this even when subtasks are blocked, so we stay in coding phase
// and let the actual implementation_plan.json status drive the UI
if (lowerLog.includes('all subtasks completed')) {
return { phase: 'coding', message: 'Subtasks marked complete' };
}
// Incomplete build detection - when coordinator exits with pending subtasks
if (lowerLog.includes('build incomplete') || lowerLog.includes('subtasks still pending')) {
return { phase: 'coding', message: 'Build paused - subtasks still pending' };
}
// Error/failure detection
if (lowerLog.includes('build failed') || lowerLog.includes('error:') || lowerLog.includes('fatal')) {
return { phase: 'failed', message: log.trim().substring(0, 200) };
}
return null;
}
/**
* Calculate overall progress based on phase and phase progress
*/
calculateOverallProgress(phase: ExecutionProgressData['phase'], phaseProgress: number): number {
// Phase weight ranges (same as in constants.ts)
const weights: Record<string, { start: number; end: number }> = {
idle: { start: 0, end: 0 },
planning: { start: 0, end: 20 },
coding: { start: 20, end: 80 },
qa_review: { start: 80, end: 95 },
qa_fixing: { start: 80, end: 95 },
complete: { start: 100, end: 100 },
failed: { start: 0, end: 0 }
};
const phaseWeight = weights[phase] || { start: 0, end: 0 };
const phaseRange = phaseWeight.end - phaseWeight.start;
return Math.round(phaseWeight.start + (phaseRange * phaseProgress / 100));
}
/**
* Parse ideation progress from log output
*/
parseIdeationProgress(
log: string,
currentPhase: string,
currentProgress: number,
completedTypes: Set<string>,
totalTypes: number
): { phase: string; progress: number } {
let phase = currentPhase;
let progress = currentProgress;
if (log.includes('PROJECT INDEX') || log.includes('PROJECT ANALYSIS')) {
phase = 'analyzing';
progress = 10;
} else if (log.includes('CONTEXT GATHERING')) {
phase = 'discovering';
progress = 20;
} else if (log.includes('GENERATING IDEAS (PARALLEL)') || (log.includes('Starting') && log.includes('ideation agents in parallel'))) {
phase = 'generating';
progress = 30;
} else if (log.includes('MERGE') || log.includes('FINALIZE')) {
phase = 'finalizing';
progress = 90;
} else if (log.includes('IDEATION COMPLETE')) {
phase = 'complete';
progress = 100;
}
// Update progress based on completed types during generation phase
if (phase === 'generating' && completedTypes.size > 0) {
// Progress from 30% to 90% based on completed types
progress = 30 + Math.floor((completedTypes.size / totalTypes) * 60);
}
return { phase, progress };
}
/**
* Parse roadmap progress from log output
*/
parseRoadmapProgress(log: string, currentPhase: string, currentProgress: number): { phase: string; progress: number } {
let phase = currentPhase;
let progress = currentProgress;
if (log.includes('PROJECT ANALYSIS')) {
phase = 'analyzing';
progress = 20;
} else if (log.includes('PROJECT DISCOVERY')) {
phase = 'discovering';
progress = 40;
} else if (log.includes('FEATURE GENERATION')) {
phase = 'generating';
progress = 70;
} else if (log.includes('ROADMAP GENERATED')) {
phase = 'complete';
progress = 100;
}
return { phase, progress };
}
}
@@ -0,0 +1,346 @@
import { EventEmitter } from 'events';
import path from 'path';
import { existsSync } from 'fs';
import { AgentState } from './agent-state';
import { AgentEvents } from './agent-events';
import { AgentProcessManager } from './agent-process';
import { AgentQueueManager } from './agent-queue';
import {
SpecCreationMetadata,
TaskExecutionOptions,
IdeationConfig
} from './types';
/**
* Main AgentManager - orchestrates agent process lifecycle
* This is a slim facade that delegates to focused modules
*/
export class AgentManager extends EventEmitter {
private state: AgentState;
private events: AgentEvents;
private processManager: AgentProcessManager;
private queueManager: AgentQueueManager;
private taskExecutionContext: Map<string, {
projectPath: string;
specId: string;
options: TaskExecutionOptions;
isSpecCreation?: boolean;
taskDescription?: string;
specDir?: string;
metadata?: SpecCreationMetadata;
swapCount: number;
}> = new Map();
constructor() {
super();
// Initialize modular components
this.state = new AgentState();
this.events = new AgentEvents();
this.processManager = new AgentProcessManager(this.state, this.events, this);
this.queueManager = new AgentQueueManager(this.state, this.events, this.processManager, this);
// Listen for auto-swap restart events
this.on('auto-swap-restart-task', (taskId: string, _newProfileId: string) => {
this.restartTask(taskId);
});
// Listen for task completion to clean up context (prevent memory leak)
this.on('exit', (taskId: string, code: number | null) => {
// Clean up context when:
// 1. Task completed successfully (code === 0), or
// 2. Task failed and won't be restarted (handled by auto-swap logic)
// Note: Auto-swap restart happens BEFORE this exit event is processed,
// so we need a small delay to allow restart to preserve context
setTimeout(() => {
const context = this.taskExecutionContext.get(taskId);
if (!context) return; // Already cleaned up or restarted
// If task completed successfully, always clean up
if (code === 0) {
this.taskExecutionContext.delete(taskId);
return;
}
// If task failed and hit max retries, clean up
if (context.swapCount >= 2) {
this.taskExecutionContext.delete(taskId);
}
// Otherwise keep context for potential restart
}, 1000); // Delay to allow restart logic to run first
});
}
/**
* Configure paths for Python and auto-claude source
*/
configure(pythonPath?: string, autoBuildSourcePath?: string): void {
this.processManager.configure(pythonPath, autoBuildSourcePath);
}
/**
* Start spec creation process
*/
startSpecCreation(
taskId: string,
projectPath: string,
taskDescription: string,
specDir?: string,
metadata?: SpecCreationMetadata
): void {
const autoBuildSource = this.processManager.getAutoBuildSourcePath();
if (!autoBuildSource) {
this.emit('error', taskId, 'Auto-build source path not found. Please configure it in App Settings.');
return;
}
const specRunnerPath = path.join(autoBuildSource, 'runners', 'spec_runner.py');
if (!existsSync(specRunnerPath)) {
this.emit('error', taskId, `Spec runner not found at: ${specRunnerPath}`);
return;
}
// Get combined environment variables
const combinedEnv = this.processManager.getCombinedEnv(projectPath);
// spec_runner.py will auto-start run.py after spec creation completes
const args = [specRunnerPath, '--task', taskDescription, '--project-dir', projectPath];
// Pass spec directory if provided (for UI-created tasks that already have a directory)
if (specDir) {
args.push('--spec-dir', specDir);
}
// Check if user requires review before coding
if (!metadata?.requireReviewBeforeCoding) {
// Auto-approve: When user starts a task from the UI without requiring review
args.push('--auto-approve');
}
// Store context for potential restart
this.storeTaskContext(taskId, projectPath, '', {}, true, taskDescription, specDir, metadata);
// Note: This is spec-creation but it chains to task-execution via run.py
this.processManager.spawnProcess(taskId, autoBuildSource, args, combinedEnv, 'task-execution');
}
/**
* Start task execution (run.py)
*/
startTaskExecution(
taskId: string,
projectPath: string,
specId: string,
options: TaskExecutionOptions = {}
): void {
const autoBuildSource = this.processManager.getAutoBuildSourcePath();
if (!autoBuildSource) {
this.emit('error', taskId, 'Auto-build source path not found. Please configure it in App Settings.');
return;
}
const runPath = path.join(autoBuildSource, 'run.py');
if (!existsSync(runPath)) {
this.emit('error', taskId, `Run script not found at: ${runPath}`);
return;
}
// Get combined environment variables
const combinedEnv = this.processManager.getCombinedEnv(projectPath);
const args = [runPath, '--spec', specId, '--project-dir', projectPath];
// Always use auto-continue when running from UI (non-interactive)
args.push('--auto-continue');
// Force: When user starts a task from the UI, that IS their approval
args.push('--force');
// Pass base branch if specified (ensures worktrees are created from the correct branch)
if (options.baseBranch) {
args.push('--base-branch', options.baseBranch);
}
// Note: --parallel was removed from run.py CLI - parallel execution is handled internally by the agent
// The options.parallel and options.workers are kept for future use or logging purposes
// Store context for potential restart
this.storeTaskContext(taskId, projectPath, specId, options, false);
this.processManager.spawnProcess(taskId, autoBuildSource, args, combinedEnv, 'task-execution');
}
/**
* Start QA process
*/
startQAProcess(
taskId: string,
projectPath: string,
specId: string
): void {
const autoBuildSource = this.processManager.getAutoBuildSourcePath();
if (!autoBuildSource) {
this.emit('error', taskId, 'Auto-build source path not found. Please configure it in App Settings.');
return;
}
const runPath = path.join(autoBuildSource, 'run.py');
if (!existsSync(runPath)) {
this.emit('error', taskId, `Run script not found at: ${runPath}`);
return;
}
// Get combined environment variables
const combinedEnv = this.processManager.getCombinedEnv(projectPath);
const args = [runPath, '--spec', specId, '--project-dir', projectPath, '--qa'];
this.processManager.spawnProcess(taskId, autoBuildSource, args, combinedEnv, 'qa-process');
}
/**
* Start roadmap generation process
*/
startRoadmapGeneration(
projectId: string,
projectPath: string,
refresh: boolean = false,
enableCompetitorAnalysis: boolean = false
): void {
this.queueManager.startRoadmapGeneration(projectId, projectPath, refresh, enableCompetitorAnalysis);
}
/**
* Start ideation generation process
*/
startIdeationGeneration(
projectId: string,
projectPath: string,
config: IdeationConfig,
refresh: boolean = false
): void {
this.queueManager.startIdeationGeneration(projectId, projectPath, config, refresh);
}
/**
* Kill a specific task's process
*/
killTask(taskId: string): boolean {
return this.processManager.killProcess(taskId);
}
/**
* Stop ideation generation for a project
*/
stopIdeation(projectId: string): boolean {
return this.queueManager.stopIdeation(projectId);
}
/**
* Check if ideation is running for a project
*/
isIdeationRunning(projectId: string): boolean {
return this.queueManager.isIdeationRunning(projectId);
}
/**
* Kill all running processes
*/
async killAll(): Promise<void> {
await this.processManager.killAllProcesses();
}
/**
* Check if a task is running
*/
isRunning(taskId: string): boolean {
return this.state.hasProcess(taskId);
}
/**
* Get all running task IDs
*/
getRunningTasks(): string[] {
return this.state.getRunningTaskIds();
}
/**
* Store task execution context for potential restarts
*/
private storeTaskContext(
taskId: string,
projectPath: string,
specId: string,
options: TaskExecutionOptions,
isSpecCreation?: boolean,
taskDescription?: string,
specDir?: string,
metadata?: SpecCreationMetadata
): void {
// Preserve swapCount if context already exists (for restarts)
const existingContext = this.taskExecutionContext.get(taskId);
const swapCount = existingContext?.swapCount ?? 0;
this.taskExecutionContext.set(taskId, {
projectPath,
specId,
options,
isSpecCreation,
taskDescription,
specDir,
metadata,
swapCount // Preserve existing count instead of resetting
});
}
/**
* Restart task after profile swap
*/
restartTask(taskId: string): boolean {
const context = this.taskExecutionContext.get(taskId);
if (!context) {
console.error('[AgentManager] No context for task:', taskId);
return false;
}
// Prevent infinite swap loops
if (context.swapCount >= 2) {
console.error('[AgentManager] Max swap count reached for task:', taskId);
return false;
}
context.swapCount++;
// Kill current process
this.killTask(taskId);
// Wait for cleanup, then restart
setTimeout(() => {
if (context.isSpecCreation) {
this.startSpecCreation(
taskId,
context.projectPath,
context.taskDescription!,
context.specDir,
context.metadata
);
} else {
this.startTaskExecution(
taskId,
context.projectPath,
context.specId,
context.options
);
}
}, 500);
return true;
}
}
@@ -0,0 +1,384 @@
import { spawn } from 'child_process';
import path from 'path';
import { existsSync, readFileSync } from 'fs';
import { app } from 'electron';
import { EventEmitter } from 'events';
import { AgentState } from './agent-state';
import { AgentEvents } from './agent-events';
import { ProcessType, ExecutionProgressData } from './types';
import { detectRateLimit, createSDKRateLimitInfo, getProfileEnv } from '../rate-limit-detector';
import { projectStore } from '../project-store';
import { getClaudeProfileManager } from '../claude-profile-manager';
/**
* Process spawning and lifecycle management
*/
export class AgentProcessManager {
private state: AgentState;
private events: AgentEvents;
private emitter: EventEmitter;
private pythonPath: string = 'python3';
private autoBuildSourcePath: string = '';
constructor(state: AgentState, events: AgentEvents, emitter: EventEmitter) {
this.state = state;
this.events = events;
this.emitter = emitter;
}
/**
* Configure paths for Python and auto-claude source
*/
configure(pythonPath?: string, autoBuildSourcePath?: string): void {
if (pythonPath) {
this.pythonPath = pythonPath;
}
if (autoBuildSourcePath) {
this.autoBuildSourcePath = autoBuildSourcePath;
}
}
/**
* Get the configured Python path
*/
getPythonPath(): string {
return this.pythonPath;
}
/**
* Get the auto-claude source path (detects automatically if not configured)
*/
getAutoBuildSourcePath(): string | null {
// If manually configured, use that
if (this.autoBuildSourcePath && existsSync(this.autoBuildSourcePath)) {
return this.autoBuildSourcePath;
}
// Auto-detect from app location
const possiblePaths = [
// Dev mode: from dist/main -> ../../auto-claude (sibling to auto-claude-ui)
path.resolve(__dirname, '..', '..', '..', 'auto-claude'),
// Alternative: from app root
path.resolve(app.getAppPath(), '..', 'auto-claude'),
// If running from repo root
path.resolve(process.cwd(), 'auto-claude')
];
for (const p of possiblePaths) {
// Use requirements.txt as marker - it always exists in auto-claude source
if (existsSync(p) && existsSync(path.join(p, 'requirements.txt'))) {
return p;
}
}
return null;
}
/**
* Get project-specific environment variables based on project settings
*/
private getProjectEnvVars(projectPath: string): Record<string, string> {
const env: Record<string, string> = {};
// Find project by path
const projects = projectStore.getProjects();
const project = projects.find((p) => p.path === projectPath);
if (project?.settings) {
// Graphiti MCP integration
if (project.settings.graphitiMcpEnabled) {
const graphitiUrl = project.settings.graphitiMcpUrl || 'http://localhost:8000/mcp/';
env['GRAPHITI_MCP_URL'] = graphitiUrl;
}
}
return env;
}
/**
* Load environment variables from auto-claude .env file
*/
loadAutoBuildEnv(): Record<string, string> {
const autoBuildSource = this.getAutoBuildSourcePath();
if (!autoBuildSource) {
return {};
}
const envPath = path.join(autoBuildSource, '.env');
if (!existsSync(envPath)) {
return {};
}
try {
const envContent = readFileSync(envPath, 'utf-8');
const envVars: Record<string, string> = {};
// Handle both Unix (\n) and Windows (\r\n) line endings
for (const line of envContent.split(/\r?\n/)) {
const trimmed = line.trim();
// Skip comments and empty lines
if (!trimmed || trimmed.startsWith('#')) {
continue;
}
const eqIndex = trimmed.indexOf('=');
if (eqIndex > 0) {
const key = trimmed.substring(0, eqIndex).trim();
let value = trimmed.substring(eqIndex + 1).trim();
// Remove quotes if present
if ((value.startsWith('"') && value.endsWith('"')) ||
(value.startsWith("'") && value.endsWith("'"))) {
value = value.slice(1, -1);
}
envVars[key] = value;
}
}
return envVars;
} catch {
return {};
}
}
/**
* Spawn a Python process for task execution
*/
spawnProcess(
taskId: string,
cwd: string,
args: string[],
extraEnv: Record<string, string> = {},
processType: ProcessType = 'task-execution'
): void {
const isSpecRunner = processType === 'spec-creation';
// Kill existing process for this task if any
this.killProcess(taskId);
// Generate unique spawn ID for this process instance
const spawnId = this.state.generateSpawnId();
// Get active Claude profile environment (CLAUDE_CONFIG_DIR if not default)
const profileEnv = getProfileEnv();
const childProcess = spawn(this.pythonPath, args, {
cwd,
env: {
...process.env,
...extraEnv,
...profileEnv, // Include active Claude profile config
PYTHONUNBUFFERED: '1', // Ensure real-time output
PYTHONIOENCODING: 'utf-8', // Ensure UTF-8 encoding on Windows
PYTHONUTF8: '1' // Force Python UTF-8 mode on Windows (Python 3.7+)
}
});
this.state.addProcess(taskId, {
taskId,
process: childProcess,
startedAt: new Date(),
spawnId
});
// Track execution progress
let currentPhase: ExecutionProgressData['phase'] = isSpecRunner ? 'planning' : 'planning';
let phaseProgress = 0;
let currentSubtask: string | undefined;
let lastMessage: string | undefined;
// Collect all output for rate limit detection
let allOutput = '';
// Emit initial progress
this.emitter.emit('execution-progress', taskId, {
phase: currentPhase,
phaseProgress: 0,
overallProgress: this.events.calculateOverallProgress(currentPhase, 0),
message: isSpecRunner ? 'Starting spec creation...' : 'Starting build process...'
});
const processLog = (log: string) => {
// Collect output for rate limit detection (keep last 10KB)
allOutput = (allOutput + log).slice(-10000);
// Parse for phase transitions
const phaseUpdate = this.events.parseExecutionPhase(log, currentPhase, isSpecRunner);
if (phaseUpdate) {
const phaseChanged = phaseUpdate.phase !== currentPhase;
currentPhase = phaseUpdate.phase;
if (phaseUpdate.currentSubtask) {
currentSubtask = phaseUpdate.currentSubtask;
}
if (phaseUpdate.message) {
lastMessage = phaseUpdate.message;
}
// Reset phase progress on phase change, otherwise increment
if (phaseChanged) {
phaseProgress = 10; // Start new phase at 10%
} else {
phaseProgress = Math.min(90, phaseProgress + 5); // Increment within phase
}
const overallProgress = this.events.calculateOverallProgress(currentPhase, phaseProgress);
this.emitter.emit('execution-progress', taskId, {
phase: currentPhase,
phaseProgress,
overallProgress,
currentSubtask,
message: lastMessage
});
}
};
// Handle stdout - explicitly decode as UTF-8 for cross-platform Unicode support
childProcess.stdout?.on('data', (data: Buffer) => {
const log = data.toString('utf8');
this.emitter.emit('log', taskId, log);
processLog(log);
});
// Handle stderr - explicitly decode as UTF-8 for cross-platform Unicode support
childProcess.stderr?.on('data', (data: Buffer) => {
const log = data.toString('utf8');
// Some Python output goes to stderr (like progress bars)
// so we treat it as log, not error
this.emitter.emit('log', taskId, log);
processLog(log);
});
// Handle process exit
childProcess.on('exit', (code: number | null) => {
this.state.deleteProcess(taskId);
// Check if this specific spawn was killed (vs exited naturally)
// If killed, don't emit exit event to prevent race condition with new process
if (this.state.wasSpawnKilled(spawnId)) {
this.state.clearKilledSpawn(spawnId);
return;
}
// Check for rate limit if process failed
if (code !== 0) {
const rateLimitDetection = detectRateLimit(allOutput);
if (rateLimitDetection.isRateLimited) {
// Check if auto-swap is enabled
const profileManager = getClaudeProfileManager();
const autoSwitchSettings = profileManager.getAutoSwitchSettings();
if (autoSwitchSettings.enabled && autoSwitchSettings.autoSwitchOnRateLimit) {
const currentProfileId = rateLimitDetection.profileId;
const bestProfile = profileManager.getBestAvailableProfile(currentProfileId);
if (bestProfile) {
// Switch active profile
profileManager.setActiveProfile(bestProfile.id);
// Emit swap info (for modal)
const source = processType === 'spec-creation' ? 'task' : 'task';
const rateLimitInfo = createSDKRateLimitInfo(source, rateLimitDetection, {
taskId
});
rateLimitInfo.wasAutoSwapped = true;
rateLimitInfo.swappedToProfile = {
id: bestProfile.id,
name: bestProfile.name
};
rateLimitInfo.swapReason = 'reactive';
this.emitter.emit('sdk-rate-limit', rateLimitInfo);
// Restart task
this.emitter.emit('auto-swap-restart-task', taskId, bestProfile.id);
return;
}
}
// Fall back to manual modal (no auto-swap or no alternative profile)
const source = processType === 'spec-creation' ? 'task' : 'task';
const rateLimitInfo = createSDKRateLimitInfo(source, rateLimitDetection, {
taskId
});
this.emitter.emit('sdk-rate-limit', rateLimitInfo);
}
}
// Emit final progress
const finalPhase = code === 0 ? 'complete' : 'failed';
this.emitter.emit('execution-progress', taskId, {
phase: finalPhase,
phaseProgress: 100,
overallProgress: code === 0 ? 100 : this.events.calculateOverallProgress(currentPhase, phaseProgress),
message: code === 0 ? 'Process completed successfully' : `Process exited with code ${code}`
});
this.emitter.emit('exit', taskId, code, processType);
});
// Handle process error
childProcess.on('error', (err: Error) => {
console.error('[AgentProcess] Process error:', err.message);
this.state.deleteProcess(taskId);
this.emitter.emit('execution-progress', taskId, {
phase: 'failed',
phaseProgress: 0,
overallProgress: 0,
message: `Error: ${err.message}`
});
this.emitter.emit('error', taskId, err.message);
});
}
/**
* Kill a specific task's process
*/
killProcess(taskId: string): boolean {
const agentProcess = this.state.getProcess(taskId);
if (agentProcess) {
try {
// Mark this specific spawn as killed so its exit handler knows to ignore
this.state.markSpawnAsKilled(agentProcess.spawnId);
// Send SIGTERM first for graceful shutdown
agentProcess.process.kill('SIGTERM');
// Force kill after timeout
setTimeout(() => {
if (!agentProcess.process.killed) {
agentProcess.process.kill('SIGKILL');
}
}, 5000);
this.state.deleteProcess(taskId);
return true;
} catch {
return false;
}
}
return false;
}
/**
* Kill all running processes
*/
async killAllProcesses(): Promise<void> {
const killPromises = this.state.getRunningTaskIds().map((taskId) => {
return new Promise<void>((resolve) => {
this.killProcess(taskId);
resolve();
});
});
await Promise.all(killPromises);
}
/**
* Get combined environment variables for a project
*/
getCombinedEnv(projectPath: string): Record<string, string> {
const autoBuildEnv = this.loadAutoBuildEnv();
const projectEnv = this.getProjectEnvVars(projectPath);
return { ...autoBuildEnv, ...projectEnv };
}
}
@@ -0,0 +1,490 @@
import { spawn } from 'child_process';
import path from 'path';
import { existsSync, readFileSync } from 'fs';
import { EventEmitter } from 'events';
import { AgentState } from './agent-state';
import { AgentEvents } from './agent-events';
import { AgentProcessManager } from './agent-process';
import { IdeationConfig } from './types';
import { detectRateLimit, createSDKRateLimitInfo, getProfileEnv } from '../rate-limit-detector';
/**
* Queue management for ideation and roadmap generation
*/
export class AgentQueueManager {
private state: AgentState;
private events: AgentEvents;
private processManager: AgentProcessManager;
private emitter: EventEmitter;
constructor(
state: AgentState,
events: AgentEvents,
processManager: AgentProcessManager,
emitter: EventEmitter
) {
this.state = state;
this.events = events;
this.processManager = processManager;
this.emitter = emitter;
}
/**
* Start roadmap generation process
*/
startRoadmapGeneration(
projectId: string,
projectPath: string,
refresh: boolean = false,
enableCompetitorAnalysis: boolean = false
): void {
const autoBuildSource = this.processManager.getAutoBuildSourcePath();
if (!autoBuildSource) {
this.emitter.emit('roadmap-error', projectId, 'Auto-build source path not found. Please configure it in App Settings.');
return;
}
const roadmapRunnerPath = path.join(autoBuildSource, 'roadmap_runner.py');
if (!existsSync(roadmapRunnerPath)) {
this.emitter.emit('roadmap-error', projectId, `Roadmap runner not found at: ${roadmapRunnerPath}`);
return;
}
const args = [roadmapRunnerPath, '--project', projectPath];
if (refresh) {
args.push('--refresh');
}
// Add competitor analysis flag if enabled
if (enableCompetitorAnalysis) {
args.push('--competitor-analysis');
}
// Use projectId as taskId for roadmap operations
this.spawnRoadmapProcess(projectId, projectPath, args);
}
/**
* Start ideation generation process
*/
startIdeationGeneration(
projectId: string,
projectPath: string,
config: IdeationConfig,
refresh: boolean = false
): void {
const autoBuildSource = this.processManager.getAutoBuildSourcePath();
if (!autoBuildSource) {
this.emitter.emit('ideation-error', projectId, 'Auto-build source path not found. Please configure it in App Settings.');
return;
}
const ideationRunnerPath = path.join(autoBuildSource, 'ideation_runner.py');
if (!existsSync(ideationRunnerPath)) {
this.emitter.emit('ideation-error', projectId, `Ideation runner not found at: ${ideationRunnerPath}`);
return;
}
const args = [ideationRunnerPath, '--project', projectPath];
// Add enabled types as comma-separated list
if (config.enabledTypes.length > 0) {
args.push('--types', config.enabledTypes.join(','));
}
// Add context flags (script uses --no-roadmap/--no-kanban negative flags)
if (!config.includeRoadmapContext) {
args.push('--no-roadmap');
}
if (!config.includeKanbanContext) {
args.push('--no-kanban');
}
// Add max ideas per type
if (config.maxIdeasPerType) {
args.push('--max-ideas', config.maxIdeasPerType.toString());
}
if (refresh) {
args.push('--refresh');
}
// Add append flag to preserve existing ideas
if (config.append) {
args.push('--append');
}
// Use projectId as taskId for ideation operations
this.spawnIdeationProcess(projectId, projectPath, args);
}
/**
* Spawn a Python process for ideation generation
*/
private spawnIdeationProcess(
projectId: string,
projectPath: string,
args: string[]
): void {
// Kill existing process for this project if any
this.processManager.killProcess(projectId);
// Generate unique spawn ID for this process instance
const spawnId = this.state.generateSpawnId();
// Run from auto-claude source directory so imports work correctly
const autoBuildSource = this.processManager.getAutoBuildSourcePath();
const cwd = autoBuildSource || process.cwd();
// Get combined environment variables
const combinedEnv = this.processManager.getCombinedEnv(projectPath);
// Get active Claude profile environment (CLAUDE_CONFIG_DIR if not default)
const profileEnv = getProfileEnv();
// Get Python path from process manager (uses venv if configured)
const pythonPath = this.processManager.getPythonPath();
const childProcess = spawn(pythonPath, args, {
cwd,
env: {
...process.env,
...combinedEnv,
...profileEnv,
PYTHONUNBUFFERED: '1',
PYTHONIOENCODING: 'utf-8',
PYTHONUTF8: '1'
}
});
this.state.addProcess(projectId, {
taskId: projectId,
process: childProcess,
startedAt: new Date(),
projectPath, // Store project path for loading session on completion
spawnId
});
// Track progress through output
let progressPhase = 'analyzing';
let progressPercent = 10;
// Collect output for rate limit detection
let allOutput = '';
// Helper to emit logs - split multi-line output into individual log lines
const emitLogs = (log: string) => {
const lines = log.split('\n').filter(line => line.trim().length > 0);
for (const line of lines) {
const trimmed = line.trim();
if (trimmed.length > 0) {
this.emitter.emit('ideation-log', projectId, trimmed);
}
}
};
// Track completed types for progress calculation
const completedTypes = new Set<string>();
const totalTypes = 7; // Default all types
// Handle stdout - explicitly decode as UTF-8 for cross-platform Unicode support
childProcess.stdout?.on('data', (data: Buffer) => {
const log = data.toString('utf8');
// Collect output for rate limit detection (keep last 10KB)
allOutput = (allOutput + log).slice(-10000);
// Emit all log lines for the activity log
emitLogs(log);
// Check for streaming type completion signals
const typeCompleteMatch = log.match(/IDEATION_TYPE_COMPLETE:(\w+):(\d+)/);
if (typeCompleteMatch) {
const [, ideationType, ideasCount] = typeCompleteMatch;
completedTypes.add(ideationType);
// Emit event for UI to load this type's ideas immediately
this.emitter.emit('ideation-type-complete', projectId, ideationType, parseInt(ideasCount, 10));
}
const typeFailedMatch = log.match(/IDEATION_TYPE_FAILED:(\w+)/);
if (typeFailedMatch) {
const [, ideationType] = typeFailedMatch;
completedTypes.add(ideationType);
this.emitter.emit('ideation-type-failed', projectId, ideationType);
}
// Parse progress using AgentEvents
const progressUpdate = this.events.parseIdeationProgress(
log,
progressPhase,
progressPercent,
completedTypes,
totalTypes
);
progressPhase = progressUpdate.phase;
progressPercent = progressUpdate.progress;
// Emit progress update with a clean message for the status bar
const statusMessage = log.trim().split('\n')[0].substring(0, 200);
this.emitter.emit('ideation-progress', projectId, {
phase: progressPhase,
progress: progressPercent,
message: statusMessage,
completedTypes: Array.from(completedTypes)
});
});
// Handle stderr - also emit as logs, explicitly decode as UTF-8
childProcess.stderr?.on('data', (data: Buffer) => {
const log = data.toString('utf8');
// Collect stderr for rate limit detection too
allOutput = (allOutput + log).slice(-10000);
console.error('[Ideation STDERR]', log);
emitLogs(log);
this.emitter.emit('ideation-progress', projectId, {
phase: progressPhase,
progress: progressPercent,
message: log.trim().split('\n')[0].substring(0, 200)
});
});
// Handle process exit
childProcess.on('exit', (code: number | null) => {
// Get the stored project path before deleting from map
const processInfo = this.state.getProcess(projectId);
const storedProjectPath = processInfo?.projectPath;
this.state.deleteProcess(projectId);
// Check for rate limit if process failed
if (code !== 0) {
const rateLimitDetection = detectRateLimit(allOutput);
if (rateLimitDetection.isRateLimited) {
const rateLimitInfo = createSDKRateLimitInfo('ideation', rateLimitDetection, {
projectId
});
this.emitter.emit('sdk-rate-limit', rateLimitInfo);
}
}
if (code === 0) {
this.emitter.emit('ideation-progress', projectId, {
phase: 'complete',
progress: 100,
message: 'Ideation generation complete'
});
// Load and emit the complete ideation session
if (storedProjectPath) {
try {
const ideationFilePath = path.join(
storedProjectPath,
'.auto-claude',
'ideation',
'ideation.json'
);
if (existsSync(ideationFilePath)) {
const content = readFileSync(ideationFilePath, 'utf-8');
const session = JSON.parse(content);
this.emitter.emit('ideation-complete', projectId, session);
} else {
console.warn('[Ideation] ideation.json not found at:', ideationFilePath);
}
} catch (err) {
console.error('[Ideation] Failed to load ideation session:', err);
}
}
} else {
this.emitter.emit('ideation-error', projectId, `Ideation generation failed with exit code ${code}`);
}
});
// Handle process error
childProcess.on('error', (err: Error) => {
console.error('[Ideation] Process error:', err.message);
this.state.deleteProcess(projectId);
this.emitter.emit('ideation-error', projectId, err.message);
});
}
/**
* Spawn a Python process for roadmap generation
*/
private spawnRoadmapProcess(
projectId: string,
projectPath: string,
args: string[]
): void {
// Kill existing process for this project if any
this.processManager.killProcess(projectId);
// Generate unique spawn ID for this process instance
const spawnId = this.state.generateSpawnId();
// Run from auto-claude source directory so imports work correctly
const autoBuildSource = this.processManager.getAutoBuildSourcePath();
const cwd = autoBuildSource || process.cwd();
// Get combined environment variables
const combinedEnv = this.processManager.getCombinedEnv(projectPath);
// Get active Claude profile environment (CLAUDE_CONFIG_DIR if not default)
const profileEnv = getProfileEnv();
// Get Python path from process manager (uses venv if configured)
const pythonPath = this.processManager.getPythonPath();
const childProcess = spawn(pythonPath, args, {
cwd,
env: {
...process.env,
...combinedEnv,
...profileEnv,
PYTHONUNBUFFERED: '1',
PYTHONIOENCODING: 'utf-8',
PYTHONUTF8: '1'
}
});
this.state.addProcess(projectId, {
taskId: projectId,
process: childProcess,
startedAt: new Date(),
projectPath, // Store project path for loading roadmap on completion
spawnId
});
// Track progress through output
let progressPhase = 'analyzing';
let progressPercent = 10;
// Collect output for rate limit detection
let allRoadmapOutput = '';
// Helper to emit logs - split multi-line output into individual log lines
const emitLogs = (log: string) => {
const lines = log.split('\n').filter(line => line.trim().length > 0);
for (const line of lines) {
const trimmed = line.trim();
if (trimmed.length > 0) {
this.emitter.emit('roadmap-log', projectId, trimmed);
}
}
};
// Handle stdout - explicitly decode as UTF-8 for cross-platform Unicode support
childProcess.stdout?.on('data', (data: Buffer) => {
const log = data.toString('utf8');
// Collect output for rate limit detection (keep last 10KB)
allRoadmapOutput = (allRoadmapOutput + log).slice(-10000);
// Emit all log lines for debugging
emitLogs(log);
// Parse progress using AgentEvents
const progressUpdate = this.events.parseRoadmapProgress(log, progressPhase, progressPercent);
progressPhase = progressUpdate.phase;
progressPercent = progressUpdate.progress;
// Emit progress update
this.emitter.emit('roadmap-progress', projectId, {
phase: progressPhase,
progress: progressPercent,
message: log.trim().substring(0, 200) // Truncate long messages
});
});
// Handle stderr - explicitly decode as UTF-8
childProcess.stderr?.on('data', (data: Buffer) => {
const log = data.toString('utf8');
// Collect stderr for rate limit detection too
allRoadmapOutput = (allRoadmapOutput + log).slice(-10000);
console.error('[Roadmap STDERR]', log);
emitLogs(log);
this.emitter.emit('roadmap-progress', projectId, {
phase: progressPhase,
progress: progressPercent,
message: log.trim().substring(0, 200)
});
});
// Handle process exit
childProcess.on('exit', (code: number | null) => {
// Get the stored project path before deleting from map
const processInfo = this.state.getProcess(projectId);
const storedProjectPath = processInfo?.projectPath;
this.state.deleteProcess(projectId);
// Check for rate limit if process failed
if (code !== 0) {
const rateLimitDetection = detectRateLimit(allRoadmapOutput);
if (rateLimitDetection.isRateLimited) {
const rateLimitInfo = createSDKRateLimitInfo('roadmap', rateLimitDetection, {
projectId
});
this.emitter.emit('sdk-rate-limit', rateLimitInfo);
}
}
if (code === 0) {
this.emitter.emit('roadmap-progress', projectId, {
phase: 'complete',
progress: 100,
message: 'Roadmap generation complete'
});
// Load and emit the complete roadmap
if (storedProjectPath) {
try {
const roadmapFilePath = path.join(
storedProjectPath,
'.auto-claude',
'roadmap',
'roadmap.json'
);
if (existsSync(roadmapFilePath)) {
const content = readFileSync(roadmapFilePath, 'utf-8');
const roadmap = JSON.parse(content);
this.emitter.emit('roadmap-complete', projectId, roadmap);
} else {
console.warn('[Roadmap] roadmap.json not found at:', roadmapFilePath);
}
} catch (err) {
console.error('[Roadmap] Failed to load roadmap:', err);
}
}
} else {
this.emitter.emit('roadmap-error', projectId, `Roadmap generation failed with exit code ${code}`);
}
});
// Handle process error
childProcess.on('error', (err: Error) => {
console.error('[Roadmap] Process error:', err.message);
this.state.deleteProcess(projectId);
this.emitter.emit('roadmap-error', projectId, err.message);
});
}
/**
* Stop ideation generation for a project
*/
stopIdeation(projectId: string): boolean {
const wasRunning = this.state.hasProcess(projectId);
if (wasRunning) {
this.processManager.killProcess(projectId);
this.emitter.emit('ideation-stopped', projectId);
return true;
}
return false;
}
/**
* Check if ideation is running for a project
*/
isIdeationRunning(projectId: string): boolean {
return this.state.hasProcess(projectId);
}
}
@@ -0,0 +1,88 @@
import { AgentProcess } from './types';
/**
* Agent state tracking and process map management
*/
export class AgentState {
private processes: Map<string, AgentProcess> = new Map();
private killedSpawnIds: Set<number> = new Set();
private spawnCounter: number = 0;
/**
* Generate a unique spawn ID
*/
generateSpawnId(): number {
return ++this.spawnCounter;
}
/**
* Add a process to the tracking map
*/
addProcess(taskId: string, process: AgentProcess): void {
this.processes.set(taskId, process);
}
/**
* Get a process by task ID
*/
getProcess(taskId: string): AgentProcess | undefined {
return this.processes.get(taskId);
}
/**
* Remove a process from tracking
*/
deleteProcess(taskId: string): boolean {
return this.processes.delete(taskId);
}
/**
* Check if a task has a running process
*/
hasProcess(taskId: string): boolean {
return this.processes.has(taskId);
}
/**
* Get all running task IDs
*/
getRunningTaskIds(): string[] {
return Array.from(this.processes.keys());
}
/**
* Mark a spawn ID as killed
*/
markSpawnAsKilled(spawnId: number): void {
this.killedSpawnIds.add(spawnId);
}
/**
* Check if a spawn ID was killed
*/
wasSpawnKilled(spawnId: number): boolean {
return this.killedSpawnIds.has(spawnId);
}
/**
* Remove a spawn ID from killed set
*/
clearKilledSpawn(spawnId: number): void {
this.killedSpawnIds.delete(spawnId);
}
/**
* Get all processes
*/
getAllProcesses(): Map<string, AgentProcess> {
return this.processes;
}
/**
* Clear all state (for testing or cleanup)
*/
clear(): void {
this.processes.clear();
this.killedSpawnIds.clear();
}
}
+28
View File
@@ -0,0 +1,28 @@
/**
* Agent module - modular agent management system
*
* This module provides a clean separation of concerns for agent process management:
* - AgentManager: Main facade for orchestrating agent lifecycle
* - AgentState: Process tracking and state management
* - AgentEvents: Event handling and progress parsing
* - AgentProcessManager: Process spawning and lifecycle
* - AgentQueueManager: Ideation and roadmap queue management
*/
export { AgentManager } from './agent-manager';
export { AgentState } from './agent-state';
export { AgentEvents } from './agent-events';
export { AgentProcessManager } from './agent-process';
export { AgentQueueManager } from './agent-queue';
export type {
AgentProcess,
ExecutionProgressData,
ProcessType,
AgentManagerEvents,
IdeationConfig,
TaskExecutionOptions,
SpecCreationMetadata,
IdeationProgressData,
RoadmapProgressData
} from './types';
+61
View File
@@ -0,0 +1,61 @@
import { ChildProcess } from 'child_process';
/**
* Agent-specific types for process and state management
*/
export interface AgentProcess {
taskId: string;
process: ChildProcess;
startedAt: Date;
projectPath?: string; // For ideation processes to load session on completion
spawnId: number; // Unique ID to identify this specific spawn
}
export interface ExecutionProgressData {
phase: 'idle' | 'planning' | 'coding' | 'qa_review' | 'qa_fixing' | 'complete' | 'failed';
phaseProgress: number;
overallProgress: number;
currentSubtask?: string;
message?: string;
}
export type ProcessType = 'spec-creation' | 'task-execution' | 'qa-process';
export interface AgentManagerEvents {
log: (taskId: string, log: string) => void;
error: (taskId: string, error: string) => void;
exit: (taskId: string, code: number | null, processType: ProcessType) => void;
'execution-progress': (taskId: string, progress: ExecutionProgressData) => void;
}
export interface IdeationConfig {
enabledTypes: string[];
includeRoadmapContext: boolean;
includeKanbanContext: boolean;
maxIdeasPerType: number;
append?: boolean;
}
export interface TaskExecutionOptions {
parallel?: boolean;
workers?: number;
baseBranch?: string;
}
export interface SpecCreationMetadata {
requireReviewBeforeCoding?: boolean;
}
export interface IdeationProgressData {
phase: string;
progress: number;
message: string;
completedTypes?: string[];
}
export interface RoadmapProgressData {
phase: string;
progress: number;
message: string;
}
+224
View File
@@ -0,0 +1,224 @@
/**
* Electron App Auto-Updater
*
* Manages automatic updates for the packaged Electron application using electron-updater.
* Updates are published through GitHub Releases and automatically downloaded and installed.
*
* Update flow:
* 1. Check for updates 3 seconds after app launch
* 2. Download updates automatically when available
* 3. Notify user when update is downloaded
* 4. Install and restart when user confirms
*
* Events sent to renderer:
* - APP_UPDATE_AVAILABLE: New update available (with version info)
* - APP_UPDATE_DOWNLOADED: Update downloaded and ready to install
* - APP_UPDATE_PROGRESS: Download progress updates
* - APP_UPDATE_ERROR: Error during update process
*/
import { autoUpdater } from 'electron-updater';
import { app } from 'electron';
import type { BrowserWindow } from 'electron';
import { IPC_CHANNELS } from '../shared/constants';
import type { AppUpdateInfo } from '../shared/types';
// Debug mode - set via environment variable
const DEBUG_UPDATER = process.env.DEBUG_UPDATER === 'true' || process.env.DEBUG === 'true';
// Configure electron-updater
autoUpdater.autoDownload = true; // Automatically download updates when available
autoUpdater.autoInstallOnAppQuit = true; // Automatically install on app quit
// Enable more verbose logging in debug mode
if (DEBUG_UPDATER) {
autoUpdater.logger = {
info: (msg: string) => console.warn('[app-updater:debug]', msg),
warn: (msg: string) => console.warn('[app-updater:debug]', msg),
error: (msg: string) => console.error('[app-updater:debug]', msg),
debug: (msg: string) => console.warn('[app-updater:debug]', msg)
};
}
let mainWindow: BrowserWindow | null = null;
/**
* Initialize the app updater system
*
* Sets up event handlers and starts periodic update checks.
* Should only be called in production (app.isPackaged).
*
* @param window - The main BrowserWindow for sending update events
*/
export function initializeAppUpdater(window: BrowserWindow): void {
mainWindow = window;
// Log updater configuration
console.warn('[app-updater] ========================================');
console.warn('[app-updater] Initializing app auto-updater');
console.warn('[app-updater] App packaged:', app.isPackaged);
console.warn('[app-updater] Current version:', autoUpdater.currentVersion.version);
console.warn('[app-updater] Auto-download enabled:', autoUpdater.autoDownload);
console.warn('[app-updater] Debug mode:', DEBUG_UPDATER);
console.warn('[app-updater] ========================================');
// ============================================
// Event Handlers
// ============================================
// Update available - new version found
autoUpdater.on('update-available', (info) => {
console.warn('[app-updater] Update available:', info.version);
if (mainWindow) {
mainWindow.webContents.send(IPC_CHANNELS.APP_UPDATE_AVAILABLE, {
version: info.version,
releaseNotes: info.releaseNotes,
releaseDate: info.releaseDate
});
}
});
// Update downloaded - ready to install
autoUpdater.on('update-downloaded', (info) => {
console.warn('[app-updater] Update downloaded:', info.version);
if (mainWindow) {
mainWindow.webContents.send(IPC_CHANNELS.APP_UPDATE_DOWNLOADED, {
version: info.version,
releaseNotes: info.releaseNotes,
releaseDate: info.releaseDate
});
}
});
// Download progress
autoUpdater.on('download-progress', (progress) => {
console.warn(`[app-updater] Download progress: ${progress.percent.toFixed(2)}%`);
if (mainWindow) {
mainWindow.webContents.send(IPC_CHANNELS.APP_UPDATE_PROGRESS, {
percent: progress.percent,
bytesPerSecond: progress.bytesPerSecond,
transferred: progress.transferred,
total: progress.total
});
}
});
// Error handling
autoUpdater.on('error', (error) => {
console.error('[app-updater] Update error:', error);
if (mainWindow) {
mainWindow.webContents.send(IPC_CHANNELS.APP_UPDATE_ERROR, {
message: error.message,
stack: error.stack
});
}
});
// No update available
autoUpdater.on('update-not-available', (info) => {
console.warn('[app-updater] No updates available - you are on the latest version');
console.warn('[app-updater] Current version:', info.version);
if (DEBUG_UPDATER) {
console.warn('[app-updater:debug] Full info:', JSON.stringify(info, null, 2));
}
});
// Checking for updates
autoUpdater.on('checking-for-update', () => {
console.warn('[app-updater] Checking for updates...');
});
// ============================================
// Update Check Schedule
// ============================================
// Check for updates 3 seconds after launch
const INITIAL_DELAY = 3000;
console.warn(`[app-updater] Will check for updates in ${INITIAL_DELAY / 1000} seconds...`);
setTimeout(() => {
console.warn('[app-updater] Performing initial update check');
autoUpdater.checkForUpdates().catch((error) => {
console.error('[app-updater] ❌ Initial update check failed:', error.message);
if (DEBUG_UPDATER) {
console.error('[app-updater:debug] Full error:', error);
}
});
}, INITIAL_DELAY);
// Check for updates every 4 hours
const FOUR_HOURS = 4 * 60 * 60 * 1000;
console.warn(`[app-updater] Periodic checks scheduled every ${FOUR_HOURS / 1000 / 60 / 60} hours`);
setInterval(() => {
console.warn('[app-updater] Performing periodic update check');
autoUpdater.checkForUpdates().catch((error) => {
console.error('[app-updater] ❌ Periodic update check failed:', error.message);
if (DEBUG_UPDATER) {
console.error('[app-updater:debug] Full error:', error);
}
});
}, FOUR_HOURS);
console.warn('[app-updater] Auto-updater initialized successfully');
}
/**
* Manually check for updates
* Called from IPC handler when user requests manual check
*/
export async function checkForUpdates(): Promise<AppUpdateInfo | null> {
try {
console.warn('[app-updater] Manual update check requested');
const result = await autoUpdater.checkForUpdates();
if (!result) {
return null;
}
const updateAvailable = result.updateInfo.version !== autoUpdater.currentVersion.version;
if (!updateAvailable) {
return null;
}
return {
version: result.updateInfo.version,
releaseNotes: result.updateInfo.releaseNotes as string | undefined,
releaseDate: result.updateInfo.releaseDate
};
} catch (error) {
console.error('[app-updater] Manual update check failed:', error);
throw error;
}
}
/**
* Manually download update
* Called from IPC handler when user requests manual download
*/
export async function downloadUpdate(): Promise<void> {
try {
console.warn('[app-updater] Manual update download requested');
await autoUpdater.downloadUpdate();
} catch (error) {
console.error('[app-updater] Manual update download failed:', error);
throw error;
}
}
/**
* Quit and install update
* Called from IPC handler when user confirms installation
*/
export function quitAndInstall(): void {
console.warn('[app-updater] Quitting and installing update');
autoUpdater.quitAndInstall(false, true);
}
/**
* Get current app version
*/
export function getCurrentVersion(): string {
return autoUpdater.currentVersion.version;
}
+34 -523
View File
@@ -1,537 +1,48 @@
/**
* Auto Claude Source Updater
*
* Checks GitHub for updates to the auto-claude framework and downloads them.
* This allows users to get new auto-claude features without requiring a full app update.
* Checks GitHub Releases for updates and downloads them.
* GitHub Releases are the single source of truth for versioning.
*
* Update flow:
* 1. Check GitHub for latest VERSION file
* 2. Compare with bundled source version
* 3. If update available, download and replace bundled source
* 1. Check GitHub Releases API for the latest release
* 2. Compare release tag with current app version
* 3. If update available, download release tarball and apply
* 4. Existing project update system handles pushing to individual projects
*/
import { existsSync, mkdirSync, writeFileSync, readFileSync, rmSync, readdirSync, statSync, copyFileSync } from 'fs';
import path from 'path';
import { app } from 'electron';
import https from 'https';
import { createWriteStream } from 'fs';
import { exec } from 'child_process';
import { promisify } from 'util';
const execAsync = promisify(exec);
/**
* GitHub repository configuration
*/
const GITHUB_CONFIG = {
owner: 'anthropics', // Update to actual repo owner
repo: 'auto-claude', // Update to actual repo name
branch: 'main',
autoBuildPath: 'auto-claude' // Path within repo
};
/**
* Result of checking for updates
*/
export interface AutoBuildUpdateCheck {
updateAvailable: boolean;
currentVersion: string;
latestVersion?: string;
releaseNotes?: string;
error?: string;
}
/**
* Result of applying an update
*/
export interface AutoBuildUpdateResult {
success: boolean;
version?: string;
error?: string;
}
/**
* Progress callback for download
*/
export type UpdateProgressCallback = (progress: {
stage: 'checking' | 'downloading' | 'extracting' | 'complete' | 'error';
percent?: number;
message: string;
}) => void;
/**
* Get the path to the bundled auto-claude source
*/
export function getBundledSourcePath(): string {
// In production, use app resources
// In development, use the repo's auto-claude folder
if (app.isPackaged) {
return path.join(process.resourcesPath, 'auto-claude');
}
// Development mode - look for auto-claude in various locations
const possiblePaths = [
path.join(app.getAppPath(), '..', 'auto-claude'),
path.join(app.getAppPath(), '..', '..', 'auto-claude'),
path.join(process.cwd(), 'auto-claude'),
path.join(process.cwd(), '..', 'auto-claude')
];
for (const p of possiblePaths) {
if (existsSync(p)) {
return p;
}
}
// Fallback
return path.join(app.getAppPath(), '..', 'auto-claude');
}
/**
* Get the path for storing downloaded updates
*/
function getUpdateCachePath(): string {
return path.join(app.getPath('userData'), 'auto-claude-updates');
}
/**
* Read the current bundled version
*/
export function getBundledVersion(): string {
const sourcePath = getBundledSourcePath();
const versionFile = path.join(sourcePath, 'VERSION');
if (existsSync(versionFile)) {
return readFileSync(versionFile, 'utf-8').trim();
}
return '0.0.0';
}
/**
* Fetch content from a URL using https
*/
function fetchUrl(url: string): Promise<string> {
return new Promise((resolve, reject) => {
const request = https.get(url, {
headers: {
'User-Agent': 'Auto-Claude-UI',
'Accept': 'application/vnd.github.v3.raw'
}
}, (response) => {
// Handle redirects
if (response.statusCode === 301 || response.statusCode === 302) {
const redirectUrl = response.headers.location;
if (redirectUrl) {
fetchUrl(redirectUrl).then(resolve).catch(reject);
return;
}
}
if (response.statusCode !== 200) {
reject(new Error(`HTTP ${response.statusCode}`));
return;
}
let data = '';
response.on('data', chunk => data += chunk);
response.on('end', () => resolve(data));
response.on('error', reject);
});
request.on('error', reject);
request.setTimeout(10000, () => {
request.destroy();
reject(new Error('Request timeout'));
});
});
}
/**
* Check GitHub for the latest version
*/
export async function checkForUpdates(): Promise<AutoBuildUpdateCheck> {
const currentVersion = getBundledVersion();
try {
// Fetch VERSION file from GitHub
const versionUrl = `https://raw.githubusercontent.com/${GITHUB_CONFIG.owner}/${GITHUB_CONFIG.repo}/${GITHUB_CONFIG.branch}/${GITHUB_CONFIG.autoBuildPath}/VERSION`;
const latestVersion = (await fetchUrl(versionUrl)).trim();
// Compare versions
const updateAvailable = compareVersions(latestVersion, currentVersion) > 0;
// If update available, try to fetch release notes
let releaseNotes: string | undefined;
if (updateAvailable) {
try {
const changelogUrl = `https://raw.githubusercontent.com/${GITHUB_CONFIG.owner}/${GITHUB_CONFIG.repo}/${GITHUB_CONFIG.branch}/${GITHUB_CONFIG.autoBuildPath}/CHANGELOG.md`;
releaseNotes = await fetchUrl(changelogUrl);
} catch {
// Changelog is optional
}
}
return {
updateAvailable,
currentVersion,
latestVersion,
releaseNotes
};
} catch (error) {
return {
updateAvailable: false,
currentVersion,
error: error instanceof Error ? error.message : 'Failed to check for updates'
};
}
}
/**
* Compare semantic versions
* Returns: 1 if a > b, -1 if a < b, 0 if equal
*/
function compareVersions(a: string, b: string): number {
const partsA = a.split('.').map(Number);
const partsB = b.split('.').map(Number);
for (let i = 0; i < Math.max(partsA.length, partsB.length); i++) {
const numA = partsA[i] || 0;
const numB = partsB[i] || 0;
if (numA > numB) return 1;
if (numA < numB) return -1;
}
return 0;
}
/**
* Download a file with progress tracking
*/
function downloadFile(
url: string,
destPath: string,
onProgress?: (percent: number) => void
): Promise<void> {
return new Promise((resolve, reject) => {
const file = createWriteStream(destPath);
const request = https.get(url, {
headers: {
'User-Agent': 'Auto-Claude-UI',
'Accept': 'application/octet-stream'
}
}, (response) => {
// Handle redirects
if (response.statusCode === 301 || response.statusCode === 302) {
file.close();
const redirectUrl = response.headers.location;
if (redirectUrl) {
downloadFile(redirectUrl, destPath, onProgress).then(resolve).catch(reject);
return;
}
}
if (response.statusCode !== 200) {
file.close();
reject(new Error(`HTTP ${response.statusCode}`));
return;
}
const totalSize = parseInt(response.headers['content-length'] || '0', 10);
let downloadedSize = 0;
response.on('data', (chunk) => {
downloadedSize += chunk.length;
if (totalSize > 0 && onProgress) {
onProgress(Math.round((downloadedSize / totalSize) * 100));
}
});
response.pipe(file);
file.on('finish', () => {
file.close();
resolve();
});
file.on('error', (err) => {
file.close();
reject(err);
});
});
request.on('error', (err) => {
file.close();
reject(err);
});
request.setTimeout(60000, () => {
request.destroy();
reject(new Error('Download timeout'));
});
});
}
/**
* Download and apply the latest auto-claude update
*
* Note: In production, this updates the bundled source in userData.
* For packaged apps, we can't modify resourcesPath directly,
* so we use a "source override" system.
* Versioning:
* - Single source of truth: GitHub Releases
* - Current version: app.getVersion() (from package.json at build time)
* - Latest version: Fetched from GitHub Releases API
* - To release: Create a GitHub release with tag (e.g., v1.2.0)
*/
export async function downloadAndApplyUpdate(
onProgress?: UpdateProgressCallback
): Promise<AutoBuildUpdateResult> {
const cachePath = getUpdateCachePath();
try {
onProgress?.({
stage: 'checking',
message: 'Checking for updates...'
});
// Export types
export type {
GitHubRelease,
AutoBuildUpdateCheck,
AutoBuildUpdateResult,
UpdateProgressCallback,
UpdateMetadata
} from './updater/types';
// Ensure cache directory exists
if (!existsSync(cachePath)) {
mkdirSync(cachePath, { recursive: true });
}
// Export version management
export { getBundledVersion } from './updater/version-manager';
// Get download URL for the tarball
const tarballUrl = `https://api.github.com/repos/${GITHUB_CONFIG.owner}/${GITHUB_CONFIG.repo}/tarball/${GITHUB_CONFIG.branch}`;
// Export path resolution
export {
getBundledSourcePath,
getEffectiveSourcePath
} from './updater/path-resolver';
const tarballPath = path.join(cachePath, 'auto-claude-update.tar.gz');
const extractPath = path.join(cachePath, 'extracted');
// Export update checking
export { checkForUpdates } from './updater/update-checker';
// Clean up previous extraction
if (existsSync(extractPath)) {
rmSync(extractPath, { recursive: true, force: true });
}
mkdirSync(extractPath, { recursive: true });
// Export update installation
export { downloadAndApplyUpdate } from './updater/update-installer';
onProgress?.({
stage: 'downloading',
percent: 0,
message: 'Downloading update...'
});
// Download the tarball
await downloadFile(tarballUrl, tarballPath, (percent) => {
onProgress?.({
stage: 'downloading',
percent,
message: `Downloading... ${percent}%`
});
});
onProgress?.({
stage: 'extracting',
message: 'Extracting update...'
});
// Extract the tarball
await extractTarball(tarballPath, extractPath);
// Find the auto-claude folder in extracted content
// GitHub tarballs have a root folder like "owner-repo-hash/"
const extractedDirs = readdirSync(extractPath);
if (extractedDirs.length === 0) {
throw new Error('Empty tarball');
}
const rootDir = path.join(extractPath, extractedDirs[0]);
const autoBuildSource = path.join(rootDir, GITHUB_CONFIG.autoBuildPath);
if (!existsSync(autoBuildSource)) {
throw new Error('auto-claude folder not found in download');
}
// Determine where to install the update
let targetPath: string;
if (app.isPackaged) {
// For packaged apps, store in userData as a source override
targetPath = path.join(app.getPath('userData'), 'auto-claude-source');
} else {
// In development, update the actual source
targetPath = getBundledSourcePath();
}
// Backup existing source (if in dev mode)
const backupPath = path.join(cachePath, 'backup');
if (!app.isPackaged && existsSync(targetPath)) {
if (existsSync(backupPath)) {
rmSync(backupPath, { recursive: true, force: true });
}
// Simple copy for backup
copyDirectoryRecursive(targetPath, backupPath);
}
// Copy new source to target
if (existsSync(targetPath)) {
// Clean target but preserve certain files
const preserveFiles = ['.env', 'specs'];
const preservedContent: Record<string, Buffer> = {};
for (const file of preserveFiles) {
const filePath = path.join(targetPath, file);
if (existsSync(filePath)) {
if (statSync(filePath).isDirectory()) {
// Skip directories for now - they'll be preserved by copyDirectoryRecursive
} else {
preservedContent[file] = readFileSync(filePath);
}
}
}
// Remove old files except preserved
const items = readdirSync(targetPath);
for (const item of items) {
if (!preserveFiles.includes(item)) {
rmSync(path.join(targetPath, item), { recursive: true, force: true });
}
}
// Copy new files
copyDirectoryRecursive(autoBuildSource, targetPath, true);
// Restore preserved files that might have been overwritten
for (const [file, content] of Object.entries(preservedContent)) {
writeFileSync(path.join(targetPath, file), content);
}
} else {
mkdirSync(targetPath, { recursive: true });
copyDirectoryRecursive(autoBuildSource, targetPath, false);
}
// Read the new version
const versionFile = path.join(targetPath, 'VERSION');
const newVersion = existsSync(versionFile)
? readFileSync(versionFile, 'utf-8').trim()
: 'unknown';
// Write update metadata
const metadataPath = path.join(targetPath, '.update-metadata.json');
writeFileSync(metadataPath, JSON.stringify({
version: newVersion,
updatedAt: new Date().toISOString(),
source: 'github',
branch: GITHUB_CONFIG.branch
}, null, 2));
// Cleanup
rmSync(tarballPath, { force: true });
rmSync(extractPath, { recursive: true, force: true });
onProgress?.({
stage: 'complete',
message: `Updated to version ${newVersion}`
});
return {
success: true,
version: newVersion
};
} catch (error) {
onProgress?.({
stage: 'error',
message: error instanceof Error ? error.message : 'Update failed'
});
return {
success: false,
error: error instanceof Error ? error.message : 'Unknown error'
};
}
}
/**
* Extract a .tar.gz file using system tar command
*/
async function extractTarball(tarballPath: string, destPath: string): Promise<void> {
// Use system tar command which is available on macOS, Linux, and modern Windows
try {
await execAsync(`tar -xzf "${tarballPath}" -C "${destPath}"`);
} catch (error) {
throw new Error(`Failed to extract tarball: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
/**
* Recursively copy directory
*/
function copyDirectoryRecursive(
src: string,
dest: string,
preserveExisting: boolean = false
): void {
if (!existsSync(dest)) {
mkdirSync(dest, { recursive: true });
}
const entries = readdirSync(src, { withFileTypes: true });
for (const entry of entries) {
const srcPath = path.join(src, entry.name);
const destPath = path.join(dest, entry.name);
// Skip certain files/directories
if (['__pycache__', '.DS_Store', '.git', 'specs', '.env'].includes(entry.name)) {
continue;
}
// In preserve mode, skip existing files
if (preserveExisting && existsSync(destPath)) {
if (entry.isDirectory()) {
copyDirectoryRecursive(srcPath, destPath, preserveExisting);
}
continue;
}
if (entry.isDirectory()) {
copyDirectoryRecursive(srcPath, destPath, preserveExisting);
} else {
copyFileSync(srcPath, destPath);
}
}
}
/**
* Get the effective source path (considers override from updates)
*/
export function getEffectiveSourcePath(): string {
if (app.isPackaged) {
// Check for user-updated source first
const overridePath = path.join(app.getPath('userData'), 'auto-claude-source');
if (existsSync(overridePath)) {
return overridePath;
}
}
return getBundledSourcePath();
}
/**
* Check if there's a pending source update that requires restart
*/
export function hasPendingSourceUpdate(): boolean {
if (!app.isPackaged) {
return false;
}
const overridePath = path.join(app.getPath('userData'), 'auto-claude-source');
const metadataPath = path.join(overridePath, '.update-metadata.json');
if (!existsSync(metadataPath)) {
return false;
}
try {
const metadata = JSON.parse(readFileSync(metadataPath, 'utf-8'));
const bundledVersion = getBundledVersion();
return compareVersions(metadata.version, bundledVersion) > 0;
} catch {
return false;
}
}
// Export update status
export {
hasPendingSourceUpdate,
getUpdateMetadata
} from './updater/update-status';
+13 -774
View File
@@ -1,777 +1,16 @@
import { EventEmitter } from 'events';
import path from 'path';
import { existsSync, readFileSync, writeFileSync } from 'fs';
import { spawn } from 'child_process';
import { app } from 'electron';
import { AUTO_BUILD_PATHS, DEFAULT_CHANGELOG_PATH } from '../shared/constants';
import type {
ChangelogTask,
TaskSpecContent,
ChangelogGenerationRequest,
ChangelogGenerationResult,
ChangelogSaveRequest,
ChangelogSaveResult,
ChangelogGenerationProgress,
ExistingChangelog,
Task,
ImplementationPlan
} from '../shared/types';
/**
* Service for generating changelogs from completed tasks
* Changelog Service - Re-export facade
*
* This file maintains backward compatibility by re-exporting from the modular changelog directory.
* The actual implementation has been split into focused modules:
*
* - changelog/changelog-service.ts: Main orchestrator
* - changelog/generator.ts: AI generation logic
* - changelog/parser.ts: Parsing and extraction
* - changelog/formatter.ts: Prompt building and formatting
* - changelog/git-integration.ts: Git operations
* - changelog/types.ts: Type definitions
*/
export class ChangelogService extends EventEmitter {
private pythonPath: string = 'python3';
private claudePath: string = 'claude';
private autoBuildSourcePath: string = '';
private generationProcesses: Map<string, ReturnType<typeof spawn>> = new Map();
private cachedEnv: Record<string, string> | null = null;
private debugEnabled: boolean | null = null;
constructor() {
super();
this.detectClaudePath();
this.debug('ChangelogService initialized');
}
/**
* Detect the full path to the claude CLI
* Electron apps don't inherit shell PATH, so we need to find it explicitly
*/
private detectClaudePath(): void {
const possiblePaths = [
'/usr/local/bin/claude',
'/opt/homebrew/bin/claude',
path.join(process.env.HOME || '', '.local/bin/claude'),
path.join(process.env.HOME || '', 'bin/claude'),
// Also check if claude is in system PATH
'claude'
];
for (const claudePath of possiblePaths) {
if (claudePath === 'claude' || existsSync(claudePath)) {
this.claudePath = claudePath;
this.debug('Claude CLI found at:', claudePath);
return;
}
}
this.debug('Claude CLI not found in common locations, using default');
}
/**
* Check if debug mode is enabled
* Checks DEBUG from auto-claude/.env and AUTO_CLAUDE_DEBUG from process.env
*/
private isDebugEnabled(): boolean {
// Cache the result after first check
if (this.debugEnabled !== null) {
return this.debugEnabled;
}
// Check process.env first
if (
process.env.DEBUG === 'true' ||
process.env.DEBUG === '1' ||
process.env.AUTO_CLAUDE_DEBUG === 'true' ||
process.env.AUTO_CLAUDE_DEBUG === '1'
) {
this.debugEnabled = true;
return true;
}
// Check auto-claude .env file
const env = this.loadAutoBuildEnv();
this.debugEnabled = env.DEBUG === 'true' || env.DEBUG === '1';
return this.debugEnabled;
}
/**
* Debug logging - only logs when DEBUG=true in auto-claude/.env or AUTO_CLAUDE_DEBUG is set
*/
private debug(...args: unknown[]): void {
if (this.isDebugEnabled()) {
console.log('[ChangelogService]', ...args);
}
}
/**
* Configure paths for Python and auto-claude source
*/
configure(pythonPath?: string, autoBuildSourcePath?: string): void {
if (pythonPath) {
this.pythonPath = pythonPath;
}
if (autoBuildSourcePath) {
this.autoBuildSourcePath = autoBuildSourcePath;
}
}
/**
* Get the auto-claude source path (detects automatically if not configured)
*/
private getAutoBuildSourcePath(): string | null {
if (this.autoBuildSourcePath && existsSync(this.autoBuildSourcePath)) {
return this.autoBuildSourcePath;
}
const possiblePaths = [
path.resolve(__dirname, '..', '..', '..', 'auto-claude'),
path.resolve(app.getAppPath(), '..', 'auto-claude'),
path.resolve(process.cwd(), 'auto-claude')
];
for (const p of possiblePaths) {
if (existsSync(p) && existsSync(path.join(p, 'VERSION'))) {
return p;
}
}
return null;
}
/**
* Load environment variables from auto-claude .env file
*/
private loadAutoBuildEnv(): Record<string, string> {
const autoBuildSource = this.getAutoBuildSourcePath();
if (!autoBuildSource) return {};
const envPath = path.join(autoBuildSource, '.env');
if (!existsSync(envPath)) return {};
try {
const envContent = readFileSync(envPath, 'utf-8');
const envVars: Record<string, string> = {};
for (const line of envContent.split('\n')) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith('#')) continue;
const eqIndex = trimmed.indexOf('=');
if (eqIndex > 0) {
const key = trimmed.substring(0, eqIndex).trim();
let value = trimmed.substring(eqIndex + 1).trim();
if ((value.startsWith('"') && value.endsWith('"')) ||
(value.startsWith("'") && value.endsWith("'"))) {
value = value.slice(1, -1);
}
envVars[key] = value;
}
}
return envVars;
} catch {
return {};
}
}
/**
* Get completed tasks from a project
* @param projectPath - Project root path
* @param tasks - List of tasks
* @param specsBaseDir - Base specs directory (e.g., 'auto-claude/specs' or 'dev/auto-claude/specs')
*/
getCompletedTasks(projectPath: string, tasks: Task[], specsBaseDir?: string): ChangelogTask[] {
const specsDir = path.join(projectPath, specsBaseDir || AUTO_BUILD_PATHS.SPECS_DIR);
return tasks
.filter(task => task.status === 'done')
.map(task => {
const specDir = path.join(specsDir, task.specId);
const hasSpecs = existsSync(specDir) && existsSync(path.join(specDir, AUTO_BUILD_PATHS.SPEC_FILE));
return {
id: task.id,
specId: task.specId,
title: task.title,
description: task.description,
completedAt: task.updatedAt,
hasSpecs
};
})
.sort((a, b) => new Date(b.completedAt).getTime() - new Date(a.completedAt).getTime());
}
/**
* Load spec files for given tasks
* @param projectPath - Project root path
* @param taskIds - IDs of tasks to load specs for
* @param tasks - List of all tasks
* @param specsBaseDir - Base specs directory (e.g., 'auto-claude/specs' or 'dev/auto-claude/specs')
*/
async loadTaskSpecs(projectPath: string, taskIds: string[], tasks: Task[], specsBaseDir?: string): Promise<TaskSpecContent[]> {
const specsDir = path.join(projectPath, specsBaseDir || AUTO_BUILD_PATHS.SPECS_DIR);
this.debug('loadTaskSpecs called', { projectPath, specsDir, taskCount: taskIds.length });
const results: TaskSpecContent[] = [];
for (const taskId of taskIds) {
const task = tasks.find(t => t.id === taskId);
if (!task) {
this.debug('Task not found:', taskId);
continue;
}
const specDir = path.join(specsDir, task.specId);
this.debug('Loading spec for task', { taskId, specId: task.specId, specDir });
const content: TaskSpecContent = {
taskId,
specId: task.specId
};
try {
// Load spec.md
const specPath = path.join(specDir, AUTO_BUILD_PATHS.SPEC_FILE);
if (existsSync(specPath)) {
content.spec = readFileSync(specPath, 'utf-8');
this.debug('Loaded spec.md', { specId: task.specId, length: content.spec.length });
}
// Load requirements.json
const requirementsPath = path.join(specDir, AUTO_BUILD_PATHS.REQUIREMENTS);
if (existsSync(requirementsPath)) {
content.requirements = JSON.parse(readFileSync(requirementsPath, 'utf-8'));
}
// Load qa_report.md
const qaReportPath = path.join(specDir, AUTO_BUILD_PATHS.QA_REPORT);
if (existsSync(qaReportPath)) {
content.qaReport = readFileSync(qaReportPath, 'utf-8');
}
// Load implementation_plan.json
const planPath = path.join(specDir, AUTO_BUILD_PATHS.IMPLEMENTATION_PLAN);
if (existsSync(planPath)) {
content.implementationPlan = JSON.parse(readFileSync(planPath, 'utf-8')) as ImplementationPlan;
}
} catch (error) {
content.error = error instanceof Error ? error.message : 'Failed to load spec files';
this.debug('Error loading spec', { specId: task.specId, error: content.error });
}
results.push(content);
}
this.debug('loadTaskSpecs complete', { loadedCount: results.length });
return results;
}
/**
* Generate changelog using Claude AI
*/
generateChangelog(
projectId: string,
projectPath: string,
request: ChangelogGenerationRequest,
specs: TaskSpecContent[]
): void {
this.debug('generateChangelog called', {
projectId,
projectPath,
taskCount: request.taskIds.length,
version: request.version,
format: request.format,
audience: request.audience
});
// Kill existing process if any
this.cancelGeneration(projectId);
// Emit initial progress
this.emitProgress(projectId, {
stage: 'loading_specs',
progress: 10,
message: 'Preparing changelog generation...'
});
// Build the prompt for Claude
const prompt = this.buildChangelogPrompt(request, specs);
this.debug('Prompt built', {
promptLength: prompt.length,
promptPreview: prompt.substring(0, 500) + '...'
});
// Use Claude Code SDK via subprocess
const autoBuildSource = this.getAutoBuildSourcePath();
if (!autoBuildSource) {
this.debug('ERROR: Auto-build source path not found');
this.emitError(projectId, 'Auto-build source path not found');
return;
}
this.debug('Auto-build source path:', autoBuildSource);
// Verify claude CLI is available
if (this.claudePath !== 'claude' && !existsSync(this.claudePath)) {
this.debug('ERROR: Claude CLI not found at:', this.claudePath);
this.emitError(projectId, `Claude CLI not found. Please ensure Claude Code is installed. Looked for: ${this.claudePath}`);
return;
}
this.debug('Using Claude CLI at:', this.claudePath);
// Create a temporary Python script to call Claude
const script = this.createGenerationScript(prompt, request);
this.debug('Python script created', { scriptLength: script.length });
this.emitProgress(projectId, {
stage: 'generating',
progress: 30,
message: 'Generating changelog with Claude AI...'
});
const autoBuildEnv = this.loadAutoBuildEnv();
this.debug('Environment loaded', {
hasOAuthToken: !!autoBuildEnv.CLAUDE_CODE_OAUTH_TOKEN,
envKeys: Object.keys(autoBuildEnv)
});
const startTime = Date.now();
this.debug('Spawning Python process...');
// Build environment with explicit critical variables
// Electron apps may not inherit shell environment correctly
const homeDir = process.env.HOME || app.getPath('home');
const spawnEnv = {
...process.env,
...autoBuildEnv,
// Ensure critical env vars are set for claude CLI
HOME: homeDir,
USER: process.env.USER || process.env.USERNAME || 'user',
// Add common binary locations to PATH for claude CLI
PATH: [
process.env.PATH || '',
'/usr/local/bin',
'/opt/homebrew/bin',
path.join(homeDir, '.local/bin'),
path.join(homeDir, 'bin')
].filter(Boolean).join(':'),
PYTHONUNBUFFERED: '1'
};
this.debug('Spawn environment', {
HOME: spawnEnv.HOME,
USER: spawnEnv.USER,
pathDirs: spawnEnv.PATH?.split(':').length
});
const childProcess = spawn(this.pythonPath, ['-c', script], {
cwd: autoBuildSource,
env: spawnEnv
});
this.generationProcesses.set(projectId, childProcess);
this.debug('Process spawned with PID:', childProcess.pid);
let output = '';
let errorOutput = '';
childProcess.stdout?.on('data', (data: Buffer) => {
const chunk = data.toString();
output += chunk;
this.debug('stdout chunk received', { chunkLength: chunk.length, totalOutput: output.length });
this.emitProgress(projectId, {
stage: 'generating',
progress: 50,
message: 'Generating changelog content...'
});
});
childProcess.stderr?.on('data', (data: Buffer) => {
const chunk = data.toString();
errorOutput += chunk;
this.debug('stderr chunk received', { chunk: chunk.substring(0, 200) });
});
childProcess.on('exit', (code: number | null) => {
const duration = Date.now() - startTime;
this.debug('Process exited', {
code,
duration: `${duration}ms`,
outputLength: output.length,
errorLength: errorOutput.length
});
this.generationProcesses.delete(projectId);
if (code === 0 && output.trim()) {
this.emitProgress(projectId, {
stage: 'formatting',
progress: 90,
message: 'Formatting changelog...'
});
// Extract changelog from output
const changelog = this.extractChangelog(output.trim());
this.debug('Changelog extracted', { changelogLength: changelog.length });
this.emitProgress(projectId, {
stage: 'complete',
progress: 100,
message: 'Changelog generation complete'
});
const result: ChangelogGenerationResult = {
success: true,
changelog,
version: request.version,
tasksIncluded: request.taskIds.length
};
this.debug('Generation complete, emitting result');
this.emit('generation-complete', projectId, result);
} else {
const error = errorOutput || `Generation failed with exit code ${code}`;
this.debug('Generation failed', { error: error.substring(0, 500) });
this.emitError(projectId, error);
}
});
childProcess.on('error', (err: Error) => {
this.debug('Process error', { error: err.message });
this.generationProcesses.delete(projectId);
this.emitError(projectId, err.message);
});
}
/**
* Extract the overview section from a spec (typically the first meaningful section)
*/
private extractSpecOverview(spec: string): string {
// Split into lines and find the Overview section
const lines = spec.split('\n');
let inOverview = false;
let overview: string[] = [];
for (const line of lines) {
// Start capturing at Overview heading
if (/^##\s*Overview/i.test(line)) {
inOverview = true;
continue;
}
// Stop at next major heading
if (inOverview && /^##\s/.test(line)) {
break;
}
if (inOverview && line.trim()) {
overview.push(line);
}
}
// If no overview found, take first paragraph after title
if (overview.length === 0) {
const paragraphs = spec.split(/\n\n+/).filter(p => !p.startsWith('#') && p.trim().length > 20);
if (paragraphs.length > 0) {
return paragraphs[0].substring(0, 300);
}
}
return overview.join(' ').substring(0, 400);
}
/**
* Build the prompt for changelog generation
* Optimized to keep prompt size manageable for faster generation
*/
private buildChangelogPrompt(
request: ChangelogGenerationRequest,
specs: TaskSpecContent[]
): string {
const audienceInstructions = {
'technical': `You are a technical documentation specialist creating a changelog for developers. Use precise technical language.`,
'user-facing': `You are a product manager writing release notes for end users. Use clear, non-technical language focusing on user benefits.`,
'marketing': `You are a marketing specialist writing release notes. Focus on outcomes and user impact with compelling language.`
};
const formatInstructions = {
'keep-a-changelog': `## [${request.version}] - ${request.date}
### Added
- [New features]
### Changed
- [Modifications]
### Fixed
- [Bug fixes]`,
'simple-list': `# Release v${request.version} (${request.date})
**New Features:**
- [List features]
**Improvements:**
- [List improvements]
**Bug Fixes:**
- [List fixes]`,
'github-release': `## What's New in v${request.version}
### New Features
- **Feature Name**: Description
### Improvements
- Description
### Bug Fixes
- Fixed [issue]`
};
// Build CONCISE task summaries (key to avoiding timeout)
const taskSummaries = specs.map(spec => {
const parts: string[] = [`- **${spec.specId}**`];
// Get workflow type if available
if (spec.implementationPlan?.workflow_type) {
parts.push(`(${spec.implementationPlan.workflow_type})`);
}
// Extract just the overview/purpose
if (spec.spec) {
const overview = this.extractSpecOverview(spec.spec);
if (overview) {
parts.push(`: ${overview}`);
}
}
return parts.join('');
}).join('\n');
return `${audienceInstructions[request.audience]}
Format:
${formatInstructions[request.format]}
Completed tasks:
${taskSummaries}
${request.customInstructions ? `Note: ${request.customInstructions}` : ''}
Generate the changelog now. Output ONLY the formatted changelog, no preamble.`;
}
/**
* Create Python script for Claude generation
*/
private createGenerationScript(prompt: string, _request: ChangelogGenerationRequest): string {
// Escape the prompt for Python string
const escapedPrompt = prompt
.replace(/\\/g, '\\\\')
.replace(/"/g, '\\"')
.replace(/\n/g, '\\n');
// Escape the claude path for Python string
const escapedClaudePath = this.claudePath.replace(/\\/g, '\\\\');
return `
import subprocess
import sys
import os
print("SCRIPT_START", file=sys.stderr, flush=True)
print(f"HOME={os.environ.get('HOME')}", file=sys.stderr, flush=True)
print(f"Claude path: ${escapedClaudePath}", file=sys.stderr, flush=True)
prompt = """${escapedPrompt}"""
print(f"Prompt length: {len(prompt)}", file=sys.stderr, flush=True)
print("Starting subprocess.run...", file=sys.stderr, flush=True)
# Use Claude Code CLI to generate
# --max-turns 1: Single response (no back-and-forth needed)
# --model haiku: Faster model for simple text generation
try:
result = subprocess.run(
['${escapedClaudePath}', '-p', prompt, '--output-format', 'text', '--max-turns', '1', '--model', 'haiku'],
capture_output=True,
text=True,
timeout=180
)
print(f"subprocess.run completed with code {result.returncode}", file=sys.stderr, flush=True)
if result.returncode == 0:
print(result.stdout)
else:
print(f"STDERR from claude: {result.stderr}", file=sys.stderr, flush=True)
print(result.stderr, file=sys.stderr)
sys.exit(1)
except Exception as e:
print(f"Exception: {type(e).__name__}: {e}", file=sys.stderr, flush=True)
sys.exit(1)
`;
}
/**
* Extract changelog content from Claude output
*/
private extractChangelog(output: string): string {
// Claude output should be the changelog directly
// Clean up any potential wrapper text
let changelog = output.trim();
// Remove any "Here's the changelog:" or similar prefixes
const prefixes = [
/^Here['']s the changelog[:\s]*/i,
/^The changelog[:\s]*/i,
/^Changelog[:\s]*/i
];
for (const prefix of prefixes) {
changelog = changelog.replace(prefix, '');
}
return changelog.trim();
}
/**
* Save changelog to file
*/
saveChangelog(
projectPath: string,
request: ChangelogSaveRequest
): ChangelogSaveResult {
const filePath = request.filePath
? path.join(projectPath, request.filePath)
: path.join(projectPath, DEFAULT_CHANGELOG_PATH);
let finalContent = request.content;
if (request.mode === 'prepend' && existsSync(filePath)) {
const existing = readFileSync(filePath, 'utf-8');
// Add separator between new and existing content
finalContent = `${request.content}\n\n${existing}`;
} else if (request.mode === 'append' && existsSync(filePath)) {
const existing = readFileSync(filePath, 'utf-8');
finalContent = `${existing}\n\n${request.content}`;
}
writeFileSync(filePath, finalContent, 'utf-8');
return {
filePath,
bytesWritten: Buffer.byteLength(finalContent, 'utf-8')
};
}
/**
* Read existing changelog file
*/
readExistingChangelog(projectPath: string): ExistingChangelog {
const filePath = path.join(projectPath, DEFAULT_CHANGELOG_PATH);
if (!existsSync(filePath)) {
return { exists: false };
}
try {
const content = readFileSync(filePath, 'utf-8');
// Try to extract last version using common patterns
const versionPatterns = [
/##\s*\[(\d+\.\d+\.\d+)\]/, // Keep-a-changelog format
/v(\d+\.\d+\.\d+)/, // v1.2.3 format
/Version\s+(\d+\.\d+\.\d+)/i // Version 1.2.3 format
];
let lastVersion: string | undefined;
for (const pattern of versionPatterns) {
const match = content.match(pattern);
if (match) {
lastVersion = match[1];
break;
}
}
return {
exists: true,
content,
lastVersion
};
} catch (error) {
return {
exists: true,
error: error instanceof Error ? error.message : 'Failed to read changelog'
};
}
}
/**
* Suggest next version based on task types
*/
suggestVersion(specs: TaskSpecContent[], currentVersion?: string): string {
// Default starting version
if (!currentVersion) {
return '1.0.0';
}
const parts = currentVersion.split('.').map(Number);
if (parts.length !== 3 || parts.some(isNaN)) {
return '1.0.0';
}
let [major, minor, patch] = parts;
// Analyze specs for version increment decision
let hasBreakingChanges = false;
let hasNewFeatures = false;
for (const spec of specs) {
const content = (spec.spec || '').toLowerCase();
if (content.includes('breaking change') || content.includes('breaking:')) {
hasBreakingChanges = true;
}
if (spec.implementationPlan?.workflow_type === 'new_feature' ||
content.includes('new feature') ||
content.includes('## added')) {
hasNewFeatures = true;
}
}
if (hasBreakingChanges) {
return `${major + 1}.0.0`;
} else if (hasNewFeatures) {
return `${major}.${minor + 1}.0`;
} else {
return `${major}.${minor}.${patch + 1}`;
}
}
/**
* Cancel ongoing generation
*/
cancelGeneration(projectId: string): boolean {
const process = this.generationProcesses.get(projectId);
if (process) {
process.kill('SIGTERM');
this.generationProcesses.delete(projectId);
return true;
}
return false;
}
/**
* Emit progress update
*/
private emitProgress(projectId: string, progress: ChangelogGenerationProgress): void {
this.emit('generation-progress', projectId, progress);
}
/**
* Emit error
*/
private emitError(projectId: string, error: string): void {
this.emit('generation-progress', projectId, {
stage: 'error',
progress: 0,
message: error,
error
});
this.emit('generation-error', projectId, error);
}
}
// Export singleton instance
export const changelogService = new ChangelogService();
export { ChangelogService, changelogService } from './changelog/changelog-service';
export type { ChangelogConfig, PromptBuildOptions, VersionSuggestion, GenerationScriptParams } from './changelog/types';
@@ -0,0 +1,99 @@
# Changelog Module
This directory contains the refactored changelog generation system, split into focused, maintainable modules.
## Architecture
The changelog service has been decomposed from a monolithic 1,279-line file into specialized modules:
### Module Structure
```
changelog/
├── changelog-service.ts # Main orchestrator (slim facade)
├── generator.ts # AI-powered changelog generation
├── parser.ts # Parsing and extraction logic
├── formatter.ts # Prompt building and formatting
├── git-integration.ts # Git operations (branches, tags, commits)
├── types.ts # Module-specific type definitions
└── index.ts # Clean module exports
```
### Responsibilities
#### `changelog-service.ts` (Main Facade)
- Orchestrates all changelog operations
- Manages configuration and environment setup
- Delegates to specialized modules
- Provides public API for IPC handlers
- ~465 lines (down from 1,279)
#### `generator.ts` (AI Generation)
- Handles Claude CLI subprocess spawning
- Manages generation lifecycle and progress
- Rate limit detection and error handling
- Environment configuration for subprocess
- ~340 lines
#### `parser.ts` (Parsing & Extraction)
- Extract spec overviews
- Extract changelog from AI output
- Parse existing changelog files
- Parse git log output into structured data
- ~160 lines
#### `formatter.ts` (Prompt Building)
- Build prompts for task-based changelogs
- Build prompts for git-based changelogs
- Format templates (keep-a-changelog, simple-list, github-release)
- Audience-specific instructions (technical, user-facing, marketing)
- Python script generation for Claude CLI
- ~190 lines
#### `git-integration.ts` (Git Operations)
- Get branches (local and remote)
- Get tags with metadata
- Get current and default branch
- Get commits for various scenarios (recent, since-date, tag-range)
- Get branch diff commits
- ~230 lines
#### `types.ts` (Type Definitions)
- Changelog-specific types
- Configuration interfaces
- Internal type definitions
- ~25 lines
## Usage
### Import the Service
```typescript
import { changelogService } from './changelog-service';
// or
import { changelogService } from './changelog';
```
### Backward Compatibility
The original `/src/main/changelog-service.ts` now serves as a re-export facade, maintaining full backward compatibility with existing code.
## Benefits of Refactoring
1. **Single Responsibility**: Each module has one clear purpose
2. **Easier Testing**: Smaller, focused modules are easier to test
3. **Better Maintainability**: Changes are isolated to relevant modules
4. **Reduced Complexity**: No single file exceeds 500 lines
5. **Improved Readability**: Clear separation of concerns
6. **Easier Navigation**: Developers can quickly find relevant code
## Design Patterns Used
- **Facade Pattern**: `changelog-service.ts` provides unified interface
- **Delegation**: Service delegates to specialized modules
- **Single Responsibility**: Each module has one clear concern
- **Event Emitter**: Generator emits progress and error events
## Migration Notes
No changes required for existing code - the refactoring maintains full API compatibility through the facade pattern.
@@ -0,0 +1,548 @@
import { EventEmitter } from 'events';
import * as path from 'path';
import * as os from 'os';
import { existsSync, readFileSync, writeFileSync } from 'fs';
import { app } from 'electron';
import { AUTO_BUILD_PATHS, DEFAULT_CHANGELOG_PATH } from '../../shared/constants';
import type {
ChangelogTask,
TaskSpecContent,
ChangelogGenerationRequest,
ChangelogSaveRequest,
ChangelogSaveResult,
ExistingChangelog,
Task,
ImplementationPlan,
GitBranchInfo,
GitTagInfo
} from '../../shared/types';
import { ChangelogGenerator } from './generator';
import { VersionSuggester } from './version-suggester';
import { parseExistingChangelog } from './parser';
import {
getBranches,
getTags,
getCurrentBranch,
getDefaultBranch,
getCommits,
getBranchDiffCommits
} from './git-integration';
/**
* Main changelog service - orchestrates all changelog operations
* Delegates to specialized modules for specific concerns
*/
export class ChangelogService extends EventEmitter {
private pythonPath: string = 'python3';
private claudePath: string = 'claude';
private autoBuildSourcePath: string = '';
private cachedEnv: Record<string, string> | null = null;
private debugEnabled: boolean | null = null;
private generator: ChangelogGenerator | null = null;
private versionSuggester: VersionSuggester | null = null;
constructor() {
super();
this.detectClaudePath();
this.debug('ChangelogService initialized');
}
/**
* Detect the full path to the claude CLI
* Electron apps don't inherit shell PATH, so we need to find it explicitly
*/
private detectClaudePath(): void {
const homeDir = os.homedir();
// Platform-specific possible paths
const possiblePaths = process.platform === 'win32'
? [
// Windows paths
path.join(homeDir, 'AppData', 'Local', 'Programs', 'claude', 'claude.exe'),
path.join(homeDir, 'AppData', 'Roaming', 'npm', 'claude.cmd'),
path.join(homeDir, '.local', 'bin', 'claude.exe'),
'C:\\Program Files\\Claude\\claude.exe',
'C:\\Program Files (x86)\\Claude\\claude.exe',
// Also check if claude is in system PATH
'claude'
]
: [
// Unix paths (macOS/Linux)
'/usr/local/bin/claude',
'/opt/homebrew/bin/claude',
path.join(homeDir, '.local/bin/claude'),
path.join(homeDir, 'bin/claude'),
// Also check if claude is in system PATH
'claude'
];
for (const claudePath of possiblePaths) {
if (claudePath === 'claude' || existsSync(claudePath)) {
this.claudePath = claudePath;
this.debug('Claude CLI found at:', claudePath);
return;
}
}
this.debug('Claude CLI not found in common locations, using default');
}
/**
* Check if debug mode is enabled
* Checks DEBUG from auto-claude/.env and AUTO_CLAUDE_DEBUG from process.env
*/
private isDebugEnabled(): boolean {
// Cache the result after first check
if (this.debugEnabled !== null) {
return this.debugEnabled;
}
// Check process.env first
if (
process.env.DEBUG === 'true' ||
process.env.DEBUG === '1' ||
process.env.AUTO_CLAUDE_DEBUG === 'true' ||
process.env.AUTO_CLAUDE_DEBUG === '1'
) {
this.debugEnabled = true;
return true;
}
// Check auto-claude .env file
const env = this.loadAutoBuildEnv();
this.debugEnabled = env.DEBUG === 'true' || env.DEBUG === '1';
return this.debugEnabled;
}
/**
* Debug logging - only logs when DEBUG=true in auto-claude/.env or AUTO_CLAUDE_DEBUG is set
*/
private debug(...args: unknown[]): void {
if (this.isDebugEnabled()) {
console.warn('[ChangelogService]', ...args);
}
}
/**
* Configure paths for Python and auto-claude source
*/
configure(pythonPath?: string, autoBuildSourcePath?: string): void {
if (pythonPath) {
this.pythonPath = pythonPath;
}
if (autoBuildSourcePath) {
this.autoBuildSourcePath = autoBuildSourcePath;
}
}
/**
* Get the auto-claude source path (detects automatically if not configured)
*/
private getAutoBuildSourcePath(): string | null {
if (this.autoBuildSourcePath && existsSync(this.autoBuildSourcePath)) {
return this.autoBuildSourcePath;
}
const possiblePaths = [
path.resolve(__dirname, '..', '..', '..', 'auto-claude'),
path.resolve(app.getAppPath(), '..', 'auto-claude'),
path.resolve(process.cwd(), 'auto-claude')
];
for (const p of possiblePaths) {
// Use requirements.txt as marker - it always exists in auto-claude source
if (existsSync(p) && existsSync(path.join(p, 'requirements.txt'))) {
return p;
}
}
return null;
}
/**
* Load environment variables from auto-claude .env file
*/
private loadAutoBuildEnv(): Record<string, string> {
const autoBuildSource = this.getAutoBuildSourcePath();
if (!autoBuildSource) return {};
const envPath = path.join(autoBuildSource, '.env');
if (!existsSync(envPath)) return {};
try {
const envContent = readFileSync(envPath, 'utf-8');
const envVars: Record<string, string> = {};
// Handle both Unix (\n) and Windows (\r\n) line endings
for (const line of envContent.split(/\r?\n/)) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith('#')) continue;
const eqIndex = trimmed.indexOf('=');
if (eqIndex > 0) {
const key = trimmed.substring(0, eqIndex).trim();
let value = trimmed.substring(eqIndex + 1).trim();
if ((value.startsWith('"') && value.endsWith('"')) ||
(value.startsWith("'") && value.endsWith("'"))) {
value = value.slice(1, -1);
}
envVars[key] = value;
}
}
return envVars;
} catch {
return {};
}
}
/**
* Get or create the generator instance
*/
private getGenerator(): ChangelogGenerator {
if (!this.generator) {
const autoBuildSource = this.getAutoBuildSourcePath();
if (!autoBuildSource) {
throw new Error('Auto-build source path not found');
}
// Verify claude CLI is available
if (this.claudePath !== 'claude' && !existsSync(this.claudePath)) {
throw new Error(`Claude CLI not found. Please ensure Claude Code is installed. Looked for: ${this.claudePath}`);
}
const autoBuildEnv = this.loadAutoBuildEnv();
this.generator = new ChangelogGenerator(
this.pythonPath,
this.claudePath,
autoBuildSource,
autoBuildEnv,
this.isDebugEnabled()
);
// Forward events from generator
this.generator.on('generation-complete', (projectId, result) => {
this.emit('generation-complete', projectId, result);
});
this.generator.on('generation-progress', (projectId, progress) => {
this.emit('generation-progress', projectId, progress);
});
this.generator.on('generation-error', (projectId, error) => {
this.emit('generation-error', projectId, error);
});
this.generator.on('rate-limit', (projectId, rateLimitInfo) => {
this.emit('rate-limit', projectId, rateLimitInfo);
});
}
return this.generator;
}
/**
* Get or create the version suggester instance
*/
private getVersionSuggester(): VersionSuggester {
if (!this.versionSuggester) {
const autoBuildSource = this.getAutoBuildSourcePath();
if (!autoBuildSource) {
throw new Error('Auto-build source path not found');
}
// Verify claude CLI is available
if (this.claudePath !== 'claude' && !existsSync(this.claudePath)) {
throw new Error(`Claude CLI not found. Please ensure Claude Code is installed. Looked for: ${this.claudePath}`);
}
this.versionSuggester = new VersionSuggester(
this.pythonPath,
this.claudePath,
autoBuildSource,
this.isDebugEnabled()
);
}
return this.versionSuggester;
}
// ============================================
// Task Management
// ============================================
/**
* Get completed tasks from a project
*/
getCompletedTasks(projectPath: string, tasks: Task[], specsBaseDir?: string): ChangelogTask[] {
const specsDir = path.join(projectPath, specsBaseDir || AUTO_BUILD_PATHS.SPECS_DIR);
return tasks
.filter(task => task.status === 'done' && !task.metadata?.archivedAt)
.map(task => {
const specDir = path.join(specsDir, task.specId);
const hasSpecs = existsSync(specDir) && existsSync(path.join(specDir, AUTO_BUILD_PATHS.SPEC_FILE));
return {
id: task.id,
specId: task.specId,
title: task.title,
description: task.description,
completedAt: task.updatedAt,
hasSpecs
};
})
.sort((a, b) => new Date(b.completedAt).getTime() - new Date(a.completedAt).getTime());
}
/**
* Load spec files for given tasks
*/
async loadTaskSpecs(projectPath: string, taskIds: string[], tasks: Task[], specsBaseDir?: string): Promise<TaskSpecContent[]> {
const specsDir = path.join(projectPath, specsBaseDir || AUTO_BUILD_PATHS.SPECS_DIR);
this.debug('loadTaskSpecs called', { projectPath, specsDir, taskCount: taskIds.length });
const results: TaskSpecContent[] = [];
for (const taskId of taskIds) {
const task = tasks.find(t => t.id === taskId);
if (!task) {
this.debug('Task not found:', taskId);
continue;
}
const specDir = path.join(specsDir, task.specId);
this.debug('Loading spec for task', { taskId, specId: task.specId, specDir });
const content: TaskSpecContent = {
taskId,
specId: task.specId
};
try {
// Load spec.md
const specPath = path.join(specDir, AUTO_BUILD_PATHS.SPEC_FILE);
if (existsSync(specPath)) {
content.spec = readFileSync(specPath, 'utf-8');
this.debug('Loaded spec.md', { specId: task.specId, length: content.spec.length });
}
// Load requirements.json
const requirementsPath = path.join(specDir, AUTO_BUILD_PATHS.REQUIREMENTS);
if (existsSync(requirementsPath)) {
content.requirements = JSON.parse(readFileSync(requirementsPath, 'utf-8'));
}
// Load qa_report.md
const qaReportPath = path.join(specDir, AUTO_BUILD_PATHS.QA_REPORT);
if (existsSync(qaReportPath)) {
content.qaReport = readFileSync(qaReportPath, 'utf-8');
}
// Load implementation_plan.json
const planPath = path.join(specDir, AUTO_BUILD_PATHS.IMPLEMENTATION_PLAN);
if (existsSync(planPath)) {
content.implementationPlan = JSON.parse(readFileSync(planPath, 'utf-8')) as ImplementationPlan;
}
} catch (error) {
content.error = error instanceof Error ? error.message : 'Failed to load spec files';
this.debug('Error loading spec', { specId: task.specId, error: content.error });
}
results.push(content);
}
this.debug('loadTaskSpecs complete', { loadedCount: results.length });
return results;
}
// ============================================
// Git Data Retrieval
// ============================================
getBranches(projectPath: string): GitBranchInfo[] {
return getBranches(projectPath, this.isDebugEnabled());
}
getTags(projectPath: string): GitTagInfo[] {
return getTags(projectPath, this.isDebugEnabled());
}
getCurrentBranch(projectPath: string): string {
return getCurrentBranch(projectPath);
}
getDefaultBranch(projectPath: string): string {
return getDefaultBranch(projectPath);
}
getCommits(projectPath: string, options: import('../../shared/types').GitHistoryOptions): import('../../shared/types').GitCommit[] {
return getCommits(projectPath, options, this.isDebugEnabled());
}
getBranchDiffCommits(projectPath: string, options: import('../../shared/types').BranchDiffOptions): import('../../shared/types').GitCommit[] {
return getBranchDiffCommits(projectPath, options, this.isDebugEnabled());
}
// ============================================
// Changelog Generation
// ============================================
generateChangelog(
projectId: string,
projectPath: string,
request: ChangelogGenerationRequest,
specs?: TaskSpecContent[]
): void {
try {
const generator = this.getGenerator();
generator.generate(projectId, projectPath, request, specs);
} catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Failed to initialize generator';
this.debug('ERROR:', errorMessage);
this.emit('generation-error', projectId, errorMessage);
}
}
cancelGeneration(projectId: string): boolean {
if (this.generator) {
return this.generator.cancel(projectId);
}
return false;
}
// ============================================
// File Operations
// ============================================
/**
* Save changelog to file
*/
saveChangelog(
projectPath: string,
request: ChangelogSaveRequest
): ChangelogSaveResult {
const filePath = request.filePath
? path.join(projectPath, request.filePath)
: path.join(projectPath, DEFAULT_CHANGELOG_PATH);
let finalContent = request.content;
if (request.mode === 'prepend' && existsSync(filePath)) {
const existing = readFileSync(filePath, 'utf-8');
// Add separator between new and existing content
finalContent = `${request.content}\n\n${existing}`;
} else if (request.mode === 'append' && existsSync(filePath)) {
const existing = readFileSync(filePath, 'utf-8');
finalContent = `${existing}\n\n${request.content}`;
}
writeFileSync(filePath, finalContent, 'utf-8');
return {
filePath,
bytesWritten: Buffer.byteLength(finalContent, 'utf-8')
};
}
/**
* Read existing changelog file
*/
readExistingChangelog(projectPath: string): ExistingChangelog {
const filePath = path.join(projectPath, DEFAULT_CHANGELOG_PATH);
if (!existsSync(filePath)) {
return { exists: false };
}
return parseExistingChangelog(filePath);
}
/**
* Suggest next version based on task types (rule-based)
*/
suggestVersion(specs: TaskSpecContent[], currentVersion?: string): string {
// Default starting version
if (!currentVersion) {
return '1.0.0';
}
const parts = currentVersion.split('.').map(Number);
if (parts.length !== 3 || parts.some(isNaN)) {
return '1.0.0';
}
const [major, minor, patch] = parts;
// Analyze specs for version increment decision
let hasBreakingChanges = false;
let hasNewFeatures = false;
for (const spec of specs) {
const content = (spec.spec || '').toLowerCase();
if (content.includes('breaking change') || content.includes('breaking:')) {
hasBreakingChanges = true;
}
if (spec.implementationPlan?.workflow_type === 'new_feature' ||
content.includes('new feature') ||
content.includes('## added')) {
hasNewFeatures = true;
}
}
if (hasBreakingChanges) {
return `${major + 1}.0.0`;
} else if (hasNewFeatures) {
return `${major}.${minor + 1}.0`;
} else {
return `${major}.${minor}.${patch + 1}`;
}
}
/**
* Suggest version using AI analysis of git commits
*/
async suggestVersionFromCommits(
projectPath: string,
commits: import('../../shared/types').GitCommit[],
currentVersion?: string
): Promise<{ version: string; reason: string }> {
try {
// Default starting version
if (!currentVersion) {
return { version: '1.0.0', reason: 'Initial version' };
}
const parts = currentVersion.split('.').map(Number);
if (parts.length !== 3 || parts.some(isNaN)) {
return { version: '1.0.0', reason: 'Invalid current version, resetting to 1.0.0' };
}
// Use AI to analyze commits and suggest version bump
const suggester = this.getVersionSuggester();
const suggestion = await suggester.suggestVersionBump(commits, currentVersion);
this.debug('AI version suggestion', suggestion);
return {
version: suggestion.version,
reason: suggestion.reason
};
} catch (error) {
this.debug('Error in AI version suggestion, falling back to patch bump', error);
// Fallback to patch bump if AI fails
const [major, minor, patch] = (currentVersion || '1.0.0').split('.').map(Number);
return {
version: `${major}.${minor}.${patch + 1}`,
reason: 'Patch version bump (AI analysis failed)'
};
}
}
}
// Export singleton instance
export const changelogService = new ChangelogService();
@@ -0,0 +1,350 @@
import type {
ChangelogGenerationRequest,
TaskSpecContent,
GitCommit
} from '../../shared/types';
import { extractSpecOverview } from './parser';
/**
* Format instructions for different changelog styles
*/
const FORMAT_TEMPLATES = {
'keep-a-changelog': (version: string, date: string) => `## [${version}] - ${date}
### Added
- [New features]
### Changed
- [Modifications]
### Fixed
- [Bug fixes]`,
'simple-list': (version: string, date: string) => `# Release v${version} (${date})
**New Features:**
- [List features]
**Improvements:**
- [List improvements]
**Bug Fixes:**
- [List fixes]`,
'github-release': (version: string, date: string) => `## ${version} - ${date}
### New Features
- Feature description
### Improvements
- Improvement description
### Bug Fixes
- Fix description
---
## What's Changed
- type: description by @contributor in commit-hash`
};
/**
* Audience-specific writing instructions
*/
const AUDIENCE_INSTRUCTIONS = {
'technical': 'You are a technical documentation specialist creating a changelog for developers. Use precise technical language.',
'user-facing': 'You are a product manager writing release notes for end users. Use clear, non-technical language focusing on user benefits.',
'marketing': 'You are a marketing specialist writing release notes. Focus on outcomes and user impact with compelling language.'
};
/**
* Get emoji usage instructions based on level and format
*/
function getEmojiInstructions(emojiLevel?: string, format?: string): string {
if (!emojiLevel || emojiLevel === 'none') {
return '';
}
// GitHub Release format uses specific emoji style matching Gemini CLI pattern
if (format === 'github-release') {
const githubInstructions: Record<string, string> = {
'little': `Add emojis ONLY to section headings. Use these specific emoji-heading pairs:
- "### ✨ New Features"
- "### 🛠️ Improvements"
- "### 🐛 Bug Fixes"
- "### 📚 Documentation"
- "### 🔧 Other Changes"
Do NOT add emojis to individual line items.`,
'medium': `Add emojis to section headings AND to notable/important items only.
Section headings MUST use these specific emoji-heading pairs:
- "### ✨ New Features"
- "### 🛠️ Improvements"
- "### 🐛 Bug Fixes"
- "### 📚 Documentation"
- "### 🔧 Other Changes"
Add emojis to 2-3 highlighted items per section that are particularly significant.`,
'high': `Add emojis to section headings AND every line item.
Section headings MUST use these specific emoji-heading pairs:
- "### ✨ New Features"
- "### 🛠️ Improvements"
- "### 🐛 Bug Fixes"
- "### 📚 Documentation"
- "### 🔧 Other Changes"
Every line item should start with a contextual emoji.`
};
return githubInstructions[emojiLevel] || '';
}
// Default instructions for other formats
const instructions: Record<string, string> = {
'little': `Add emojis ONLY to section headings. Each heading should have one contextual emoji at the start.
Examples:
- "### ✨ New Features" or "### 🚀 New Features"
- "### 🐛 Bug Fixes"
- "### 🔧 Improvements" or "### ⚡ Improvements"
- "### 📚 Documentation"
Do NOT add emojis to individual line items.`,
'medium': `Add emojis to section headings AND to notable/important items only.
Section headings should have one emoji (e.g., "### ✨ New Features", "### 🐛 Bug Fixes").
Add emojis to 2-3 highlighted items per section that are particularly significant.
Examples of highlighted items:
- "- 🎉 **Major Feature**: Description"
- "- 🔒 **Security Fix**: Description"
Most regular line items should NOT have emojis.`,
'high': `Add emojis to section headings AND every line item for maximum visual appeal.
Section headings: "### ✨ New Features", "### 🐛 Bug Fixes", "### ⚡ Improvements"
Every line item should start with a contextual emoji:
- "- ✨ Added new feature..."
- "- 🐛 Fixed bug where..."
- "- 🔧 Improved performance of..."
- "- 📝 Updated documentation for..."
- "- 🎨 Refined UI styling..."
Use diverse, contextually appropriate emojis for each item.`
};
return instructions[emojiLevel] || '';
}
/**
* Build changelog prompt from task specs
*/
export function buildChangelogPrompt(
request: ChangelogGenerationRequest,
specs: TaskSpecContent[]
): string {
const audienceInstruction = AUDIENCE_INSTRUCTIONS[request.audience];
const formatInstruction = FORMAT_TEMPLATES[request.format](request.version, request.date);
const emojiInstruction = getEmojiInstructions(request.emojiLevel, request.format);
// Build CONCISE task summaries (key to avoiding timeout)
const taskSummaries = specs.map(spec => {
const parts: string[] = [`- **${spec.specId}**`];
// Get workflow type if available
if (spec.implementationPlan?.workflow_type) {
parts.push(`(${spec.implementationPlan.workflow_type})`);
}
// Extract just the overview/purpose
if (spec.spec) {
const overview = extractSpecOverview(spec.spec);
if (overview) {
parts.push(`: ${overview}`);
}
}
return parts.join('');
}).join('\n');
// Format-specific instructions for tasks mode
let formatSpecificInstructions = '';
if (request.format === 'github-release') {
formatSpecificInstructions = `
For GitHub Release format:
RELEASE TITLE (CRITICAL):
- First, analyze all completed tasks to identify the main theme or focus of this release
- Create a concise, descriptive title (2-5 words) that captures what this release is about
- Examples of good titles:
* "Improved Terminal Experience" (for terminal-related improvements)
* "Enhanced Security Features" (for security updates)
* "UI/UX Refinements" (for interface changes)
* "Agent Performance Boost" (for performance improvements)
- The version header MUST be: "## ${request.version} - [Your Thematic Title]"
- Focus on the USER BENEFIT or FUNCTIONAL AREA, not technical implementation details
- The title should be what the release is "about" in layman's terms
`;
}
return `${audienceInstruction}
Format:
${formatInstruction}
${emojiInstruction ? `\nEmoji Usage:\n${emojiInstruction}` : ''}
${formatSpecificInstructions}
Completed tasks:
${taskSummaries}
${request.customInstructions ? `Note: ${request.customInstructions}` : ''}
CRITICAL: Output ONLY the raw changelog content. Do NOT include ANY introductory text, analysis, or explanation. Start directly with the changelog heading (## or #). No "Here's the changelog" or similar phrases.`;
}
/**
* Build changelog prompt from git commits
*/
export function buildGitPrompt(
request: ChangelogGenerationRequest,
commits: GitCommit[]
): string {
const audienceInstruction = AUDIENCE_INSTRUCTIONS[request.audience];
const formatInstruction = FORMAT_TEMPLATES[request.format](request.version, request.date);
const emojiInstruction = getEmojiInstructions(request.emojiLevel, request.format);
// Format commits for the prompt
// Include author info for github-release format
const commitLines = commits.map(commit => {
const hash = commit.hash;
const subject = commit.subject;
const author = commit.author;
// Detect conventional commit format: type(scope): message
const conventionalMatch = subject.match(/^(\w+)(?:\(([^)]+)\))?:\s*(.+)$/);
if (conventionalMatch) {
const [, type, scope, message] = conventionalMatch;
return `- ${hash} | ${type}${scope ? `(${scope})` : ''}: ${message} | by ${author}`;
}
return `- ${hash} | ${subject} | by ${author}`;
}).join('\n');
// Add context about branch/range if available
let sourceContext = '';
if (request.branchDiff) {
sourceContext = `These commits are from branch "${request.branchDiff.compareBranch}" that are not in "${request.branchDiff.baseBranch}".`;
} else if (request.gitHistory) {
switch (request.gitHistory.type) {
case 'recent':
sourceContext = `These are the ${commits.length} most recent commits.`;
break;
case 'since-date':
sourceContext = `These are commits since ${request.gitHistory.sinceDate}.`;
break;
case 'tag-range':
sourceContext = `These are commits between tag "${request.gitHistory.fromTag}" and "${request.gitHistory.toTag || 'HEAD'}".`;
break;
}
}
// Format-specific instructions
let formatSpecificInstructions = '';
if (request.format === 'github-release') {
formatSpecificInstructions = `
For GitHub Release format, you MUST follow this structure:
RELEASE TITLE (CRITICAL):
- First, analyze all commits to identify the main theme or focus of this release
- Create a concise, descriptive title (2-5 words) that captures what this release is about
- Examples of good titles:
* "Improved Terminal Experience" (for terminal-related improvements)
* "Enhanced Security Features" (for security updates)
* "Performance Optimizations" (for speed improvements)
* "UI/UX Refinements" (for interface changes)
* "Agent System Overhaul" (for major architectural changes)
* "Build Pipeline Enhancements" (for CI/CD improvements)
- The version header MUST be: "## ${request.version} - [Your Thematic Title]"
- Focus on the USER BENEFIT or FUNCTIONAL AREA, not technical implementation details
- The title should be what the release is "about" in layman's terms
PART 1 - Categorized changes (summarized):
- Use category sections: New Features, Improvements, Bug Fixes, Documentation, Other Changes
- ONLY include sections that have actual changes - skip empty sections entirely
- Add a blank line between each bullet point for cleaner formatting
- Summarize and group related commits into clear, readable descriptions
- Do NOT include commit hashes in this section
PART 2 - "What's Changed" (raw commit list):
- Add a horizontal rule (---) before this section
- List each commit in format: "- type: description by @author in hash"
- Example: "- fix: upgrade react to 19.2.3 by @douxc in abc1234"
- Example: "- feat: add dark mode support by @contributor in def5678"
- Include the commit type prefix (feat:, fix:, docs:, etc.)
- Show the author name with @ prefix
- Show the short commit hash at the end`;
}
return `${audienceInstruction}
${sourceContext}
Generate a changelog from these git commits. Group related changes together and categorize them appropriately.
Conventional commit types to recognize:
- feat/feature: New features New Features section
- fix/bugfix: Bug fixes Bug Fixes section
- docs: Documentation Documentation section
- style/refactor/perf: Improvements Improvements section
- chore/build/ci: Other changes Other Changes section (usually omit unless significant)
- test: Tests (usually omit unless significant)
${formatSpecificInstructions}
Format:
${formatInstruction}
${emojiInstruction ? `\nEmoji Usage:\n${emojiInstruction}` : ''}
Git commits (${commits.length} total):
${commitLines}
${request.customInstructions ? `Note: ${request.customInstructions}` : ''}
CRITICAL: Output ONLY the raw changelog content. Do NOT include ANY introductory text, analysis, or explanation. Start directly with the changelog heading (## or #). No "Here's the changelog" or similar phrases. Intelligently group and summarize related commits - don't just list each commit individually. Only include sections that have actual changes.`;
}
/**
* Create Python script for Claude generation
*/
export function createGenerationScript(prompt: string, claudePath: string): string {
// Convert prompt to base64 to avoid any string escaping issues in Python
const base64Prompt = Buffer.from(prompt, 'utf-8').toString('base64');
// Escape the claude path for Python string
const escapedClaudePath = claudePath.replace(/\\/g, '\\\\').replace(/'/g, "\\'");
return `
import subprocess
import sys
import base64
try:
# Decode the base64 prompt to avoid string escaping issues
prompt = base64.b64decode('${base64Prompt}').decode('utf-8')
# Use Claude Code CLI to generate
# stdin=DEVNULL prevents hanging when claude checks for interactive input
result = subprocess.run(
['${escapedClaudePath}', '-p', prompt, '--output-format', 'text', '--model', 'haiku'],
capture_output=True,
text=True,
stdin=subprocess.DEVNULL,
timeout=300
)
if result.returncode == 0:
print(result.stdout)
else:
# Print more detailed error info
print(f"Claude CLI error (code {result.returncode}):", file=sys.stderr)
if result.stderr:
print(result.stderr, file=sys.stderr)
if result.stdout:
print(f"stdout: {result.stdout}", file=sys.stderr)
sys.exit(1)
except Exception as e:
print(f"Python error: {type(e).__name__}: {e}", file=sys.stderr)
sys.exit(1)
`;
}
@@ -0,0 +1,327 @@
import { EventEmitter } from 'events';
import { spawn } from 'child_process';
import * as path from 'path';
import * as os from 'os';
import type {
ChangelogGenerationRequest,
ChangelogGenerationResult,
ChangelogGenerationProgress,
TaskSpecContent
} from '../../shared/types';
import { buildChangelogPrompt, buildGitPrompt, createGenerationScript } from './formatter';
import { extractChangelog } from './parser';
import { getCommits, getBranchDiffCommits } from './git-integration';
import { detectRateLimit, createSDKRateLimitInfo, getProfileEnv } from '../rate-limit-detector';
/**
* Core changelog generation logic
* Handles AI generation via Claude CLI subprocess
*/
export class ChangelogGenerator extends EventEmitter {
private generationProcesses: Map<string, ReturnType<typeof spawn>> = new Map();
private debugEnabled: boolean;
constructor(
private pythonPath: string,
private claudePath: string,
private autoBuildSourcePath: string,
private autoBuildEnv: Record<string, string>,
debugEnabled: boolean
) {
super();
this.debugEnabled = debugEnabled;
}
private debug(...args: unknown[]): void {
if (this.debugEnabled) {
console.warn('[ChangelogGenerator]', ...args);
}
}
/**
* Generate changelog using Claude AI
* Supports multiple source modes: tasks (specs), git-history, or branch-diff
*/
async generate(
projectId: string,
projectPath: string,
request: ChangelogGenerationRequest,
specs?: TaskSpecContent[]
): Promise<void> {
const sourceMode = request.sourceMode || 'tasks';
this.debug('generate called', {
projectId,
projectPath,
sourceMode,
taskCount: request.taskIds?.length || 0,
version: request.version,
format: request.format,
audience: request.audience
});
// Kill existing process if any
this.cancel(projectId);
let prompt: string;
let itemCount: number;
// Handle different source modes
if (sourceMode === 'git-history' && request.gitHistory) {
// Git history mode
this.emitProgress(projectId, {
stage: 'loading_commits',
progress: 10,
message: 'Loading commits from git history...'
});
const commits = getCommits(projectPath, request.gitHistory, this.debugEnabled);
if (commits.length === 0) {
this.emitError(projectId, 'No commits found for the specified range');
return;
}
prompt = buildGitPrompt(request, commits);
itemCount = commits.length;
} else if (sourceMode === 'branch-diff' && request.branchDiff) {
// Branch diff mode
this.emitProgress(projectId, {
stage: 'loading_commits',
progress: 10,
message: `Loading commits between ${request.branchDiff.baseBranch} and ${request.branchDiff.compareBranch}...`
});
const commits = getBranchDiffCommits(projectPath, request.branchDiff, this.debugEnabled);
if (commits.length === 0) {
this.emitError(projectId, 'No commits found between the specified branches');
return;
}
prompt = buildGitPrompt(request, commits);
itemCount = commits.length;
} else {
// Tasks mode (original behavior)
if (!specs || specs.length === 0) {
this.emitError(projectId, 'No specs provided for changelog generation');
return;
}
this.emitProgress(projectId, {
stage: 'loading_specs',
progress: 10,
message: 'Preparing changelog generation...'
});
prompt = buildChangelogPrompt(request, specs);
itemCount = specs.length;
}
this.debug('Prompt built', {
promptLength: prompt.length,
promptPreview: prompt.substring(0, 500) + '...'
});
// Create Python script
const script = createGenerationScript(prompt, this.claudePath);
this.debug('Python script created', { scriptLength: script.length });
this.emitProgress(projectId, {
stage: 'generating',
progress: 30,
message: 'Generating changelog with Claude AI...'
});
const startTime = Date.now();
this.debug('Spawning Python process...');
// Build environment with explicit critical variables
const spawnEnv = this.buildSpawnEnvironment();
const childProcess = spawn(this.pythonPath, ['-c', script], {
cwd: this.autoBuildSourcePath,
env: spawnEnv
});
this.generationProcesses.set(projectId, childProcess);
this.debug('Process spawned with PID:', childProcess.pid);
let output = '';
let errorOutput = '';
childProcess.stdout?.on('data', (data: Buffer) => {
const chunk = data.toString();
output += chunk;
this.debug('stdout chunk received', { chunkLength: chunk.length, totalOutput: output.length });
this.emitProgress(projectId, {
stage: 'generating',
progress: 50,
message: 'Generating changelog content...'
});
});
childProcess.stderr?.on('data', (data: Buffer) => {
const chunk = data.toString();
errorOutput += chunk;
this.debug('stderr chunk received', { chunk: chunk.substring(0, 200) });
});
childProcess.on('exit', (code: number | null) => {
const duration = Date.now() - startTime;
this.debug('Process exited', {
code,
duration: `${duration}ms`,
outputLength: output.length,
errorLength: errorOutput.length
});
this.generationProcesses.delete(projectId);
if (code === 0 && output.trim()) {
this.emitProgress(projectId, {
stage: 'formatting',
progress: 90,
message: 'Formatting changelog...'
});
// Extract changelog from output
const changelog = extractChangelog(output.trim());
this.debug('Changelog extracted', { changelogLength: changelog.length });
this.emitProgress(projectId, {
stage: 'complete',
progress: 100,
message: 'Changelog generation complete'
});
const result: ChangelogGenerationResult = {
success: true,
changelog,
version: request.version,
tasksIncluded: itemCount
};
this.debug('Generation complete, emitting result');
this.emit('generation-complete', projectId, result);
} else {
// Combine all output for error analysis
const combinedOutput = `${output}\n${errorOutput}`;
const error = errorOutput || `Generation failed with exit code ${code}`;
// Check for rate limit
const rateLimitDetection = detectRateLimit(combinedOutput);
if (rateLimitDetection.isRateLimited) {
this.debug('Rate limit detected in changelog generation', {
resetTime: rateLimitDetection.resetTime,
limitType: rateLimitDetection.limitType,
suggestedProfile: rateLimitDetection.suggestedProfile?.name
});
// Emit rate limit event
const rateLimitInfo = createSDKRateLimitInfo('changelog', rateLimitDetection, { projectId });
this.emit('rate-limit', projectId, rateLimitInfo);
}
this.debug('Generation failed', { error: error.substring(0, 500), isRateLimited: rateLimitDetection.isRateLimited });
this.emitError(projectId, error);
}
});
childProcess.on('error', (err: Error) => {
this.debug('Process error', { error: err.message });
this.generationProcesses.delete(projectId);
this.emitError(projectId, err.message);
});
}
/**
* Build spawn environment with proper PATH and auth settings
*/
private buildSpawnEnvironment(): Record<string, string> {
const homeDir = os.homedir();
const isWindows = process.platform === 'win32';
// Build PATH with platform-appropriate separator and locations
const pathAdditions = isWindows
? [
path.join(homeDir, 'AppData', 'Local', 'Programs', 'claude'),
path.join(homeDir, 'AppData', 'Roaming', 'npm'),
path.join(homeDir, '.local', 'bin'),
'C:\\Program Files\\Claude',
'C:\\Program Files (x86)\\Claude'
]
: [
'/usr/local/bin',
'/opt/homebrew/bin',
path.join(homeDir, '.local', 'bin'),
path.join(homeDir, 'bin')
];
// Get active Claude profile environment (OAuth token preferred, falls back to CLAUDE_CONFIG_DIR)
const profileEnv = getProfileEnv();
this.debug('Active profile environment', {
hasOAuthToken: !!profileEnv.CLAUDE_CODE_OAUTH_TOKEN,
hasConfigDir: !!profileEnv.CLAUDE_CONFIG_DIR,
authMethod: profileEnv.CLAUDE_CODE_OAUTH_TOKEN ? 'oauth-token' : (profileEnv.CLAUDE_CONFIG_DIR ? 'config-dir' : 'default')
});
const spawnEnv: Record<string, string> = {
...process.env as Record<string, string>,
...this.autoBuildEnv,
...profileEnv, // Include active Claude profile config
// Ensure critical env vars are set for claude CLI
// Use USERPROFILE on Windows, HOME on Unix
...(isWindows ? { USERPROFILE: homeDir } : { HOME: homeDir }),
USER: process.env.USER || process.env.USERNAME || 'user',
// Add common binary locations to PATH for claude CLI
PATH: [process.env.PATH || '', ...pathAdditions].filter(Boolean).join(path.delimiter),
PYTHONUNBUFFERED: '1',
PYTHONIOENCODING: 'utf-8',
PYTHONUTF8: '1'
};
this.debug('Spawn environment', {
HOME: spawnEnv.HOME,
USER: spawnEnv.USER,
pathDirs: spawnEnv.PATH?.split(':').length,
authMethod: spawnEnv.CLAUDE_CODE_OAUTH_TOKEN ? 'oauth-token' : (spawnEnv.CLAUDE_CONFIG_DIR ? `config-dir:${spawnEnv.CLAUDE_CONFIG_DIR}` : 'default')
});
return spawnEnv;
}
/**
* Cancel ongoing generation
*/
cancel(projectId: string): boolean {
const process = this.generationProcesses.get(projectId);
if (process) {
process.kill('SIGTERM');
this.generationProcesses.delete(projectId);
return true;
}
return false;
}
/**
* Emit progress update
*/
private emitProgress(projectId: string, progress: ChangelogGenerationProgress): void {
this.emit('generation-progress', projectId, progress);
}
/**
* Emit error
*/
private emitError(projectId: string, error: string): void {
this.emit('generation-progress', projectId, {
stage: 'error',
progress: 0,
message: error,
error
});
this.emit('generation-error', projectId, error);
}
}
@@ -0,0 +1,253 @@
import { execSync } from 'child_process';
import type {
GitBranchInfo,
GitTagInfo,
GitCommit,
GitHistoryOptions,
BranchDiffOptions
} from '../../shared/types';
import { parseGitLogOutput } from './parser';
/**
* Debug logging helper
*/
function debug(enabled: boolean, ...args: unknown[]): void {
if (enabled) {
console.warn('[GitIntegration]', ...args);
}
}
/**
* Get list of branches for changelog git mode
*/
export function getBranches(projectPath: string, debugEnabled = false): GitBranchInfo[] {
try {
// Get current branch
let currentBranch = '';
try {
currentBranch = execSync('git rev-parse --abbrev-ref HEAD', {
cwd: projectPath,
encoding: 'utf-8'
}).trim();
} catch {
// Ignore - might be in detached HEAD
}
// Get all branches (local and remote)
const output = execSync('git branch -a --format="%(refname:short)|%(HEAD)"', {
cwd: projectPath,
encoding: 'utf-8'
});
const branches: GitBranchInfo[] = [];
const seenNames = new Set<string>();
// Handle both Unix (\n) and Windows (\r\n) line endings
for (const line of output.split(/\r?\n/)) {
const trimmed = line.trim();
if (!trimmed) continue;
const [name, head] = trimmed.split('|');
if (!name) continue;
// Skip HEAD references
if (name === 'HEAD' || name.includes('HEAD')) continue;
// Parse remote branches (origin/xxx) and mark as remote
const isRemote = name.startsWith('origin/') || name.includes('/');
const displayName = isRemote ? name.replace(/^origin\//, '') : name;
// Skip duplicates (prefer local over remote)
if (seenNames.has(displayName) && isRemote) continue;
seenNames.add(displayName);
branches.push({
name: displayName,
isRemote,
isCurrent: head === '*' || displayName === currentBranch
});
}
// Sort: current first, then local branches, then remote
return branches.sort((a, b) => {
if (a.isCurrent && !b.isCurrent) return -1;
if (!a.isCurrent && b.isCurrent) return 1;
if (!a.isRemote && b.isRemote) return -1;
if (a.isRemote && !b.isRemote) return 1;
return a.name.localeCompare(b.name);
});
} catch (error) {
debug(debugEnabled, 'Error getting branches:', error);
return [];
}
}
/**
* Get list of tags for changelog git mode
*/
export function getTags(projectPath: string, debugEnabled = false): GitTagInfo[] {
try {
// Get tags sorted by creation date (newest first)
const output = execSync(
'git tag -l --sort=-creatordate --format="%(refname:short)|%(creatordate:iso-strict)|%(objectname:short)"',
{
cwd: projectPath,
encoding: 'utf-8'
}
);
const tags: GitTagInfo[] = [];
// Handle both Unix (\n) and Windows (\r\n) line endings
for (const line of output.split(/\r?\n/)) {
const trimmed = line.trim();
if (!trimmed) continue;
const parts = trimmed.split('|');
const name = parts[0];
const date = parts[1] || undefined;
const commit = parts[2] || undefined;
if (name) {
tags.push({ name, date, commit });
}
}
return tags;
} catch (error) {
debug(debugEnabled, 'Error getting tags:', error);
return [];
}
}
/**
* Get current branch name
*/
export function getCurrentBranch(projectPath: string): string {
try {
return execSync('git rev-parse --abbrev-ref HEAD', {
cwd: projectPath,
encoding: 'utf-8'
}).trim();
} catch {
return 'main';
}
}
/**
* Get the default/main branch name
*/
export function getDefaultBranch(projectPath: string): string {
try {
// Try to get from origin/HEAD
const result = execSync('git rev-parse --abbrev-ref origin/HEAD', {
cwd: projectPath,
encoding: 'utf-8'
}).trim();
return result.replace('origin/', '');
} catch {
// Fallback: check if main or master exists
try {
execSync('git rev-parse --verify main', {
cwd: projectPath,
encoding: 'utf-8'
});
return 'main';
} catch {
try {
execSync('git rev-parse --verify master', {
cwd: projectPath,
encoding: 'utf-8'
});
return 'master';
} catch {
return 'main';
}
}
}
}
/**
* Get commits for git-history mode
*/
export function getCommits(
projectPath: string,
options: GitHistoryOptions,
debugEnabled = false
): GitCommit[] {
try {
// Build the git log command based on options
const format = '%h|%H|%s|%an|%ae|%aI';
let command = `git log --pretty=format:"${format}"`;
// Add merge commit handling
if (!options.includeMergeCommits) {
command += ' --no-merges';
}
// Add range/filters based on type
switch (options.type) {
case 'recent':
command += ` -n ${options.count || 25}`;
break;
case 'since-date':
if (options.sinceDate) {
command += ` --since="${options.sinceDate}"`;
}
break;
case 'tag-range':
if (options.fromTag) {
const toRef = options.toTag || 'HEAD';
command += ` ${options.fromTag}..${toRef}`;
}
break;
case 'since-version':
// Get all commits since the specified version/tag up to HEAD
if (options.fromTag) {
command += ` ${options.fromTag}..HEAD`;
}
break;
}
debug(debugEnabled, 'Getting commits with command:', command);
const output = execSync(command, {
cwd: projectPath,
encoding: 'utf-8',
maxBuffer: 10 * 1024 * 1024 // 10MB buffer for large histories
});
return parseGitLogOutput(output);
} catch (error) {
debug(debugEnabled, 'Error getting commits:', error);
return [];
}
}
/**
* Get commits between two branches (for branch-diff mode)
*/
export function getBranchDiffCommits(
projectPath: string,
options: BranchDiffOptions,
debugEnabled = false
): GitCommit[] {
try {
const format = '%h|%H|%s|%an|%ae|%aI';
// Get commits in compareBranch that are not in baseBranch
const command = `git log --pretty=format:"${format}" --no-merges ${options.baseBranch}..${options.compareBranch}`;
debug(debugEnabled, 'Getting branch diff commits with command:', command);
const output = execSync(command, {
cwd: projectPath,
encoding: 'utf-8',
maxBuffer: 10 * 1024 * 1024
});
return parseGitLogOutput(output);
} catch (error) {
debug(debugEnabled, 'Error getting branch diff commits:', error);
return [];
}
}
@@ -0,0 +1,20 @@
/**
* Changelog module - clean exports
*
* Architecture:
* - changelog-service.ts: Main service facade (orchestrates all operations)
* - generator.ts: AI-powered changelog generation
* - version-suggester.ts: AI-powered version bump suggestions
* - parser.ts: Changelog and spec parsing logic
* - formatter.ts: Prompt building and formatting
* - git-integration.ts: Git operations (branches, tags, commits)
* - types.ts: Module-specific types
*/
export { ChangelogService, changelogService } from './changelog-service';
export { ChangelogGenerator } from './generator';
export { VersionSuggester } from './version-suggester';
export * from './parser';
export * from './formatter';
export * from './git-integration';
export * from './types';
+166
View File
@@ -0,0 +1,166 @@
import { readFileSync } from 'fs';
import type { ExistingChangelog } from '../../shared/types';
/**
* Extract the overview section from a spec (typically the first meaningful section)
*/
export function extractSpecOverview(spec: string): string {
// Split into lines and find the Overview section
// Handle both Unix (\n) and Windows (\r\n) line endings
const lines = spec.split(/\r?\n/);
let inOverview = false;
const overview: string[] = [];
for (const line of lines) {
// Start capturing at Overview heading
if (/^##\s*Overview/i.test(line)) {
inOverview = true;
continue;
}
// Stop at next major heading
if (inOverview && /^##\s/.test(line)) {
break;
}
if (inOverview && line.trim()) {
overview.push(line);
}
}
// If no overview found, take first paragraph after title
if (overview.length === 0) {
const paragraphs = spec.split(/\n\n+/).filter(p => !p.startsWith('#') && p.trim().length > 20);
if (paragraphs.length > 0) {
return paragraphs[0].substring(0, 300);
}
}
return overview.join(' ').substring(0, 400);
}
/**
* Extract changelog content from Claude output
* Removes AI preambles and finds the actual changelog content
*/
export function extractChangelog(output: string): string {
// Claude output should be the changelog directly
// Clean up any potential wrapper text
let changelog = output.trim();
// Find where the actual changelog starts (look for markdown heading)
// This handles cases where AI includes preamble like "I'll analyze..." or "Here's the changelog:"
const changelogStartPatterns = [
/^(##\s*\[[\d.]+\])/m, // Keep-a-changelog: ## [1.0.0]
/^(##\s*What['']?s\s+New)/im, // GitHub release: ## What's New
/^(#\s*Release\s+v?[\d.]+)/im, // Simple: # Release v1.0.0
/^(#\s*Changelog)/im, // # Changelog
/^(##\s*v?[\d.]+)/m // ## v1.0.0 or ## 1.0.0
];
for (const pattern of changelogStartPatterns) {
const match = changelog.match(pattern);
if (match && match.index !== undefined) {
// Found a changelog heading - extract from there
changelog = changelog.substring(match.index);
break;
}
}
// Additional cleanup - remove common AI preambles if they somehow remain
const prefixes = [
/^I['']ll\s+analyze[^#]*(?=#)/is,
/^I['']ll\s+generate[^#]*(?=#)/is,
/^Here['']s the changelog[:\s]*/i,
/^The changelog[:\s]*/i,
/^Changelog[:\s]*/i,
/^Based on[^#]*(?=#)/is,
/^Let me[^#]*(?=#)/is
];
for (const prefix of prefixes) {
changelog = changelog.replace(prefix, '');
}
return changelog.trim();
}
/**
* Parse existing changelog file and extract metadata
*/
export function parseExistingChangelog(filePath: string): ExistingChangelog {
try {
const content = readFileSync(filePath, 'utf-8');
// Try to extract last version using common patterns
const versionPatterns = [
/##\s*\[(\d+\.\d+\.\d+)\]/, // Keep-a-changelog format
/v(\d+\.\d+\.\d+)/, // v1.2.3 format
/Version\s+(\d+\.\d+\.\d+)/i // Version 1.2.3 format
];
let lastVersion: string | undefined;
for (const pattern of versionPatterns) {
const match = content.match(pattern);
if (match) {
lastVersion = match[1];
break;
}
}
return {
exists: true,
content,
lastVersion
};
} catch (error) {
return {
exists: true,
error: error instanceof Error ? error.message : 'Failed to read changelog'
};
}
}
/**
* Parse git log output into GitCommit objects
*/
export function parseGitLogOutput(output: string): Array<{
hash: string;
fullHash: string;
subject: string;
body?: string;
author: string;
authorEmail: string;
date: string;
}> {
const commits: Array<{
hash: string;
fullHash: string;
subject: string;
body?: string;
author: string;
authorEmail: string;
date: string;
}> = [];
// Handle both Unix (\n) and Windows (\r\n) line endings
for (const line of output.split(/\r?\n/)) {
const trimmed = line.trim();
if (!trimmed) continue;
const parts = trimmed.split('|');
if (parts.length < 6) continue;
const [hash, fullHash, subject, author, authorEmail, date] = parts;
commits.push({
hash,
fullHash,
subject,
body: undefined, // We don't fetch body for performance
author,
authorEmail,
date
});
}
return commits;
}
@@ -0,0 +1,30 @@
/**
* Changelog-specific types
* These types extend the base types from shared/types.ts
*/
export interface ChangelogConfig {
pythonPath: string;
claudePath: string;
autoBuildSourcePath: string;
}
export interface PromptBuildOptions {
version: string;
date: string;
audience: 'technical' | 'user-facing' | 'marketing';
format: 'keep-a-changelog' | 'simple-list' | 'github-release';
customInstructions?: string;
}
export interface VersionSuggestion {
suggested: string;
reason: string;
hasBreakingChanges: boolean;
hasNewFeatures: boolean;
}
export interface GenerationScriptParams {
prompt: string;
claudePath: string;
}
@@ -0,0 +1,247 @@
import { spawn } from 'child_process';
import * as path from 'path';
import * as os from 'os';
import type { GitCommit } from '../../shared/types';
import { getProfileEnv } from '../rate-limit-detector';
interface VersionSuggestion {
version: string;
reason: string;
bumpType: 'major' | 'minor' | 'patch';
}
/**
* AI-powered version bump suggester using Claude SDK with haiku model
* Analyzes commits to intelligently suggest semantic version bumps
*/
export class VersionSuggester {
private debugEnabled: boolean;
constructor(
private pythonPath: string,
private claudePath: string,
private autoBuildSourcePath: string,
debugEnabled: boolean
) {
this.debugEnabled = debugEnabled;
}
private debug(...args: unknown[]): void {
if (this.debugEnabled) {
console.warn('[VersionSuggester]', ...args);
}
}
/**
* Suggest version bump using AI analysis of commits
*/
async suggestVersionBump(
commits: GitCommit[],
currentVersion: string
): Promise<VersionSuggestion> {
this.debug('suggestVersionBump called', {
commitCount: commits.length,
currentVersion
});
// Build prompt for Claude to analyze commits
const prompt = this.buildPrompt(commits, currentVersion);
const script = this.createAnalysisScript(prompt);
// Build environment
const spawnEnv = this.buildSpawnEnvironment();
return new Promise((resolve, _reject) => {
const childProcess = spawn(this.pythonPath, ['-c', script], {
cwd: this.autoBuildSourcePath,
env: spawnEnv
});
let output = '';
let errorOutput = '';
childProcess.stdout?.on('data', (data: Buffer) => {
output += data.toString();
});
childProcess.stderr?.on('data', (data: Buffer) => {
errorOutput += data.toString();
});
childProcess.on('exit', (code: number | null) => {
if (code === 0 && output.trim()) {
try {
const result = this.parseAIResponse(output.trim(), currentVersion);
this.debug('AI suggestion parsed', result);
resolve(result);
} catch (error) {
this.debug('Failed to parse AI response', error);
// Fallback to simple bump
resolve(this.fallbackSuggestion(currentVersion));
}
} else {
this.debug('AI analysis failed', { code, error: errorOutput });
// Fallback to simple bump
resolve(this.fallbackSuggestion(currentVersion));
}
});
childProcess.on('error', (err: Error) => {
this.debug('Process error', err);
resolve(this.fallbackSuggestion(currentVersion));
});
});
}
/**
* Build prompt for Claude to analyze commits and suggest version bump
*/
private buildPrompt(commits: GitCommit[], currentVersion: string): string {
const commitSummary = commits
.map((c, i) => `${i + 1}. ${c.hash} - ${c.subject}`)
.join('\n');
return `You are a semantic versioning expert analyzing git commits to suggest the appropriate version bump.
Current version: ${currentVersion}
Analyze these ${commits.length} commits and determine the appropriate semantic version bump:
${commitSummary}
Consider:
- MAJOR (X.0.0): Breaking changes, API changes, removed features, architectural changes
- MINOR (0.X.0): New features, enhancements, additions that maintain backward compatibility
- PATCH (0.0.X): Bug fixes, small tweaks, documentation updates, refactoring without new features
Respond with ONLY a JSON object in this exact format (no markdown, no extra text):
{
"bumpType": "major|minor|patch",
"reason": "Brief explanation of the decision"
}`;
}
/**
* Create Python script to run Claude analysis
*/
private createAnalysisScript(prompt: string): string {
// Escape the prompt for Python string literal
const escapedPrompt = prompt
.replace(/\\/g, '\\\\')
.replace(/"/g, '\\"')
.replace(/\n/g, '\\n');
return `
import subprocess
import sys
# Use haiku model for fast, cost-effective analysis
prompt = "${escapedPrompt}"
try:
result = subprocess.run(
["${this.claudePath}", "chat", "--model", "haiku", "--prompt", prompt],
capture_output=True,
text=True,
check=True
)
print(result.stdout)
except subprocess.CalledProcessError as e:
print(f"Error: {e.stderr}", file=sys.stderr)
sys.exit(1)
except Exception as e:
print(f"Error: {str(e)}", file=sys.stderr)
sys.exit(1)
`;
}
/**
* Parse AI response to extract version suggestion
*/
private parseAIResponse(output: string, currentVersion: string): VersionSuggestion {
// Extract JSON from output (Claude might wrap it in markdown or other text)
const jsonMatch = output.match(/\{[\s\S]*"bumpType"[\s\S]*"reason"[\s\S]*\}/);
if (!jsonMatch) {
throw new Error('No JSON found in AI response');
}
const parsed = JSON.parse(jsonMatch[0]);
const bumpType = parsed.bumpType as 'major' | 'minor' | 'patch';
const reason = parsed.reason || 'AI analysis of commits';
// Calculate new version
const [major, minor, patch] = currentVersion.split('.').map(Number);
let newVersion: string;
switch (bumpType) {
case 'major':
newVersion = `${major + 1}.0.0`;
break;
case 'minor':
newVersion = `${major}.${minor + 1}.0`;
break;
case 'patch':
default:
newVersion = `${major}.${minor}.${patch + 1}`;
break;
}
return {
version: newVersion,
reason,
bumpType
};
}
/**
* Fallback suggestion if AI analysis fails
*/
private fallbackSuggestion(currentVersion: string): VersionSuggestion {
const [major, minor, patch] = currentVersion.split('.').map(Number);
return {
version: `${major}.${minor}.${patch + 1}`,
reason: 'Patch version bump (default)',
bumpType: 'patch'
};
}
/**
* Build spawn environment with proper PATH and auth settings
*/
private buildSpawnEnvironment(): Record<string, string> {
const homeDir = os.homedir();
const isWindows = process.platform === 'win32';
// Build PATH with platform-appropriate separator and locations
const pathAdditions = isWindows
? [
path.join(homeDir, 'AppData', 'Local', 'Programs', 'claude'),
path.join(homeDir, 'AppData', 'Roaming', 'npm'),
path.join(homeDir, '.local', 'bin'),
'C:\\Program Files\\Claude',
'C:\\Program Files (x86)\\Claude'
]
: [
'/usr/local/bin',
'/opt/homebrew/bin',
path.join(homeDir, '.local', 'bin'),
path.join(homeDir, 'bin')
];
// Get active Claude profile environment
const profileEnv = getProfileEnv();
const spawnEnv: Record<string, string> = {
...process.env as Record<string, string>,
...profileEnv,
...(isWindows ? { USERPROFILE: homeDir } : { HOME: homeDir }),
USER: process.env.USER || process.env.USERNAME || 'user',
PATH: [process.env.PATH || '', ...pathAdditions].filter(Boolean).join(path.delimiter),
PYTHONUNBUFFERED: '1',
PYTHONIOENCODING: 'utf-8',
PYTHONUTF8: '1'
};
return spawnEnv;
}
}
@@ -0,0 +1,508 @@
/**
* Claude Profile Manager
* Main coordinator for multi-account profile management
*
* This class delegates to specialized modules:
* - token-encryption: OAuth token encryption/decryption
* - usage-parser: Usage data parsing and reset time calculations
* - rate-limit-manager: Rate limit event tracking
* - profile-storage: Disk persistence
* - profile-scorer: Profile availability scoring and auto-switch logic
* - profile-utils: Helper utilities
*/
import { app } from 'electron';
import { join } from 'path';
import { existsSync, mkdirSync } from 'fs';
import type {
ClaudeProfile,
ClaudeProfileSettings,
ClaudeUsageData,
ClaudeRateLimitEvent,
ClaudeAutoSwitchSettings
} from '../shared/types';
// Module imports
import { encryptToken, decryptToken } from './claude-profile/token-encryption';
import { parseUsageOutput } from './claude-profile/usage-parser';
import {
recordRateLimitEvent as recordRateLimitEventImpl,
isProfileRateLimited as isProfileRateLimitedImpl,
clearRateLimitEvents as clearRateLimitEventsImpl
} from './claude-profile/rate-limit-manager';
import {
loadProfileStore,
saveProfileStore,
ProfileStoreData,
DEFAULT_AUTO_SWITCH_SETTINGS
} from './claude-profile/profile-storage';
import {
getBestAvailableProfile,
shouldProactivelySwitch as shouldProactivelySwitchImpl,
getProfilesSortedByAvailability as getProfilesSortedByAvailabilityImpl
} from './claude-profile/profile-scorer';
import {
DEFAULT_CLAUDE_CONFIG_DIR,
generateProfileId as generateProfileIdImpl,
createProfileDirectory as createProfileDirectoryImpl,
isProfileAuthenticated as isProfileAuthenticatedImpl,
hasValidToken,
expandHomePath
} from './claude-profile/profile-utils';
/**
* Manages Claude Code profiles for multi-account support.
* Profiles are stored in the app's userData directory.
* Each profile points to a separate Claude config directory.
*/
export class ClaudeProfileManager {
private storePath: string;
private data: ProfileStoreData;
constructor() {
const configDir = join(app.getPath('userData'), 'config');
this.storePath = join(configDir, 'claude-profiles.json');
// Ensure directory exists
if (!existsSync(configDir)) {
mkdirSync(configDir, { recursive: true });
}
// Load existing data or initialize with default profile
this.data = this.load();
}
/**
* Load profiles from disk
*/
private load(): ProfileStoreData {
const loadedData = loadProfileStore(this.storePath);
if (loadedData) {
return loadedData;
}
// Return default with a single "Default" profile
return this.createDefaultData();
}
/**
* Create default profile data
*/
private createDefaultData(): ProfileStoreData {
const defaultProfile: ClaudeProfile = {
id: 'default',
name: 'Default',
configDir: DEFAULT_CLAUDE_CONFIG_DIR,
isDefault: true,
description: 'Default Claude configuration (~/.claude)',
createdAt: new Date()
};
return {
version: 3,
profiles: [defaultProfile],
activeProfileId: 'default',
autoSwitch: DEFAULT_AUTO_SWITCH_SETTINGS
};
}
/**
* Save profiles to disk
*/
private save(): void {
saveProfileStore(this.storePath, this.data);
}
/**
* Get all profiles and settings
*/
getSettings(): ClaudeProfileSettings {
return {
profiles: this.data.profiles,
activeProfileId: this.data.activeProfileId,
autoSwitch: this.data.autoSwitch || DEFAULT_AUTO_SWITCH_SETTINGS
};
}
/**
* Get auto-switch settings
*/
getAutoSwitchSettings(): ClaudeAutoSwitchSettings {
return this.data.autoSwitch || DEFAULT_AUTO_SWITCH_SETTINGS;
}
/**
* Update auto-switch settings
*/
updateAutoSwitchSettings(settings: Partial<ClaudeAutoSwitchSettings>): void {
this.data.autoSwitch = {
...(this.data.autoSwitch || DEFAULT_AUTO_SWITCH_SETTINGS),
...settings
};
this.save();
}
/**
* Get a specific profile by ID
*/
getProfile(profileId: string): ClaudeProfile | undefined {
return this.data.profiles.find(p => p.id === profileId);
}
/**
* Get the active profile
*/
getActiveProfile(): ClaudeProfile {
const active = this.data.profiles.find(p => p.id === this.data.activeProfileId);
if (!active) {
// Fallback to default
const defaultProfile = this.data.profiles.find(p => p.isDefault);
if (defaultProfile) {
return defaultProfile;
}
// If somehow no default exists, return first profile
return this.data.profiles[0];
}
return active;
}
/**
* Save or update a profile
*/
saveProfile(profile: ClaudeProfile): ClaudeProfile {
// Expand ~ in configDir path
if (profile.configDir) {
profile.configDir = expandHomePath(profile.configDir);
}
const index = this.data.profiles.findIndex(p => p.id === profile.id);
if (index >= 0) {
// Update existing
this.data.profiles[index] = profile;
} else {
// Add new
this.data.profiles.push(profile);
}
this.save();
return profile;
}
/**
* Delete a profile (cannot delete default or last profile)
*/
deleteProfile(profileId: string): boolean {
const profile = this.getProfile(profileId);
if (!profile) {
return false;
}
// Cannot delete default profile
if (profile.isDefault) {
console.warn('[ClaudeProfileManager] Cannot delete default profile');
return false;
}
// Cannot delete if it's the only profile
if (this.data.profiles.length <= 1) {
console.warn('[ClaudeProfileManager] Cannot delete last profile');
return false;
}
// Remove the profile
this.data.profiles = this.data.profiles.filter(p => p.id !== profileId);
// If we deleted the active profile, switch to default
if (this.data.activeProfileId === profileId) {
const defaultProfile = this.data.profiles.find(p => p.isDefault);
this.data.activeProfileId = defaultProfile?.id || this.data.profiles[0].id;
}
this.save();
return true;
}
/**
* Rename a profile
*/
renameProfile(profileId: string, newName: string): boolean {
const profile = this.getProfile(profileId);
if (!profile) {
return false;
}
// Cannot rename to empty name
if (!newName.trim()) {
console.warn('[ClaudeProfileManager] Cannot rename to empty name');
return false;
}
profile.name = newName.trim();
this.save();
console.warn('[ClaudeProfileManager] Renamed profile:', profileId, 'to:', newName);
return true;
}
/**
* Set the active profile
*/
setActiveProfile(profileId: string): boolean {
const profile = this.getProfile(profileId);
if (!profile) {
return false;
}
this.data.activeProfileId = profileId;
profile.lastUsedAt = new Date();
this.save();
return true;
}
/**
* Update last used timestamp for a profile
*/
markProfileUsed(profileId: string): void {
const profile = this.getProfile(profileId);
if (profile) {
profile.lastUsedAt = new Date();
this.save();
}
}
/**
* Get the OAuth token for the active profile (decrypted).
* Returns undefined if no token is set (profile needs authentication).
*/
getActiveProfileToken(): string | undefined {
const profile = this.getActiveProfile();
if (!profile?.oauthToken) {
return undefined;
}
// Decrypt the token before returning
return decryptToken(profile.oauthToken);
}
/**
* Get the decrypted OAuth token for a specific profile.
*/
getProfileToken(profileId: string): string | undefined {
const profile = this.getProfile(profileId);
if (!profile?.oauthToken) {
return undefined;
}
return decryptToken(profile.oauthToken);
}
/**
* Set the OAuth token for a profile (encrypted storage).
* Used when capturing token from `claude setup-token` output.
*/
setProfileToken(profileId: string, token: string, email?: string): boolean {
const profile = this.getProfile(profileId);
if (!profile) {
return false;
}
// Encrypt the token before storing
profile.oauthToken = encryptToken(token);
profile.tokenCreatedAt = new Date();
if (email) {
profile.email = email;
}
// Clear any rate limit events since this might be a new account
profile.rateLimitEvents = [];
this.save();
const isEncrypted = profile.oauthToken.startsWith('enc:');
console.warn('[ClaudeProfileManager] Set OAuth token for profile:', profile.name, {
email: email || '(not captured)',
encrypted: isEncrypted,
tokenLength: token.length
});
return true;
}
/**
* Check if a profile has a valid OAuth token.
* Token is valid for 1 year from creation.
*/
hasValidToken(profileId: string): boolean {
const profile = this.getProfile(profileId);
if (!profile) {
return false;
}
return hasValidToken(profile);
}
/**
* Get environment variables for spawning processes with the active profile.
* Returns { CLAUDE_CODE_OAUTH_TOKEN: token } if token is available (decrypted).
*/
getActiveProfileEnv(): Record<string, string> {
const profile = this.getActiveProfile();
const env: Record<string, string> = {};
if (profile?.oauthToken) {
// Decrypt the token before putting in environment
const decryptedToken = decryptToken(profile.oauthToken);
if (decryptedToken) {
env.CLAUDE_CODE_OAUTH_TOKEN = decryptedToken;
console.warn('[ClaudeProfileManager] Using OAuth token for profile:', profile.name);
} else {
console.warn('[ClaudeProfileManager] Failed to decrypt token for profile:', profile.name);
}
} else if (profile?.configDir && !profile.isDefault) {
// Fallback to configDir for backward compatibility
env.CLAUDE_CONFIG_DIR = profile.configDir;
console.warn('[ClaudeProfileManager] Using configDir for profile:', profile.name);
}
return env;
}
/**
* Update usage data for a profile (parsed from /usage output)
*/
updateProfileUsage(profileId: string, usageOutput: string): ClaudeUsageData | null {
const profile = this.getProfile(profileId);
if (!profile) {
return null;
}
const usage = parseUsageOutput(usageOutput);
profile.usage = usage;
this.save();
console.warn('[ClaudeProfileManager] Updated usage for', profile.name, ':', usage);
return usage;
}
/**
* Record a rate limit event for a profile
*/
recordRateLimitEvent(profileId: string, resetTimeStr: string): ClaudeRateLimitEvent {
const profile = this.getProfile(profileId);
if (!profile) {
throw new Error('Profile not found');
}
const event = recordRateLimitEventImpl(profile, resetTimeStr);
this.save();
console.warn('[ClaudeProfileManager] Recorded rate limit event for', profile.name, ':', event);
return event;
}
/**
* Check if a profile is currently rate-limited
*/
isProfileRateLimited(profileId: string): { limited: boolean; type?: 'session' | 'weekly'; resetAt?: Date } {
const profile = this.getProfile(profileId);
if (!profile) {
return { limited: false };
}
return isProfileRateLimitedImpl(profile);
}
/**
* Get the best profile to switch to based on usage and rate limit status
* Returns null if no good alternative is available
*/
getBestAvailableProfile(excludeProfileId?: string): ClaudeProfile | null {
const settings = this.getAutoSwitchSettings();
return getBestAvailableProfile(this.data.profiles, settings, excludeProfileId);
}
/**
* Determine if we should proactively switch profiles based on current usage
*/
shouldProactivelySwitch(profileId: string): { shouldSwitch: boolean; reason?: string; suggestedProfile?: ClaudeProfile } {
const profile = this.getProfile(profileId);
if (!profile) {
return { shouldSwitch: false };
}
const settings = this.getAutoSwitchSettings();
return shouldProactivelySwitchImpl(profile, this.data.profiles, settings);
}
/**
* Generate a unique ID for a new profile
*/
generateProfileId(name: string): string {
return generateProfileIdImpl(name, this.data.profiles);
}
/**
* Create a new profile directory and initialize it
*/
async createProfileDirectory(profileName: string): Promise<string> {
return createProfileDirectoryImpl(profileName);
}
/**
* Check if a profile has valid authentication
* (checks if the config directory has credential files)
*/
isProfileAuthenticated(profile: ClaudeProfile): boolean {
return isProfileAuthenticatedImpl(profile);
}
/**
* Get environment variables for invoking Claude with a specific profile
*/
getProfileEnv(profileId: string): Record<string, string> {
const profile = this.getProfile(profileId);
if (!profile) {
return {};
}
// Only set CLAUDE_CONFIG_DIR if not using default
if (profile.isDefault) {
return {};
}
// Only set CLAUDE_CONFIG_DIR if configDir is defined
if (!profile.configDir) {
return {};
}
return {
CLAUDE_CONFIG_DIR: profile.configDir
};
}
/**
* Clear rate limit events for a profile (e.g., when they've reset)
*/
clearRateLimitEvents(profileId: string): void {
const profile = this.getProfile(profileId);
if (profile) {
clearRateLimitEventsImpl(profile);
this.save();
}
}
/**
* Get profiles sorted by availability (best first)
*/
getProfilesSortedByAvailability(): ClaudeProfile[] {
return getProfilesSortedByAvailabilityImpl(this.data.profiles);
}
}
// Singleton instance
let profileManager: ClaudeProfileManager | null = null;
/**
* Get the singleton Claude profile manager instance
*/
export function getClaudeProfileManager(): ClaudeProfileManager {
if (!profileManager) {
profileManager = new ClaudeProfileManager();
}
return profileManager;
}
@@ -0,0 +1,148 @@
# Claude Profile Module
This directory contains the refactored Claude profile management system, broken down into logical, maintainable modules.
## Architecture
The profile management system is organized using separation of concerns, with each module handling a specific responsibility:
```
claude-profile/
├── index.ts # Central export point
├── types.ts # Type definitions
├── token-encryption.ts # OAuth token encryption/decryption
├── usage-parser.ts # Usage data parsing and reset time calculations
├── rate-limit-manager.ts # Rate limit event tracking
├── profile-storage.ts # Disk persistence
├── profile-scorer.ts # Profile availability scoring and auto-switch logic
└── profile-utils.ts # Helper utilities
```
## Modules
### 1. **token-encryption.ts**
Handles OAuth token encryption and decryption using the OS keychain (Electron's safeStorage API).
**Key Functions:**
- `encryptToken(token: string): string` - Encrypts a token using OS keychain
- `decryptToken(storedToken: string): string` - Decrypts a token, handles legacy plain tokens
- `isTokenEncrypted(storedToken: string): boolean` - Checks if token is encrypted
### 2. **usage-parser.ts**
Parses Claude `/usage` command output and calculates reset times.
**Key Functions:**
- `parseUsageOutput(usageOutput: string): ClaudeUsageData` - Parses full usage output
- `parseResetTime(resetTimeStr: string): Date` - Converts reset time strings to Date objects
- `classifyRateLimitType(resetTimeStr: string): 'session' | 'weekly'` - Determines rate limit type
### 3. **rate-limit-manager.ts**
Manages rate limit events and status tracking.
**Key Functions:**
- `recordRateLimitEvent(profile, resetTimeStr): ClaudeRateLimitEvent` - Records a rate limit hit
- `isProfileRateLimited(profile): {limited, type?, resetAt?}` - Checks current rate limit status
- `clearRateLimitEvents(profile): void` - Clears rate limit history
### 4. **profile-storage.ts**
Handles persistence of profile data to disk with version migration.
**Key Functions:**
- `loadProfileStore(storePath: string): ProfileStoreData | null` - Loads profiles from disk
- `saveProfileStore(storePath: string, data: ProfileStoreData): void` - Saves profiles to disk
**Constants:**
- `STORE_VERSION` - Current storage format version
- `DEFAULT_AUTO_SWITCH_SETTINGS` - Default auto-switch configuration
### 5. **profile-scorer.ts**
Implements intelligent profile scoring and auto-switch logic.
**Key Functions:**
- `getBestAvailableProfile(profiles, settings, excludeProfileId?): ClaudeProfile | null` - Finds best profile based on usage/limits
- `shouldProactivelySwitch(profile, allProfiles, settings): {shouldSwitch, reason?, suggestedProfile?}` - Determines if proactive switch is needed
- `getProfilesSortedByAvailability(profiles): ClaudeProfile[]` - Sorts profiles by availability
**Scoring Criteria:**
1. Not rate-limited (highest priority)
2. Lower weekly usage (more important than session)
3. Lower session usage
4. Authenticated profiles
### 6. **profile-utils.ts**
Helper utilities for profile operations.
**Key Functions:**
- `generateProfileId(name, existingProfiles): string` - Generates unique profile IDs
- `createProfileDirectory(profileName): Promise<string>` - Creates profile directory
- `isProfileAuthenticated(profile): boolean` - Checks if profile has valid auth
- `hasValidToken(profile): boolean` - Validates OAuth token (1 year expiry)
- `expandHomePath(path): string` - Expands ~ in paths
**Constants:**
- `DEFAULT_CLAUDE_CONFIG_DIR` - Default Claude config location (~/.claude)
- `CLAUDE_PROFILES_DIR` - Additional profiles directory (~/.claude-profiles)
### 7. **types.ts**
Re-exports shared types for convenience and future extensibility.
### 8. **index.ts**
Central export point providing a clean public API for all profile functionality.
## Main Manager
The `claude-profile-manager.ts` (parent directory) serves as the high-level coordinator that:
- Delegates to specialized modules
- Manages the overall profile lifecycle
- Coordinates between different subsystems
- Provides the singleton instance
**Original size:** 903 lines
**Refactored size:** 509 lines (44% reduction)
**Total with modules:** 1197 lines (organized and maintainable)
## Usage
### Using the Main Manager
```typescript
import { getClaudeProfileManager } from './claude-profile-manager';
const manager = getClaudeProfileManager();
const profile = manager.getActiveProfile();
const usage = manager.updateProfileUsage(profileId, usageOutput);
```
### Using Individual Modules (Advanced)
```typescript
import { parseUsageOutput, isProfileRateLimited } from './claude-profile';
const usage = parseUsageOutput(output);
const status = isProfileRateLimited(profile);
```
## Benefits of Refactoring
1. **Separation of Concerns** - Each module has a single, well-defined responsibility
2. **Testability** - Modules can be unit tested independently
3. **Maintainability** - Easier to understand and modify specific functionality
4. **Reusability** - Modules can be imported individually when needed
5. **Readability** - Smaller files are easier to navigate and understand
6. **Type Safety** - Clear module boundaries with explicit TypeScript types
## Backward Compatibility
All existing imports continue to work without modification:
```typescript
import { getClaudeProfileManager } from './claude-profile-manager';
```
The public API of `ClaudeProfileManager` remains unchanged, ensuring zero breaking changes for existing code.
## Future Enhancements
Potential areas for future improvement:
- Add comprehensive unit tests for each module
- Implement profile import/export functionality
- Add profile usage analytics and reporting
- Enhance auto-switch algorithms with machine learning
- Add profile backup and restore capabilities
@@ -0,0 +1,56 @@
/**
* Claude Profile Module
* Central export point for all profile management functionality
*/
// Core types
export type {
ClaudeProfile,
ClaudeProfileSettings,
ClaudeUsageData,
ClaudeRateLimitEvent,
ClaudeAutoSwitchSettings
} from './types';
// Token encryption utilities
export { encryptToken, decryptToken, isTokenEncrypted } from './token-encryption';
// Usage parsing utilities
export { parseUsageOutput, parseResetTime, classifyRateLimitType } from './usage-parser';
// Rate limit management
export {
recordRateLimitEvent,
isProfileRateLimited,
clearRateLimitEvents
} from './rate-limit-manager';
// Storage utilities
export {
loadProfileStore,
saveProfileStore,
DEFAULT_AUTO_SWITCH_SETTINGS,
STORE_VERSION
} from './profile-storage';
export type { ProfileStoreData } from './profile-storage';
// Profile scoring and auto-switch
export {
getBestAvailableProfile,
shouldProactivelySwitch,
getProfilesSortedByAvailability
} from './profile-scorer';
// Profile utilities
export {
DEFAULT_CLAUDE_CONFIG_DIR,
CLAUDE_PROFILES_DIR,
generateProfileId,
createProfileDirectory,
isProfileAuthenticated,
hasValidToken,
expandHomePath
} from './profile-utils';
// Usage monitoring (proactive account switching)
export { UsageMonitor, getUsageMonitor } from './usage-monitor';
@@ -0,0 +1,174 @@
/**
* Profile Scorer Module
* Handles profile availability scoring and auto-switch logic
*/
import type { ClaudeProfile, ClaudeAutoSwitchSettings } from '../../shared/types';
import { isProfileRateLimited } from './rate-limit-manager';
import { isProfileAuthenticated } from './profile-utils';
interface ScoredProfile {
profile: ClaudeProfile;
score: number;
}
/**
* Get the best profile to switch to based on usage and rate limit status
* Returns null if no good alternative is available
*/
export function getBestAvailableProfile(
profiles: ClaudeProfile[],
settings: ClaudeAutoSwitchSettings,
excludeProfileId?: string
): ClaudeProfile | null {
const now = new Date();
// Get all profiles except the excluded one
const candidates = profiles.filter(p => p.id !== excludeProfileId);
if (candidates.length === 0) {
return null;
}
// Score each profile based on:
// 1. Not rate-limited (highest priority)
// 2. Lower weekly usage (more important than session)
// 3. Lower session usage
// 4. More recently authenticated
const scoredProfiles: ScoredProfile[] = candidates.map(profile => {
let score = 100; // Base score
// Check rate limit status
const rateLimitStatus = isProfileRateLimited(profile);
if (rateLimitStatus.limited) {
// Severely penalize rate-limited profiles
if (rateLimitStatus.type === 'weekly') {
score -= 1000; // Weekly limit is worse
} else {
score -= 500; // Session limit will reset sooner
}
// But add back some score based on how soon it resets
if (rateLimitStatus.resetAt) {
const hoursUntilReset = (rateLimitStatus.resetAt.getTime() - now.getTime()) / (1000 * 60 * 60);
score += Math.max(0, 50 - hoursUntilReset); // Closer reset = higher score
}
}
// Factor in current usage (if known)
if (profile.usage) {
// Weekly usage is more important
score -= profile.usage.weeklyUsagePercent * 0.5;
// Session usage is less important (resets more frequently)
score -= profile.usage.sessionUsagePercent * 0.2;
// Penalize if above thresholds
if (profile.usage.weeklyUsagePercent >= settings.weeklyThreshold) {
score -= 200;
}
if (profile.usage.sessionUsagePercent >= settings.sessionThreshold) {
score -= 100;
}
}
// Check if authenticated
if (!isProfileAuthenticated(profile)) {
score -= 500; // Severely penalize unauthenticated profiles
}
return { profile, score };
});
// Sort by score (highest first)
scoredProfiles.sort((a, b) => b.score - a.score);
// Return the best candidate if it has a positive score
const best = scoredProfiles[0];
if (best && best.score > 0) {
console.warn('[ProfileScorer] Best available profile:', best.profile.name, 'score:', best.score);
return best.profile;
}
// All profiles are rate-limited or have issues
console.warn('[ProfileScorer] No good profile available, all are rate-limited or have issues');
return null;
}
/**
* Determine if we should proactively switch profiles based on current usage
*/
export function shouldProactivelySwitch(
profile: ClaudeProfile,
allProfiles: ClaudeProfile[],
settings: ClaudeAutoSwitchSettings
): { shouldSwitch: boolean; reason?: string; suggestedProfile?: ClaudeProfile } {
if (!settings.enabled) {
return { shouldSwitch: false };
}
if (!profile?.usage) {
return { shouldSwitch: false };
}
const usage = profile.usage;
// Check if we're approaching limits
if (usage.weeklyUsagePercent >= settings.weeklyThreshold) {
const bestProfile = getBestAvailableProfile(allProfiles, settings, profile.id);
if (bestProfile) {
return {
shouldSwitch: true,
reason: `Weekly usage at ${usage.weeklyUsagePercent}% (threshold: ${settings.weeklyThreshold}%)`,
suggestedProfile: bestProfile
};
}
}
if (usage.sessionUsagePercent >= settings.sessionThreshold) {
const bestProfile = getBestAvailableProfile(allProfiles, settings, profile.id);
if (bestProfile) {
return {
shouldSwitch: true,
reason: `Session usage at ${usage.sessionUsagePercent}% (threshold: ${settings.sessionThreshold}%)`,
suggestedProfile: bestProfile
};
}
}
return { shouldSwitch: false };
}
/**
* Get profiles sorted by availability (best first)
*/
export function getProfilesSortedByAvailability(profiles: ClaudeProfile[]): ClaudeProfile[] {
const _now = new Date();
return [...profiles].sort((a, b) => {
// Not rate-limited profiles first
const aLimited = isProfileRateLimited(a);
const bLimited = isProfileRateLimited(b);
if (aLimited.limited !== bLimited.limited) {
return aLimited.limited ? 1 : -1;
}
// If both limited, sort by reset time
if (aLimited.limited && bLimited.limited && aLimited.resetAt && bLimited.resetAt) {
return aLimited.resetAt.getTime() - bLimited.resetAt.getTime();
}
// Sort by lower weekly usage
const aWeekly = a.usage?.weeklyUsagePercent ?? 0;
const bWeekly = b.usage?.weeklyUsagePercent ?? 0;
if (aWeekly !== bWeekly) {
return aWeekly - bWeekly;
}
// Sort by lower session usage
const aSession = a.usage?.sessionUsagePercent ?? 0;
const bSession = b.usage?.sessionUsagePercent ?? 0;
return aSession - bSession;
});
}
@@ -0,0 +1,84 @@
/**
* Profile Storage Module
* Handles persistence of profile data to disk
*/
import { existsSync, readFileSync, writeFileSync } from 'fs';
import type { ClaudeProfile, ClaudeAutoSwitchSettings } from '../../shared/types';
export const STORE_VERSION = 3; // Bumped for encrypted token storage
/**
* Default auto-switch settings
*/
export const DEFAULT_AUTO_SWITCH_SETTINGS: ClaudeAutoSwitchSettings = {
enabled: false,
proactiveSwapEnabled: false, // Proactive monitoring disabled by default
sessionThreshold: 95, // Consider switching at 95% session usage
weeklyThreshold: 99, // Consider switching at 99% weekly usage
autoSwitchOnRateLimit: false, // Prompt user by default
usageCheckInterval: 30000 // Check every 30s when enabled (0 = disabled)
};
/**
* Internal storage format for Claude profiles
*/
export interface ProfileStoreData {
version: number;
profiles: ClaudeProfile[];
activeProfileId: string;
autoSwitch?: ClaudeAutoSwitchSettings;
}
/**
* Load profiles from disk
*/
export function loadProfileStore(storePath: string): ProfileStoreData | null {
try {
if (existsSync(storePath)) {
const content = readFileSync(storePath, 'utf-8');
const data = JSON.parse(content);
// Handle version migration
if (data.version === 1) {
// Migrate v1 to v2: add usage and rateLimitEvents fields
data.version = STORE_VERSION;
data.autoSwitch = DEFAULT_AUTO_SWITCH_SETTINGS;
}
if (data.version === STORE_VERSION) {
// Parse dates
data.profiles = data.profiles.map((p: ClaudeProfile) => ({
...p,
createdAt: new Date(p.createdAt),
lastUsedAt: p.lastUsedAt ? new Date(p.lastUsedAt) : undefined,
usage: p.usage ? {
...p.usage,
lastUpdated: new Date(p.usage.lastUpdated)
} : undefined,
rateLimitEvents: p.rateLimitEvents?.map(e => ({
...e,
hitAt: new Date(e.hitAt),
resetAt: new Date(e.resetAt)
}))
}));
return data;
}
}
} catch (error) {
console.error('[ProfileStorage] Error loading profiles:', error);
}
return null;
}
/**
* Save profiles to disk
*/
export function saveProfileStore(storePath: string, data: ProfileStoreData): void {
try {
writeFileSync(storePath, JSON.stringify(data, null, 2), 'utf-8');
} catch (error) {
console.error('[ProfileStorage] Error saving profiles:', error);
}
}
@@ -0,0 +1,137 @@
/**
* Profile Utilities Module
* Helper functions for profile operations
*/
import { homedir } from 'os';
import { join } from 'path';
import { existsSync, readFileSync, readdirSync, mkdirSync } from 'fs';
import type { ClaudeProfile } from '../../shared/types';
/**
* Default Claude config directory
*/
export const DEFAULT_CLAUDE_CONFIG_DIR = join(homedir(), '.claude');
/**
* Default profiles directory for additional accounts
*/
export const CLAUDE_PROFILES_DIR = join(homedir(), '.claude-profiles');
/**
* Generate a unique ID for a new profile
*/
export function generateProfileId(name: string, existingProfiles: ClaudeProfile[]): string {
const baseId = name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
let id = baseId;
let counter = 1;
while (existingProfiles.some(p => p.id === id)) {
id = `${baseId}-${counter}`;
counter++;
}
return id;
}
/**
* Create a new profile directory and initialize it
*/
export async function createProfileDirectory(profileName: string): Promise<string> {
// Ensure profiles directory exists
if (!existsSync(CLAUDE_PROFILES_DIR)) {
mkdirSync(CLAUDE_PROFILES_DIR, { recursive: true });
}
// Create directory for this profile
const sanitizedName = profileName.toLowerCase().replace(/[^a-z0-9]+/g, '-');
const profileDir = join(CLAUDE_PROFILES_DIR, sanitizedName);
if (!existsSync(profileDir)) {
mkdirSync(profileDir, { recursive: true });
}
return profileDir;
}
/**
* Check if a profile has valid authentication
* (checks if the config directory has credential files)
*/
export function isProfileAuthenticated(profile: ClaudeProfile): boolean {
const configDir = profile.configDir;
if (!configDir || !existsSync(configDir)) {
return false;
}
// Claude stores auth in .claude/credentials or similar files
// Check for common auth indicators
const possibleAuthFiles = [
join(configDir, 'credentials'),
join(configDir, 'credentials.json'),
join(configDir, '.credentials'),
join(configDir, 'settings.json'), // Often contains auth tokens
];
for (const authFile of possibleAuthFiles) {
if (existsSync(authFile)) {
try {
const content = readFileSync(authFile, 'utf-8');
// Check if file has actual content (not just empty or placeholder)
if (content.length > 10) {
return true;
}
} catch {
// Ignore read errors
}
}
}
// Also check if there are any session files (indicates authenticated usage)
const projectsDir = join(configDir, 'projects');
if (existsSync(projectsDir)) {
try {
const projects = readdirSync(projectsDir);
if (projects.length > 0) {
return true;
}
} catch {
// Ignore read errors
}
}
return false;
}
/**
* Check if a profile has a valid OAuth token.
* Token is valid for 1 year from creation.
*/
export function hasValidToken(profile: ClaudeProfile): boolean {
if (!profile?.oauthToken) {
return false;
}
// Check if token is expired (1 year validity)
if (profile.tokenCreatedAt) {
const oneYearAgo = new Date();
oneYearAgo.setFullYear(oneYearAgo.getFullYear() - 1);
if (new Date(profile.tokenCreatedAt) < oneYearAgo) {
console.warn('[ProfileUtils] Token expired for profile:', profile.name);
return false;
}
}
return true;
}
/**
* Expand ~ in path to home directory
*/
export function expandHomePath(path: string): string {
if (path && path.startsWith('~')) {
const home = homedir();
return path.replace(/^~/, home);
}
return path;
}
@@ -0,0 +1,62 @@
/**
* Rate Limit Manager Module
* Handles rate limit event recording and status checking
*/
import type { ClaudeProfile, ClaudeRateLimitEvent } from '../../shared/types';
import { parseResetTime, classifyRateLimitType } from './usage-parser';
/**
* Record a rate limit event for a profile
*/
export function recordRateLimitEvent(
profile: ClaudeProfile,
resetTimeStr: string
): ClaudeRateLimitEvent {
const event: ClaudeRateLimitEvent = {
type: classifyRateLimitType(resetTimeStr),
hitAt: new Date(),
resetAt: parseResetTime(resetTimeStr),
resetTimeString: resetTimeStr
};
// Keep last 10 events
profile.rateLimitEvents = [
event,
...(profile.rateLimitEvents || []).slice(0, 9)
];
return event;
}
/**
* Check if a profile is currently rate-limited
*/
export function isProfileRateLimited(
profile: ClaudeProfile
): { limited: boolean; type?: 'session' | 'weekly'; resetAt?: Date } {
if (!profile || !profile.rateLimitEvents?.length) {
return { limited: false };
}
const now = new Date();
// Check the most recent event
const latestEvent = profile.rateLimitEvents[0];
if (latestEvent.resetAt > now) {
return {
limited: true,
type: latestEvent.type,
resetAt: latestEvent.resetAt
};
}
return { limited: false };
}
/**
* Clear rate limit events for a profile (e.g., when they've reset)
*/
export function clearRateLimitEvents(profile: ClaudeProfile): void {
profile.rateLimitEvents = [];
}
@@ -0,0 +1,47 @@
/**
* Token Encryption Module
* Handles OAuth token encryption/decryption using OS keychain
*/
import { safeStorage } from 'electron';
/**
* Encrypt a token using the OS keychain (safeStorage API).
* Returns base64-encoded encrypted data, or the raw token if encryption unavailable.
*/
export function encryptToken(token: string): string {
try {
if (safeStorage.isEncryptionAvailable()) {
const encrypted = safeStorage.encryptString(token);
// Prefix with 'enc:' to identify encrypted tokens
return 'enc:' + encrypted.toString('base64');
}
} catch (error) {
console.warn('[TokenEncryption] Encryption not available, storing token as-is:', error);
}
return token;
}
/**
* Decrypt a token. Handles both encrypted (enc:...) and legacy plain tokens.
*/
export function decryptToken(storedToken: string): string {
try {
if (storedToken.startsWith('enc:') && safeStorage.isEncryptionAvailable()) {
const encryptedData = Buffer.from(storedToken.slice(4), 'base64');
return safeStorage.decryptString(encryptedData);
}
} catch (error) {
console.error('[TokenEncryption] Failed to decrypt token:', error);
return ''; // Return empty string on decryption failure
}
// Return as-is for legacy unencrypted tokens
return storedToken;
}
/**
* Check if a token is encrypted
*/
export function isTokenEncrypted(storedToken: string): boolean {
return storedToken.startsWith('enc:');
}

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