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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import path from 'path';
import type { Feature } from '@automaker/types';

/**
 * Helper to normalize paths for cross-platform test compatibility.
 */
const normalizePath = (p: string): string => path.resolve(p);
import {
  ExecutionService,
  type RunAgentFn,
  type ExecutePipelineFn,
  type UpdateFeatureStatusFn,
  type LoadFeatureFn,
  type GetPlanningPromptPrefixFn,
  type SaveFeatureSummaryFn,
  type RecordLearningsFn,
  type ContextExistsFn,
  type ResumeFeatureFn,
  type TrackFailureFn,
  type SignalPauseFn,
  type RecordSuccessFn,
} from '../../../src/services/execution-service.js';
import type { TypedEventBus } from '../../../src/services/typed-event-bus.js';
import type {
  ConcurrencyManager,
  RunningFeature,
} from '../../../src/services/concurrency-manager.js';
import type { WorktreeResolver } from '../../../src/services/worktree-resolver.js';
import type { SettingsService } from '../../../src/services/settings-service.js';
import { pipelineService } from '../../../src/services/pipeline-service.js';
import * as secureFs from '../../../src/lib/secure-fs.js';
import { getFeatureDir } from '@automaker/platform';
import {
  getPromptCustomization,
  getAutoLoadClaudeMdSetting,
  getUseClaudeCodeSystemPromptSetting,
  filterClaudeMdFromContext,
} from '../../../src/lib/settings-helpers.js';
import { extractSummary } from '../../../src/services/spec-parser.js';
import { resolveModelString } from '@automaker/model-resolver';

// Mock pipelineService
vi.mock('../../../src/services/pipeline-service.js', () => ({
  pipelineService: {
    getPipelineConfig: vi.fn(),
    isPipelineStatus: vi.fn(),
    getStepIdFromStatus: vi.fn(),
  },
}));

// Mock secureFs
vi.mock('../../../src/lib/secure-fs.js', () => ({
  readFile: vi.fn(),
  writeFile: vi.fn(),
  mkdir: vi.fn(),
  access: vi.fn(),
}));

// Mock settings helpers
vi.mock('../../../src/lib/settings-helpers.js', () => ({
  getPromptCustomization: vi.fn().mockResolvedValue({
    taskExecution: {
      implementationInstructions: 'test instructions',
      playwrightVerificationInstructions: 'test playwright',
      continuationAfterApprovalTemplate:
        '{{userFeedback}}\n\nApproved plan:\n{{approvedPlan}}\n\nProceed.',
    },
  }),
  getAutoLoadClaudeMdSetting: vi.fn().mockResolvedValue(true),
  getUseClaudeCodeSystemPromptSetting: vi.fn().mockResolvedValue(true),
  filterClaudeMdFromContext: vi.fn().mockReturnValue('context prompt'),
}));

// Mock sdk-options
vi.mock('../../../src/lib/sdk-options.js', () => ({
  validateWorkingDirectory: vi.fn(),
}));

// Mock platform
vi.mock('@automaker/platform', () => ({
  getFeatureDir: vi
    .fn()
    .mockImplementation(
      (projectPath: string, featureId: string) => `${projectPath}/.automaker/features/${featureId}`
    ),
}));

// Mock model-resolver
vi.mock('@automaker/model-resolver', () => ({
  resolveModelString: vi.fn().mockReturnValue('claude-sonnet-4'),
  DEFAULT_MODELS: { claude: 'claude-sonnet-4' },
}));

// Mock provider-factory
vi.mock('../../../src/providers/provider-factory.js', () => ({
  ProviderFactory: {
    getProviderNameForModel: vi.fn().mockReturnValue('anthropic'),
  },
}));

// Mock spec-parser
vi.mock('../../../src/services/spec-parser.js', () => ({
  extractSummary: vi.fn().mockReturnValue('Test summary'),
}));

// Mock @automaker/utils
vi.mock('@automaker/utils', () => ({
  createLogger: vi.fn().mockReturnValue({
    info: vi.fn(),
    warn: vi.fn(),
    error: vi.fn(),
    debug: vi.fn(),
  }),
  classifyError: vi.fn((error: unknown) => {
    const err = error as Error | null;
    if (err?.name === 'AbortError' || err?.message?.includes('abort')) {
      return { isAbort: true, type: 'abort', message: 'Aborted' };
    }
    return { isAbort: false, type: 'unknown', message: err?.message || 'Unknown error' };
  }),
  loadContextFiles: vi.fn(),
  recordMemoryUsage: vi.fn().mockResolvedValue(undefined),
}));

describe('execution-service.ts', () => {
  // Mock dependencies
  let mockEventBus: TypedEventBus;
  let mockConcurrencyManager: ConcurrencyManager;
  let mockWorktreeResolver: WorktreeResolver;
  let mockSettingsService: SettingsService | null;

  // Callback mocks
  let mockRunAgentFn: RunAgentFn;
  let mockExecutePipelineFn: ExecutePipelineFn;
  let mockUpdateFeatureStatusFn: UpdateFeatureStatusFn;
  let mockLoadFeatureFn: LoadFeatureFn;
  let mockGetPlanningPromptPrefixFn: GetPlanningPromptPrefixFn;
  let mockSaveFeatureSummaryFn: SaveFeatureSummaryFn;
  let mockRecordLearningsFn: RecordLearningsFn;
  let mockContextExistsFn: ContextExistsFn;
  let mockResumeFeatureFn: ResumeFeatureFn;
  let mockTrackFailureFn: TrackFailureFn;
  let mockSignalPauseFn: SignalPauseFn;
  let mockRecordSuccessFn: RecordSuccessFn;
  let mockSaveExecutionStateFn: vi.Mock;
  let mockLoadContextFilesFn: vi.Mock;

  let service: ExecutionService;

  // Test data
  const testFeature: Feature = {
    id: 'feature-1',
    title: 'Test Feature',
    category: 'test',
    description: 'Test description',
    status: 'backlog',
    branchName: 'feature/test-1',
  };

  const createRunningFeature = (featureId: string): RunningFeature => ({
    featureId,
    projectPath: '/test/project',
    worktreePath: null,
    branchName: null,
    abortController: new AbortController(),
    isAutoMode: false,
    startTime: Date.now(),
    leaseCount: 1,
  });

  beforeEach(() => {
    vi.clearAllMocks();

    mockEventBus = {
      emitAutoModeEvent: vi.fn(),
    } as unknown as TypedEventBus;

    mockConcurrencyManager = {
      acquire: vi.fn().mockImplementation(({ featureId, isAutoMode }) => ({
        ...createRunningFeature(featureId),
        isAutoMode: isAutoMode ?? false,
      })),
      release: vi.fn(),
      getRunningFeature: vi.fn(),
      isRunning: vi.fn(),
    } as unknown as ConcurrencyManager;

    mockWorktreeResolver = {
      findWorktreeForBranch: vi.fn().mockResolvedValue('/test/worktree'),
    } as unknown as WorktreeResolver;

    mockSettingsService = null;

    mockRunAgentFn = vi.fn().mockResolvedValue(undefined);
    mockExecutePipelineFn = vi.fn().mockResolvedValue(undefined);
    mockUpdateFeatureStatusFn = vi.fn().mockResolvedValue(undefined);
    mockLoadFeatureFn = vi.fn().mockResolvedValue(testFeature);
    mockGetPlanningPromptPrefixFn = vi.fn().mockResolvedValue('');
    mockSaveFeatureSummaryFn = vi.fn().mockResolvedValue(undefined);
    mockRecordLearningsFn = vi.fn().mockResolvedValue(undefined);
    mockContextExistsFn = vi.fn().mockResolvedValue(false);
    mockResumeFeatureFn = vi.fn().mockResolvedValue(undefined);
    mockTrackFailureFn = vi.fn().mockReturnValue(false);
    mockSignalPauseFn = vi.fn();
    mockRecordSuccessFn = vi.fn();
    mockSaveExecutionStateFn = vi.fn().mockResolvedValue(undefined);
    mockLoadContextFilesFn = vi.fn().mockResolvedValue({
      formattedPrompt: 'test context',
      memoryFiles: [],
    });

    // Default mocks for secureFs
    // Include tool usage markers to simulate meaningful agent output.
    // The execution service checks for '🔧 Tool:' markers and minimum
    // output length to determine if the agent did real work.
    vi.mocked(secureFs.readFile).mockResolvedValue(
      'Starting implementation...\n\n🔧 Tool: Read\nInput: {"file_path": "/src/index.ts"}\n\n' +
        '🔧 Tool: Edit\nInput: {"file_path": "/src/index.ts", "old_string": "foo", "new_string": "bar"}\n\n' +
        'Implementation complete. Updated the code as requested.'
    );
    vi.mocked(secureFs.access).mockResolvedValue(undefined);

    // Re-setup platform mocks
    vi.mocked(getFeatureDir).mockImplementation(
      (projectPath: string, featureId: string) => `${projectPath}/.automaker/features/${featureId}`
    );

    // Default pipeline config (no steps)
    vi.mocked(pipelineService.getPipelineConfig).mockResolvedValue({ version: 1, steps: [] });

    // Re-setup settings helpers mocks (vi.clearAllMocks clears implementations)
    vi.mocked(getPromptCustomization).mockResolvedValue({
      taskExecution: {
        implementationInstructions: 'test instructions',
        playwrightVerificationInstructions: 'test playwright',
        continuationAfterApprovalTemplate:
          '{{userFeedback}}\n\nApproved plan:\n{{approvedPlan}}\n\nProceed.',
      },
    } as Awaited<ReturnType<typeof getPromptCustomization>>);
    vi.mocked(getAutoLoadClaudeMdSetting).mockResolvedValue(true);
    vi.mocked(getUseClaudeCodeSystemPromptSetting).mockResolvedValue(true);
    vi.mocked(filterClaudeMdFromContext).mockReturnValue('context prompt');

    // Re-setup spec-parser mock
    vi.mocked(extractSummary).mockReturnValue('Test summary');

    // Re-setup model-resolver mock
    vi.mocked(resolveModelString).mockReturnValue('claude-sonnet-4');

    service = new ExecutionService(
      mockEventBus,
      mockConcurrencyManager,
      mockWorktreeResolver,
      mockSettingsService,
      mockRunAgentFn,
      mockExecutePipelineFn,
      mockUpdateFeatureStatusFn,
      mockLoadFeatureFn,
      mockGetPlanningPromptPrefixFn,
      mockSaveFeatureSummaryFn,
      mockRecordLearningsFn,
      mockContextExistsFn,
      mockResumeFeatureFn,
      mockTrackFailureFn,
      mockSignalPauseFn,
      mockRecordSuccessFn,
      mockSaveExecutionStateFn,
      mockLoadContextFilesFn
    );
  });

  afterEach(() => {
    vi.clearAllMocks();
  });

  describe('constructor', () => {
    it('creates service with all dependencies', () => {
      expect(service).toBeInstanceOf(ExecutionService);
    });

    it('accepts null settingsService', () => {
      const svc = new ExecutionService(
        mockEventBus,
        mockConcurrencyManager,
        mockWorktreeResolver,
        null,
        mockRunAgentFn,
        mockExecutePipelineFn,
        mockUpdateFeatureStatusFn,
        mockLoadFeatureFn,
        mockGetPlanningPromptPrefixFn,
        mockSaveFeatureSummaryFn,
        mockRecordLearningsFn,
        mockContextExistsFn,
        mockResumeFeatureFn,
        mockTrackFailureFn,
        mockSignalPauseFn,
        mockRecordSuccessFn,
        mockSaveExecutionStateFn,
        mockLoadContextFilesFn
      );
      expect(svc).toBeInstanceOf(ExecutionService);
    });
  });

  describe('buildFeaturePrompt', () => {
    const taskPrompts = {
      implementationInstructions: 'impl instructions',
      playwrightVerificationInstructions: 'playwright instructions',
    };

    it('includes feature title and description', () => {
      const prompt = service.buildFeaturePrompt(testFeature, taskPrompts);
      expect(prompt).toContain('**Feature ID:** feature-1');
      expect(prompt).toContain('Test description');
    });

    it('includes specification when present', () => {
      const featureWithSpec: Feature = {
        ...testFeature,
        spec: 'Detailed specification here',
      };
      const prompt = service.buildFeaturePrompt(featureWithSpec, taskPrompts);
      expect(prompt).toContain('**Specification:**');
      expect(prompt).toContain('Detailed specification here');
    });

    it('includes acceptance criteria from task prompts', () => {
      const prompt = service.buildFeaturePrompt(testFeature, taskPrompts);
      expect(prompt).toContain('impl instructions');
    });

    it('adds playwright instructions when skipTests is false', () => {
      const featureWithTests: Feature = { ...testFeature, skipTests: false };
      const prompt = service.buildFeaturePrompt(featureWithTests, taskPrompts);
      expect(prompt).toContain('playwright instructions');
    });

    it('omits playwright instructions when skipTests is true', () => {
      const featureWithoutTests: Feature = { ...testFeature, skipTests: true };
      const prompt = service.buildFeaturePrompt(featureWithoutTests, taskPrompts);
      expect(prompt).not.toContain('playwright instructions');
    });

    it('includes images note when imagePaths present', () => {
      const featureWithImages: Feature = {
        ...testFeature,
        imagePaths: ['/path/to/image.png', { path: '/path/to/image2.jpg', mimeType: 'image/jpeg' }],
      };
      const prompt = service.buildFeaturePrompt(featureWithImages, taskPrompts);
      expect(prompt).toContain('Context Images Attached:');
      expect(prompt).toContain('2 image(s)');
    });

    it('extracts title from first line of description', () => {
      const featureWithLongDesc: Feature = {
        ...testFeature,
        description: 'First line title\nRest of description',
      };
      const prompt = service.buildFeaturePrompt(featureWithLongDesc, taskPrompts);
      expect(prompt).toContain('**Title:** First line title');
    });

    it('truncates long titles to 60 characters', () => {
      const longDescription = 'A'.repeat(100);
      const featureWithLongTitle: Feature = {
        ...testFeature,
        description: longDescription,
      };
      const prompt = service.buildFeaturePrompt(featureWithLongTitle, taskPrompts);
      expect(prompt).toContain('**Title:** ' + 'A'.repeat(57) + '...');
    });
  });

  describe('executeFeature', () => {
    it('throws if feature not found', async () => {
      mockLoadFeatureFn = vi.fn().mockResolvedValue(null);
      const svc = new ExecutionService(
        mockEventBus,
        mockConcurrencyManager,
        mockWorktreeResolver,
        mockSettingsService,
        mockRunAgentFn,
        mockExecutePipelineFn,
        mockUpdateFeatureStatusFn,
        mockLoadFeatureFn,
        mockGetPlanningPromptPrefixFn,
        mockSaveFeatureSummaryFn,
        mockRecordLearningsFn,
        mockContextExistsFn,
        mockResumeFeatureFn,
        mockTrackFailureFn,
        mockSignalPauseFn,
        mockRecordSuccessFn,
        mockSaveExecutionStateFn,
        mockLoadContextFilesFn
      );

      await svc.executeFeature('/test/project', 'nonexistent');

      // Error event should be emitted
      expect(mockEventBus.emitAutoModeEvent).toHaveBeenCalledWith(
        'auto_mode_error',
        expect.objectContaining({ featureId: 'nonexistent' })
      );
    });

    it('acquires running feature slot', async () => {
      await service.executeFeature('/test/project', 'feature-1');

      expect(mockConcurrencyManager.acquire).toHaveBeenCalledWith(
        expect.objectContaining({
          featureId: 'feature-1',
          projectPath: '/test/project',
        })
      );
    });

    it('updates status to in_progress before starting', async () => {
      await service.executeFeature('/test/project', 'feature-1');

      expect(mockUpdateFeatureStatusFn).toHaveBeenCalledWith(
        '/test/project',
        'feature-1',
        'in_progress'
      );
    });

    it('emits feature_start event after status update', async () => {
      await service.executeFeature('/test/project', 'feature-1');

      expect(mockEventBus.emitAutoModeEvent).toHaveBeenCalledWith(
        'auto_mode_feature_start',
        expect.objectContaining({
          featureId: 'feature-1',
          projectPath: '/test/project',
        })
      );

      // Verify order: status update happens before event
      const statusCallIndex = mockUpdateFeatureStatusFn.mock.invocationCallOrder[0];
      const eventCallIndex = mockEventBus.emitAutoModeEvent.mock.invocationCallOrder[0];
      expect(statusCallIndex).toBeLessThan(eventCallIndex);
    });

    it('runs agent with correct prompt', async () => {
      await service.executeFeature('/test/project', 'feature-1');

      expect(mockRunAgentFn).toHaveBeenCalled();
      const callArgs = mockRunAgentFn.mock.calls[0];
      expect(callArgs[0]).toMatch(/test.*project/); // workDir contains project
      expect(callArgs[1]).toBe('feature-1');
      expect(callArgs[2]).toContain('Feature Task');
      expect(callArgs[3]).toBeInstanceOf(AbortController);
      expect(callArgs[4]).toBe('/test/project');
      // Model (index 6) should be resolved
      expect(callArgs[6]).toBe('claude-sonnet-4');
    });

    it('passes providerId to runAgentFn when present on feature', async () => {
      const featureWithProvider: Feature = {
        ...testFeature,
        providerId: 'zai-provider-1',
      };
      vi.mocked(mockLoadFeatureFn).mockResolvedValue(featureWithProvider);

      await service.executeFeature('/test/project', 'feature-1');

      expect(mockRunAgentFn).toHaveBeenCalled();
      const callArgs = mockRunAgentFn.mock.calls[0];
      const options = callArgs[7];
      expect(options.providerId).toBe('zai-provider-1');
    });

    it('executes pipeline after agent completes', async () => {
      const pipelineSteps = [{ id: 'step-1', name: 'Step 1', order: 1, instructions: 'Do step 1' }];
      vi.mocked(pipelineService.getPipelineConfig).mockResolvedValue({
        version: 1,
        steps: pipelineSteps as any,
      });

      await service.executeFeature('/test/project', 'feature-1');

      // Agent runs first
      expect(mockRunAgentFn).toHaveBeenCalled();
      // Then pipeline executes
      expect(mockExecutePipelineFn).toHaveBeenCalledWith(
        expect.objectContaining({
          projectPath: '/test/project',
          featureId: 'feature-1',
          steps: pipelineSteps,
        })
      );
    });

    it('updates status to verified on completion', async () => {
      await service.executeFeature('/test/project', 'feature-1');

      expect(mockUpdateFeatureStatusFn).toHaveBeenCalledWith(
        '/test/project',
        'feature-1',
        'verified'
      );
    });

    it('updates status to waiting_approval when skipTests is true', async () => {
      mockLoadFeatureFn = vi.fn().mockResolvedValue({ ...testFeature, skipTests: true });
      const svc = new ExecutionService(
        mockEventBus,
        mockConcurrencyManager,
        mockWorktreeResolver,
        mockSettingsService,
        mockRunAgentFn,
        mockExecutePipelineFn,
        mockUpdateFeatureStatusFn,
        mockLoadFeatureFn,
        mockGetPlanningPromptPrefixFn,
        mockSaveFeatureSummaryFn,
        mockRecordLearningsFn,
        mockContextExistsFn,
        mockResumeFeatureFn,
        mockTrackFailureFn,
        mockSignalPauseFn,
        mockRecordSuccessFn,
        mockSaveExecutionStateFn,
        mockLoadContextFilesFn
      );

      await svc.executeFeature('/test/project', 'feature-1');

      expect(mockUpdateFeatureStatusFn).toHaveBeenCalledWith(
        '/test/project',
        'feature-1',
        'waiting_approval'
      );
    });

    it('records success on completion', async () => {
      await service.executeFeature('/test/project', 'feature-1');

      expect(mockRecordSuccessFn).toHaveBeenCalled();
    });

    it('releases running feature in finally block', async () => {
      await service.executeFeature('/test/project', 'feature-1');

      expect(mockConcurrencyManager.release).toHaveBeenCalledWith('feature-1', undefined);
    });

    it('redirects to resumeFeature when context exists', async () => {
      mockContextExistsFn = vi.fn().mockResolvedValue(true);
      const svc = new ExecutionService(
        mockEventBus,
        mockConcurrencyManager,
        mockWorktreeResolver,
        mockSettingsService,
        mockRunAgentFn,
        mockExecutePipelineFn,
        mockUpdateFeatureStatusFn,
        mockLoadFeatureFn,
        mockGetPlanningPromptPrefixFn,
        mockSaveFeatureSummaryFn,
        mockRecordLearningsFn,
        mockContextExistsFn,
        mockResumeFeatureFn,
        mockTrackFailureFn,
        mockSignalPauseFn,
        mockRecordSuccessFn,
        mockSaveExecutionStateFn,
        mockLoadContextFilesFn
      );

      await svc.executeFeature('/test/project', 'feature-1', true);

      expect(mockResumeFeatureFn).toHaveBeenCalledWith('/test/project', 'feature-1', true, true);
      // Should not run agent
      expect(mockRunAgentFn).not.toHaveBeenCalled();
    });

    it('emits feature_complete event on success when isAutoMode is true', async () => {
      await service.executeFeature('/test/project', 'feature-1', false, true);

      expect(mockEventBus.emitAutoModeEvent).toHaveBeenCalledWith(
        'auto_mode_feature_complete',
        expect.objectContaining({
          featureId: 'feature-1',
          passes: true,
        })
      );
    });

    it('does not emit feature_complete event on success when isAutoMode is false', async () => {
      await service.executeFeature('/test/project', 'feature-1', false, false);

      const completeCalls = vi
        .mocked(mockEventBus.emitAutoModeEvent)
        .mock.calls.filter((call) => call[0] === 'auto_mode_feature_complete');
      expect(completeCalls.length).toBe(0);
    });
  });

  describe('executeFeature - approved plan handling', () => {
    it('builds continuation prompt for approved plan', async () => {
      const featureWithApprovedPlan: Feature = {
        ...testFeature,
        planSpec: { status: 'approved', content: 'The approved plan content' },
      };
      mockLoadFeatureFn = vi.fn().mockResolvedValue(featureWithApprovedPlan);

      const svc = new ExecutionService(
        mockEventBus,
        mockConcurrencyManager,
        mockWorktreeResolver,
        mockSettingsService,
        mockRunAgentFn,
        mockExecutePipelineFn,
        mockUpdateFeatureStatusFn,
        mockLoadFeatureFn,
        mockGetPlanningPromptPrefixFn,
        mockSaveFeatureSummaryFn,
        mockRecordLearningsFn,
        mockContextExistsFn,
        mockResumeFeatureFn,
        mockTrackFailureFn,
        mockSignalPauseFn,
        mockRecordSuccessFn,
        mockSaveExecutionStateFn,
        mockLoadContextFilesFn
      );

      await svc.executeFeature('/test/project', 'feature-1');

      // Agent should be called with continuation prompt
      expect(mockRunAgentFn).toHaveBeenCalled();
      const callArgs = mockRunAgentFn.mock.calls[0];
      expect(callArgs[1]).toBe('feature-1');
      expect(callArgs[2]).toContain('The approved plan content');
    });

    it('recursively calls executeFeature with continuation', async () => {
      const featureWithApprovedPlan: Feature = {
        ...testFeature,
        planSpec: { status: 'approved', content: 'Plan' },
      };
      mockLoadFeatureFn = vi.fn().mockResolvedValue(featureWithApprovedPlan);

      const svc = new ExecutionService(
        mockEventBus,
        mockConcurrencyManager,
        mockWorktreeResolver,
        mockSettingsService,
        mockRunAgentFn,
        mockExecutePipelineFn,
        mockUpdateFeatureStatusFn,
        mockLoadFeatureFn,
        mockGetPlanningPromptPrefixFn,
        mockSaveFeatureSummaryFn,
        mockRecordLearningsFn,
        mockContextExistsFn,
        mockResumeFeatureFn,
        mockTrackFailureFn,
        mockSignalPauseFn,
        mockRecordSuccessFn,
        mockSaveExecutionStateFn,
        mockLoadContextFilesFn
      );

      await svc.executeFeature('/test/project', 'feature-1');

      // acquire should be called twice - once for initial, once for recursive
      expect(mockConcurrencyManager.acquire).toHaveBeenCalledTimes(2);
      // Second call should have allowReuse: true
      expect(mockConcurrencyManager.acquire).toHaveBeenLastCalledWith(
        expect.objectContaining({ allowReuse: true })
      );
    });

    it('skips contextExists check when continuation prompt provided', async () => {
      // Feature has context AND approved plan, but continuation prompt is provided
      const featureWithApprovedPlan: Feature = {
        ...testFeature,
        planSpec: { status: 'approved', content: 'Plan' },
      };
      mockLoadFeatureFn = vi.fn().mockResolvedValue(featureWithApprovedPlan);
      mockContextExistsFn = vi.fn().mockResolvedValue(true);

      const svc = new ExecutionService(
        mockEventBus,
        mockConcurrencyManager,
        mockWorktreeResolver,
        mockSettingsService,
        mockRunAgentFn,
        mockExecutePipelineFn,
        mockUpdateFeatureStatusFn,
        mockLoadFeatureFn,
        mockGetPlanningPromptPrefixFn,
        mockSaveFeatureSummaryFn,
        mockRecordLearningsFn,
        mockContextExistsFn,
        mockResumeFeatureFn,
        mockTrackFailureFn,
        mockSignalPauseFn,
        mockRecordSuccessFn,
        mockSaveExecutionStateFn,
        mockLoadContextFilesFn
      );

      await svc.executeFeature('/test/project', 'feature-1');

      // resumeFeature should NOT be called even though context exists
      // because we're going through approved plan flow
      expect(mockResumeFeatureFn).not.toHaveBeenCalled();
    });
  });

  describe('executeFeature - incomplete task retry', () => {
    const createServiceWithMocks = () => {
      return new ExecutionService(
        mockEventBus,
        mockConcurrencyManager,
        mockWorktreeResolver,
        mockSettingsService,
        mockRunAgentFn,
        mockExecutePipelineFn,
        mockUpdateFeatureStatusFn,
        mockLoadFeatureFn,
        mockGetPlanningPromptPrefixFn,
        mockSaveFeatureSummaryFn,
        mockRecordLearningsFn,
        mockContextExistsFn,
        mockResumeFeatureFn,
        mockTrackFailureFn,
        mockSignalPauseFn,
        mockRecordSuccessFn,
        mockSaveExecutionStateFn,
        mockLoadContextFilesFn
      );
    };

    it('does not re-run agent when feature has no tasks', async () => {
      // Feature with no planSpec/tasks - should complete normally with 1 agent call
      mockLoadFeatureFn = vi.fn().mockResolvedValue(testFeature);
      const svc = createServiceWithMocks();

      await svc.executeFeature('/test/project', 'feature-1');

      expect(mockRunAgentFn).toHaveBeenCalledTimes(1);
    });

    it('does not re-run agent when all tasks are completed', async () => {
      const featureWithCompletedTasks: Feature = {
        ...testFeature,
        planSpec: {
          status: 'approved',
          content: 'Plan',
          tasks: [
            { id: 'T001', title: 'Task 1', status: 'completed', description: 'First task' },
            { id: 'T002', title: 'Task 2', status: 'completed', description: 'Second task' },
          ],
          tasksCompleted: 2,
        },
      };
      mockLoadFeatureFn = vi.fn().mockResolvedValue(featureWithCompletedTasks);
      const svc = createServiceWithMocks();

      await svc.executeFeature('/test/project', 'feature-1');

      // Only the initial agent call + the approved-plan recursive call
      // The approved plan triggers recursive executeFeature, so runAgentFn is called once in the inner call
      expect(mockRunAgentFn).toHaveBeenCalledTimes(1);
    });

    it('re-runs agent when there are pending tasks after initial execution', async () => {
      const featureWithPendingTasks: Feature = {
        ...testFeature,
        planSpec: {
          status: 'approved',
          content: 'Plan',
          tasks: [
            { id: 'T001', title: 'Task 1', status: 'completed', description: 'First task' },
            { id: 'T002', title: 'Task 2', status: 'pending', description: 'Second task' },
            { id: 'T003', title: 'Task 3', status: 'pending', description: 'Third task' },
          ],
          tasksCompleted: 1,
        },
      };

      // After first agent run, loadFeature returns feature with pending tasks
      // After second agent run, loadFeature returns feature with all tasks completed
      const featureAllDone: Feature = {
        ...testFeature,
        planSpec: {
          status: 'approved',
          content: 'Plan',
          tasks: [
            { id: 'T001', title: 'Task 1', status: 'completed', description: 'First task' },
            { id: 'T002', title: 'Task 2', status: 'completed', description: 'Second task' },
            { id: 'T003', title: 'Task 3', status: 'completed', description: 'Third task' },
          ],
          tasksCompleted: 3,
        },
      };

      let loadCallCount = 0;
      mockLoadFeatureFn = vi.fn().mockImplementation(() => {
        loadCallCount++;
        // First call: initial feature load at the top of executeFeature
        // Second call: after first agent run (check for incomplete tasks) - has pending tasks
        // Third call: after second agent run (check for incomplete tasks) - all done
        if (loadCallCount <= 2) return featureWithPendingTasks;
        return featureAllDone;
      });

      const svc = createServiceWithMocks();
      await svc.executeFeature('/test/project', 'feature-1', false, false, undefined, {
        continuationPrompt: 'Continue',
        _calledInternally: true,
      });

      // Should have called runAgentFn twice: initial + one retry
      expect(mockRunAgentFn).toHaveBeenCalledTimes(2);

      // The retry call should contain continuation prompt about incomplete tasks
      const retryCallArgs = mockRunAgentFn.mock.calls[1];
      expect(retryCallArgs[2]).toContain('Continue Implementation - Incomplete Tasks');
      expect(retryCallArgs[2]).toContain('T002');
      expect(retryCallArgs[2]).toContain('T003');

      // Should have emitted a progress event about retrying
      expect(mockEventBus.emitAutoModeEvent).toHaveBeenCalledWith(
        'auto_mode_progress',
        expect.objectContaining({
          featureId: 'feature-1',
          content: expect.stringContaining('Re-running to complete tasks'),
        })
      );
    });

    it('respects maximum retry attempts', async () => {
      const featureAlwaysPending: Feature = {
        ...testFeature,
        planSpec: {
          status: 'approved',
          content: 'Plan',
          tasks: [
            { id: 'T001', title: 'Task 1', status: 'completed', description: 'First task' },
            { id: 'T002', title: 'Task 2', status: 'pending', description: 'Second task' },
          ],
          tasksCompleted: 1,
        },
      };

      // Always return feature with pending tasks (agent never completes T002)
      mockLoadFeatureFn = vi.fn().mockResolvedValue(featureAlwaysPending);

      const svc = createServiceWithMocks();
      await svc.executeFeature('/test/project', 'feature-1', false, false, undefined, {
        continuationPrompt: 'Continue',
        _calledInternally: true,
      });

      // Initial run + 3 retry attempts = 4 total
      expect(mockRunAgentFn).toHaveBeenCalledTimes(4);

      // Should still set final status even with incomplete tasks
      expect(mockUpdateFeatureStatusFn).toHaveBeenCalledWith(
        '/test/project',
        'feature-1',
        'verified'
      );
    });

    it('stops retrying when abort signal is triggered', async () => {
      const featureWithPendingTasks: Feature = {
        ...testFeature,
        planSpec: {
          status: 'approved',
          content: 'Plan',
          tasks: [
            { id: 'T001', title: 'Task 1', status: 'completed', description: 'First task' },
            { id: 'T002', title: 'Task 2', status: 'pending', description: 'Second task' },
          ],
          tasksCompleted: 1,
        },
      };

      mockLoadFeatureFn = vi.fn().mockResolvedValue(featureWithPendingTasks);

      // Simulate abort after first agent run
      let runCount = 0;
      const capturedAbortController = { current: null as AbortController | null };
      mockRunAgentFn = vi.fn().mockImplementation((_wd, _fid, _prompt, abortCtrl) => {
        capturedAbortController.current = abortCtrl;
        runCount++;
        if (runCount >= 1) {
          // Abort after first run
          abortCtrl.abort();
        }
        return Promise.resolve();
      });

      const svc = createServiceWithMocks();
      await svc.executeFeature('/test/project', 'feature-1', false, false, undefined, {
        continuationPrompt: 'Continue',
        _calledInternally: true,
      });

      // Should only have the initial run, then abort prevents retries
      expect(mockRunAgentFn).toHaveBeenCalledTimes(1);
    });

    it('re-runs agent for in_progress tasks (not just pending)', async () => {
      const featureWithInProgressTask: Feature = {
        ...testFeature,
        planSpec: {
          status: 'approved',
          content: 'Plan',
          tasks: [
            { id: 'T001', title: 'Task 1', status: 'completed', description: 'First task' },
            { id: 'T002', title: 'Task 2', status: 'in_progress', description: 'Second task' },
          ],
          tasksCompleted: 1,
          currentTaskId: 'T002',
        },
      };

      const featureAllDone: Feature = {
        ...testFeature,
        planSpec: {
          status: 'approved',
          content: 'Plan',
          tasks: [
            { id: 'T001', title: 'Task 1', status: 'completed', description: 'First task' },
            { id: 'T002', title: 'Task 2', status: 'completed', description: 'Second task' },
          ],
          tasksCompleted: 2,
        },
      };

      let loadCallCount = 0;
      mockLoadFeatureFn = vi.fn().mockImplementation(() => {
        loadCallCount++;
        if (loadCallCount <= 2) return featureWithInProgressTask;
        return featureAllDone;
      });

      const svc = createServiceWithMocks();
      await svc.executeFeature('/test/project', 'feature-1', false, false, undefined, {
        continuationPrompt: 'Continue',
        _calledInternally: true,
      });

      // Should have retried for the in_progress task
      expect(mockRunAgentFn).toHaveBeenCalledTimes(2);

      // The retry prompt should mention the in_progress task
      const retryCallArgs = mockRunAgentFn.mock.calls[1];
      expect(retryCallArgs[2]).toContain('T002');
      expect(retryCallArgs[2]).toContain('in_progress');
    });

    it('uses planningMode skip and no plan approval for retry runs', async () => {
      const featureWithPendingTasks: Feature = {
        ...testFeature,
        planningMode: 'full',
        requirePlanApproval: true,
        planSpec: {
          status: 'approved',
          content: 'Plan',
          tasks: [
            { id: 'T001', title: 'Task 1', status: 'completed', description: 'First task' },
            { id: 'T002', title: 'Task 2', status: 'pending', description: 'Second task' },
          ],
          tasksCompleted: 1,
        },
      };

      const featureAllDone: Feature = {
        ...testFeature,
        planSpec: {
          status: 'approved',
          content: 'Plan',
          tasks: [
            { id: 'T001', title: 'Task 1', status: 'completed', description: 'First task' },
            { id: 'T002', title: 'Task 2', status: 'completed', description: 'Second task' },
          ],
          tasksCompleted: 2,
        },
      };

      let loadCallCount = 0;
      mockLoadFeatureFn = vi.fn().mockImplementation(() => {
        loadCallCount++;
        if (loadCallCount <= 2) return featureWithPendingTasks;
        return featureAllDone;
      });

      const svc = createServiceWithMocks();
      await svc.executeFeature('/test/project', 'feature-1', false, false, undefined, {
        continuationPrompt: 'Continue',
        _calledInternally: true,
      });

      // The retry agent call should use planningMode: 'skip' and requirePlanApproval: false
      const retryCallArgs = mockRunAgentFn.mock.calls[1];
      const retryOptions = retryCallArgs[7]; // options object
      expect(retryOptions.planningMode).toBe('skip');
      expect(retryOptions.requirePlanApproval).toBe(false);
    });
  });

  describe('executeFeature - error handling', () => {
    it('classifies and emits error event', async () => {
      const testError = new Error('Test error');
      mockRunAgentFn = vi.fn().mockRejectedValue(testError);
      const svc = new ExecutionService(
        mockEventBus,
        mockConcurrencyManager,
        mockWorktreeResolver,
        mockSettingsService,
        mockRunAgentFn,
        mockExecutePipelineFn,
        mockUpdateFeatureStatusFn,
        mockLoadFeatureFn,
        mockGetPlanningPromptPrefixFn,
        mockSaveFeatureSummaryFn,
        mockRecordLearningsFn,
        mockContextExistsFn,
        mockResumeFeatureFn,
        mockTrackFailureFn,
        mockSignalPauseFn,
        mockRecordSuccessFn,
        mockSaveExecutionStateFn,
        mockLoadContextFilesFn
      );

      await svc.executeFeature('/test/project', 'feature-1');

      expect(mockEventBus.emitAutoModeEvent).toHaveBeenCalledWith(
        'auto_mode_error',
        expect.objectContaining({
          featureId: 'feature-1',
          error: 'Test error',
        })
      );
    });

    it('updates status to backlog on error', async () => {
      const testError = new Error('Test error');
      mockRunAgentFn = vi.fn().mockRejectedValue(testError);
      const svc = new ExecutionService(
        mockEventBus,
        mockConcurrencyManager,
        mockWorktreeResolver,
        mockSettingsService,
        mockRunAgentFn,
        mockExecutePipelineFn,
        mockUpdateFeatureStatusFn,
        mockLoadFeatureFn,
        mockGetPlanningPromptPrefixFn,
        mockSaveFeatureSummaryFn,
        mockRecordLearningsFn,
        mockContextExistsFn,
        mockResumeFeatureFn,
        mockTrackFailureFn,
        mockSignalPauseFn,
        mockRecordSuccessFn,
        mockSaveExecutionStateFn,
        mockLoadContextFilesFn
      );

      await svc.executeFeature('/test/project', 'feature-1');

      expect(mockUpdateFeatureStatusFn).toHaveBeenCalledWith(
        '/test/project',
        'feature-1',
        'backlog'
      );
    });

    it('tracks failure and checks pause', async () => {
      const testError = new Error('Rate limit error');
      mockRunAgentFn = vi.fn().mockRejectedValue(testError);
      const svc = new ExecutionService(
        mockEventBus,
        mockConcurrencyManager,
        mockWorktreeResolver,
        mockSettingsService,
        mockRunAgentFn,
        mockExecutePipelineFn,
        mockUpdateFeatureStatusFn,
        mockLoadFeatureFn,
        mockGetPlanningPromptPrefixFn,
        mockSaveFeatureSummaryFn,
        mockRecordLearningsFn,
        mockContextExistsFn,
        mockResumeFeatureFn,
        mockTrackFailureFn,
        mockSignalPauseFn,
        mockRecordSuccessFn,
        mockSaveExecutionStateFn,
        mockLoadContextFilesFn
      );

      await svc.executeFeature('/test/project', 'feature-1');

      expect(mockTrackFailureFn).toHaveBeenCalledWith(
        expect.objectContaining({
          message: 'Rate limit error',
        })
      );
    });

    it('signals pause when threshold reached', async () => {
      const testError = new Error('Quota exceeded');
      mockRunAgentFn = vi.fn().mockRejectedValue(testError);
      mockTrackFailureFn = vi.fn().mockReturnValue(true); // threshold reached

      const svc = new ExecutionService(
        mockEventBus,
        mockConcurrencyManager,
        mockWorktreeResolver,
        mockSettingsService,
        mockRunAgentFn,
        mockExecutePipelineFn,
        mockUpdateFeatureStatusFn,
        mockLoadFeatureFn,
        mockGetPlanningPromptPrefixFn,
        mockSaveFeatureSummaryFn,
        mockRecordLearningsFn,
        mockContextExistsFn,
        mockResumeFeatureFn,
        mockTrackFailureFn,
        mockSignalPauseFn,
        mockRecordSuccessFn,
        mockSaveExecutionStateFn,
        mockLoadContextFilesFn
      );

      await svc.executeFeature('/test/project', 'feature-1');

      expect(mockSignalPauseFn).toHaveBeenCalledWith(
        expect.objectContaining({
          message: 'Quota exceeded',
        })
      );
    });

    it('handles abort signal without error event (emits feature_complete when isAutoMode=true)', async () => {
      const abortError = new Error('abort');
      abortError.name = 'AbortError';
      mockRunAgentFn = vi.fn().mockRejectedValue(abortError);

      const svc = new ExecutionService(
        mockEventBus,
        mockConcurrencyManager,
        mockWorktreeResolver,
        mockSettingsService,
        mockRunAgentFn,
        mockExecutePipelineFn,
        mockUpdateFeatureStatusFn,
        mockLoadFeatureFn,
        mockGetPlanningPromptPrefixFn,
        mockSaveFeatureSummaryFn,
        mockRecordLearningsFn,
        mockContextExistsFn,
        mockResumeFeatureFn,
        mockTrackFailureFn,
        mockSignalPauseFn,
        mockRecordSuccessFn,
        mockSaveExecutionStateFn,
        mockLoadContextFilesFn
      );

      await svc.executeFeature('/test/project', 'feature-1', false, true);

      // Should emit feature_complete with stopped by user
      expect(mockEventBus.emitAutoModeEvent).toHaveBeenCalledWith(
        'auto_mode_feature_complete',
        expect.objectContaining({
          featureId: 'feature-1',
          passes: false,
          message: 'Feature stopped by user',
        })
      );

      // Should NOT emit error event
      const errorCalls = vi
        .mocked(mockEventBus.emitAutoModeEvent)
        .mock.calls.filter((call) => call[0] === 'auto_mode_error');
      expect(errorCalls.length).toBe(0);
    });

    it('handles abort signal without emitting feature_complete when isAutoMode=false', async () => {
      const abortError = new Error('abort');
      abortError.name = 'AbortError';
      mockRunAgentFn = vi.fn().mockRejectedValue(abortError);

      const svc = new ExecutionService(
        mockEventBus,
        mockConcurrencyManager,
        mockWorktreeResolver,
        mockSettingsService,
        mockRunAgentFn,
        mockExecutePipelineFn,
        mockUpdateFeatureStatusFn,
        mockLoadFeatureFn,
        mockGetPlanningPromptPrefixFn,
        mockSaveFeatureSummaryFn,
        mockRecordLearningsFn,
        mockContextExistsFn,
        mockResumeFeatureFn,
        mockTrackFailureFn,
        mockSignalPauseFn,
        mockRecordSuccessFn,
        mockSaveExecutionStateFn,
        mockLoadContextFilesFn
      );

      await svc.executeFeature('/test/project', 'feature-1', false, false);

      // Should NOT emit feature_complete when isAutoMode is false
      const completeCalls = vi
        .mocked(mockEventBus.emitAutoModeEvent)
        .mock.calls.filter((call) => call[0] === 'auto_mode_feature_complete');
      expect(completeCalls.length).toBe(0);

      // Should NOT emit error event (abort is not an error)
      const errorCalls = vi
        .mocked(mockEventBus.emitAutoModeEvent)
        .mock.calls.filter((call) => call[0] === 'auto_mode_error');
      expect(errorCalls.length).toBe(0);
    });

    it('releases running feature even on error', async () => {
      const testError = new Error('Test error');
      mockRunAgentFn = vi.fn().mockRejectedValue(testError);
      const svc = new ExecutionService(
        mockEventBus,
        mockConcurrencyManager,
        mockWorktreeResolver,
        mockSettingsService,
        mockRunAgentFn,
        mockExecutePipelineFn,
        mockUpdateFeatureStatusFn,
        mockLoadFeatureFn,
        mockGetPlanningPromptPrefixFn,
        mockSaveFeatureSummaryFn,
        mockRecordLearningsFn,
        mockContextExistsFn,
        mockResumeFeatureFn,
        mockTrackFailureFn,
        mockSignalPauseFn,
        mockRecordSuccessFn,
        mockSaveExecutionStateFn,
        mockLoadContextFilesFn
      );

      await svc.executeFeature('/test/project', 'feature-1');

      expect(mockConcurrencyManager.release).toHaveBeenCalledWith('feature-1', undefined);
    });
  });

  describe('stopFeature', () => {
    it('returns false if feature not running', async () => {
      vi.mocked(mockConcurrencyManager.getRunningFeature).mockReturnValue(undefined);

      const result = await service.stopFeature('feature-1');

      expect(result).toBe(false);
    });

    it('aborts running feature', async () => {
      const runningFeature = createRunningFeature('feature-1');
      const abortSpy = vi.spyOn(runningFeature.abortController, 'abort');
      vi.mocked(mockConcurrencyManager.getRunningFeature).mockReturnValue(runningFeature);

      const result = await service.stopFeature('feature-1');

      expect(result).toBe(true);
      expect(abortSpy).toHaveBeenCalled();
    });

    it('releases running feature with force', async () => {
      const runningFeature = createRunningFeature('feature-1');
      vi.mocked(mockConcurrencyManager.getRunningFeature).mockReturnValue(runningFeature);

      await service.stopFeature('feature-1');

      expect(mockConcurrencyManager.release).toHaveBeenCalledWith('feature-1', { force: true });
    });

    it('immediately updates feature status to interrupted before subprocess terminates', async () => {
      const runningFeature = createRunningFeature('feature-1');
      vi.mocked(mockConcurrencyManager.getRunningFeature).mockReturnValue(runningFeature);

      await service.stopFeature('feature-1');

      // Should update to 'interrupted' immediately so the UI reflects the stop
      // without waiting for the CLI subprocess to fully terminate
      expect(mockUpdateFeatureStatusFn).toHaveBeenCalledWith(
        '/test/project',
        'feature-1',
        'interrupted'
      );
    });

    it('still aborts and releases even if status update fails', async () => {
      const runningFeature = createRunningFeature('feature-1');
      const abortSpy = vi.spyOn(runningFeature.abortController, 'abort');
      vi.mocked(mockConcurrencyManager.getRunningFeature).mockReturnValue(runningFeature);
      vi.mocked(mockUpdateFeatureStatusFn).mockRejectedValueOnce(new Error('disk error'));

      const result = await service.stopFeature('feature-1');

      expect(result).toBe(true);
      expect(abortSpy).toHaveBeenCalled();
      expect(mockConcurrencyManager.release).toHaveBeenCalledWith('feature-1', { force: true });
    });
  });

  describe('worktree resolution', () => {
    it('uses worktree when useWorktrees is true and branch exists', async () => {
      await service.executeFeature('/test/project', 'feature-1', true);

      expect(mockWorktreeResolver.findWorktreeForBranch).toHaveBeenCalledWith(
        '/test/project',
        'feature/test-1'
      );
    });

    it('emits error and does not execute agent when worktree is not found in worktree mode', async () => {
      vi.mocked(mockWorktreeResolver.findWorktreeForBranch).mockResolvedValue(null);

      await service.executeFeature('/test/project', 'feature-1', true);

      expect(mockRunAgentFn).not.toHaveBeenCalled();
      expect(mockEventBus.emitAutoModeEvent).toHaveBeenCalledWith(
        'auto_mode_error',
        expect.objectContaining({
          featureId: 'feature-1',
          error: 'Worktree enabled but no worktree found for feature branch "feature/test-1".',
        })
      );
    });

    it('skips worktree resolution when useWorktrees is false', async () => {
      await service.executeFeature('/test/project', 'feature-1', false);

      expect(mockWorktreeResolver.findWorktreeForBranch).not.toHaveBeenCalled();
    });
  });

  describe('auto-mode integration', () => {
    it('saves execution state when isAutoMode is true', async () => {
      await service.executeFeature('/test/project', 'feature-1', false, true);

      expect(mockSaveExecutionStateFn).toHaveBeenCalledWith('/test/project');
    });

    it('saves execution state after completion in auto-mode', async () => {
      await service.executeFeature('/test/project', 'feature-1', false, true);

      // Should be called twice: once at start, once at end
      expect(mockSaveExecutionStateFn).toHaveBeenCalledTimes(2);
    });

    it('does not save execution state when isAutoMode is false', async () => {
      await service.executeFeature('/test/project', 'feature-1', false, false);

      expect(mockSaveExecutionStateFn).not.toHaveBeenCalled();
    });
  });

  describe('planning mode', () => {
    it('calls getPlanningPromptPrefix for features', async () => {
      await service.executeFeature('/test/project', 'feature-1');

      expect(mockGetPlanningPromptPrefixFn).toHaveBeenCalledWith(testFeature);
    });

    it('emits planning_started event when planning mode is not skip', async () => {
      const featureWithPlanning: Feature = {
        ...testFeature,
        planningMode: 'lite',
      };
      mockLoadFeatureFn = vi.fn().mockResolvedValue(featureWithPlanning);
      const svc = new ExecutionService(
        mockEventBus,
        mockConcurrencyManager,
        mockWorktreeResolver,
        mockSettingsService,
        mockRunAgentFn,
        mockExecutePipelineFn,
        mockUpdateFeatureStatusFn,
        mockLoadFeatureFn,
        mockGetPlanningPromptPrefixFn,
        mockSaveFeatureSummaryFn,
        mockRecordLearningsFn,
        mockContextExistsFn,
        mockResumeFeatureFn,
        mockTrackFailureFn,
        mockSignalPauseFn,
        mockRecordSuccessFn,
        mockSaveExecutionStateFn,
        mockLoadContextFilesFn
      );

      await svc.executeFeature('/test/project', 'feature-1');

      expect(mockEventBus.emitAutoModeEvent).toHaveBeenCalledWith(
        'planning_started',
        expect.objectContaining({
          featureId: 'feature-1',
          mode: 'lite',
        })
      );
    });
  });

  describe('summary extraction', () => {
    it('extracts and saves summary from agent output', async () => {
      vi.mocked(secureFs.readFile).mockResolvedValue('Agent output with summary');

      await service.executeFeature('/test/project', 'feature-1');

      expect(mockSaveFeatureSummaryFn).toHaveBeenCalledWith(
        '/test/project',
        'feature-1',
        'Test summary'
      );
    });

    it('records learnings from agent output', async () => {
      vi.mocked(secureFs.readFile).mockResolvedValue('Agent output');

      await service.executeFeature('/test/project', 'feature-1');

      expect(mockRecordLearningsFn).toHaveBeenCalledWith(
        '/test/project',
        testFeature,
        'Agent output'
      );
    });

    it('handles missing agent output gracefully', async () => {
      vi.mocked(secureFs.readFile).mockRejectedValue(new Error('ENOENT'));

      // Should not throw (isAutoMode=true so event is emitted)
      await service.executeFeature('/test/project', 'feature-1', false, true);

      // Feature should still complete successfully
      expect(mockEventBus.emitAutoModeEvent).toHaveBeenCalledWith(
        'auto_mode_feature_complete',
        expect.objectContaining({ passes: true })
      );
    });

    // Helper to create ExecutionService with a custom loadFeatureFn that returns
    // different features on first load (initial) vs subsequent loads (after completion)
    const createServiceWithCustomLoad = (completedFeature: Feature): ExecutionService => {
      let loadCallCount = 0;
      mockLoadFeatureFn = vi.fn().mockImplementation(() => {
        loadCallCount++;
        return loadCallCount === 1 ? testFeature : completedFeature;
      });

      return new ExecutionService(
        mockEventBus,
        mockConcurrencyManager,
        mockWorktreeResolver,
        mockSettingsService,
        mockRunAgentFn,
        mockExecutePipelineFn,
        mockUpdateFeatureStatusFn,
        mockLoadFeatureFn,
        mockGetPlanningPromptPrefixFn,
        mockSaveFeatureSummaryFn,
        mockRecordLearningsFn,
        mockContextExistsFn,
        mockResumeFeatureFn,
        mockTrackFailureFn,
        mockSignalPauseFn,
        mockRecordSuccessFn,
        mockSaveExecutionStateFn,
        mockLoadContextFilesFn
      );
    };

    it('does not overwrite accumulated summary when feature already has one', async () => {
      const featureWithAccumulatedSummary: Feature = {
        ...testFeature,
        summary:
          '### Implementation\n\nFirst step output\n\n---\n\n### Code Review\n\nReview findings',
      };

      const svc = createServiceWithCustomLoad(featureWithAccumulatedSummary);
      await svc.executeFeature('/test/project', 'feature-1');

      // saveFeatureSummaryFn should NOT be called because feature already has a summary
      // This prevents overwriting accumulated pipeline summaries with just the last step's output
      expect(mockSaveFeatureSummaryFn).not.toHaveBeenCalled();
    });

    it('saves summary when feature has no existing summary', async () => {
      const featureWithoutSummary: Feature = {
        ...testFeature,
        summary: undefined,
      };

      vi.mocked(secureFs.readFile).mockResolvedValue(
        '🔧 Tool: Edit\nInput: {"file_path": "/src/index.ts"}\n\n<summary>New summary</summary>'
      );

      const svc = createServiceWithCustomLoad(featureWithoutSummary);
      await svc.executeFeature('/test/project', 'feature-1');

      // Should save the extracted summary since feature has none
      expect(mockSaveFeatureSummaryFn).toHaveBeenCalledWith(
        '/test/project',
        'feature-1',
        'Test summary'
      );
    });

    it('does not overwrite summary when feature has empty string summary (treats as no summary)', async () => {
      // Empty string is falsy, so it should be treated as "no summary" and a new one should be saved
      const featureWithEmptySummary: Feature = {
        ...testFeature,
        summary: '',
      };

      vi.mocked(secureFs.readFile).mockResolvedValue(
        '🔧 Tool: Edit\nInput: {"file_path": "/src/index.ts"}\n\n<summary>New summary</summary>'
      );

      const svc = createServiceWithCustomLoad(featureWithEmptySummary);
      await svc.executeFeature('/test/project', 'feature-1');

      // Empty string is falsy, so it should save a new summary
      expect(mockSaveFeatureSummaryFn).toHaveBeenCalledWith(
        '/test/project',
        'feature-1',
        'Test summary'
      );
    });

    it('preserves accumulated summary when feature is transitioned from pipeline to verified', async () => {
      // This is the key scenario: feature went through pipeline steps, accumulated a summary,
      // then status changed to 'verified' - we should NOT overwrite the accumulated summary
      const featureWithAccumulatedSummary: Feature = {
        ...testFeature,
        status: 'verified',
        summary:
          '### Implementation\n\nCreated auth module\n\n---\n\n### Code Review\n\nApproved\n\n---\n\n### Testing\n\nAll tests pass',
      };

      vi.mocked(secureFs.readFile).mockResolvedValue('Agent output with summary');

      const svc = createServiceWithCustomLoad(featureWithAccumulatedSummary);
      await svc.executeFeature('/test/project', 'feature-1');

      // The accumulated summary should be preserved
      expect(mockSaveFeatureSummaryFn).not.toHaveBeenCalled();
    });
  });

  describe('executeFeature - agent output validation', () => {
    // Helper to generate realistic agent output with tool markers
    const makeAgentOutput = (toolCount: number, extraText = ''): string => {
      let output = 'Starting implementation...\n\n';
      for (let i = 0; i < toolCount; i++) {
        output += `🔧 Tool: Edit\nInput: {"file_path": "/src/file${i}.ts", "old_string": "old${i}", "new_string": "new${i}"}\n\n`;
      }
      output += `Implementation complete. ${extraText}`;
      return output;
    };

    const createServiceWithMocks = () => {
      return new ExecutionService(
        mockEventBus,
        mockConcurrencyManager,
        mockWorktreeResolver,
        mockSettingsService,
        mockRunAgentFn,
        mockExecutePipelineFn,
        mockUpdateFeatureStatusFn,
        mockLoadFeatureFn,
        mockGetPlanningPromptPrefixFn,
        mockSaveFeatureSummaryFn,
        mockRecordLearningsFn,
        mockContextExistsFn,
        mockResumeFeatureFn,
        mockTrackFailureFn,
        mockSignalPauseFn,
        mockRecordSuccessFn,
        mockSaveExecutionStateFn,
        mockLoadContextFilesFn
      );
    };

    it('sets verified when agent output has tool usage and sufficient length', async () => {
      const output = makeAgentOutput(3, 'Updated authentication module with new login flow.');
      vi.mocked(secureFs.readFile).mockResolvedValue(output);

      await service.executeFeature('/test/project', 'feature-1');

      expect(mockUpdateFeatureStatusFn).toHaveBeenCalledWith(
        '/test/project',
        'feature-1',
        'verified'
      );
    });

    it('sets waiting_approval when agent output is empty', async () => {
      vi.mocked(secureFs.readFile).mockResolvedValue('');

      const svc = createServiceWithMocks();
      await svc.executeFeature('/test/project', 'feature-1');

      expect(mockUpdateFeatureStatusFn).toHaveBeenCalledWith(
        '/test/project',
        'feature-1',
        'waiting_approval'
      );
    });

    it('sets waiting_approval when agent output has no tool usage markers', async () => {
      // Long output but no tool markers - agent printed text but didn't use tools
      const longOutputNoTools = 'I analyzed the codebase and found several issues. '.repeat(20);
      vi.mocked(secureFs.readFile).mockResolvedValue(longOutputNoTools);

      const svc = createServiceWithMocks();
      await svc.executeFeature('/test/project', 'feature-1');

      expect(mockUpdateFeatureStatusFn).toHaveBeenCalledWith(
        '/test/project',
        'feature-1',
        'waiting_approval'
      );
    });

    it('sets waiting_approval when agent output has tool markers but is too short', async () => {
      // Has a tool marker but total output is under 200 chars
      const shortWithTool = '🔧 Tool: Read\nInput: {"file_path": "/src/index.ts"}\nDone.';
      expect(shortWithTool.trim().length).toBeLessThan(200);

      vi.mocked(secureFs.readFile).mockResolvedValue(shortWithTool);

      const svc = createServiceWithMocks();
      await svc.executeFeature('/test/project', 'feature-1');

      expect(mockUpdateFeatureStatusFn).toHaveBeenCalledWith(
        '/test/project',
        'feature-1',
        'waiting_approval'
      );
    });

    it('sets waiting_approval when agent output file is missing (ENOENT)', async () => {
      vi.mocked(secureFs.readFile).mockRejectedValue(new Error('ENOENT'));

      const svc = createServiceWithMocks();
      await svc.executeFeature('/test/project', 'feature-1');

      expect(mockUpdateFeatureStatusFn).toHaveBeenCalledWith(
        '/test/project',
        'feature-1',
        'waiting_approval'
      );
    });

    it('sets waiting_approval when agent output is only whitespace', async () => {
      vi.mocked(secureFs.readFile).mockResolvedValue('   \n\n\t  \n  ');

      const svc = createServiceWithMocks();
      await svc.executeFeature('/test/project', 'feature-1');

      expect(mockUpdateFeatureStatusFn).toHaveBeenCalledWith(
        '/test/project',
        'feature-1',
        'waiting_approval'
      );
    });

    it('sets verified when output is exactly at the 200 char threshold with tool usage', async () => {
      // Create output that's exactly 200 chars trimmed with tool markers
      const toolMarker = '🔧 Tool: Edit\nInput: {"file_path": "/src/index.ts"}\n';
      const padding = 'x'.repeat(200 - toolMarker.length);
      const output = toolMarker + padding;
      expect(output.trim().length).toBeGreaterThanOrEqual(200);

      vi.mocked(secureFs.readFile).mockResolvedValue(output);

      const svc = createServiceWithMocks();
      await svc.executeFeature('/test/project', 'feature-1');

      expect(mockUpdateFeatureStatusFn).toHaveBeenCalledWith(
        '/test/project',
        'feature-1',
        'verified'
      );
    });

    it('sets waiting_approval when output is 199 chars with tool usage (below threshold)', async () => {
      const toolMarker = '🔧 Tool: Read\n';
      const padding = 'x'.repeat(199 - toolMarker.length);
      const output = toolMarker + padding;
      expect(output.trim().length).toBe(199);

      vi.mocked(secureFs.readFile).mockResolvedValue(output);

      const svc = createServiceWithMocks();
      await svc.executeFeature('/test/project', 'feature-1');

      expect(mockUpdateFeatureStatusFn).toHaveBeenCalledWith(
        '/test/project',
        'feature-1',
        'waiting_approval'
      );
    });

    it('skipTests always takes priority over output validation', async () => {
      // Meaningful output with tool usage - would normally be 'verified'
      const output = makeAgentOutput(5, 'All changes applied successfully.');
      vi.mocked(secureFs.readFile).mockResolvedValue(output);

      mockLoadFeatureFn = vi.fn().mockResolvedValue({ ...testFeature, skipTests: true });
      const svc = createServiceWithMocks();

      await svc.executeFeature('/test/project', 'feature-1');

      // skipTests=true always means waiting_approval regardless of output quality
      expect(mockUpdateFeatureStatusFn).toHaveBeenCalledWith(
        '/test/project',
        'feature-1',
        'waiting_approval'
      );
    });

    it('skipTests with empty output still results in waiting_approval', async () => {
      vi.mocked(secureFs.readFile).mockResolvedValue('');

      mockLoadFeatureFn = vi.fn().mockResolvedValue({ ...testFeature, skipTests: true });
      const svc = createServiceWithMocks();

      await svc.executeFeature('/test/project', 'feature-1');

      expect(mockUpdateFeatureStatusFn).toHaveBeenCalledWith(
        '/test/project',
        'feature-1',
        'waiting_approval'
      );
    });

    it('still records success even when output validation fails', async () => {
      vi.mocked(secureFs.readFile).mockResolvedValue('');

      const svc = createServiceWithMocks();
      await svc.executeFeature('/test/project', 'feature-1');

      // recordSuccess should still be called - the agent ran without errors
      expect(mockRecordSuccessFn).toHaveBeenCalled();
    });

    it('still extracts summary when output has content but no tool markers', async () => {
      const outputNoTools = 'A '.repeat(150); // > 200 chars but no tool markers
      vi.mocked(secureFs.readFile).mockResolvedValue(outputNoTools);

      const svc = createServiceWithMocks();
      await svc.executeFeature('/test/project', 'feature-1');

      // Summary extraction still runs even though status is waiting_approval
      expect(extractSummary).toHaveBeenCalledWith(outputNoTools);
      expect(mockSaveFeatureSummaryFn).toHaveBeenCalledWith(
        '/test/project',
        'feature-1',
        'Test summary'
      );
    });

    it('emits feature_complete with passes=true even when output validation routes to waiting_approval', async () => {
      vi.mocked(secureFs.readFile).mockResolvedValue('');

      const svc = createServiceWithMocks();
      await svc.executeFeature('/test/project', 'feature-1', false, true);

      // The agent ran without error - it's still a "pass" from the execution perspective
      expect(mockEventBus.emitAutoModeEvent).toHaveBeenCalledWith(
        'auto_mode_feature_complete',
        expect.objectContaining({ passes: true })
      );
    });

    it('handles realistic Cursor CLI output that exits quickly', async () => {
      // Simulates a Cursor CLI that prints a brief message and exits
      const cursorQuickExit = 'Task received. Processing...\nResult: completed successfully.';
      expect(cursorQuickExit.includes('🔧 Tool:')).toBe(false);

      vi.mocked(secureFs.readFile).mockResolvedValue(cursorQuickExit);

      const svc = createServiceWithMocks();
      await svc.executeFeature('/test/project', 'feature-1');

      // No tool usage = waiting_approval
      expect(mockUpdateFeatureStatusFn).toHaveBeenCalledWith(
        '/test/project',
        'feature-1',
        'waiting_approval'
      );
    });

    it('handles realistic Claude SDK output with multiple tool uses', async () => {
      // Simulates a Claude SDK agent that does real work
      const claudeOutput =
        "I'll implement the requested feature.\n\n" +
        '🔧 Tool: Read\nInput: {"file_path": "/src/components/App.tsx"}\n\n' +
        'I can see the existing component structure. Let me modify it.\n\n' +
        '🔧 Tool: Edit\nInput: {"file_path": "/src/components/App.tsx", "old_string": "const App = () => {", "new_string": "const App: React.FC = () => {"}\n\n' +
        '🔧 Tool: Write\nInput: {"file_path": "/src/components/NewFeature.tsx"}\n\n' +
        "I've created the new component and updated the existing one. The feature is now implemented with proper TypeScript types.";

      vi.mocked(secureFs.readFile).mockResolvedValue(claudeOutput);

      const svc = createServiceWithMocks();
      await svc.executeFeature('/test/project', 'feature-1');

      // Real work = verified
      expect(mockUpdateFeatureStatusFn).toHaveBeenCalledWith(
        '/test/project',
        'feature-1',
        'verified'
      );
    });

    it('reads agent output from the correct path with utf-8 encoding', async () => {
      const output = makeAgentOutput(2, 'Done with changes.');
      vi.mocked(secureFs.readFile).mockResolvedValue(output);

      const svc = createServiceWithMocks();
      await svc.executeFeature('/test/project', 'feature-1');

      // Verify readFile was called with the correct path derived from getFeatureDir
      expect(secureFs.readFile).toHaveBeenCalledWith(
        '/test/project/.automaker/features/feature-1/agent-output.md',
        'utf-8'
      );
    });

    it('completion message includes auto-verified when status is verified', async () => {
      const output = makeAgentOutput(3, 'All changes applied.');
      vi.mocked(secureFs.readFile).mockResolvedValue(output);

      const svc = createServiceWithMocks();
      await svc.executeFeature('/test/project', 'feature-1', false, true);

      expect(mockEventBus.emitAutoModeEvent).toHaveBeenCalledWith(
        'auto_mode_feature_complete',
        expect.objectContaining({
          message: expect.stringContaining('auto-verified'),
        })
      );
    });

    it('completion message does NOT include auto-verified when status is waiting_approval', async () => {
      // Empty output → waiting_approval
      vi.mocked(secureFs.readFile).mockResolvedValue('');

      const svc = createServiceWithMocks();
      await svc.executeFeature('/test/project', 'feature-1', false, true);

      const completeCall = vi
        .mocked(mockEventBus.emitAutoModeEvent)
        .mock.calls.find((call) => call[0] === 'auto_mode_feature_complete');
      expect(completeCall).toBeDefined();
      expect((completeCall![1] as { message: string }).message).not.toContain('auto-verified');
    });

    it('uses same agentOutput for both status determination and summary extraction', async () => {
      // Specific output that is long enough with tool markers (verified path)
      // AND has content for summary extraction
      const specificOutput =
        '🔧 Tool: Read\nReading file...\n🔧 Tool: Edit\nEditing file...\n' +
        'The implementation is complete. Here is a detailed description of what was done. '.repeat(
          3
        );
      vi.mocked(secureFs.readFile).mockResolvedValue(specificOutput);

      const svc = createServiceWithMocks();
      await svc.executeFeature('/test/project', 'feature-1');

      // Status should be verified (has tools + long enough)
      expect(mockUpdateFeatureStatusFn).toHaveBeenCalledWith(
        '/test/project',
        'feature-1',
        'verified'
      );
      // extractSummary should receive the exact same output
      expect(extractSummary).toHaveBeenCalledWith(specificOutput);
      // recordLearnings should also receive the same output
      expect(mockRecordLearningsFn).toHaveBeenCalledWith(
        '/test/project',
        testFeature,
        specificOutput
      );
    });

    it('does not call recordMemoryUsage when output is empty and memoryFiles is empty', async () => {
      vi.mocked(secureFs.readFile).mockResolvedValue('');
      const { recordMemoryUsage } = await import('@automaker/utils');

      const svc = createServiceWithMocks();
      await svc.executeFeature('/test/project', 'feature-1');

      // With empty output and empty memoryFiles, recordMemoryUsage should not be called
      expect(recordMemoryUsage).not.toHaveBeenCalled();
    });

    it('handles output with special unicode characters correctly', async () => {
      // Output with various unicode but includes tool markers
      const unicodeOutput =
        '🔧 Tool: Read\n' +
        '🔧 Tool: Edit\n' +
        'Añadiendo función de búsqueda con caracteres especiales: ñ, ü, ö, é, 日本語テスト. ' +
        'Die Änderungen wurden erfolgreich implementiert. '.repeat(3);
      vi.mocked(secureFs.readFile).mockResolvedValue(unicodeOutput);

      const svc = createServiceWithMocks();
      await svc.executeFeature('/test/project', 'feature-1');

      // Should still detect tool markers and sufficient length
      expect(mockUpdateFeatureStatusFn).toHaveBeenCalledWith(
        '/test/project',
        'feature-1',
        'verified'
      );
    });

    it('treats output with only newlines and spaces around tool marker as insufficient', async () => {
      // Has tool marker but surrounded by whitespace, total trimmed < 200
      const sparseOutput = '\n\n  🔧 Tool: Read  \n\n';
      expect(sparseOutput.trim().length).toBeLessThan(200);

      vi.mocked(secureFs.readFile).mockResolvedValue(sparseOutput);

      const svc = createServiceWithMocks();
      await svc.executeFeature('/test/project', 'feature-1');

      expect(mockUpdateFeatureStatusFn).toHaveBeenCalledWith(
        '/test/project',
        'feature-1',
        'waiting_approval'
      );
    });

    it('detects tool marker substring correctly (partial match like "🔧 Tools:" does not count)', async () => {
      // Output with a similar but not exact marker - "🔧 Tools:" instead of "🔧 Tool:"
      const wrongMarker = '🔧 Tools: Read\n🔧 Tools: Edit\n' + 'Implementation done. '.repeat(20);
      expect(wrongMarker.includes('🔧 Tool:')).toBe(false);

      vi.mocked(secureFs.readFile).mockResolvedValue(wrongMarker);

      const svc = createServiceWithMocks();
      await svc.executeFeature('/test/project', 'feature-1');

      // "🔧 Tools:" is not the same as "🔧 Tool:" - should be waiting_approval
      expect(mockUpdateFeatureStatusFn).toHaveBeenCalledWith(
        '/test/project',
        'feature-1',
        'waiting_approval'
      );
    });

    it('pipeline merge_conflict status short-circuits before output validation', async () => {
      // Set up pipeline that results in merge_conflict
      vi.mocked(pipelineService.getPipelineConfig).mockResolvedValue({
        version: 1,
        steps: [{ id: 'step-1', name: 'Step 1', order: 1, instructions: 'Do step 1' }] as any,
      });

      // After pipeline, loadFeature returns merge_conflict status
      let loadCallCount = 0;
      mockLoadFeatureFn = vi.fn().mockImplementation(() => {
        loadCallCount++;
        if (loadCallCount === 1) return testFeature; // initial load
        // All subsequent loads (task check + pipeline refresh) return merge_conflict
        return { ...testFeature, status: 'merge_conflict' };
      });

      const svc = createServiceWithMocks();
      await svc.executeFeature('/test/project', 'feature-1');

      // Should NOT have called updateFeatureStatusFn with 'verified' or 'waiting_approval'
      // because pipeline merge_conflict short-circuits the method
      const statusCalls = vi
        .mocked(mockUpdateFeatureStatusFn)
        .mock.calls.filter((call) => call[2] === 'verified' || call[2] === 'waiting_approval');
      // The only non-in_progress status call should be absent since merge_conflict returns early
      expect(statusCalls.length).toBe(0);
    });

    it('sets waiting_approval instead of backlog when error occurs after pipeline completes', async () => {
      // Set up pipeline with steps
      vi.mocked(pipelineService.getPipelineConfig).mockResolvedValue({
        version: 1,
        steps: [{ id: 'step-1', name: 'Step 1', order: 1, instructions: 'Do step 1' }] as any,
      });

      // Pipeline succeeds, but reading agent output throws after pipeline completes
      mockExecutePipelineFn = vi.fn().mockResolvedValue(undefined);
      // Simulate an error after pipeline completes by making loadFeature throw
      // on the post-pipeline refresh call
      let loadCallCount = 0;
      mockLoadFeatureFn = vi.fn().mockImplementation(() => {
        loadCallCount++;
        if (loadCallCount === 1) return testFeature; // initial load
        // Second call is the task-retry check, third is the pipeline refresh
        if (loadCallCount <= 2) return testFeature;
        throw new Error('Unexpected post-pipeline error');
      });

      const svc = createServiceWithMocks();
      await svc.executeFeature('/test/project', 'feature-1');

      // Should set to waiting_approval, NOT backlog, since pipeline completed
      const backlogCalls = vi
        .mocked(mockUpdateFeatureStatusFn)
        .mock.calls.filter((call) => call[2] === 'backlog');
      expect(backlogCalls.length).toBe(0);

      const waitingCalls = vi
        .mocked(mockUpdateFeatureStatusFn)
        .mock.calls.filter((call) => call[2] === 'waiting_approval');
      expect(waitingCalls.length).toBeGreaterThan(0);
    });

    it('still sets backlog when error occurs before pipeline completes', async () => {
      // Set up pipeline with steps
      vi.mocked(pipelineService.getPipelineConfig).mockResolvedValue({
        version: 1,
        steps: [{ id: 'step-1', name: 'Step 1', order: 1, instructions: 'Do step 1' }] as any,
      });

      // Pipeline itself throws (e.g., agent error during pipeline step)
      mockExecutePipelineFn = vi.fn().mockRejectedValue(new Error('Agent execution failed'));

      const svc = createServiceWithMocks();
      await svc.executeFeature('/test/project', 'feature-1');

      // Should still set to backlog since pipeline did NOT complete
      const backlogCalls = vi
        .mocked(mockUpdateFeatureStatusFn)
        .mock.calls.filter((call) => call[2] === 'backlog');
      expect(backlogCalls.length).toBe(1);
    });
  });
});