gitpadi 2.0.7 → 2.1.1

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