gitpadi 2.0.7 → 2.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/.gitlab/duo/chat-rules.md +40 -0
  2. package/.gitlab/duo/mr-review-instructions.md +44 -0
  3. package/.gitlab-ci.yml +136 -0
  4. package/README.md +585 -57
  5. package/action.yml +21 -2
  6. package/dist/applicant-scorer.js +27 -105
  7. package/dist/cli.js +1045 -34
  8. package/dist/commands/apply-for-issue.js +396 -0
  9. package/dist/commands/bounty-hunter.js +441 -0
  10. package/dist/commands/contribute.js +245 -51
  11. package/dist/commands/drips.js +351 -0
  12. package/dist/commands/gitlab-issues.js +87 -0
  13. package/dist/commands/gitlab-mrs.js +163 -0
  14. package/dist/commands/gitlab-pipelines.js +95 -0
  15. package/dist/commands/prs.js +3 -3
  16. package/dist/core/github.js +24 -0
  17. package/dist/core/gitlab.js +233 -0
  18. package/dist/gitlab-agents/ci-recovery-agent.js +173 -0
  19. package/dist/gitlab-agents/contributor-scoring-agent.js +159 -0
  20. package/dist/gitlab-agents/grade-assignment-agent.js +252 -0
  21. package/dist/gitlab-agents/mr-review-agent.js +200 -0
  22. package/dist/gitlab-agents/reminder-agent.js +164 -0
  23. package/dist/grade-assignment.js +262 -0
  24. package/dist/remind-contributors.js +127 -0
  25. package/dist/review-and-merge.js +125 -0
  26. package/examples/gitpadi.yml +152 -0
  27. package/package.json +20 -4
  28. package/src/applicant-scorer.ts +33 -141
  29. package/src/cli.ts +1078 -34
  30. package/src/commands/apply-for-issue.ts +452 -0
  31. package/src/commands/bounty-hunter.ts +529 -0
  32. package/src/commands/contribute.ts +264 -50
  33. package/src/commands/drips.ts +408 -0
  34. package/src/commands/gitlab-issues.ts +87 -0
  35. package/src/commands/gitlab-mrs.ts +185 -0
  36. package/src/commands/gitlab-pipelines.ts +104 -0
  37. package/src/commands/prs.ts +3 -3
  38. package/src/core/github.ts +24 -0
  39. package/src/core/gitlab.ts +397 -0
  40. package/src/gitlab-agents/ci-recovery-agent.ts +201 -0
  41. package/src/gitlab-agents/contributor-scoring-agent.ts +196 -0
  42. package/src/gitlab-agents/grade-assignment-agent.ts +275 -0
  43. package/src/gitlab-agents/mr-review-agent.ts +231 -0
  44. package/src/gitlab-agents/reminder-agent.ts +203 -0
  45. package/src/grade-assignment.ts +283 -0
  46. package/src/remind-contributors.ts +159 -0
  47. package/src/review-and-merge.ts +143 -0
package/src/cli.ts CHANGED
@@ -10,12 +10,17 @@ import inquirer from 'inquirer';
10
10
  import gradient from 'gradient-string';
11
11
  import figlet from 'figlet';
12
12
  import os from 'node:os';
13
- import { execSync } from 'child_process';
13
+ import { execFileSync } from 'child_process';
14
14
 
15
15
  import boxen from 'boxen';
16
16
  import { createSpinner } from 'nanospinner';
17
17
  import { Octokit } from '@octokit/rest';
18
18
  import { initGitHub, setRepo, getOwner, getRepo, getOctokit, loadConfig, saveConfig, getToken, getAuthenticatedUser, getRepoPermissions } from './core/github.js';
19
+ import {
20
+ initGitLab, getGitLabToken, getNamespace, getProject, getFullProject,
21
+ saveGitLabConfig, savePlatformPreference, loadPlatformPreference,
22
+ getAuthenticatedGitLabUser, getGitLabProject, setGitLabProject,
23
+ } from './core/gitlab.js';
19
24
 
20
25
  import * as issues from './commands/issues.js';
21
26
  import * as prs from './commands/prs.js';
@@ -23,9 +28,16 @@ import * as repos from './commands/repos.js';
23
28
  import * as contributors from './commands/contributors.js';
24
29
  import * as releases from './commands/releases.js';
25
30
  import * as contribute from './commands/contribute.js';
26
-
27
- const VERSION = '2.0.0';
31
+ import * as applyForIssue from './commands/apply-for-issue.js';
32
+ import { runBountyHunter } from './commands/bounty-hunter.js';
33
+ import { dripsMenu } from './commands/drips.js';
34
+ import * as gitlabIssues from './commands/gitlab-issues.js';
35
+ import * as gitlabMRs from './commands/gitlab-mrs.js';
36
+ import * as gitlabPipelines from './commands/gitlab-pipelines.js';
37
+
38
+ const VERSION = '2.1.2';
28
39
  let targetConfirmed = false;
40
+ let gitlabProjectConfirmed = false;
29
41
 
30
42
  // ── Styling ────────────────────────────────────────────────────────────
31
43
  const cyber = gradient(['#ff00ff', '#00ffff', '#ff00ff']);
@@ -115,7 +127,7 @@ async function bootSequence() {
115
127
  const bootSteps = [
116
128
  '▸ Initializing GitPadi engine',
117
129
  '▸ Loading command modules',
118
- '▸ Establishing GitHub connection',
130
+ '▸ Connecting to GitHub & GitLab',
119
131
  '▸ Systems online',
120
132
  ];
121
133
 
@@ -150,6 +162,19 @@ async function ensureAuthenticated() {
150
162
 
151
163
  console.log(neon(' ⚡ Authentication — let\'s connect you to GitHub.\n'));
152
164
 
165
+ console.log(dim(' ┌─ How to get your GitHub Token ──────────────────────────────┐'));
166
+ console.log(dim(' │'));
167
+ console.log(dim(' │ 1. Open: ') + cyan('https://github.com/settings/tokens'));
168
+ console.log(dim(' │ 2. Click ') + bold('"Generate new token (classic)"'));
169
+ console.log(dim(' │ 3. Give it a name (e.g. "gitpadi")'));
170
+ console.log(dim(' │ 4. Select scopes: ') + yellow('repo') + dim(' (and ') + yellow('read:org') + dim(' for org repos)'));
171
+ console.log(dim(' │ 5. Click "Generate token" and copy it'));
172
+ console.log(dim(' │'));
173
+ console.log(dim(' │ The token will look like: ') + dim('ghp_xxxxxxxxxxxxxxxxxxxx'));
174
+ console.log(dim(' │'));
175
+ console.log(dim(' └─────────────────────────────────────────────────────────────┘'));
176
+ console.log('');
177
+
153
178
  const { t } = await inquirer.prompt([{
154
179
  type: 'password',
155
180
  name: 't',
@@ -288,34 +313,673 @@ async function ensureTargetRepo(force = false) {
288
313
  console.log(green(`\n ✅ Locked in → ${cyan(`${targetOwner}/${repo}`)}\n`));
289
314
  }
290
315
 
316
+ // ── GitLab Authentication ───────────────────────────────────────────────
317
+ async function ensureGitLabAuthenticated() {
318
+ initGitLab();
319
+ let token = getGitLabToken();
320
+
321
+ if (token) {
322
+ try {
323
+ await getAuthenticatedGitLabUser();
324
+ return; // token valid
325
+ } catch {
326
+ console.log(red(' ❌ Saved GitLab session invalid. Re-authenticating...'));
327
+ token = '';
328
+ }
329
+ }
330
+
331
+ console.log(neon('\n ⚡ GitLab Authentication — connect your account.\n'));
332
+
333
+ console.log(dim(' ┌─ How to get your GitLab Personal Access Token ──────────────┐'));
334
+ console.log(dim(' │'));
335
+ console.log(dim(' │ 1. Open: ') + cyan('https://gitlab.com/-/user_settings/personal_access_tokens'));
336
+ console.log(dim(' │ 2. Click ') + bold('"Add new token"'));
337
+ console.log(dim(' │ 3. Give it a name (e.g. "gitpadi") and set an expiry date'));
338
+ console.log(dim(' │ 4. Select scopes: ') + yellow('api') + dim(' (covers read/write access)'));
339
+ console.log(dim(' │ 5. Click "Create personal access token" and copy it'));
340
+ console.log(dim(' │'));
341
+ console.log(dim(' │ The token will look like: ') + dim('glpat-xxxxxxxxxxxxxxxxxxxx'));
342
+ console.log(dim(' │ For self-hosted GitLab, use your own host in the next step.'));
343
+ console.log(dim(' │'));
344
+ console.log(dim(' └─────────────────────────────────────────────────────────────┘'));
345
+ console.log('');
346
+
347
+ const { host } = await inquirer.prompt([{
348
+ type: 'input',
349
+ name: 'host',
350
+ message: cyan('🌐 GitLab host:'),
351
+ default: 'https://gitlab.com',
352
+ }]);
353
+
354
+ const { t } = await inquirer.prompt([{
355
+ type: 'password',
356
+ name: 't',
357
+ message: magenta('🔑 GitLab Personal Access Token') + dim(' (glpat-xxx):'),
358
+ mask: '•',
359
+ validate: async (v: string) => {
360
+ if (!v.startsWith('glpat-') && !v.startsWith('gl-')) {
361
+ return 'Token should start with glpat-';
362
+ }
363
+ const spinner = createSpinner(dim('Validating token...')).start();
364
+ try {
365
+ // Temp init to validate
366
+ const tmpRes = await fetch(`${host.replace(/\/$/, '')}/api/v4/user`, {
367
+ headers: { 'PRIVATE-TOKEN': v },
368
+ });
369
+ if (!tmpRes.ok) throw new Error('Invalid');
370
+ spinner.success({ text: green('Token valid!') });
371
+ return true;
372
+ } catch {
373
+ spinner.error({ text: red('Invalid token — GitLab rejected it.') });
374
+ return 'Invalid token';
375
+ }
376
+ },
377
+ }]);
378
+
379
+ saveGitLabConfig(t, host, '', '');
380
+ initGitLab(t, '', '', host);
381
+ const user = await getAuthenticatedGitLabUser();
382
+ console.log(green(`\n ✅ Authenticated as @${user.username}\n`));
383
+ }
384
+
385
+ /**
386
+ * Prompts user to select a GitLab project (namespace/project)
387
+ */
388
+ async function ensureGitLabProject(force = false) {
389
+ let ns = getNamespace();
390
+ let proj = getProject();
391
+
392
+ if (!force && ns && proj) {
393
+ if (gitlabProjectConfirmed) return;
394
+ const { confirm } = await inquirer.prompt([{
395
+ type: 'confirm',
396
+ name: 'confirm',
397
+ message: cyan('🎯 Targeting ') + bold(`${ns}/${proj}`) + cyan('. Correct?'),
398
+ default: true,
399
+ }]);
400
+ if (confirm) { gitlabProjectConfirmed = true; return; }
401
+ }
402
+
403
+ console.log(neon('\n 📦 GitLab Project — which project are we working on?\n'));
404
+
405
+ const user = await getAuthenticatedGitLabUser();
406
+
407
+ const { targetNs } = await inquirer.prompt([{
408
+ type: 'input',
409
+ name: 'targetNs',
410
+ message: cyan('👤 Namespace (user or group):'),
411
+ default: ns || user.username,
412
+ validate: (v: string) => v.length > 0 || 'Required',
413
+ }]);
414
+
415
+ const { targetProj } = await inquirer.prompt([{
416
+ type: 'input',
417
+ name: 'targetProj',
418
+ message: cyan('📦 Project path:'),
419
+ default: proj || '',
420
+ validate: (v: string) => v.length > 0 || 'Required',
421
+ }]);
422
+
423
+ // Verify project exists
424
+ const spin = createSpinner(dim(`Verifying ${targetNs}/${targetProj}...`)).start();
425
+ try {
426
+ const project = await getGitLabProject(targetNs, targetProj);
427
+ spin.success({ text: green(`Found: ${project.path_with_namespace}`) });
428
+ } catch {
429
+ spin.warn({ text: yellow('Could not verify project — proceeding anyway.') });
430
+ }
431
+
432
+ setGitLabProject(targetNs, targetProj);
433
+ gitlabProjectConfirmed = true;
434
+ console.log(green(`\n ✅ Locked in → ${cyan(`${targetNs}/${targetProj}`)}\n`));
435
+ }
436
+
437
+ // ── GitLab Maintainer Menu ─────────────────────────────────────────────
438
+ async function gitlabMaintainerMenu() {
439
+ while (true) {
440
+ line('═');
441
+ console.log(gradient(['#FC6D26', '#E24329'])(' 🦊 GITPADI GITLAB MAINTAINER'));
442
+ console.log(dim(' Manage issues, merge requests, and pipelines'));
443
+ line('═');
444
+ console.log('');
445
+
446
+ const { category } = await inquirer.prompt([{
447
+ type: 'list',
448
+ name: 'category',
449
+ message: bold('Select operation:'),
450
+ choices: [
451
+ { name: `${magenta('📋')} ${bold('Issues')} ${dim('— create, close, comment')}`, value: 'issues' },
452
+ { name: `${cyan('🔀')} ${bold('Merge Requests')} ${dim('— list, merge, review, diff')}`, value: 'mrs' },
453
+ { name: `${yellow('🔧')} ${bold('Pipelines')} ${dim('— list, view jobs, read logs')}`, value: 'pipelines' },
454
+ new inquirer.Separator(dim(' ─────────────────────────────')),
455
+ { name: `${dim('⚙️')} ${dim('Switch Project')}`, value: 'switch' },
456
+ { name: `${dim('⬅')} ${dim('Back to Mode Selector')}`, value: 'back' },
457
+ ],
458
+ loop: false,
459
+ }]);
460
+
461
+ if (category === 'back') break;
462
+
463
+ if (category === 'switch') {
464
+ await ensureGitLabProject(true);
465
+ continue;
466
+ }
467
+
468
+ if (category === 'issues') await safeMenu(gitlabIssueMenu);
469
+ else if (category === 'mrs') await safeMenu(gitlabMRMenu);
470
+ else if (category === 'pipelines') await safeMenu(gitlabPipelineMenu);
471
+
472
+ console.log('');
473
+ }
474
+ }
475
+
476
+ async function gitlabIssueMenu() {
477
+ const { action } = await inquirer.prompt([{
478
+ type: 'list', name: 'action', message: magenta('📋 Issue Operation:'),
479
+ choices: [
480
+ { name: ` ${dim('⬅ Back')}`, value: 'back' },
481
+ new inquirer.Separator(dim(' ─────────────────────────────')),
482
+ { name: ` ${green('▸')} List issues`, value: 'list' },
483
+ { name: ` ${green('▸')} Create issue`, value: 'create' },
484
+ { name: ` ${red('▸')} Close issue`, value: 'close' },
485
+ { name: ` ${green('▸')} Reopen issue`, value: 'reopen' },
486
+ { name: ` ${cyan('▸')} Comment on issue`, value: 'comment' },
487
+ ],
488
+ }]);
489
+
490
+ if (action === 'back') return;
491
+
492
+ if (action === 'list') {
493
+ const a = await ask([
494
+ { type: 'list', name: 'state', message: 'State:', choices: ['opened', 'closed', 'all'], default: 'opened' },
495
+ { type: 'input', name: 'limit', message: dim('Max results:'), default: '50' },
496
+ ]);
497
+ await gitlabIssues.listIssues({ state: a.state, limit: parseInt(a.limit) });
498
+ } else if (action === 'create') {
499
+ const a = await ask([
500
+ { type: 'input', name: 'title', message: yellow('Issue title'), validate: (v: string) => v.length > 0 || 'Required' },
501
+ { type: 'input', name: 'description', message: dim('Description (optional):'), default: '' },
502
+ { type: 'input', name: 'labels', message: dim('Labels (comma-separated):'), default: '' },
503
+ ]);
504
+ await gitlabIssues.createIssue({ title: a.title, description: a.description || undefined, labels: a.labels || undefined });
505
+ } else if (action === 'close' || action === 'reopen') {
506
+ const { n } = await ask([{ type: 'input', name: 'n', message: yellow('Issue #') + dim(' (q=back):') }]);
507
+ if (!n || isNaN(Number(n))) return;
508
+ if (action === 'close') await gitlabIssues.closeIssue(parseInt(n));
509
+ else await gitlabIssues.reopenIssue(parseInt(n));
510
+ } else if (action === 'comment') {
511
+ const a = await ask([
512
+ { type: 'input', name: 'n', message: yellow('Issue #') + dim(' (q=back):') },
513
+ { type: 'input', name: 'body', message: cyan('Comment:') },
514
+ ]);
515
+ if (!a.n || isNaN(Number(a.n))) return;
516
+ await gitlabIssues.commentOnIssue(parseInt(a.n), a.body);
517
+ }
518
+ }
519
+
520
+ async function gitlabMRMenu() {
521
+ const { action } = await inquirer.prompt([{
522
+ type: 'list', name: 'action', message: cyan('🔀 Merge Request Operation:'),
523
+ choices: [
524
+ { name: ` ${dim('⬅ Back')}`, value: 'back' },
525
+ new inquirer.Separator(dim(' ─────────────────────────────')),
526
+ { name: ` ${green('▸')} List merge requests`, value: 'list' },
527
+ { name: ` ${green('▸')} Merge MR ${dim('(checks pipeline first)')}`, value: 'merge' },
528
+ { name: ` ${yellow('▸')} Force merge ${dim('(skip pipeline)')}`, value: 'force-merge' },
529
+ { name: ` ${red('▸')} Close MR`, value: 'close' },
530
+ { name: ` ${yellow('▸')} Review MR`, value: 'review' },
531
+ { name: ` ${cyan('▸')} View diff`, value: 'diff' },
532
+ ],
533
+ }]);
534
+
535
+ if (action === 'back') return;
536
+
537
+ if (action === 'list') {
538
+ const a = await ask([
539
+ { type: 'list', name: 'state', message: 'State:', choices: ['opened', 'closed', 'merged', 'all'], default: 'opened' },
540
+ { type: 'input', name: 'limit', message: dim('Max results:'), default: '50' },
541
+ ]);
542
+ await gitlabMRs.listMRs({ state: a.state, limit: parseInt(a.limit) });
543
+ } else if (action === 'merge' || action === 'force-merge') {
544
+ const a = await ask([
545
+ { type: 'input', name: 'n', message: yellow('MR !') + dim('(q=back):') },
546
+ { type: 'confirm', name: 'squash', message: 'Squash commits?', default: true },
547
+ { type: 'confirm', name: 'confirm', message: action === 'force-merge' ? yellow('⚠️ Force merge (skip pipeline)?') : red('⚠️ Merge this MR?'), default: false },
548
+ ]);
549
+ if (a.confirm) await gitlabMRs.mergeMR(parseInt(a.n), { squash: a.squash, force: action === 'force-merge' });
550
+ } else {
551
+ const { n } = await ask([{ type: 'input', name: 'n', message: yellow('MR !') + dim('(q=back):') }]);
552
+ if (!n || isNaN(Number(n))) return;
553
+ if (action === 'close') await gitlabMRs.closeMR(parseInt(n));
554
+ else if (action === 'review') await gitlabMRs.reviewMR(parseInt(n));
555
+ else await gitlabMRs.diffMR(parseInt(n));
556
+ }
557
+ }
558
+
559
+ async function gitlabPipelineMenu() {
560
+ const { action } = await inquirer.prompt([{
561
+ type: 'list', name: 'action', message: yellow('🔧 Pipeline Operation:'),
562
+ choices: [
563
+ { name: ` ${dim('⬅ Back')}`, value: 'back' },
564
+ new inquirer.Separator(dim(' ─────────────────────────────')),
565
+ { name: ` ${green('▸')} List pipelines`, value: 'list' },
566
+ { name: ` ${cyan('▸')} View pipeline jobs`, value: 'jobs' },
567
+ { name: ` ${cyan('▸')} View job log`, value: 'log' },
568
+ ],
569
+ }]);
570
+
571
+ if (action === 'back') return;
572
+
573
+ if (action === 'list') {
574
+ const a = await ask([
575
+ { type: 'input', name: 'ref', message: dim('Branch/ref (blank for all):'), default: '' },
576
+ { type: 'input', name: 'limit', message: dim('Max results:'), default: '20' },
577
+ ]);
578
+ await gitlabPipelines.listPipelines({ ref: a.ref || undefined, limit: parseInt(a.limit) });
579
+ } else if (action === 'jobs') {
580
+ const { n } = await ask([{ type: 'input', name: 'n', message: yellow('Pipeline ID:') + dim(' (q=back):') }]);
581
+ if (!n || isNaN(Number(n))) return;
582
+ await gitlabPipelines.viewPipelineJobs(parseInt(n));
583
+ } else if (action === 'log') {
584
+ const { n } = await ask([{ type: 'input', name: 'n', message: yellow('Job ID:') + dim(' (q=back):') }]);
585
+ if (!n || isNaN(Number(n))) return;
586
+ await gitlabPipelines.viewJobLog(parseInt(n));
587
+ }
588
+ }
589
+
590
+ // ── Platform Selector ──────────────────────────────────────────────────
591
+ async function selectPlatform(): Promise<'github' | 'gitlab'> {
592
+ const saved = loadPlatformPreference();
593
+ if (saved) {
594
+ const { keepPlatform } = await inquirer.prompt([{
595
+ type: 'confirm',
596
+ name: 'keepPlatform',
597
+ message: `${dim('Last session:')} ${saved === 'github' ? cyan('GitHub') : gradient(['#FC6D26', '#E24329'])('GitLab')} — continue with this?`,
598
+ default: true,
599
+ }]);
600
+ if (keepPlatform) return saved;
601
+ }
602
+
603
+ const { platform } = await inquirer.prompt([{
604
+ type: 'list',
605
+ name: 'platform',
606
+ message: bold('Choose your platform:'),
607
+ choices: [
608
+ { name: `${cyan('🐙')} ${bold('GitHub')} ${dim('— github.com')}`, value: 'github' },
609
+ { name: `${gradient(['#FC6D26', '#E24329'])('🦊')} ${bold('GitLab')} ${dim('— gitlab.com or self-hosted')}`, value: 'gitlab' },
610
+ ],
611
+ loop: false,
612
+ }]);
613
+
614
+ savePlatformPreference(platform);
615
+ return platform;
616
+ }
617
+
291
618
  // ── Mode Selector ──────────────────────────────────────────────────────
292
619
  async function mainMenu() {
620
+ const platform = await selectPlatform();
621
+
622
+ // Authenticate for selected platform
623
+ if (platform === 'gitlab') {
624
+ await ensureGitLabAuthenticated();
625
+ }
626
+
293
627
  while (true) {
294
628
  line('═');
295
- console.log(cyber(' ⟨ GITPADI MODE SELECTOR '));
629
+ const platformLabel = platform === 'github'
630
+ ? cyan('GitHub')
631
+ : gradient(['#FC6D26', '#E24329'])('GitLab');
632
+ console.log(cyber(` ⟨ GITPADI MODE SELECTOR ⟩`) + dim(` [${platformLabel}]`));
296
633
  console.log(dim(' Select your workflow persona to continue'));
297
634
  line('═');
298
635
  console.log('');
299
636
 
300
- const { mode } = await inquirer.prompt([{
637
+ if (platform === 'github') {
638
+ const { mode } = await inquirer.prompt([{
639
+ type: 'list',
640
+ name: 'mode',
641
+ message: bold('Choose your path:'),
642
+ choices: [
643
+ { name: `${cyan('✨')} ${bold('Contributor Mode')} ${dim('— fork, clone, sync, submit PRs')}`, value: 'contributor' },
644
+ { name: `${magenta('🛠️')} ${bold('Maintainer Mode')} ${dim('— manage issues, PRs, contributors')}`, value: 'maintainer' },
645
+ { name: `${yellow('🏫')} ${bold('Organization/School')} ${dim('— assignments, grading, leaderboard')}`, value: 'org' },
646
+ { name: `${cyan('🌊')} ${bold('Drips Network')} ${dim('— apply for bounty issues on drips.network')}`, value: 'drips' },
647
+ new inquirer.Separator(dim(' ─────────────────────────────')),
648
+ { name: `${dim('🔄')} ${dim('Switch Platform')}`, value: 'switch' },
649
+ { name: `${dim('👋')} ${dim('Exit')}`, value: 'exit' },
650
+ ],
651
+ loop: false,
652
+ }]);
653
+
654
+ if (mode === 'exit') break;
655
+ if (mode === 'switch') { savePlatformPreference('gitlab'); return mainMenu(); }
656
+ if (mode === 'contributor') await safeMenu(contributorMenu);
657
+ else if (mode === 'maintainer') {
658
+ await ensureTargetRepo();
659
+ await safeMenu(maintainerMenu);
660
+ } else if (mode === 'org') {
661
+ await ensureTargetRepo();
662
+ await safeMenu(orgMenu);
663
+ } else if (mode === 'drips') {
664
+ await safeMenu(dripsMenu);
665
+ }
666
+ } else {
667
+ // GitLab mode
668
+ const { mode } = await inquirer.prompt([{
669
+ type: 'list',
670
+ name: 'mode',
671
+ message: bold('Choose your path:'),
672
+ choices: [
673
+ { name: `${gradient(['#FC6D26', '#E24329'])('🛠️')} ${bold('GitLab Maintainer')} ${dim('— issues, MRs, pipelines')}`, value: 'gl-maintainer' },
674
+ new inquirer.Separator(dim(' ─────────────────────────────')),
675
+ { name: `${dim('🔄')} ${dim('Switch Platform')}`, value: 'switch' },
676
+ { name: `${dim('👋')} ${dim('Exit')}`, value: 'exit' },
677
+ ],
678
+ loop: false,
679
+ }]);
680
+
681
+ if (mode === 'exit') break;
682
+ if (mode === 'switch') { savePlatformPreference('github'); return mainMenu(); }
683
+ if (mode === 'gl-maintainer') {
684
+ await ensureGitLabProject();
685
+ await safeMenu(gitlabMaintainerMenu);
686
+ }
687
+ }
688
+ }
689
+ }
690
+
691
+ // ── Organization / School Menu ─────────────────────────────────────────
692
+ async function orgMenu() {
693
+ while (true) {
694
+ line('═');
695
+ console.log(yellow(' 🏫 GITPADI ORGANIZATION / SCHOOL'));
696
+ console.log(dim(' Create assignments, grade PRs, track student performance'));
697
+ line('═');
698
+ console.log('');
699
+
700
+ const { action } = await inquirer.prompt([{
301
701
  type: 'list',
302
- name: 'mode',
303
- message: bold('Choose your path:'),
702
+ name: 'action',
703
+ message: bold('Select operation:'),
304
704
  choices: [
305
- { name: `${cyan('')} ${bold('Contributor Mode')} ${dim('— fork, clone, sync, submit PRs')}`, value: 'contributor' },
306
- { name: `${magenta('🛠️')} ${bold('Maintainer Mode')} ${dim('— manage issues, PRs, contributors')}`, value: 'maintainer' },
705
+ { name: `${yellow('📝')} ${bold('Create Assignment')} ${dim('— post a new assignment as an issue')}`, value: 'create' },
706
+ { name: `${green('📊')} ${bold('Grade a PR')} ${dim('— score a student submission')}`, value: 'grade' },
707
+ { name: `${cyan('🏆')} ${bold('Cohort Leaderboard')} ${dim('— rank all students by score')}`, value: 'leaderboard' },
307
708
  new inquirer.Separator(dim(' ─────────────────────────────')),
308
- { name: `${dim('👋')} ${dim('Exit')}`, value: 'exit' },
709
+ { name: `${dim('⚙️')} ${dim('Switch Repo')}`, value: 'switch' },
710
+ { name: `${dim('⬅')} ${dim('Back to Mode Selector')}`, value: 'back' },
309
711
  ],
310
712
  loop: false,
311
713
  }]);
312
714
 
313
- if (mode === 'contributor') await safeMenu(contributorMenu);
314
- else if (mode === 'maintainer') {
315
- await ensureTargetRepo();
316
- await safeMenu(maintainerMenu);
715
+ if (action === 'back') break;
716
+
717
+ if (action === 'switch') {
718
+ await ensureTargetRepo(true);
719
+ continue;
317
720
  }
318
- else break;
721
+
722
+ // ── Create Assignment ──────────────────────────────────────────
723
+ if (action === 'create') {
724
+ const answers = await ask([
725
+ { type: 'input', name: 'title', message: yellow('Assignment title:') },
726
+ { type: 'input', name: 'description', message: yellow('Description (what students should build):') },
727
+ { type: 'input', name: 'deadline', message: yellow('Deadline (e.g. "March 15, 2026"):'), default: '' },
728
+ { type: 'input', name: 'files', message: yellow('Expected files/folders (comma-separated):'), default: '' },
729
+ { type: 'input', name: 'labels', message: yellow('Labels (space-separated):'), default: 'assignment' },
730
+ ]);
731
+
732
+ if (!answers.title) continue;
733
+
734
+ const ora = (await import('ora')).default;
735
+ const spinner = ora('Creating assignment...').start();
736
+ try {
737
+ const octokit = getOctokit();
738
+ const owner = getOwner();
739
+ const repo = getRepo();
740
+
741
+ let body = `## 📝 ${answers.title}\n\n`;
742
+ body += `${answers.description}\n\n`;
743
+ if (answers.deadline) body += `**Deadline:** ${answers.deadline}\n\n`;
744
+ if (answers.files) body += `**Expected files:** ${answers.files}\n\n`;
745
+ body += `---\n\n`;
746
+ body += `### Submission Instructions\n\n`;
747
+ body += `1. Fork this repository\n`;
748
+ body += `2. Create a branch named \`assignment-<issue-number>\` (e.g. \`assignment-5\`)\n`;
749
+ body += `3. Complete the assignment\n`;
750
+ body += `4. Open a Pull Request with \`Fixes #<issue-number>\` in the description\n`;
751
+ body += `5. GitPadi will automatically grade your submission\n\n`;
752
+ body += `### Grading Criteria\n\n`;
753
+ body += `| Criteria | Points |\n|----------|--------|\n`;
754
+ body += `| CI Passing | 25 |\n`;
755
+ body += `| Assignment Relevance | 25 |\n`;
756
+ body += `| Test Coverage | 20 |\n`;
757
+ body += `| Code Quality | 15 |\n`;
758
+ body += `| Submission Format | 15 |\n`;
759
+ body += `| **Total** | **100** |\n\n`;
760
+ body += `**Pass threshold:** 40/100 (Grade C or above)\n`;
761
+
762
+ const labels = answers.labels.split(/\s+/).filter((l: string) => l);
763
+
764
+ const { data: issue } = await octokit.issues.create({
765
+ owner, repo,
766
+ title: `📝 ${answers.title}`,
767
+ body,
768
+ labels,
769
+ });
770
+
771
+ spinner.succeed(green(`Assignment created: #${issue.number} — ${issue.html_url}`));
772
+ } catch (e: any) {
773
+ spinner.fail(e.message);
774
+ }
775
+ }
776
+
777
+ // ── Grade a PR ─────────────────────────────────────────────────
778
+ else if (action === 'grade') {
779
+ const { prNum } = await ask([{ type: 'input', name: 'prNum', message: cyan('PR number to grade:') }]);
780
+ if (!prNum || isNaN(Number(prNum))) continue;
781
+
782
+ const ora = (await import('ora')).default;
783
+ const spinner = ora('Grading submission...').start();
784
+ try {
785
+ const octokit = getOctokit();
786
+ const owner = getOwner();
787
+ const repo = getRepo();
788
+ const prNumber = parseInt(prNum);
789
+
790
+ const { data: pr } = await octokit.pulls.get({ owner, repo, pull_number: prNumber });
791
+ const student = pr.user?.login || 'unknown';
792
+ const branchName = pr.head.ref;
793
+ const prBody = pr.body || '';
794
+
795
+ // Detect assignment
796
+ const bodyMatch = prBody.match(/(?:fixes|closes|resolves|assignment)\s*#(\d+)/i);
797
+ const branchMatch = branchName.match(/(?:assignment|hw|task|fix\/issue)-(\d+)/i);
798
+ const assignmentNum = bodyMatch ? parseInt(bodyMatch[1]) : branchMatch ? parseInt(branchMatch[1]) : null;
799
+
800
+ if (!assignmentNum) {
801
+ spinner.fail('No assignment issue linked. Student should use `Fixes #N` or branch `assignment-N`.');
802
+ continue;
803
+ }
804
+
805
+ // Fetch assignment
806
+ const { data: issue } = await octokit.issues.get({ owner, repo, issue_number: assignmentNum });
807
+ const { data: files } = await octokit.pulls.listFiles({ owner, repo, pull_number: prNumber });
808
+ const totalChanges = files.reduce((sum: number, f: any) => sum + f.additions + f.deletions, 0);
809
+
810
+ // CI
811
+ const sha = pr.head.sha;
812
+ const { data: ciChecks } = await octokit.checks.listForRef({ owner, repo, ref: sha });
813
+ const { data: statuses } = await octokit.repos.getCombinedStatusForRef({ owner, repo, ref: sha });
814
+ const ciPassed = statuses.state === 'success' || (ciChecks.total_count > 0 && ciChecks.check_runs.every((c: any) => c.conclusion === 'success'));
815
+ const ciFailed = statuses.state === 'failure' || ciChecks.check_runs.some((c: any) => c.conclusion === 'failure');
816
+
817
+ // Quick score
818
+ let score = 0;
819
+ if (ciPassed) score += 25;
820
+ score += 15; // base relevance
821
+ const testFiles = files.filter((f: any) => f.filename.includes('test') || f.filename.includes('spec'));
822
+ if (testFiles.length > 0) score += 20; else score += 5;
823
+ if (totalChanges < 500) score += 15; else score += 5;
824
+ const hasRef = /(?:fixes|closes|resolves)\s+#\d+/i.test(prBody);
825
+ if (hasRef && prBody.length > 20) score += 15; else score += 5;
826
+
827
+ const letter = score >= 80 ? 'A' : score >= 60 ? 'B' : score >= 40 ? 'C' : score >= 20 ? 'D' : 'F';
828
+ const emoji = score >= 80 ? '🟢' : score >= 60 ? '🔵' : score >= 40 ? '🟡' : score >= 20 ? '🟠' : '🔴';
829
+ const passed = score >= 40;
830
+
831
+ spinner.stop();
832
+
833
+ console.log(bold(`\n 📊 Grade for @${student} — PR #${prNumber}`));
834
+ console.log(` Assignment: ${issue.title} (#${assignmentNum})`);
835
+ console.log(` Changes: ${totalChanges} lines across ${files.length} files`);
836
+ console.log(` CI: ${ciPassed ? green('✅ Passed') : ciFailed ? red('❌ Failed') : yellow('⏳ Pending')}`);
837
+ console.log(` Tests: ${testFiles.length > 0 ? green(`${testFiles.length} file(s)`) : red('None')}`);
838
+ console.log(bold(`\n Score: ${score}/100 — Grade ${letter} ${emoji}\n`));
839
+
840
+ // Post grade
841
+ const gradeBody = `## ${emoji} GitPadi Grade — PR #${prNumber}\n\n**Student:** @${student}\n**Assignment:** ${issue.title} (#${assignmentNum})\n**Score:** ${score}/100\n**Grade:** ${letter}\n\n${passed ? '> ✅ **Passed.**' : '> ❌ **Did not pass.** Please fix and re-submit.'}\n\n---\n_Graded by [GitPadi](https://github.com/Netwalls/contributor-agent) 📝_\n\n<!-- gitpadi-grade -->`;
842
+ await octokit.issues.createComment({ owner, repo, issue_number: prNumber, body: gradeBody });
843
+ console.log(green(' ✅ Grade posted to PR.'));
844
+
845
+ if (passed && ciPassed) {
846
+ const { merge } = await inquirer.prompt([{
847
+ type: 'list', name: 'merge', message: green('Merge this PR?'),
848
+ choices: [
849
+ { name: `${green('✅')} Yes, squash & merge`, value: 'yes' },
850
+ { name: `${dim('⬅')} No`, value: 'no' },
851
+ ]
852
+ }]);
853
+ if (merge === 'yes') {
854
+ const mergeSpinner = ora('Merging...').start();
855
+ await octokit.pulls.merge({
856
+ owner, repo, pull_number: prNumber,
857
+ merge_method: 'squash',
858
+ commit_title: `[Grade ${letter}] ${pr.title} (#${prNumber})`,
859
+ });
860
+ mergeSpinner.succeed(green(`PR #${prNumber} merged!`));
861
+ }
862
+ }
863
+ } catch (e: any) {
864
+ spinner.fail(e.message);
865
+ }
866
+ }
867
+
868
+ // ── Cohort Leaderboard ─────────────────────────────────────────
869
+ else if (action === 'leaderboard') {
870
+ const ora = (await import('ora')).default;
871
+ const Table = (await import('cli-table3')).default;
872
+ const spinner = ora('Building cohort leaderboard...').start();
873
+
874
+ try {
875
+ const octokit = getOctokit();
876
+ const owner = getOwner();
877
+ const repo = getRepo();
878
+
879
+ // Find all PRs with grade comments
880
+ const { data: allPRs } = await octokit.pulls.list({ owner, repo, state: 'all', per_page: 100 });
881
+
882
+ const studentScores: Record<string, { scores: number[]; grades: string[]; prs: number[] }> = {};
883
+
884
+ for (const pr of allPRs) {
885
+ const { data: comments } = await octokit.issues.listComments({ owner, repo, issue_number: pr.number });
886
+ const gradeComment = comments.find(c => c.body?.includes('<!-- gitpadi-grade -->'));
887
+
888
+ if (gradeComment && gradeComment.body) {
889
+ const student = pr.user?.login || 'unknown';
890
+ const scoreMatch = gradeComment.body.match(/\*\*Score:\*\*\s*(\d+)/);
891
+ const gradeMatch = gradeComment.body.match(/\*\*Grade:\*\*\s*(\w)/);
892
+
893
+ if (scoreMatch) {
894
+ if (!studentScores[student]) studentScores[student] = { scores: [], grades: [], prs: [] };
895
+ studentScores[student].scores.push(parseInt(scoreMatch[1]));
896
+ studentScores[student].grades.push(gradeMatch ? gradeMatch[1] : '?');
897
+ studentScores[student].prs.push(pr.number);
898
+ }
899
+ }
900
+ }
901
+
902
+ spinner.stop();
903
+
904
+ const students = Object.entries(studentScores)
905
+ .map(([name, data]) => ({
906
+ name,
907
+ avg: Math.round(data.scores.reduce((a, b) => a + b, 0) / data.scores.length),
908
+ total: data.scores.reduce((a, b) => a + b, 0),
909
+ assignments: data.scores.length,
910
+ grades: data.grades.join(', '),
911
+ }))
912
+ .sort((a, b) => b.avg - a.avg);
913
+
914
+ if (students.length === 0) {
915
+ console.log(yellow('\n No graded submissions found yet.\n'));
916
+ continue;
917
+ }
918
+
919
+ const table = new Table({
920
+ head: ['Rank', 'Student', 'Avg Score', 'Assignments', 'Grades', 'Total Points'].map(h => cyan(h)),
921
+ style: { head: [], border: [] },
922
+ });
923
+
924
+ students.forEach((s, i) => {
925
+ const medal = i === 0 ? '🥇' : i === 1 ? '🥈' : i === 2 ? '🥉' : `${i + 1}.`;
926
+ const avgColor = s.avg >= 80 ? green : s.avg >= 60 ? cyan : s.avg >= 40 ? yellow : red;
927
+ table.push([
928
+ medal,
929
+ bold(`@${s.name}`),
930
+ avgColor(`${s.avg}/100`),
931
+ `${s.assignments}`,
932
+ s.grades,
933
+ `${s.total}`,
934
+ ]);
935
+ });
936
+
937
+ console.log(bold(`\n 🏆 COHORT LEADERBOARD — ${owner}/${repo}\n`));
938
+ console.log(table.toString());
939
+ console.log(green(`\n 👑 Top student: @${students[0].name} (${students[0].avg}/100 avg)\n`));
940
+
941
+ // Offer to post leaderboard as an issue comment
942
+ const { post } = await inquirer.prompt([{
943
+ type: 'list', name: 'post',
944
+ message: 'Post leaderboard to a pinned issue?',
945
+ choices: [
946
+ { name: `${green('✅')} Yes`, value: 'yes' },
947
+ { name: `${dim('⬅')} No`, value: 'no' },
948
+ ]
949
+ }]);
950
+
951
+ if (post === 'yes') {
952
+ let leaderBody = `## 🏆 Cohort Leaderboard\n\n`;
953
+ leaderBody += `_Last updated: ${new Date().toLocaleDateString()}_\n\n`;
954
+ leaderBody += `| Rank | Student | Avg Score | Assignments | Grades |\n|------|---------|-----------|-------------|--------|\n`;
955
+ students.forEach((s, i) => {
956
+ const medal = i === 0 ? '🥇' : i === 1 ? '🥈' : i === 2 ? '🥉' : `${i + 1}`;
957
+ leaderBody += `| ${medal} | @${s.name} | ${s.avg}/100 | ${s.assignments} | ${s.grades} |\n`;
958
+ });
959
+ leaderBody += `\n👑 **Top student:** @${students[0].name}\n\n<!-- gitpadi-leaderboard -->`;
960
+
961
+ // Find or create leaderboard issue
962
+ const { data: issues } = await octokit.issues.listForRepo({ owner, repo, state: 'open', labels: 'leaderboard', per_page: 5 });
963
+ const existing = issues[0];
964
+
965
+ if (existing) {
966
+ await octokit.issues.update({ owner, repo, issue_number: existing.number, body: leaderBody });
967
+ console.log(green(` ✅ Leaderboard updated: ${existing.html_url}`));
968
+ } else {
969
+ const { data: newIssue } = await octokit.issues.create({
970
+ owner, repo, title: '🏆 Cohort Leaderboard', body: leaderBody, labels: ['leaderboard'],
971
+ });
972
+ // Pin it
973
+ try { await octokit.issues.update({ owner, repo, issue_number: newIssue.number }); } catch { }
974
+ console.log(green(` ✅ Leaderboard created: ${newIssue.html_url}`));
975
+ }
976
+ }
977
+ } catch (e: any) {
978
+ spinner.fail(e.message);
979
+ }
980
+ }
981
+
982
+ console.log('');
319
983
  }
320
984
  }
321
985
 
@@ -327,29 +991,50 @@ async function contributorMenu() {
327
991
  console.log(dim(' Automating forking, syncing, and PR delivery'));
328
992
  line('═');
329
993
 
330
- // Auto-check for updates if in a repo
331
- if (getOwner() && getRepo()) {
332
- await contribute.syncBranch();
333
- }
334
-
335
994
  const { action } = await inquirer.prompt([{
336
995
  type: 'list',
337
996
  name: 'action',
338
997
  message: bold('Contributor Action:'),
339
998
  choices: [
340
- { name: `${cyan('🚀')} ${bold('Start Contribution')} ${dim('— fork, clone & branch')}`, value: 'start' },
341
- { name: `${green('🔄')} ${bold('Sync with Upstream')} ${dim(' pull latest changes')}`, value: 'sync' },
342
- { name: `${yellow('📋')} ${bold('View Action Logs')} ${dim('— check PR/commit status')}`, value: 'logs' },
343
- { name: `${magenta('🚀')} ${bold('Submit PR')} ${dim('— add, commit, push & PR')}`, value: 'submit' },
344
- new inquirer.Separator(dim(' ─────────────────────────────')),
999
+ // ── Bounty Discovery ──────────────────────────────────
1000
+ new inquirer.Separator(dim(' ── Bounty Discovery ─────────────────────')),
1001
+ { name: `${green('🎯')} ${bold('Bounty Hunter')} ${dim('— auto-apply Drips Wave & GrantFox')}`, value: 'hunt' },
1002
+ { name: `${yellow('🙋')} ${bold('Apply for Issue')} ${dim('— browse a repo & request to work')}`, value: 'apply' },
1003
+ { name: `${cyan('🔍')} ${bold('My Applications')} ${dim('— see issues you applied for')}`, value: 'my-apps' },
1004
+ // ── Contribution Flow ─────────────────────────────────
1005
+ new inquirer.Separator(dim(' ── Contribution Flow ────────────────────')),
1006
+ { name: `${cyan('🚀')} ${bold('Start Contribution')} ${dim('— fork, clone & branch from URL')}`, value: 'start' },
1007
+ { name: `${green('🔄')} ${bold('Sync with Upstream')} ${dim('— pull latest from original repo')}`, value: 'sync' },
1008
+ { name: `${magenta('🚀')} ${bold('Submit PR')} ${dim('— stage, commit, push & open PR')}`, value: 'submit' },
1009
+ { name: `${red('🔧')} ${bold('Fix & Re-push')} ${dim('— fix CI failures & force-push')}`, value: 'fix' },
1010
+ { name: `${cyan('💬')} ${bold('Reply to Comments')} ${dim('— respond to reviewer feedback')}`, value: 'reply' },
1011
+ // ── Visibility ────────────────────────────────────────
1012
+ new inquirer.Separator(dim(' ── Visibility ───────────────────────────')),
1013
+ { name: `${yellow('📋')} ${bold('View Action Logs')} ${dim('— check CI status on latest commit')}`, value: 'logs' },
1014
+ { name: `${green('📝')} ${bold('My Open PRs')} ${dim('— list your open PRs in this repo')}`, value: 'my-prs' },
1015
+ { name: `${magenta('📊')} ${bold('My Score')} ${dim('— see your contributor tier & breakdown')}`, value: 'my-score' },
1016
+ // ── Back ──────────────────────────────────────────────
1017
+ new inquirer.Separator(dim(' ─────────────────────────────────────────')),
345
1018
  { name: `${dim('⬅')} ${dim('Back to Mode Selector')}`, value: 'back' },
346
1019
  ],
347
1020
  loop: false,
1021
+ pageSize: 18,
348
1022
  }]);
349
1023
 
350
1024
  if (action === 'back') break;
351
1025
 
352
- if (action === 'start') {
1026
+ if (action === 'hunt') {
1027
+ await runBountyHunter({ platform: 'all', maxApplications: 3, dryRun: false });
1028
+ } else if (action === 'apply') {
1029
+ await applyForIssue.browseAndApply();
1030
+ } else if (action === 'my-apps') {
1031
+ await myApplicationsMenu();
1032
+ } else if (action === 'my-prs') {
1033
+ await ensureTargetRepo();
1034
+ await myOpenPRsMenu();
1035
+ } else if (action === 'my-score') {
1036
+ await myScoreMenu();
1037
+ } else if (action === 'start') {
353
1038
  const { url } = await ask([{ type: 'input', name: 'url', message: 'Enter Repo or Issue URL:' }]);
354
1039
  await contribute.forkAndClone(url);
355
1040
  } else {
@@ -360,8 +1045,12 @@ async function contributorMenu() {
360
1045
  await contribute.syncBranch();
361
1046
  } else if (action === 'logs') {
362
1047
  await contribute.viewLogs();
1048
+ } else if (action === 'fix') {
1049
+ await contribute.fixAndRepush();
1050
+ } else if (action === 'reply') {
1051
+ await contribute.replyToComments();
363
1052
  } else if (action === 'submit') {
364
- const branch = execSync('git rev-parse --abbrev-ref HEAD', { encoding: 'utf-8' }).trim();
1053
+ const branch = execFileSync('git', ['rev-parse', '--abbrev-ref', 'HEAD'], { encoding: 'utf-8' }).trim();
365
1054
  const match = branch.match(/issue-(\d+)/);
366
1055
  const detectedIssue = match ? parseInt(match[1]) : undefined;
367
1056
 
@@ -424,16 +1113,19 @@ async function maintainerMenu() {
424
1113
  name: 'category',
425
1114
  message: bold('Select operation:'),
426
1115
  choices: [
427
- { name: `${magenta('📋')} ${bold('Issues')} ${dim('— create, close, delete, assign, search')}`, value: 'issues' },
428
- { name: `${cyan('🔀')} ${bold('Pull Requests')} ${dim('— merge, review, approve, diff')}`, value: 'prs' },
429
- { name: `${green('📦')} ${bold('Repositories')} ${dim('— create, delete, clone, info')}`, value: 'repos' },
430
- { name: `${yellow('🏆')} ${bold('Contributors')} ${dim('— score, rank, auto-assign best')}`, value: 'contributors' },
431
- { name: `${red('🚀')} ${bold('Releases')} ${dim('— create, list, manage')}`, value: 'releases' },
432
- new inquirer.Separator(dim(' ─────────────────────────────')),
1116
+ { name: `${magenta('📋')} ${bold('Issues')} ${dim('— create, close, assign, bulk-create')}`, value: 'issues' },
1117
+ { name: `${cyan('🔀')} ${bold('Pull Requests')} ${dim('— list, merge, review, approve, diff')}`, value: 'prs' },
1118
+ { name: `${green('')} ${bold('Review & Merge')} ${dim('— review a PR, check CI, squash merge')}`, value: 'review-merge' },
1119
+ { name: `${yellow('🏆')} ${bold('Contributors')} ${dim('— score applicants, rank, auto-assign')}`, value: 'contributors' },
1120
+ { name: `${green('📦')} ${bold('Repositories')} ${dim('— create, delete, clone, topics, info')}`, value: 'repos' },
1121
+ { name: `${red('🚀')} ${bold('Releases')} ${dim('— create, list, tag releases')}`, value: 'releases' },
1122
+ { name: `${green('🎯')} ${bold('Bounty Hunter')} ${dim('— auto-apply to Drips Wave & GrantFox')}`, value: 'hunt' },
1123
+ new inquirer.Separator(dim(' ─────────────────────────────────────────')),
433
1124
  { name: `${dim('⚙️')} ${dim('Switch Repo')}`, value: 'switch' },
434
1125
  { name: `${dim('⬅')} ${dim('Back to Mode Selector')}`, value: 'back' },
435
1126
  ],
436
1127
  loop: false,
1128
+ pageSize: 12,
437
1129
  }]);
438
1130
 
439
1131
  if (category === 'back') break;
@@ -448,11 +1140,342 @@ async function maintainerMenu() {
448
1140
  else if (category === 'repos') await safeMenu(repoMenu);
449
1141
  else if (category === 'contributors') await safeMenu(contributorScoringMenu);
450
1142
  else if (category === 'releases') await safeMenu(releaseMenu);
1143
+ else if (category === 'hunt') await runBountyHunter({ platform: 'all', maxApplications: 3, dryRun: false });
1144
+ else if (category === 'review-merge') {
1145
+ await ensureTargetRepo();
1146
+ const { prNum } = await ask([{ type: 'input', name: 'prNum', message: cyan('PR number to review:') }]);
1147
+ if (!prNum || isNaN(Number(prNum))) continue;
1148
+
1149
+ const ora = (await import('ora')).default;
1150
+ const spinner = ora('Reviewing PR...').start();
1151
+ try {
1152
+ const octokit = getOctokit();
1153
+ const owner = getOwner();
1154
+ const repo = getRepo();
1155
+ const prNumber = parseInt(prNum);
1156
+
1157
+ const { data: pr } = await octokit.pulls.get({ owner, repo, pull_number: prNumber });
1158
+ const { data: files } = await octokit.pulls.listFiles({ owner, repo, pull_number: prNumber });
1159
+ const totalChanges = files.reduce((sum: number, f: any) => sum + f.additions + f.deletions, 0);
1160
+
1161
+ // CI Check
1162
+ const sha = pr.head.sha;
1163
+ const { data: ciChecks } = await octokit.checks.listForRef({ owner, repo, ref: sha });
1164
+ const { data: statuses } = await octokit.repos.getCombinedStatusForRef({ owner, repo, ref: sha });
1165
+
1166
+ const ciPassed = statuses.state === 'success' || (ciChecks.total_count > 0 && ciChecks.check_runs.every((c: any) => c.conclusion === 'success'));
1167
+ const ciFailed = statuses.state === 'failure' || ciChecks.check_runs.some((c: any) => c.conclusion === 'failure');
1168
+
1169
+ spinner.stop();
1170
+
1171
+ console.log(bold(`\n 📋 PR #${prNumber}: "${pr.title}"\n`));
1172
+ console.log(` ${dim('Author:')} @${pr.user?.login}`);
1173
+ console.log(` ${dim('Changes:')} ${totalChanges} lines across ${files.length} files`);
1174
+ console.log(` ${dim('CI:')} ${ciPassed ? green('✅ Passed') : ciFailed ? red('❌ Failed') : yellow('⏳ Pending')}\n`);
1175
+
1176
+ if (ciFailed) {
1177
+ // Notify contributor
1178
+ const failMsg = `❌ **CI Failed.** Please fix the failing checks and re-push.\n\nUse \`npx gitpadi\` → \`Fix & Re-push\` for a guided workflow.\n\n---\n_Review by [GitPadi](https://github.com/Netwalls/contributor-agent) 🤖_`;
1179
+ await octokit.issues.createComment({ owner, repo, issue_number: prNumber, body: failMsg });
1180
+ console.log(red(' ❌ CI failed. Contributor notified.'));
1181
+ } else if (ciPassed) {
1182
+ const { mergeAction } = await inquirer.prompt([{
1183
+ type: 'list', name: 'mergeAction', message: green('CI passed! Merge this PR?'),
1184
+ choices: [
1185
+ { name: `${green('✅')} Squash & Merge`, value: 'squash' },
1186
+ { name: `${cyan('🔀')} Merge Commit`, value: 'merge' },
1187
+ { name: `${dim('⬅')} Skip`, value: 'skip' },
1188
+ ]
1189
+ }]);
1190
+
1191
+ if (mergeAction !== 'skip') {
1192
+ const mergeSpinner = ora('Merging...').start();
1193
+ await octokit.pulls.merge({
1194
+ owner, repo, pull_number: prNumber,
1195
+ merge_method: mergeAction as 'squash' | 'merge',
1196
+ commit_title: `${pr.title} (#${prNumber})`,
1197
+ });
1198
+ mergeSpinner.succeed(green(`PR #${prNumber} merged successfully! 🎉`));
1199
+ }
1200
+ } else {
1201
+ console.log(yellow(' ⏳ CI is still running. Try again later.'));
1202
+ }
1203
+ } catch (e: any) {
1204
+ spinner.fail(e.message);
1205
+ }
1206
+ }
451
1207
 
452
1208
  console.log('');
453
1209
  }
454
1210
  }
455
1211
 
1212
+ // ── CI Actions Menu ────────────────────────────────────────────────────
1213
+ // Triggers GitHub Actions workflow_dispatch events from the terminal.
1214
+ // This makes npx gitpadi the primary interface for all CI operations.
1215
+ async function ciActionsMenu() {
1216
+ const WORKFLOW_FILE = 'gitpadi.yml';
1217
+ const owner = getOwner();
1218
+ const repo = getRepo();
1219
+ const octokit = getOctokit();
1220
+
1221
+ // Detect default branch
1222
+ let ref = 'main';
1223
+ try {
1224
+ const { data: repoData } = await octokit.repos.get({ owner, repo });
1225
+ ref = repoData.default_branch || 'main';
1226
+ } catch { /* use main */ }
1227
+
1228
+ while (true) {
1229
+ line('─');
1230
+ console.log(green(` 🤖 CI ACTIONS — ${owner}/${repo}`));
1231
+ console.log(dim(` Triggers .github/workflows/${WORKFLOW_FILE} via GitHub Actions API`));
1232
+ line('─');
1233
+
1234
+ const { action } = await inquirer.prompt([{
1235
+ type: 'list',
1236
+ name: 'action',
1237
+ message: bold('Select CI action to trigger:'),
1238
+ choices: [
1239
+ { name: `${green('✅')} ${bold('Review & Merge PR')} ${dim('— review + auto-merge a specific PR')}`, value: 'review-and-merge' },
1240
+ { name: `${magenta('📊')} ${bold('Grade Assignment PR')} ${dim('— grade a student submission PR')}`, value: 'grade-assignment' },
1241
+ { name: `${yellow('🏆')} ${bold('Score Applicants')} ${dim('— score contributors on an issue')}`, value: 'score-applicant' },
1242
+ { name: `${cyan('🔔')} ${bold('Remind Contributors')} ${dim('— send escalating reminders now')}`, value: 'remind-contributors' },
1243
+ { name: `${green('📋')} ${bold('Create Issues from File')} ${dim('— bulk-create from JSON/MD file')}`, value: 'create-issues' },
1244
+ new inquirer.Separator(dim(' ─────────────────────────────────────────')),
1245
+ { name: `${dim('⬅')} ${dim('Back')}`, value: 'back' },
1246
+ ],
1247
+ loop: false,
1248
+ }]);
1249
+
1250
+ if (action === 'back') break;
1251
+
1252
+ let inputs: Record<string, string> = { action };
1253
+
1254
+ if (action === 'review-and-merge') {
1255
+ const { prNum } = await ask([{ type: 'input', name: 'prNum', message: cyan('PR number:'), validate: (v: string) => /^\d+$/.test(v) || 'Enter a number' }]);
1256
+ inputs.pr_number = prNum;
1257
+ }
1258
+
1259
+ if (action === 'create-issues') {
1260
+ const { file } = await ask([{ type: 'input', name: 'file', message: cyan('Issues file path:'), default: 'issues.json' }]);
1261
+ inputs.issues_file = file;
1262
+ }
1263
+
1264
+ await triggerWorkflow(action, inputs, ref, WORKFLOW_FILE);
1265
+ }
1266
+ }
1267
+
1268
+ async function triggerWorkflow(action: string, extraInputs: Record<string, string> = {}, ref?: string, workflowFile = 'gitpadi.yml') {
1269
+ const owner = getOwner();
1270
+ const repo = getRepo();
1271
+ const octokit = getOctokit();
1272
+ const ora = (await import('ora')).default;
1273
+
1274
+ if (!ref) {
1275
+ try {
1276
+ const { data } = await octokit.repos.get({ owner, repo });
1277
+ ref = data.default_branch || 'main';
1278
+ } catch { ref = 'main'; }
1279
+ }
1280
+
1281
+ const spinner = ora(` Triggering ${bold(action)} on ${cyan(`${owner}/${repo}`)}…`).start();
1282
+ try {
1283
+ await octokit.actions.createWorkflowDispatch({
1284
+ owner, repo,
1285
+ workflow_id: workflowFile,
1286
+ ref,
1287
+ inputs: { action, ...extraInputs },
1288
+ });
1289
+ spinner.succeed(` ✅ ${bold(action)} triggered on branch ${cyan(ref)}`);
1290
+ console.log(dim(` Monitor at: https://github.com/${owner}/${repo}/actions\n`));
1291
+ } catch (e: any) {
1292
+ spinner.fail(` Failed to trigger workflow: ${e.message}`);
1293
+ console.log(dim(` Make sure ${workflowFile} exists in .github/workflows/ and has workflow_dispatch enabled.\n`));
1294
+ }
1295
+ }
1296
+
1297
+ // ── My Score Menu ──────────────────────────────────────────────────────
1298
+ async function myScoreMenu() {
1299
+ const ora = (await import('ora')).default;
1300
+ const { fetchProfile, scoreApplicant, TIER_EMOJI } = await import('./core/scorer.js');
1301
+
1302
+ const spinner = ora(' Fetching your GitHub profile…').start();
1303
+ try {
1304
+ const me = await getAuthenticatedUser();
1305
+ const profile = await fetchProfile(me, '');
1306
+ const scored = scoreApplicant(profile, []);
1307
+ spinner.succeed(` @${me} ${TIER_EMOJI[scored.tier]} Tier ${scored.tier} ${scored.score}/100`);
1308
+
1309
+ console.log();
1310
+ console.log(bold(' 📊 Score Breakdown'));
1311
+ console.log(` ${'─'.repeat(40)}`);
1312
+ console.log(` Account Maturity ${magenta(`${scored.breakdown.accountMaturity}/15`)}`);
1313
+ console.log(` Repo Experience ${cyan(`${scored.breakdown.repoExperience}/30`)}`);
1314
+ console.log(` GitHub Presence ${green(`${scored.breakdown.githubPresence}/15`)}`);
1315
+ console.log(` Activity Level ${yellow(`${scored.breakdown.activityLevel}/15`)}`);
1316
+ console.log(` Language Relevance ${magenta(`${scored.breakdown.languageRelevance}/10`)}`);
1317
+ console.log(` ${'─'.repeat(40)}`);
1318
+ console.log(` ${bold('Total')} ${bold(`${scored.score}/100`)} ${TIER_EMOJI[scored.tier]} ${bold(`Tier ${scored.tier}`)}`);
1319
+ console.log();
1320
+
1321
+ const tierMsg: Record<string, string> = {
1322
+ S: green('Exceptional — you qualify for auto-assign on Drips/GrantFox issues.'),
1323
+ A: green('Strong — most maintainers will assign you on application.'),
1324
+ B: yellow('Decent — you\'ll get considered. Keep contributing to improve.'),
1325
+ C: yellow('Building up — contribute more to boost your score.'),
1326
+ D: red('Early stage — focus on getting PRs merged to level up.'),
1327
+ };
1328
+ console.log(` ${tierMsg[scored.tier]}`);
1329
+ console.log();
1330
+ } catch (e: any) {
1331
+ spinner.fail(` Could not load profile: ${e.message}`);
1332
+ }
1333
+ }
1334
+
1335
+ // ── My Applications Menu ───────────────────────────────────────────────
1336
+ async function myApplicationsMenu() {
1337
+ const ora = (await import('ora')).default;
1338
+ const { APPLICATION_PATTERNS } = await import('./core/scorer.js');
1339
+ const octokit = getOctokit();
1340
+
1341
+ const { target } = await inquirer.prompt([{
1342
+ type: 'input',
1343
+ name: 'target',
1344
+ message: bold('Repo to check (owner/repo or leave blank for current):'),
1345
+ default: getOwner() && getRepo() ? `${getOwner()}/${getRepo()}` : '',
1346
+ }]);
1347
+
1348
+ const [owner, repo] = (target || `${getOwner()}/${getRepo()}`).split('/');
1349
+ if (!owner || !repo) { console.log(yellow(' No repo selected.')); return; }
1350
+
1351
+ const spinner = ora(` Fetching your applications in ${cyan(`${owner}/${repo}`)}…`).start();
1352
+ const me = await getAuthenticatedUser();
1353
+
1354
+ try {
1355
+ // Search issues where you commented with an application-style comment
1356
+ const { data: comments } = await octokit.search.issuesAndPullRequests({
1357
+ q: `commenter:${me} type:issue state:open repo:${owner}/${repo}`,
1358
+ per_page: 50, sort: 'updated',
1359
+ });
1360
+
1361
+ const applied: Array<{ number: number; title: string; url: string; assignees: string[]; status: string }> = [];
1362
+
1363
+ for (const item of comments.items) {
1364
+ const { data: issueComments } = await octokit.issues.listComments({
1365
+ owner, repo, issue_number: item.number, per_page: 100,
1366
+ });
1367
+
1368
+ const myComments = issueComments.filter((c: any) =>
1369
+ c.user?.login === me &&
1370
+ APPLICATION_PATTERNS.some(p => p.test(c.body || ''))
1371
+ );
1372
+
1373
+ if (myComments.length > 0) {
1374
+ const assignees: string[] = (item as any).assignees?.map((a: any) => a.login) || [];
1375
+ const isAssignedToMe = assignees.includes(me);
1376
+ applied.push({
1377
+ number: item.number,
1378
+ title: item.title,
1379
+ url: item.html_url,
1380
+ assignees,
1381
+ status: isAssignedToMe ? green('✅ Assigned to you') : assignees.length > 0 ? yellow(`⚠ Assigned to @${assignees[0]}`) : cyan('⏳ Pending'),
1382
+ });
1383
+ }
1384
+ }
1385
+
1386
+ spinner.succeed(` ${applied.length} application(s) found in ${owner}/${repo}`);
1387
+ console.log();
1388
+
1389
+ if (applied.length === 0) {
1390
+ console.log(dim(' You haven\'t applied for any open issues in this repo yet.'));
1391
+ console.log(dim(' Use "Bounty Hunter" or "Apply for Issue" to get started.'));
1392
+ } else {
1393
+ applied.forEach(a => {
1394
+ console.log(` ${cyan(`#${a.number}`)} ${bold(a.title)}`);
1395
+ console.log(` ${a.status} ${dim(a.url)}`);
1396
+ console.log();
1397
+ });
1398
+ }
1399
+ } catch (e: any) {
1400
+ spinner.fail(e.message);
1401
+ }
1402
+ }
1403
+
1404
+ // ── My Open PRs Menu ───────────────────────────────────────────────────
1405
+ async function myOpenPRsMenu() {
1406
+ const ora = (await import('ora')).default;
1407
+ const octokit = getOctokit();
1408
+ const owner = getOwner();
1409
+ const repo = getRepo();
1410
+ const me = await getAuthenticatedUser();
1411
+
1412
+ const spinner = ora(` Fetching your open PRs in ${cyan(`${owner}/${repo}`)}…`).start();
1413
+ try {
1414
+ const { data: prs } = await octokit.pulls.list({ owner, repo, state: 'open', per_page: 50 });
1415
+ const mine = prs.filter((p: any) => p.user?.login === me);
1416
+ spinner.succeed(` ${mine.length} open PR(s) as @${me}`);
1417
+ console.log();
1418
+
1419
+ if (mine.length === 0) {
1420
+ console.log(dim(' No open PRs. Use "Submit PR" to open one.'));
1421
+ } else {
1422
+ mine.forEach((p: any) => {
1423
+ const age = Math.floor((Date.now() - new Date(p.updated_at).getTime()) / 86_400_000);
1424
+ const draft = p.draft ? yellow(' [draft]') : '';
1425
+ console.log(` ${cyan(`#${p.number}`)}${draft} ${bold(p.title)}`);
1426
+ console.log(` ${dim(`branch: ${p.head.ref}`)} ${dim(`updated ${age}d ago`)} ${dim(p.html_url)}`);
1427
+ console.log();
1428
+ });
1429
+ }
1430
+ } catch (e: any) {
1431
+ spinner.fail(e.message);
1432
+ }
1433
+ }
1434
+
1435
+ // ── Repo Stats Menu ────────────────────────────────────────────────────
1436
+ async function repoStatsMenu() {
1437
+ const ora = (await import('ora')).default;
1438
+ const octokit = getOctokit();
1439
+ const owner = getOwner();
1440
+ const repo = getRepo();
1441
+
1442
+ const spinner = ora(` Loading stats for ${cyan(`${owner}/${repo}`)}…`).start();
1443
+ try {
1444
+ const [repoData, openIssues, openPRs, closedPRs, contributors] = await Promise.all([
1445
+ octokit.repos.get({ owner, repo }),
1446
+ octokit.issues.listForRepo({ owner, repo, state: 'open', per_page: 1 }),
1447
+ octokit.pulls.list({ owner, repo, state: 'open', per_page: 1 }),
1448
+ octokit.pulls.list({ owner, repo, state: 'closed', per_page: 50 }),
1449
+ octokit.repos.listContributors({ owner, repo, per_page: 10 }),
1450
+ ]);
1451
+
1452
+ const merged = closedPRs.data.filter((p: any) => p.merged_at).length;
1453
+ const mergeRate = closedPRs.data.length > 0
1454
+ ? Math.round((merged / closedPRs.data.length) * 100) : 0;
1455
+
1456
+ spinner.succeed();
1457
+ console.log();
1458
+ console.log(bold(` 📊 ${owner}/${repo}`));
1459
+ console.log(` ${'─'.repeat(42)}`);
1460
+ console.log(` ⭐ Stars ${yellow(String(repoData.data.stargazers_count))}`);
1461
+ console.log(` 🍴 Forks ${cyan(String(repoData.data.forks_count))}`);
1462
+ console.log(` 📋 Open Issues ${magenta(String(repoData.data.open_issues_count))}`);
1463
+ console.log(` 🔀 Open PRs ${cyan(String(openPRs.data.length ? '1+' : '0'))}`);
1464
+ console.log(` ✅ Merge Rate ${mergeRate >= 70 ? green(`${mergeRate}%`) : yellow(`${mergeRate}%`)} (last 50 closed PRs)`);
1465
+ console.log(` 🌿 Default Branch ${dim(repoData.data.default_branch)}`);
1466
+ console.log(` 📝 Language ${dim(repoData.data.language || 'mixed')}`);
1467
+ console.log();
1468
+ console.log(` Top Contributors:`);
1469
+ contributors.data.slice(0, 5).forEach((c: any, i: number) => {
1470
+ const medal = i === 0 ? '🥇' : i === 1 ? '🥈' : i === 2 ? '🥉' : ' ';
1471
+ console.log(` ${medal} @${c.login} ${dim(`${c.contributions} commits`)}`);
1472
+ });
1473
+ console.log();
1474
+ } catch (e: any) {
1475
+ spinner.fail(e.message);
1476
+ }
1477
+ }
1478
+
456
1479
  // ── Issue Menu ─────────────────────────────────────────────────────────
457
1480
  async function issueMenu() {
458
1481
  const { action } = await inquirer.prompt([{
@@ -890,6 +1913,27 @@ function setupCommander(): Command {
890
1913
  });
891
1914
  program.command('logs').description('📋 View Action logs').action(async () => { await contribute.viewLogs(); });
892
1915
 
1916
+ program.command('hunt')
1917
+ .description('🎯 Bounty Hunter — auto-apply to Drips Wave & GrantFox issues')
1918
+ .option('-p, --platform <p>', 'Platform: drips | grantfox | all (default: all)', 'all')
1919
+ .option('-m, --max <n>', 'Max applications to post (default: 3)', '3')
1920
+ .option('-s, --skills <langs>', 'Comma-separated languages to filter by (e.g. typescript,rust)', '')
1921
+ .option('--min-points <n>', 'Minimum Drips points (e.g. 150)', '0')
1922
+ .option('--dry-run', 'Show what would be applied for without posting', false)
1923
+ .option('--include-assigned', 'Include already-assigned issues', false)
1924
+ .action(async (o) => {
1925
+ const platform = (['drips', 'grantfox', 'all'].includes(o.platform) ? o.platform : 'all') as 'drips' | 'grantfox' | 'all';
1926
+ await runBountyHunter({
1927
+ platform,
1928
+ maxApplications: parseInt(o.max) || 3,
1929
+ skills: o.skills ? o.skills.split(',').map((s: string) => s.trim()).filter(Boolean) : [],
1930
+ minPoints: parseInt(o.minPoints) || 0,
1931
+ dryRun: !!o.dryRun,
1932
+ skipAssigned: !o.includeAssigned,
1933
+ verbose: false,
1934
+ });
1935
+ });
1936
+
893
1937
  return program;
894
1938
  }
895
1939