@e0ipso/ai-task-manager 1.19.0 → 1.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,437 @@
1
+ ---
2
+ argument-hint: [user-prompt]
3
+ description: Execute the full workflow from plan creation to blueprint execution
4
+ ---
5
+ # Full Workflow Execution
6
+
7
+ You are a workflow composition assistant. Your role is to execute the complete task management workflow from plan creation through blueprint execution **without pausing between steps**. This is a fully automated workflow that executes all three steps sequentially.
8
+
9
+ ## Assistant Configuration
10
+
11
+ Before proceeding with this command, you MUST load and respect the assistant's configuration:
12
+
13
+ **Run the following scripts:**
14
+ ```bash
15
+ ASSISTANT=$(node .ai/task-manager/config/scripts/detect-assistant.cjs)
16
+ node .ai/task-manager/config/scripts/read-assistant-config.cjs "$ASSISTANT"
17
+ ```
18
+
19
+ The output above contains your global and project-level configuration rules. You MUST keep these rules and guidelines in mind during all subsequent operations in this command.
20
+
21
+ ---
22
+
23
+ ## Workflow Execution Instructions
24
+
25
+ **CRITICAL**: Execute all three steps sequentially without waiting for user input between steps. Progress indicators are for user visibility only - do not pause execution.
26
+
27
+ The user input is:
28
+
29
+ <user-input>
30
+ $ARGUMENTS
31
+ </user-input>
32
+
33
+ If no user input is provided, stop immediately and show an error message to the user.
34
+
35
+ ### Context Passing Between Steps
36
+
37
+ **How information flows through the workflow:**
38
+ 1. User provides prompt → use as input in Step 1
39
+ 2. Step 1 outputs "Plan ID: X" in structured format → extract X, use in Step 2
40
+ 3. Step 2 outputs "Tasks: Y" in structured format → use for progress tracking in Step 3
41
+
42
+ Use your internal Todo task tool to track the workflow execution:
43
+
44
+ - [ ] Step 1: Create Plan
45
+ - [ ] Step 2: Generate Tasks
46
+ - [ ] Step 3: Execute Blueprint
47
+
48
+ ---
49
+
50
+ ## Step 1: Plan Creation
51
+
52
+ **Progress**: ⬛⬜⬜ 0% - Step 1/3: Starting Plan Creation
53
+
54
+ Execute the following plan creation process:
55
+
56
+ Think harder and use tools.
57
+
58
+ You are a comprehensive task planning assistant. Your role is to think hard to create detailed, actionable plans based on user input while ensuring you have all necessary context before proceeding.
59
+
60
+ Include .ai/task-manager/config/TASK_MANAGER.md for the directory structure of tasks.
61
+
62
+ ### Process
63
+
64
+ Use your internal Todo task tool to track the plan generation:
65
+
66
+ - [ ] Read and execute .ai/task-manager/config/hooks/PRE_PLAN.md
67
+ - [ ] User input and context analysis
68
+ - [ ] Clarification questions
69
+ - [ ] Plan generation: Executive Summary
70
+ - [ ] Plan generation: Detailed Steps
71
+ - [ ] Plan generation: Risk Considerations
72
+ - [ ] Plan generation: Success Metrics
73
+ - [ ] Read and execute .ai/task-manager/config/hooks/POST_PLAN.md
74
+
75
+ #### Context Analysis
76
+ Before creating any plan, analyze the user's request for:
77
+ - **Objective**: What is the end goal?
78
+ - **Scope**: What are the boundaries and constraints?
79
+ - **Resources**: What tools, budget, or team are available?
80
+ - **Success Criteria**: How will success be measured?
81
+ - **Dependencies**: What prerequisites or blockers exist?
82
+ - **Technical Requirements**: What technologies or skills are needed?
83
+
84
+ #### Clarification Phase
85
+ If any critical context is missing:
86
+ 1. Identify specific gaps in the information provided
87
+ 2. Ask targeted follow-up questions grouped by category
88
+ 3. Wait for user responses before proceeding to planning
89
+ 4. Frame questions clearly with examples when helpful
90
+ 5. Be extra cautious. Users miss important context very often. Don't hesitate to ask for clarifications.
91
+
92
+ Example clarifying questions:
93
+ - "Q: What is your primary goal with [specific aspect]?"
94
+ - "Q: Do you have any existing [resources/code/infrastructure] I should consider?"
95
+ - "Q: What is your timeline for completing this?"
96
+ - "Q: Are there specific constraints I should account for?"
97
+ - "Q: Do you want me to write tests for this?"
98
+ - "Q: Are there other systems, projects, or modules that perform a similar task?"
99
+
100
+ Try to answer your own questions first by inspecting the codebase, docs, and assistant documents like CLAUDE.md, GEMINI.md, AGENTS.md ...
101
+
102
+ #### Plan Generation
103
+ Only after confirming sufficient context, create a plan that includes:
104
+ 1. **Executive Summary**: Brief overview of the approach
105
+ 2. **Detailed Steps**: Numbered, actionable tasks with clear outcomes
106
+ 3. **Risk Considerations**: Potential challenges and mitigation strategies
107
+ 4. **Success Metrics**: How to measure completion and quality
108
+
109
+ Remember that a plan needs to be reviewed by a human. Be concise and to the point. Also, include mermaid diagrams to illustrate the plan.
110
+
111
+ #### Output Format
112
+
113
+ **Output Behavior: CRITICAL - Structured Output for Command Coordination**
114
+
115
+ Always end your output with a standardized summary in this exact format, for command coordination:
116
+
117
+ ```
118
+ ---
119
+
120
+ Plan Summary:
121
+ - Plan ID: [numeric-id]
122
+ - Plan File: [full-path-to-plan-file]
123
+ ```
124
+
125
+ This structured output enables automated workflow coordination and must be included even when running standalone.
126
+
127
+ #### Plan Template
128
+
129
+ Use the template in .ai/task-manager/config/templates/PLAN_TEMPLATE.md
130
+
131
+ #### Patterns to Avoid
132
+ Do not include the following in your plan output.
133
+ - Avoid time estimations
134
+ - Avoid task lists and mentions of phases (those are things we'll introduce later)
135
+
136
+ #### Frontmatter Structure
137
+
138
+ Example:
139
+ ```yaml
140
+ ---
141
+ id: 1
142
+ summary: "Implement a comprehensive CI/CD pipeline using GitHub Actions for automated linting, testing, semantic versioning, and NPM publishing"
143
+ created: 2025-09-01
144
+ ---
145
+ ```
146
+
147
+ #### Plan ID Generation
148
+
149
+ **Auto-generate the next plan ID:**
150
+ ```bash
151
+ node .ai/task-manager/config/scripts/get-next-plan-id.cjs
152
+ ```
153
+
154
+ **Key formatting:**
155
+ - **Front-matter**: Use numeric values (`id: 7`)
156
+ - **Directory names**: Use zero-padded strings (`07--plan-name`)
157
+
158
+ **After completing Step 1:**
159
+ - Extract the Plan ID from the structured output
160
+ - Extract the Plan File path from the structured output
161
+
162
+ **Progress**: ⬛⬜⬜ 33% - Step 1/3: Plan Creation Complete
163
+
164
+ ---
165
+
166
+ ## Step 2: Task Generation
167
+
168
+ **Progress**: ⬛⬜⬜ 33% - Step 2/3: Starting Task Generation
169
+
170
+ Using the Plan ID extracted from Step 1, execute task generation:
171
+
172
+ Think harder and use tools.
173
+
174
+ You are a comprehensive task planning assistant. Your role is to create detailed, actionable plans based on user input while ensuring you have all necessary context before proceeding.
175
+
176
+ Include /TASK_MANAGER.md for the directory structure of tasks.
177
+
178
+ ### Instructions
179
+
180
+ You will think hard to analyze the provided plan document and decompose it into atomic, actionable tasks with clear dependencies and groupings.
181
+
182
+ Use your internal Todo task tool to track the following process:
183
+
184
+ - [ ] Read and process plan [PLAN_ID from Step 1]
185
+ - [ ] Use the Task Generation Process to create tasks according to the Task Creation Guidelines
186
+ - [ ] Read and run the .ai/task-manager/config/hooks/POST_TASK_GENERATION_ALL.md
187
+
188
+ #### Input
189
+ - A plan document. See .ai/task-manager/config/TASK_MANAGER.md to find the plan with ID from Step 1
190
+ - The plan contains high-level objectives and implementation steps
191
+
192
+ #### Input Error Handling
193
+ If the plan does not exist. Stop immediately and show an error to the user.
194
+
195
+ ### Task Creation Guidelines
196
+
197
+ #### Task Minimization Principles
198
+ **Core Constraint:** Create only the minimum number of tasks necessary to satisfy the plan requirements. Target a 20-30% reduction from comprehensive task lists by questioning the necessity of each component.
199
+
200
+ **Minimization Rules:**
201
+ - **Direct Implementation Only**: Create tasks for explicitly stated requirements, not "nice-to-have" features
202
+ - **DRY Task Principle**: Each task should have a unique, non-overlapping purpose
203
+ - **Question Everything**: For each task, ask "Is this absolutely necessary to meet the plan objectives?"
204
+ - **Avoid Gold-plating**: Resist the urge to add comprehensive features not explicitly required
205
+
206
+ **Antipatterns to Avoid:**
207
+ - Creating separate tasks for "error handling" when it can be included in the main implementation
208
+ - Breaking simple operations into multiple tasks (e.g., separate "validate input" and "process input" tasks)
209
+ - Adding tasks for "future extensibility" or "best practices" not mentioned in the plan
210
+ - Creating comprehensive test suites for trivial functionality
211
+
212
+ #### Task Granularity
213
+ Each task must be:
214
+ - **Single-purpose**: One clear deliverable or outcome
215
+ - **Atomic**: Cannot be meaningfully split further
216
+ - **Skill-specific**: Executable by a single skill agent
217
+ - **Verifiable**: Has clear completion criteria
218
+
219
+ #### Skill Selection and Technical Requirements
220
+
221
+ **Core Principle**: Each task should require 1-2 specific technical skills that can be handled by specialized agents. Skills should be automatically inferred from the task's technical requirements and objectives.
222
+
223
+ **Assignment Guidelines**:
224
+ - **1 skill**: Focused, single-domain tasks
225
+ - **2 skills**: Tasks requiring complementary domains
226
+ - **Split if 3+**: Indicates task should be broken down
227
+
228
+ #### Meaningful Test Strategy Guidelines
229
+
230
+ **IMPORTANT** Make sure to copy this _Meaningful Test Strategy Guidelines_ section into all the tasks focused on testing, and **also** keep them in mind when generating tasks.
231
+
232
+ Your critical mantra for test generation is: "write a few tests, mostly integration".
233
+
234
+ **When TO Write Tests:**
235
+ - Custom business logic and algorithms
236
+ - Critical user workflows and data transformations
237
+ - Edge cases and error conditions for core functionality
238
+ - Integration points between different system components
239
+ - Complex validation logic or calculations
240
+
241
+ **When NOT to Write Tests:**
242
+ - Third-party library functionality (already tested upstream)
243
+ - Framework features (React hooks, Express middleware, etc.)
244
+ - Simple CRUD operations without custom logic
245
+ - Getter/setter methods or basic property access
246
+ - Configuration files or static data
247
+ - Obvious functionality that would break immediately if incorrect
248
+
249
+ ### Task Generation Process
250
+
251
+ #### Step 1: Task Decomposition
252
+ 1. Read through the entire plan
253
+ 2. Identify all concrete deliverables **explicitly stated** in the plan
254
+ 3. Apply minimization principles: question necessity of each potential task
255
+ 4. Break each deliverable into atomic tasks (only if genuinely needed)
256
+ 5. Ensure no task requires multiple skill sets
257
+ 6. Verify each task has clear inputs and outputs
258
+ 7. **Minimize test tasks**: Combine related testing scenarios, avoid testing framework functionality
259
+ 8. Be very detailed with the "Implementation Notes". This should contain enough detail for a non-thinking LLM model to successfully complete the task. Put these instructions in a collapsible field `<details>`.
260
+
261
+ #### Step 2: Dependency Analysis
262
+ For each task, identify:
263
+ - **Hard dependencies**: Tasks that MUST complete before this can start
264
+ - **Soft dependencies**: Tasks that SHOULD complete for optimal execution
265
+ - **No circular dependencies**: Validate the dependency graph is acyclic
266
+
267
+ #### Step 3: Task Generation
268
+
269
+ Use the task template in .ai/task-manager/config/templates/TASK_TEMPLATE.md
270
+
271
+ **Task ID Generation:**
272
+
273
+ When creating tasks, you need to determine the next available task ID for the specified plan. Use this bash command to automatically generate the correct ID:
274
+
275
+ ```bash
276
+ node .ai/task-manager/config/scripts/get-next-task-id.cjs [PLAN_ID from Step 1]
277
+ ```
278
+
279
+ #### Step 4: POST_TASK_GENERATION_ALL hook
280
+
281
+ Read and run the .ai/task-manager/config/hooks/POST_TASK_GENERATION_ALL.md
282
+
283
+ ### Output Requirements
284
+
285
+ **Output Behavior:**
286
+
287
+ Provide a concise completion message with task count and location:
288
+ - Example: "Task generation complete. Created [count] tasks in `.ai/task-manager/plans/[plan-id]--[name]/tasks/`"
289
+
290
+ **CRITICAL - Structured Output for Command Coordination:**
291
+
292
+ Always end your output with a standardized summary in this exact format:
293
+
294
+ ```
295
+ ---
296
+ Task Generation Summary:
297
+ - Plan ID: [numeric-id]
298
+ - Tasks: [count]
299
+ - Status: Ready for execution
300
+ ```
301
+
302
+ This structured output enables automated workflow coordination and must be included even when running standalone.
303
+
304
+ **Progress**: ⬛⬛⬜ 66% - Step 2/3: Task Generation Complete
305
+
306
+ ---
307
+
308
+ ## Step 3: Blueprint Execution
309
+
310
+ **Progress**: ⬛⬛⬜ 66% - Step 3/3: Starting Blueprint Execution
311
+
312
+ Using the Plan ID from previous steps, execute the blueprint:
313
+
314
+ You are the coordinator responsible for executing all tasks defined in the execution blueprint of a plan document, so choose an appropriate sub-agent for this role. Your role is to coordinate phase-by-phase execution, manage parallel task processing, and ensure validation gates pass before phase transitions.
315
+
316
+ ### Critical Rules
317
+
318
+ 1. **Never skip validation gates** - Phase progression requires successful validation
319
+ 2. **Maintain task isolation** - Parallel tasks must not interfere with each other
320
+ 3. **Preserve dependency order** - Never execute a task before its dependencies
321
+ 4. **Document everything** - All decisions, issues, and outcomes must be recorded in the "Execution Summary", under "Noteworthy Events"
322
+ 5. **Fail safely** - Better to halt and request help than corrupt the execution state
323
+
324
+ ### Input Requirements
325
+ - A plan document with an execution blueprint section. See /TASK_MANAGER.md to find the plan with ID from Step 1
326
+ - Task files with frontmatter metadata (id, group, dependencies, status)
327
+ - Validation gates document: `/config/hooks/POST_PHASE.md`
328
+
329
+ #### Input Error Handling
330
+
331
+ If the plan does not exist, stop immediately and show an error to the user.
332
+
333
+ **Note**: If tasks or the execution blueprint section are missing, they will be automatically generated before execution begins (see Task and Blueprint Validation below).
334
+
335
+ #### Task and Blueprint Validation
336
+
337
+ Before proceeding with execution, validate that tasks exist and the execution blueprint has been generated. If either is missing, automatically invoke task generation.
338
+
339
+ **Validation Steps:**
340
+
341
+ ```bash
342
+ # Extract validation results directly from script
343
+ PLAN_FILE=$(node .ai/task-manager/config/scripts/validate-plan-blueprint.cjs [PLAN_ID] planFile)
344
+ PLAN_DIR=$(node .ai/task-manager/config/scripts/validate-plan-blueprint.cjs [PLAN_ID] planDir)
345
+ TASK_COUNT=$(node .ai/task-manager/config/scripts/validate-plan-blueprint.cjs [PLAN_ID] taskCount)
346
+ BLUEPRINT_EXISTS=$(node .ai/task-manager/config/scripts/validate-plan-blueprint.cjs [PLAN_ID] blueprintExists)
347
+ ```
348
+
349
+ If either `$TASK_COUNT` is 0 or `$BLUEPRINT_EXISTS` is "no":
350
+ - Display notification to user: "⚠️ Tasks or execution blueprint not found. Generating tasks automatically..."
351
+
352
+ ### Execution Process
353
+
354
+ Use your internal Todo task tool to track the execution of all phases, and the final update of the plan with the summary.
355
+
356
+ #### Phase Pre-Execution
357
+
358
+ Read and execute .ai/task-manager/config/hooks/PRE_PHASE.md
359
+
360
+ #### Phase Execution Workflow
361
+
362
+ 1. **Phase Initialization**
363
+ - Identify current phase from the execution blueprint
364
+ - List all tasks scheduled for parallel execution in this phase
365
+
366
+ 2. **Agent Selection and Task Assignment**
367
+ Read and execute .ai/task-manager/config/hooks/PRE_TASK_ASSIGNMENT.md
368
+
369
+ 3. **Parallel Execution**
370
+ - Deploy all selected agents simultaneously using your internal Task tool
371
+ - Monitor execution progress for each task
372
+ - Capture outputs and artifacts from each agent
373
+ - Update task status in real-time
374
+
375
+ 4. **Phase Completion Verification**
376
+ - Ensure all tasks in the phase have status: "completed"
377
+ - Collect and review all task outputs
378
+ - Document any issues or exceptions encountered
379
+
380
+ #### Phase Post-Execution
381
+
382
+ Read and execute .ai/task-manager/config/hooks/POST_PHASE.md
383
+
384
+ #### Phase Transition
385
+
386
+ - Update phase status to "completed" in the Blueprint section of the plan document.
387
+ - Initialize next phase
388
+ - Repeat process until all phases are complete
389
+
390
+ ### Output Requirements
391
+
392
+ **Output Behavior:**
393
+
394
+ Provide a concise execution summary:
395
+ - Example: "Execution completed. Review summary: `.ai/task-manager/archive/[plan]/plan-[id].md`"
396
+
397
+ **CRITICAL - Structured Output for Command Coordination:**
398
+
399
+ Always end your output with a standardized summary in this exact format:
400
+
401
+ ```
402
+ ---
403
+ Execution Summary:
404
+ - Plan ID: [numeric-id]
405
+ - Status: Archived
406
+ - Location: .ai/task-manager/archive/[plan-id]--[plan-name]/
407
+ ```
408
+
409
+ This structured output enables automated workflow coordination and must be included even when running standalone.
410
+
411
+ ### Post-Execution Processing
412
+
413
+ Upon successful completion of all phases and validation gates, perform the following additional steps:
414
+
415
+ - [ ] Execution Summary Generation
416
+ - [ ] Plan Archival
417
+
418
+ #### Execution Summary Generation
419
+
420
+ Append an execution summary section to the plan document with the format described in .ai/task-manager/config/templates/EXECUTION_SUMMARY_TEMPLATE.md
421
+
422
+ #### Plan Archival
423
+
424
+ After successfully appending the execution summary:
425
+
426
+ **Move completed plan to archive**:
427
+ ```bash
428
+ mv .ai/task-manager/plans/[plan-folder] .ai/task-manager/archive/
429
+ ```
430
+
431
+ **Progress**: ⬛⬛⬛ 100% - Step 3/3: Blueprint Execution Complete
432
+
433
+ ---
434
+
435
+ ## Final Summary
436
+
437
+ Generate an extremely concise final summary using the structured output from Step 3.
@@ -296,35 +296,10 @@ Read and run the .ai/task-manager/config/hooks/POST_TASK_GENERATION_ALL.md
296
296
 
297
297
  ### Output Requirements
298
298
 
299
- **Context-Aware Output Behavior:**
299
+ **Output Behavior:**
300
300
 
301
- **Extract approval method from plan metadata:**
302
-
303
- First, extract the approval_method from the plan document:
304
-
305
- ```bash
306
- # Extract approval method from plan metadata
307
- APPROVAL_METHODS=$(node .ai/task-manager/config/scripts/get-approval-methods.cjs $1)
308
-
309
- APPROVAL_METHOD_TASKS=$(echo "$APPROVAL_METHODS" | grep -o '"approval_method_tasks": "[^"]*"' | cut -d'"' -f4)
310
-
311
- # Default to "manual" if field doesn't exist (backward compatibility)
312
- APPROVAL_METHOD_TASKS=${APPROVAL_METHOD_TASKS:-manual}
313
- ```
314
-
315
- Then adjust output based on the extracted approval method:
316
-
317
- - **If `APPROVAL_METHOD_TASKS="auto"` (automated workflow mode)**:
318
- - Simply confirm task generation with task count
319
- - Do NOT instruct user to review the tasks
320
- - Do NOT add any prompts that would pause execution
321
- - Example output: "Tasks generated for plan [id]: [count] tasks created"
322
-
323
- - **If `APPROVAL_METHOD_TASKS="manual"` or empty (standalone mode)**:
324
- - Be concise but helpful
325
- - Tell the user that you are done
326
- - Instruct them to review the tasks with file paths
327
- - Example output: "Task generation complete. Review tasks in: `.ai/task-manager/plans/[plan-id]--[name]/tasks/`"
301
+ Provide a concise completion message with task count and location:
302
+ - Example: "Task generation complete. Created [count] tasks in `.ai/task-manager/plans/[plan-id]--[name]/tasks/`"
328
303
 
329
304
  **CRITICAL - Structured Output for Command Coordination:**
330
305
 
@@ -1,229 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- const fs = require('fs');
4
- const path = require('path');
5
-
6
- // Enable debug logging via environment variable
7
- const DEBUG = process.env.DEBUG === 'true';
8
-
9
- /**
10
- * Debug logging utility
11
- * @param {string} message - Debug message
12
- * @param {...any} args - Additional arguments to log
13
- */
14
- function debugLog(message, ...args) {
15
- if (DEBUG) {
16
- console.error(`[DEBUG] ${message}`, ...args);
17
- }
18
- }
19
-
20
- /**
21
- * Error logging utility
22
- * @param {string} message - Error message
23
- * @param {...any} args - Additional arguments to log
24
- */
25
- function errorLog(message, ...args) {
26
- console.error(`[ERROR] ${message}`, ...args);
27
- }
28
-
29
- /**
30
- * Find the task manager root directory by traversing up from current working directory
31
- * @returns {string|null} Path to task manager root or null if not found
32
- */
33
- function findTaskManagerRoot() {
34
- let currentPath = process.cwd();
35
- const filesystemRoot = path.parse(currentPath).root;
36
-
37
- debugLog(`Starting search for task manager root from: ${currentPath}`);
38
-
39
- while (currentPath !== filesystemRoot) {
40
- const taskManagerPlansPath = path.join(currentPath, '.ai', 'task-manager', 'plans');
41
- debugLog(`Checking for task manager at: ${taskManagerPlansPath}`);
42
-
43
- try {
44
- if (fs.existsSync(taskManagerPlansPath)) {
45
- const stats = fs.lstatSync(taskManagerPlansPath);
46
- if (stats.isDirectory()) {
47
- const taskManagerRoot = path.join(currentPath, '.ai', 'task-manager');
48
- debugLog(`Found valid task manager root at: ${taskManagerRoot}`);
49
- return taskManagerRoot;
50
- }
51
- }
52
- } catch (err) {
53
- debugLog(`Filesystem error checking ${taskManagerPlansPath}: ${err.message}`);
54
- }
55
-
56
- const parentPath = path.dirname(currentPath);
57
- if (parentPath === currentPath) {
58
- break;
59
- }
60
-
61
- currentPath = parentPath;
62
- }
63
-
64
- debugLog(`Task manager root not found in any parent directory`);
65
- return null;
66
- }
67
-
68
- /**
69
- * Find plan file by ID in plans or archive directories
70
- * @param {string} taskManagerRoot - Path to task manager root
71
- * @param {string} planId - Plan ID to find
72
- * @returns {string|null} Path to plan file or null if not found
73
- */
74
- function findPlanFile(taskManagerRoot, planId) {
75
- const plansDir = path.join(taskManagerRoot, 'plans');
76
- const archiveDir = path.join(taskManagerRoot, 'archive');
77
-
78
- debugLog(`Searching for plan ${planId} in ${plansDir} and ${archiveDir}`);
79
-
80
- for (const dir of [plansDir, archiveDir]) {
81
- if (!fs.existsSync(dir)) {
82
- debugLog(`Directory does not exist: ${dir}`);
83
- continue;
84
- }
85
-
86
- try {
87
- const entries = fs.readdirSync(dir, { withFileTypes: true });
88
-
89
- for (const entry of entries) {
90
- if (entry.isDirectory() && entry.name.match(/^\d+--/)) {
91
- // Check if directory matches plan ID
92
- const dirMatch = entry.name.match(/^(\d+)--/);
93
- if (dirMatch && dirMatch[1] === planId) {
94
- const planDirPath = path.join(dir, entry.name);
95
- debugLog(`Found plan directory: ${planDirPath}`);
96
-
97
- // Look for plan file inside directory
98
- try {
99
- const planDirEntries = fs.readdirSync(planDirPath, { withFileTypes: true });
100
-
101
- for (const planEntry of planDirEntries) {
102
- if (planEntry.isFile() && planEntry.name.match(/^plan-\d+--.*\.md$/)) {
103
- const planFilePath = path.join(planDirPath, planEntry.name);
104
- debugLog(`Found plan file: ${planFilePath}`);
105
- return planFilePath;
106
- }
107
- }
108
- } catch (err) {
109
- debugLog(`Failed to read plan directory ${planDirPath}: ${err.message}`);
110
- }
111
- }
112
- } else if (entry.isFile() && entry.name.match(/^plan-\d+--.*\.md$/)) {
113
- // Legacy: direct plan file in plans/archive directory
114
- const filenameMatch = entry.name.match(/^plan-(\d+)--/);
115
- if (filenameMatch && filenameMatch[1] === planId) {
116
- const planFilePath = path.join(dir, entry.name);
117
- debugLog(`Found legacy plan file: ${planFilePath}`);
118
- return planFilePath;
119
- }
120
- }
121
- }
122
- } catch (err) {
123
- errorLog(`Failed to read directory ${dir}: ${err.message}`);
124
- }
125
- }
126
-
127
- return null;
128
- }
129
-
130
- /**
131
- * Extract a field value from YAML frontmatter
132
- * @param {string} frontmatter - YAML frontmatter text
133
- * @param {string} fieldName - Field name to extract
134
- * @param {string} defaultValue - Default value if field not found
135
- * @returns {string} Field value or default
136
- */
137
- function extractField(frontmatter, fieldName, defaultValue = 'manual') {
138
- debugLog(`Extracting field: ${fieldName}`);
139
-
140
- // Pattern to match field with various formatting:
141
- // - field: value
142
- // - field: "value"
143
- // - field: 'value'
144
- // - "field": value
145
- // - field : value (extra spaces)
146
- const regex = new RegExp(`^\\s*["']?${fieldName}["']?\\s*:\\s*(.+)$`, 'm');
147
- const match = frontmatter.match(regex);
148
-
149
- if (!match) {
150
- debugLog(`Field ${fieldName} not found, using default: ${defaultValue}`);
151
- return defaultValue;
152
- }
153
-
154
- // Clean up value: remove quotes and trim
155
- let value = match[1].trim();
156
- value = value.replace(/^['"]|['"]$/g, '');
157
-
158
- debugLog(`Extracted ${fieldName}: ${value}`);
159
- return value || defaultValue;
160
- }
161
-
162
- /**
163
- * Main function to get approval methods from plan file
164
- */
165
- function main() {
166
- // Get plan ID from command line
167
- const planId = process.argv[2];
168
- if (!planId) {
169
- errorLog('Error: Plan ID is required');
170
- console.error('Usage: node get-approval-methods.cjs <plan-id>');
171
- process.exit(1);
172
- }
173
-
174
- debugLog(`Looking for plan ID: ${planId}`);
175
-
176
- // Find task manager root
177
- const taskManagerRoot = findTaskManagerRoot();
178
- if (!taskManagerRoot) {
179
- errorLog('No .ai/task-manager directory found in current directory or any parent directory.');
180
- errorLog('Please ensure you are in a project with task manager initialized.');
181
- errorLog(`Current working directory: ${process.cwd()}`);
182
- process.exit(1);
183
- }
184
-
185
- // Find plan file
186
- const planFile = findPlanFile(taskManagerRoot, planId);
187
- if (!planFile) {
188
- errorLog(`Plan file for ID ${planId} not found in plans or archive directories.`);
189
- process.exit(1);
190
- }
191
-
192
- debugLog(`Reading plan file: ${planFile}`);
193
-
194
- // Read plan file
195
- let content;
196
- try {
197
- content = fs.readFileSync(planFile, 'utf8');
198
- } catch (err) {
199
- errorLog(`Failed to read plan file ${planFile}: ${err.message}`);
200
- process.exit(1);
201
- }
202
-
203
- // Extract YAML frontmatter
204
- const frontmatterRegex = /^---\s*\r?\n([\s\S]*?)\r?\n---/;
205
- const match = content.match(frontmatterRegex);
206
-
207
- if (!match) {
208
- errorLog('No YAML frontmatter found in plan file');
209
- process.exit(1);
210
- }
211
-
212
- const frontmatter = match[1];
213
- debugLog(`Found frontmatter:\n${frontmatter}`);
214
-
215
- // Extract approval method fields
216
- const approvalMethodPlan = extractField(frontmatter, 'approval_method_plan');
217
- const approvalMethodTasks = extractField(frontmatter, 'approval_method_tasks');
218
-
219
- // Output JSON
220
- const result = {
221
- approval_method_plan: approvalMethodPlan,
222
- approval_method_tasks: approvalMethodTasks
223
- };
224
-
225
- console.log(JSON.stringify(result, null, 2));
226
- }
227
-
228
- // Run main function
229
- main();