File size: 58,392 Bytes
a6b96c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"use strict";
/**
 * Commands β€” Standalone utility commands
 *
 * ADR-457 build-at-publish: the hand-written bin/lib/commands.cjs collapsed
 * to a TypeScript source of truth. Behaviour is preserved byte-for-behaviour
 * from the prior hand-written .cjs; only strict types are added.
 */
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
const node_fs_1 = __importDefault(require("node:fs"));
const node_path_1 = __importDefault(require("node:path"));
const shell_command_projection_cjs_1 = require("./shell-command-projection.cjs");
// eslint-disable-next-line @typescript-eslint/no-require-imports
const ioMod = require("./io.cjs");
const { output, error } = ioMod;
// eslint-disable-next-line @typescript-eslint/no-require-imports
const configLoaderMod = require("./config-loader.cjs");
const { loadConfig, isGitIgnored } = configLoaderMod;
// eslint-disable-next-line @typescript-eslint/no-require-imports
const coreUtilsMod = require("./core-utils.cjs");
const { toPosixPath, generateSlugInternal, extractOneLinerFromBody } = coreUtilsMod;
// eslint-disable-next-line @typescript-eslint/no-require-imports
const phaseIdMod = require("./phase-id.cjs");
const { normalizePhaseName, comparePhaseNum, extractPhaseToken } = phaseIdMod;
// eslint-disable-next-line @typescript-eslint/no-require-imports
const phaseLocatorMod = require("./phase-locator.cjs");
const { getArchivedPhaseDirs, findPhaseInternal } = phaseLocatorMod;
// eslint-disable-next-line @typescript-eslint/no-require-imports
const roadmapParserMod = require("./roadmap-parser.cjs");
const { extractCurrentMilestone, stripShippedMilestones: _stripShippedMilestones, getMilestoneInfo, getMilestonePhaseFilter, getRoadmapPhaseInternal } = roadmapParserMod;
// eslint-disable-next-line @typescript-eslint/no-require-imports
const modelResolverMod = require("./model-resolver.cjs");
const { resolveModelInternal, resolveEffortInternal, resolveFastModeInternal, resolveEffortForTier, resolveGranularityInternal, assertValidGranularityOverride } = modelResolverMod;
const model_catalog_cjs_1 = require("./model-catalog.cjs");
// eslint-disable-next-line @typescript-eslint/no-require-imports
const planningWorkspace = require("./planning-workspace.cjs");
const { planningDir, planningPaths } = planningWorkspace;
// eslint-disable-next-line @typescript-eslint/no-require-imports
const frontmatter = require("./frontmatter.cjs");
const { extractFrontmatter } = frontmatter;
// eslint-disable-next-line @typescript-eslint/no-require-imports
const modelProfiles = require("./model-profiles.cjs");
const { MODEL_PROFILES, VALID_PHASE_TYPES } = modelProfiles;
const runtime_slash_cjs_1 = require("./runtime-slash.cjs");
// ─── Phase Status ─────────────────────────────────────────────────────────────
/**
 * Determine phase status by checking plan/summary counts AND verification state.
 * Introduces "Executed" for phases with all summaries but no passing verification.
 */
function determinePhaseStatus(plans, summaries, phaseDir, defaultPending) {
    if (plans === 0)
        return defaultPending;
    if (summaries < plans && summaries > 0)
        return 'In Progress';
    if (summaries < plans)
        return 'Planned';
    // summaries >= plans β€” check verification
    try {
        const files = node_fs_1.default.readdirSync(phaseDir);
        const verificationFile = files.find(f => f === 'VERIFICATION.md' || f.endsWith('-VERIFICATION.md'));
        if (verificationFile) {
            const content = (0, shell_command_projection_cjs_1.platformReadSync)(node_path_1.default.join(phaseDir, verificationFile)) || '';
            // #1159 (Defect A): read ONLY the frontmatter `status` key to avoid false
            // matches from historical body metadata such as `previous_status: gaps_found`.
            // Full-text regexes like /status:\s*gaps_found/ match the substring inside
            // `previous_status: gaps_found`, producing incorrect phase status labels.
            const fm = extractFrontmatter(content);
            // Normalise to lower-case to preserve the prior case-insensitive behaviour
            // while reading only the frontmatter `status` key (not the full body text).
            const fmStatus = typeof fm['status'] === 'string' ? fm['status'].trim().toLowerCase() : '';
            if (fmStatus === 'passed')
                return 'Complete';
            if (fmStatus === 'human_needed')
                return 'Needs Review';
            if (fmStatus === 'gaps_found')
                return 'Executed';
            // Verification exists but unrecognized status β€” treat as executed
            return 'Executed';
        }
    }
    catch { /* directory read failed β€” fall through */ }
    // No verification file β€” executed but not verified
    return 'Executed';
}
function cmdGenerateSlug(text, raw) {
    if (!text) {
        error('text required for slug generation');
    }
    const slug = text
        .toLowerCase()
        .replace(/[^a-z0-9]+/g, '-')
        .replace(/^-+|-+$/g, '')
        .substring(0, 60);
    const result = { slug };
    output(result, raw, slug);
}
function cmdCurrentTimestamp(format, raw) {
    const now = new Date();
    let result;
    switch (format) {
        case 'date':
            result = now.toISOString().split('T')[0];
            break;
        case 'filename':
            result = now.toISOString().replace(/:/g, '-').replace(/\..+/, '');
            break;
        case 'full':
        default:
            result = now.toISOString();
            break;
    }
    output({ timestamp: result }, raw, result);
}
function cmdListTodos(cwd, area, raw) {
    const pendingDir = node_path_1.default.join(planningDir(cwd), 'todos', 'pending');
    let count = 0;
    const todos = [];
    try {
        const files = node_fs_1.default.readdirSync(pendingDir).filter(f => f.endsWith('.md'));
        for (const file of files) {
            const content = (0, shell_command_projection_cjs_1.platformReadSync)(node_path_1.default.join(pendingDir, file));
            if (content === null)
                continue;
            const createdMatch = content.match(/^created:\s*(.+)$/m);
            const titleMatch = content.match(/^title:\s*(.+)$/m);
            const areaMatch = content.match(/^area:\s*(.+)$/m);
            const todoArea = areaMatch ? areaMatch[1].trim() : 'general';
            // Apply area filter if specified
            if (area && todoArea !== area)
                continue;
            count++;
            todos.push({
                file,
                created: createdMatch ? createdMatch[1].trim() : 'unknown',
                title: titleMatch ? titleMatch[1].trim() : 'Untitled',
                area: todoArea,
                path: toPosixPath(node_path_1.default.relative(cwd, node_path_1.default.join(pendingDir, file))),
            });
        }
    }
    catch { /* intentionally empty */ }
    const result = { count, todos };
    output(result, raw, count.toString());
}
function cmdVerifyPathExists(cwd, targetPath, raw) {
    if (!targetPath) {
        error('path required for verification');
    }
    // Reject null bytes and validate path does not contain traversal attempts
    if (targetPath.includes('\0')) {
        error('path contains null bytes');
    }
    const fullPath = node_path_1.default.isAbsolute(targetPath) ? targetPath : node_path_1.default.join(cwd, targetPath);
    try {
        const stats = node_fs_1.default.statSync(fullPath);
        const type = stats.isDirectory() ? 'directory' : stats.isFile() ? 'file' : 'other';
        const result = { exists: true, type };
        output(result, raw, 'true');
    }
    catch {
        const result = { exists: false, type: null };
        output(result, raw, 'false');
    }
}
function cmdHistoryDigest(cwd, raw) {
    const phasesDir = planningPaths(cwd).phases;
    const digest = { phases: {}, decisions: [], tech_stack: new Set() };
    // Collect all phase directories: archived + current
    const allPhaseDirs = [];
    // Add archived phases first (oldest milestones first)
    const archived = getArchivedPhaseDirs(cwd);
    for (const a of archived) {
        allPhaseDirs.push({ name: a.name, fullPath: a.fullPath, milestone: a.milestone });
    }
    // Add current phases
    if (node_fs_1.default.existsSync(phasesDir)) {
        try {
            const currentDirs = node_fs_1.default.readdirSync(phasesDir, { withFileTypes: true })
                .filter(e => e.isDirectory())
                .map(e => e.name)
                .sort();
            for (const dir of currentDirs) {
                allPhaseDirs.push({ name: dir, fullPath: node_path_1.default.join(phasesDir, dir), milestone: null });
            }
        }
        catch { /* intentionally empty */ }
    }
    if (allPhaseDirs.length === 0) {
        digest.tech_stack = [];
        output(digest, raw, undefined);
        return;
    }
    try {
        for (const { name: dir, fullPath: dirPath } of allPhaseDirs) {
            const summaries = node_fs_1.default.readdirSync(dirPath).filter(f => f.endsWith('-SUMMARY.md') || f === 'SUMMARY.md');
            for (const summary of summaries) {
                const content = (0, shell_command_projection_cjs_1.platformReadSync)(node_path_1.default.join(dirPath, summary));
                if (content === null)
                    continue;
                try {
                    const fm = extractFrontmatter(content);
                    const phaseNum = fm['phase'] || dir.split('-')[0];
                    if (!digest.phases[phaseNum]) {
                        digest.phases[phaseNum] = {
                            name: fm['name'] || dir.split('-').slice(1).join(' ') || 'Unknown',
                            provides: new Set(),
                            affects: new Set(),
                            patterns: new Set(),
                        };
                    }
                    // Merge provides
                    const depGraph = fm['dependency-graph'];
                    if (depGraph && depGraph['provides']) {
                        depGraph['provides'].forEach((p) => digest.phases[phaseNum].provides.add(p));
                    }
                    else if (fm['provides']) {
                        fm['provides'].forEach((p) => digest.phases[phaseNum].provides.add(p));
                    }
                    // Merge affects
                    if (depGraph && depGraph['affects']) {
                        depGraph['affects'].forEach((a) => digest.phases[phaseNum].affects.add(a));
                    }
                    // Merge patterns
                    if (fm['patterns-established']) {
                        fm['patterns-established'].forEach((p) => digest.phases[phaseNum].patterns.add(p));
                    }
                    // Merge decisions
                    if (fm['key-decisions']) {
                        fm['key-decisions'].forEach((d) => {
                            digest.decisions.push({ phase: phaseNum, decision: d });
                        });
                    }
                    // Merge tech stack
                    const techStack = fm['tech-stack'];
                    if (techStack && techStack['added']) {
                        techStack['added'].forEach((t) => digest.tech_stack.add(typeof t === 'string' ? t : t.name));
                    }
                }
                catch {
                    // Skip malformed summaries
                }
            }
        }
        // Convert Sets to Arrays for JSON output
        Object.keys(digest.phases).forEach(p => {
            digest.phases[p].provides = [...digest.phases[p].provides];
            digest.phases[p].affects = [...digest.phases[p].affects];
            digest.phases[p].patterns = [...digest.phases[p].patterns];
        });
        digest.tech_stack = [...digest.tech_stack];
        output(digest, raw, undefined);
    }
    catch (e) {
        error('Failed to generate history digest: ' + e.message);
    }
}
function cmdResolveModel(cwd, agentType, raw) {
    if (!agentType) {
        error('agent-type required');
    }
    const config = loadConfig(cwd);
    const profile = config['model_profile'] || 'balanced';
    const model = resolveModelInternal(cwd, agentType);
    const effort = resolveEffortInternal(cwd, agentType);
    const agentModels = MODEL_PROFILES[agentType];
    const result = agentModels
        ? { model, profile, effort }
        : { model, profile, effort, unknown_agent: true };
    output(result, raw, model);
}
function cmdResolveGranularity(cwd, phaseType, raw, override) {
    if (!phaseType) {
        error('phase-type required');
    }
    assertValidGranularityOverride(override, error);
    const granularity = resolveGranularityInternal(cwd, phaseType, override);
    const result = (VALID_PHASE_TYPES).has(phaseType)
        ? { granularity, phase_type: phaseType }
        : { granularity, phase_type: phaseType, unknown_phase_type: true };
    output(result, raw, granularity);
}
/**
 * #443 β€” Superset execution query: model + unified effort + fast_mode.
 *
 * Emits JSON:
 *   { model, profile, effort, effort_rendered, effort_param, effort_propagation,
 *     fast_mode, fast_mode_supported, [unknown_agent] }
 *
 * Flags: --effort <level>, --fast-mode <true|false>, --attempt <n>
 */
function cmdResolveExecution(cwd, agentType, raw, opts) {
    if (!agentType) {
        error('agent-type required');
    }
    opts = opts || {};
    const config = loadConfig(cwd);
    const profile = config['model_profile'] || 'balanced';
    const model = resolveModelInternal(cwd, agentType);
    const effortOpts = {};
    if (typeof opts.effortOverride === 'string')
        effortOpts['override'] = opts.effortOverride;
    const fastModeOpts = {};
    if (typeof opts.fastModeOverride === 'boolean')
        fastModeOpts['override'] = opts.fastModeOverride;
    const effort = (opts.attempt !== undefined && opts.attempt !== null)
        ? resolveEffortForTier(cwd, agentType, opts.attempt)
        : resolveEffortInternal(cwd, agentType, effortOpts);
    const fastMode = resolveFastModeInternal(cwd, agentType, fastModeOpts);
    const runtime = config['runtime'] || 'claude';
    const rendered = (0, model_catalog_cjs_1.renderEffortForRuntime)(runtime, effort);
    const fastModeSupported = model_catalog_cjs_1.RUNTIMES_WITH_FAST_MODE.has(runtime);
    const agentModels = MODEL_PROFILES[agentType];
    const result = {
        model,
        profile,
        effort,
        effort_rendered: rendered.value,
        effort_param: rendered.param,
        effort_propagation: rendered.channel,
        fast_mode: fastMode,
        fast_mode_supported: fastModeSupported,
    };
    if (!agentModels)
        result['unknown_agent'] = true;
    output(result, raw, effort);
}
/**
 * #488 β€” Replace or inject the `effort:` value in YAML frontmatter.
 * Unlike injectEffortFrontmatter (install.js), this overwrites an existing value.
 */
function setEffortFrontmatter(content, effortValue) {
    const eol = /^---\r\n/.test(content) ? '\r\n' : '\n';
    const fmRe = /^---\r?\n([\s\S]*?)^---\r?$/m;
    const match = fmRe.exec(content);
    if (!match)
        return content;
    const fmBody = match[1];
    if (/^effort:/m.test(fmBody)) {
        return content.replace(/^(effort:)[ \t]*.*$/m, `$1 ${effortValue}`);
    }
    const openLen = 3 + eol.length;
    const closingStart = match.index + openLen + fmBody.length;
    return content.slice(0, closingStart) + `effort: ${effortValue}${eol}` + content.slice(closingStart);
}
/**
 * #488 β€” Re-sync effort: frontmatter in all installed gsd-*.md agent files to
 * match the current effort config, without requiring a full reinstall.
 *
 * Uses install-time resolution (readGsdEffectiveEffortConfig + resolveInstallTimeEffort
 * from bin/install.js) rather than the runtime resolver (resolveEffortInternal), because
 * the sync must mirror what install actually wrote: home defaults merged with project config.
 * The runtime resolver (loadConfig) does not merge ~/.gsd/defaults.json when a project
 * .planning/config.json exists, so it would silently ignore home-level effort changes.
 */
function cmdEffortSync(cwd, raw, opts) {
    opts = opts || {};
    const dryRun = opts.dryRun !== false;
    const config = loadConfig(cwd);
    const runtime = opts.runtime || config['runtime'] || 'claude';
    if (runtime !== 'claude') {
        output({ synced: 0, skipped: 0, changes: [], dry_run: dryRun, reason: `runtime '${runtime}' does not use effort: frontmatter` }, raw, '');
        return;
    }
    // eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/unbound-method
    const { getGlobalConfigDir } = require('./runtime-homes.cjs');
    // Use install-time resolvers: they merge ~/.gsd/defaults.json with project config,
    // matching the exact logic used when agents were originally installed.
    // eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/unbound-method
    const { readGsdEffectiveEffortConfig, resolveInstallTimeEffort } = require('../../../bin/install.js');
    const effortCfg = readGsdEffectiveEffortConfig(cwd);
    const agentsDir = node_path_1.default.join(opts.configDir || getGlobalConfigDir(runtime), 'agents');
    if (!node_fs_1.default.existsSync(agentsDir)) {
        output({ synced: 0, skipped: 0, changes: [], dry_run: dryRun, agents_dir: agentsDir, reason: 'agents directory not found' }, raw, '');
        return;
    }
    // Skip symlinks β€” only write regular files to avoid clobbering symlink targets.
    const files = node_fs_1.default.readdirSync(agentsDir).filter(f => {
        if (!f.startsWith('gsd-') || !f.endsWith('.md'))
            return false;
        try {
            return node_fs_1.default.lstatSync(node_path_1.default.join(agentsDir, f)).isFile();
        }
        catch {
            return false;
        }
    });
    const changes = [];
    let synced = 0;
    let skipped = 0;
    for (const file of files) {
        const agentName = file.replace(/\.md$/, '');
        const filePath = node_path_1.default.join(agentsDir, file);
        const content = node_fs_1.default.readFileSync(filePath, 'utf8');
        // Resolve using install-time logic: home defaults merged with project config.
        const universalEffort = resolveInstallTimeEffort(effortCfg, agentName);
        const rendered = (0, model_catalog_cjs_1.renderEffortForRuntime)(runtime, universalEffort);
        const newEffortValue = rendered.value;
        const fmMatch = /^---\r?\n([\s\S]*?)^---\r?$/m.exec(content);
        if (!fmMatch) {
            skipped++;
            continue;
        }
        const effortMatch = /^effort:[ \t]*(.+?)[ \t]*$/m.exec(fmMatch[1]);
        const currentEffort = effortMatch ? effortMatch[1] : null;
        if (currentEffort === newEffortValue) {
            skipped++;
            continue;
        }
        changes.push({ agent: agentName, from: currentEffort, to: newEffortValue });
        synced++;
        if (!dryRun) {
            node_fs_1.default.writeFileSync(filePath, setEffortFrontmatter(content, newEffortValue));
        }
    }
    output({ synced, skipped, changes, dry_run: dryRun, agents_dir: agentsDir }, raw, synced > 0 ? 'changed' : 'ok');
}
function cmdCommit(cwd, message, files, raw, amend, noVerify) {
    if (!message && !amend) {
        error('commit message required');
    }
    // Sanitize commit message: strip invisible chars and injection markers
    // that could hijack agent context when commit messages are read back
    let sanitizedMessage = message;
    if (sanitizedMessage) {
        // eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/unbound-method
        const { sanitizeForPrompt } = require('./security.cjs');
        sanitizedMessage = sanitizeForPrompt(sanitizedMessage);
    }
    const config = loadConfig(cwd);
    // Check commit_docs config
    // `skipped: true` is explicit so agent prompts can match on a first-class
    // success signal rather than inferring "skip" from "committed is missing"
    // and improvising raw git fallbacks (#3678).
    if (!config['commit_docs']) {
        const result = { committed: false, skipped: true, hash: null, reason: 'skipped_commit_docs_false' };
        output(result, raw, 'skipped');
        return;
    }
    // Check if .planning is gitignored
    if (isGitIgnored(cwd, '.planning')) {
        const result = { committed: false, skipped: true, hash: null, reason: 'skipped_gitignored' };
        output(result, raw, 'skipped');
        return;
    }
    // Ensure branching strategy branch exists before first commit (#1278).
    // Pre-execution workflows (discuss, plan, research) commit artifacts but the branch
    // was previously only created during execute-phase β€” too late.
    const branchingStrategy = config['branching_strategy'];
    if (branchingStrategy && branchingStrategy !== 'none') {
        let branchName = null;
        if (branchingStrategy === 'phase') {
            // Determine which phase we're committing for from the file paths
            const phaseMatch = (files || []).join(' ').match(/(\d+(?:\.\d+)*)-/);
            if (phaseMatch) {
                const phaseNum = phaseMatch[1];
                const phaseInfo = findPhaseInternal(cwd, phaseNum);
                if (phaseInfo) {
                    branchName = config['phase_branch_template']
                        .replace('{phase}', normalizePhaseName(phaseInfo['phase_number']))
                        .replace('{slug}', phaseInfo['phase_slug'] || 'phase');
                }
            }
        }
        else if (branchingStrategy === 'milestone') {
            const milestone = getMilestoneInfo(cwd);
            if (milestone && milestone.version) {
                branchName = config['milestone_branch_template']
                    .replace('{milestone}', milestone.version)
                    .replace('{slug}', generateSlugInternal(milestone.name) || 'milestone');
            }
        }
        if (branchName) {
            const currentBranch = (0, shell_command_projection_cjs_1.execGit)(['rev-parse', '--abbrev-ref', 'HEAD'], { cwd });
            if (currentBranch.exitCode === 0 && currentBranch.stdout.trim() !== branchName) {
                // Create branch if it doesn't exist, or switch to it if it does
                const create = (0, shell_command_projection_cjs_1.execGit)(['checkout', '-b', branchName], { cwd });
                if (create.exitCode !== 0) {
                    (0, shell_command_projection_cjs_1.execGit)(['checkout', branchName], { cwd });
                }
            }
        }
    }
    // Stage files
    const explicitFiles = files && files.length > 0;
    const filesToStage = explicitFiles ? files : ['.planning/'];
    for (const file of filesToStage) {
        const fullPath = node_path_1.default.join(cwd, file);
        if (!node_fs_1.default.existsSync(fullPath)) {
            if (explicitFiles) {
                // Caller passed an explicit --files list: missing files are skipped.
                // Staging a deletion here would silently remove tracked planning files
                // (e.g. STATE.md, ROADMAP.md) when they are temporarily absent (#2014).
                continue;
            }
            // Default mode (staging all of .planning/): stage the deletion so
            // removed planning files are not left dangling in the index.
            (0, shell_command_projection_cjs_1.execGit)(['rm', '--cached', '--ignore-unmatch', file], { cwd });
        }
        else {
            (0, shell_command_projection_cjs_1.execGit)(['add', file], { cwd });
        }
    }
    // Commit (--no-verify skips pre-commit hooks, used by parallel executor agents)
    const commitArgs = amend ? ['commit', '--amend', '--no-edit'] : ['commit', '-m', sanitizedMessage];
    if (noVerify)
        commitArgs.push('--no-verify');
    const commitResult = (0, shell_command_projection_cjs_1.execGit)(commitArgs, { cwd });
    if (commitResult.exitCode !== 0) {
        if (commitResult.stdout.includes('nothing to commit') || commitResult.stderr.includes('nothing to commit')) {
            const result = { committed: false, hash: null, reason: 'nothing_to_commit' };
            output(result, raw, 'nothing');
            return;
        }
        const result = {
            committed: false,
            hash: null,
            reason: 'commit_failed',
            error: commitResult.stderr || commitResult.stdout,
        };
        output(result, raw, 'failed');
        return;
    }
    // Get short hash
    const hashResult = (0, shell_command_projection_cjs_1.execGit)(['rev-parse', '--short', 'HEAD'], { cwd });
    const hash = hashResult.exitCode === 0 ? hashResult.stdout : null;
    const result = { committed: true, hash, reason: 'committed' };
    output(result, raw, hash || 'committed');
}
/**
 * Route a list of changed files to their sub-repo prefixes.
 *
 * Bucket sub-repos by their first path segment (#311). Any file that matches a
 * sub-repo prefix must share that sub-repo's first segment, so we only scan
 * the (small) same-first-segment bucket instead of all sub-repos. Within that
 * bucket all candidates are scanned to find the longest (most-specific)
 * matching prefix, so nested sub_repos (e.g. ['packages', 'packages/core'])
 * route to the deepest match regardless of sub_repos array order (#391).
 *
 * @param files    - changed file paths (relative to project root)
 * @param subRepos - sub-repo path prefixes from config.sub_repos
 */
function groupFilesBySubrepo(files, subRepos) {
    const reposByFirstSeg = new Map();
    for (const repo of subRepos) {
        const firstSeg = String(repo).split('/')[0];
        let bucket = reposByFirstSeg.get(firstSeg);
        if (!bucket) {
            bucket = [];
            reposByFirstSeg.set(firstSeg, bucket);
        }
        bucket.push(repo);
    }
    const grouped = {};
    const unmatched = [];
    for (const file of files) {
        const candidates = reposByFirstSeg.get(file.split('/')[0]);
        // Select the longest (most-specific) matching sub-repo prefix so nested
        // sub_repos (e.g. ['packages', 'packages/core']) route correctly regardless
        // of array order. (#391) String() guards the length read so non-string
        // entries never throw, matching the tolerance of the prior `.find` path.
        let match;
        let matchLen = -1;
        if (candidates) {
            for (const repo of candidates) {
                if (file.startsWith(repo + '/')) {
                    const repoLen = String(repo).length;
                    if (repoLen > matchLen) {
                        match = repo;
                        matchLen = repoLen;
                    }
                }
            }
        }
        if (match) {
            (grouped[match] ||= []).push(file);
        }
        else {
            unmatched.push(file);
        }
    }
    return { grouped, unmatched };
}
function cmdCommitToSubrepo(cwd, message, files, raw) {
    if (!message) {
        error('commit message required');
    }
    const config = loadConfig(cwd);
    const subRepos = config['sub_repos'];
    if (!subRepos || subRepos.length === 0) {
        error('no sub_repos configured in .planning/config.json');
    }
    if (!files || files.length === 0) {
        error('--files required for commit-to-subrepo');
    }
    // Group files by sub-repo prefix
    const { grouped, unmatched } = groupFilesBySubrepo(files, subRepos);
    if (unmatched.length > 0) {
        process.stderr.write(`Warning: ${unmatched.length} file(s) did not match any sub-repo prefix: ${unmatched.join(', ')}\n`);
    }
    const repos = {};
    for (const [repo, repoFiles] of Object.entries(grouped)) {
        const repoCwd = node_path_1.default.join(cwd, repo);
        // Stage files (strip sub-repo prefix for paths relative to that repo)
        for (const file of repoFiles) {
            const relativePath = file.slice(repo.length + 1);
            (0, shell_command_projection_cjs_1.execGit)(['add', relativePath], { cwd: repoCwd });
        }
        // Commit
        const commitResult = (0, shell_command_projection_cjs_1.execGit)(['commit', '-m', message], { cwd: repoCwd });
        if (commitResult.exitCode !== 0) {
            if (commitResult.stdout.includes('nothing to commit') || commitResult.stderr.includes('nothing to commit')) {
                repos[repo] = { committed: false, hash: null, files: repoFiles, reason: 'nothing_to_commit' };
                continue;
            }
            repos[repo] = { committed: false, hash: null, files: repoFiles, reason: 'error', error: commitResult.stderr };
            continue;
        }
        // Get hash
        const hashResult = (0, shell_command_projection_cjs_1.execGit)(['rev-parse', '--short', 'HEAD'], { cwd: repoCwd });
        const hash = hashResult.exitCode === 0 ? hashResult.stdout : null;
        repos[repo] = { committed: true, hash, files: repoFiles };
    }
    const result = {
        committed: Object.values(repos).some(r => r.committed),
        repos,
        unmatched: unmatched.length > 0 ? unmatched : undefined,
    };
    output(result, raw, Object.entries(repos).map(([r, v]) => `${r}:${v.hash || 'skip'}`).join(' '));
}
function cmdSummaryExtract(cwd, summaryPath, fields, raw) {
    if (!summaryPath) {
        error('summary-path required for summary-extract');
    }
    const fullPath = node_path_1.default.join(cwd, summaryPath);
    if (!node_fs_1.default.existsSync(fullPath)) {
        output({ error: 'File not found', path: summaryPath }, raw, undefined);
        return;
    }
    const content = node_fs_1.default.readFileSync(fullPath, 'utf-8');
    const fm = extractFrontmatter(content);
    // Parse key-decisions into structured format
    const parseDecisions = (decisionsList) => {
        if (!decisionsList || !Array.isArray(decisionsList))
            return [];
        return decisionsList.map(d => {
            const colonIdx = d.indexOf(':');
            if (colonIdx > 0) {
                return {
                    summary: d.substring(0, colonIdx).trim(),
                    rationale: d.substring(colonIdx + 1).trim(),
                };
            }
            return { summary: d, rationale: null };
        });
    };
    const techStack = fm['tech-stack'];
    // Build full result
    const fullResult = {
        path: summaryPath,
        one_liner: fm['one-liner'] || extractOneLinerFromBody(content) || null,
        key_files: fm['key-files'] || [],
        tech_added: (techStack && techStack['added']) || [],
        patterns: fm['patterns-established'] || [],
        decisions: parseDecisions(fm['key-decisions']),
        // Tolerate both key forms: the template/reader use kebab `requirements-completed`,
        // but the tool's own JSON output and the milestone audit `--pick` use snake
        // `requirements_completed`. Reading both prevents a snake-keyed SUMMARY (the form the
        // tool emits) from being silently dropped to []. See #628.
        requirements_completed: fm['requirements-completed'] ?? fm['requirements_completed'] ?? [],
    };
    // If fields specified, filter to only those fields
    if (fields && fields.length > 0) {
        const filtered = { path: summaryPath };
        for (const field of fields) {
            if (fullResult[field] !== undefined) {
                filtered[field] = fullResult[field];
            }
        }
        output(filtered, raw, undefined);
        return;
    }
    output(fullResult, raw, undefined);
}
function _wsSleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}
function _wsParseRetryAfter(header) {
    if (!header)
        return null;
    const trimmed = header.trim();
    if (/^\d+$/.test(trimmed)) {
        return Math.min(Math.max(parseInt(trimmed, 10) * 1000, 0), 60000);
    }
    const asDate = Date.parse(trimmed);
    if (!isNaN(asDate)) {
        return Math.min(Math.max(asDate - Date.now(), 0), 60000);
    }
    return null;
}
function _wsRetryDelayMs(attempt) {
    const base = 250;
    const cap = 2000;
    const exp = Math.min(base * Math.pow(2, attempt), cap);
    return exp + Math.floor(Math.random() * 100);
}
async function cmdWebsearch(query, options, raw) {
    const apiKey = process.env['BRAVE_API_KEY'];
    if (!apiKey) {
        // No key = silent skip, agent falls back to built-in WebSearch
        output({ available: false, reason: 'BRAVE_API_KEY not set' }, raw, '');
        return;
    }
    if (!query) {
        output({ available: false, error: 'Query required' }, raw, '');
        return;
    }
    const params = new URLSearchParams({
        q: query,
        count: String(options.limit || 10),
        country: 'us',
        search_lang: 'en',
        text_decorations: 'false'
    });
    if (options.freshness) {
        params.set('freshness', options.freshness);
    }
    const rawTimeout = parseInt(process.env['GSD_WEBSEARCH_TIMEOUT_MS'], 10);
    const timeoutMs = (Number.isInteger(rawTimeout) && rawTimeout > 0) ? rawTimeout : 10000;
    const MAX_RETRIES = 2;
    let attempt = 0;
    while (true) {
        try {
            const ac = new AbortController();
            const timer = setTimeout(() => ac.abort(new Error('timeout')), timeoutMs);
            let response;
            try {
                response = await fetch(
                // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
                `https://api.search.brave.com/res/v1/web/search?${params}`, {
                    headers: {
                        'Accept': 'application/json',
                        'X-Subscription-Token': apiKey
                    },
                    signal: ac.signal
                });
            }
            finally {
                clearTimeout(timer);
            }
            if (response.ok) {
                const data = await response.json();
                const results = (data.web?.results || []).map(r => ({
                    title: r.title,
                    url: r.url,
                    description: r.description,
                    age: r.age || null
                }));
                output({
                    available: true,
                    query,
                    count: results.length,
                    results
                }, raw, results.map(r => `${r.title}\n${r.url}\n${r.description}`).join('\n\n'));
                return;
            }
            const status = response.status;
            const isRetryable = status === 429 || status >= 500;
            if (!isRetryable) {
                // Non-retryable 4xx β€” fail immediately, no attempts field
                output({ available: false, error: `API error: ${status}` }, raw, '');
                return;
            }
            // Retryable HTTP error
            attempt++;
            if (attempt > MAX_RETRIES) {
                output({ available: false, error: `API error: ${status}`, attempts: attempt }, raw, '');
                return;
            }
            let delay;
            if (status === 429) {
                const retryAfter = _wsParseRetryAfter(response.headers.get('retry-after'));
                delay = retryAfter !== null ? retryAfter : _wsRetryDelayMs(attempt - 1);
            }
            else {
                delay = _wsRetryDelayMs(attempt - 1);
            }
            await _wsSleep(delay);
        }
        catch (err) {
            attempt++;
            if (attempt > MAX_RETRIES) {
                output({ available: false, error: err.message, attempts: attempt }, raw, '');
                return;
            }
            await _wsSleep(_wsRetryDelayMs(attempt - 1));
        }
    }
}
function cmdProgressRender(cwd, format, raw) {
    const phasesDir = planningPaths(cwd).phases;
    const milestone = getMilestoneInfo(cwd);
    const phases = [];
    let totalPlans = 0;
    let totalSummaries = 0;
    try {
        const entries = node_fs_1.default.readdirSync(phasesDir, { withFileTypes: true });
        const dirs = entries.filter(e => e.isDirectory()).map(e => e.name).sort((a, b) => comparePhaseNum(a, b));
        for (const dir of dirs) {
            const dm = dir.match(/^(\d+(?:\.\d+)*)-?(.*)/);
            const phaseNum = dm ? dm[1] : dir;
            const phaseName = dm && dm[2] ? dm[2].replace(/-/g, ' ') : '';
            const phaseFiles = node_fs_1.default.readdirSync(node_path_1.default.join(phasesDir, dir));
            const plans = phaseFiles.filter(f => f.endsWith('-PLAN.md') || f === 'PLAN.md').length;
            const summaries = phaseFiles.filter(f => f.endsWith('-SUMMARY.md') || f === 'SUMMARY.md').length;
            totalPlans += plans;
            totalSummaries += summaries;
            const status = determinePhaseStatus(plans, summaries, node_path_1.default.join(phasesDir, dir), 'Pending');
            phases.push({ number: phaseNum, name: phaseName, plans, summaries, status });
        }
    }
    catch { /* intentionally empty */ }
    const percent = totalPlans > 0 ? Math.min(100, Math.round((totalSummaries / totalPlans) * 100)) : 0;
    if (format === 'table') {
        // Render markdown table
        const barWidth = 10;
        const filled = Math.round((percent / 100) * barWidth);
        const bar = 'β–ˆ'.repeat(filled) + 'β–‘'.repeat(barWidth - filled);
        let out = `# ${milestone.version} ${milestone.name}\n\n`;
        out += `**Progress:** [${bar}] ${totalSummaries}/${totalPlans} plans (${percent}%)\n\n`;
        out += `| Phase | Name | Plans | Status |\n`;
        out += `|-------|------|-------|--------|\n`;
        for (const p of phases) {
            out += `| ${p.number} | ${p.name} | ${p.summaries}/${p.plans} | ${p.status} |\n`;
        }
        output({ rendered: out }, raw, out);
    }
    else if (format === 'bar') {
        const barWidth = 20;
        const filled = Math.round((percent / 100) * barWidth);
        const bar = 'β–ˆ'.repeat(filled) + 'β–‘'.repeat(barWidth - filled);
        const text = `[${bar}] ${totalSummaries}/${totalPlans} plans (${percent}%)`;
        output({ bar: text, percent, completed: totalSummaries, total: totalPlans }, raw, text);
    }
    else {
        // JSON format
        output({
            milestone_version: milestone.version,
            milestone_name: milestone.name,
            phases,
            total_plans: totalPlans,
            total_summaries: totalSummaries,
            percent,
        }, raw, undefined);
    }
}
/**
 * Match pending todos against a phase's goal/name/requirements.
 * Returns todos with relevance scores based on keyword, area, and file overlap.
 * Used by discuss-phase to surface relevant todos before scope-setting.
 */
function cmdTodoMatchPhase(cwd, phase, raw) {
    if (!phase) {
        error('phase required for todo match-phase');
    }
    const pendingDir = node_path_1.default.join(planningDir(cwd), 'todos', 'pending');
    const todos = [];
    // Load pending todos
    try {
        const files = node_fs_1.default.readdirSync(pendingDir).filter(f => f.endsWith('.md'));
        for (const file of files) {
            const content = (0, shell_command_projection_cjs_1.platformReadSync)(node_path_1.default.join(pendingDir, file));
            if (content === null)
                continue;
            const titleMatch = content.match(/^title:\s*(.+)$/m);
            const areaMatch = content.match(/^area:\s*(.+)$/m);
            const filesMatch = content.match(/^files:\s*(.+)$/m);
            const body = content.replace(/^(title|area|files|created|priority):.*$/gm, '').trim();
            todos.push({
                file,
                title: titleMatch ? titleMatch[1].trim() : 'Untitled',
                area: areaMatch ? areaMatch[1].trim() : 'general',
                files: filesMatch ? filesMatch[1].trim().split(/[,\s]+/).filter(Boolean) : [],
                body: body.slice(0, 200), // first 200 chars for context
            });
        }
    }
    catch { /* intentionally empty */ }
    if (todos.length === 0) {
        output({ phase, matches: [], todo_count: 0 }, raw, undefined);
        return;
    }
    // Load phase goal/name from ROADMAP
    const phaseInfo = getRoadmapPhaseInternal(cwd, phase);
    const phaseName = phaseInfo ? (phaseInfo['phase_name'] || '') : '';
    const phaseGoal = phaseInfo ? (phaseInfo['goal'] || '') : '';
    const phaseSection = phaseInfo ? (phaseInfo['section'] || '') : '';
    // Build keyword set from phase name + goal + section text
    const phaseText = `${phaseName} ${phaseGoal} ${phaseSection}`.toLowerCase();
    const stopWords = new Set(['the', 'and', 'for', 'with', 'from', 'that', 'this', 'will', 'are', 'was', 'has', 'have', 'been', 'not', 'but', 'all', 'can', 'into', 'each', 'when', 'any', 'use', 'new']);
    const phaseKeywords = new Set(phaseText.split(/[\s\-_/.,;:()\[\]{}|]+/)
        .map(w => w.replace(/[^a-z0-9]/g, ''))
        .filter(w => w.length > 2 && !stopWords.has(w)));
    // Find phase directory to get expected file paths
    const phaseInfoDisk = findPhaseInternal(cwd, phase);
    const phasePlans = [];
    if (phaseInfoDisk && phaseInfoDisk['found']) {
        try {
            const phaseDir = node_path_1.default.join(cwd, phaseInfoDisk['directory']);
            const planFiles = node_fs_1.default.readdirSync(phaseDir).filter(f => f.endsWith('-PLAN.md'));
            for (const pf of planFiles) {
                const planContent = (0, shell_command_projection_cjs_1.platformReadSync)(node_path_1.default.join(phaseDir, pf));
                if (planContent === null)
                    continue;
                const fmFiles = planContent.match(/files_modified:\s*\[([^\]]*)\]/);
                if (fmFiles) {
                    phasePlans.push(...fmFiles[1].split(',').map(s => s.trim().replace(/['"]/g, '')).filter(Boolean));
                }
            }
        }
        catch { /* intentionally empty */ }
    }
    // Score each todo for relevance
    const matches = [];
    for (const todo of todos) {
        let score = 0;
        const reasons = [];
        // Keyword match: todo title/body terms in phase text
        const todoWords = `${todo.title} ${todo.body}`.toLowerCase()
            .split(/[\s\-_/.,;:()\[\]{}|]+/)
            .map(w => w.replace(/[^a-z0-9]/g, ''))
            .filter(w => w.length > 2 && !stopWords.has(w));
        const matchedKeywords = todoWords.filter(w => phaseKeywords.has(w));
        if (matchedKeywords.length > 0) {
            score += Math.min(matchedKeywords.length * 0.2, 0.6);
            reasons.push(`keywords: ${[...new Set(matchedKeywords)].slice(0, 5).join(', ')}`);
        }
        // Area match: todo area appears in phase text
        if (todo.area !== 'general' && phaseText.includes(todo.area.toLowerCase())) {
            score += 0.3;
            reasons.push(`area: ${todo.area}`);
        }
        // File match: todo files overlap with phase plan files
        if (todo.files.length > 0 && phasePlans.length > 0) {
            const fileOverlap = todo.files.filter(f => phasePlans.some(pf => pf.includes(f) || f.includes(pf)));
            if (fileOverlap.length > 0) {
                score += 0.4;
                reasons.push(`files: ${fileOverlap.slice(0, 3).join(', ')}`);
            }
        }
        if (score > 0) {
            matches.push({
                file: todo.file,
                title: todo.title,
                area: todo.area,
                score: Math.round(score * 100) / 100,
                reasons,
            });
        }
    }
    // Sort by score descending
    matches.sort((a, b) => b.score - a.score);
    output({ phase, matches, todo_count: todos.length }, raw, undefined);
}
function cmdTodoComplete(cwd, filename, raw) {
    if (!filename) {
        error('filename required for todo complete');
    }
    const pendingDir = node_path_1.default.join(planningDir(cwd), 'todos', 'pending');
    const completedDir = node_path_1.default.join(planningDir(cwd), 'todos', 'completed');
    const sourcePath = node_path_1.default.join(pendingDir, filename);
    if (!node_fs_1.default.existsSync(sourcePath)) {
        error(`Todo not found: ${filename}`);
    }
    // Ensure completed directory exists
    (0, shell_command_projection_cjs_1.platformEnsureDir)(completedDir);
    // Read, add completion timestamp, move
    let content = node_fs_1.default.readFileSync(sourcePath, 'utf-8');
    const today = new Date().toISOString().split('T')[0];
    content = `completed: ${today}\n` + content;
    (0, shell_command_projection_cjs_1.platformWriteSync)(node_path_1.default.join(completedDir, filename), content);
    node_fs_1.default.unlinkSync(sourcePath);
    output({ completed: true, file: filename, date: today }, raw, 'completed');
}
function cmdScaffold(cwd, type, options, raw) {
    const { phase, name } = options;
    const padded = phase ? normalizePhaseName(phase) : '00';
    const today = new Date().toISOString().split('T')[0];
    // Find phase directory
    const phaseInfo = phase ? findPhaseInternal(cwd, phase) : null;
    const phaseDir = phaseInfo ? node_path_1.default.join(cwd, phaseInfo['directory']) : null;
    if (phase && !phaseDir && type !== 'phase-dir') {
        error(`Phase ${phase} directory not found`);
    }
    let filePath, content;
    switch (type) {
        case 'context': {
            filePath = node_path_1.default.join(phaseDir, `${padded}-CONTEXT.md`);
            content = `---\nphase: "${padded}"\nname: "${name || phaseInfo?.['phase_name'] || 'Unnamed'}"\ncreated: ${today}\n---\n\n# Phase ${phase}: ${name || phaseInfo?.['phase_name'] || 'Unnamed'} β€” Context\n\n## Decisions\n\n_Decisions will be captured during ${String((0, runtime_slash_cjs_1.formatGsdSlash)('discuss-phase', (0, runtime_slash_cjs_1.resolveRuntime)(cwd)))} ${phase}_\n\n## Discretion Areas\n\n_Areas where the executor can use judgment_\n\n## Deferred Ideas\n\n_Ideas to consider later_\n`;
            break;
        }
        case 'uat': {
            filePath = node_path_1.default.join(phaseDir, `${padded}-UAT.md`);
            content = `---\nphase: "${padded}"\nname: "${name || phaseInfo?.['phase_name'] || 'Unnamed'}"\ncreated: ${today}\nstatus: pending\n---\n\n# Phase ${phase}: ${name || phaseInfo?.['phase_name'] || 'Unnamed'} β€” User Acceptance Testing\n\n## Test Results\n\n| # | Test | Status | Notes |\n|---|------|--------|-------|\n\n## Summary\n\n_Pending UAT_\n`;
            break;
        }
        case 'verification': {
            filePath = node_path_1.default.join(phaseDir, `${padded}-VERIFICATION.md`);
            content = `---\nphase: "${padded}"\nname: "${name || phaseInfo?.['phase_name'] || 'Unnamed'}"\ncreated: ${today}\nstatus: pending\n---\n\n# Phase ${phase}: ${name || phaseInfo?.['phase_name'] || 'Unnamed'} β€” Verification\n\n## Goal-Backward Verification\n\n**Phase Goal:** [From ROADMAP.md]\n\n## Checks\n\n| # | Requirement | Status | Evidence |\n|---|------------|--------|----------|\n\n## Result\n\n_Pending verification_\n`;
            break;
        }
        case 'phase-dir': {
            if (!phase || !name) {
                error('phase and name required for phase-dir scaffold');
            }
            const slug = generateSlugInternal(name);
            // #3287: apply project_code prefix to stay consistent with phase.add/phase.insert
            const scaffoldConfig = loadConfig(cwd);
            const scaffoldProjectCode = scaffoldConfig['project_code'] || '';
            const scaffoldPrefix = scaffoldProjectCode ? `${scaffoldProjectCode}-` : '';
            const dirName = `${scaffoldPrefix}${padded}-${slug}`;
            const phasesParent = planningPaths(cwd).phases;
            (0, shell_command_projection_cjs_1.platformEnsureDir)(phasesParent);
            const dirPath = node_path_1.default.join(phasesParent, dirName);
            (0, shell_command_projection_cjs_1.platformEnsureDir)(dirPath);
            output({ created: true, directory: toPosixPath(node_path_1.default.relative(cwd, dirPath)), path: dirPath }, raw, dirPath);
            return;
        }
        default:
            error(`Unknown scaffold type: ${type}. Available: context, uat, verification, phase-dir`);
            // unreachable β€” error() calls process.exit
            return;
    }
    if (node_fs_1.default.existsSync(filePath)) {
        output({ created: false, reason: 'already_exists', path: filePath }, raw, 'exists');
        return;
    }
    (0, shell_command_projection_cjs_1.platformWriteSync)(filePath, content);
    const relPath = toPosixPath(node_path_1.default.relative(cwd, filePath));
    output({ created: true, path: relPath }, raw, relPath);
}
function cmdStats(cwd, format, raw) {
    const phasesDir = planningPaths(cwd).phases;
    const roadmapPath = planningPaths(cwd).roadmap;
    const reqPath = planningPaths(cwd).requirements;
    const statePath = planningPaths(cwd).state;
    const milestone = getMilestoneInfo(cwd);
    const isDirInMilestone = getMilestonePhaseFilter(cwd);
    // Phase & plan stats (reuse progress pattern)
    const phasesByNumber = new Map();
    let totalPlans = 0;
    let totalSummaries = 0;
    try {
        const roadmapRaw = (0, shell_command_projection_cjs_1.platformReadSync)(roadmapPath);
        if (roadmapRaw === null)
            throw new Error('roadmap missing');
        const roadmapContent = extractCurrentMilestone(roadmapRaw, cwd);
        // Matches both plain numeric (Phase 1:) and milestone-prefixed (Phase 2-01:) headings.
        // Also tolerates optional [bracket-token] scope prefix on phase headings.
        const headingPattern = /#{2,4}\s*(?:\[[^\]]+\]\s*)?Phase\s+([\w][\w.-]*)\s*:\s*([^\n]+)/gi;
        let match;
        while ((match = headingPattern.exec(roadmapContent)) !== null) {
            const key = normalizePhaseName(match[1]);
            phasesByNumber.set(key, {
                number: key,
                name: match[2].replace(/\(INSERTED\)/i, '').trim(),
                plans: 0,
                summaries: 0,
                status: 'Not Started',
            });
        }
    }
    catch { /* intentionally empty */ }
    try {
        const entries = node_fs_1.default.readdirSync(phasesDir, { withFileTypes: true });
        const dirs = entries
            .filter(e => e.isDirectory())
            .map(e => e.name)
            .filter(isDirInMilestone)
            .sort((a, b) => comparePhaseNum(a, b));
        for (const dir of dirs) {
            // Use extractPhaseToken to correctly parse M-NN-style and code-prefixed dir names.
            const phaseToken = extractPhaseToken(dir);
            const phaseNum = phaseToken || dir;
            // phaseName is everything after the token (strip leading '-')
            const afterToken = dir.slice(phaseToken ? phaseToken.length : 0).replace(/^-/, '');
            const phaseName = afterToken ? afterToken.replace(/-/g, ' ') : '';
            const phaseFiles = node_fs_1.default.readdirSync(node_path_1.default.join(phasesDir, dir));
            const plans = phaseFiles.filter(f => f.endsWith('-PLAN.md') || f === 'PLAN.md').length;
            const summaries = phaseFiles.filter(f => f.endsWith('-SUMMARY.md') || f === 'SUMMARY.md').length;
            totalPlans += plans;
            totalSummaries += summaries;
            const status = determinePhaseStatus(plans, summaries, node_path_1.default.join(phasesDir, dir), 'Not Started');
            const normalizedNum = normalizePhaseName(phaseNum);
            const existing = phasesByNumber.get(normalizedNum);
            phasesByNumber.set(normalizedNum, {
                number: normalizedNum,
                name: existing?.name || phaseName,
                plans: (existing?.plans || 0) + plans,
                summaries: (existing?.summaries || 0) + summaries,
                status,
            });
        }
    }
    catch { /* intentionally empty */ }
    const phases = [...phasesByNumber.values()].sort((a, b) => comparePhaseNum(a.number, b.number));
    const completedPhases = phases.filter(p => p.status === 'Complete').length;
    const planPercent = totalPlans > 0 ? Math.min(100, Math.round((totalSummaries / totalPlans) * 100)) : 0;
    const percent = phases.length > 0 ? Math.min(100, Math.round((completedPhases / phases.length) * 100)) : 0;
    // Requirements stats
    let requirementsTotal = 0;
    let requirementsComplete = 0;
    const reqContent = (0, shell_command_projection_cjs_1.platformReadSync)(reqPath);
    if (reqContent !== null) {
        const checked = reqContent.match(/^- \[x\] \*\*/gm);
        const unchecked = reqContent.match(/^- \[ \] \*\*/gm);
        requirementsComplete = checked ? checked.length : 0;
        requirementsTotal = requirementsComplete + (unchecked ? unchecked.length : 0);
    }
    // Last activity from STATE.md
    let lastActivity = null;
    const stateContent = (0, shell_command_projection_cjs_1.platformReadSync)(statePath);
    if (stateContent !== null) {
        const activityMatch = stateContent.match(/^last_activity:\s*(.+)$/im)
            || stateContent.match(/\*\*Last Activity:\*\*\s*(.+)/i)
            || stateContent.match(/^Last Activity:\s*(.+)$/im)
            || stateContent.match(/^Last activity:\s*(.+)$/im);
        if (activityMatch)
            lastActivity = activityMatch[1].trim();
    }
    // Git stats
    let gitCommits = 0;
    let gitFirstCommitDate = null;
    const commitCount = (0, shell_command_projection_cjs_1.execGit)(['rev-list', '--count', 'HEAD'], { cwd });
    if (commitCount.exitCode === 0) {
        gitCommits = parseInt(commitCount.stdout, 10) || 0;
    }
    const rootHash = (0, shell_command_projection_cjs_1.execGit)(['rev-list', '--max-parents=0', 'HEAD'], { cwd });
    if (rootHash.exitCode === 0 && rootHash.stdout) {
        const firstCommit = rootHash.stdout.split('\n')[0].trim();
        const firstDate = (0, shell_command_projection_cjs_1.execGit)(['show', '-s', '--format=%as', firstCommit], { cwd });
        if (firstDate.exitCode === 0) {
            gitFirstCommitDate = firstDate.stdout || null;
        }
    }
    const result = {
        milestone_version: milestone.version,
        milestone_name: milestone.name,
        phases,
        phases_completed: completedPhases,
        phases_total: phases.length,
        total_plans: totalPlans,
        total_summaries: totalSummaries,
        percent,
        plan_percent: planPercent,
        requirements_total: requirementsTotal,
        requirements_complete: requirementsComplete,
        git_commits: gitCommits,
        git_first_commit_date: gitFirstCommitDate,
        last_activity: lastActivity,
    };
    if (format === 'table') {
        const barWidth = 10;
        const filled = Math.round((percent / 100) * barWidth);
        const bar = 'β–ˆ'.repeat(filled) + 'β–‘'.repeat(barWidth - filled);
        let out = `# ${milestone.version} ${milestone.name} β€” Statistics\n\n`;
        out += `**Progress:** [${bar}] ${completedPhases}/${phases.length} phases (${percent}%)\n`;
        if (totalPlans > 0) {
            out += `**Plans:** ${totalSummaries}/${totalPlans} complete (${planPercent}%)\n`;
        }
        out += `**Phases:** ${completedPhases}/${phases.length} complete\n`;
        if (requirementsTotal > 0) {
            out += `**Requirements:** ${requirementsComplete}/${requirementsTotal} complete\n`;
        }
        out += '\n';
        out += `| Phase | Name | Plans | Completed | Status |\n`;
        out += `|-------|------|-------|-----------|--------|\n`;
        for (const p of phases) {
            out += `| ${p.number} | ${p.name} | ${p.plans} | ${p.summaries} | ${p.status} |\n`;
        }
        if (gitCommits > 0) {
            out += `\n**Git:** ${gitCommits} commits`;
            if (gitFirstCommitDate)
                out += ` (since ${gitFirstCommitDate})`;
            out += '\n';
        }
        if (lastActivity)
            out += `**Last activity:** ${lastActivity}\n`;
        output({ rendered: out }, raw, out);
    }
    else {
        output(result, raw, undefined);
    }
}
/**
 * Check whether a commit should be allowed based on commit_docs config.
 * When commit_docs is false, rejects commits that stage .planning/ files.
 * Intended for use as a pre-commit hook guard.
 */
function cmdCheckCommit(cwd, raw) {
    const config = loadConfig(cwd);
    // If commit_docs is true (or not set), allow all commits
    if (config['commit_docs'] !== false) {
        output({ allowed: true, reason: 'commit_docs_enabled' }, raw, 'allowed');
        return;
    }
    // commit_docs is false β€” check if any .planning/ files are staged
    const stagedResult = (0, shell_command_projection_cjs_1.execGit)(['diff', '--cached', '--name-only'], { cwd });
    if (stagedResult.exitCode === 0) {
        const planningFiles = stagedResult.stdout.split('\n').filter(f => f.startsWith('.planning/') || f.startsWith('.planning\\'));
        if (planningFiles.length > 0) {
            error(`commit_docs is false but ${planningFiles.length} .planning/ file(s) are staged:\n` +
                planningFiles.map(f => `  ${f}`).join('\n') +
                `\n\nTo unstage: git reset HEAD ${planningFiles.join(' ')}`);
        }
    }
    // exitCode !== 0 β†’ no staged files or not a git repo β€” allow
    output({ allowed: true, reason: 'no_planning_files_staged' }, raw, 'allowed');
}
module.exports = {
    groupFilesBySubrepo,
    determinePhaseStatus,
    cmdGenerateSlug,
    cmdCurrentTimestamp,
    cmdListTodos,
    cmdVerifyPathExists,
    cmdHistoryDigest,
    cmdResolveModel,
    cmdResolveGranularity,
    cmdResolveExecution,
    cmdEffortSync,
    cmdCommit,
    cmdCommitToSubrepo,
    cmdSummaryExtract,
    cmdWebsearch,
    cmdProgressRender,
    cmdTodoComplete,
    cmdTodoMatchPhase,
    cmdScaffold,
    cmdStats,
    cmdCheckCommit,
    _wsParseRetryAfter,
};