@oss-autopilot/core 3.42.5 → 3.43.0

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 (168) hide show
  1. package/dist/cli-pre-action.js +8 -3
  2. package/dist/cli-registry.js +272 -25
  3. package/dist/cli.bundle.cjs +183 -154
  4. package/dist/commands/check-integration.js +1 -0
  5. package/dist/commands/cleanup.d.ts +76 -0
  6. package/dist/commands/cleanup.js +269 -0
  7. package/dist/commands/comments.d.ts +6 -0
  8. package/dist/commands/comments.js +6 -2
  9. package/dist/commands/config.js +37 -5
  10. package/dist/commands/daily-dismiss-filter.d.ts +7 -0
  11. package/dist/commands/daily-dismiss-filter.js +17 -1
  12. package/dist/commands/daily-ledger.d.ts +122 -0
  13. package/dist/commands/daily-ledger.js +225 -0
  14. package/dist/commands/daily-recent-prs.d.ts +26 -0
  15. package/dist/commands/daily-recent-prs.js +55 -0
  16. package/dist/commands/daily.d.ts +2 -1
  17. package/dist/commands/daily.js +59 -89
  18. package/dist/commands/dashboard-cache.d.ts +2 -0
  19. package/dist/commands/dashboard-cache.js +33 -8
  20. package/dist/commands/dashboard-data.js +71 -36
  21. package/dist/commands/dashboard-gist-sync.js +3 -1
  22. package/dist/commands/dashboard-lifecycle.js +1 -1
  23. package/dist/commands/dashboard-process.d.ts +14 -1
  24. package/dist/commands/dashboard-process.js +46 -7
  25. package/dist/commands/dashboard-server.js +89 -23
  26. package/dist/commands/detect-formatters.js +1 -0
  27. package/dist/commands/dismiss.js +5 -2
  28. package/dist/commands/doctor.d.ts +15 -1
  29. package/dist/commands/doctor.js +73 -5
  30. package/dist/commands/draft.d.ts +77 -0
  31. package/dist/commands/draft.js +218 -0
  32. package/dist/commands/eval.js +1 -0
  33. package/dist/commands/guidelines.d.ts +23 -1
  34. package/dist/commands/guidelines.js +49 -4
  35. package/dist/commands/index.d.ts +24 -4
  36. package/dist/commands/index.js +15 -3
  37. package/dist/commands/issue-thread.d.ts +46 -0
  38. package/dist/commands/issue-thread.js +123 -0
  39. package/dist/commands/ledger-backfill.d.ts +9 -0
  40. package/dist/commands/ledger-backfill.js +44 -1
  41. package/dist/commands/list-mark-done.d.ts +2 -1
  42. package/dist/commands/list-mark-done.js +3 -1
  43. package/dist/commands/list-move-tier.d.ts +2 -1
  44. package/dist/commands/list-move-tier.js +3 -1
  45. package/dist/commands/local-repos.js +10 -5
  46. package/dist/commands/locate-issue-list.d.ts +40 -17
  47. package/dist/commands/locate-issue-list.js +148 -88
  48. package/dist/commands/move.js +7 -1
  49. package/dist/commands/overnight-handoff.d.ts +17 -7
  50. package/dist/commands/overnight-handoff.js +36 -14
  51. package/dist/commands/overnight-push-prep.d.ts +13 -8
  52. package/dist/commands/overnight-push-prep.js +106 -34
  53. package/dist/commands/overnight-tool-rules.d.ts +54 -0
  54. package/dist/commands/overnight-tool-rules.js +217 -0
  55. package/dist/commands/overnight.d.ts +5 -6
  56. package/dist/commands/overnight.js +61 -140
  57. package/dist/commands/parse-list.js +7 -1
  58. package/dist/commands/policy.d.ts +86 -0
  59. package/dist/commands/policy.js +263 -0
  60. package/dist/commands/pr-preflight.d.ts +43 -0
  61. package/dist/commands/pr-preflight.js +294 -0
  62. package/dist/commands/repo-vet.d.ts +9 -0
  63. package/dist/commands/repo-vet.js +36 -11
  64. package/dist/commands/scout-bridge.js +18 -8
  65. package/dist/commands/search.js +7 -0
  66. package/dist/commands/setup.d.ts +3 -3
  67. package/dist/commands/setup.js +46 -18
  68. package/dist/commands/skip-add.js +10 -1
  69. package/dist/commands/startup.d.ts +5 -3
  70. package/dist/commands/startup.js +65 -49
  71. package/dist/commands/state-cmd.d.ts +2 -0
  72. package/dist/commands/state-cmd.js +5 -1
  73. package/dist/commands/stats.js +1 -0
  74. package/dist/commands/status.js +1 -0
  75. package/dist/commands/strategy.js +1 -0
  76. package/dist/commands/vet-list.d.ts +6 -0
  77. package/dist/commands/vet-list.js +25 -0
  78. package/dist/commands/vet.d.ts +12 -0
  79. package/dist/commands/vet.js +118 -1
  80. package/dist/core/__fixtures__/prompt-injection-payloads.js +31 -0
  81. package/dist/core/anti-llm-policy.d.ts +3 -0
  82. package/dist/core/anti-llm-policy.js +3 -0
  83. package/dist/core/auth.js +2 -0
  84. package/dist/core/ci-analysis.d.ts +7 -2
  85. package/dist/core/ci-analysis.js +76 -21
  86. package/dist/core/commit-date.d.ts +19 -0
  87. package/dist/core/commit-date.js +17 -0
  88. package/dist/core/config-registry.js +11 -5
  89. package/dist/core/contributing.d.ts +2 -3
  90. package/dist/core/contributing.js +2 -3
  91. package/dist/core/daily-logic.d.ts +27 -5
  92. package/dist/core/daily-logic.js +57 -19
  93. package/dist/core/errors.d.ts +37 -3
  94. package/dist/core/errors.js +54 -5
  95. package/dist/core/gist-health.d.ts +15 -3
  96. package/dist/core/gist-health.js +8 -0
  97. package/dist/core/gist-state-store.d.ts +24 -4
  98. package/dist/core/gist-state-store.js +97 -46
  99. package/dist/core/github-stats.d.ts +104 -16
  100. package/dist/core/github-stats.js +282 -97
  101. package/dist/core/http-cache.d.ts +0 -10
  102. package/dist/core/http-cache.js +0 -19
  103. package/dist/core/index.d.ts +12 -5
  104. package/dist/core/index.js +15 -5
  105. package/dist/core/issue-conversation.d.ts +8 -2
  106. package/dist/core/issue-conversation.js +31 -12
  107. package/dist/core/local-config.d.ts +95 -0
  108. package/dist/core/local-config.js +271 -0
  109. package/dist/core/merged-pr-notes.d.ts +2 -2
  110. package/dist/core/pagination.d.ts +55 -0
  111. package/dist/core/pagination.js +59 -0
  112. package/dist/core/paths.d.ts +7 -0
  113. package/dist/core/paths.js +9 -0
  114. package/dist/core/pr-assembly.js +6 -2
  115. package/dist/core/pr-graphql.d.ts +37 -3
  116. package/dist/core/pr-graphql.js +73 -12
  117. package/dist/core/pr-monitor.d.ts +29 -12
  118. package/dist/core/pr-monitor.js +71 -23
  119. package/dist/core/pr-preflight.d.ts +113 -0
  120. package/dist/core/pr-preflight.js +364 -0
  121. package/dist/core/pr-quality-rubric.d.ts +0 -6
  122. package/dist/core/pr-quality-rubric.js +0 -8
  123. package/dist/core/pr-template.d.ts +2 -0
  124. package/dist/core/pr-template.js +5 -1
  125. package/dist/core/repo-policy.d.ts +105 -0
  126. package/dist/core/repo-policy.js +400 -0
  127. package/dist/core/repo-score-manager.d.ts +48 -0
  128. package/dist/core/repo-score-manager.js +111 -1
  129. package/dist/core/review-analysis.d.ts +34 -19
  130. package/dist/core/review-analysis.js +67 -10
  131. package/dist/core/reviewed-prs-fetch.js +11 -29
  132. package/dist/core/reviewed-prs.js +8 -15
  133. package/dist/core/stale-data.d.ts +41 -0
  134. package/dist/core/stale-data.js +115 -0
  135. package/dist/core/state-persistence.d.ts +62 -27
  136. package/dist/core/state-persistence.js +338 -117
  137. package/dist/core/state-schema.d.ts +113 -210
  138. package/dist/core/state-schema.js +165 -80
  139. package/dist/core/state.d.ts +60 -8
  140. package/dist/core/state.js +192 -46
  141. package/dist/core/status-determination.js +26 -8
  142. package/dist/core/strategy.js +3 -1
  143. package/dist/core/types.d.ts +22 -1
  144. package/dist/core/types.js +1 -0
  145. package/dist/core/untrusted-content.d.ts +30 -11
  146. package/dist/core/untrusted-content.js +77 -42
  147. package/dist/core/urls.d.ts +9 -0
  148. package/dist/core/urls.js +18 -0
  149. package/dist/dashboard/assets/{chart-panel-DPKNBUts.js → chart-panel-C_C1lFTI.js} +1 -1
  150. package/dist/dashboard/assets/{index-B25bZOYX.js → index-B--H66Jk.js} +1 -1
  151. package/dist/dashboard/index.html +1 -1
  152. package/dist/formatters/json.d.ts +262 -6
  153. package/dist/formatters/json.js +77 -1
  154. package/package.json +1 -1
  155. package/dist/core/ci-enforced-tools.d.ts +0 -35
  156. package/dist/core/ci-enforced-tools.js +0 -109
  157. package/dist/core/comment-decision.d.ts +0 -79
  158. package/dist/core/comment-decision.js +0 -82
  159. package/dist/core/extraction-categories.d.ts +0 -55
  160. package/dist/core/extraction-categories.js +0 -108
  161. package/dist/core/follow-up-history.d.ts +0 -40
  162. package/dist/core/follow-up-history.js +0 -71
  163. package/dist/core/issue-effort.d.ts +0 -29
  164. package/dist/core/issue-effort.js +0 -47
  165. package/dist/core/maintainer-hints.d.ts +0 -23
  166. package/dist/core/maintainer-hints.js +0 -36
  167. package/dist/core/workflow-state.d.ts +0 -56
  168. package/dist/core/workflow-state.js +0 -101
@@ -24,11 +24,13 @@ import * as path from 'node:path';
24
24
  import { errorMessage, getStateManager, maybeCheckpoint, parseGitHubUrl, requireGitHubToken } from '../core/index.js';
25
25
  import { UNATTENDED_ENV, ValidationError } from '../core/errors.js';
26
26
  import { warn } from '../core/logger.js';
27
- import { getReportsDir } from '../core/paths.js';
27
+ import { getReportsDir, resolveDataDir } from '../core/paths.js';
28
+ import { pruneRejectedCopies } from '../core/stale-data.js';
28
29
  import { detectIssueListPath } from './locate-issue-list.js';
29
30
  import { parseIssueList } from './parse-list.js';
30
31
  import { executeDailyCheck } from './daily.js';
31
32
  import { exportHandoff, handoffDir, pruneHandoffBundles, writeHandoffBundle } from './overnight-handoff.js';
33
+ import { OVERNIGHT_ALLOWED_TOOLS, OVERNIGHT_DISALLOWED_TOOLS, OVERNIGHT_GIT_ENV } from './overnight-tool-rules.js';
32
34
  const MODULE = 'overnight';
33
35
  // ponytail: static table, not a classifier. Every ActionableIssueType is
34
36
  // listed: the Record key type makes a new variant fail typecheck here.
@@ -94,11 +96,21 @@ export function pickImplementCandidate(items, openPRs, attempts, listPath, langu
94
96
  }
95
97
  return null;
96
98
  }
97
- /** The curated list's available items, or null when there is no readable list. */
98
- function loadListItems() {
99
+ /**
100
+ * The curated list's available items, or null when there is no readable list.
101
+ * With no list configured, says so in `warnings` (#1933): a probed file is
102
+ * never used here, so a machine that relied on one needs the path set.
103
+ */
104
+ function loadListItems(warnings) {
99
105
  const located = detectIssueListPath();
100
- if (!located)
106
+ if (!located) {
107
+ warnings.push({
108
+ phase: 'issue-list',
109
+ operation: 'find curated issue list',
110
+ message: 'no curated issue list configured on this machine; run setup --set issueListPath=<abs path>',
111
+ });
101
112
  return null;
113
+ }
102
114
  try {
103
115
  return { items: parseIssueList(fs.readFileSync(located.path, 'utf8')).available, path: located.path };
104
116
  }
@@ -221,12 +233,15 @@ function reportPathFor(d) {
221
233
  export async function runOvernight() {
222
234
  const sm = getStateManager();
223
235
  const daily = await executeDailyCheck(requireGitHubToken());
236
+ // The nightly sweep for rejected state copies past retention (#1956); never throws.
237
+ pruneRejectedCopies(resolveDataDir());
224
238
  const now = new Date();
225
239
  const runAt = now.toISOString();
226
240
  const languageOf = (repo) => sm.getRepoScore(repo)?.language;
227
241
  const { prepare, judgment } = bucketize(daily, languageOf);
228
242
  const previous = sm.getLastOvernight();
229
- const list = loadListItems();
243
+ const warnings = [...daily.warnings];
244
+ const list = loadListItems(warnings);
230
245
  // Attempts survive across runs; the ones whose issue left the list are
231
246
  // dropped so a re-added issue can be tried again.
232
247
  const attempts = (previous?.implementAttempts ?? []).filter((a) => !list || list.items.some((i) => i.url === a.url));
@@ -238,9 +253,9 @@ export async function runOvernight() {
238
253
  prepare,
239
254
  judgment,
240
255
  implement,
256
+ warnings,
241
257
  attention: daily.attention,
242
258
  failures: daily.failures,
243
- warnings: daily.warnings,
244
259
  };
245
260
  const reportPath = reportPathFor(now);
246
261
  // A re-run on the same date (launchd retry, manual) must not drop branches
@@ -345,6 +360,11 @@ export async function runOvernightRecord(options) {
345
360
  const last = sm.getLastOvernight();
346
361
  if (!last)
347
362
  throw new Error('No overnight run recorded yet; run `overnight` first.');
363
+ // The URL lands in the morning report and in commands built from it (#1933).
364
+ const parsed = parseGitHubUrl(options.url);
365
+ if (!parsed || options.url !== `https://github.com/${parsed.owner}/${parsed.repo}/${parsed.type}/${parsed.number}`) {
366
+ throw new ValidationError(`Refusing to record an unusual URL: ${options.url}`);
367
+ }
348
368
  const report = options.fromReport ? readPreparerReport(options.fromReport) : {};
349
369
  const branch = options.branch ?? report.branch;
350
370
  if (!branch)
@@ -465,138 +485,41 @@ export function overnightFreshness(now = new Date()) {
465
485
  : { ...base, ageHours: Math.max(0, Math.round(ageMs / 36e5)) };
466
486
  }
467
487
  export const LAUNCHD_LABEL = 'com.oss-autopilot.overnight';
488
+ export { OVERNIGHT_ALLOWED_TOOLS, OVERNIGHT_DISALLOWED_TOOLS, OVERNIGHT_GIT_ENV, PUSH_DISABLED_URL, } from './overnight-tool-rules.js';
489
+ function xmlEscape(s) {
490
+ return s.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;');
491
+ }
468
492
  /**
469
- * Tools the headless run may use without a prompt (see commands/oss-overnight.md).
470
- *
471
- * The allowlist is the enforcement half of the no-side-effects gate, so it is
472
- * enumerated, not wildcarded: every git subcommand except `push`, only the
473
- * read side of `gh` (no `create`/`comment`/`merge`/`close`/`rerun`, no `gh api`
474
- * because it can POST), and no `bash`/`sh`/`npx` shell escapes. `node`, `pnpm`
475
- * and `npm` stay because the CLI bundle and a repo's test suite are already
476
- * arbitrary code; the credential-bearing writes are what the list keeps out.
477
- * Stronger isolation (a dedicated user with no push credentials, or a
478
- * container) is the upgrade path if that trust level is not acceptable.
493
+ * The flags that make the rule lists the only permissions in force. An empty
494
+ * `--setting-sources` is what drops the user's own settings, and Claude Code
495
+ * does not document the empty value: the run depends on behaviour that could
496
+ * change. `--restricted` (managed settings and `--settings` only, file tools
497
+ * confined to working directories) is the documented flag to evaluate instead.
479
498
  */
480
- const GIT_SUBCOMMANDS = [
481
- 'clone',
482
- 'fetch',
483
- 'worktree',
484
- 'checkout',
485
- 'switch',
486
- 'branch',
487
- 'rebase',
488
- 'merge-base',
489
- 'status',
490
- 'diff',
491
- 'log',
492
- 'show',
493
- 'add',
494
- 'commit',
495
- 'rev-parse',
496
- 'remote',
497
- ];
498
- const GH_READ_SUBCOMMANDS = [
499
- 'pr view',
500
- 'pr checks',
501
- 'pr diff',
502
- 'pr list',
503
- 'run view',
504
- 'run list',
505
- 'issue view',
506
- 'repo view',
507
- 'auth status',
508
- ];
499
+ const PERMISSION_FLAGS = ['--permission-mode', 'dontAsk', '--setting-sources', ''];
500
+ function plistArg(value) {
501
+ return ` <string>${xmlEscape(value)}</string>`;
502
+ }
503
+ function plistEnvLine(key, value) {
504
+ return ` <key>${key}</key><string>${xmlEscape(value)}</string>`;
505
+ }
506
+ function gitEnvLines() {
507
+ return Object.entries(OVERNIGHT_GIT_ENV).map(([key, value]) => plistEnvLine(key, value));
508
+ }
509
509
  /**
510
- * Deny list layered under the allowlist (deny beats allow): even if a future
511
- * allow rule widens, these never run unattended. `AskUserQuestion` is denied
512
- * because nobody can answer; the preparer agent reports `blocked` instead.
510
+ * Pure: whether an installed plist carries the rules and environment this
511
+ * version renders. The lists are baked in when the plist is written, so a
512
+ * schedule installed before an upgrade keeps the old ones (`doctor` warns).
513
513
  */
514
- export const OVERNIGHT_DISALLOWED_TOOLS = [
515
- 'Bash(git push)',
516
- 'Bash(git push *)',
517
- // The -C form of push: `git -C <dir> push` would otherwise slip past a
518
- // prefix rule on `git push`.
519
- 'Bash(git * push)',
520
- 'Bash(git * push *)',
521
- 'Bash(gh pr create *)',
522
- 'Bash(gh pr comment *)',
523
- 'Bash(gh pr merge *)',
524
- 'Bash(gh pr close *)',
525
- 'Bash(gh pr edit *)',
526
- 'Bash(gh pr ready *)',
527
- 'Bash(gh issue create *)',
528
- 'Bash(gh issue comment *)',
529
- 'Bash(gh issue close *)',
530
- 'Bash(gh run rerun *)',
531
- 'Bash(gh api *)',
532
- // `npm`/`pnpm` are allowed for builds and tests, but a token in ~/.npmrc
533
- // would let their registry writes ship a release unattended — exactly the
534
- // credential-bearing writes the gate exists to keep out.
535
- 'Bash(npm publish)',
536
- 'Bash(npm publish *)',
537
- 'Bash(npm unpublish *)',
538
- 'Bash(npm deprecate *)',
539
- 'Bash(pnpm publish)',
540
- 'Bash(pnpm publish *)',
541
- // Direct shell escapes inside the allowed programs (#1728): `npm exec` IS
542
- // npx, `pnpm dlx`/`pnpm exec` run arbitrary packages, and `node -e` runs
543
- // arbitrary JS — each can spawn `git push` and void the push denies above.
544
- // The residual (a repo's own test scripts run arbitrary code) is documented
545
- // in commands/oss-overnight.md and cannot be closed by tool rules.
546
- 'Bash(npm exec)',
547
- 'Bash(npm exec *)',
548
- 'Bash(npm x)',
549
- 'Bash(npm x *)',
550
- 'Bash(npm * exec *)',
551
- 'Bash(pnpm dlx *)',
552
- 'Bash(pnpm * dlx *)',
553
- 'Bash(pnpm exec)',
554
- 'Bash(pnpm exec *)',
555
- 'Bash(pnpm * exec *)',
556
- 'Bash(node -e *)',
557
- 'Bash(node --eval *)',
558
- 'Bash(node -p *)',
559
- 'Bash(node -pe *)',
560
- 'Bash(node --print *)',
561
- // The same escapes after a leading flag (`node --no-warnings -e`,
562
- // `pnpm --dir x exec`), mirroring the `git * push` deny.
563
- 'Bash(node * -e *)',
564
- 'Bash(node * --eval *)',
565
- 'Bash(node * -p *)',
566
- 'Bash(node * -pe *)',
567
- 'Bash(node * --print *)',
568
- 'Bash(npm * x *)',
569
- // The `=` forms take no space, so the space-delimited denies above miss
570
- // them: `node --eval=<js>` runs exactly like `node --eval <js>`.
571
- 'Bash(node --eval=*)',
572
- 'Bash(node * --eval=*)',
573
- 'Bash(node --print=*)',
574
- 'Bash(node * --print=*)',
575
- 'AskUserQuestion',
576
- ].join(',');
577
- export const OVERNIGHT_ALLOWED_TOOLS = [
578
- 'Read',
579
- 'Edit',
580
- 'Write',
581
- 'Glob',
582
- 'Grep',
583
- 'Task',
584
- // Both the bare and the `-C <dir>` forms: a preparer's worktree is never its
585
- // cwd, and `cd <dir> && git ...` is denied under dontAsk, so without `-C`
586
- // every preparer blocks (#1697).
587
- ...GIT_SUBCOMMANDS.flatMap((sub) => [
588
- `Bash(git ${sub})`,
589
- `Bash(git ${sub} *)`,
590
- `Bash(git -C * ${sub})`,
591
- `Bash(git -C * ${sub} *)`,
592
- ]),
593
- ...GH_READ_SUBCOMMANDS.map((sub) => `Bash(gh ${sub} *)`),
594
- 'Bash(node *)',
595
- 'Bash(pnpm *)',
596
- 'Bash(npm *)',
597
- ].join(',');
598
- function xmlEscape(s) {
599
- return s.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;');
514
+ export function isScheduleCurrent(plist) {
515
+ const required = [
516
+ PERMISSION_FLAGS.map((flag) => plistArg(flag)).join('\n'),
517
+ plistArg(OVERNIGHT_ALLOWED_TOOLS),
518
+ plistArg(OVERNIGHT_DISALLOWED_TOOLS),
519
+ plistEnvLine(UNATTENDED_ENV, '1'),
520
+ ...gitEnvLines(),
521
+ ];
522
+ return required.every((part) => plist.includes(part));
600
523
  }
601
524
  /**
602
525
  * The settings layer the scheduled job runs with instead of the user's own
@@ -620,10 +543,7 @@ export function renderLaunchdPlist(options, logPath, settingsPath) {
620
543
  options.claudePath,
621
544
  '-p',
622
545
  '/oss-overnight',
623
- '--permission-mode',
624
- 'dontAsk',
625
- '--setting-sources',
626
- '',
546
+ ...PERMISSION_FLAGS,
627
547
  '--settings',
628
548
  settingsPath,
629
549
  '--allowedTools',
@@ -641,7 +561,7 @@ export function renderLaunchdPlist(options, logPath, settingsPath) {
641
561
  ` <key>Label</key><string>${LAUNCHD_LABEL}</string>`,
642
562
  ' <key>ProgramArguments</key>',
643
563
  ' <array>',
644
- ...args.map((a) => ` <string>${xmlEscape(a)}</string>`),
564
+ ...args.map((a) => plistArg(a)),
645
565
  ' </array>',
646
566
  ' <key>StartCalendarInterval</key>',
647
567
  ` <dict><key>Hour</key><integer>${options.hour}</integer><key>Minute</key><integer>0</integer></dict>`,
@@ -654,7 +574,8 @@ export function renderLaunchdPlist(options, logPath, settingsPath) {
654
574
  ` <key>PATH</key><string>${xmlEscape(`${path.dirname(process.execPath)}:/usr/local/bin:/opt/homebrew/bin:/usr/bin:/bin`)}</string>`,
655
575
  // The CLI's own GitHub-writing commands refuse while this is set (see
656
576
  // assertAttended): `Bash(node *)` has to stay allowed, so the gate is in code.
657
- ` <key>${UNATTENDED_ENV}</key><string>1</string>`,
577
+ plistEnvLine(UNATTENDED_ENV, '1'),
578
+ ...gitEnvLines(),
658
579
  ' </dict>',
659
580
  '</dict>',
660
581
  '</plist>',
@@ -5,16 +5,21 @@
5
5
  import * as fs from 'node:fs';
6
6
  import * as path from 'node:path';
7
7
  import { errorMessage } from '../core/errors.js';
8
+ import { parseGitHubUrl } from '../core/urls.js';
8
9
  /**
9
10
  * Extract a GitHub issue URL from a markdown line.
10
11
  *
11
12
  * Guard 1: PR URLs (/pull/) are intentionally excluded. A pull-request URL is
12
13
  * never a valid issue candidate — collecting them inflates `availableCount` and
13
14
  * causes `vet-list` to spend API calls on URLs that cannot resolve as issues.
15
+ *
16
+ * Guard 2: the owner/repo must pass `parseGitHubUrl` (#1933). List URLs reach
17
+ * the overnight dispatch line and quoted shell arguments, so a line whose URL
18
+ * carries quotes, spaces or other characters GitHub never uses is dropped.
14
19
  */
15
20
  function extractGitHubUrl(line) {
16
21
  const match = line.match(/https:\/\/github\.com\/([^/]+\/[^/]+)\/issues\/(\d+)/);
17
- if (match) {
22
+ if (match && parseGitHubUrl(match[0])) {
18
23
  return { repo: match[1], number: parseInt(match[2], 10), url: match[0] };
19
24
  }
20
25
  return null;
@@ -399,6 +404,7 @@ export function pruneIssueList(content, minScore = 6) {
399
404
  }
400
405
  return { pruned: collapsed.join('\n') + '\n', removedCount };
401
406
  }
407
+ // eslint-disable-next-line @typescript-eslint/require-await -- async keeps the Promise-returning contract callers rely on; the body has no await yet
402
408
  export async function runParseList(options) {
403
409
  const filePath = path.resolve(options.filePath);
404
410
  if (!fs.existsSync(filePath)) {
@@ -0,0 +1,86 @@
1
+ /**
2
+ * `policy get|set|reset --repo owner/repo` (#1953): the per-repo contribution
3
+ * policy record, and the vet-time write that fills it in.
4
+ *
5
+ * `get` only reads. `set` and `reset` refuse unattended runs: a record the
6
+ * user sets is trusted over vet's reading of the repo docs, so nobody but the
7
+ * user writes one. There is no MCP setter on purpose.
8
+ */
9
+ import { type RepoPolicy, type RepoPolicySummary } from '../core/repo-policy.js';
10
+ export interface PolicyGetOutput {
11
+ repo: string;
12
+ /** The policy that applies: the stored record with `config.aiPolicyBlocklist` read as a ban. Null when nothing is known. */
13
+ policy: (RepoPolicySummary & {
14
+ updatedAt: string;
15
+ /** True when the repo is in `config.aiPolicyBlocklist`; `policy set` cannot lift that ban. */
16
+ blocklisted: boolean;
17
+ /** The disclosure line the repo asks for, inside a `<github-content>` fence. */
18
+ disclosureText?: string;
19
+ /** `file: quoted line` per rule, inside a `<github-content>` fence. */
20
+ sources?: string;
21
+ }) | null;
22
+ }
23
+ export interface PolicySetOptions {
24
+ repo: string;
25
+ aiPolicy?: string;
26
+ disclosureText?: string;
27
+ cla?: string;
28
+ prGate?: string;
29
+ /** Replaces the list; an empty string clears it. */
30
+ commitRules?: string;
31
+ /** 0 clears it. */
32
+ maxOpenAiPRs?: number;
33
+ /** Where the rule came from, e.g. a maintainer's comment; stored as a short quoted line. */
34
+ source?: string;
35
+ }
36
+ export interface PolicyWriteOutput extends PolicyGetOutput {
37
+ /**
38
+ * How `--ai-policy` changed `config.aiPolicyBlocklist`: `added` for banned
39
+ * (clients that predate policy records read only the blocklist), `removed`
40
+ * for any other value (the blocklist always bans, so it would override the
41
+ * record). Absent when the list did not change.
42
+ */
43
+ blocklistChange?: 'added' | 'removed';
44
+ /** Set when the post-mutation Gist checkpoint failed; the local mutation succeeded (#1370). */
45
+ gistSyncWarning?: string;
46
+ }
47
+ export interface PolicyResetOutput {
48
+ repo: string;
49
+ deleted: boolean;
50
+ gistSyncWarning?: string;
51
+ }
52
+ /** Read the policy that applies to `repo`. Untrusted text comes back fenced. */
53
+ export declare function runPolicyGet(options: {
54
+ repo: string;
55
+ }): Promise<PolicyGetOutput>;
56
+ /**
57
+ * Record the user's policy for `repo`, merged over what is stored. Refused
58
+ * unattended, and the result is `reviewedByUser: true`, so vet never
59
+ * overwrites it. It cannot lift a `config.aiPolicyBlocklist` ban.
60
+ */
61
+ export declare function runPolicySet(options: PolicySetOptions): Promise<PolicyWriteOutput>;
62
+ /**
63
+ * Delete the stored record for `repo`. Refused unattended: deleting a ban the
64
+ * user recorded relaxes it. `config.aiPolicyBlocklist` is left as is.
65
+ */
66
+ export declare function runPolicyReset(options: {
67
+ repo: string;
68
+ }): Promise<PolicyResetOutput>;
69
+ /**
70
+ * Store what vet read from the repo docs, unreviewed. Never replaces a record
71
+ * the user set, and skips the write when nothing changed. A failure is logged,
72
+ * never thrown: recording the policy must not fail the vet.
73
+ */
74
+ export declare function recordVetPolicy(repo: string, derived: RepoPolicy): Promise<void>;
75
+ /**
76
+ * {@link recordVetPolicy} for several repos, with one Gist checkpoint. With
77
+ * `fillOnly` (vet-list, which reads only scout's CONTRIBUTING text) a stored
78
+ * record is replaced only by a ban: a narrower reading must not overwrite one
79
+ * vet took from more docs.
80
+ */
81
+ export declare function recordVetPolicies(readings: ReadonlyArray<{
82
+ repo: string;
83
+ policy: RepoPolicy;
84
+ }>, options?: {
85
+ fillOnly?: boolean;
86
+ }): Promise<void>;
@@ -0,0 +1,263 @@
1
+ /**
2
+ * `policy get|set|reset --repo owner/repo` (#1953): the per-repo contribution
3
+ * policy record, and the vet-time write that fills it in.
4
+ *
5
+ * `get` only reads. `set` and `reset` refuse unattended runs: a record the
6
+ * user sets is trusted over vet's reading of the repo docs, so nobody but the
7
+ * user writes one. There is no MCP setter on purpose.
8
+ */
9
+ import { getStateManager, maybeCheckpoint, warn, errorMessage } from '../core/index.js';
10
+ import { ValidationError, assertAttended } from '../core/errors.js';
11
+ import { AI_POLICIES, CLA_POLICIES, COMMIT_RULES, PR_GATES, effectivePolicy, fencePolicyText, isBlocklisted, isUnreadable, isUserReviewed, quote, isSamePolicy, storedPolicy, unknownFields, summarizePolicy, } from '../core/repo-policy.js';
12
+ import { validateRepoIdentifier } from './validation.js';
13
+ const MODULE = 'policy';
14
+ function oneOf(value, allowed, flag) {
15
+ if (value === undefined)
16
+ return undefined;
17
+ if (!allowed.includes(value)) {
18
+ throw new ValidationError(`Invalid ${flag} "${value}". Expected one of: ${allowed.join(', ')}.`);
19
+ }
20
+ return value;
21
+ }
22
+ function parseCommitRules(value) {
23
+ if (value === undefined)
24
+ return undefined;
25
+ const rules = value
26
+ .split(',')
27
+ .map((r) => r.trim())
28
+ .filter((r) => r !== '');
29
+ for (const rule of rules)
30
+ oneOf(rule, COMMIT_RULES, '--commit-rules entry');
31
+ return [...new Set(rules)];
32
+ }
33
+ function getOutput(repo) {
34
+ const state = getStateManager().getState();
35
+ const policy = effectivePolicy(state, repo);
36
+ if (!policy)
37
+ return { repo, policy: null };
38
+ return {
39
+ repo,
40
+ policy: {
41
+ ...summarizePolicy(policy),
42
+ updatedAt: policy.updatedAt,
43
+ blocklisted: isBlocklisted(state, repo),
44
+ ...fencePolicyText(repo, policy),
45
+ },
46
+ };
47
+ }
48
+ /** Read the policy that applies to `repo`. Untrusted text comes back fenced. */
49
+ export function runPolicyGet(options) {
50
+ validateRepoIdentifier(options.repo);
51
+ return Promise.resolve(getOutput(options.repo));
52
+ }
53
+ function parseMax(value) {
54
+ if (value === undefined)
55
+ return undefined;
56
+ if (!Number.isSafeInteger(value) || value < 0) {
57
+ throw new ValidationError(`Invalid --max-open-ai-prs "${value}". Expected a whole number (0 clears it).`);
58
+ }
59
+ return value;
60
+ }
61
+ /** The fields `options` sets; an absent flag leaves the stored value. */
62
+ function changes(options) {
63
+ const fields = {
64
+ aiPolicy: oneOf(options.aiPolicy, AI_POLICIES, '--ai-policy'),
65
+ cla: oneOf(options.cla, CLA_POLICIES, '--cla'),
66
+ prGate: oneOf(options.prGate, PR_GATES, '--pr-gate'),
67
+ commitRules: parseCommitRules(options.commitRules),
68
+ maxOpenAiPRs: parseMax(options.maxOpenAiPRs),
69
+ disclosureText: options.disclosureText === undefined ? undefined : quote(options.disclosureText),
70
+ };
71
+ const entries = Object.entries(fields);
72
+ return Object.fromEntries(entries.filter(([, v]) => v !== undefined));
73
+ }
74
+ function applySet(current, options, now) {
75
+ const merged = { ...current, ...changes(options) };
76
+ const source = options.source === undefined ? [] : [{ file: 'user', quotedLine: quote(options.source) }];
77
+ const { maxOpenAiPRs, disclosureText, ...rest } = merged;
78
+ return {
79
+ ...rest,
80
+ // 0 and '' clear these.
81
+ ...(maxOpenAiPRs !== undefined && maxOpenAiPRs > 0 && { maxOpenAiPRs }),
82
+ ...(disclosureText && { disclosureText }),
83
+ source: [...source, ...current.source].slice(0, 10),
84
+ reviewedByUser: true,
85
+ updatedAt: now,
86
+ };
87
+ }
88
+ /**
89
+ * The stored record `set` merges over, or null. Refuses two cases where a merge
90
+ * would record something the user never looked at: an entry this release
91
+ * cannot parse (a newer release wrote it; merging would replace it with
92
+ * defaults), and an unreviewed vet reading edited without `--ai-policy` (one
93
+ * field edited would mark the heuristic's AI reading as reviewed).
94
+ */
95
+ function storedRecordToEdit(state, options) {
96
+ if (isUnreadable(state, options.repo)) {
97
+ throw new ValidationError(`The stored policy for ${options.repo} was written by a newer oss-autopilot release and cannot be edited here. ` +
98
+ `Update, or delete it with policy reset --repo ${options.repo} and set it again.`);
99
+ }
100
+ const stored = storedPolicy(state, options.repo);
101
+ if (stored && !stored.reviewedByUser && options.aiPolicy === undefined) {
102
+ throw new ValidationError(`The stored policy for ${options.repo} was read from the repo docs (aiPolicy: ${stored.aiPolicy}) and nobody has ` +
103
+ 'reviewed it. Pass --ai-policy with the value you confirmed, so setting another field does not approve that reading.');
104
+ }
105
+ return stored;
106
+ }
107
+ /**
108
+ * An unreviewed stored record without the derived commit rules, AI-PR limit
109
+ * and PR gate (reset to unknown) the user did not pass: confirming `--ai-policy` must not mark those as
110
+ * reviewed. A record the user set is returned as is.
111
+ */
112
+ function withoutUnseenFields(stored, options) {
113
+ if (stored.reviewedByUser)
114
+ return stored;
115
+ const { maxOpenAiPRs, commitRules, ...rest } = stored;
116
+ return {
117
+ ...rest,
118
+ commitRules: options.commitRules === undefined ? [] : commitRules,
119
+ prGate: options.prGate === undefined ? 'unknown' : rest.prGate,
120
+ ...(options.maxOpenAiPRs !== undefined && maxOpenAiPRs !== undefined && { maxOpenAiPRs }),
121
+ };
122
+ }
123
+ /**
124
+ * Record the user's policy for `repo`, merged over what is stored. Refused
125
+ * unattended, and the result is `reviewedByUser: true`, so vet never
126
+ * overwrites it. It cannot lift a `config.aiPolicyBlocklist` ban.
127
+ */
128
+ export async function runPolicySet(options) {
129
+ validateRepoIdentifier(options.repo);
130
+ assertAttended('set a repo contribution policy');
131
+ const sm = getStateManager();
132
+ const stored = storedRecordToEdit(sm.getState(), options);
133
+ const date = new Date();
134
+ const now = date.toISOString();
135
+ const current = (stored && withoutUnseenFields(stored, options)) ?? {
136
+ aiPolicy: 'unknown',
137
+ cla: 'unknown',
138
+ commitRules: [],
139
+ prGate: 'unknown',
140
+ source: [],
141
+ reviewedByUser: true,
142
+ updatedAt: now,
143
+ };
144
+ // Keep fields a newer release added; the known ones come from the merge.
145
+ const next = { ...unknownFields(sm.getState(), options.repo), ...applySet(current, options, now) };
146
+ const blocklist = blocklistUpdate(sm.getState().config.aiPolicyBlocklist ?? [], options);
147
+ const persist = () => {
148
+ sm.setRepoPolicy(options.repo, next);
149
+ if (blocklist)
150
+ sm.updateConfig({ aiPolicyBlocklist: blocklist.list });
151
+ };
152
+ persist();
153
+ const gistSyncWarning = await maybeCheckpoint(sm, MODULE, persist);
154
+ return {
155
+ ...getOutput(options.repo),
156
+ ...(blocklist && { blocklistChange: blocklist.change }),
157
+ ...(gistSyncWarning && { gistSyncWarning }),
158
+ };
159
+ }
160
+ /**
161
+ * The blocklist after `--ai-policy`, or null when it does not change. Appends
162
+ * to the stored list (never replaces it); removal is case-insensitive. Without
163
+ * `--ai-policy` the list is left alone, and so does `policy reset`.
164
+ */
165
+ function blocklistUpdate(current, options) {
166
+ if (options.aiPolicy === undefined)
167
+ return null;
168
+ const lower = options.repo.toLowerCase();
169
+ const isListed = current.some((r) => r.toLowerCase() === lower);
170
+ if (options.aiPolicy === 'banned')
171
+ return isListed ? null : { list: [...current, options.repo], change: 'added' };
172
+ if (!isListed)
173
+ return null;
174
+ return { list: current.filter((r) => r.toLowerCase() !== lower), change: 'removed' };
175
+ }
176
+ /**
177
+ * Delete the stored record for `repo`. Refused unattended: deleting a ban the
178
+ * user recorded relaxes it. `config.aiPolicyBlocklist` is left as is.
179
+ */
180
+ export async function runPolicyReset(options) {
181
+ validateRepoIdentifier(options.repo);
182
+ assertAttended('reset a repo contribution policy');
183
+ const sm = getStateManager();
184
+ const hasRecord = sm.getState().repoPolicies?.[options.repo.toLowerCase()] !== undefined;
185
+ if (!hasRecord)
186
+ return { repo: options.repo, deleted: false };
187
+ sm.setRepoPolicy(options.repo, null);
188
+ const gistSyncWarning = await maybeCheckpoint(sm, MODULE, () => sm.setRepoPolicy(options.repo, null));
189
+ return { repo: options.repo, deleted: true, ...(gistSyncWarning && { gistSyncWarning }) };
190
+ }
191
+ /**
192
+ * Store what vet read from the repo docs, unreviewed. Never replaces a record
193
+ * the user set, and skips the write when nothing changed. A failure is logged,
194
+ * never thrown: recording the policy must not fail the vet.
195
+ */
196
+ export async function recordVetPolicy(repo, derived) {
197
+ await recordVetPolicies([{ repo, policy: derived }]);
198
+ }
199
+ /**
200
+ * {@link recordVetPolicy} for several repos, with one Gist checkpoint. With
201
+ * `fillOnly` (vet-list, which reads only scout's CONTRIBUTING text) a stored
202
+ * record is replaced only by a ban: a narrower reading must not overwrite one
203
+ * vet took from more docs.
204
+ */
205
+ export async function recordVetPolicies(readings, options = {}) {
206
+ try {
207
+ await writeVetPolicies(readings, options.fillOnly === true);
208
+ }
209
+ catch (error) {
210
+ const repos = readings.map((r) => r.repo).join(', ');
211
+ warn(MODULE, `Could not record the contribution policy for ${repos}: ${errorMessage(error)}`);
212
+ }
213
+ }
214
+ async function writeVetPolicies(readings, isFillOnly) {
215
+ const sm = getStateManager();
216
+ sm.reloadIfChanged();
217
+ const perRepo = onePerRepo(readings);
218
+ // Re-checked on every run, so a Gist conflict replay judges against the fresh baseline.
219
+ let written = 0;
220
+ const write = () => {
221
+ written = 0;
222
+ for (const { repo, policy } of perRepo) {
223
+ if (!shouldWrite(repo, policy, isFillOnly))
224
+ continue;
225
+ sm.setRepoPolicy(repo, policy);
226
+ written++;
227
+ }
228
+ };
229
+ write();
230
+ if (written > 0)
231
+ await maybeCheckpoint(sm, MODULE, write);
232
+ }
233
+ /** One reading per repo (case-insensitive); a ban wins over any other reading of the same repo. */
234
+ function onePerRepo(readings) {
235
+ const kept = [];
236
+ const indexByRepo = new Map();
237
+ for (const reading of readings) {
238
+ const index = indexByRepo.get(reading.repo.toLowerCase());
239
+ if (index === undefined) {
240
+ indexByRepo.set(reading.repo.toLowerCase(), kept.length);
241
+ kept.push(reading);
242
+ continue;
243
+ }
244
+ if (reading.policy.aiPolicy === 'banned')
245
+ kept[index] = reading;
246
+ }
247
+ return kept;
248
+ }
249
+ function shouldWrite(repo, derived, isFillOnly) {
250
+ const state = getStateManager().getState();
251
+ // Never replace the user's record or one a newer release wrote.
252
+ if (isUserReviewed(state, repo) || isUnreadable(state, repo))
253
+ return false;
254
+ const stored = storedPolicy(state, repo);
255
+ if (!stored)
256
+ return true;
257
+ if (isSamePolicy(stored, derived))
258
+ return false;
259
+ // A recorded ban stays until the user says otherwise: a later reading that misses it does not lift it.
260
+ if (stored.aiPolicy === 'banned')
261
+ return derived.aiPolicy === 'banned';
262
+ return !isFillOnly || derived.aiPolicy === 'banned';
263
+ }