@oss-autopilot/core 3.42.5 → 3.44.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 (192) hide show
  1. package/dist/cli-pre-action.js +8 -3
  2. package/dist/cli-registry.js +428 -27
  3. package/dist/cli.bundle.cjs +212 -156
  4. package/dist/commands/check-integration.js +5 -1
  5. package/dist/commands/cleanup.d.ts +80 -0
  6. package/dist/commands/cleanup.js +334 -0
  7. package/dist/commands/comments.d.ts +14 -1
  8. package/dist/commands/comments.js +17 -5
  9. package/dist/commands/config.d.ts +2 -0
  10. package/dist/commands/config.js +63 -6
  11. package/dist/commands/daily-dismiss-filter.d.ts +7 -0
  12. package/dist/commands/daily-dismiss-filter.js +17 -1
  13. package/dist/commands/daily-ledger.d.ts +150 -0
  14. package/dist/commands/daily-ledger.js +248 -0
  15. package/dist/commands/daily-recent-prs.d.ts +26 -0
  16. package/dist/commands/daily-recent-prs.js +55 -0
  17. package/dist/commands/daily-render.d.ts +2 -1
  18. package/dist/commands/daily-render.js +4 -1
  19. package/dist/commands/daily.d.ts +5 -1
  20. package/dist/commands/daily.js +83 -93
  21. package/dist/commands/dashboard-cache.d.ts +2 -0
  22. package/dist/commands/dashboard-cache.js +33 -8
  23. package/dist/commands/dashboard-data.js +113 -69
  24. package/dist/commands/dashboard-gist-sync.js +3 -1
  25. package/dist/commands/dashboard-lifecycle.d.ts +36 -8
  26. package/dist/commands/dashboard-lifecycle.js +132 -39
  27. package/dist/commands/dashboard-process.d.ts +49 -1
  28. package/dist/commands/dashboard-process.js +111 -12
  29. package/dist/commands/dashboard-server.js +89 -23
  30. package/dist/commands/detect-formatters.js +1 -0
  31. package/dist/commands/dismiss.js +11 -7
  32. package/dist/commands/doctor.d.ts +15 -1
  33. package/dist/commands/doctor.js +66 -5
  34. package/dist/commands/draft.d.ts +77 -0
  35. package/dist/commands/draft.js +218 -0
  36. package/dist/commands/eval.js +1 -0
  37. package/dist/commands/fork-prune.d.ts +58 -0
  38. package/dist/commands/fork-prune.js +247 -0
  39. package/dist/commands/guidelines.d.ts +69 -2
  40. package/dist/commands/guidelines.js +158 -14
  41. package/dist/commands/index.d.ts +29 -4
  42. package/dist/commands/index.js +20 -3
  43. package/dist/commands/issue-thread.d.ts +46 -0
  44. package/dist/commands/issue-thread.js +123 -0
  45. package/dist/commands/ledger-backfill.d.ts +9 -0
  46. package/dist/commands/ledger-backfill.js +44 -1
  47. package/dist/commands/list-mark-done.d.ts +2 -1
  48. package/dist/commands/list-mark-done.js +3 -1
  49. package/dist/commands/list-move-tier.d.ts +2 -1
  50. package/dist/commands/list-move-tier.js +3 -1
  51. package/dist/commands/local-repos.js +10 -5
  52. package/dist/commands/locate-issue-list.d.ts +40 -17
  53. package/dist/commands/locate-issue-list.js +148 -88
  54. package/dist/commands/move.js +7 -1
  55. package/dist/commands/overnight-handoff.d.ts +17 -7
  56. package/dist/commands/overnight-handoff.js +36 -14
  57. package/dist/commands/overnight-push-prep.d.ts +14 -8
  58. package/dist/commands/overnight-push-prep.js +107 -35
  59. package/dist/commands/overnight-tool-rules.d.ts +54 -0
  60. package/dist/commands/overnight-tool-rules.js +217 -0
  61. package/dist/commands/overnight.d.ts +5 -6
  62. package/dist/commands/overnight.js +61 -140
  63. package/dist/commands/parse-list.js +7 -1
  64. package/dist/commands/policy.d.ts +90 -0
  65. package/dist/commands/policy.js +276 -0
  66. package/dist/commands/pr-create.d.ts +48 -0
  67. package/dist/commands/pr-create.js +200 -0
  68. package/dist/commands/pr-preflight.d.ts +69 -0
  69. package/dist/commands/pr-preflight.js +348 -0
  70. package/dist/commands/repo-vet.d.ts +9 -0
  71. package/dist/commands/repo-vet.js +36 -11
  72. package/dist/commands/scout-bridge.js +18 -8
  73. package/dist/commands/search.js +7 -0
  74. package/dist/commands/setup.d.ts +3 -3
  75. package/dist/commands/setup.js +160 -48
  76. package/dist/commands/skip-add.js +10 -1
  77. package/dist/commands/startup.d.ts +12 -3
  78. package/dist/commands/startup.js +82 -49
  79. package/dist/commands/state-cmd.d.ts +2 -0
  80. package/dist/commands/state-cmd.js +5 -1
  81. package/dist/commands/stats.js +1 -0
  82. package/dist/commands/status.js +6 -0
  83. package/dist/commands/strategy.js +1 -0
  84. package/dist/commands/validation.d.ts +5 -0
  85. package/dist/commands/validation.js +5 -0
  86. package/dist/commands/vet-list.d.ts +6 -0
  87. package/dist/commands/vet-list.js +26 -1
  88. package/dist/commands/vet.d.ts +20 -0
  89. package/dist/commands/vet.js +133 -2
  90. package/dist/commands/work.d.ts +4 -0
  91. package/dist/commands/work.js +34 -11
  92. package/dist/core/__fixtures__/prompt-injection-payloads.js +31 -0
  93. package/dist/core/anti-llm-policy.d.ts +3 -0
  94. package/dist/core/anti-llm-policy.js +3 -0
  95. package/dist/core/auth.js +2 -0
  96. package/dist/core/ci-analysis.d.ts +7 -2
  97. package/dist/core/ci-analysis.js +76 -21
  98. package/dist/core/commit-date.d.ts +45 -0
  99. package/dist/core/commit-date.js +45 -0
  100. package/dist/core/compliance-score.d.ts +3 -0
  101. package/dist/core/compliance-score.js +13 -9
  102. package/dist/core/config-registry.d.ts +27 -2
  103. package/dist/core/config-registry.js +94 -7
  104. package/dist/core/contributing.d.ts +2 -3
  105. package/dist/core/contributing.js +2 -3
  106. package/dist/core/daily-logic.d.ts +30 -5
  107. package/dist/core/daily-logic.js +68 -19
  108. package/dist/core/errors.d.ts +37 -3
  109. package/dist/core/errors.js +54 -5
  110. package/dist/core/fork-prune.d.ts +149 -0
  111. package/dist/core/fork-prune.js +333 -0
  112. package/dist/core/gist-health.d.ts +15 -3
  113. package/dist/core/gist-health.js +8 -0
  114. package/dist/core/gist-state-store.d.ts +24 -4
  115. package/dist/core/gist-state-store.js +98 -51
  116. package/dist/core/github-stats.d.ts +110 -16
  117. package/dist/core/github-stats.js +295 -110
  118. package/dist/core/http-cache.d.ts +0 -10
  119. package/dist/core/http-cache.js +0 -19
  120. package/dist/core/index.d.ts +13 -6
  121. package/dist/core/index.js +16 -6
  122. package/dist/core/issue-conversation.d.ts +8 -2
  123. package/dist/core/issue-conversation.js +31 -12
  124. package/dist/core/local-config.d.ts +95 -0
  125. package/dist/core/local-config.js +270 -0
  126. package/dist/core/merged-pr-notes.d.ts +2 -2
  127. package/dist/core/pacing.d.ts +41 -0
  128. package/dist/core/pacing.js +115 -0
  129. package/dist/core/pagination.d.ts +55 -0
  130. package/dist/core/pagination.js +59 -0
  131. package/dist/core/paths.d.ts +7 -0
  132. package/dist/core/paths.js +9 -0
  133. package/dist/core/pr-assembly.d.ts +2 -0
  134. package/dist/core/pr-assembly.js +6 -2
  135. package/dist/core/pr-graphql.d.ts +53 -4
  136. package/dist/core/pr-graphql.js +87 -14
  137. package/dist/core/pr-monitor.d.ts +35 -12
  138. package/dist/core/pr-monitor.js +110 -26
  139. package/dist/core/pr-preflight.d.ts +154 -0
  140. package/dist/core/pr-preflight.js +753 -0
  141. package/dist/core/pr-quality-rubric.d.ts +0 -6
  142. package/dist/core/pr-quality-rubric.js +0 -8
  143. package/dist/core/pr-template.d.ts +2 -0
  144. package/dist/core/pr-template.js +5 -1
  145. package/dist/core/prose-script.d.ts +72 -0
  146. package/dist/core/prose-script.js +223 -0
  147. package/dist/core/repo-policy.d.ts +111 -0
  148. package/dist/core/repo-policy.js +428 -0
  149. package/dist/core/repo-score-manager.d.ts +66 -0
  150. package/dist/core/repo-score-manager.js +140 -1
  151. package/dist/core/review-analysis.d.ts +49 -21
  152. package/dist/core/review-analysis.js +89 -15
  153. package/dist/core/reviewed-prs-fetch.js +11 -29
  154. package/dist/core/reviewed-prs.js +8 -15
  155. package/dist/core/stale-data.d.ts +78 -0
  156. package/dist/core/stale-data.js +153 -0
  157. package/dist/core/state-persistence.d.ts +62 -27
  158. package/dist/core/state-persistence.js +338 -119
  159. package/dist/core/state-schema.d.ts +152 -210
  160. package/dist/core/state-schema.js +232 -80
  161. package/dist/core/state.d.ts +81 -8
  162. package/dist/core/state.js +239 -46
  163. package/dist/core/status-determination.js +32 -12
  164. package/dist/core/strategy.js +3 -1
  165. package/dist/core/types.d.ts +22 -1
  166. package/dist/core/types.js +1 -0
  167. package/dist/core/untrusted-content.d.ts +30 -11
  168. package/dist/core/untrusted-content.js +95 -42
  169. package/dist/core/urls.d.ts +33 -0
  170. package/dist/core/urls.js +94 -0
  171. package/dist/dashboard/assets/chart-panel-B-nLVgzQ.js +3 -0
  172. package/dist/dashboard/assets/index-5IvMGokL.js +55 -0
  173. package/dist/dashboard/index.html +1 -1
  174. package/dist/formatters/json.d.ts +432 -10
  175. package/dist/formatters/json.js +156 -1
  176. package/package.json +6 -6
  177. package/dist/core/ci-enforced-tools.d.ts +0 -35
  178. package/dist/core/ci-enforced-tools.js +0 -109
  179. package/dist/core/comment-decision.d.ts +0 -79
  180. package/dist/core/comment-decision.js +0 -82
  181. package/dist/core/extraction-categories.d.ts +0 -55
  182. package/dist/core/extraction-categories.js +0 -108
  183. package/dist/core/follow-up-history.d.ts +0 -40
  184. package/dist/core/follow-up-history.js +0 -71
  185. package/dist/core/issue-effort.d.ts +0 -29
  186. package/dist/core/issue-effort.js +0 -47
  187. package/dist/core/maintainer-hints.d.ts +0 -23
  188. package/dist/core/maintainer-hints.js +0 -36
  189. package/dist/core/workflow-state.d.ts +0 -56
  190. package/dist/core/workflow-state.js +0 -101
  191. package/dist/dashboard/assets/chart-panel-DPKNBUts.js +0 -3
  192. package/dist/dashboard/assets/index-B25bZOYX.js +0 -55
@@ -0,0 +1,48 @@
1
+ /**
2
+ * pr-create command (#2085): the one way the plugin opens a pull request.
3
+ * It fetches the target branch and runs the pr-preflight checks on the staged
4
+ * title and body, so the description and WIP-title gate always runs. It
5
+ * refuses when a GitHub read failed (a blind guard blocks), on any `fail`, and
6
+ * on any `warn` the user has not accepted. It then checks that GitHub holds
7
+ * exactly the commit it checked and opens the PR with the same title, body
8
+ * and draft value. A GitHub write: refused during an unattended run.
9
+ */
10
+ import type { PreflightCheck, PreflightVerdict } from '../core/pr-preflight.js';
11
+ export interface PrCreateOptions {
12
+ /** Local clone or worktree whose checked-out branch is the PR's head; defaults to the current directory. */
13
+ dir?: string;
14
+ /** Issue URL, or an issue number in the upstream repository. */
15
+ issue?: string;
16
+ /** Branch the PR targets; defaults to the upstream default branch. */
17
+ base?: string;
18
+ /** `owner:branch` for a fork, or `branch`; the branch must be the one checked out in `dir`. */
19
+ head: string;
20
+ title: string;
21
+ body: string;
22
+ /** The repo's PR template text; body lines copied from it are not a description. */
23
+ template?: string;
24
+ draft: boolean;
25
+ allowScriptMismatch?: boolean;
26
+ /** `<id>:<state>` keys the user agreed to (see acceptKey): any `warn`, and a `competing-work` fail when they chose to open anyway. */
27
+ accept?: string[];
28
+ /** The target repo the user was shown; refused when the checks resolve another (the MCP form, #2085). */
29
+ repo?: string;
30
+ }
31
+ export interface PrCreateOutput {
32
+ prUrl: string;
33
+ number: number;
34
+ repo: string;
35
+ base: string;
36
+ head: string;
37
+ draft: boolean;
38
+ /** The create call failed but an open PR from this head at the checked commit was found. */
39
+ alreadyExisted: boolean;
40
+ verdict: PreflightVerdict;
41
+ /** The `<id>:<state>` keys of the warn and fail checks the user accepted. */
42
+ accepted: string[];
43
+ checks: PreflightCheck[];
44
+ }
45
+ /** Check the staged PR and the pushed commit, then open the PR with exactly the checked title, body and draft value. */
46
+ export declare function runPrCreate(options: PrCreateOptions): Promise<PrCreateOutput>;
47
+ /** Text mode: the new PR, then any check that warned. */
48
+ export declare function printPrCreate(data: PrCreateOutput): void;
@@ -0,0 +1,200 @@
1
+ /**
2
+ * pr-create command (#2085): the one way the plugin opens a pull request.
3
+ * It fetches the target branch and runs the pr-preflight checks on the staged
4
+ * title and body, so the description and WIP-title gate always runs. It
5
+ * refuses when a GitHub read failed (a blind guard blocks), on any `fail`, and
6
+ * on any `warn` the user has not accepted. It then checks that GitHub holds
7
+ * exactly the commit it checked and opens the PR with the same title, body
8
+ * and draft value. A GitHub write: refused during an unattended run.
9
+ */
10
+ import { errorMessage, getHttpStatusCode, getOctokit, requireGitHubToken, splitRepo } from '../core/index.js';
11
+ import { ValidationError, assertAttended } from '../core/errors.js';
12
+ import { parseRemoteOwner } from './overnight-push-prep.js';
13
+ import { runPreflightOnText } from './pr-preflight.js';
14
+ import { BRANCH_NAME_PATTERN, validateMessage } from './validation.js';
15
+ const HEAD_PATTERN = /^(?:([\w-]+):)?([^:]+)$/;
16
+ /** The one check whose `fail` the user may accept: they checked the competing work and chose to open anyway. */
17
+ const ACCEPTABLE_FAIL = 'competing-work';
18
+ const fullName = (r) => `${r.owner}/${r.repo}`;
19
+ const isSameName = (a, b) => a.toLowerCase() === b.toLowerCase();
20
+ /** Reads that failed or never ran. Each one leaves a guard blind, so each one blocks. */
21
+ function blindSpots(facts) {
22
+ const reads = [
23
+ ['GitHub', facts.networkSkip],
24
+ ['the repository', facts.githubError],
25
+ ['the issue', facts.issueError],
26
+ ['the open-PR cap', facts.capError],
27
+ ['the issue labels', facts.labelsError],
28
+ ['the target branch (fetch)', facts.fetchError],
29
+ ];
30
+ const spots = reads.filter(([, error]) => error !== null).map(([what, error]) => `could not read ${what}: ${error}`);
31
+ if (facts.mergeBase === null)
32
+ spots.push('no branch point with the target branch, so the commits were not checked');
33
+ if (facts.issueUrl !== null && facts.login === null) {
34
+ spots.push('githubUsername is not configured, so the open-PR cap was not checked; run setup');
35
+ }
36
+ return spots;
37
+ }
38
+ /**
39
+ * What the user accepts: `<id>:<state>`, where the state is the competing-work
40
+ * verdict (`own-open-pr`, `at-risk`, `taken`, `closed`) or the check's status.
41
+ * An acceptance covers only the state the user saw.
42
+ */
43
+ function acceptKey(check) {
44
+ const verdict = check.details?.verdict;
45
+ return `${check.id}:${typeof verdict === 'string' ? verdict : check.status}`;
46
+ }
47
+ /** The accepted `id:state` keys; throws naming every check that is neither passing nor accepted. */
48
+ function gateChecks(checks, accept) {
49
+ const isAccepted = (c) => accept.has(acceptKey(c)) && (c.status === 'warn' || (c.status === 'fail' && c.id === ACCEPTABLE_FAIL));
50
+ const open = checks.filter((c) => (c.status === 'fail' || c.status === 'warn') && !isAccepted(c));
51
+ if (open.length > 0) {
52
+ const listed = open.map((c) => `${c.id} (${c.status}): ${c.summary} [${acceptKey(c)}]`).join('; ');
53
+ throw new ValidationError(`Preflight did not pass, no PR was created: ${listed}. A warn, or a ${ACCEPTABLE_FAIL} fail, needs the user's agreement; then pass --accept with the key in brackets`);
54
+ }
55
+ return checks.filter((c) => isAccepted(c)).map((c) => acceptKey(c));
56
+ }
57
+ /** The repo that holds the head branch: the target for a same-repo PR, else the user's fork. */
58
+ function headRepo(owner, target, login, remotes) {
59
+ if (isSameName(owner, target.owner))
60
+ return target;
61
+ if (login === null || !isSameName(owner, login)) {
62
+ throw new ValidationError(`The head owner ${owner} is neither you (${login ?? 'no username set'}) nor ${target.owner}`);
63
+ }
64
+ const fork = remotes.map((r) => parseRemoteOwner(r.url)).find((p) => p !== null && isSameName(p.owner, owner));
65
+ return { owner, repo: fork?.repo ?? target.repo };
66
+ }
67
+ /** GitHub opens a cross-repo PR from a fork of the target; refuse any other source repo. */
68
+ async function assertForkOf(octokit, source, target) {
69
+ if (isSameName(fullName(source), fullName(target)))
70
+ return;
71
+ const { data } = await octokit.repos.get({ ...source });
72
+ const parents = [data.parent?.full_name, data.source?.full_name];
73
+ if (parents.every((name) => name === undefined || !isSameName(name, fullName(target)))) {
74
+ throw new ValidationError(`${fullName(source)} is not a fork of ${fullName(target)}; no PR was created`);
75
+ }
76
+ }
77
+ /** Refuse unless GitHub's branch is at the commit the checks ran on. */
78
+ async function assertPushed(octokit, source, branch, sha) {
79
+ let pushed = null;
80
+ try {
81
+ const { data } = await octokit.repos.getBranch({ ...source, branch });
82
+ pushed = data.commit.sha;
83
+ }
84
+ catch (err) {
85
+ if (getHttpStatusCode(err) !== 404)
86
+ throw err;
87
+ }
88
+ if (pushed !== sha) {
89
+ throw new ValidationError(`${fullName(source)}:${branch} is at ${pushed?.slice(0, 7) ?? 'nothing'}, not the checked ${sha.slice(0, 7)}: push first; no PR was created`);
90
+ }
91
+ }
92
+ /** The created PR is from the checked repo at the checked commit; else say loudly that a PR exists and differs. */
93
+ function assertOpenedAsChecked(data, request) {
94
+ const from = data.head.repo?.full_name ?? 'an unknown repo';
95
+ if (data.head.sha === request.sha && isSameName(from, fullName(request.source)))
96
+ return;
97
+ throw new Error(`PR #${data.number} was created at ${data.html_url}, but GitHub opened it from ${from} at ${data.head.sha.slice(0, 7)}, ` +
98
+ `not the checked ${fullName(request.source)} at ${request.sha.slice(0, 7)}. The PR exists: check it now and close it if it is wrong`);
99
+ }
100
+ /** The open PR is this one: the user's, with exactly the checked title, body and draft state. */
101
+ function isThisPr(pr, request) {
102
+ const author = pr.user?.login;
103
+ const isUsers = request.login !== null && author !== undefined && isSameName(author, request.login);
104
+ const isSameText = pr.title === request.title && (pr.body ?? '') === request.body;
105
+ return isUsers && isSameText && pr.draft === request.draft;
106
+ }
107
+ /** After a failed create: the open PR from this head at the checked commit when it is this one; else throws naming what was found. */
108
+ async function existingPr(octokit, request, createError) {
109
+ const { target, head, base, sha } = request;
110
+ const failed = `Creating the PR failed (${errorMessage(createError)})`;
111
+ let open;
112
+ try {
113
+ ({ data: open } = await octokit.pulls.list({ ...target, head, base, state: 'open' }));
114
+ }
115
+ catch (lookupError) {
116
+ throw new Error(`${failed} and the lookup for an open PR from ${head} failed too (${errorMessage(lookupError)}); a PR may exist on ${fullName(target)}: check before retrying`, { cause: lookupError });
117
+ }
118
+ const found = open.find((pr) => pr.head.sha === sha);
119
+ if (!found) {
120
+ throw new Error(`${failed} and no open PR from ${head} at ${sha.slice(0, 7)} was found on ${fullName(target)}`, {
121
+ cause: createError,
122
+ });
123
+ }
124
+ if (!isThisPr(found, request)) {
125
+ throw new Error(`${failed}. PR #${found.number} (${found.html_url}) is open from ${head} at this commit, but its author, title, body or draft state differ from what was checked`, { cause: createError });
126
+ }
127
+ return { prUrl: found.html_url, number: found.number, draft: found.draft === true, alreadyExisted: true };
128
+ }
129
+ /** Open the PR, or find it when the call failed after GitHub made it (already exists, timeout, 5xx). */
130
+ async function createOrFind(octokit, request) {
131
+ assertAttended('create a pull request');
132
+ const { target, source, title, body, head, base, draft } = request;
133
+ const crossRepo = isSameName(fullName(source), fullName(target)) ? {} : { head_repo: fullName(source) };
134
+ let data;
135
+ try {
136
+ ({ data } = await octokit.pulls.create({ ...target, ...crossRepo, title, body, head, base, draft }));
137
+ }
138
+ catch (err) {
139
+ return existingPr(octokit, request, err);
140
+ }
141
+ assertOpenedAsChecked(data, request);
142
+ return { prUrl: data.html_url, number: data.number, draft: data.draft === true, alreadyExisted: false };
143
+ }
144
+ /** The trimmed title and the head's owner and branch; throws on what can be refused before any read. */
145
+ function parseRequest(options) {
146
+ const title = options.title.trim();
147
+ if (title === '')
148
+ throw new ValidationError('The PR title is empty');
149
+ validateMessage(title);
150
+ validateMessage(options.body);
151
+ const [, owner, headBranch = ''] = HEAD_PATTERN.exec(options.head) ?? [];
152
+ if (!BRANCH_NAME_PATTERN.test(headBranch))
153
+ throw new ValidationError(`Invalid head: ${options.head}`);
154
+ return { title, owner, headBranch };
155
+ }
156
+ /** The checked target and commit; throws when a read failed, or when it is not the repo or branch the caller named. */
157
+ function checkedTarget(run, options, headBranch) {
158
+ const blind = blindSpots(run.facts);
159
+ if (blind.length > 0)
160
+ throw new ValidationError(`No PR was created: ${blind.join('; ')}`);
161
+ const { repo, base, branch, dir } = run.output;
162
+ if (!repo || !base || !run.headSha)
163
+ throw new ValidationError('Could not resolve the target repository, base branch and commit');
164
+ if (options.repo !== undefined && !isSameName(options.repo, repo)) {
165
+ throw new ValidationError(`The checks resolved ${repo}, not ${options.repo}; no PR was created`);
166
+ }
167
+ // The checks ran on the checked-out branch; a PR from any other branch would not be what was checked.
168
+ if (branch !== headBranch) {
169
+ throw new ValidationError(`The head branch ${headBranch} is not the branch checked out in ${dir} (${branch ?? 'detached HEAD'}); no PR was created`);
170
+ }
171
+ return { repo, base, sha: run.headSha };
172
+ }
173
+ /** Check the staged PR and the pushed commit, then open the PR with exactly the checked title, body and draft value. */
174
+ export async function runPrCreate(options) {
175
+ assertAttended('create a pull request');
176
+ const { title, owner, headBranch } = parseRequest(options);
177
+ const octokit = getOctokit(requireGitHubToken());
178
+ const run = await runPreflightOnText({ ...options, fetch: true, local: false }, { prTitle: title, prBody: options.body, prTemplate: options.template ?? null });
179
+ const { repo, base, sha } = checkedTarget(run, options, headBranch);
180
+ const accepted = gateChecks(run.output.checks, new Set(options.accept));
181
+ const target = splitRepo(repo);
182
+ const { login } = run.facts;
183
+ const source = headRepo(owner ?? target.owner, target, login, run.remotes);
184
+ await assertForkOf(octokit, source, target);
185
+ await assertPushed(octokit, source, headBranch, sha);
186
+ const head = `${source.owner}:${headBranch}`;
187
+ const request = { body: options.body, draft: options.draft, target, source, login, title, head, base, sha };
188
+ const created = await createOrFind(octokit, request);
189
+ const { verdict, checks } = run.output;
190
+ return { ...created, head, verdict, checks, repo, base, accepted };
191
+ }
192
+ /** Text mode: the new PR, then any check that warned. */
193
+ export function printPrCreate(data) {
194
+ const kind = data.draft ? 'Draft PR' : 'PR';
195
+ console.log(`${kind} #${data.number} ${data.alreadyExisted ? 'already open' : 'created'}: ${data.prUrl}`);
196
+ for (const check of data.checks) {
197
+ if (check.status === 'warn')
198
+ console.log(` [warn] ${check.id}: ${check.summary}`);
199
+ }
200
+ }
@@ -0,0 +1,69 @@
1
+ /**
2
+ * pr-preflight command (#1952): one gate before a branch is pushed and a PR
3
+ * is opened. Gathers facts from the local clone (read-only commands) and from
4
+ * GitHub (read-only API), then runs the pure checks in core/pr-preflight.ts:
5
+ * upstream drift, base branch, head branch, working tree, competing work on
6
+ * the issue, the per-repo open-PR cap, the pacing caps, the repo policy and
7
+ * its commit rules.
8
+ *
9
+ * It only reads, so it runs in unattended mode. Without a GitHub token, or
10
+ * with `--local`, the local checks still run and the network checks come back
11
+ * `skipped`; a GitHub read that fails degrades its own check only. The one
12
+ * thing it can change is remote-tracking refs, and only when `--fetch` is
13
+ * passed; without it a stale `<remote>/<base>` is reported, not refreshed.
14
+ */
15
+ import { type PreflightCheck, type PreflightFacts, type PreflightVerdict } from '../core/pr-preflight.js';
16
+ import { type GitRemote } from './overnight-push-prep.js';
17
+ export interface PrPreflightOptions {
18
+ /** Local clone or worktree; defaults to the current directory. */
19
+ dir?: string;
20
+ /** Issue URL, or an issue number in the upstream repository. */
21
+ issue?: string;
22
+ /** Branch the PR will target; defaults to the upstream default branch. */
23
+ base?: string;
24
+ /** Run `git fetch <remote> <base>` before measuring drift. */
25
+ fetch: boolean;
26
+ /** Skip every GitHub read; for callers that only want the local numbers. */
27
+ local: boolean;
28
+ /** The staged PR body, a file in the draft directory; the disclosure rule is checked against it. */
29
+ bodyFile?: string;
30
+ /** The staged PR title, a file in the draft directory; checked for a WIP marker. */
31
+ titleFile?: string;
32
+ /** The repo's PR template, a file in the draft directory; body lines copied from it are not a description. */
33
+ templateFile?: string;
34
+ /** A script mismatch in the staged title or body warns instead of failing (#1909). */
35
+ allowScriptMismatch?: boolean;
36
+ /** The PR will be opened as a draft, which may keep a WIP title. */
37
+ draft?: boolean;
38
+ }
39
+ /** The options that are not staged files; the staged text comes separately. */
40
+ export type PreflightRunOptions = Omit<PrPreflightOptions, 'bodyFile' | 'titleFile' | 'templateFile'>;
41
+ /** The staged PR text the description and language checks read; null where none was given. */
42
+ export type StagedPrText = Pick<PreflightFacts, 'prTitle' | 'prBody' | 'prTemplate'>;
43
+ export interface PrPreflightOutput {
44
+ verdict: PreflightVerdict;
45
+ dir: string;
46
+ repo: string | null;
47
+ issueUrl: string | null;
48
+ branch: string | null;
49
+ remote: string | null;
50
+ base: string | null;
51
+ mergeBase: string | null;
52
+ ahead: number | null;
53
+ behind: number | null;
54
+ checks: PreflightCheck[];
55
+ }
56
+ /** Run every preflight check for the branch checked out in `options.dir`. */
57
+ export declare function runPrPreflight(options: PrPreflightOptions): Promise<PrPreflightOutput>;
58
+ /** What one preflight run saw: the output, the facts behind it (read errors included) and the clone's remotes. */
59
+ export interface PreflightRun {
60
+ output: PrPreflightOutput;
61
+ facts: PreflightFacts;
62
+ remotes: GitRemote[];
63
+ /** HEAD when the run started, before any check read the branch; null on an unborn branch. */
64
+ headSha: string | null;
65
+ }
66
+ /** Run every preflight check against staged text already read; `pr-create` sends exactly the text it checked (#2085). */
67
+ export declare function runPreflightOnText(options: PreflightRunOptions, staged: StagedPrText): Promise<PreflightRun>;
68
+ /** Text mode: the verdict, then one line per check. */
69
+ export declare function printPrPreflight(data: PrPreflightOutput): void;
@@ -0,0 +1,348 @@
1
+ /**
2
+ * pr-preflight command (#1952): one gate before a branch is pushed and a PR
3
+ * is opened. Gathers facts from the local clone (read-only commands) and from
4
+ * GitHub (read-only API), then runs the pure checks in core/pr-preflight.ts:
5
+ * upstream drift, base branch, head branch, working tree, competing work on
6
+ * the issue, the per-repo open-PR cap, the pacing caps, the repo policy and
7
+ * its commit rules.
8
+ *
9
+ * It only reads, so it runs in unattended mode. Without a GitHub token, or
10
+ * with `--local`, the local checks still run and the network checks come back
11
+ * `skipped`; a GitHub read that fails degrades its own check only. The one
12
+ * thing it can change is remote-tracking refs, and only when `--fetch` is
13
+ * passed; without it a stale `<remote>/<base>` is reported, not refreshed.
14
+ */
15
+ import { errorMessage, fetchIssueVerification, getGitHubTokenAsync, getHttpStatusCode, getOctokit, getStateManager, parseGitHubUrl, splitRepo, } from '../core/index.js';
16
+ import { ValidationError } from '../core/errors.js';
17
+ import { runPreflightChecks, } from '../core/pr-preflight.js';
18
+ import { git, parseRemoteOwner, parseRemotesOutput, resolvePushRemote } from './overnight-push-prep.js';
19
+ import { runRepoCap } from './repo-cap.js';
20
+ import { effectivePolicy } from '../core/repo-policy.js';
21
+ import { getPacingStatus } from '../core/pacing.js';
22
+ import { isFirstInRepo } from '../core/pick-snapshot.js';
23
+ import { BRANCH_NAME_PATTERN, ISSUE_URL_PATTERN, validateGitHubUrl, validateUrl } from './validation.js';
24
+ import { readDraft } from './draft.js';
25
+ import { readRepoScripts } from '../core/prose-script.js';
26
+ const ISSUE_NUMBER = /^#?(\d+)$/;
27
+ const MAX_OVERLAP_LINES = 20;
28
+ // ponytail: a branch with more commits than this has only its newest 200 checked against the commit rules.
29
+ const MAX_BRANCH_COMMITS = 200;
30
+ // ponytail: argv ceiling. A branch touching more files than this is checked on the first 500 only.
31
+ const MAX_PATHSPECS = 500;
32
+ /** Output of a command that may legitimately fail (missing ref, unborn HEAD); null when it does. */
33
+ function tryGit(dir, args) {
34
+ try {
35
+ return git(dir, args).trim();
36
+ }
37
+ catch {
38
+ return null;
39
+ }
40
+ }
41
+ function repoName(remote) {
42
+ const parsed = remote ? parseRemoteOwner(remote.url) : null;
43
+ return parsed ? `${parsed.owner}/${parsed.repo}` : null;
44
+ }
45
+ /** The remote for `repo` when one points at it, else `upstream`, else `origin`, else the first. */
46
+ function pickRemote(remotes, repo) {
47
+ // A remote named like an option would be read as one.
48
+ const usable = remotes.filter((r) => !r.name.startsWith('-'));
49
+ const wanted = repo?.toLowerCase();
50
+ const matching = usable.find((r) => wanted !== undefined && repoName(r)?.toLowerCase() === wanted);
51
+ const named = usable.find((r) => r.name === 'upstream') ?? usable.find((r) => r.name === 'origin');
52
+ return matching ?? named ?? usable.at(0) ?? null;
53
+ }
54
+ function issueRepo(issue) {
55
+ if (issue === undefined || ISSUE_NUMBER.test(issue))
56
+ return null;
57
+ validateUrl(issue);
58
+ validateGitHubUrl(issue, ISSUE_URL_PATTERN, 'issue');
59
+ const parsed = parseGitHubUrl(issue);
60
+ if (!parsed)
61
+ throw new ValidationError(`Not a parseable GitHub issue URL: ${issue}`);
62
+ return `${parsed.owner}/${parsed.repo}`;
63
+ }
64
+ function issueUrlFor(issue, repo) {
65
+ if (issue === undefined)
66
+ return null;
67
+ const numbered = ISSUE_NUMBER.exec(issue);
68
+ if (!numbered)
69
+ return issue;
70
+ if (!repo)
71
+ throw new ValidationError(`No GitHub remote to resolve issue ${issue} against; pass the issue URL`);
72
+ return `https://github.com/${repo}/issues/${numbered[1]}`;
73
+ }
74
+ async function branchHeadSha(octokit, repo, branch) {
75
+ try {
76
+ const { data } = await octokit.repos.getBranch({ ...splitRepo(repo), branch });
77
+ return data.commit.sha;
78
+ }
79
+ catch (err) {
80
+ if (getHttpStatusCode(err) === 404)
81
+ return null;
82
+ throw err;
83
+ }
84
+ }
85
+ async function fetchGitHubFacts(octokit, repo, base) {
86
+ const { data } = await octokit.repos.get(splitRepo(repo));
87
+ return {
88
+ defaultBranch: data.default_branch,
89
+ parent: data.parent?.full_name ?? null,
90
+ canPush: data.permissions?.push === true,
91
+ baseHeadSha: await branchHeadSha(octokit, repo, base ?? data.default_branch),
92
+ };
93
+ }
94
+ function offline(networkSkip) {
95
+ return {
96
+ networkSkip,
97
+ github: null,
98
+ issue: null,
99
+ cap: null,
100
+ githubError: null,
101
+ issueError: null,
102
+ capError: null,
103
+ issueLabels: null,
104
+ labelsError: null,
105
+ repoScripts: null,
106
+ };
107
+ }
108
+ /** The issue's label names, for a `maintainer-label` gate. */
109
+ async function fetchIssueLabels(octokit, issue) {
110
+ const { data } = await octokit.issues.get({ owner: issue.owner, repo: issue.repo, issue_number: issue.number });
111
+ return data.labels.map((label) => (typeof label === 'string' ? label : (label.name ?? ''))).filter((n) => n !== '');
112
+ }
113
+ const NOT_RUN = { value: null, error: null };
114
+ /** One GitHub read. A failure is recorded for its check; bad input (an issue that does not exist) still throws. */
115
+ async function attempt(read) {
116
+ try {
117
+ return { value: await read(), error: null };
118
+ }
119
+ catch (err) {
120
+ if (err instanceof ValidationError)
121
+ throw err;
122
+ return { value: null, error: errorMessage(err).split('\n', 1)[0] };
123
+ }
124
+ }
125
+ /** The repo's language, read only when there is staged text to compare it with (#1909). Never throws. */
126
+ async function repoScriptsFor(octokit, repo, staged) {
127
+ if (staged.prTitle === null && staged.prBody === null)
128
+ return null;
129
+ const { owner, repo: name } = splitRepo(repo);
130
+ return readRepoScripts(octokit, owner, name);
131
+ }
132
+ async function gatherNetworkFacts(target, options, login, shouldReadLabels, staged) {
133
+ const { repo, issueUrl } = target;
134
+ if (options.local)
135
+ return offline('local mode (--local)');
136
+ if (!repo)
137
+ return offline('no remote points at a GitHub repository');
138
+ const token = await getGitHubTokenAsync();
139
+ if (!token)
140
+ return offline('no GitHub token (run gh auth login or set GITHUB_TOKEN)');
141
+ const octokit = getOctokit(token);
142
+ const parsed = issueUrl ? parseGitHubUrl(issueUrl) : null;
143
+ const github = await attempt(() => fetchGitHubFacts(octokit, repo, options.base));
144
+ const issue = parsed
145
+ ? await attempt(() => fetchIssueVerification(octokit, parsed))
146
+ : NOT_RUN;
147
+ // The cap gates a new PR, so it runs only for an issue; its search needs the username.
148
+ const cap = parsed && login ? await attempt(() => runRepoCap({ repo })) : NOT_RUN;
149
+ // One more read only where the recorded policy waits for a maintainer's label (#2040).
150
+ const labels = parsed && shouldReadLabels ? await attempt(() => fetchIssueLabels(octokit, parsed)) : NOT_RUN;
151
+ return {
152
+ networkSkip: null,
153
+ github: github.value,
154
+ githubError: github.error,
155
+ issue: issue.value,
156
+ issueError: issue.error,
157
+ cap: cap.value,
158
+ capError: cap.error,
159
+ issueLabels: labels.value,
160
+ labelsError: labels.error,
161
+ repoScripts: await repoScriptsFor(octokit, repo, staged),
162
+ };
163
+ }
164
+ /** `git log --oneline` lines for commits in `mergeBase..upstream` touching files changed in `mergeBase..HEAD`. */
165
+ function overlappingCommits(dir, mergeBase, upstream) {
166
+ const files = git(dir, ['diff', '--name-only', '-z', mergeBase, 'HEAD'])
167
+ .split('\0')
168
+ .filter((file) => file !== '');
169
+ if (files.length === 0)
170
+ return [];
171
+ const range = `${mergeBase}..${upstream}`;
172
+ const limit = `--max-count=${MAX_OVERLAP_LINES}`;
173
+ const log = git(dir, [
174
+ '--literal-pathspecs',
175
+ 'log',
176
+ '--oneline',
177
+ limit,
178
+ range,
179
+ '--',
180
+ ...files.slice(0, MAX_PATHSPECS),
181
+ ]);
182
+ return log.split('\n').filter((line) => line !== '');
183
+ }
184
+ /** Full messages of the branch's own non-merge commits since `mergeBase`, newest first. */
185
+ function branchCommits(dir, mergeBase) {
186
+ const log = git(dir, [
187
+ 'log',
188
+ '--no-merges',
189
+ `--max-count=${MAX_BRANCH_COMMITS}`,
190
+ '--format=%B%x00',
191
+ `${mergeBase}..HEAD`,
192
+ ]);
193
+ return log
194
+ .split('\0')
195
+ .map((message) => message.trim())
196
+ .filter((message) => message !== '');
197
+ }
198
+ /**
199
+ * Fetch the target branch into its remote-tracking ref, the only thing this command ever changes.
200
+ * The full refspec keeps a branch name from being read as an option. Returns the failure, or null.
201
+ */
202
+ function fetchBase(dir, remote, base) {
203
+ try {
204
+ git(dir, ['fetch', '--quiet', remote, `+refs/heads/${base}:refs/remotes/${remote}/${base}`]);
205
+ return null;
206
+ }
207
+ catch (err) {
208
+ return errorMessage(err).split('\n', 1)[0];
209
+ }
210
+ }
211
+ function gatherDriftFacts(dir, remote, base, mode) {
212
+ const none = {
213
+ remoteRefSha: null,
214
+ behind: null,
215
+ ahead: null,
216
+ mergeBase: null,
217
+ overlappingCommits: [],
218
+ branchCommits: null,
219
+ };
220
+ if (!remote || !base)
221
+ return { ...none, fetchError: null };
222
+ const fetchError = mode === 'fetch' ? fetchBase(dir, remote, base) : null;
223
+ const remoteRefSha = tryGit(dir, ['rev-parse', '--verify', '--quiet', `refs/remotes/${remote}/${base}`]);
224
+ const counts = remoteRefSha ? tryGit(dir, ['rev-list', '--left-right', '--count', `${remoteRefSha}...HEAD`]) : null;
225
+ if (!remoteRefSha || !counts)
226
+ return { ...none, remoteRefSha, fetchError };
227
+ const [behind, ahead] = counts.split(/\s+/).map(Number);
228
+ const mergeBase = tryGit(dir, ['merge-base', remoteRefSha, 'HEAD']);
229
+ return {
230
+ remoteRefSha,
231
+ behind,
232
+ ahead,
233
+ mergeBase,
234
+ fetchError,
235
+ overlappingCommits: mergeBase ? overlappingCommits(dir, mergeBase, remoteRefSha) : [],
236
+ branchCommits: mergeBase ? branchCommits(dir, mergeBase) : null,
237
+ };
238
+ }
239
+ /**
240
+ * The default branch the clone records for the remote. A remote added by hand has no `HEAD`, so
241
+ * `origin`'s is the fallback: a fork almost always keeps its parent's default branch name.
242
+ */
243
+ function localDefaultBranch(dir, remote) {
244
+ if (!remote)
245
+ return null;
246
+ const names = new Set([remote, 'origin']);
247
+ for (const name of names) {
248
+ const head = tryGit(dir, ['symbolic-ref', '--quiet', '--short', `refs/remotes/${name}/HEAD`]);
249
+ if (head)
250
+ return head.slice(name.length + 1);
251
+ }
252
+ return null;
253
+ }
254
+ function repoRoot(dir) {
255
+ const root = tryGit(dir, ['rev-parse', '--show-toplevel']);
256
+ if (!root)
257
+ throw new ValidationError(`Not a git working tree: ${dir}`);
258
+ return root;
259
+ }
260
+ /** Which repository the PR goes to and which remote stands for it. */
261
+ function resolveTarget(remotes, issue) {
262
+ const fromIssue = issueRepo(issue);
263
+ const remote = pickRemote(remotes, fromIssue);
264
+ const remoteRepo = repoName(remote);
265
+ const repo = fromIssue ?? remoteRepo;
266
+ return { repo, remoteRepo, remote: remote?.name ?? null, issueUrl: issueUrlFor(issue, repo) };
267
+ }
268
+ function gatherHeadFacts(dir, remotes, login) {
269
+ const pushTarget = login ? resolvePushRemote(remotes, login) : null;
270
+ const status = git(dir, ['status', '--porcelain']);
271
+ return {
272
+ login,
273
+ branch: tryGit(dir, ['branch', '--show-current']) || null,
274
+ dirtyCount: status.split('\n').filter((line) => line !== '').length,
275
+ pushRemote: pushTarget?.remote ?? null,
276
+ };
277
+ }
278
+ function repoScoreFor(state, repo) {
279
+ const lower = repo.toLowerCase();
280
+ return Object.entries(state.repoScores).find(([key]) => key.toLowerCase() === lower)?.[1];
281
+ }
282
+ /** The repo's contribution policy and whether this is the user's first PR there; read from local state only. */
283
+ function policyFacts(state, repo) {
284
+ if (!repo)
285
+ return { policy: null, isFirstContribution: false };
286
+ return {
287
+ policy: effectivePolicy(state, repo),
288
+ // State keys keep the casing of the URL they came from; the remote may differ.
289
+ isFirstContribution: isFirstInRepo(repo, repoScoreFor(state, repo), state.mergedPRs),
290
+ };
291
+ }
292
+ /** A staged file's text, or null when no file was given. */
293
+ function draftOrNull(file) {
294
+ return file === undefined ? null : readDraft(file).content;
295
+ }
296
+ /** Run every preflight check for the branch checked out in `options.dir`. */
297
+ export async function runPrPreflight(options) {
298
+ // Read before anything else, so a bad path fails before any GitHub read.
299
+ const staged = {
300
+ prBody: draftOrNull(options.bodyFile),
301
+ prTitle: draftOrNull(options.titleFile),
302
+ prTemplate: draftOrNull(options.templateFile),
303
+ };
304
+ const run = await runPreflightOnText(options, staged);
305
+ return run.output;
306
+ }
307
+ /** Run every preflight check against staged text already read; `pr-create` sends exactly the text it checked (#2085). */
308
+ export async function runPreflightOnText(options, staged) {
309
+ if (options.base !== undefined && !BRANCH_NAME_PATTERN.test(options.base)) {
310
+ throw new ValidationError(`Invalid base branch name: ${options.base}`);
311
+ }
312
+ const dir = repoRoot(options.dir ?? process.cwd());
313
+ const headSha = tryGit(dir, ['rev-parse', '--verify', '--quiet', 'HEAD']);
314
+ const remotes = parseRemotesOutput(git(dir, ['remote', '-v']));
315
+ const target = resolveTarget(remotes, options.issue);
316
+ const sm = getStateManager();
317
+ const login = sm.getState().config.githubUsername || null;
318
+ const policy = policyFacts(sm.getState(), target.repo);
319
+ const shouldReadLabels = policy.policy?.prGate === 'maintainer-label';
320
+ const network = await gatherNetworkFacts(target, options, login, shouldReadLabels, staged);
321
+ const localDefault = localDefaultBranch(dir, target.remote);
322
+ const base = options.base ?? network.github?.defaultBranch ?? localDefault;
323
+ const facts = {
324
+ ...target,
325
+ ...network,
326
+ ...gatherHeadFacts(dir, remotes, login),
327
+ ...gatherDriftFacts(dir, target.remote, base, options.fetch ? 'fetch' : 'no-fetch'),
328
+ base,
329
+ localDefault,
330
+ ...policy,
331
+ pacing: getPacingStatus(sm.getState()),
332
+ ...staged,
333
+ isDraft: options.draft === true,
334
+ allowScriptMismatch: options.allowScriptMismatch === true,
335
+ };
336
+ const { repo, remote, issueUrl, branch, mergeBase, ahead, behind } = facts;
337
+ const result = runPreflightChecks(facts);
338
+ const output = { ...result, dir, repo, issueUrl, branch, remote, base, mergeBase, ahead, behind };
339
+ return { output, facts, remotes, headSha };
340
+ }
341
+ /** Text mode: the verdict, then one line per check. */
342
+ export function printPrPreflight(data) {
343
+ const target = `${data.branch ?? '(detached HEAD)'} -> ${data.repo ?? '(no GitHub remote)'}:${data.base ?? '?'}`;
344
+ console.log(`\nPR preflight: ${data.verdict.toUpperCase()} ${target}`);
345
+ for (const check of data.checks) {
346
+ console.log(` [${check.status}] ${check.id}: ${check.summary}`);
347
+ }
348
+ }