diff --git a/.taskmaster/docs/research/2025-06-13_what-is-typescript.md b/.taskmaster/docs/research/2025-06-13_what-is-typescript.md deleted file mode 100644 index 218bf43a..00000000 --- a/.taskmaster/docs/research/2025-06-13_what-is-typescript.md +++ /dev/null @@ -1,42 +0,0 @@ ---- -title: Research Session -query: "What is TypeScript?" -date: 6/13/2025 -time: 3:07:41 PM -timestamp: 2025-06-13T19:07:41.313Z -exchanges: 2 ---- - -# Research Session - -**Query:** What is TypeScript? -**Date:** 6/13/2025 3:07:41 PM -**Exchanges:** 2 - ---- - -## Initial Query - -**Question:** What is TypeScript? - -**Response:** - -TypeScript is a strongly typed, object-oriented programming language that builds on JavaScript by adding static typing and type annotations. It is a syntactic superset of JavaScript, meaning all JavaScript code is valid TypeScript, but TypeScript adds extra syntax to specify types, enabling compile-time type checking and better tooling support. This helps catch errors early before running the code and improves code quality, especially in large-scale applications. TypeScript code is transpiled to plain JavaScript, which can run anywhere JavaScript runs, such as browsers, Node.js, or Deno. It is developed and maintained by Microsoft as open-source software under the Apache 2.0 license[1][2][3][4][5]. - ---- - -## Follow-up 1 - -**Question:** And why is the sky blue? - -**Response:** - -- The sky appears blue because sunlight interacts with Earth's atmosphere, and the shorter wavelengths of light (blue and violet) are scattered in all directions by air molecules—a process called Rayleigh scattering[1][2][3][5]. -- Blue light is scattered more than red light because it has a shorter wavelength, making the sky look blue to our eyes during the day[2][3][5]. -- If Earth's atmosphere didn't scatter sunlight, the sky would appear dark, as it does on the Moon, which lacks an atmosphere[5]. - - ---- - -*Generated by Task Master Research Command* -*Timestamp: 2025-06-13T19:07:41.313Z* diff --git a/.taskmaster/docs/research/2025-06-14_how-can-i-improve-the-scope-up-and-scope-down-comm.md b/.taskmaster/docs/research/2025-06-14_how-can-i-improve-the-scope-up-and-scope-down-comm.md new file mode 100644 index 00000000..dcfb19c9 --- /dev/null +++ b/.taskmaster/docs/research/2025-06-14_how-can-i-improve-the-scope-up-and-scope-down-comm.md @@ -0,0 +1,128 @@ +--- +title: Research Session +query: "how can i improve the scope-up and scope-down command" +date: 6/14/2025 +time: 4:35:03 PM +timestamp: 2025-06-14T20:35:03.231Z +exchanges: 2 +--- + +# Research Session + +## Initial Query + +**Question:** how can i improve the scope-up and scope-down command + +**Response:** + +## Improving the `scope-up` and `scope-down` Commands + +**Clarify Command Purpose and User Experience** + +- Ensure the commands have clear, intuitive behavior. For example, `scope-up` should consistently broaden the context or task view, while `scope-down` should reliably narrow it. +- Provide immediate, user-friendly feedback after each command, indicating what changed (e.g., "Now viewing parent task and all subtasks" or "Focused on subtask: X"). +- Document the commands with examples in your `docs/command-reference.md` and `docs/examples.md` to help users understand their effects and use cases. + +**Enhance Context Awareness** + +- Make the commands context-sensitive: if the user is already at the top or bottom of the scope hierarchy, return a helpful message instead of failing silently. +- Allow optional arguments to specify the exact level or target (e.g., `scope-up 2` to move up two levels, or `scope-down ` to jump directly to a subtask). + +**Robust Error Handling and Validation** + +- Implement checks to prevent invalid operations, such as attempting to scope up from the root or scope down when no subtasks exist. +- Provide clear error messages and suggestions for next steps, improving user trust and reducing confusion[1][5]. + +**Integrate with Task and Tag Systems** + +- Ensure `scope-up` and `scope-down` interact smoothly with your tagging and task hierarchy features. For example, scoping up from a subtask should show the parent task and its context, while scoping down should allow selection from available subtasks or related tags. +- Consider supporting batch operations, such as scoping down into all subtasks and displaying them in a summarized view. + +**Improve Performance and Synchronization** + +- Optimize the underlying logic to minimize delays, especially in large task trees. Use asynchronous operations where possible to keep the UI responsive. +- If the commands trigger data loading or context switching, ensure synchronization so that subsequent commands operate on the correct, updated context[2][4]. + +**Testing and Stakeholder Feedback** + +- Add or expand unit and integration tests for these commands (see `tests/unit/commands.test.js` and `integration/cli/commands.test.js`) to cover edge cases and ensure reliability. +- Gather feedback from users and stakeholders to identify pain points and desired enhancements, then iterate on the command design and implementation[1][5]. + +**Example Improvements Table** + +| Area | Current Issue | Suggested Improvement | +|---------------------|-----------------------------|----------------------------------------------| +| User Feedback | Minimal or unclear output | Add explicit, contextual messages | +| Error Handling | Silent failures | Informative errors and recovery suggestions | +| Flexibility | Only single-level movement | Support multi-level and targeted navigation | +| Integration | Limited context awareness | Sync with tags, parent/child relationships | +| Performance | Slow on large hierarchies | Optimize data access and UI updates | + +By focusing on these areas, you can make `scope-up` and `scope-down` more robust, user-friendly, and aligned with best practices in scope management and command design[1][5]. + +--- + +## Follow-up 1 + +**Question:** how might i do this relative to the tag system? + +**Response:** + +## Integrating Scope-Up and Scope-Down with the Tag System + +**Conceptual Mapping** + +- In your project, *scope-up* and *scope-down* commands currently operate on the task hierarchy, broadening or narrowing the context by moving between parent and child tasks. +- The tag system provides a parallel, orthogonal way to group and filter tasks—tags can represent categories, priorities, or any custom grouping, independent of strict parent/child relationships. + +**How to Make Scope Commands Tag-Aware** + +- **Scoping by Tag**: Allow users to "scope-down" into a tag, viewing only tasks associated with that tag. Conversely, "scope-up" could move from a specific tag context back to the broader task list or to a parent tag grouping if you support tag hierarchies. +- **Tag-Scoped Views**: When a tag is active as the current scope, all navigation and operations (listing, editing, etc.) are limited to tasks with that tag. This is similar to how some systems let you set the "Tag Scope" to filter navigation and search to only tagged items[1][5]. +- **Combining Hierarchy and Tags**: Enable compound scoping, such as "all subtasks of Task X that also have Tag Y." This can be implemented by intersecting the results of hierarchical and tag-based queries. + +**Implementation Strategies** + +- **Scope Stack or Context Object**: Maintain a stack or context object that tracks both the current task scope and any active tag filters. Each scope change (up/down or tag in/out) updates this context. +- **Commands**: + - `scope-down --tag `: Narrows the view to tasks with the specified tag. + - `scope-up --tag`: Removes the tag filter, broadening the view. + - `scope-down --tag `: Narrows to a specific subtask *and* applies a tag filter. +- **Tag Hierarchies (Optional)**: If your tag system supports parent/child tags or tag groups, allow "scope-up" to move from a specific tag to its parent tag or group, and "scope-down" to move into a child tag[4][5]. + +**Example User Flows** + +- *Scoping Down by Tag*: + User runs `scope-down --tag urgent` → Only tasks tagged "urgent" are shown. +- *Combining Task and Tag*: + User runs `scope-down --tag frontend` → Only subtasks of `` that are tagged "frontend" are shown. +- *Scoping Up from Tag*: + User runs `scope-up --tag` → Removes the tag filter, returning to the previous broader context. + +**Technical Considerations** + +- **Efficient Filtering**: Use indexed queries or in-memory filtering to efficiently combine tag and hierarchy filters, especially for large task sets. +- **Feedback and UI**: Always display the current scope context (e.g., "Viewing tasks tagged 'urgent' under 'Feature X'") so users understand what they're seeing. +- **Extensibility**: Design the scope system so new types of scopes (e.g., by status, assignee) can be added in the future, not just tags and hierarchy. + +**Relevant Precedents** + +- Tag-based file systems and management tools often implement "scopes" as dynamic groups defined by tag criteria, allowing users to build up complex views by combining tags and other filters[5]. +- Some systems allow scoping into tag management itself, where you can create, edit, or view tags and their associated objects, which could be mirrored in your CLI or UI[4]. + +**Summary Table** + +| Command Example | Resulting Scope | +|----------------------------------|--------------------------------------------------| +| `scope-down --tag bug` | All tasks tagged "bug" | +| `scope-down --tag api` | Subtasks of `` tagged "api" | +| `scope-up --tag` | Removes tag filter, returns to previous scope | +| `scope-down --tag frontend` | All tasks tagged "frontend" | + +By integrating tag-based scoping, you make your scope commands more flexible and powerful, supporting both hierarchical and ad-hoc organizational strategies[1][5]. + + +--- + +*Generated by Task Master Research Command* +*Timestamp: 2025-06-14T20:35:03.231Z* diff --git a/.taskmaster/docs/research/2025-06-14_should-i-be-using-any-specific-libraries-for-this.md b/.taskmaster/docs/research/2025-06-14_should-i-be-using-any-specific-libraries-for-this.md new file mode 100644 index 00000000..62d7623e --- /dev/null +++ b/.taskmaster/docs/research/2025-06-14_should-i-be-using-any-specific-libraries-for-this.md @@ -0,0 +1,158 @@ +--- +title: Research Session +query: "should i be using any specific libraries for this?" +date: 6/14/2025 +time: 5:20:00 PM +timestamp: 2025-06-14T21:20:00.561Z +exchanges: 2 +--- + +# Research Session + +## Initial Query + +**Question:** should i be using any specific libraries for this? + +**Response:** + +HELL YEAH PARTNER + +For implementing a GitHub Issue export feature with bidirectional linking in your project, you absolutely should use a dedicated library for interacting with the GitHub API. This will save you a ton of time, reduce boilerplate, and help you avoid common pitfalls with authentication, pagination, and error handling. + +## Recommended Library: PyGithub + +- **PyGithub** is the most widely used and well-documented Python library for accessing the GitHub REST API v3. It allows you to manage repositories, issues, user profiles, and more, all with a clean, object-oriented interface[1][2][3][5]. +- It supports all the operations you’ll need for your export feature, including creating issues, updating them, and managing references for bidirectional linking. + +### Key Features + +- **Authentication**: Easily authenticate with a personal access token. +- **Issue Management**: Create, update, and link issues programmatically. +- **Repository Access**: Fetch and manipulate repository data. +- **User/Org Support**: Works for both user and organization repos. +- **Pagination & Rate Limiting**: Handles these for you. + +### Example Usage + +```python +from github import Github, Auth + +# Authenticate with a personal access token +auth = Auth.Token("your_github_token") +g = Github(auth=auth) + +# Get the repo +repo = g.get_repo("owner/repo_name") + +# Create a new issue +issue = repo.create_issue( + title="Exported from Task Master", + body="This issue was created by Task Master. [Task ID: 123]" +) + +# Add a comment or update the issue to include a backlink +issue.create_comment("Linked to Task Master task #123") +``` +[3][5] + +## Why Not Use Raw Requests? + +- While you *can* use the `requests` library to call the GitHub API directly[4], PyGithub abstracts away authentication, error handling, and pagination, making your code much cleaner and less error-prone[2][5]. + +## Integration Tips + +- Store your GitHub token securely (e.g., in environment variables). +- Use PyGithub’s objects to fetch, create, and update issues. +- For bidirectional linking, store the GitHub issue URL in your task data and the Task Master task ID in the GitHub issue body or as a label/comment. +- PyGithub is actively maintained and widely used, so you’ll find plenty of support and documentation. + +## Installation + +```bash +pip install PyGithub +``` +[3] + +## Summary Table + +| Library | Language | API Coverage | Ease of Use | Maintained | Docs/Support | +|-----------|----------|--------------|-------------|------------|--------------| +| PyGithub | Python | Full | High | Yes | Excellent | +| requests | Python | Full (manual)| Medium | Yes | Good | + +**Use PyGithub for all GitHub API interactions in your export/import features.** It’s the standard for Python projects and will make your implementation faster, safer, and more maintainable[1][2][3][5]. + +--- + +## Follow-up 1 + +**Question:** we don't want to use py github because we have a node project + +**Response:** + +HELL YEAH PARTNER + +For a Node.js project, you should use a Node-native library to interact with the GitHub API instead of PyGithub, which is Python-only. The industry standard for Node.js is **Octokit**, the official GitHub SDK for JavaScript/TypeScript[1][2]. + +## Why Use Octokit? + +- **Official & Complete**: Octokit is maintained by GitHub and covers all REST and GraphQL API endpoints, including issues, repositories, users, and more[1][2]. +- **Universal**: Works in Node.js, browsers, and Deno environments[2]. +- **Typed & Tested**: Comes with TypeScript declarations and 100% test coverage[2]. +- **Authentication**: Supports personal access tokens, GitHub Apps, OAuth, and more. +- **Pagination & Error Handling**: Handles pagination and common error scenarios out of the box. +- **Extendable**: Supports plugins and custom hooks for advanced use cases[2]. + +## How to Use Octokit for GitHub Issue Export + +Install Octokit in your Node.js project: + +```bash +npm install @octokit/rest +``` + +Basic usage for creating and linking issues: + +```js +const { Octokit } = require("@octokit/rest"); + +// Authenticate with a personal access token +const octokit = new Octokit({ auth: process.env.GITHUB_TOKEN }); + +// Create a new issue +const { data: issue } = await octokit.issues.create({ + owner: "owner", + repo: "repo_name", + title: "Exported from Task Master", + body: "This issue was created by Task Master. [Task ID: 123]" +}); + +// Add a comment for bidirectional linking +await octokit.issues.createComment({ + owner: "owner", + repo: "repo_name", + issue_number: issue.number, + body: "Linked to Task Master task #123" +}); +``` + +## Alternatives + +- **node-github**: An older library, less maintained than Octokit, but still functional for basic API access[5]. +- **Raw HTTP Requests**: You can use `node-fetch` or `axios` to call the GitHub API directly, but you’ll need to handle authentication, pagination, and error handling yourself[3]. Octokit abstracts all of this for you. + +## Summary Table + +| Library | Language | API Coverage | Maintained | TypeScript | Docs/Support | +|-----------------|----------|--------------|------------|------------|--------------| +| Octokit | Node.js | Full | Yes | Yes | Excellent | +| node-github | Node.js | Full | No | No | Limited | +| Raw HTTP | Node.js | Full (manual)| N/A | N/A | N/A | + +**Recommendation:** Use Octokit for all GitHub API interactions in your Node.js project. It’s the official, most robust, and best-supported option for your use case[1][2]. + + +--- + +*Generated by Task Master Research Command* +*Timestamp: 2025-06-14T21:20:00.561Z* diff --git a/.taskmaster/docs/research/2025-06-14_test-save-functionality.md b/.taskmaster/docs/research/2025-06-14_test-save-functionality.md new file mode 100644 index 00000000..9a69a76c --- /dev/null +++ b/.taskmaster/docs/research/2025-06-14_test-save-functionality.md @@ -0,0 +1,76 @@ +--- +title: Research Session +query: "test save functionality" +date: 6/14/2025 +time: 5:50:23 PM +timestamp: 2025-06-14T21:50:23.797Z +exchanges: 1 +--- + +# Research Session + +## Initial Query + +**Question:** test save functionality + +**Response:** + +## Testing Save Functionality in a Task Management System + +**Core Steps for Testing Save Functionality** + +- Create or update a task in the system using the CLI or UI. +- Trigger the save operation (e.g., by issuing a command or clicking a save button). +- Verify that the data is correctly written to the persistent storage (e.g., `tasks.json`). +- Reload or re-query the data to ensure the saved changes persist and are accurately reflected. +- Validate that all required fields and relationships (such as dependencies and subtasks) are preserved and correctly structured. + +**Key Test Scenarios** + +- **Basic Save:** Add a new task and confirm it appears in `tasks.json` with all fields populated. +- **Update Save:** Modify an existing task (e.g., change status, description, or priority) and verify the changes are saved. +- **Subtask and Dependency Preservation:** Update a parent task and ensure that completed subtasks and dependency links remain intact, especially after using commands like `updateTask`. +- **Batch Operations:** Perform bulk updates or additions and confirm all affected tasks are saved correctly, with no data loss or corruption. +- **Validation:** Attempt to save invalid data and ensure the system rejects it or provides meaningful error messages, confirming validation logic is enforced. + +**Recommended Practices** + +- Use automated tests to simulate save operations for various scenarios, including edge cases (e.g., circular dependencies, missing required fields). +- After each save, reload the data and compare it to the expected state to ensure integrity. +- Log all save operations and errors for traceability and debugging. +- Regularly back up the `tasks.json` file to prevent data loss during testing and development. + +**Relevant Features from Industry Standards** + +- Task management systems typically provide robust save and update mechanisms, ensuring that all task attributes (including dependencies, subtasks, and comments) are consistently maintained[1][2][5]. +- Validation and error handling are critical to prevent corrupt or incomplete saves, especially when handling complex relationships or batch operations[1][5]. +- User feedback (such as success messages or error alerts) is important for confirming save actions and guiding users in case of issues[1][2]. + +**Example Test Case** + +1. Create a task with subtasks and dependencies. +2. Mark some subtasks as complete. +3. Use the `updateTask` command to modify the parent task. +4. Save and reload the data. +5. Assert that: + - The parent task reflects the updates. + - Completed subtasks remain marked as complete. + - Dependencies are unchanged and valid. + +**Summary Table: Save Functionality Test Aspects** + +| Aspect | What to Test | Expected Outcome | +|-----------------------|---------------------------------------------------|-----------------------------------------| +| Basic Save | Add/update task, save, reload | Data persists and matches expectations | +| Subtask Preservation | Update parent, check subtask status | Completed subtasks remain complete | +| Dependency Handling | Save with dependencies, reload | Dependencies are intact and valid | +| Batch Operations | Bulk save/update, reload | All changes persist, no data loss | +| Validation | Save invalid data | Error is raised, data not corrupted | + +These steps and scenarios ensure that the save functionality is robust, reliable, and meets the requirements of a modern task management system[1][2][5]. + + +--- + +*Generated by Task Master Research Command* +*Timestamp: 2025-06-14T21:50:23.797Z* diff --git a/.taskmaster/docs/research/2025-06-14_test-the-fix-for-duplicate-saves-final-test.md b/.taskmaster/docs/research/2025-06-14_test-the-fix-for-duplicate-saves-final-test.md new file mode 100644 index 00000000..bb83ec99 --- /dev/null +++ b/.taskmaster/docs/research/2025-06-14_test-the-fix-for-duplicate-saves-final-test.md @@ -0,0 +1,81 @@ +--- +title: Research Session +query: "test the fix for duplicate saves - final test" +date: 6/14/2025 +time: 6:10:00 PM +timestamp: 2025-06-14T22:10:00.394Z +exchanges: 1 +--- + +# Research Session + +## Initial Query + +**Question:** test the fix for duplicate saves - final test + +**Response:** + +## Steps to Test the Fix for Duplicate Saves + +**1. Prepare a Clean Test Environment** +- Ensure the tasks.json file and any related data stores are in a known, clean state with no pre-existing duplicate entries. +- Back up the current tasks.json in case rollback is needed. + +**2. Define Test Scenarios** +- Attempt to save a new task with unique data. +- Attempt to save a task with the same ID or unique identifier as an existing task (simulate a duplicate). +- Attempt to save a task with the same title or content but a different ID (to test if the fix is based on ID or content). +- Simultaneously trigger multiple save operations (if the system supports concurrency) to test race conditions. + +**3. Execute Manual and Automated Tests** +- Use the application's UI or API to create and save tasks as per the scenarios above. +- For each save operation, check the tasks.json file or the data store to verify: + - No duplicate entries are created. + - Existing tasks are not overwritten unless intended (e.g., for updates). + - The system returns appropriate error messages or warnings when a duplicate save is attempted. + +**4. Validate System Behavior** +- Confirm that after all test operations, each task in tasks.json is unique according to the defined criteria (ID, title, or other unique fields). +- If the system is designed to merge duplicates, verify that merging occurs as expected. +- If the system is designed to reject duplicates, ensure that the rejection is clear and no duplicate is present. + +**5. Test Edge Cases** +- Attempt to save tasks with minor variations (e.g., whitespace differences, case sensitivity) to ensure the duplicate detection logic is robust. +- Test with large numbers of tasks to ensure performance and correctness at scale. + +**6. Review Logs and Error Handling** +- Check application logs for any errors or warnings related to duplicate saves. +- Ensure that error handling is user-friendly and provides actionable feedback. + +**7. Regression Testing** +- Run the full suite of task operations (create, update, delete) to ensure the fix for duplicate saves does not introduce new issues elsewhere in the system. + +## Additional Best Practices + +- Communicate test results with the team to confirm the fix is effective and to prevent future regressions[1][2][5]. +- Consider implementing automated duplicate detection as part of the save operation to prevent future issues[2][3]. +- Document the test cases and results for future reference and audits. + +## Example Test Case Table + +| Test Scenario | Expected Result | Actual Result | Pass/Fail | +|--------------------------------------|-------------------------------|---------------|-----------| +| Save unique task | Task saved | | | +| Save duplicate task (same ID) | Duplicate rejected/merged | | | +| Save duplicate task (same title) | Duplicate rejected/merged | | | +| Simultaneous saves (race condition) | Only one unique task present | | | +| Save with minor variations | No false positives/negatives | | | + +Fill in the "Actual Result" and "Pass/Fail" columns during testing. + +## Action Items + +- Complete all test scenarios above. +- Document any issues found and retest after fixes. +- Confirm with stakeholders before closing the issue. + + +--- + +*Generated by Task Master Research Command* +*Timestamp: 2025-06-14T22:10:00.394Z* diff --git a/.taskmaster/docs/task-template-importing-prd.txt b/.taskmaster/docs/task-template-importing-prd.txt new file mode 100644 index 00000000..c0cf61f2 --- /dev/null +++ b/.taskmaster/docs/task-template-importing-prd.txt @@ -0,0 +1,471 @@ +# Task Template Importing System - Product Requirements Document + + +# Overview +The Task Template Importing system enables seamless integration of external task templates into the Task Master CLI through automatic file discovery. This system allows users to drop task template files into the tasks directory and immediately access them as new tag contexts without manual import commands or configuration. The solution addresses the need for multi-project task management, team collaboration through shared templates, and clean separation between permanent tasks and temporary project contexts. + +# Core Features +## Silent Task Template Discovery +- **What it does**: Automatically scans for `tasks_*.json` files in the tasks directory during tag operations +- **Why it's important**: Eliminates friction in adding new task contexts and enables zero-configuration workflow +- **How it works**: File pattern matching extracts tag names from filenames and validates against internal tag keys + +## External Tag Resolution System +- **What it does**: Provides fallback mechanism to external files when tags are not found in main tasks.json +- **Why it's important**: Maintains clean separation between core tasks and project-specific templates +- **How it works**: Tag resolution logic checks external files as secondary source while preserving main file precedence + +## Read-Only External Tag Access +- **What it does**: Allows viewing and switching to external tags while preventing modifications +- **Why it's important**: Protects template integrity and prevents accidental changes to shared templates +- **How it works**: All task modifications route to main tasks.json regardless of current tag context + +## Tag Precedence Management +- **What it does**: Ensures main tasks.json tags override external files with same tag names +- **Why it's important**: Prevents conflicts and maintains data integrity +- **How it works**: Priority system where main file tags take precedence over external file tags + +# User Experience +## User Personas +- **Solo Developer**: Manages multiple projects with different task contexts +- **Team Lead**: Shares standardized task templates across team members +- **Project Manager**: Organizes tasks by project phases or feature branches + +## Key User Flows +### Template Addition Flow +1. User receives or creates a `tasks_projectname.json` file +2. User drops file into `.taskmaster/tasks/` directory +3. Tag becomes immediately available via `task-master use-tag projectname` +4. User can list, view, and switch to external tag without configuration + +### Template Usage Flow +1. User runs `task-master tags` to see available tags including external ones +2. External tags display with `(imported)` indicator +3. User switches to external tag with `task-master use-tag projectname` +4. User can view tasks but modifications are routed to main tasks.json + +## UI/UX Considerations +- External tags clearly marked with `(imported)` suffix in listings +- Visual indicators distinguish between main and external tags +- Error messages guide users when external files are malformed +- Read-only warnings when attempting to modify external tag contexts + + + +# Technical Architecture +## System Components +1. **External File Discovery Engine** + - File pattern scanner for `tasks_*.json` files + - Tag name extraction from filenames using regex + - Dynamic tag registry combining main and external sources + - Error handling for malformed external files + +2. **Enhanced Tag Resolution System** + - Fallback mechanism to external files when tags not found in main tasks.json + - Precedence management ensuring main file tags override external files + - Read-only access enforcement for external tags + - Tag metadata preservation during discovery operations + +3. **Silent Discovery Integration** + - Automatic scanning during tag-related operations + - Seamless integration with existing tag management functions + - Zero-configuration workflow requiring no manual import commands + - Dynamic tag availability without restart requirements + +## Data Models + +### External Task File Structure +```json +{ + "meta": { + "projectName": "External Project Name", + "version": "1.0.0", + "templateSource": "external", + "createdAt": "ISO-8601 timestamp" + }, + "tags": { + "projectname": { + "meta": { + "name": "Project Name", + "description": "Project description", + "createdAt": "ISO-8601 timestamp" + }, + "tasks": [ + // Array of task objects + ] + }, + "master": { + // This section is ignored to prevent conflicts + } + } +} +``` + +### Enhanced Tag Registry Model +```json +{ + "mainTags": [ + { + "name": "master", + "source": "main", + "taskCount": 150, + "isActive": true + } + ], + "externalTags": [ + { + "name": "projectname", + "source": "external", + "filename": "tasks_projectname.json", + "taskCount": 25, + "isReadOnly": true + } + ] +} +``` + +## APIs and Integrations +1. **File System Discovery API** + - Directory scanning with pattern matching + - JSON file validation and parsing + - Error handling for corrupted or malformed files + - File modification time tracking for cache invalidation + +2. **Enhanced Tag Management API** + - `scanForExternalTaskFiles(projectRoot)` - Discover external template files + - `getExternalTagsFromFiles(projectRoot)` - Extract tag names from external files + - `readExternalTagData(projectRoot, tagName)` - Read specific external tag data + - `getAvailableTags(projectRoot)` - Combined main and external tag listing + +3. **Tag Resolution Enhancement** + - Modified `readJSON()` with external file fallback + - Enhanced `tags()` function with external tag display + - Updated `useTag()` function supporting external tag switching + - Read-only enforcement for external tag operations + +## Infrastructure Requirements +1. **File System Access** + - Read permissions for tasks directory + - JSON parsing capabilities + - Pattern matching and regex support + - Error handling for file system operations + +2. **Backward Compatibility** + - Existing tag operations continue unchanged + - Main tasks.json structure preserved + - No breaking changes to current workflows + - Graceful degradation when external files unavailable + +# Development Roadmap +## Phase 1: Core External File Discovery (Foundation) +1. **External File Scanner Implementation** + - Create `scanForExternalTaskFiles()` function in utils.js + - Implement file pattern matching for `tasks_*.json` files + - Add error handling for file system access issues + - Test with various filename patterns and edge cases + +2. **Tag Name Extraction System** + - Implement `getExternalTagsFromFiles()` function + - Create regex pattern for extracting tag names from filenames + - Add validation to ensure tag names match internal tag key format + - Handle special characters and invalid filename patterns + +3. **External Tag Data Reader** + - Create `readExternalTagData()` function + - Implement JSON parsing with error handling + - Add validation for required tag structure + - Ignore 'master' key in external files to prevent conflicts + +## Phase 2: Tag Resolution Enhancement (Core Integration) +1. **Enhanced Tag Registry** + - Implement `getAvailableTags()` function combining main and external sources + - Create tag metadata structure including source information + - Add deduplication logic prioritizing main tags over external + - Implement caching mechanism for performance optimization + +2. **Modified readJSON Function** + - Add external file fallback when tag not found in main tasks.json + - Maintain precedence rule: main tasks.json overrides external files + - Preserve existing error handling and validation patterns + - Ensure read-only access for external tags + +3. **Tag Listing Enhancement** + - Update `tags()` function to display external tags with `(imported)` indicator + - Show external tag metadata and task counts + - Maintain current tag highlighting and sorting functionality + - Add visual distinction between main and external tags + +## Phase 3: User Interface Integration (User Experience) +1. **Tag Switching Enhancement** + - Update `useTag()` function to support external tag switching + - Add read-only warnings when switching to external tags + - Update state.json with external tag context information + - Maintain current tag switching behavior for main tags + +2. **Error Handling and User Feedback** + - Implement comprehensive error messages for malformed external files + - Add user guidance for proper external file structure + - Create warnings for read-only operations on external tags + - Ensure graceful degradation when external files are corrupted + +3. **Documentation and Help Integration** + - Update command help text to include external tag information + - Add examples of external file structure and usage + - Create troubleshooting guide for common external file issues + - Document file naming conventions and best practices + +## Phase 4: Advanced Features and Optimization (Enhancement) +1. **Performance Optimization** + - Implement file modification time caching + - Add lazy loading for external tag data + - Optimize file scanning for directories with many files + - Create efficient tag resolution caching mechanism + +2. **Advanced External File Features** + - Support for nested external file directories + - Batch external file validation and reporting + - External file metadata display and management + - Integration with version control ignore patterns + +3. **Team Collaboration Features** + - Shared external file validation + - External file conflict detection and resolution + - Team template sharing guidelines and documentation + - Integration with git workflows for template management + +# Logical Dependency Chain +## Foundation Layer (Must Be Built First) +1. **External File Scanner** + - Core requirement for all other functionality + - Provides the discovery mechanism for external template files + - Must handle file system access and pattern matching reliably + +2. **Tag Name Extraction** + - Depends on file scanner functionality + - Required for identifying available external tags + - Must validate tag names against internal format requirements + +3. **External Tag Data Reader** + - Depends on tag name extraction + - Provides access to external tag content + - Must handle JSON parsing and validation safely + +## Integration Layer (Builds on Foundation) +4. **Enhanced Tag Registry** + - Depends on all foundation components + - Combines main and external tag sources + - Required for unified tag management across the system + +5. **Modified readJSON Function** + - Depends on enhanced tag registry + - Provides fallback mechanism for tag resolution + - Critical for maintaining backward compatibility + +6. **Tag Listing Enhancement** + - Depends on enhanced tag registry + - Provides user visibility into external tags + - Required for user discovery of available templates + +## User Experience Layer (Completes the Feature) +7. **Tag Switching Enhancement** + - Depends on modified readJSON and tag listing + - Enables user interaction with external tags + - Must enforce read-only access properly + +8. **Error Handling and User Feedback** + - Can be developed in parallel with other UX components + - Enhances reliability and user experience + - Should be integrated throughout development process + +9. **Documentation and Help Integration** + - Should be developed alongside implementation + - Required for user adoption and proper usage + - Can be completed in parallel with advanced features + +## Optimization Layer (Performance and Advanced Features) +10. **Performance Optimization** + - Can be developed after core functionality is stable + - Improves user experience with large numbers of external files + - Not blocking for initial release + +11. **Advanced External File Features** + - Can be developed independently after core features + - Enhances power user workflows + - Optional for initial release + +12. **Team Collaboration Features** + - Depends on stable core functionality + - Enhances team workflows and template sharing + - Can be prioritized based on user feedback + +# Risks and Mitigations +## Technical Challenges + +### File System Performance +**Risk**: Scanning for external files on every tag operation could impact performance with large directories. +**Mitigation**: +- Implement file modification time caching to avoid unnecessary rescans +- Use lazy loading for external tag data - only read when accessed +- Add configurable limits on number of external files to scan +- Optimize file pattern matching with efficient regex patterns + +### External File Corruption +**Risk**: Malformed or corrupted external JSON files could break tag operations. +**Mitigation**: +- Implement robust JSON parsing with comprehensive error handling +- Add file validation before attempting to parse external files +- Gracefully skip corrupted files and continue with valid ones +- Provide clear error messages guiding users to fix malformed files + +### Tag Name Conflicts +**Risk**: External files might contain tag names that conflict with main tasks.json tags. +**Mitigation**: +- Implement strict precedence rule: main tasks.json always overrides external files +- Add warnings when external tags are ignored due to conflicts +- Document naming conventions to avoid common conflicts +- Provide validation tools to check for potential conflicts + +## MVP Definition + +### Core Feature Scope +**Risk**: Including too many advanced features could delay the core functionality. +**Mitigation**: +- Define MVP as basic external file discovery + tag switching +- Focus on the silent discovery mechanism as the primary value proposition +- Defer advanced features like nested directories and batch operations +- Ensure each phase delivers complete, usable functionality + +### User Experience Complexity +**Risk**: The read-only nature of external tags might confuse users. +**Mitigation**: +- Provide clear visual indicators for external tags in all interfaces +- Add explicit warnings when users attempt to modify external tag contexts +- Document the read-only behavior and its rationale clearly +- Consider future enhancement for external tag modification workflows + +### Backward Compatibility +**Risk**: Changes to tag resolution logic might break existing workflows. +**Mitigation**: +- Maintain existing tag operations unchanged for main tasks.json +- Add external file support as enhancement, not replacement +- Test thoroughly with existing task structures and workflows +- Provide migration path if any breaking changes are necessary + +## Resource Constraints + +### Development Complexity +**Risk**: Integration with existing tag management system could be complex. +**Mitigation**: +- Phase implementation to minimize risk of breaking existing functionality +- Create comprehensive test suite covering both main and external tag scenarios +- Use feature flags to enable/disable external file support during development +- Implement thorough error handling to prevent system failures + +### File System Dependencies +**Risk**: Different operating systems might handle file operations differently. +**Mitigation**: +- Use Node.js built-in file system APIs for cross-platform compatibility +- Test on multiple operating systems (Windows, macOS, Linux) +- Handle file path separators and naming conventions properly +- Add fallback mechanisms for file system access issues + +### User Adoption +**Risk**: Users might not understand or adopt the external file template system. +**Mitigation**: +- Create clear documentation with practical examples +- Provide sample external template files for common use cases +- Integrate help and guidance directly into the CLI interface +- Gather user feedback early and iterate on the user experience + +# Appendix +## External File Naming Convention + +### Filename Pattern +- **Format**: `tasks_[tagname].json` +- **Examples**: `tasks_feature-auth.json`, `tasks_v2-migration.json`, `tasks_project-alpha.json` +- **Validation**: Tag name must match internal tag key format (alphanumeric, hyphens, underscores) + +### File Structure Requirements +```json +{ + "meta": { + "projectName": "Required: Human-readable project name", + "version": "Optional: Template version", + "templateSource": "Optional: Source identifier", + "createdAt": "Optional: ISO-8601 timestamp" + }, + "tags": { + "[tagname]": { + "meta": { + "name": "Required: Tag display name", + "description": "Optional: Tag description", + "createdAt": "Optional: ISO-8601 timestamp" + }, + "tasks": [ + // Required: Array of task objects following standard task structure + ] + } + } +} +``` + +## Implementation Functions Specification + +### Core Discovery Functions +```javascript +// Scan tasks directory for external template files +function scanForExternalTaskFiles(projectRoot) { + // Returns: Array of external file paths +} + +// Extract tag names from external filenames +function getExternalTagsFromFiles(projectRoot) { + // Returns: Array of external tag names +} + +// Read specific external tag data +function readExternalTagData(projectRoot, tagName) { + // Returns: Tag data object or null if not found +} + +// Get combined main and external tags +function getAvailableTags(projectRoot) { + // Returns: Combined tag registry with metadata +} +``` + +### Integration Points +```javascript +// Enhanced readJSON with external fallback +function readJSON(projectRoot, tag = null) { + // Modified to check external files when tag not found in main +} + +// Enhanced tags listing with external indicators +function tags(projectRoot, options = {}) { + // Modified to display external tags with (imported) suffix +} + +// Enhanced tag switching with external support +function useTag(projectRoot, tagName) { + // Modified to support switching to external tags (read-only) +} +``` + +## Error Handling Specifications + +### File System Errors +- **ENOENT**: External file not found - gracefully skip and continue +- **EACCES**: Permission denied - warn user and continue with available files +- **EISDIR**: Directory instead of file - skip and continue scanning + +### JSON Parsing Errors +- **SyntaxError**: Malformed JSON - skip file and log warning with filename +- **Missing required fields**: Skip file and provide specific error message +- **Invalid tag structure**: Skip file and guide user to correct format + +### Tag Conflict Resolution +- **Duplicate tag names**: Main tasks.json takes precedence, log warning +- **Invalid tag names**: Skip external file and provide naming guidance +- **Master key in external**: Ignore master key, process other tags normally + \ No newline at end of file diff --git a/.taskmaster/state.json b/.taskmaster/state.json index 3cef5c5a..1d0d2694 100644 --- a/.taskmaster/state.json +++ b/.taskmaster/state.json @@ -1,8 +1,9 @@ { "currentTag": "master", - "lastSwitched": "2025-06-14T00:46:38.351Z", + "lastSwitched": "2025-06-14T20:37:15.456Z", "branchTagMapping": { - "v017-adds": "v017-adds" + "v017-adds": "v017-adds", + "next": "next" }, "migrationNoticeShown": true } diff --git a/.taskmaster/tasks/task_001_test-tag.txt b/.taskmaster/tasks/task_001_test-tag.txt new file mode 100644 index 00000000..30aed9f2 --- /dev/null +++ b/.taskmaster/tasks/task_001_test-tag.txt @@ -0,0 +1,23 @@ +# Task ID: 1 +# Title: Implement TTS Flag for Taskmaster Commands +# Status: pending +# Dependencies: 16 (Not found) +# Priority: medium +# Description: Add text-to-speech functionality to taskmaster commands with configurable voice options and audio output settings. +# Details: +Implement TTS functionality including: +- Add --tts flag to all relevant taskmaster commands (list, show, generate, etc.) +- Integrate with system TTS engines (Windows SAPI, macOS say command, Linux espeak/festival) +- Create TTS configuration options in the configuration management system +- Add voice selection options (male/female, different languages if available) +- Implement audio output settings (volume, speed, pitch) +- Add TTS-specific error handling for cases where TTS is unavailable +- Create fallback behavior when TTS fails (silent failure or text output) +- Support for reading task titles, descriptions, and status updates aloud +- Add option to read entire task lists or individual task details +- Implement TTS for command confirmations and error messages +- Create TTS output formatting to make spoken text more natural (removing markdown, formatting numbers/dates appropriately) +- Add configuration option to enable/disable TTS globally + +# Test Strategy: +Test TTS functionality across different operating systems (Windows, macOS, Linux). Verify that the --tts flag works with all major commands. Test voice configuration options and ensure audio output settings are properly applied. Test error handling when TTS services are unavailable. Verify that text formatting for speech is natural and understandable. Test with various task content types including special characters, code snippets, and long descriptions. Ensure TTS can be disabled and enabled through configuration. diff --git a/.taskmaster/tasks/task_095.txt b/.taskmaster/tasks/task_095.txt deleted file mode 100644 index fec48871..00000000 --- a/.taskmaster/tasks/task_095.txt +++ /dev/null @@ -1,149 +0,0 @@ -# Task ID: 95 -# Title: Implement .taskmaster Directory Structure -# Status: done -# Dependencies: 1, 3, 4, 17 -# Priority: high -# Description: Consolidate all Task Master-managed files in user projects into a clean, centralized .taskmaster/ directory structure to improve organization and keep user project directories clean, based on GitHub issue #275. -# Details: -This task involves restructuring how Task Master organizes files within user projects to improve maintainability and keep project directories clean: - -1. Create a new `.taskmaster/` directory structure in user projects: - - Move task files from `tasks/` to `.taskmaster/tasks/` - - Move PRD files from `scripts/` to `.taskmaster/docs/` - - Move analysis reports to `.taskmaster/reports/` - - Move configuration from `.taskmasterconfig` to `.taskmaster/config.json` - - Create `.taskmaster/templates/` for user templates - -2. Update all Task Master code that creates/reads user files: - - Modify task file generation to use `.taskmaster/tasks/` - - Update PRD file handling to use `.taskmaster/docs/` - - Adjust report generation to save to `.taskmaster/reports/` - - Update configuration loading to look for `.taskmaster/config.json` - - Modify any path resolution logic in Task Master's codebase - -3. Ensure backward compatibility during migration: - - Implement path fallback logic that checks both old and new locations - - Add deprecation warnings when old paths are detected - - Create a migration command to help users transition to the new structure - - Preserve existing user data during migration - -4. Update the project initialization process: - - Modify the init command to create the new `.taskmaster/` directory structure - - Update default file creation to use new paths - -5. Benefits of the new structure: - - Keeps user project directories clean and organized - - Clearly separates Task Master files from user project files - - Makes it easier to add Task Master to .gitignore if desired - - Provides logical grouping of different file types - -6. Test thoroughly to ensure all functionality works with the new structure: - - Verify all Task Master commands work with the new paths - - Ensure backward compatibility functions correctly - - Test migration process preserves all user data - -7. Update documentation: - - Update README.md to reflect the new user file structure - - Add migration guide for existing users - - Document the benefits of the cleaner organization - -# Test Strategy: -1. Unit Testing: - - Create unit tests for path resolution that verify both new and old paths work - - Test configuration loading with both `.taskmasterconfig` and `.taskmaster/config.json` - - Verify the migration command correctly moves files and preserves content - - Test file creation in all new subdirectories - -2. Integration Testing: - - Run all existing integration tests with the new directory structure - - Verify that all Task Master commands function correctly with new paths - - Test backward compatibility by running commands with old file structure - -3. Migration Testing: - - Test the migration process on sample projects with existing tasks and files - - Verify all tasks, PRDs, reports, and configurations are correctly moved - - Ensure no data loss occurs during migration - - Test migration with partial existing structures (e.g., only tasks/ exists) - -4. User Workflow Testing: - - Test complete workflows: init → create tasks → generate reports → update PRDs - - Verify all generated files go to correct locations in `.taskmaster/` - - Test that user project directories remain clean - -5. Manual Testing: - - Perform end-to-end testing with the new structure - - Create, update, and delete tasks using the new structure - - Generate reports and verify they're saved to `.taskmaster/reports/` - -6. Documentation Verification: - - Review all documentation to ensure it accurately reflects the new user file structure - - Verify the migration guide provides clear instructions - -7. Regression Testing: - - Run the full test suite to ensure no regressions were introduced - - Verify existing user projects continue to work during transition period - -# Subtasks: -## 1. Create .taskmaster directory structure [done] -### Dependencies: None -### Description: Create the new .taskmaster directory and move existing files to their new locations -### Details: -Create a new .taskmaster/ directory in the project root. Move the tasks/ directory to .taskmaster/tasks/. Move the scripts/ directory to .taskmaster/scripts/. Move the .taskmasterconfig file to .taskmaster/config.json. Ensure proper file permissions are maintained during the move. - -Create the new .taskmaster/ directory structure in user projects with subdirectories for tasks/, docs/, reports/, and templates/. Move the existing .taskmasterconfig file to .taskmaster/config.json. Since this project is also a Task Master user, move this project's current user files (tasks.json, PRD files, etc.) to the new .taskmaster/ structure to test the implementation. This subtask focuses on user project directory structure, not Task Master source code relocation. - - -## 2. Update Task Master code for new user file paths [done] -### Dependencies: 95.1 -### Description: Modify all Task Master code that creates or reads user project files to use the new .taskmaster structure -### Details: -Update Task Master's file handling code to use the new paths: tasks in .taskmaster/tasks/, PRD files in .taskmaster/docs/, reports in .taskmaster/reports/, and config in .taskmaster/config.json. Modify path resolution logic throughout the Task Master codebase to reference the new user file locations. - -## 3. Update task file generation system [done] -### Dependencies: 95.1 -### Description: Modify the task file generation system to use the new directory structure -### Details: -Update the task file generation system to create and read task files from .taskmaster/tasks/ instead of tasks/. Ensure all template paths are updated. Modify any path resolution logic specific to task file handling. - -## 4. Implement backward compatibility logic [done] -### Dependencies: 95.2, 95.3 -### Description: Add fallback mechanisms to support both old and new file locations during transition -### Details: -Implement path fallback logic that checks both old and new locations when files aren't found. Add deprecation warnings when old paths are used, informing users about the new structure. Ensure error messages are clear about the transition. - -## 5. Create migration command for users [done] -### Dependencies: 95.1, 95.4 -### Description: Develop a Task Master command to help users transition their existing projects to the new structure -### Details: -Create a 'taskmaster migrate' command that automatically moves user files from old locations to the new .taskmaster structure. Move tasks/ to .taskmaster/tasks/, scripts/prd.txt to .taskmaster/docs/, reports to .taskmaster/reports/, and .taskmasterconfig to .taskmaster/config.json. Include backup functionality and validation to ensure migration completed successfully. - -## 6. Update project initialization process [done] -### Dependencies: 95.1 -### Description: Modify the init command to create the new directory structure for new projects -### Details: -Update the init command to create the .taskmaster directory and its subdirectories (tasks/, docs/, reports/, templates/). Modify default file creation to use the new paths. Ensure new projects are created with the correct structure from the start. - -## 7. Update PRD and report file handling [done] -### Dependencies: 95.2, 95.6 -### Description: Modify PRD file creation and report generation to use the new directory structure -### Details: -Update PRD file handling to create and read files from .taskmaster/docs/ instead of scripts/. Modify report generation (like task-complexity-report.json) to save to .taskmaster/reports/. Ensure all file operations use the new paths consistently. - -## 8. Update documentation and create migration guide [done] -### Dependencies: 95.5, 95.6, 95.7 -### Description: Update all documentation to reflect the new directory structure and provide migration guidance -### Details: -Update README.md and other documentation to reflect the new .taskmaster structure for user projects. Create a comprehensive migration guide explaining the benefits of the new structure and how to migrate existing projects. Include examples of the new directory layout and explain how it keeps user project directories clean. - -## 9. Add templates directory support [done] -### Dependencies: 95.2, 95.6 -### Description: Implement support for user templates in the .taskmaster/templates/ directory -### Details: -Create functionality to support user-defined templates in .taskmaster/templates/. Allow users to store custom task templates, PRD templates, or other reusable files. Update Task Master commands to recognize and use templates from this directory when available. - -## 10. Verify clean user project directories [done] -### Dependencies: 95.8, 95.9 -### Description: Ensure the new structure keeps user project root directories clean and organized -### Details: -Validate that after implementing the new structure, user project root directories only contain their actual project files plus the single .taskmaster/ directory. Verify that no Task Master files are created outside of .taskmaster/. Test that users can easily add .taskmaster/ to .gitignore if they choose to exclude Task Master files from version control. - diff --git a/.taskmaster/tasks/task_096.txt b/.taskmaster/tasks/task_096.txt deleted file mode 100644 index 3468bfa5..00000000 --- a/.taskmaster/tasks/task_096.txt +++ /dev/null @@ -1,37 +0,0 @@ -# Task ID: 96 -# Title: Create Export Command for On-Demand Task File and PDF Generation -# Status: pending -# Dependencies: 2, 4, 95 -# Priority: medium -# Description: Develop an 'export' CLI command that generates task files and comprehensive PDF exports on-demand, replacing automatic file generation and providing users with flexible export options. -# Details: -Implement a new 'export' command in the CLI that supports two primary modes: (1) generating individual task files on-demand (superseding the current automatic generation system), and (2) producing a comprehensive PDF export. The PDF should include: a first page with the output of 'tm list --with-subtasks', followed by individual pages for each task (using 'tm show ') and each subtask (using 'tm show '). Integrate PDF generation using a robust library (e.g., pdfkit, Puppeteer, or jsPDF) to ensure high-quality output and proper pagination. Refactor or disable any existing automatic file generation logic to avoid performance overhead. Ensure the command supports flexible output paths and options for exporting only files, only PDF, or both. Update documentation and help output to reflect the new export capabilities. Consider concurrency and error handling for large projects. Ensure the export process is efficient and does not block the main CLI thread unnecessarily. - -# Test Strategy: -1. Run the 'export' command with various options and verify that task files are generated only on-demand, not automatically. 2. Generate a PDF export and confirm that the first page contains the correct 'tm list --with-subtasks' output, and that each subsequent page accurately reflects the output of 'tm show ' and 'tm show ' for all tasks and subtasks. 3. Test exporting in projects with large numbers of tasks and subtasks to ensure performance and correctness. 4. Attempt exports with invalid paths or missing data to verify robust error handling. 5. Confirm that no automatic file generation occurs during normal task operations. 6. Review CLI help output and documentation for accuracy regarding the new export functionality. - -# Subtasks: -## 1. Remove Automatic Task File Generation from Task Operations [pending] -### Dependencies: None -### Description: Eliminate all calls to generateTaskFiles() from task operations such as add-task, remove-task, set-status, and similar commands to prevent unnecessary performance overhead. -### Details: -Audit the codebase for any automatic invocations of generateTaskFiles() and remove or refactor them to ensure task files are not generated automatically during task operations. - -## 2. Implement Export Command Infrastructure with On-Demand Task File Generation [pending] -### Dependencies: 96.1 -### Description: Develop the CLI 'export' command infrastructure, enabling users to generate task files on-demand by invoking the preserved generateTaskFiles function only when requested. -### Details: -Create the export command with options for output paths and modes (files, PDF, or both). Ensure generateTaskFiles is only called within this command and not elsewhere. - -## 3. Implement Comprehensive PDF Export Functionality [pending] -### Dependencies: 96.2 -### Description: Add PDF export capability to the export command, generating a structured PDF with a first page listing all tasks and subtasks, followed by individual pages for each task and subtask, using a robust PDF library. -### Details: -Integrate a PDF generation library (e.g., pdfkit, Puppeteer, or jsPDF). Ensure the PDF includes the output of 'tm list --with-subtasks' on the first page, and uses 'tm show ' and 'tm show ' for subsequent pages. Handle pagination, concurrency, and error handling for large projects. - -## 4. Update Documentation, Tests, and CLI Help for Export Workflow [pending] -### Dependencies: 96.2, 96.3 -### Description: Revise all relevant documentation, automated tests, and CLI help output to reflect the new export-based workflow and available options. -### Details: -Update user guides, README files, and CLI help text. Add or modify tests to cover the new export command and its options. Ensure all documentation accurately describes the new workflow and usage. - diff --git a/.taskmaster/tasks/tasks.json b/.taskmaster/tasks/tasks.json index d7e789dc..13d04984 100644 --- a/.taskmaster/tasks/tasks.json +++ b/.taskmaster/tasks/tasks.json @@ -6163,7 +6163,7 @@ "id": 101, "title": "Implement GitHub Issue Export Feature with Bidirectional Linking", "description": "Add a 'github-export' command that creates GitHub issues from Task Master tasks and establishes bidirectional linking between tasks and issues. This complements the import feature by enabling full GitHub integration workflow.", - "details": "## Core Problem Statement\n\nUsers need the ability to export Task Master tasks to GitHub issues to:\n\n1. **Share Tasks with Team**: Convert internal tasks to GitHub issues for team collaboration\n2. **Track Progress Publicly**: Make task progress visible in GitHub project boards\n3. **Integrate with GitHub Workflow**: Connect Task Master planning with GitHub development workflow\n4. **Maintain Synchronization**: Keep tasks and issues linked for status updates\n5. **Enable Hybrid Workflow**: Allow teams to work with both Task Master and GitHub seamlessly\n\n## Core Requirements\n\n### 1. GitHub Export Command\n- **Command**: `task-master github-export --id= --repo= [options]`\n- **Functionality**: Create GitHub issue from Task Master task\n- **Authentication**: Use GitHub Personal Access Token or OAuth\n- **Repository Target**: Support any accessible GitHub repository\n\n### 2. Bidirectional Linking System\n- **Task → Issue**: Store GitHub issue URL in task metadata\n- **Issue → Task**: Include Task Master reference in GitHub issue description\n- **Link Validation**: Verify links remain valid and accessible\n- **Link Display**: Show GitHub links in task views and vice versa\n\n### 3. Content Mapping and Formatting\n- **Title Mapping**: Task title → GitHub issue title\n- **Description Mapping**: Task description → GitHub issue description\n- **Details Conversion**: Convert Task Master details to GitHub markdown\n- **Metadata Preservation**: Include Task Master ID, priority, status in issue\n- **Subtask Handling**: Convert subtasks to GitHub issue checklist or separate issues\n\n### 4. Advanced Export Options\n- **Selective Export**: Choose which task fields to include\n- **Template Customization**: Custom GitHub issue templates\n- **Label Management**: Map Task Master priorities/tags to GitHub labels\n- **Assignee Mapping**: Map Task Master assignments to GitHub assignees\n- **Milestone Integration**: Connect tasks to GitHub milestones\n\n## Technical Implementation Requirements\n\n### 1. GitHub API Integration\n```javascript\n// Core export service\nclass GitHubExportService {\n constructor(token, baseURL = 'https://api.github.com') {\n this.token = token;\n this.baseURL = baseURL;\n this.rateLimiter = new RateLimiter();\n }\n \n async exportTask(task, repoOwner, repoName, options = {}) {\n // Validate repository access\n // Format task content for GitHub\n // Create GitHub issue via API\n // Update task with GitHub link\n // Return export result\n }\n \n async updateTaskWithGitHubLink(taskId, issueUrl) {\n // Add GitHub link to task metadata\n // Update task file with link reference\n // Regenerate task files if needed\n }\n}\n```\n\n### 2. Content Formatting System\n```javascript\nclass TaskToGitHubFormatter {\n formatIssueTitle(task) {\n return `[Task ${task.id}] ${task.title}`;\n }\n \n formatIssueDescription(task) {\n let description = `# ${task.title}\\n\\n`;\n description += `**Task Master ID**: ${task.id}\\n`;\n description += `**Priority**: ${task.priority}\\n`;\n description += `**Status**: ${task.status}\\n\\n`;\n \n if (task.description) {\n description += `## Description\\n${task.description}\\n\\n`;\n }\n \n if (task.details) {\n description += `## Implementation Details\\n${task.details}\\n\\n`;\n }\n \n if (task.subtasks && task.subtasks.length > 0) {\n description += `## Subtasks\\n`;\n task.subtasks.forEach(subtask => {\n const checked = subtask.status === 'done' ? 'x' : ' ';\n description += `- [${checked}] ${subtask.title}\\n`;\n });\n }\n \n description += `\\n---\\n*Exported from Task Master*`;\n return description;\n }\n}\n```\n\n### 3. Bidirectional Link Management\n```javascript\nclass LinkManager {\n async addGitHubLinkToTask(taskId, issueUrl, issueNumber) {\n const task = await getTask(taskId);\n \n if (!task.metadata) task.metadata = {};\n task.metadata.githubIssue = {\n url: issueUrl,\n number: issueNumber,\n exportedAt: new Date().toISOString(),\n repository: this.extractRepoFromUrl(issueUrl)\n };\n \n await updateTask(taskId, task);\n await regenerateTaskFiles();\n }\n \n async validateGitHubLink(issueUrl) {\n // Check if GitHub issue still exists\n // Verify access permissions\n // Return link status\n }\n \n generateTaskMasterReference(taskId, projectName) {\n return `\\n\\n---\\n**Task Master Reference**: Task #${taskId} in project \"${projectName}\"`;\n }\n}\n```\n\n### 4. Command Line Interface\n```javascript\n// In commands.js\nprogram\n .command('github-export')\n .description('Export Task Master task to GitHub issue')\n .requiredOption('-i, --id ', 'Task ID to export')\n .requiredOption('-r, --repo ', 'Target GitHub repository')\n .option('-t, --token ', 'GitHub Personal Access Token (or use GITHUB_TOKEN env var)')\n .option('--title ', 'Override issue title')\n .option('--labels <labels>', 'Comma-separated list of GitHub labels')\n .option('--assignees <assignees>', 'Comma-separated list of GitHub usernames')\n .option('--milestone <milestone>', 'GitHub milestone number or title')\n .option('--template <template>', 'Custom issue template file')\n .option('--include-subtasks', 'Export subtasks as checklist items')\n .option('--separate-subtasks', 'Create separate issues for subtasks')\n .option('--dry-run', 'Preview the issue content without creating it')\n .option('--force', 'Overwrite existing GitHub link if present')\n .action(async (options) => {\n await handleGitHubExport(options);\n });\n```\n\n### 5. MCP Tool Integration\n```javascript\n// MCP tool for github-export\nexport function registerGitHubExportTool(server) {\n server.addTool({\n name: \"github_export_task\",\n description: \"Export a Task Master task to GitHub issue with bidirectional linking\",\n parameters: {\n type: \"object\",\n properties: {\n taskId: { type: \"string\", description: \"Task ID to export\" },\n repository: { type: \"string\", description: \"GitHub repository (owner/repo)\" },\n token: { type: \"string\", description: \"GitHub Personal Access Token\" },\n options: {\n type: \"object\",\n properties: {\n title: { type: \"string\", description: \"Override issue title\" },\n labels: { type: \"array\", items: { type: \"string\" } },\n assignees: { type: \"array\", items: { type: \"string\" } },\n milestone: { type: \"string\", description: \"Milestone number or title\" },\n includeSubtasks: { type: \"boolean\", description: \"Include subtasks as checklist\" },\n separateSubtasks: { type: \"boolean\", description: \"Create separate issues for subtasks\" },\n dryRun: { type: \"boolean\", description: \"Preview without creating\" }\n }\n }\n },\n required: [\"taskId\", \"repository\"]\n },\n execute: async (args) => {\n return await gitHubExportDirect(args);\n }\n });\n}\n```\n\n## Advanced Features\n\n### 1. Batch Export\n- Export multiple tasks at once\n- Maintain relationships between exported issues\n- Progress tracking for bulk operations\n- Rollback capability for failed exports\n\n### 2. Synchronization Features\n- **Status Sync**: Update Task Master when GitHub issue status changes\n- **Comment Sync**: Sync comments between Task Master and GitHub\n- **Webhook Integration**: Real-time updates via GitHub webhooks\n- **Conflict Resolution**: Handle conflicting updates gracefully\n\n### 3. Template System\n```javascript\n// Custom export templates\nconst issueTemplates = {\n bug: {\n title: \"[BUG] {task.title}\",\n labels: [\"bug\", \"task-master\"],\n body: `## Bug Description\\n{task.description}\\n\\n## Steps to Reproduce\\n{task.details}`\n },\n feature: {\n title: \"[FEATURE] {task.title}\",\n labels: [\"enhancement\", \"task-master\"],\n body: `## Feature Request\\n{task.description}\\n\\n## Implementation Details\\n{task.details}`\n }\n};\n```\n\n### 4. Integration with GitHub Projects\n- Automatically add exported issues to GitHub project boards\n- Map Task Master status to GitHub project columns\n- Sync priority levels with GitHub project priorities\n\n## Error Handling and Edge Cases\n\n### 1. Authentication Issues\n- Invalid or expired GitHub tokens\n- Insufficient repository permissions\n- Rate limiting and quota management\n\n### 2. Repository Issues\n- Non-existent repositories\n- Private repository access\n- Repository permission changes\n\n### 3. Content Issues\n- Task content too large for GitHub issue\n- Invalid characters in titles or descriptions\n- Markdown formatting conflicts\n\n### 4. Link Management Issues\n- Broken or invalid GitHub links\n- Deleted GitHub issues\n- Repository transfers or renames\n\n## Testing Strategy\n\n### 1. Unit Tests\n- GitHub API client functionality\n- Content formatting and conversion\n- Link management operations\n- Error handling scenarios\n\n### 2. Integration Tests\n- End-to-end export workflow\n- Bidirectional linking verification\n- GitHub API integration\n- Authentication flow testing\n\n### 3. Performance Tests\n- Bulk export operations\n- Rate limiting compliance\n- Large task content handling\n- Concurrent export operations\n\n## Security Considerations\n\n### 1. Token Management\n- Secure storage of GitHub tokens\n- Token validation and refresh\n- Scope limitation and permissions\n- Environment variable protection\n\n### 2. Data Privacy\n- Sensitive information filtering\n- Private repository handling\n- User consent for public exports\n- Audit logging for exports\n\n## Documentation Requirements\n\n### 1. User Guide\n- Setup and authentication instructions\n- Export workflow examples\n- Troubleshooting common issues\n- Best practices for GitHub integration\n\n### 2. API Documentation\n- MCP tool reference\n- CLI command documentation\n- Configuration options\n- Integration examples\n\n### 3. Developer Guide\n- Extension points for custom templates\n- Webhook setup instructions\n- Advanced configuration options\n- Contributing guidelines", + "details": "## Core Problem Statement\n\nUsers need the ability to export Task Master tasks to GitHub issues to:\n\n1. **Share Tasks with Team**: Convert internal tasks to GitHub issues for team collaboration\n2. **Track Progress Publicly**: Make task progress visible in GitHub project boards\n3. **Integrate with GitHub Workflow**: Connect Task Master planning with GitHub development workflow\n4. **Maintain Synchronization**: Keep tasks and issues linked for status updates\n5. **Enable Hybrid Workflow**: Allow teams to work with both Task Master and GitHub seamlessly\n\n## Core Requirements\n\n### 1. GitHub Export Command\n- **Command**: `task-master github-export --id=<taskId> --repo=<owner/repo> [options]`\n- **Functionality**: Create GitHub issue from Task Master task\n- **Authentication**: Use GitHub Personal Access Token or OAuth\n- **Repository Target**: Support any accessible GitHub repository\n\n### 2. Bidirectional Linking System\n- **Task → Issue**: Store GitHub issue URL in task metadata\n- **Issue → Task**: Include Task Master reference in GitHub issue description\n- **Link Validation**: Verify links remain valid and accessible\n- **Link Display**: Show GitHub links in task views and vice versa\n\n### 3. Content Mapping and Formatting\n- **Title Mapping**: Task title → GitHub issue title\n- **Description Mapping**: Task description → GitHub issue description\n- **Details Conversion**: Convert Task Master details to GitHub markdown\n- **Metadata Preservation**: Include Task Master ID, priority, status in issue\n- **Subtask Handling**: Convert subtasks to GitHub issue checklist or separate issues\n\n### 4. Advanced Export Options\n- **Selective Export**: Choose which task fields to include\n- **Template Customization**: Custom GitHub issue templates\n- **Label Management**: Map Task Master priorities/tags to GitHub labels\n- **Assignee Mapping**: Map Task Master assignments to GitHub assignees\n- **Milestone Integration**: Connect tasks to GitHub milestones\n\n## Technical Implementation Requirements\n\n### 1. GitHub API Integration\n```javascript\n// Core export service\nclass GitHubExportService {\n constructor(token, baseURL = 'https://api.github.com') {\n this.token = token;\n this.baseURL = baseURL;\n this.rateLimiter = new RateLimiter();\n }\n \n async exportTask(task, repoOwner, repoName, options = {}) {\n // Validate repository access\n // Format task content for GitHub\n // Create GitHub issue via API\n // Update task with GitHub link\n // Return export result\n }\n \n async updateTaskWithGitHubLink(taskId, issueUrl) {\n // Add GitHub link to task metadata\n // Update task file with link reference\n // Regenerate task files if needed\n }\n}\n```\n\n### 2. Content Formatting System\n```javascript\nclass TaskToGitHubFormatter {\n formatIssueTitle(task) {\n return `[Task ${task.id}] ${task.title}`;\n }\n \n formatIssueDescription(task) {\n let description = `# ${task.title}\\n\\n`;\n description += `**Task Master ID**: ${task.id}\\n`;\n description += `**Priority**: ${task.priority}\\n`;\n description += `**Status**: ${task.status}\\n\\n`;\n \n if (task.description) {\n description += `## Description\\n${task.description}\\n\\n`;\n }\n \n if (task.details) {\n description += `## Implementation Details\\n${task.details}\\n\\n`;\n }\n \n if (task.subtasks && task.subtasks.length > 0) {\n description += `## Subtasks\\n`;\n task.subtasks.forEach(subtask => {\n const checked = subtask.status === 'done' ? 'x' : ' ';\n description += `- [${checked}] ${subtask.title}\\n`;\n });\n }\n \n description += `\\n---\\n*Exported from Task Master*`;\n return description;\n }\n}\n```\n\n### 3. Bidirectional Link Management\n```javascript\nclass LinkManager {\n async addGitHubLinkToTask(taskId, issueUrl, issueNumber) {\n const task = await getTask(taskId);\n \n if (!task.metadata) task.metadata = {};\n task.metadata.githubIssue = {\n url: issueUrl,\n number: issueNumber,\n exportedAt: new Date().toISOString(),\n repository: this.extractRepoFromUrl(issueUrl)\n };\n \n await updateTask(taskId, task);\n await regenerateTaskFiles();\n }\n \n async validateGitHubLink(issueUrl) {\n // Check if GitHub issue still exists\n // Verify access permissions\n // Return link status\n }\n \n generateTaskMasterReference(taskId, projectName) {\n return `\\n\\n---\\n**Task Master Reference**: Task #${taskId} in project \"${projectName}\"`;\n }\n}\n```\n\n### 4. Command Line Interface\n```javascript\n// In commands.js\nprogram\n .command('github-export')\n .description('Export Task Master task to GitHub issue')\n .requiredOption('-i, --id <taskId>', 'Task ID to export')\n .requiredOption('-r, --repo <owner/repo>', 'Target GitHub repository')\n .option('-t, --token <token>', 'GitHub Personal Access Token (or use GITHUB_TOKEN env var)')\n .option('--title <title>', 'Override issue title')\n .option('--labels <labels>', 'Comma-separated list of GitHub labels')\n .option('--assignees <assignees>', 'Comma-separated list of GitHub usernames')\n .option('--milestone <milestone>', 'GitHub milestone number or title')\n .option('--template <template>', 'Custom issue template file')\n .option('--include-subtasks', 'Export subtasks as checklist items')\n .option('--separate-subtasks', 'Create separate issues for subtasks')\n .option('--dry-run', 'Preview the issue content without creating it')\n .option('--force', 'Overwrite existing GitHub link if present')\n .action(async (options) => {\n await handleGitHubExport(options);\n });\n```\n\n### 5. MCP Tool Integration\n```javascript\n// MCP tool for github-export\nexport function registerGitHubExportTool(server) {\n server.addTool({\n name: \"github_export_task\",\n description: \"Export a Task Master task to GitHub issue with bidirectional linking\",\n parameters: {\n type: \"object\",\n properties: {\n taskId: { type: \"string\", description: \"Task ID to export\" },\n repository: { type: \"string\", description: \"GitHub repository (owner/repo)\" },\n token: { type: \"string\", description: \"GitHub Personal Access Token\" },\n options: {\n type: \"object\",\n properties: {\n title: { type: \"string\", description: \"Override issue title\" },\n labels: { type: \"array\", items: { type: \"string\" } },\n assignees: { type: \"array\", items: { type: \"string\" } },\n milestone: { type: \"string\", description: \"Milestone number or title\" },\n includeSubtasks: { type: \"boolean\", description: \"Include subtasks as checklist\" },\n separateSubtasks: { type: \"boolean\", description: \"Create separate issues for subtasks\" },\n dryRun: { type: \"boolean\", description: \"Preview without creating\" }\n }\n }\n },\n required: [\"taskId\", \"repository\"]\n },\n execute: async (args) => {\n return await gitHubExportDirect(args);\n }\n });\n}\n```\n\n## Advanced Features\n\n### 1. Batch Export\n- Export multiple tasks at once\n- Maintain relationships between exported issues\n- Progress tracking for bulk operations\n- Rollback capability for failed exports\n\n### 2. Synchronization Features\n- **Status Sync**: Update Task Master when GitHub issue status changes\n- **Comment Sync**: Sync comments between Task Master and GitHub\n- **Webhook Integration**: Real-time updates via GitHub webhooks\n- **Conflict Resolution**: Handle conflicting updates gracefully\n\n### 3. Template System\n```javascript\n// Custom export templates\nconst issueTemplates = {\n bug: {\n title: \"[BUG] {task.title}\",\n labels: [\"bug\", \"task-master\"],\n body: `## Bug Description\\n{task.description}\\n\\n## Steps to Reproduce\\n{task.details}`\n },\n feature: {\n title: \"[FEATURE] {task.title}\",\n labels: [\"enhancement\", \"task-master\"],\n body: `## Feature Request\\n{task.description}\\n\\n## Implementation Details\\n{task.details}`\n }\n};\n```\n\n### 4. Integration with GitHub Projects\n- Automatically add exported issues to GitHub project boards\n- Map Task Master status to GitHub project columns\n- Sync priority levels with GitHub project priorities\n\n## Error Handling and Edge Cases\n\n### 1. Authentication Issues\n- Invalid or expired GitHub tokens\n- Insufficient repository permissions\n- Rate limiting and quota management\n\n### 2. Repository Issues\n- Non-existent repositories\n- Private repository access\n- Repository permission changes\n\n### 3. Content Issues\n- Task content too large for GitHub issue\n- Invalid characters in titles or descriptions\n- Markdown formatting conflicts\n\n### 4. Link Management Issues\n- Broken or invalid GitHub links\n- Deleted GitHub issues\n- Repository transfers or renames\n\n## Testing Strategy\n\n### 1. Unit Tests\n- GitHub API client functionality\n- Content formatting and conversion\n- Link management operations\n- Error handling scenarios\n\n### 2. Integration Tests\n- End-to-end export workflow\n- Bidirectional linking verification\n- GitHub API integration\n- Authentication flow testing\n\n### 3. Performance Tests\n- Bulk export operations\n- Rate limiting compliance\n- Large task content handling\n- Concurrent export operations\n\n## Security Considerations\n\n### 1. Token Management\n- Secure storage of GitHub tokens\n- Token validation and refresh\n- Scope limitation and permissions\n- Environment variable protection\n\n### 2. Data Privacy\n- Sensitive information filtering\n- Private repository handling\n- User consent for public exports\n- Audit logging for exports\n\n## Documentation Requirements\n\n### 1. User Guide\n- Setup and authentication instructions\n- Export workflow examples\n- Troubleshooting common issues\n- Best practices for GitHub integration\n\n### 2. API Documentation\n- MCP tool reference\n- CLI command documentation\n- Configuration options\n- Integration examples\n\n### 3. Developer Guide\n- Extension points for custom templates\n- Webhook setup instructions\n- Advanced configuration options\n- Contributing guidelines\n<info added on 2025-06-14T21:18:58.143Z>\n## Library Recommendations and Technical Stack\n\n### Primary GitHub API Library: PyGithub\n\nBased on research conducted on 6/14/2025, **PyGithub** is the recommended library for implementing the GitHub export functionality. This is the most widely used and well-documented Python library for accessing the GitHub REST API v3.\n\n#### Key Benefits:\n- **Clean Object-Oriented Interface**: Simplifies repository, issue, and user management\n- **Built-in Authentication**: Easy personal access token integration\n- **Automatic Pagination & Rate Limiting**: Handles API complexities automatically\n- **Comprehensive Issue Management**: Full support for creating, updating, and linking issues\n- **Active Maintenance**: Well-supported with excellent documentation\n\n#### Installation:\n```bash\npip install PyGithub\n```\n\n#### Integration Example:\n```python\nfrom github import Github, Auth\n\nclass GitHubExportService:\n def __init__(self, token):\n auth = Auth.Token(token)\n self.github = Github(auth=auth)\n \n async def export_task_to_issue(self, task, repo_name):\n repo = self.github.get_repo(repo_name)\n \n # Create issue with formatted content\n issue = repo.create_issue(\n title=f\"[Task {task.id}] {task.title}\",\n body=self.format_task_for_github(task),\n labels=self.map_task_labels(task)\n )\n \n # Establish bidirectional link\n await self.add_github_link_to_task(task.id, issue.html_url)\n \n return issue\n \n def format_task_for_github(self, task):\n body = f\"**Task Master ID**: {task.id}\\n\"\n body += f\"**Priority**: {task.priority}\\n\"\n body += f\"**Status**: {task.status}\\n\\n\"\n \n if task.description:\n body += f\"## Description\\n{task.description}\\n\\n\"\n \n if task.details:\n body += f\"## Implementation Details\\n{task.details}\\n\\n\"\n \n body += \"\\n---\\n*Exported from Task Master*\"\n return body\n```\n\n### Alternative Considerations\n\nWhile raw `requests` library could be used for direct API calls, PyGithub is strongly preferred because it:\n- Eliminates boilerplate authentication and error handling code\n- Provides built-in pagination support\n- Offers better maintainability and readability\n- Reduces likelihood of API integration bugs\n\n### Security and Token Management\n\nWhen implementing with PyGithub:\n- Store GitHub tokens in environment variables\n- Use token scoping to limit permissions\n- Implement token validation and refresh logic\n- Add audit logging for all GitHub operations\n\nThis library choice aligns with the project's need for reliable, maintainable GitHub integration while minimizing implementation complexity.\n</info added on 2025-06-14T21:18:58.143Z>\n<info added on 2025-06-14T21:20:39.682Z>\n## Research Session - 6/14/2025 5:20:03 PM\n\n**Initial Query:** should i be using any specific libraries for this?\n\n**Response:** HELL YEAH PARTNER\n\nFor implementing a GitHub Issue export feature with bidirectional linking in your project, you absolutely should use a dedicated library for interacting with the GitHub API. This will save you a ton of time, reduce boilerplate, and help you avoid common pitfalls with authentication, pagination, and error handling.\n\n## Recommended Library: PyGithub\n\n- **PyGithub** is the most widely used and well-documented Python library for accessing the GitHub REST API v3. It allows you to manage repositories, issues, user profiles, and more, all with a clean, object-oriented interface[1][2][3][5].\n- It supports all the operations you'll need for your export feature, including creating issues, updating them, and managing references for bidirectional linking.\n\n### Key Features\n\n- **Authentication**: Easily authenticate with a personal access token.\n- **Issue Management**: Create, update, and link issues programmatically.\n- **Repository Access**: Fetch and manipulate repository data.\n- **User/Org Support**: Works for both user and organization repos.\n- **Pagination & Rate Limiting**: Handles these for you.\n\n### Example Usage\n\n```python\nfrom github import Github, Auth\n\n# Authenticate with a personal access token\nauth = Auth.Token(\"your_github_token\")\ng = Github(auth=auth)\n\n# Get the repo\nrepo = g.get_repo(\"owner/repo_name\")\n\n# Create a new issue\nissue = repo.create_issue(\n title=\"Exported from Task Master\",\n body=\"This issue was created by Task Master. [Task ID: 123]\"\n)\n\n# Add a comment or update the issue to include a backlink\nissue.create_comment(\"Linked to Task Master task #123\")\n```\n[3][5]\n\n## Why Not Use Raw Requests?\n\n- While you *can* use the `requests` library to call the GitHub API directly[4], PyGithub abstracts away authentication, error handling, and pagination, making your code much cleaner and less error-prone[2][5].\n\n## Integration Tips\n\n- Store your GitHub token securely (e.g., in environment variables).\n- Use PyGithub's objects to fetch, create, and update issues.\n- For bidirectional linking, store the GitHub issue URL in your task data and the Task Master task ID in the GitHub issue body or as a label/comment.\n- PyGithub is actively maintained and widely used, so you'll find plenty of support and documentation.\n\n## Installation\n\n```bash\npip install PyGithub\n```\n[3]\n\n## Summary Table\n\n| Library | Language | API Coverage | Ease of Use | Maintained | Docs/Support |\n|-----------|----------|--------------|-------------|------------|--------------|\n| PyGithub | Python | Full | High | Yes | Excellent |\n| requests | Python | Full (manual)| Medium | Yes | Good |\n\n**Use PyGithub for all GitHub API interactions in your export/import features.** It's the standard for Python projects and will make your implementation faster, safer, and more maintainable[1][2][3][5].\n\n---\n\n**Follow-up 1:** we don't want to use py github because we have a node project\n\n**Response:** HELL YEAH PARTNER\n\nFor a Node.js project, you should use a Node-native library to interact with the GitHub API instead of PyGithub, which is Python-only. The industry standard for Node.js is **Octokit**, the official GitHub SDK for JavaScript/TypeScript[1][2].\n\n## Why Use Octokit?\n\n- **Official & Complete**: Octokit is maintained by GitHub and covers all REST and GraphQL API endpoints, including issues, repositories, users, and more[1][2].\n- **Universal**: Works in Node.js, browsers, and Deno environments[2].\n- **Typed & Tested**: Comes with TypeScript declarations and 100% test coverage[2].\n- **Authentication**: Supports personal access tokens, GitHub Apps, OAuth, and more.\n- **Pagination & Error Handling**: Handles pagination and common error scenarios out of the box.\n- **Extendable**: Supports plugins and custom hooks for advanced use cases[2].\n\n## How to Use Octokit for GitHub Issue Export\n\nInstall Octokit in your Node.js project:\n\n```bash\nnpm install @octokit/rest\n```\n\nBasic usage for creating and linking issues:\n\n```js\nconst { Octokit } = require(\"@octokit/rest\");\n\n// Authenticate with a personal access token\nconst octokit = new Octokit({ auth: process.env.GITHUB_TOKEN });\n\n// Create a new issue\nconst { data: issue } = await octokit.issues.create({\n owner: \"owner\",\n repo: \"repo_name\",\n title: \"Exported from Task Master\",\n body: \"This issue was created by Task Master. [Task ID: 123]\"\n});\n\n// Add a comment for bidirectional linking\nawait octokit.issues.createComment({\n owner: \"owner\",\n repo: \"repo_name\",\n issue_number: issue.number,\n body: \"Linked to Task Master task #123\"\n});\n```\n\n## Alternatives\n\n- **node-github**: An older library, less maintained than Octokit, but still functional for basic API access[5].\n- **Raw HTTP Requests**: You can use `node-fetch` or `axios` to call the GitHub API directly, but you'll need to handle authentication, pagination, and error handling yourself[3]. Octokit abstracts all of this for you.\n\n## Summary Table\n\n| Library | Language | API Coverage | Maintained | TypeScript | Docs/Support |\n|-----------------|----------|--------------|------------|------------|--------------|\n| Octokit | Node.js | Full | Yes | Yes | Excellent |\n| node-github | Node.js | Full | No | No | Limited |\n| Raw HTTP | Node.js | Full (manual)| N/A | N/A | N/A |\n\n**Recommendation:** Use Octokit for all GitHub API interactions in your Node.js project. It's the official, most robust, and best-supported option for your use case[1][2].\n</info added on 2025-06-14T21:20:39.682Z>", "testStrategy": "", "status": "pending", "dependencies": [], @@ -6587,12 +6587,26 @@ "description": "Main tag for the taskmaster project" } }, - "v017-adds": { - "tasks": [], + "test-tag": { + "tasks": [ + { + "id": 1, + "title": "Implement TTS Flag for Taskmaster Commands", + "description": "Add text-to-speech functionality to taskmaster commands with configurable voice options and audio output settings.", + "details": "Implement TTS functionality including:\n- Add --tts flag to all relevant taskmaster commands (list, show, generate, etc.)\n- Integrate with system TTS engines (Windows SAPI, macOS say command, Linux espeak/festival)\n- Create TTS configuration options in the configuration management system\n- Add voice selection options (male/female, different languages if available)\n- Implement audio output settings (volume, speed, pitch)\n- Add TTS-specific error handling for cases where TTS is unavailable\n- Create fallback behavior when TTS fails (silent failure or text output)\n- Support for reading task titles, descriptions, and status updates aloud\n- Add option to read entire task lists or individual task details\n- Implement TTS for command confirmations and error messages\n- Create TTS output formatting to make spoken text more natural (removing markdown, formatting numbers/dates appropriately)\n- Add configuration option to enable/disable TTS globally\n<info added on 2025-06-14T21:55:53.499Z>\nAdd comprehensive testing strategy for TTS functionality:\n\n**TTS Testing Requirements:**\n- Test TTS flag functionality across all commands (list, show, generate) with various voice configurations\n- Validate TTS engine integration on different platforms (Windows SAPI, macOS say, Linux espeak/festival)\n- Test voice selection options and audio output settings (volume, speed, pitch) with edge cases\n- Verify TTS error handling when engines are unavailable or fail\n- Test fallback behavior scenarios (silent failure vs text output)\n- Validate TTS output formatting for natural speech (markdown removal, number/date pronunciation)\n- Test global TTS enable/disable configuration settings\n- Verify TTS works correctly with task titles, descriptions, and status updates of varying lengths and complexity\n- Test TTS performance with large task lists and individual task details\n- Validate TTS for command confirmations and error messages across different error scenarios\n\n**Automated TTS Test Cases:**\n- Enable TTS flag and verify audio output generation without errors\n- Test each supported TTS engine with fallback when primary engine fails\n- Validate configuration persistence for TTS settings across application restarts\n- Test TTS with special characters, long text, and multilingual content\n- Verify TTS integration doesn't interfere with normal command execution or file operations\n- Test concurrent TTS operations and resource management\n- Validate TTS accessibility compliance and user experience consistency\n</info added on 2025-06-14T21:55:53.499Z>\n<info added on 2025-06-14T22:07:04.840Z>\n**Duplicate Save Prevention Testing for TTS Implementation:**\n\nSince TTS functionality involves configuration persistence and potential concurrent operations, implement specific tests to prevent duplicate saves in the TTS context:\n\n- Test TTS configuration saves to prevent duplicate entries in configuration files when users rapidly change voice settings, volume, or other audio parameters\n- Validate that TTS engine initialization doesn't create duplicate configuration entries when switching between different TTS engines (Windows SAPI, macOS say, Linux espeak)\n- Test concurrent TTS operations to ensure audio output settings aren't duplicated when multiple commands with --tts flag run simultaneously\n- Verify that TTS preference saves are atomic and don't result in corrupted or duplicate configuration data during rapid user interactions\n- Implement unique constraint checks for TTS configuration entries to prevent duplicate voice profiles or audio settings\n- Test TTS configuration persistence across application restarts to ensure settings aren't duplicated on reload\n- Validate that TTS error logging doesn't create duplicate log entries when TTS engines fail or fallback mechanisms activate\n- Test edge cases where users rapidly toggle global TTS enable/disable settings to prevent duplicate configuration states\n- Ensure TTS-related task metadata (like audio output preferences per task) doesn't create duplicate entries in tasks.json\n- Implement locking mechanisms for TTS configuration file operations to prevent race conditions during concurrent access\n\nThis testing should be integrated with the existing TTS test strategy to ensure robust duplicate prevention across all TTS-related save operations.\n</info added on 2025-06-14T22:07:04.840Z>\n<info added on 2025-06-14T22:08:10.995Z>\n**Claude API Integration Testing for TTS Commands:**\n\nAdd specific testing requirements for Claude API integration within the TTS implementation context:\n\n- Test Claude API connectivity when generating TTS-enabled task content to ensure API calls don't interfere with audio output generation\n- Validate Claude API authentication and error handling when TTS commands request AI-generated content with --tts flag enabled\n- Test Claude API response parsing and integration with TTS output formatting to ensure AI-generated text is properly converted for speech synthesis\n- Verify Claude API token usage tracking doesn't conflict with TTS configuration persistence mechanisms\n- Test concurrent operations where Claude API calls and TTS audio generation occur simultaneously\n- Validate Claude API retry and backoff logic works correctly when TTS commands fail and need to regenerate content\n- Test Claude API integration with task generation workflows that include TTS output requirements\n- Ensure Claude API error messages are properly formatted for TTS output when --tts flag is enabled\n- Test Claude API model parameter configuration persistence alongside TTS configuration settings\n- Validate that Claude API failures gracefully fallback without breaking TTS functionality for existing task content\n- Test environment variable handling for ANTHROPIC_API_KEY in conjunction with TTS engine configuration\n- Verify Claude API integration logging doesn't create conflicts with TTS error logging mechanisms\n\nThis testing should ensure seamless integration between Claude API functionality and TTS features without interference or duplicate save issues.\n</info added on 2025-06-14T22:08:10.995Z>\n<info added on 2025-06-14T22:10:22.106Z>\n**Final Duplicate Save Testing Protocol - Research Session 6/14/2025:**\n\n**Comprehensive Test Environment Setup:**\n- Create clean test environment with known state of tasks.json and TTS configuration files\n- Back up current tasks.json, TTS settings, and Claude API configuration before testing\n- Ensure all TTS engines and Claude API connectivity are functional for comprehensive testing\n\n**Duplicate Save Test Scenarios for TTS Implementation:**\n- Test saving TTS configuration with identical voice settings to verify no duplicate entries\n- Attempt simultaneous TTS configuration saves while audio output is active\n- Test Claude API task generation with --tts flag to ensure no duplicate task entries in tasks.json\n- Validate TTS preference persistence doesn't create duplicate configuration entries during rapid setting changes\n- Test concurrent TTS operations with multiple commands to verify no duplicate audio output settings\n- Simulate race conditions between TTS configuration saves and Claude API calls\n\n**Manual and Automated Test Execution:**\n- Execute TTS commands with --tts flag while monitoring tasks.json for duplicate entries\n- Test Claude API integration with TTS-enabled commands to verify single task creation\n- Validate TTS configuration file integrity after multiple rapid setting changes\n- Test TTS error logging to ensure no duplicate log entries during engine failures\n- Verify TTS-related task metadata saves don't create duplicate entries\n\n**Edge Case Testing for TTS Context:**\n- Test TTS configuration saves with minor variations (case sensitivity, whitespace) in voice names\n- Validate duplicate detection with similar TTS settings across different engines\n- Test large-scale TTS operations to ensure performance and correctness\n- Verify TTS global enable/disable toggle doesn't create duplicate configuration states\n\n**Validation and Documentation:**\n- Monitor TTS configuration files, tasks.json, and logs for any duplicate entries\n- Document test results in provided table format with TTS-specific scenarios\n- Verify error handling provides clear feedback for TTS-related duplicate save attempts\n- Confirm regression testing covers all TTS functionality without introducing new duplicate save issues\n- Complete stakeholder confirmation before closing duplicate save testing for TTS implementation\n</info added on 2025-06-14T22:10:22.106Z>", + "testStrategy": "Test TTS functionality across different operating systems (Windows, macOS, Linux). Verify that the --tts flag works with all major commands. Test voice configuration options and ensure audio output settings are properly applied. Test error handling when TTS services are unavailable. Verify that text formatting for speech is natural and understandable. Test with various task content types including special characters, code snippets, and long descriptions. Ensure TTS can be disabled and enabled through configuration.", + "status": "pending", + "dependencies": [ + 16 + ], + "priority": "medium", + "subtasks": [] + } + ], "metadata": { - "created": "2025-06-14T00:49:52.563Z", - "updated": "2025-06-14T00:49:52.563Z", - "description": "Tag created from git branch \"v017-adds\"" + "created": "2025-06-14T21:30:21.214Z", + "updated": "2025-06-14T21:31:06.388Z", + "description": "Tag created on 6/14/2025" } } } \ No newline at end of file diff --git a/mcp-server/src/core/direct-functions/clear-subtasks.js b/mcp-server/src/core/direct-functions/clear-subtasks.js index 12082db2..7aabb807 100644 --- a/mcp-server/src/core/direct-functions/clear-subtasks.js +++ b/mcp-server/src/core/direct-functions/clear-subtasks.js @@ -5,9 +5,11 @@ import { clearSubtasks } from '../../../../scripts/modules/task-manager.js'; import { enableSilentMode, - disableSilentMode + disableSilentMode, + readJSON } from '../../../../scripts/modules/utils.js'; import fs from 'fs'; +import path from 'path'; /** * Clear subtasks from specified tasks @@ -15,12 +17,13 @@ import fs from 'fs'; * @param {string} args.tasksJsonPath - Explicit path to the tasks.json file. * @param {string} [args.id] - Task IDs (comma-separated) to clear subtasks from * @param {boolean} [args.all] - Clear subtasks from all tasks + * @param {string} [args.tag] - Tag context to operate on (defaults to current active tag) * @param {Object} log - Logger object * @returns {Promise<{success: boolean, data?: Object, error?: {code: string, message: string}}>} */ export async function clearSubtasksDirect(args, log) { // Destructure expected args - const { tasksJsonPath, id, all } = args; + const { tasksJsonPath, id, all, tag, projectRoot } = args; try { log.info(`Clearing subtasks with args: ${JSON.stringify(args)}`); @@ -64,52 +67,70 @@ export async function clearSubtasksDirect(args, log) { let taskIds; + // Use readJSON which handles silent migration and tag resolution + const data = readJSON(tasksPath, projectRoot, tag); + + if (!data || !data.tasks) { + return { + success: false, + error: { + code: 'INPUT_VALIDATION_ERROR', + message: `No tasks found in tasks file: ${tasksPath}` + } + }; + } + + const currentTag = data.tag || 'master'; + const tasks = data.tasks; + // If all is specified, get all task IDs if (all) { - log.info('Clearing subtasks from all tasks'); - const data = JSON.parse(fs.readFileSync(tasksPath, 'utf8')); - if (!data || !data.tasks || data.tasks.length === 0) { + log.info(`Clearing subtasks from all tasks in tag '${currentTag}'`); + if (tasks.length === 0) { return { success: false, error: { code: 'INPUT_VALIDATION_ERROR', - message: 'No valid tasks found in the tasks file' + message: `No tasks found in tag context '${currentTag}'` } }; } - taskIds = data.tasks.map((t) => t.id).join(','); + taskIds = tasks.map((t) => t.id).join(','); } else { // Use the provided task IDs taskIds = id; } - log.info(`Clearing subtasks from tasks: ${taskIds}`); + log.info(`Clearing subtasks from tasks: ${taskIds} in tag '${currentTag}'`); // Enable silent mode to prevent console logs from interfering with JSON response enableSilentMode(); // Call the core function - clearSubtasks(tasksPath, taskIds); + clearSubtasks(tasksPath, taskIds, { projectRoot, tag: currentTag }); // Restore normal logging disableSilentMode(); // Read the updated data to provide a summary - const updatedData = JSON.parse(fs.readFileSync(tasksPath, 'utf8')); + const updatedData = readJSON(tasksPath, projectRoot, currentTag); const taskIdArray = taskIds.split(',').map((id) => parseInt(id.trim(), 10)); // Build a summary of what was done const clearedTasksCount = taskIdArray.length; + const updatedTasks = updatedData.tasks || []; + const taskSummary = taskIdArray.map((id) => { - const task = updatedData.tasks.find((t) => t.id === id); + const task = updatedTasks.find((t) => t.id === id); return task ? { id, title: task.title } : { id, title: 'Task not found' }; }); return { success: true, data: { - message: `Successfully cleared subtasks from ${clearedTasksCount} task(s)`, - tasksCleared: taskSummary + message: `Successfully cleared subtasks from ${clearedTasksCount} task(s) in tag '${currentTag}'`, + tasksCleared: taskSummary, + tag: currentTag } }; } catch (error) { diff --git a/mcp-server/src/core/direct-functions/move-task.js b/mcp-server/src/core/direct-functions/move-task.js index 25a920eb..9cc06d61 100644 --- a/mcp-server/src/core/direct-functions/move-task.js +++ b/mcp-server/src/core/direct-functions/move-task.js @@ -71,7 +71,11 @@ export async function moveTaskDirect(args, log, context = {}) { tasksPath, args.sourceId, args.destinationId, - generateFiles + generateFiles, + { + projectRoot: args.projectRoot, + tag: args.tag + } ); // Restore console output diff --git a/mcp-server/src/tools/clear-subtasks.js b/mcp-server/src/tools/clear-subtasks.js index 82184e97..4bff2bcc 100644 --- a/mcp-server/src/tools/clear-subtasks.js +++ b/mcp-server/src/tools/clear-subtasks.js @@ -35,7 +35,8 @@ export function registerClearSubtasksTool(server) { ), projectRoot: z .string() - .describe('The directory of the project. Must be an absolute path.') + .describe('The directory of the project. Must be an absolute path.'), + tag: z.string().optional().describe('Tag context to operate on') }) .refine((data) => data.id || data.all, { message: "Either 'id' or 'all' parameter must be provided", @@ -64,7 +65,8 @@ export function registerClearSubtasksTool(server) { tasksJsonPath: tasksJsonPath, id: args.id, all: args.all, - projectRoot: args.projectRoot + projectRoot: args.projectRoot, + tag: args.tag || 'master' }, log, { session } diff --git a/scripts/modules/commands.js b/scripts/modules/commands.js index f83272b7..2d897394 100644 --- a/scripts/modules/commands.js +++ b/scripts/modules/commands.js @@ -1614,7 +1614,7 @@ function registerCommands(programInstance) { .command('research') .description('Perform AI-powered research queries with project context') .argument('[prompt]', 'Research prompt to investigate') - .option('--file <file>', 'Path to the tasks file', 'tasks/tasks.json') + .option('--file <file>', 'Path to the tasks file') .option( '-i, --id <ids>', 'Comma-separated task/subtask IDs to include as context (e.g., "15,16.2")' @@ -1752,7 +1752,8 @@ function registerCommands(programInstance) { const projectRoot = findProjectRoot() || '.'; const tag = options.tag || getCurrentTag(projectRoot) || 'master'; const tasksPath = - options.file || path.join(projectRoot, 'tasks', 'tasks.json'); + options.file || + path.join(projectRoot, '.taskmaster', 'tasks', 'tasks.json'); // Show current tag context displayCurrentTagIndicator(tag); @@ -1856,14 +1857,15 @@ function registerCommands(programInstance) { researchOptions, { commandName: 'research', - outputType: 'cli' + outputType: 'cli', + tag: tag }, 'text', validatedParams.allowFollowUp // Pass follow-up flag ); - // Auto-save to task/subtask if requested - if (validatedParams.saveToId) { + // Auto-save to task/subtask if requested and no interactive save occurred + if (validatedParams.saveToId && !result.interactiveSaveOccurred) { try { const isSubtask = validatedParams.saveToId.includes('.'); @@ -1892,7 +1894,8 @@ ${result.result}`; { commandName: 'research-save', outputType: 'cli', - projectRoot: validatedParams.projectRoot + projectRoot: validatedParams.projectRoot, + tag: tag }, 'text' ); @@ -1917,7 +1920,8 @@ ${result.result}`; { commandName: 'research-save', outputType: 'cli', - projectRoot: validatedParams.projectRoot + projectRoot: validatedParams.projectRoot, + tag: tag }, 'text', true // appendMode = true @@ -3540,7 +3544,7 @@ Examples: try { // Read tasks data once to validate destination IDs - const tasksData = readJSON(tasksPath); + const tasksData = readJSON(tasksPath, projectRoot, tag); if (!tasksData || !tasksData.tasks) { console.error( chalk.red(`Error: Invalid or missing tasks file at ${tasksPath}`) diff --git a/scripts/modules/task-manager/add-task.js b/scripts/modules/task-manager/add-task.js index d86b520e..61883ba3 100644 --- a/scripts/modules/task-manager/add-task.js +++ b/scripts/modules/task-manager/add-task.js @@ -558,14 +558,14 @@ async function addTask( report('DEBUG: tasks.json written.', 'debug'); // Generate markdown task files - report('Generating task files...', 'info'); - report('DEBUG: Calling generateTaskFiles...', 'debug'); - // Pass mcpLog if available to generateTaskFiles - await generateTaskFiles(tasksPath, path.dirname(tasksPath), { - projectRoot, - tag: targetTag - }); - report('DEBUG: generateTaskFiles finished.', 'debug'); + // report('Generating task files...', 'info'); + // report('DEBUG: Calling generateTaskFiles...', 'debug'); + // // Pass mcpLog if available to generateTaskFiles + // await generateTaskFiles(tasksPath, path.dirname(tasksPath), { + // projectRoot, + // tag: targetTag + // }); + // report('DEBUG: generateTaskFiles finished.', 'debug'); // Show success message - only for text output (CLI) if (outputFormat === 'text') { diff --git a/scripts/modules/task-manager/clear-subtasks.js b/scripts/modules/task-manager/clear-subtasks.js index e18a079d..760b5581 100644 --- a/scripts/modules/task-manager/clear-subtasks.js +++ b/scripts/modules/task-manager/clear-subtasks.js @@ -5,7 +5,6 @@ import Table from 'cli-table3'; import { log, readJSON, writeJSON, truncate, isSilentMode } from '../utils.js'; import { displayBanner } from '../ui.js'; -import generateTaskFiles from './generate-task-files.js'; /** * Clear subtasks from specified tasks @@ -99,10 +98,6 @@ function clearSubtasks(tasksPath, taskIds, context = {}) { console.log(summaryTable.toString()); } - // Regenerate task files to reflect changes - log('info', 'Regenerating task files...'); - generateTaskFiles(tasksPath, path.dirname(tasksPath), { projectRoot, tag }); - // Success message if (!isSilentMode()) { console.log( diff --git a/scripts/modules/task-manager/expand-task.js b/scripts/modules/task-manager/expand-task.js index 26b7e15a..c24fc1cb 100644 --- a/scripts/modules/task-manager/expand-task.js +++ b/scripts/modules/task-manager/expand-task.js @@ -669,7 +669,7 @@ async function expandTask( data.tasks[taskIndex] = task; // Assign the modified task back writeJSON(tasksPath, data); - await generateTaskFiles(tasksPath, path.dirname(tasksPath)); + // await generateTaskFiles(tasksPath, path.dirname(tasksPath)); // Display AI Usage Summary for CLI if ( diff --git a/scripts/modules/task-manager/move-task.js b/scripts/modules/task-manager/move-task.js index e77d9497..19538330 100644 --- a/scripts/modules/task-manager/move-task.js +++ b/scripts/modules/task-manager/move-task.js @@ -120,7 +120,7 @@ async function moveTask( // Always write the data object, never the _rawTaggedData directly // The writeJSON function will filter out _rawTaggedData automatically - writeJSON(tasksPath, rawData); + writeJSON(tasksPath, rawData, options.projectRoot, currentTag); if (generateFiles) { await generateTaskFiles(tasksPath, path.dirname(tasksPath)); diff --git a/scripts/modules/task-manager/research.js b/scripts/modules/task-manager/research.js index 3488162b..80e27c5f 100644 --- a/scripts/modules/task-manager/research.js +++ b/scripts/modules/task-manager/research.js @@ -107,8 +107,13 @@ async function performResearch( let autoDiscoveredIds = []; try { - const tasksPath = path.join(projectRoot, 'tasks', 'tasks.json'); - const tasksData = await readJSON(tasksPath); + const tasksPath = path.join( + projectRoot, + '.taskmaster', + 'tasks', + 'tasks.json' + ); + const tasksData = await readJSON(tasksPath, projectRoot); if (tasksData && tasksData.tasks && tasksData.tasks.length > 0) { // Flatten tasks to include subtasks for fuzzy search @@ -250,6 +255,9 @@ async function performResearch( const tagInfo = aiResult.tagInfo; // Format and display results + // Initialize interactive save tracking + let interactiveSaveInfo = { interactiveSaveOccurred: false }; + if (outputFormat === 'text') { displayResearchResults( researchResult, @@ -265,7 +273,7 @@ async function performResearch( // Offer follow-up question option (only for initial CLI queries, not MCP) if (allowFollowUp && !isMCP) { - await handleFollowUpQuestions( + interactiveSaveInfo = await handleFollowUpQuestions( options, context, outputFormat, @@ -308,7 +316,8 @@ async function performResearch( detailLevel, telemetryData, tagInfo, - savedFilePath + savedFilePath, + interactiveSaveOccurred: false // MCP save-to-file doesn't count as interactive save }; } @@ -325,7 +334,9 @@ async function performResearch( totalInputTokens, detailLevel, telemetryData, - tagInfo + tagInfo, + interactiveSaveOccurred: + interactiveSaveInfo?.interactiveSaveOccurred || false }; } catch (error) { logFn.error(`Research query failed: ${error.message}`); @@ -643,6 +654,8 @@ async function handleFollowUpQuestions( initialQuery, initialResult ) { + let interactiveSaveOccurred = false; + try { // Import required modules for saving const { readJSON } = await import('../utils.js'); @@ -693,12 +706,15 @@ async function handleFollowUpQuestions( if (action === 'save') { // Handle save functionality - await handleSaveToTask( + const saveResult = await handleSaveToTask( conversationHistory, projectRoot, context, logFn ); + if (saveResult) { + interactiveSaveOccurred = true; + } continue; } @@ -762,6 +778,8 @@ async function handleFollowUpQuestions( // silently continue without follow-up functionality logFn.debug(`Follow-up questions not available: ${error.message}`); } + + return { interactiveSaveOccurred }; } /** @@ -828,8 +846,10 @@ async function handleSaveToTask( return; } - // Validate ID exists - const data = readJSON(tasksPath, projectRoot); + // Validate ID exists - use tag from context + const { getCurrentTag } = await import('../utils.js'); + const tag = context.tag || getCurrentTag(projectRoot) || 'master'; + const data = readJSON(tasksPath, projectRoot, tag); if (!data || !data.tasks) { console.log(chalk.red('❌ No valid tasks found.')); return; @@ -863,7 +883,7 @@ async function handleSaveToTask( trimmedTaskId, conversationThread, false, // useResearch = false for simple append - context, + { ...context, tag }, 'text' ); @@ -890,7 +910,7 @@ async function handleSaveToTask( taskIdNum, conversationThread, false, // useResearch = false for simple append - context, + { ...context, tag }, 'text', true // appendMode = true ); @@ -899,9 +919,12 @@ async function handleSaveToTask( chalk.green(`✅ Research conversation saved to task ${trimmedTaskId}`) ); } + + return true; // Indicate successful save } catch (error) { console.log(chalk.red(`❌ Error saving conversation: ${error.message}`)); logFn.error(`Error saving conversation: ${error.message}`); + return false; // Indicate failed save } } diff --git a/scripts/modules/task-manager/update-subtask-by-id.js b/scripts/modules/task-manager/update-subtask-by-id.js index 1b2367c8..c5afb94d 100644 --- a/scripts/modules/task-manager/update-subtask-by-id.js +++ b/scripts/modules/task-manager/update-subtask-by-id.js @@ -17,7 +17,8 @@ import { truncate, isSilentMode, findProjectRoot, - flattenTasksWithSubtasks + flattenTasksWithSubtasks, + getCurrentTag } from '../utils.js'; import { generateTextService } from '../ai-services-unified.js'; import { getDebugFlag } from '../config-manager.js'; @@ -46,7 +47,7 @@ async function updateSubtaskById( context = {}, outputFormat = context.mcpLog ? 'json' : 'text' ) { - const { session, mcpLog, projectRoot: providedProjectRoot } = context; + const { session, mcpLog, projectRoot: providedProjectRoot, tag } = context; const logFn = mcpLog || consoleLog; const isMCP = !!mcpLog; @@ -90,7 +91,10 @@ async function updateSubtaskById( throw new Error('Could not determine project root directory'); } - const data = readJSON(tasksPath, projectRoot); + // Determine the tag to use + const currentTag = tag || getCurrentTag(projectRoot) || 'master'; + + const data = readJSON(tasksPath, projectRoot, currentTag); if (!data || !data.tasks) { throw new Error( `No valid tasks found in ${tasksPath}. The file may be corrupted or have an invalid format.` @@ -331,7 +335,7 @@ Output Requirements: if (outputFormat === 'text' && getDebugFlag(session)) { console.log('>>> DEBUG: About to call writeJSON with updated data...'); } - writeJSON(tasksPath, data, projectRoot); + writeJSON(tasksPath, data, projectRoot, currentTag); if (outputFormat === 'text' && getDebugFlag(session)) { console.log('>>> DEBUG: writeJSON call completed.'); } diff --git a/scripts/modules/task-manager/update-task-by-id.js b/scripts/modules/task-manager/update-task-by-id.js index 38f62220..15dad92a 100644 --- a/scripts/modules/task-manager/update-task-by-id.js +++ b/scripts/modules/task-manager/update-task-by-id.js @@ -12,7 +12,8 @@ import { truncate, isSilentMode, flattenTasksWithSubtasks, - findProjectRoot + findProjectRoot, + getCurrentTag } from '../utils.js'; import { @@ -23,11 +24,7 @@ import { } from '../ui.js'; import { generateTextService } from '../ai-services-unified.js'; -import { - getDebugFlag, - isApiKeySet // Keep this check -} from '../config-manager.js'; -import generateTaskFiles from './generate-task-files.js'; +import { getDebugFlag, isApiKeySet } from '../config-manager.js'; import { ContextGatherer } from '../utils/contextGatherer.js'; import { FuzzyTaskSearch } from '../utils/fuzzyTaskSearch.js'; @@ -223,7 +220,7 @@ async function updateTaskById( outputFormat = 'text', appendMode = false ) { - const { session, mcpLog, projectRoot: providedProjectRoot } = context; + const { session, mcpLog, projectRoot: providedProjectRoot, tag } = context; const logFn = mcpLog || consoleLog; const isMCP = !!mcpLog; @@ -268,8 +265,11 @@ async function updateTaskById( throw new Error('Could not determine project root directory'); } + // Determine the tag to use + const currentTag = tag || getCurrentTag(projectRoot) || 'master'; + // --- Task Loading and Status Check (Keep existing) --- - const data = readJSON(tasksPath, projectRoot); + const data = readJSON(tasksPath, projectRoot, currentTag); if (!data || !data.tasks) throw new Error(`No valid tasks found in ${tasksPath}.`); const taskIndex = data.tasks.findIndex((task) => task.id === taskId); @@ -510,7 +510,7 @@ The changes described in the prompt should be thoughtfully applied to make the t // Write the updated task back to file data.tasks[taskIndex] = taskToUpdate; - writeJSON(tasksPath, data); + writeJSON(tasksPath, data, projectRoot, currentTag); report('success', `Successfully appended to task ${taskId}`); // Display success message for CLI @@ -624,7 +624,7 @@ The changes described in the prompt should be thoughtfully applied to make the t // --- End Update Task Data --- // --- Write File and Generate (Unchanged) --- - writeJSON(tasksPath, data); + writeJSON(tasksPath, data, projectRoot, currentTag); report('success', `Successfully updated task ${taskId}`); // await generateTaskFiles(tasksPath, path.dirname(tasksPath)); // --- End Write File --- diff --git a/tests/unit/scripts/modules/task-manager/add-task.test.js b/tests/unit/scripts/modules/task-manager/add-task.test.js index a22acc73..4f894729 100644 --- a/tests/unit/scripts/modules/task-manager/add-task.test.js +++ b/tests/unit/scripts/modules/task-manager/add-task.test.js @@ -260,7 +260,6 @@ describe('addTask', () => { }) }) ); - expect(generateTaskFiles).toHaveBeenCalled(); expect(result).toEqual( expect.objectContaining({ newTaskId: 4, diff --git a/tests/unit/scripts/modules/task-manager/clear-subtasks.test.js b/tests/unit/scripts/modules/task-manager/clear-subtasks.test.js index ee5ebe53..cf869f42 100644 --- a/tests/unit/scripts/modules/task-manager/clear-subtasks.test.js +++ b/tests/unit/scripts/modules/task-manager/clear-subtasks.test.js @@ -144,10 +144,6 @@ describe('clearSubtasks', () => { undefined, undefined ); - expect(generateTaskFiles).toHaveBeenCalledWith(tasksPath, 'tasks', { - projectRoot: undefined, - tag: undefined - }); }); test('should clear subtasks from multiple tasks when given comma-separated IDs', () => { @@ -175,10 +171,6 @@ describe('clearSubtasks', () => { undefined, undefined ); - expect(generateTaskFiles).toHaveBeenCalledWith(tasksPath, 'tasks', { - projectRoot: undefined, - tag: undefined - }); }); test('should handle tasks with no subtasks', () => { @@ -242,10 +234,6 @@ describe('clearSubtasks', () => { undefined, undefined ); - expect(generateTaskFiles).toHaveBeenCalledWith(tasksPath, 'tasks', { - projectRoot: undefined, - tag: undefined - }); }); test('should handle file read errors', () => {