ai-sdlc 0.2.1-alpha.1 → 0.3.0-alpha.10

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.
Files changed (88) hide show
  1. package/README.md +78 -6
  2. package/dist/agents/implementation.d.ts +30 -1
  3. package/dist/agents/implementation.d.ts.map +1 -1
  4. package/dist/agents/implementation.js +110 -23
  5. package/dist/agents/implementation.js.map +1 -1
  6. package/dist/agents/review.d.ts +49 -1
  7. package/dist/agents/review.d.ts.map +1 -1
  8. package/dist/agents/review.js +318 -46
  9. package/dist/agents/review.js.map +1 -1
  10. package/dist/agents/rework.d.ts.map +1 -1
  11. package/dist/agents/rework.js +3 -1
  12. package/dist/agents/rework.js.map +1 -1
  13. package/dist/agents/verification.d.ts.map +1 -1
  14. package/dist/agents/verification.js +26 -12
  15. package/dist/agents/verification.js.map +1 -1
  16. package/dist/cli/batch-processor.d.ts +64 -0
  17. package/dist/cli/batch-processor.d.ts.map +1 -0
  18. package/dist/cli/batch-processor.js +85 -0
  19. package/dist/cli/batch-processor.js.map +1 -0
  20. package/dist/cli/batch-validator.d.ts +80 -0
  21. package/dist/cli/batch-validator.d.ts.map +1 -0
  22. package/dist/cli/batch-validator.js +121 -0
  23. package/dist/cli/batch-validator.js.map +1 -0
  24. package/dist/cli/commands.d.ts +11 -0
  25. package/dist/cli/commands.d.ts.map +1 -1
  26. package/dist/cli/commands.js +772 -46
  27. package/dist/cli/commands.js.map +1 -1
  28. package/dist/cli/daemon.d.ts.map +1 -1
  29. package/dist/cli/daemon.js +5 -0
  30. package/dist/cli/daemon.js.map +1 -1
  31. package/dist/cli/dependency-resolver.d.ts +49 -0
  32. package/dist/cli/dependency-resolver.d.ts.map +1 -0
  33. package/dist/cli/dependency-resolver.js +133 -0
  34. package/dist/cli/dependency-resolver.js.map +1 -0
  35. package/dist/cli/epic-processor.d.ts +16 -0
  36. package/dist/cli/epic-processor.d.ts.map +1 -0
  37. package/dist/cli/epic-processor.js +361 -0
  38. package/dist/cli/epic-processor.js.map +1 -0
  39. package/dist/cli/formatting.d.ts +15 -0
  40. package/dist/cli/formatting.d.ts.map +1 -1
  41. package/dist/cli/formatting.js +19 -0
  42. package/dist/cli/formatting.js.map +1 -1
  43. package/dist/cli/progress-dashboard.d.ts +58 -0
  44. package/dist/cli/progress-dashboard.d.ts.map +1 -0
  45. package/dist/cli/progress-dashboard.js +216 -0
  46. package/dist/cli/progress-dashboard.js.map +1 -0
  47. package/dist/cli/runner.d.ts.map +1 -1
  48. package/dist/cli/runner.js +17 -2
  49. package/dist/cli/runner.js.map +1 -1
  50. package/dist/cli/table-renderer.d.ts.map +1 -1
  51. package/dist/cli/table-renderer.js +5 -1
  52. package/dist/cli/table-renderer.js.map +1 -1
  53. package/dist/core/client.d.ts +19 -1
  54. package/dist/core/client.d.ts.map +1 -1
  55. package/dist/core/client.js +191 -5
  56. package/dist/core/client.js.map +1 -1
  57. package/dist/core/config.d.ts +13 -1
  58. package/dist/core/config.d.ts.map +1 -1
  59. package/dist/core/config.js +117 -0
  60. package/dist/core/config.js.map +1 -1
  61. package/dist/core/git-utils.d.ts +19 -0
  62. package/dist/core/git-utils.d.ts.map +1 -1
  63. package/dist/core/git-utils.js +58 -0
  64. package/dist/core/git-utils.js.map +1 -1
  65. package/dist/core/kanban.d.ts +125 -1
  66. package/dist/core/kanban.d.ts.map +1 -1
  67. package/dist/core/kanban.js +363 -4
  68. package/dist/core/kanban.js.map +1 -1
  69. package/dist/core/process-manager.d.ts +15 -0
  70. package/dist/core/process-manager.d.ts.map +1 -0
  71. package/dist/core/process-manager.js +132 -0
  72. package/dist/core/process-manager.js.map +1 -0
  73. package/dist/core/story.d.ts +24 -0
  74. package/dist/core/story.d.ts.map +1 -1
  75. package/dist/core/story.js +78 -0
  76. package/dist/core/story.js.map +1 -1
  77. package/dist/core/worktree.d.ts +111 -2
  78. package/dist/core/worktree.d.ts.map +1 -1
  79. package/dist/core/worktree.js +310 -2
  80. package/dist/core/worktree.js.map +1 -1
  81. package/dist/index.js +38 -0
  82. package/dist/index.js.map +1 -1
  83. package/dist/types/index.d.ts +184 -0
  84. package/dist/types/index.d.ts.map +1 -1
  85. package/dist/types/index.js +23 -0
  86. package/dist/types/index.js.map +1 -1
  87. package/package.json +2 -2
  88. package/templates/story.md +5 -0
@@ -2,10 +2,11 @@ import ora from 'ora';
2
2
  import fs from 'fs';
3
3
  import path from 'path';
4
4
  import * as readline from 'readline';
5
+ import { spawnSync } from 'child_process';
5
6
  import { getSdlcRoot, loadConfig, initConfig, validateWorktreeBasePath, DEFAULT_WORKTREE_CONFIG } from '../core/config.js';
6
7
  import { initializeKanban, kanbanExists, assessState, getBoardStats, findStoryBySlug, findStoriesByStatus } from '../core/kanban.js';
7
- import { createStory, parseStory, resetRPIVCycle, isAtMaxRetries, unblockStory, getStory, findStoryById, updateStoryField, writeStory, sanitizeStoryId, autoCompleteStoryAfterReview } from '../core/story.js';
8
- import { GitWorktreeService } from '../core/worktree.js';
8
+ import { createStory, parseStory, resetRPIVCycle, isAtMaxRetries, unblockStory, getStory, findStoryById, updateStoryField, writeStory, sanitizeStoryId, autoCompleteStoryAfterReview, incrementImplementationRetryCount, resetImplementationRetryCount, getEffectiveMaxImplementationRetries, isAtMaxImplementationRetries, updateStoryStatus } from '../core/story.js';
9
+ import { GitWorktreeService, getLastCompletedPhase, getNextPhase } from '../core/worktree.js';
9
10
  import { ReviewDecision } from '../types/index.js';
10
11
  import { getThemedChalk } from '../core/theme.js';
11
12
  import { saveWorkflowState, loadWorkflowState, clearWorkflowState, generateWorkflowId, calculateStoryHash, hasWorkflowState, } from '../core/workflow-state.js';
@@ -18,6 +19,13 @@ import { validateGitState } from '../core/git-utils.js';
18
19
  import { StoryLogger } from '../core/story-logger.js';
19
20
  import { detectConflicts } from '../core/conflict-detector.js';
20
21
  import { getLogger } from '../core/logger.js';
22
+ /**
23
+ * Branch divergence threshold for warnings
24
+ * When a worktree branch has diverged by more than this number of commits
25
+ * from the base branch (ahead or behind), a warning will be displayed
26
+ * suggesting the user rebase to sync with latest changes.
27
+ */
28
+ const DIVERGENCE_WARNING_THRESHOLD = 10;
21
29
  /**
22
30
  * Initialize the .ai-sdlc folder structure
23
31
  */
@@ -279,6 +287,35 @@ function validateAutoStoryOptions(options) {
279
287
  ' - ai-sdlc run --story <id> --step <phase> (single phase)');
280
288
  }
281
289
  }
290
+ /**
291
+ * Validates flag combinations for --batch conflicts
292
+ * @throws Error if conflicting flags are detected
293
+ */
294
+ function validateBatchOptions(options) {
295
+ if (!options.batch) {
296
+ return; // No batch flag, nothing to validate
297
+ }
298
+ // --batch and --story are mutually exclusive
299
+ if (options.story) {
300
+ throw new Error('Cannot combine --batch with --story flag.\n' +
301
+ 'Use either:\n' +
302
+ ' - ai-sdlc run --batch S-001,S-002,S-003 (batch processing)\n' +
303
+ ' - ai-sdlc run --auto --story <id> (single story)');
304
+ }
305
+ // --batch and --watch are mutually exclusive
306
+ if (options.watch) {
307
+ throw new Error('Cannot combine --batch with --watch flag.\n' +
308
+ 'Use either:\n' +
309
+ ' - ai-sdlc run --batch S-001,S-002,S-003 (batch processing)\n' +
310
+ ' - ai-sdlc run --watch (daemon mode)');
311
+ }
312
+ // --batch and --continue are mutually exclusive
313
+ if (options.continue) {
314
+ throw new Error('Cannot combine --batch with --continue flag.\n' +
315
+ 'Batch mode does not support resuming from checkpoints.\n' +
316
+ 'Use: ai-sdlc run --batch S-001,S-002,S-003');
317
+ }
318
+ }
282
319
  /**
283
320
  * Determines if a specific phase should be executed based on story state
284
321
  * @param story The story to check
@@ -380,6 +417,51 @@ function displayGitValidationResult(result, c) {
380
417
  }
381
418
  }
382
419
  }
420
+ /**
421
+ * Display detailed information about an existing worktree
422
+ */
423
+ function displayExistingWorktreeInfo(status, c) {
424
+ console.log();
425
+ console.log(c.warning('A worktree already exists for this story:'));
426
+ console.log();
427
+ console.log(c.bold(' Worktree Path:'), status.path);
428
+ console.log(c.bold(' Branch: '), status.branch);
429
+ if (status.lastCommit) {
430
+ console.log(c.bold(' Last Commit: '), `${status.lastCommit.hash.substring(0, 7)} - ${status.lastCommit.message}`);
431
+ console.log(c.bold(' Committed: '), status.lastCommit.timestamp);
432
+ }
433
+ const statusLabel = status.workingDirectoryStatus === 'clean'
434
+ ? c.success('clean')
435
+ : c.warning(status.workingDirectoryStatus);
436
+ console.log(c.bold(' Working Dir: '), statusLabel);
437
+ if (status.modifiedFiles.length > 0) {
438
+ console.log();
439
+ console.log(c.warning(' Modified files:'));
440
+ for (const file of status.modifiedFiles.slice(0, 5)) {
441
+ console.log(c.dim(` M ${file}`));
442
+ }
443
+ if (status.modifiedFiles.length > 5) {
444
+ console.log(c.dim(` ... and ${status.modifiedFiles.length - 5} more`));
445
+ }
446
+ }
447
+ if (status.untrackedFiles.length > 0) {
448
+ console.log();
449
+ console.log(c.warning(' Untracked files:'));
450
+ for (const file of status.untrackedFiles.slice(0, 5)) {
451
+ console.log(c.dim(` ? ${file}`));
452
+ }
453
+ if (status.untrackedFiles.length > 5) {
454
+ console.log(c.dim(` ... and ${status.untrackedFiles.length - 5} more`));
455
+ }
456
+ }
457
+ console.log();
458
+ console.log(c.info('To resume work in this worktree:'));
459
+ console.log(c.dim(` cd ${status.path}`));
460
+ console.log();
461
+ console.log(c.info('To remove the worktree and start fresh:'));
462
+ console.log(c.dim(` ai-sdlc worktrees remove ${status.storyId}`));
463
+ console.log();
464
+ }
383
465
  // ANSI escape sequence patterns for sanitization
384
466
  const ANSI_CSI_PATTERN = /\x1B\[[0-9;]*[a-zA-Z]/g;
385
467
  const ANSI_OSC_BEL_PATTERN = /\x1B\][^\x07]*\x07/g;
@@ -448,8 +530,8 @@ export async function preFlightConflictCheck(targetStory, sdlcRoot, options) {
448
530
  if (normalizedPath.length > 1024) {
449
531
  throw new Error('Invalid project path');
450
532
  }
451
- // Check if target story is already in-progress
452
- if (targetStory.frontmatter.status === 'in-progress') {
533
+ // Check if target story is already in-progress (allow if resuming existing worktree)
534
+ if (targetStory.frontmatter.status === 'in-progress' && !targetStory.frontmatter.worktree_path) {
453
535
  console.log(c.error('❌ Story is already in-progress'));
454
536
  return { proceed: false, warnings: ['Story already in progress'] };
455
537
  }
@@ -534,6 +616,149 @@ export async function preFlightConflictCheck(targetStory, sdlcRoot, options) {
534
616
  return { proceed: true, warnings: ['Conflict detection failed'] };
535
617
  }
536
618
  }
619
+ /**
620
+ * Process multiple stories sequentially through full SDLC
621
+ * Internal function used by batch mode
622
+ */
623
+ async function processBatchInternal(storyIds, sdlcRoot, options) {
624
+ const startTime = Date.now();
625
+ const config = loadConfig();
626
+ const c = getThemedChalk(config);
627
+ const { formatBatchProgress, formatBatchSummary, logStoryCompletion, promptContinueOnError } = await import('./batch-processor.js');
628
+ const result = {
629
+ total: storyIds.length,
630
+ succeeded: 0,
631
+ failed: 0,
632
+ skipped: 0,
633
+ errors: [],
634
+ duration: 0,
635
+ };
636
+ console.log();
637
+ console.log(c.bold('═══ Starting Batch Processing ═══'));
638
+ console.log(c.dim(` Stories: ${storyIds.join(', ')}`));
639
+ console.log(c.dim(` Dry run: ${options.dryRun ? 'yes' : 'no'}`));
640
+ console.log();
641
+ // Process each story sequentially
642
+ for (let i = 0; i < storyIds.length; i++) {
643
+ const storyId = storyIds[i];
644
+ // Get story and check status
645
+ let story;
646
+ try {
647
+ story = getStory(sdlcRoot, storyId);
648
+ }
649
+ catch (error) {
650
+ result.failed++;
651
+ result.errors.push({
652
+ storyId,
653
+ error: `Story not found: ${error instanceof Error ? error.message : String(error)}`,
654
+ });
655
+ console.log(c.error(`[${i + 1}/${storyIds.length}] ✗ Story not found: ${storyId}`));
656
+ console.log();
657
+ // Ask if user wants to continue (or abort in non-interactive)
658
+ const shouldContinue = await promptContinueOnError(storyId, c);
659
+ if (!shouldContinue) {
660
+ console.log(c.warning('Batch processing aborted.'));
661
+ break;
662
+ }
663
+ continue;
664
+ }
665
+ // Skip if already done
666
+ if (story.frontmatter.status === 'done') {
667
+ result.skipped++;
668
+ console.log(c.dim(`[${i + 1}/${storyIds.length}] ⊘ Skipping ${storyId} (already completed)`));
669
+ console.log();
670
+ continue;
671
+ }
672
+ // Show progress header
673
+ const progress = {
674
+ currentIndex: i,
675
+ total: storyIds.length,
676
+ currentStory: story,
677
+ };
678
+ console.log(c.info(formatBatchProgress(progress)));
679
+ console.log();
680
+ // Dry-run mode: just show what would be done
681
+ if (options.dryRun) {
682
+ console.log(c.dim(' Would process story through full SDLC'));
683
+ console.log(c.dim(` Status: ${story.frontmatter.status}`));
684
+ console.log();
685
+ result.succeeded++;
686
+ continue;
687
+ }
688
+ // Process story through full SDLC by recursively calling run()
689
+ // We set auto: true to ensure full SDLC execution
690
+ try {
691
+ await run({
692
+ auto: true,
693
+ story: storyId,
694
+ dryRun: false,
695
+ worktree: options.worktree,
696
+ force: options.force,
697
+ });
698
+ // Check if story completed successfully (moved to done)
699
+ const finalStory = getStory(sdlcRoot, storyId);
700
+ if (finalStory.frontmatter.status === 'done') {
701
+ result.succeeded++;
702
+ logStoryCompletion(storyId, true, c);
703
+ }
704
+ else {
705
+ // Story didn't reach done state - treat as failure
706
+ result.failed++;
707
+ result.errors.push({
708
+ storyId,
709
+ error: `Story did not complete (status: ${finalStory.frontmatter.status})`,
710
+ });
711
+ logStoryCompletion(storyId, false, c);
712
+ // Ask if user wants to continue (or abort in non-interactive)
713
+ const shouldContinue = await promptContinueOnError(storyId, c);
714
+ if (!shouldContinue) {
715
+ console.log(c.warning('Batch processing aborted.'));
716
+ break;
717
+ }
718
+ }
719
+ }
720
+ catch (error) {
721
+ result.failed++;
722
+ result.errors.push({
723
+ storyId,
724
+ error: error instanceof Error ? error.message : String(error),
725
+ });
726
+ logStoryCompletion(storyId, false, c);
727
+ // Ask if user wants to continue (or abort in non-interactive)
728
+ const shouldContinue = await promptContinueOnError(storyId, c);
729
+ if (!shouldContinue) {
730
+ console.log(c.warning('Batch processing aborted.'));
731
+ break;
732
+ }
733
+ }
734
+ console.log();
735
+ }
736
+ // Display final summary
737
+ result.duration = Date.now() - startTime;
738
+ const summaryLines = formatBatchSummary(result);
739
+ summaryLines.forEach((line) => {
740
+ if (line.includes('✓')) {
741
+ console.log(c.success(line));
742
+ }
743
+ else if (line.includes('✗')) {
744
+ console.log(c.error(line));
745
+ }
746
+ else if (line.includes('⊘')) {
747
+ console.log(c.warning(line));
748
+ }
749
+ else if (line.startsWith(' -')) {
750
+ console.log(c.dim(line));
751
+ }
752
+ else {
753
+ console.log(line);
754
+ }
755
+ });
756
+ // Return non-zero exit code if any failures occurred
757
+ if (result.failed > 0) {
758
+ process.exitCode = 1;
759
+ }
760
+ return result;
761
+ }
537
762
  /**
538
763
  * Run the workflow (process one action or all)
539
764
  */
@@ -554,6 +779,7 @@ export async function run(options) {
554
779
  step: options.step,
555
780
  watch: options.watch,
556
781
  worktree: options.worktree,
782
+ clean: options.clean,
557
783
  force: options.force,
558
784
  });
559
785
  // Migrate global workflow state to story-specific location if needed
@@ -572,6 +798,64 @@ export async function run(options) {
572
798
  await startDaemon({ maxIterations: maxIterationsOverride });
573
799
  return; // Daemon runs indefinitely
574
800
  }
801
+ // Handle epic mode
802
+ if (options.epic) {
803
+ const { processEpic } = await import('./epic-processor.js');
804
+ const maxConcurrent = options.maxConcurrent ? parseInt(options.maxConcurrent, 10) : undefined;
805
+ const exitCode = await processEpic({
806
+ epicId: options.epic,
807
+ maxConcurrent,
808
+ dryRun: options.dryRun,
809
+ force: options.force,
810
+ keepWorktrees: options.keepWorktrees,
811
+ });
812
+ process.exit(exitCode);
813
+ }
814
+ // Handle batch mode
815
+ if (options.batch) {
816
+ // Validate batch options first
817
+ try {
818
+ validateBatchOptions(options);
819
+ }
820
+ catch (error) {
821
+ console.log(c.error(`Error: ${error instanceof Error ? error.message : String(error)}`));
822
+ return;
823
+ }
824
+ // Import batch validation modules
825
+ const { parseStoryIdList, deduplicateStoryIds, validateStoryIds } = await import('./batch-validator.js');
826
+ // Parse and validate story IDs
827
+ const rawStoryIds = parseStoryIdList(options.batch);
828
+ if (rawStoryIds.length === 0) {
829
+ console.log(c.error('Error: Empty batch - no story IDs provided'));
830
+ console.log(c.dim('Usage: ai-sdlc run --batch S-001,S-002,S-003'));
831
+ return;
832
+ }
833
+ // Deduplicate story IDs
834
+ const storyIds = deduplicateStoryIds(rawStoryIds);
835
+ if (storyIds.length < rawStoryIds.length) {
836
+ const duplicateCount = rawStoryIds.length - storyIds.length;
837
+ console.log(c.dim(`Note: Removed ${duplicateCount} duplicate story ID(s)`));
838
+ }
839
+ // Validate all stories exist before processing
840
+ const validation = validateStoryIds(storyIds, sdlcRoot);
841
+ if (!validation.valid) {
842
+ console.log(c.error('Error: Batch validation failed'));
843
+ console.log();
844
+ for (const error of validation.errors) {
845
+ console.log(c.error(` - ${error.message}`));
846
+ }
847
+ console.log();
848
+ console.log(c.dim('Fix the errors above and try again.'));
849
+ return;
850
+ }
851
+ // Process the batch using internal function
852
+ await processBatchInternal(storyIds, sdlcRoot, {
853
+ dryRun: options.dryRun,
854
+ worktree: options.worktree,
855
+ force: options.force,
856
+ });
857
+ return; // Batch processing complete
858
+ }
575
859
  // Valid step names for --step option
576
860
  const validSteps = ['refine', 'research', 'plan', 'implement', 'review'];
577
861
  // Validate --step option early
@@ -839,17 +1123,154 @@ export async function run(options) {
839
1123
  }
840
1124
  const workingDir = path.dirname(sdlcRoot);
841
1125
  // Check if story already has an existing worktree (resume scenario)
1126
+ // Note: We check only if existingWorktreePath is set, not if it exists.
1127
+ // The validation logic will handle missing directories/branches.
842
1128
  const existingWorktreePath = targetStory.frontmatter.worktree_path;
843
- if (existingWorktreePath && fs.existsSync(existingWorktreePath)) {
1129
+ if (existingWorktreePath) {
1130
+ // Validate worktree before resuming
1131
+ const resolvedBasePath = validateWorktreeBasePath(worktreeConfig.basePath, workingDir);
1132
+ // Security validation: ensure worktree_path is within the configured base directory
1133
+ const absoluteWorktreePath = path.resolve(existingWorktreePath);
1134
+ const absoluteBasePath = path.resolve(resolvedBasePath);
1135
+ if (!absoluteWorktreePath.startsWith(absoluteBasePath)) {
1136
+ console.log(c.error('Security Error: worktree_path is outside configured base directory'));
1137
+ console.log(c.dim(` Worktree path: ${absoluteWorktreePath}`));
1138
+ console.log(c.dim(` Expected base: ${absoluteBasePath}`));
1139
+ return;
1140
+ }
1141
+ // Warn if story is marked as done but has an existing worktree
1142
+ if (targetStory.frontmatter.status === 'done') {
1143
+ console.log(c.warning('⚠ Story is marked as done but has an existing worktree'));
1144
+ console.log(c.dim(' This may be a stale worktree that should be cleaned up.'));
1145
+ console.log();
1146
+ // Prompt user for confirmation to proceed
1147
+ const rl = readline.createInterface({
1148
+ input: process.stdin,
1149
+ output: process.stdout,
1150
+ });
1151
+ const answer = await new Promise((resolve) => {
1152
+ rl.question(c.dim('Continue with this worktree? (y/N): '), (ans) => {
1153
+ rl.close();
1154
+ resolve(ans.toLowerCase().trim());
1155
+ });
1156
+ });
1157
+ if (answer !== 'y' && answer !== 'yes') {
1158
+ console.log(c.dim('Aborted. Consider removing the worktree_path from the story frontmatter.'));
1159
+ return;
1160
+ }
1161
+ console.log();
1162
+ }
1163
+ const worktreeService = new GitWorktreeService(workingDir, resolvedBasePath);
1164
+ const branchName = worktreeService.getBranchName(targetStory.frontmatter.id, targetStory.slug);
1165
+ const validation = worktreeService.validateWorktreeForResume(existingWorktreePath, branchName);
1166
+ if (!validation.canResume) {
1167
+ console.log(c.error('Cannot resume worktree:'));
1168
+ validation.issues.forEach(issue => console.log(c.dim(` ✗ ${issue}`)));
1169
+ if (validation.requiresRecreation) {
1170
+ const branchExists = !validation.issues.includes('Branch does not exist');
1171
+ const dirMissing = validation.issues.includes('Worktree directory does not exist');
1172
+ const dirExists = !dirMissing;
1173
+ // Case 1: Directory missing but branch exists - recreate worktree from existing branch
1174
+ // Case 2: Directory exists but branch missing - recreate with new branch
1175
+ if ((branchExists && dirMissing) || (!branchExists && dirExists)) {
1176
+ const reason = branchExists
1177
+ ? 'Branch exists - automatically recreating worktree directory'
1178
+ : 'Directory exists - automatically recreating worktree with new branch';
1179
+ console.log(c.dim(`\n✓ ${reason}`));
1180
+ try {
1181
+ // Remove the old worktree reference if it exists
1182
+ const removeResult = spawnSync('git', ['worktree', 'remove', existingWorktreePath, '--force'], {
1183
+ cwd: workingDir,
1184
+ encoding: 'utf-8',
1185
+ shell: false,
1186
+ stdio: ['ignore', 'pipe', 'pipe'],
1187
+ });
1188
+ // Create the worktree at the same path
1189
+ // If branch exists, checkout that branch; otherwise create a new branch
1190
+ const baseBranch = worktreeService.detectBaseBranch();
1191
+ const worktreeAddArgs = branchExists
1192
+ ? ['worktree', 'add', existingWorktreePath, branchName]
1193
+ : ['worktree', 'add', '-b', branchName, existingWorktreePath, baseBranch];
1194
+ const addResult = spawnSync('git', worktreeAddArgs, {
1195
+ cwd: workingDir,
1196
+ encoding: 'utf-8',
1197
+ shell: false,
1198
+ stdio: ['ignore', 'pipe', 'pipe'],
1199
+ });
1200
+ if (addResult.status !== 0) {
1201
+ throw new Error(`Failed to recreate worktree: ${addResult.stderr}`);
1202
+ }
1203
+ // Install dependencies in the recreated worktree
1204
+ worktreeService.installDependencies(existingWorktreePath);
1205
+ console.log(c.success(`✓ Worktree recreated at ${existingWorktreePath}`));
1206
+ getLogger().info('worktree', `Recreated worktree for ${targetStory.frontmatter.id} at ${existingWorktreePath}`);
1207
+ }
1208
+ catch (error) {
1209
+ console.log(c.error(`Failed to recreate worktree: ${error instanceof Error ? error.message : String(error)}`));
1210
+ console.log(c.dim('Please manually remove the worktree_path from the story frontmatter and try again.'));
1211
+ return;
1212
+ }
1213
+ }
1214
+ else {
1215
+ console.log(c.dim('\nWorktree needs manual intervention. Please remove the worktree_path from the story frontmatter and try again.'));
1216
+ return;
1217
+ }
1218
+ }
1219
+ else {
1220
+ return;
1221
+ }
1222
+ }
844
1223
  // Reuse existing worktree
845
1224
  originalCwd = process.cwd();
846
1225
  worktreePath = existingWorktreePath;
847
1226
  process.chdir(worktreePath);
848
1227
  sdlcRoot = getSdlcRoot();
849
1228
  worktreeCreated = true;
1229
+ // Re-load story from worktree context to get current state
1230
+ const worktreeStory = findStoryById(sdlcRoot, targetStory.frontmatter.id);
1231
+ if (worktreeStory) {
1232
+ targetStory = worktreeStory;
1233
+ }
1234
+ // Get phase information for resume context
1235
+ const lastPhase = getLastCompletedPhase(targetStory);
1236
+ const nextPhase = getNextPhase(targetStory);
1237
+ // Get worktree status for uncommitted changes info
1238
+ const worktreeInfo = {
1239
+ path: existingWorktreePath,
1240
+ branch: branchName,
1241
+ storyId: targetStory.frontmatter.id,
1242
+ exists: true,
1243
+ };
1244
+ const worktreeStatus = worktreeService.getWorktreeStatus(worktreeInfo);
1245
+ // Check branch divergence
1246
+ const divergence = worktreeService.checkBranchDivergence(branchName);
850
1247
  console.log(c.success(`✓ Resuming in existing worktree: ${worktreePath}`));
851
- console.log(c.dim(` Branch: ai-sdlc/${targetStory.frontmatter.id}-${targetStory.slug}`));
1248
+ console.log(c.dim(` Branch: ${branchName}`));
1249
+ if (lastPhase) {
1250
+ console.log(c.dim(` Last completed phase: ${lastPhase}`));
1251
+ }
1252
+ if (nextPhase) {
1253
+ console.log(c.dim(` Next phase: ${nextPhase}`));
1254
+ }
1255
+ // Display uncommitted changes if present
1256
+ if (worktreeStatus.workingDirectoryStatus !== 'clean') {
1257
+ const totalChanges = worktreeStatus.modifiedFiles.length + worktreeStatus.untrackedFiles.length;
1258
+ console.log(c.dim(` Uncommitted changes: ${totalChanges} file(s)`));
1259
+ if (worktreeStatus.modifiedFiles.length > 0) {
1260
+ console.log(c.dim(` Modified: ${worktreeStatus.modifiedFiles.slice(0, 3).join(', ')}${worktreeStatus.modifiedFiles.length > 3 ? '...' : ''}`));
1261
+ }
1262
+ if (worktreeStatus.untrackedFiles.length > 0) {
1263
+ console.log(c.dim(` Untracked: ${worktreeStatus.untrackedFiles.slice(0, 3).join(', ')}${worktreeStatus.untrackedFiles.length > 3 ? '...' : ''}`));
1264
+ }
1265
+ }
1266
+ // Warn if branch has diverged significantly
1267
+ if (divergence.diverged && (divergence.ahead > DIVERGENCE_WARNING_THRESHOLD || divergence.behind > DIVERGENCE_WARNING_THRESHOLD)) {
1268
+ console.log(c.warning(` ⚠ Branch has diverged from base: ${divergence.ahead} ahead, ${divergence.behind} behind`));
1269
+ console.log(c.dim(` Consider rebasing to sync with latest changes`));
1270
+ }
852
1271
  console.log();
1272
+ // Log resume event
1273
+ getLogger().info('worktree', `Resumed worktree for ${targetStory.frontmatter.id} at ${worktreePath}`);
853
1274
  }
854
1275
  else {
855
1276
  // Create new worktree
@@ -864,49 +1285,260 @@ export async function run(options) {
864
1285
  return;
865
1286
  }
866
1287
  const worktreeService = new GitWorktreeService(workingDir, resolvedBasePath);
867
- // Validate git state for worktree creation
868
- const validation = worktreeService.validateCanCreateWorktree();
869
- if (!validation.valid) {
870
- console.log(c.error(`Error: ${validation.error}`));
871
- return;
872
- }
873
- try {
874
- // Detect base branch
875
- const baseBranch = worktreeService.detectBaseBranch();
876
- // Create worktree
877
- originalCwd = process.cwd();
878
- worktreePath = worktreeService.create({
879
- storyId: targetStory.frontmatter.id,
880
- slug: targetStory.slug,
881
- baseBranch,
882
- });
883
- // Change to worktree directory BEFORE updating story
884
- // This ensures story updates happen in the worktree, not on main
885
- // (allows parallel story launches from clean main)
886
- process.chdir(worktreePath);
887
- // Recalculate sdlcRoot for the worktree context
888
- sdlcRoot = getSdlcRoot();
889
- worktreeCreated = true;
890
- // Now update story frontmatter with worktree path (writes to worktree copy)
891
- // Re-resolve target story in worktree context
892
- const worktreeStory = findStoryById(sdlcRoot, targetStory.frontmatter.id);
893
- if (worktreeStory) {
894
- const updatedStory = await updateStoryField(worktreeStory, 'worktree_path', worktreePath);
895
- await writeStory(updatedStory);
896
- // Update targetStory reference for downstream use
897
- targetStory = updatedStory;
1288
+ // Check for existing worktree NOT recorded in story frontmatter
1289
+ // This catches scenarios where workflow was interrupted after worktree creation
1290
+ // but before the story file was updated
1291
+ const existingWorktree = worktreeService.findByStoryId(targetStory.frontmatter.id);
1292
+ let shouldCreateNewWorktree = !existingWorktree || !existingWorktree.exists;
1293
+ if (existingWorktree && existingWorktree.exists) {
1294
+ // Handle --clean flag: cleanup and restart
1295
+ if (options.clean) {
1296
+ console.log(c.warning('Existing worktree found - cleaning up before restart...'));
1297
+ console.log();
1298
+ const worktreeStatus = worktreeService.getWorktreeStatus(existingWorktree);
1299
+ const unpushedResult = worktreeService.hasUnpushedCommits(existingWorktree.path);
1300
+ const commitCount = worktreeService.getCommitCount(existingWorktree.path);
1301
+ const branchOnRemote = worktreeService.branchExistsOnRemote(existingWorktree.branch);
1302
+ // Display summary of what will be deleted
1303
+ console.log(c.bold('Cleanup Summary:'));
1304
+ console.log(c.dim('─'.repeat(60)));
1305
+ console.log(`${c.dim('Worktree Path:')} ${worktreeStatus.path}`);
1306
+ console.log(`${c.dim('Branch:')} ${worktreeStatus.branch}`);
1307
+ console.log(`${c.dim('Total Commits:')} ${commitCount}`);
1308
+ console.log(`${c.dim('Unpushed Commits:')} ${unpushedResult.hasUnpushed ? c.warning(unpushedResult.count.toString()) : c.success('0')}`);
1309
+ console.log(`${c.dim('Modified Files:')} ${worktreeStatus.modifiedFiles.length > 0 ? c.warning(worktreeStatus.modifiedFiles.length.toString()) : c.success('0')}`);
1310
+ console.log(`${c.dim('Untracked Files:')} ${worktreeStatus.untrackedFiles.length > 0 ? c.warning(worktreeStatus.untrackedFiles.length.toString()) : c.success('0')}`);
1311
+ console.log(`${c.dim('Remote Branch:')} ${branchOnRemote ? c.warning('EXISTS') : c.dim('none')}`);
1312
+ console.log();
1313
+ // Warn about data loss
1314
+ if (worktreeStatus.modifiedFiles.length > 0 || worktreeStatus.untrackedFiles.length > 0 || unpushedResult.hasUnpushed) {
1315
+ console.log(c.error('⚠ WARNING: This will DELETE all uncommitted and unpushed work!'));
1316
+ console.log();
1317
+ }
1318
+ // Check for --force flag to skip confirmation
1319
+ const forceCleanup = options.force;
1320
+ if (!forceCleanup) {
1321
+ // Prompt for confirmation
1322
+ const confirmed = await new Promise((resolve) => {
1323
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
1324
+ rl.question(c.warning('Are you sure you want to proceed? (y/N): '), (answer) => {
1325
+ rl.close();
1326
+ resolve(answer.toLowerCase() === 'y' || answer.toLowerCase() === 'yes');
1327
+ });
1328
+ });
1329
+ if (!confirmed) {
1330
+ console.log(c.info('Cleanup cancelled.'));
1331
+ return;
1332
+ }
1333
+ }
1334
+ console.log();
1335
+ const cleanupSpinner = ora('Cleaning up worktree...').start();
1336
+ try {
1337
+ // Remove worktree (force remove to handle uncommitted changes)
1338
+ const forceRemove = worktreeStatus.modifiedFiles.length > 0 || worktreeStatus.untrackedFiles.length > 0;
1339
+ worktreeService.remove(existingWorktree.path, forceRemove);
1340
+ cleanupSpinner.text = 'Worktree removed, deleting branch...';
1341
+ // Delete local branch
1342
+ worktreeService.deleteBranch(existingWorktree.branch, true);
1343
+ // Optionally delete remote branch if it exists
1344
+ if (branchOnRemote) {
1345
+ if (!forceCleanup) {
1346
+ cleanupSpinner.stop();
1347
+ const deleteRemote = await new Promise((resolve) => {
1348
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
1349
+ rl.question(c.warning('Branch exists on remote. Delete it too? (y/N): '), (answer) => {
1350
+ rl.close();
1351
+ resolve(answer.toLowerCase() === 'y' || answer.toLowerCase() === 'yes');
1352
+ });
1353
+ });
1354
+ if (deleteRemote) {
1355
+ cleanupSpinner.start('Deleting remote branch...');
1356
+ worktreeService.deleteRemoteBranch(existingWorktree.branch);
1357
+ }
1358
+ cleanupSpinner.start();
1359
+ }
1360
+ else {
1361
+ // --force provided, skip remote deletion by default (safer)
1362
+ cleanupSpinner.text = 'Skipping remote branch deletion (use manual cleanup if needed)';
1363
+ }
1364
+ }
1365
+ // Reset story workflow state
1366
+ cleanupSpinner.text = 'Resetting story state...';
1367
+ const { resetWorkflowState } = await import('../core/story.js');
1368
+ targetStory = await resetWorkflowState(targetStory);
1369
+ // Clear workflow checkpoint if exists
1370
+ if (hasWorkflowState(sdlcRoot, targetStory.frontmatter.id)) {
1371
+ await clearWorkflowState(sdlcRoot, targetStory.frontmatter.id);
1372
+ }
1373
+ cleanupSpinner.succeed(c.success('✓ Cleanup complete - ready to create fresh worktree'));
1374
+ console.log();
1375
+ }
1376
+ catch (error) {
1377
+ cleanupSpinner.fail(c.error('Cleanup failed'));
1378
+ console.log(c.error(`Error: ${error instanceof Error ? error.message : String(error)}`));
1379
+ return;
1380
+ }
1381
+ // After cleanup, create a fresh worktree
1382
+ shouldCreateNewWorktree = true;
1383
+ }
1384
+ else {
1385
+ // Not cleaning - resume in existing worktree (S-0063 feature)
1386
+ getLogger().info('worktree', `Detected existing worktree for ${targetStory.frontmatter.id} at ${existingWorktree.path}`);
1387
+ // Validate the existing worktree before resuming
1388
+ const branchName = worktreeService.getBranchName(targetStory.frontmatter.id, targetStory.slug);
1389
+ const validation = worktreeService.validateWorktreeForResume(existingWorktree.path, branchName);
1390
+ if (!validation.canResume) {
1391
+ console.log(c.error('Detected existing worktree but cannot resume:'));
1392
+ validation.issues.forEach(issue => console.log(c.dim(` ✗ ${issue}`)));
1393
+ if (validation.requiresRecreation) {
1394
+ const branchExists = !validation.issues.includes('Branch does not exist');
1395
+ const dirMissing = validation.issues.includes('Worktree directory does not exist');
1396
+ const dirExists = !dirMissing;
1397
+ // Case 1: Directory missing but branch exists - recreate worktree from existing branch
1398
+ // Case 2: Directory exists but branch missing - recreate with new branch
1399
+ if ((branchExists && dirMissing) || (!branchExists && dirExists)) {
1400
+ const reason = branchExists
1401
+ ? 'Branch exists - automatically recreating worktree directory'
1402
+ : 'Directory exists - automatically recreating worktree with new branch';
1403
+ console.log(c.dim(`\n✓ ${reason}`));
1404
+ try {
1405
+ // Remove the old worktree reference if it exists
1406
+ const removeResult = spawnSync('git', ['worktree', 'remove', existingWorktree.path, '--force'], {
1407
+ cwd: workingDir,
1408
+ encoding: 'utf-8',
1409
+ shell: false,
1410
+ stdio: ['ignore', 'pipe', 'pipe'],
1411
+ });
1412
+ // Create the worktree at the same path
1413
+ // If branch exists, checkout that branch; otherwise create a new branch
1414
+ const baseBranch = worktreeService.detectBaseBranch();
1415
+ const worktreeAddArgs = branchExists
1416
+ ? ['worktree', 'add', existingWorktree.path, branchName]
1417
+ : ['worktree', 'add', '-b', branchName, existingWorktree.path, baseBranch];
1418
+ const addResult = spawnSync('git', worktreeAddArgs, {
1419
+ cwd: workingDir,
1420
+ encoding: 'utf-8',
1421
+ shell: false,
1422
+ stdio: ['ignore', 'pipe', 'pipe'],
1423
+ });
1424
+ if (addResult.status !== 0) {
1425
+ throw new Error(`Failed to recreate worktree: ${addResult.stderr}`);
1426
+ }
1427
+ // Install dependencies in the recreated worktree
1428
+ worktreeService.installDependencies(existingWorktree.path);
1429
+ console.log(c.success(`✓ Worktree recreated at ${existingWorktree.path}`));
1430
+ getLogger().info('worktree', `Recreated worktree for ${targetStory.frontmatter.id} at ${existingWorktree.path}`);
1431
+ }
1432
+ catch (error) {
1433
+ console.log(c.error(`Failed to recreate worktree: ${error instanceof Error ? error.message : String(error)}`));
1434
+ console.log(c.dim('Please manually remove it with:'));
1435
+ console.log(c.dim(` git worktree remove ${existingWorktree.path}`));
1436
+ return;
1437
+ }
1438
+ }
1439
+ else {
1440
+ console.log(c.dim('\nWorktree needs manual intervention. Please remove it manually with:'));
1441
+ console.log(c.dim(` git worktree remove ${existingWorktree.path}`));
1442
+ return;
1443
+ }
1444
+ }
1445
+ else {
1446
+ return;
1447
+ }
1448
+ }
1449
+ // Automatically resume in the existing worktree
1450
+ originalCwd = process.cwd();
1451
+ worktreePath = existingWorktree.path;
1452
+ process.chdir(worktreePath);
1453
+ sdlcRoot = getSdlcRoot();
1454
+ worktreeCreated = true;
1455
+ // Update story frontmatter with worktree path (sync state)
1456
+ const worktreeStory = findStoryById(sdlcRoot, targetStory.frontmatter.id);
1457
+ if (worktreeStory) {
1458
+ const updatedStory = await updateStoryField(worktreeStory, 'worktree_path', worktreePath);
1459
+ await writeStory(updatedStory);
1460
+ targetStory = updatedStory;
1461
+ }
1462
+ // Get phase information for resume context
1463
+ const lastPhase = getLastCompletedPhase(targetStory);
1464
+ const nextPhase = getNextPhase(targetStory);
1465
+ // Get worktree status for uncommitted changes info
1466
+ const worktreeStatus = worktreeService.getWorktreeStatus(existingWorktree);
1467
+ // Check branch divergence
1468
+ const divergence = worktreeService.checkBranchDivergence(branchName);
1469
+ console.log(c.success(`✓ Resuming in existing worktree: ${worktreePath}`));
1470
+ console.log(c.dim(` Branch: ${branchName}`));
1471
+ console.log(c.dim(` (Worktree path synced to story frontmatter)`));
1472
+ if (lastPhase) {
1473
+ console.log(c.dim(` Last completed phase: ${lastPhase}`));
1474
+ }
1475
+ if (nextPhase) {
1476
+ console.log(c.dim(` Next phase: ${nextPhase}`));
1477
+ }
1478
+ // Display uncommitted changes if present
1479
+ if (worktreeStatus.workingDirectoryStatus !== 'clean') {
1480
+ const totalChanges = worktreeStatus.modifiedFiles.length + worktreeStatus.untrackedFiles.length;
1481
+ console.log(c.dim(` Uncommitted changes: ${totalChanges} file(s)`));
1482
+ if (worktreeStatus.modifiedFiles.length > 0) {
1483
+ console.log(c.dim(` Modified: ${worktreeStatus.modifiedFiles.slice(0, 3).join(', ')}${worktreeStatus.modifiedFiles.length > 3 ? '...' : ''}`));
1484
+ }
1485
+ if (worktreeStatus.untrackedFiles.length > 0) {
1486
+ console.log(c.dim(` Untracked: ${worktreeStatus.untrackedFiles.slice(0, 3).join(', ')}${worktreeStatus.untrackedFiles.length > 3 ? '...' : ''}`));
1487
+ }
1488
+ }
1489
+ // Warn if branch has diverged significantly
1490
+ if (divergence.diverged && (divergence.ahead > DIVERGENCE_WARNING_THRESHOLD || divergence.behind > DIVERGENCE_WARNING_THRESHOLD)) {
1491
+ console.log(c.warning(` ⚠ Branch has diverged from base: ${divergence.ahead} ahead, ${divergence.behind} behind`));
1492
+ console.log(c.dim(` Consider rebasing to sync with latest changes`));
1493
+ }
1494
+ console.log();
898
1495
  }
899
- console.log(c.success(`✓ Created worktree at: ${worktreePath}`));
900
- console.log(c.dim(` Branch: ai-sdlc/${targetStory.frontmatter.id}-${targetStory.slug}`));
901
- console.log();
902
1496
  }
903
- catch (error) {
904
- // Restore directory on worktree creation failure
905
- if (originalCwd) {
906
- process.chdir(originalCwd);
1497
+ if (shouldCreateNewWorktree) {
1498
+ // Validate git state for worktree creation
1499
+ const validation = worktreeService.validateCanCreateWorktree();
1500
+ if (!validation.valid) {
1501
+ console.log(c.error(`Error: ${validation.error}`));
1502
+ return;
1503
+ }
1504
+ try {
1505
+ // Detect base branch
1506
+ const baseBranch = worktreeService.detectBaseBranch();
1507
+ // Create worktree
1508
+ originalCwd = process.cwd();
1509
+ worktreePath = worktreeService.create({
1510
+ storyId: targetStory.frontmatter.id,
1511
+ slug: targetStory.slug,
1512
+ baseBranch,
1513
+ });
1514
+ // Change to worktree directory BEFORE updating story
1515
+ // This ensures story updates happen in the worktree, not on main
1516
+ // (allows parallel story launches from clean main)
1517
+ process.chdir(worktreePath);
1518
+ // Recalculate sdlcRoot for the worktree context
1519
+ sdlcRoot = getSdlcRoot();
1520
+ worktreeCreated = true;
1521
+ // Now update story frontmatter with worktree path (writes to worktree copy)
1522
+ // Re-resolve target story in worktree context
1523
+ const worktreeStory = findStoryById(sdlcRoot, targetStory.frontmatter.id);
1524
+ if (worktreeStory) {
1525
+ const updatedStory = await updateStoryField(worktreeStory, 'worktree_path', worktreePath);
1526
+ await writeStory(updatedStory);
1527
+ // Update targetStory reference for downstream use
1528
+ targetStory = updatedStory;
1529
+ }
1530
+ console.log(c.success(`✓ Created worktree at: ${worktreePath}`));
1531
+ console.log(c.dim(` Branch: ai-sdlc/${targetStory.frontmatter.id}-${targetStory.slug}`));
1532
+ console.log();
1533
+ }
1534
+ catch (error) {
1535
+ // Restore directory on worktree creation failure
1536
+ if (originalCwd) {
1537
+ process.chdir(originalCwd);
1538
+ }
1539
+ console.log(c.error(`Failed to create worktree: ${error instanceof Error ? error.message : String(error)}`));
1540
+ return;
907
1541
  }
908
- console.log(c.error(`Failed to create worktree: ${error instanceof Error ? error.message : String(error)}`));
909
- return;
910
1542
  }
911
1543
  }
912
1544
  }
@@ -1017,6 +1649,56 @@ export async function run(options) {
1017
1649
  return;
1018
1650
  }
1019
1651
  }
1652
+ else if (reviewResult.decision === ReviewDecision.RECOVERY) {
1653
+ // Implementation recovery: reset implementation_complete and increment implementation retry count
1654
+ // This is distinct from REJECTED which resets the entire RPIV cycle
1655
+ const story = parseStory(action.storyPath);
1656
+ const config = loadConfig();
1657
+ const retryCount = story.frontmatter.implementation_retry_count || 0;
1658
+ const maxRetries = getEffectiveMaxImplementationRetries(story, config);
1659
+ const maxRetriesDisplay = Number.isFinite(maxRetries) ? maxRetries : '∞';
1660
+ console.log();
1661
+ console.log(c.warning(`🔄 Implementation recovery triggered (attempt ${retryCount + 1}/${maxRetriesDisplay})`));
1662
+ console.log(c.dim(` Reason: ${story.frontmatter.last_restart_reason || 'No source code changes detected'}`));
1663
+ // Increment implementation retry count
1664
+ await incrementImplementationRetryCount(story);
1665
+ // Check if we've exceeded max implementation retries after incrementing
1666
+ const freshStory = parseStory(action.storyPath);
1667
+ if (isAtMaxImplementationRetries(freshStory, config)) {
1668
+ console.log();
1669
+ console.log(c.error('═'.repeat(50)));
1670
+ console.log(c.error(`✗ Implementation recovery failed - maximum retries reached`));
1671
+ console.log(c.error('═'.repeat(50)));
1672
+ console.log(c.dim(`Story has reached the maximum implementation retry limit (${maxRetries}).`));
1673
+ console.log(c.warning('Marking story as blocked. Manual intervention required.'));
1674
+ // Mark story as blocked
1675
+ await updateStoryStatus(freshStory, 'blocked');
1676
+ console.log(c.info('Story status updated to: blocked'));
1677
+ await clearWorkflowState(sdlcRoot, action.storyId);
1678
+ process.exit(1);
1679
+ }
1680
+ // Regenerate actions to restart from implementation phase
1681
+ const newActions = generateFullSDLCActions(freshStory, c);
1682
+ if (newActions.length > 0) {
1683
+ currentActions = newActions;
1684
+ currentActionIndex = 0;
1685
+ console.log(c.info(` → Restarting from ${newActions[0].type} phase`));
1686
+ console.log();
1687
+ continue; // Restart the loop with new actions
1688
+ }
1689
+ else {
1690
+ console.log(c.error('Error: No actions generated for recovery. Manual intervention required.'));
1691
+ process.exit(1);
1692
+ }
1693
+ }
1694
+ else if (reviewResult.decision === ReviewDecision.FAILED) {
1695
+ // Review agent failed - don't increment retry count
1696
+ console.log();
1697
+ console.log(c.error(`✗ Review process failed: ${reviewResult.error || 'Unknown error'}`));
1698
+ console.log(c.warning('This does not count as a retry attempt. You can retry manually.'));
1699
+ await clearWorkflowState(sdlcRoot, action.storyId);
1700
+ process.exit(1);
1701
+ }
1020
1702
  }
1021
1703
  // Save checkpoint after successful action
1022
1704
  if (actionResult.success) {
@@ -1241,8 +1923,43 @@ async function executeAction(action, sdlcRoot) {
1241
1923
  story = await autoCompleteStoryAfterReview(story, config, reviewResult);
1242
1924
  // Log auto-completion if it occurred
1243
1925
  if (reviewResult.decision === ReviewDecision.APPROVED && config.reviewConfig.autoCompleteOnApproval) {
1926
+ // Reset implementation retry count on successful review approval
1927
+ await resetImplementationRetryCount(story);
1928
+ storyLogger?.log('INFO', 'Implementation retry count reset after review approval');
1244
1929
  spinner.text = c.success('Review approved - auto-completing story');
1245
1930
  storyLogger?.log('INFO', `Story auto-completed after review approval: "${story.frontmatter.title}"`);
1931
+ // Auto-create PR in automated mode
1932
+ const workflowState = await loadWorkflowState(sdlcRoot, story.frontmatter.id);
1933
+ const isAutoMode = workflowState?.context.options.auto ?? false;
1934
+ if (isAutoMode || config.reviewConfig.autoCreatePROnApproval) {
1935
+ try {
1936
+ // Create PR (this will automatically commit any uncommitted changes)
1937
+ spinner.text = c.dim('Creating pull request...');
1938
+ const { createPullRequest } = await import('../agents/review.js');
1939
+ const prResult = await createPullRequest(action.storyPath, sdlcRoot);
1940
+ if (prResult.success) {
1941
+ spinner.text = c.success('Review approved - PR created');
1942
+ storyLogger?.log('INFO', `PR created successfully for ${story.frontmatter.id}`);
1943
+ }
1944
+ else {
1945
+ // PR creation failed - mark as blocked
1946
+ const { updateStoryStatus } = await import('../core/story.js');
1947
+ const blockedStory = await updateStoryStatus(story, 'blocked');
1948
+ await writeStory(blockedStory);
1949
+ spinner.text = c.warning('Review approved but PR creation failed - story marked as blocked');
1950
+ storyLogger?.log('WARN', `PR creation failed for ${story.frontmatter.id}: ${prResult.error || 'Unknown error'}`);
1951
+ }
1952
+ }
1953
+ catch (error) {
1954
+ // Error during PR creation - mark as blocked
1955
+ const { updateStoryStatus } = await import('../core/story.js');
1956
+ const blockedStory = await updateStoryStatus(story, 'blocked');
1957
+ await writeStory(blockedStory);
1958
+ const errorMsg = error instanceof Error ? error.message : String(error);
1959
+ spinner.text = c.warning(`Review approved but auto-PR failed: ${errorMsg}`);
1960
+ storyLogger?.log('ERROR', `Auto-PR failed for ${story.frontmatter.id}: ${errorMsg}`);
1961
+ }
1962
+ }
1246
1963
  // Handle worktree cleanup if story has a worktree
1247
1964
  if (story.frontmatter.worktree_path) {
1248
1965
  await handleWorktreeCleanup(story, config, c);
@@ -2000,6 +2717,15 @@ async function handleWorktreeCleanup(story, config, c) {
2000
2717
  await writeStory(updated);
2001
2718
  }
2002
2719
  }
2720
+ /**
2721
+ * Security: Escape shell arguments for safe use in commands
2722
+ * For use with execSync when shell execution is required
2723
+ * @internal Exported for testing
2724
+ */
2725
+ export function escapeShellArg(arg) {
2726
+ // Replace single quotes with '\'' and wrap in single quotes
2727
+ return `'${arg.replace(/'/g, "'\\''")}'`;
2728
+ }
2003
2729
  /**
2004
2730
  * List all ai-sdlc managed worktrees
2005
2731
  */