-
Notifications
You must be signed in to change notification settings - Fork 328
Expand file tree
/
Copy pathindex.cjs
More file actions
1920 lines (1700 loc) · 71.5 KB
/
index.cjs
File metadata and controls
1920 lines (1700 loc) · 71.5 KB
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
#!/usr/bin/env node
const fs = require('fs');
const path = require('path');
const { calculatePrRework, calculateReworkSummary } = require('./lib/rework.cjs');
const GREEN = '\x1b[32m';
const RED = '\x1b[31m';
const YELLOW = '\x1b[33m';
const DIM = '\x1b[2m';
const BOLD = '\x1b[1m';
const RESET = '\x1b[0m';
function fatal(msg) {
console.error(`${RED}✗${RESET} ${msg}`);
process.exit(1);
}
// Detect squad directory — .squad/ first, fall back to .ai-team/
function detectSquadDir(dest) {
const squadDir = path.join(dest, '.squad');
const aiTeamDir = path.join(dest, '.ai-team');
if (fs.existsSync(squadDir)) {
return { path: squadDir, name: '.squad', isLegacy: false };
}
if (fs.existsSync(aiTeamDir)) {
return { path: aiTeamDir, name: '.ai-team', isLegacy: true };
}
// Default for new installations
return { path: squadDir, name: '.squad', isLegacy: false };
}
function showDeprecationWarning() {
console.log();
console.log(`${YELLOW}⚠️ DEPRECATION: .ai-team/ is deprecated and will be removed in v1.0.0${RESET}`);
console.log(`${YELLOW} Run 'npx github:bradygaster/squad upgrade --migrate-directory' to migrate to .squad/${RESET}`);
console.log(`${YELLOW} Details: https://github.com/bradygaster/squad/issues/101${RESET}`);
console.log();
}
process.on('uncaughtException', (err) => {
fatal(`Unexpected error: ${err.message}`);
});
const root = __dirname;
const dest = process.cwd();
const pkg = require(path.join(root, 'package.json'));
const cmd = process.argv[2];
// --version / --help
if (cmd === '--version' || cmd === '-v') {
console.log(`Package: ${pkg.version}`);
const agentMdPath = path.join(dest, '.github', 'agents', 'squad.agent.md');
let installedVersion = 'not installed';
if (fs.existsSync(agentMdPath)) {
const content = fs.readFileSync(agentMdPath, 'utf8');
const match = content.match(/<!-- version: ([^\s]+) -->/);
if (match) installedVersion = match[1];
}
console.log(`Installed: ${installedVersion}`);
process.exit(0);
}
if (cmd === '--help' || cmd === '-h' || cmd === 'help') {
console.log(`\n${BOLD}squad${RESET} v${pkg.version} — Add an AI agent team to any project\n`);
console.log(`Usage: npx github:bradygaster/squad [command]\n`);
console.log(`Commands:`);
console.log(` ${BOLD}(default)${RESET} Initialize Squad (skip files that already exist)`);
console.log(` ${BOLD}upgrade${RESET} Update Squad-owned files to latest version`);
console.log(` Overwrites: squad.agent.md, templates dir (.squad/templates/ or .ai-team-templates/)`);
console.log(` Never touches: .squad/ or .ai-team/ (your team state)`);
console.log(` Flags: --migrate-directory (rename .ai-team/ → .squad/)`);
console.log(` ${BOLD}copilot${RESET} Add/remove the Copilot coding agent (@copilot)`);
console.log(` Usage: copilot [--off] [--auto-assign]`);
console.log(` ${BOLD}rework${RESET} Analyze PR rework rate (the 5th DORA metric)`);
console.log(` Usage: rework [--days <N>] [--limit <N>] [--json]`);
console.log(` Default: last 30 days, up to 20 PRs`);
console.log(` ${BOLD}watch${RESET} Run Ralph's work monitor as a local polling process`);
console.log(` Usage: watch [--interval <minutes>]`);
console.log(` Default: checks every 10 minutes (Ctrl+C to stop)`);
console.log(` ${BOLD}plugin${RESET} Manage plugin marketplaces`);
console.log(` Usage: plugin marketplace add|remove|list|browse`);
console.log(` ${BOLD}export${RESET} Export squad to a portable JSON snapshot`);
console.log(` Default: squad-export.json (use --out <path> to override)`);
console.log(` ${BOLD}import${RESET} Import squad from an export file`);
console.log(` Usage: import <file> [--force]`);
console.log(` ${BOLD}scrub-emails${RESET} Remove email addresses from Squad state files`);
console.log(` Usage: scrub-emails [directory] (default: .ai-team/)`);
console.log(` ${BOLD}help${RESET} Show this help message`);
console.log(`\nFlags:`);
console.log(` ${BOLD}--version, -v${RESET} Print version`);
console.log(` ${BOLD}--help, -h${RESET} Show help`);
console.log(`\nInsider channel: npx github:bradygaster/squad#insider\n`);
process.exit(0);
}
function copyRecursive(src, target) {
try {
if (fs.statSync(src).isDirectory()) {
fs.mkdirSync(target, { recursive: true });
for (const entry of fs.readdirSync(src)) {
copyRecursive(path.join(src, entry), path.join(target, entry));
}
} else {
fs.mkdirSync(path.dirname(target), { recursive: true });
fs.copyFileSync(src, target);
}
} catch (err) {
fatal(`Failed to copy ${path.relative(root, src)}: ${err.message}`);
}
}
// --- Rework Rate subcommand ---
if (cmd === 'rework') {
const { execSync } = require('child_process');
// Verify gh CLI is available
try {
execSync('gh --version', { stdio: 'pipe' });
} catch {
fatal('gh CLI not found — install from https://cli.github.com');
}
// Parse flags
const daysIdx = process.argv.indexOf('--days');
const lookbackDays = (daysIdx !== -1 && process.argv[daysIdx + 1])
? parseInt(process.argv[daysIdx + 1], 10) : 30;
const limitIdx = process.argv.indexOf('--limit');
const prLimit = (limitIdx !== -1 && process.argv[limitIdx + 1])
? parseInt(process.argv[limitIdx + 1], 10) : 20;
const jsonOutput = process.argv.includes('--json');
if (isNaN(lookbackDays) || lookbackDays < 1) fatal('--days must be a positive number');
if (isNaN(prLimit) || prLimit < 1) fatal('--limit must be a positive number');
const sinceDate = new Date(Date.now() - lookbackDays * 86400000).toISOString().split('T')[0];
if (!jsonOutput) {
console.log(`\n${BOLD}📊 Rework Rate Analysis${RESET}`);
console.log(`${DIM}Analyzing merged PRs from the last ${lookbackDays} days (limit: ${prLimit})...${RESET}\n`);
}
// Fetch merged PRs
let prs;
try {
const prJson = execSync(
`gh pr list --state merged --limit ${prLimit} --search "merged:>=${sinceDate}" --json number,title,author,mergedAt,additions,deletions,changedFiles`,
{ encoding: 'utf8', timeout: 30000, stdio: ['pipe', 'pipe', 'pipe'] }
);
prs = JSON.parse(prJson || '[]');
} catch (err) {
fatal(`Failed to fetch PRs: ${err.message}`);
}
if (prs.length === 0) {
if (jsonOutput) {
console.log(JSON.stringify({ prs: [], summary: { totalPrs: 0 } }, null, 2));
} else {
console.log(`${DIM}No merged PRs found in the last ${lookbackDays} days.${RESET}`);
}
process.exit(0);
}
// Analyze each PR for rework
const results = [];
for (const pr of prs) {
let reviews, commits;
try {
const prDetail = execSync(
`gh pr view ${pr.number} --json reviews,commits`,
{ encoding: 'utf8', timeout: 15000, stdio: ['pipe', 'pipe', 'pipe'] }
);
const detail = JSON.parse(prDetail);
reviews = detail.reviews || [];
commits = detail.commits || [];
} catch {
// Skip PRs we can't fetch details for
continue;
}
const rework = calculatePrRework(pr, reviews, commits);
results.push(rework);
}
// Calculate aggregate metrics
const summary = calculateReworkSummary(results);
if (jsonOutput) {
console.log(JSON.stringify({ prs: results, summary }, null, 2));
} else {
printReworkReport(results, summary, lookbackDays);
}
process.exit(0);
}
/**
* Print human-readable rework report.
*/
function printReworkReport(results, summary, lookbackDays) {
console.log(`${BOLD}Summary (${summary.totalPrs} PRs, last ${lookbackDays} days)${RESET}`);
console.log(`${'─'.repeat(50)}`);
console.log(` Average rework rate: ${colorReworkRate(summary.avgReworkRate)}%`);
console.log(` PRs with rework: ${summary.prsWithRework}/${summary.totalPrs} (${Math.round(summary.prsWithRework / summary.totalPrs * 100)}%)`);
console.log(` Rejection rate: ${summary.rejectionRate}%`);
console.log(` Avg review cycles: ${summary.avgReviewCycles}`);
console.log(` Total rework commits: ${summary.totalReworkCommits}/${summary.totalCommits}`);
if (summary.avgReworkTimeHours !== null) {
console.log(` Avg rework time: ${summary.avgReworkTimeHours}h`);
}
console.log();
// Per-PR breakdown
console.log(`${BOLD}Per-PR Breakdown${RESET}`);
console.log(`${'─'.repeat(80)}`);
for (const r of results) {
const rateLabel = colorReworkRate(r.reworkRate);
const changeLabel = r.hadChangesRequested ? `${YELLOW}⚑${RESET}` : ' ';
console.log(` #${String(r.number).padEnd(5)} ${rateLabel.padEnd(20)}% rework ${r.reviewCycles} cycles ${changeLabel} ${DIM}${r.title.substring(0, 40)}${RESET}`);
}
console.log();
// Interpretation guide
if (summary.avgReworkRate <= 15) {
console.log(`${GREEN}✓${RESET} Rework rate is healthy. Code quality and review process are strong.`);
} else if (summary.avgReworkRate <= 30) {
console.log(`${YELLOW}⚠${RESET} Moderate rework rate. Consider improving PR descriptions or pre-review checks.`);
} else {
console.log(`${RED}✗${RESET} High rework rate. Review process may need attention — consider smaller PRs, clearer specs, or pair reviews.`);
}
console.log();
}
function colorReworkRate(rate) {
if (rate <= 15) return `${GREEN}${rate}${RESET}`;
if (rate <= 30) return `${YELLOW}${rate}${RESET}`;
return `${RED}${rate}${RESET}`;
}
// --- Watch subcommand (Ralph local watchdog) ---
if (cmd === 'watch') {
const { execSync } = require('child_process');
const squadDirInfo = detectSquadDir(dest);
if (squadDirInfo.isLegacy) showDeprecationWarning();
const teamMd = path.join(squadDirInfo.path, 'team.md');
if (!fs.existsSync(teamMd)) {
fatal('No squad found — run init first.');
}
// Verify gh CLI is available
try {
execSync('gh --version', { stdio: 'pipe' });
} catch {
fatal('gh CLI not found — install from https://cli.github.com');
}
// Parse --interval flag (default: 10 minutes)
const intervalIdx = process.argv.indexOf('--interval');
const intervalMin = (intervalIdx !== -1 && process.argv[intervalIdx + 1])
? parseInt(process.argv[intervalIdx + 1], 10)
: 10;
if (isNaN(intervalMin) || intervalMin < 1) {
fatal('--interval must be a positive number of minutes');
}
const content = fs.readFileSync(teamMd, 'utf8');
function slugify(t) { return t.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, ''); }
// Parse members from roster
function parseMembers(text) {
const lines = text.split('\n');
const members = [];
let inMembersTable = false;
for (const line of lines) {
if (line.startsWith('## Members')) { inMembersTable = true; continue; }
if (inMembersTable && line.startsWith('## ')) break;
if (inMembersTable && line.startsWith('|') && !line.includes('---') && !line.includes('Name')) {
const cells = line.split('|').map(c => c.trim()).filter(Boolean);
if (cells.length >= 2 && !['Scribe', 'Ralph'].includes(cells[0])) {
members.push({ name: cells[0], role: cells[1], label: `squad:${slugify(cells[0])}` });
}
}
}
return members;
}
const members = parseMembers(content);
if (members.length === 0) {
fatal('No squad members found in team.md');
}
const hasCopilot = content.includes('🤖 Coding Agent') || content.includes('@copilot');
const autoAssign = content.includes('<!-- copilot-auto-assign: true -->');
console.log(`\n${BOLD}🔄 Ralph — Watch Mode${RESET}`);
console.log(`${DIM}Polling every ${intervalMin} minute(s) for squad work. Ctrl+C to stop.${RESET}\n`);
function runCheck() {
const timestamp = new Date().toLocaleTimeString();
try {
// Fetch open issues with squad label
const issuesJson = execSync(
'gh issue list --label "squad" --state open --json number,title,labels,assignees --limit 20',
{ stdio: 'pipe', encoding: 'utf8' }
);
const issues = JSON.parse(issuesJson || '[]');
const memberLabels = members.map(m => m.label);
const untriaged = issues.filter(issue => {
const issueLabels = issue.labels.map(l => l.name);
return !memberLabels.some(ml => issueLabels.includes(ml));
});
// Find unassigned squad:copilot issues
let unassignedCopilot = [];
if (hasCopilot && autoAssign) {
try {
const copilotJson = execSync(
'gh issue list --label "squad:copilot" --state open --json number,title,assignees --limit 10',
{ stdio: 'pipe', encoding: 'utf8' }
);
const copilotIssues = JSON.parse(copilotJson || '[]');
unassignedCopilot = copilotIssues.filter(i => !i.assignees || i.assignees.length === 0);
} catch { /* label may not exist */ }
}
if (untriaged.length === 0 && unassignedCopilot.length === 0) {
console.log(`${DIM}[${timestamp}]${RESET} 📋 Board is clear — no pending work`);
return;
}
// Triage untriaged issues
for (const issue of untriaged) {
const issueText = `${issue.title}`.toLowerCase();
let assignedMember = null;
let reason = '';
for (const member of members) {
const role = member.role.toLowerCase();
if ((role.includes('frontend') || role.includes('ui')) &&
(issueText.includes('ui') || issueText.includes('frontend') || issueText.includes('css'))) {
assignedMember = member; reason = 'frontend/UI domain'; break;
}
if ((role.includes('backend') || role.includes('api') || role.includes('server')) &&
(issueText.includes('api') || issueText.includes('backend') || issueText.includes('database'))) {
assignedMember = member; reason = 'backend/API domain'; break;
}
if ((role.includes('test') || role.includes('qa')) &&
(issueText.includes('test') || issueText.includes('bug') || issueText.includes('fix'))) {
assignedMember = member; reason = 'testing/QA domain'; break;
}
}
if (!assignedMember) {
const lead = members.find(m =>
m.role.toLowerCase().includes('lead') || m.role.toLowerCase().includes('architect')
);
if (lead) { assignedMember = lead; reason = 'no domain match — routed to Lead'; }
}
if (assignedMember) {
try {
execSync(`gh issue edit ${issue.number} --add-label "${assignedMember.label}"`, { stdio: 'pipe' });
console.log(`${GREEN}✓${RESET} [${timestamp}] Triaged #${issue.number} "${issue.title}" → ${assignedMember.name} (${reason})`);
} catch (e) {
console.error(`${RED}✗${RESET} [${timestamp}] Failed to label #${issue.number}: ${e.message}`);
}
}
}
// Assign @copilot to unassigned copilot issues
for (const issue of unassignedCopilot) {
try {
execSync(
`gh issue edit ${issue.number} --add-assignee copilot-swe-agent`,
{ stdio: 'pipe' }
);
console.log(`${GREEN}✓${RESET} [${timestamp}] Assigned @copilot to #${issue.number} "${issue.title}"`);
} catch (e) {
console.error(`${RED}✗${RESET} [${timestamp}] Failed to assign @copilot to #${issue.number}: ${e.message}`);
}
}
} catch (e) {
console.error(`${RED}✗${RESET} [${timestamp}] Check failed: ${e.message}`);
}
}
// Run immediately, then on interval
runCheck();
setInterval(runCheck, intervalMin * 60 * 1000);
// Handle Ctrl+C gracefully
process.on('SIGINT', () => {
console.log(`\n${DIM}🔄 Ralph — Watch stopped${RESET}`);
process.exit(0);
});
// Prevent fall-through to init/upgrade logic
return;
}
// Scrub email addresses from Squad state files
function scrubEmailsFromDirectory(dirPath) {
const EMAIL_PATTERN = /([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})/g;
const NAME_WITH_EMAIL_PATTERN = /([a-zA-Z0-9_-]+)\s*\(([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})\)/g;
const scrubbedFiles = [];
const filesToScrub = [
'team.md',
'decisions.md',
'routing.md',
'ceremonies.md'
];
// Scrub root-level files
for (const file of filesToScrub) {
const filePath = path.join(dirPath, file);
if (fs.existsSync(filePath)) {
try {
let content = fs.readFileSync(filePath, 'utf8');
let modified = false;
// Replace "name (email)" → "name"
const beforeNameEmail = content;
content = content.replace(NAME_WITH_EMAIL_PATTERN, '$1');
if (content !== beforeNameEmail) modified = true;
// Replace bare emails in identity contexts (but preserve in URLs and code examples)
const lines = content.split('\n');
const scrubbed = lines.map(line => {
// Skip lines that look like URLs, code blocks, or examples
if (line.includes('http://') || line.includes('https://') ||
line.includes('```') || line.includes('example.com') ||
line.trim().startsWith('//') || line.trim().startsWith('#')) {
return line;
}
// Scrub emails from identity/attribution contexts
const before = line;
const after = line.replace(EMAIL_PATTERN, '[email scrubbed]');
if (before !== after) modified = true;
return after;
});
if (modified) {
fs.writeFileSync(filePath, scrubbed.join('\n'));
scrubbedFiles.push(path.relative(dirPath, filePath));
}
} catch (err) {
console.error(`${RED}✗${RESET} Failed to scrub ${file}: ${err.message}`);
}
}
}
// Scrub agent history files
const agentsDir = path.join(dirPath, 'agents');
if (fs.existsSync(agentsDir)) {
try {
for (const agentName of fs.readdirSync(agentsDir)) {
const historyPath = path.join(agentsDir, agentName, 'history.md');
if (fs.existsSync(historyPath)) {
let content = fs.readFileSync(historyPath, 'utf8');
let modified = false;
// Replace "name (email)" → "name"
const beforeNameEmail = content;
content = content.replace(NAME_WITH_EMAIL_PATTERN, '$1');
if (content !== beforeNameEmail) modified = true;
// Scrub bare emails carefully
const lines = content.split('\n');
const scrubbed = lines.map(line => {
// Skip URLs, code, examples
if (line.includes('http://') || line.includes('https://') ||
line.includes('```') || line.includes('example.com') ||
line.trim().startsWith('//') || line.trim().startsWith('#')) {
return line;
}
const before = line;
const after = line.replace(EMAIL_PATTERN, '[email scrubbed]');
if (before !== after) modified = true;
return after;
});
if (modified) {
fs.writeFileSync(historyPath, scrubbed.join('\n'));
scrubbedFiles.push(path.relative(dirPath, historyPath));
}
}
}
} catch (err) {
console.error(`${RED}✗${RESET} Failed to scrub agent histories: ${err.message}`);
}
}
// Scrub log files
const logDir = path.join(dirPath, 'log');
if (fs.existsSync(logDir)) {
try {
const logFiles = fs.readdirSync(logDir).filter(f => f.endsWith('.md') || f.endsWith('.txt') || f.endsWith('.log'));
for (const file of logFiles) {
const filePath = path.join(logDir, file);
let content = fs.readFileSync(filePath, 'utf8');
const before = content;
content = content.replace(NAME_WITH_EMAIL_PATTERN, '$1');
content = content.replace(EMAIL_PATTERN, '[email scrubbed]');
if (content !== before) {
fs.writeFileSync(filePath, content);
scrubbedFiles.push(path.relative(dirPath, filePath));
}
}
} catch (err) {
console.error(`${RED}✗${RESET} Failed to scrub log files: ${err.message}`);
}
}
return scrubbedFiles;
}
// Replace legacy .ai-team/ path references inside .md and .json files
function replaceAiTeamReferences(dirPath) {
const updatedFiles = [];
const replacements = [
[/\.ai-team-templates\//g, '.squad/templates/'],
[/\.ai-team\//g, '.squad/']
];
function walk(dir) {
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) {
walk(full);
} else if (entry.isFile() && (entry.name.endsWith('.md') || entry.name.endsWith('.json'))) {
try {
let content = fs.readFileSync(full, 'utf8');
const original = content;
for (const [pattern, replacement] of replacements) {
content = content.replace(pattern, replacement);
}
if (content !== original) {
fs.writeFileSync(full, content);
updatedFiles.push(path.relative(dirPath, full));
}
} catch (err) {
// skip unreadable files
}
}
}
}
walk(dirPath);
return updatedFiles;
}
// Detect project type by checking for marker files in the target directory
function detectProjectType(dir) {
if (fs.existsSync(path.join(dir, 'package.json'))) return 'npm';
if (fs.existsSync(path.join(dir, 'go.mod'))) return 'go';
if (fs.existsSync(path.join(dir, 'requirements.txt')) ||
fs.existsSync(path.join(dir, 'pyproject.toml'))) return 'python';
if (fs.existsSync(path.join(dir, 'pom.xml')) ||
fs.existsSync(path.join(dir, 'build.gradle')) ||
fs.existsSync(path.join(dir, 'build.gradle.kts'))) return 'java';
try {
const entries = fs.readdirSync(dir);
if (entries.some(e => e.endsWith('.csproj') || e.endsWith('.sln') || e.endsWith('.slnx') || e.endsWith('.fsproj') || e.endsWith('.vbproj'))) return 'dotnet';
} catch { }
return 'unknown';
}
// Workflows that contain Node.js/npm-specific commands and need project-type adaptation
const PROJECT_TYPE_SENSITIVE_WORKFLOWS = new Set([
'squad-ci.yml',
'squad-release.yml',
'squad-preview.yml',
'squad-insider-release.yml',
'squad-docs.yml',
]);
// Generate a stub workflow for non-npm projects so no broken npm commands run
function generateProjectWorkflowStub(workflowFile, projectType) {
const typeLabel = projectType === 'unknown'
? 'Project type was not detected'
: projectType + ' project';
const todoBuildCmd = projectType === 'unknown'
? '# TODO: Project type was not detected — add your build/test commands here'
: '# TODO: Add your ' + projectType + ' build/test commands here';
const buildHints = [
' # Go: go test ./...',
' # Python: pip install -r requirements.txt && pytest',
' # .NET: dotnet test',
' # Java (Maven): mvn test',
' # Java (Gradle): ./gradlew test',
].join('\n');
if (workflowFile === 'squad-ci.yml') {
return 'name: Squad CI\n' +
'# ' + typeLabel + ' — configure build/test commands below\n\n' +
'on:\n' +
' pull_request:\n' +
' branches: [dev, preview, main, insider]\n' +
' types: [opened, synchronize, reopened]\n' +
' push:\n' +
' branches: [dev, insider]\n\n' +
'permissions:\n' +
' contents: read\n\n' +
'jobs:\n' +
' test:\n' +
' runs-on: ubuntu-latest\n' +
' steps:\n' +
' - uses: actions/checkout@v4\n\n' +
' - name: Build and test\n' +
' run: |\n' +
' ' + todoBuildCmd + '\n' +
buildHints + '\n' +
' echo "No build commands configured — update squad-ci.yml"\n';
}
if (workflowFile === 'squad-release.yml') {
return 'name: Squad Release\n' +
'# ' + typeLabel + ' — configure build, test, and release commands below\n\n' +
'on:\n' +
' push:\n' +
' branches: [main]\n\n' +
'permissions:\n' +
' contents: write\n\n' +
'jobs:\n' +
' release:\n' +
' runs-on: ubuntu-latest\n' +
' steps:\n' +
' - uses: actions/checkout@v4\n' +
' with:\n' +
' fetch-depth: 0\n\n' +
' - name: Build and test\n' +
' run: |\n' +
' ' + todoBuildCmd + '\n' +
buildHints + '\n' +
' echo "No build commands configured — update squad-release.yml"\n\n' +
' - name: Create release\n' +
' env:\n' +
' GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n' +
' run: |\n' +
' # TODO: Add your release commands here (e.g., git tag, gh release create)\n' +
' echo "No release commands configured — update squad-release.yml"\n';
}
if (workflowFile === 'squad-preview.yml') {
return 'name: Squad Preview Validation\n' +
'# ' + typeLabel + ' — configure build, test, and validation commands below\n\n' +
'on:\n' +
' push:\n' +
' branches: [preview]\n\n' +
'permissions:\n' +
' contents: read\n\n' +
'jobs:\n' +
' validate:\n' +
' runs-on: ubuntu-latest\n' +
' steps:\n' +
' - uses: actions/checkout@v4\n\n' +
' - name: Build and test\n' +
' run: |\n' +
' ' + todoBuildCmd + '\n' +
buildHints + '\n' +
' echo "No build commands configured — update squad-preview.yml"\n\n' +
' - name: Validate\n' +
' run: |\n' +
' # TODO: Add pre-release validation commands here\n' +
' echo "No validation commands configured — update squad-preview.yml"\n';
}
if (workflowFile === 'squad-insider-release.yml') {
return 'name: Squad Insider Release\n' +
'# ' + typeLabel + ' — configure build, test, and insider release commands below\n\n' +
'on:\n' +
' push:\n' +
' branches: [insider]\n\n' +
'permissions:\n' +
' contents: write\n\n' +
'jobs:\n' +
' release:\n' +
' runs-on: ubuntu-latest\n' +
' steps:\n' +
' - uses: actions/checkout@v4\n' +
' with:\n' +
' fetch-depth: 0\n\n' +
' - name: Build and test\n' +
' run: |\n' +
' ' + todoBuildCmd + '\n' +
buildHints + '\n' +
' echo "No build commands configured — update squad-insider-release.yml"\n\n' +
' - name: Create insider release\n' +
' env:\n' +
' GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n' +
' run: |\n' +
' # TODO: Add your insider/pre-release commands here\n' +
' echo "No release commands configured — update squad-insider-release.yml"\n';
}
if (workflowFile === 'squad-docs.yml') {
return 'name: Squad Docs — Build & Deploy\n' +
'# ' + typeLabel + ' — configure documentation build commands below\n\n' +
'on:\n' +
' workflow_dispatch:\n' +
' push:\n' +
' branches: [preview]\n' +
' paths:\n' +
" - 'docs/**'\n" +
" - '.github/workflows/squad-docs.yml'\n\n" +
'permissions:\n' +
' contents: read\n' +
' pages: write\n' +
' id-token: write\n\n' +
'jobs:\n' +
' build:\n' +
' runs-on: ubuntu-latest\n' +
' steps:\n' +
' - uses: actions/checkout@v4\n\n' +
' - name: Build docs\n' +
' run: |\n' +
' # TODO: Add your documentation build commands here\n' +
' # This workflow is optional — remove or customize it for your project\n' +
' echo "No docs build commands configured — update or remove squad-docs.yml"\n';
}
return null;
}
// Write a workflow file: verbatim copy for npm projects, stub for others
function writeWorkflowFile(file, srcPath, destPath, projectType) {
if (projectType !== 'npm' && PROJECT_TYPE_SENSITIVE_WORKFLOWS.has(file)) {
const stub = generateProjectWorkflowStub(file, projectType);
if (stub) {
fs.writeFileSync(destPath, stub);
return;
}
}
fs.copyFileSync(srcPath, destPath);
}
// --- Email scrubbing subcommand ---
if (cmd === 'scrub-emails') {
const targetDir = process.argv[3] || path.join(dest, '.ai-team');
if (!fs.existsSync(targetDir)) {
fatal(`Directory not found: ${targetDir}`);
}
console.log(`${DIM}Scanning ${path.relative(dest, targetDir)} for email addresses...${RESET}`);
const scrubbedFiles = scrubEmailsFromDirectory(targetDir);
if (scrubbedFiles.length === 0) {
console.log(`${GREEN}✓${RESET} No email addresses found — all clean`);
} else {
console.log(`${GREEN}✓${RESET} Scrubbed email addresses from ${scrubbedFiles.length} file(s):`);
for (const file of scrubbedFiles) {
console.log(` ${BOLD}${file}${RESET}`);
}
console.log();
console.log(`${YELLOW}⚠️ Note: Git history may still contain email addresses${RESET}`);
console.log(`${YELLOW} For a complete scrub, use git-filter-repo:${RESET}`);
console.log(`${YELLOW} https://github.com/newren/git-filter-repo${RESET}`);
}
console.log();
process.exit(0);
}
// --- Copilot subcommand ---
if (cmd === 'copilot') {
const teamMd = path.join(dest, '.ai-team', 'team.md');
if (!fs.existsSync(teamMd)) {
fatal('No squad found — run init first, then add the copilot agent.');
}
const isOff = process.argv.includes('--off');
const autoAssign = process.argv.includes('--auto-assign');
let content = fs.readFileSync(teamMd, 'utf8');
const hasCopilot = content.includes('🤖 Coding Agent');
if (isOff) {
if (!hasCopilot) {
console.log(`${DIM}Copilot coding agent is not on the team — nothing to remove${RESET}`);
process.exit(0);
}
// Remove the Coding Agent section
content = content.replace(/\n## Coding Agent\n[\s\S]*?(?=\n## |\n*$)/, '');
fs.writeFileSync(teamMd, content);
console.log(`${GREEN}✓${RESET} Removed @copilot from the team roster`);
// Remove copilot-instructions.md
const instructionsDest = path.join(dest, '.github', 'copilot-instructions.md');
if (fs.existsSync(instructionsDest)) {
fs.unlinkSync(instructionsDest);
console.log(`${GREEN}✓${RESET} Removed .github/copilot-instructions.md`);
}
process.exit(0);
}
// Adding copilot
if (hasCopilot) {
// Update auto-assign if requested
if (autoAssign) {
content = content.replace('<!-- copilot-auto-assign: false -->', '<!-- copilot-auto-assign: true -->');
fs.writeFileSync(teamMd, content);
console.log(`${GREEN}✓${RESET} Enabled @copilot auto-assign`);
} else {
console.log(`${DIM}@copilot is already on the team${RESET}`);
}
process.exit(0);
}
// Add Coding Agent section before Project Context
const autoAssignValue = autoAssign ? 'true' : 'false';
const copilotSection = `
## Coding Agent
<!-- copilot-auto-assign: ${autoAssignValue} -->
| Name | Role | Charter | Status |
|------|------|---------|--------|
| @copilot | Coding Agent | — | 🤖 Coding Agent |
### Capabilities
**🟢 Good fit — auto-route when enabled:**
- Bug fixes with clear reproduction steps
- Test coverage (adding missing tests, fixing flaky tests)
- Lint/format fixes and code style cleanup
- Dependency updates and version bumps
- Small isolated features with clear specs
- Boilerplate/scaffolding generation
- Documentation fixes and README updates
**🟡 Needs review — route to @copilot but flag for squad member PR review:**
- Medium features with clear specs and acceptance criteria
- Refactoring with existing test coverage
- API endpoint additions following established patterns
- Migration scripts with well-defined schemas
**🔴 Not suitable — route to squad member instead:**
- Architecture decisions and system design
- Multi-system integration requiring coordination
- Ambiguous requirements needing clarification
- Security-critical changes (auth, encryption, access control)
- Performance-critical paths requiring benchmarking
- Changes requiring cross-team discussion
`;
// Insert before "## Project Context" if it exists, otherwise append
if (content.includes('## Project Context')) {
content = content.replace('## Project Context', copilotSection + '## Project Context');
} else {
content = content.trimEnd() + '\n' + copilotSection;
}
fs.writeFileSync(teamMd, content);
console.log(`${GREEN}✓${RESET} Added @copilot (Coding Agent) to team roster`);
if (autoAssign) {
console.log(`${GREEN}✓${RESET} Auto-assign enabled — squad-labeled issues will be assigned to @copilot`);
}
// Copy copilot-instructions.md
const instructionsSrc = path.join(root, 'templates', 'copilot-instructions.md');
const instructionsDest = path.join(dest, '.github', 'copilot-instructions.md');
if (fs.existsSync(instructionsSrc)) {
fs.mkdirSync(path.dirname(instructionsDest), { recursive: true });
fs.copyFileSync(instructionsSrc, instructionsDest);
console.log(`${GREEN}✓${RESET} .github/copilot-instructions.md`);
}
console.log();
console.log(`${BOLD}@copilot is on the team.${RESET}`);
console.log(`The coding agent will pick up issues matching its capability profile.`);
if (!autoAssign) {
console.log(`Run with ${BOLD}--auto-assign${RESET} to auto-assign @copilot on squad-labeled issues.`);
}
console.log();
console.log(`${BOLD}Required:${RESET} Add a classic PAT (repo scope) as a repo secret for auto-assignment:`);
console.log(` 1. Create token: ${DIM}https://github.com/settings/tokens/new${RESET}`);
console.log(` 2. Set secret: ${DIM}gh secret set COPILOT_ASSIGN_TOKEN${RESET}`);
console.log();
process.exit(0);
}
// --- Plugin marketplace subcommand ---
if (cmd === 'plugin') {
const subCmd = process.argv[3];
const action = process.argv[4];
if (subCmd !== 'marketplace' || !action) {
fatal('Usage: squad plugin marketplace add|remove|list|browse');
}
const squadDirInfo = detectSquadDir(dest);
const pluginsDir = path.join(squadDirInfo.path, 'plugins');
const marketplacesFile = path.join(pluginsDir, 'marketplaces.json');
function readMarketplaces() {
if (!fs.existsSync(marketplacesFile)) return { marketplaces: [] };
try {
return JSON.parse(fs.readFileSync(marketplacesFile, 'utf8'));
} catch {
return { marketplaces: [] };
}
}
function writeMarketplaces(data) {
fs.mkdirSync(pluginsDir, { recursive: true });
fs.writeFileSync(marketplacesFile, JSON.stringify(data, null, 2) + '\n');
}
if (action === 'add') {
const source = process.argv[5];
if (!source || !source.includes('/')) {
fatal('Usage: squad plugin marketplace add <owner/repo>');
}
const data = readMarketplaces();
const name = source.split('/').pop();
if (data.marketplaces.some(m => m.source === source)) {
console.log(`${DIM}${source} is already registered${RESET}`);
process.exit(0);
}
data.marketplaces.push({
name,
source,
added_at: new Date().toISOString()
});
writeMarketplaces(data);
console.log(`${GREEN}✓${RESET} Registered marketplace: ${BOLD}${name}${RESET} (${source})`);
process.exit(0);
}
if (action === 'remove') {
const name = process.argv[5];
if (!name) {
fatal('Usage: squad plugin marketplace remove <name>');
}
const data = readMarketplaces();
const before = data.marketplaces.length;
data.marketplaces = data.marketplaces.filter(m => m.name !== name);
if (data.marketplaces.length === before) {
fatal(`Marketplace "${name}" not found`);
}
writeMarketplaces(data);
console.log(`${GREEN}✓${RESET} Removed marketplace: ${BOLD}${name}${RESET}`);
process.exit(0);
}
if (action === 'list') {
const data = readMarketplaces();
if (data.marketplaces.length === 0) {
console.log(`${DIM}No marketplaces registered${RESET}`);
console.log(`\nAdd one with: ${BOLD}squad plugin marketplace add <owner/repo>${RESET}`);
process.exit(0);
}
console.log(`\n${BOLD}Registered marketplaces:${RESET}\n`);
for (const m of data.marketplaces) {
const date = m.added_at ? ` ${DIM}(added ${m.added_at.split('T')[0]})${RESET}` : '';
console.log(` ${BOLD}${m.name}${RESET} → ${m.source}${date}`);
}
console.log();
process.exit(0);
}
if (action === 'browse') {
const name = process.argv[5];
if (!name) {
fatal('Usage: squad plugin marketplace browse <name>');
}
const data = readMarketplaces();
const marketplace = data.marketplaces.find(m => m.name === name);
if (!marketplace) {
fatal(`Marketplace "${name}" not found. Run "squad plugin marketplace list" to see registered marketplaces.`);
}
// Browse the marketplace repo for plugins using gh CLI
const { execSync } = require('child_process');
let entries;
try {
const output = execSync(
`gh api repos/${marketplace.source}/contents --jq "[.[] | select(.type == \\"dir\\") | .name]"`,
{ encoding: 'utf8', timeout: 15000 }
).trim();
entries = JSON.parse(output);
} catch (err) {
fatal(`Could not browse ${marketplace.source} — is the GitHub CLI installed and authenticated?\n ${err.message}`);
}
if (!entries || entries.length === 0) {
console.log(`${DIM}No plugins found in ${marketplace.source}${RESET}`);
process.exit(0);