@oss-autopilot/core 3.43.0 → 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 (100) hide show
  1. package/dist/cli-registry.js +160 -6
  2. package/dist/cli.bundle.cjs +207 -180
  3. package/dist/commands/check-integration.js +4 -1
  4. package/dist/commands/cleanup.d.ts +6 -2
  5. package/dist/commands/cleanup.js +72 -7
  6. package/dist/commands/comments.d.ts +8 -1
  7. package/dist/commands/comments.js +11 -3
  8. package/dist/commands/config.d.ts +2 -0
  9. package/dist/commands/config.js +26 -1
  10. package/dist/commands/daily-ledger.d.ts +33 -5
  11. package/dist/commands/daily-ledger.js +36 -13
  12. package/dist/commands/daily-render.d.ts +2 -1
  13. package/dist/commands/daily-render.js +4 -1
  14. package/dist/commands/daily.d.ts +3 -0
  15. package/dist/commands/daily.js +25 -5
  16. package/dist/commands/dashboard-data.js +70 -61
  17. package/dist/commands/dashboard-lifecycle.d.ts +36 -8
  18. package/dist/commands/dashboard-lifecycle.js +131 -38
  19. package/dist/commands/dashboard-process.d.ts +35 -0
  20. package/dist/commands/dashboard-process.js +65 -5
  21. package/dist/commands/dismiss.js +7 -6
  22. package/dist/commands/doctor.js +1 -8
  23. package/dist/commands/fork-prune.d.ts +58 -0
  24. package/dist/commands/fork-prune.js +247 -0
  25. package/dist/commands/guidelines.d.ts +46 -1
  26. package/dist/commands/guidelines.js +111 -12
  27. package/dist/commands/index.d.ts +5 -0
  28. package/dist/commands/index.js +5 -0
  29. package/dist/commands/overnight-push-prep.d.ts +2 -1
  30. package/dist/commands/overnight-push-prep.js +3 -3
  31. package/dist/commands/policy.d.ts +5 -1
  32. package/dist/commands/policy.js +14 -1
  33. package/dist/commands/pr-create.d.ts +48 -0
  34. package/dist/commands/pr-create.js +200 -0
  35. package/dist/commands/pr-preflight.d.ts +28 -2
  36. package/dist/commands/pr-preflight.js +63 -9
  37. package/dist/commands/setup.js +120 -36
  38. package/dist/commands/startup.d.ts +7 -0
  39. package/dist/commands/startup.js +17 -0
  40. package/dist/commands/status.js +5 -0
  41. package/dist/commands/validation.d.ts +5 -0
  42. package/dist/commands/validation.js +5 -0
  43. package/dist/commands/vet-list.js +2 -2
  44. package/dist/commands/vet.d.ts +8 -0
  45. package/dist/commands/vet.js +15 -1
  46. package/dist/commands/work.d.ts +4 -0
  47. package/dist/commands/work.js +34 -11
  48. package/dist/core/commit-date.d.ts +31 -5
  49. package/dist/core/commit-date.js +36 -8
  50. package/dist/core/compliance-score.d.ts +3 -0
  51. package/dist/core/compliance-score.js +13 -9
  52. package/dist/core/config-registry.d.ts +27 -2
  53. package/dist/core/config-registry.js +83 -2
  54. package/dist/core/daily-logic.d.ts +4 -1
  55. package/dist/core/daily-logic.js +13 -2
  56. package/dist/core/fork-prune.d.ts +149 -0
  57. package/dist/core/fork-prune.js +333 -0
  58. package/dist/core/gist-state-store.js +4 -8
  59. package/dist/core/github-stats.d.ts +7 -1
  60. package/dist/core/github-stats.js +15 -15
  61. package/dist/core/index.d.ts +1 -1
  62. package/dist/core/index.js +1 -1
  63. package/dist/core/local-config.js +2 -3
  64. package/dist/core/pacing.d.ts +41 -0
  65. package/dist/core/pacing.js +115 -0
  66. package/dist/core/pr-assembly.d.ts +2 -0
  67. package/dist/core/pr-graphql.d.ts +16 -1
  68. package/dist/core/pr-graphql.js +15 -3
  69. package/dist/core/pr-monitor.d.ts +6 -0
  70. package/dist/core/pr-monitor.js +46 -10
  71. package/dist/core/pr-preflight.d.ts +41 -0
  72. package/dist/core/pr-preflight.js +406 -17
  73. package/dist/core/prose-script.d.ts +72 -0
  74. package/dist/core/prose-script.js +223 -0
  75. package/dist/core/repo-policy.d.ts +8 -2
  76. package/dist/core/repo-policy.js +34 -6
  77. package/dist/core/repo-score-manager.d.ts +18 -0
  78. package/dist/core/repo-score-manager.js +29 -0
  79. package/dist/core/review-analysis.d.ts +15 -2
  80. package/dist/core/review-analysis.js +22 -5
  81. package/dist/core/stale-data.d.ts +44 -7
  82. package/dist/core/stale-data.js +46 -8
  83. package/dist/core/state-persistence.js +2 -4
  84. package/dist/core/state-schema.d.ts +39 -0
  85. package/dist/core/state-schema.js +68 -1
  86. package/dist/core/state.d.ts +21 -0
  87. package/dist/core/state.js +47 -0
  88. package/dist/core/status-determination.js +10 -8
  89. package/dist/core/untrusted-content.d.ts +3 -3
  90. package/dist/core/untrusted-content.js +26 -8
  91. package/dist/core/urls.d.ts +24 -0
  92. package/dist/core/urls.js +76 -0
  93. package/dist/dashboard/assets/chart-panel-B-nLVgzQ.js +3 -0
  94. package/dist/dashboard/assets/index-5IvMGokL.js +55 -0
  95. package/dist/dashboard/index.html +1 -1
  96. package/dist/formatters/json.d.ts +171 -5
  97. package/dist/formatters/json.js +79 -0
  98. package/package.json +6 -6
  99. package/dist/dashboard/assets/chart-panel-C_C1lFTI.js +0 -3
  100. package/dist/dashboard/assets/index-B--H66Jk.js +0 -55
@@ -7,19 +7,26 @@
7
7
  * `guidelines reset` — tombstone the file so subsequent reads return null.
8
8
  * `guidelines fetch-corpus` — pull raw PR comment bundles for the host's
9
9
  * extract-learnings prompt to consume.
10
+ * `guidelines mark-proposed` — record that a proposal file waits for review
11
+ * on this machine (#2041).
10
12
  *
11
13
  * The CLI layer is pure data plumbing — extraction is the host's job.
12
14
  * Standalone-mode users see "not available" on store/reset/fetch-corpus
13
15
  * because per-repo guidelines require Gist persistence to be useful.
14
16
  */
15
17
  import { createHash } from 'node:crypto';
16
- import { getStateManager, requireGitHubToken, getOctokit, GuidelinesNotAvailableError, GUIDELINES_PROVENANCE_NOTE, wrapUntrustedContent, maybeCheckpoint, } from '../core/index.js';
18
+ import * as fs from 'node:fs';
19
+ import path from 'node:path';
20
+ import { getStateManager, requireGitHubToken, getOctokit, GuidelinesNotAvailableError, GUIDELINES_PROVENANCE_NOTE, wrapUntrustedContent, maybeCheckpoint, getMachineId, } from '../core/index.js';
17
21
  import { ValidationError, assertAttended } from '../core/errors.js';
18
22
  import { fetchPRCommentBundlesBatch } from '../core/pr-comments-fetcher.js';
19
23
  import { warn } from '../core/logger.js';
20
- import { assertSha256 } from './draft.js';
24
+ import { assertSha256, getDraftsDir, MAX_DRAFT_AGE_MS } from './draft.js';
21
25
  const MODULE = 'guidelines';
22
26
  const REPO_ID_PATTERN = /^[^/]+\/[^/]+$/;
27
+ /** Repo names a proposal file may be named after (#2041); the prompts filter `daily`'s repos the same way. */
28
+ const PROPOSAL_REPO_PATTERN = /^[a-z\d-]+\/[\w.-]+$/i;
29
+ const DAY_MS = 24 * 60 * 60 * 1000;
23
30
  const DEFAULT_FETCH_LIMIT = 5;
24
31
  const MAX_FETCH_LIMIT = 10;
25
32
  /**
@@ -50,6 +57,63 @@ function validateRepo(repo) {
50
57
  throw new Error(`Invalid repo identifier "${repo}". Expected "owner/repo" format.`);
51
58
  }
52
59
  }
60
+ /** Whether `repo` is a name a proposal file can be named after (#2041); others get no proposal. */
61
+ export function isProposalRepo(repo) {
62
+ return PROPOSAL_REPO_PATTERN.test(repo);
63
+ }
64
+ /**
65
+ * Where this machine keeps the guideline proposal for `repo` (#1929, #2041):
66
+ * `guidelines-<owner>--<repo>.md` in the draft directory. The only place the
67
+ * name is computed; the prompts take it from `daily` or `draft path`.
68
+ */
69
+ export function guidelineProposalPath(repo) {
70
+ if (!isProposalRepo(repo)) {
71
+ throw new ValidationError(`Invalid repo identifier "${repo}" for a guideline proposal`);
72
+ }
73
+ const [owner, name] = repo.split('/', 2);
74
+ return path.join(getDraftsDir(), `guidelines-${owner}--${name}.md`);
75
+ }
76
+ /** Modification time of the regular file at `file` (symlinks not followed), or null when there is none. */
77
+ function proposalMtimeMs(file) {
78
+ const stat = fs.lstatSync(file, { throwIfNoEntry: false });
79
+ return stat?.isFile() ? stat.mtimeMs : null;
80
+ }
81
+ /**
82
+ * Whether a guideline proposal for `repo` is waiting for review (#2041).
83
+ * `prs` are the repo's PRs that still lack `learningsExtractedAt`.
84
+ *
85
+ * A file at {@link guidelineProposalPath} is a proposal on this machine.
86
+ * Without one, a `learningsProposedAt` stamp written by another machine
87
+ * (`guidelines mark-proposed`, synced through the Gist) means a proposal for
88
+ * these PRs waits there, so this machine must not extract them again. Both
89
+ * expire with the draft retention, {@link MAX_DRAFT_AGE_MS}: `getDraftsDir`
90
+ * deletes an older file, and an older stamp is ignored. A stamp this machine
91
+ * wrote whose file is gone is ignored too, so the repo is extracted again.
92
+ */
93
+ export function guidelineProposalStatus(repo, prs, nowMs = Date.now()) {
94
+ const proposalPath = guidelineProposalPath(repo);
95
+ const ageDays = (ms) => Math.max(0, Math.floor((nowMs - ms) / DAY_MS));
96
+ const localMs = proposalMtimeMs(proposalPath);
97
+ if (localMs !== null) {
98
+ return { repo, proposalPath, proposalAgeDays: ageDays(localMs), proposalOnThisMachine: true };
99
+ }
100
+ const self = getMachineId();
101
+ const cutoff = nowMs - MAX_DRAFT_AGE_MS;
102
+ let newest = null;
103
+ for (const pr of prs) {
104
+ if (!pr.learningsProposedAt || (self !== undefined && pr.learningsProposedOn === self))
105
+ continue;
106
+ const at = Date.parse(pr.learningsProposedAt);
107
+ if (at > cutoff && (newest === null || at > newest))
108
+ newest = at;
109
+ }
110
+ return {
111
+ repo,
112
+ proposalPath,
113
+ proposalAgeDays: newest === null ? null : ageDays(newest),
114
+ proposalOnThisMachine: false,
115
+ };
116
+ }
53
117
  /** Read the per-repo guidelines for `repo`. Returns a `local-unavailable` envelope in non-Gist mode. */
54
118
  // eslint-disable-next-line @typescript-eslint/require-await -- async keeps the Promise-returning contract callers rely on; the body has no await yet
55
119
  export async function runGuidelinesView(options) {
@@ -126,6 +190,13 @@ export async function runGuidelinesStore(options) {
126
190
  ...(gistSyncWarning && { gistSyncWarning }),
127
191
  };
128
192
  }
193
+ /** Merged and closed PRs of `repo` whose comment bundle was fetched but not yet marked extracted. */
194
+ function fetchedUnextractedPRUrls(sm, repo) {
195
+ const repoUrlPrefix = `https://github.com/${repo}/`;
196
+ return [...(sm.getMergedPRs() ?? []), ...(sm.getClosedPRs() ?? [])]
197
+ .filter((pr) => pr.url.startsWith(repoUrlPrefix) && pr.commentsFetchedAt && !pr.learningsExtractedAt)
198
+ .map((pr) => pr.url);
199
+ }
129
200
  /**
130
201
  * Stamp `learningsExtractedAt` on every merged/closed PR of `repo` whose
131
202
  * comment bundle was fetched (`commentsFetchedAt` set) but not yet marked
@@ -136,25 +207,53 @@ export async function runGuidelinesStore(options) {
136
207
  export async function runMarkExtracted(options) {
137
208
  validateRepo(options.repo);
138
209
  const sm = getStateManager();
139
- const repoUrlPrefix = `https://github.com/${options.repo}/`;
140
210
  const now = new Date().toISOString();
141
211
  const mark = () => {
142
- let n = 0;
143
- for (const pr of [...(sm.getMergedPRs() ?? []), ...(sm.getClosedPRs() ?? [])]) {
144
- if (!pr.url.startsWith(repoUrlPrefix) || !pr.commentsFetchedAt || pr.learningsExtractedAt)
145
- continue;
146
- sm.markPRLearningsExtracted(pr.url, now);
147
- n++;
148
- }
149
- return n;
212
+ const urls = fetchedUnextractedPRUrls(sm, options.repo);
213
+ for (const url of urls)
214
+ sm.markPRLearningsExtracted(url, now);
215
+ return urls.length;
150
216
  };
151
217
  const marked = mark();
152
218
  const gistSyncWarning = marked > 0 ? await maybeCheckpoint(sm, MODULE, mark) : null;
153
219
  return { repo: options.repo, marked, ...(gistSyncWarning && { gistSyncWarning }) };
154
220
  }
155
- /** Tombstone the guidelines file for `repo`. */
221
+ /**
222
+ * Record that the proposal file for `repo` is written and waits for review on
223
+ * this machine (#2041): stamp `learningsProposedAt` and this machine's id on
224
+ * the PRs it was built from (fetched, not yet extracted). The stamp is synced
225
+ * through the Gist, so another machine's `daily` reports the proposal as held
226
+ * elsewhere instead of extracting the same PRs again. Refuses when no file
227
+ * is at {@link guidelineProposalPath}.
228
+ */
229
+ export async function runMarkProposed(options) {
230
+ validateRepo(options.repo);
231
+ const proposalPath = guidelineProposalPath(options.repo);
232
+ if (proposalMtimeMs(proposalPath) === null) {
233
+ throw new ValidationError(`No guideline proposal at ${proposalPath}: write it there first`);
234
+ }
235
+ const sm = getStateManager();
236
+ const proposedAt = new Date();
237
+ const now = proposedAt.toISOString();
238
+ const machineId = getMachineId();
239
+ const mark = () => {
240
+ const urls = fetchedUnextractedPRUrls(sm, options.repo);
241
+ for (const url of urls)
242
+ sm.markPRLearningsProposed(url, now, machineId);
243
+ return urls.length;
244
+ };
245
+ const marked = mark();
246
+ const gistSyncWarning = marked > 0 ? await maybeCheckpoint(sm, MODULE, mark) : null;
247
+ return { repo: options.repo, path: proposalPath, marked, ...(gistSyncWarning && { gistSyncWarning }) };
248
+ }
249
+ /**
250
+ * Tombstone the guidelines file for `repo`. Refused during an unattended run,
251
+ * like {@link runGuidelinesStore}: the stored text is guidelines the user
252
+ * reviewed, and nobody is there to agree to losing them (#2036).
253
+ */
156
254
  export async function runGuidelinesReset(options) {
157
255
  validateRepo(options.repo);
256
+ assertAttended('reset guidelines');
158
257
  const sm = getStateManager();
159
258
  if (!sm.isGuidelinesAvailable()) {
160
259
  throw new GuidelinesNotAvailableError();
@@ -39,6 +39,8 @@ export { runVerifyIssue, type VerifyIssueOptions } from './verify-issue.js';
39
39
  export { runIssueThread, type IssueThreadOptions } from './issue-thread.js';
40
40
  /** Re-vet all available issues in a curated issue list for freshness. */
41
41
  export { runVetList } from './vet-list.js';
42
+ /** The curated issue list this machine is configured to use; throws when none is usable (#2035). */
43
+ export { configuredIssueListPath } from './locate-issue-list.js';
42
44
  export { runEval, type EvalOutput } from './eval.js';
43
45
  /** Fetch PR metadata from GitHub (informational; nothing is persisted). */
44
46
  export { runTrack } from './track.js';
@@ -58,8 +60,11 @@ export { runWorkClaim, runWorkFinish, runWorkRelease, runWorkList } from './work
58
60
  export { runComments } from './comments.js';
59
61
  /** Post a comment to a GitHub issue or PR. */
60
62
  export { runPost } from './comments.js';
63
+ export { runForkPrune } from './fork-prune.js';
61
64
  /** Post a claim comment on a GitHub issue. */
62
65
  export { runClaim, DEFAULT_CLAIM_MESSAGE } from './comments.js';
66
+ /** Run the PR preflight checks on the staged title and body, then open the PR (#2085). */
67
+ export { runPrCreate } from './pr-create.js';
63
68
  /** Read or write user configuration (githubUsername, languages, labels, etc). */
64
69
  export { runConfig } from './config.js';
65
70
  /** Initialize with a GitHub username and import open PRs. */
@@ -40,6 +40,8 @@ export { runVerifyIssue } from './verify-issue.js';
40
40
  export { runIssueThread } from './issue-thread.js';
41
41
  /** Re-vet all available issues in a curated issue list for freshness. */
42
42
  export { runVetList } from './vet-list.js';
43
+ /** The curated issue list this machine is configured to use; throws when none is usable (#2035). */
44
+ export { configuredIssueListPath } from './locate-issue-list.js';
43
45
  export { runEval } from './eval.js';
44
46
  // ── PR Management ───────────────────────────────────────────────────────────
45
47
  /** Fetch PR metadata from GitHub (informational; nothing is persisted). */
@@ -61,8 +63,11 @@ export { runWorkClaim, runWorkFinish, runWorkRelease, runWorkList } from './work
61
63
  export { runComments } from './comments.js';
62
64
  /** Post a comment to a GitHub issue or PR. */
63
65
  export { runPost } from './comments.js';
66
+ export { runForkPrune } from './fork-prune.js';
64
67
  /** Post a claim comment on a GitHub issue. */
65
68
  export { runClaim, DEFAULT_CLAIM_MESSAGE } from './comments.js';
69
+ /** Run the PR preflight checks on the staged title and body, then open the PR (#2085). */
70
+ export { runPrCreate } from './pr-create.js';
66
71
  // ── Configuration & Setup ───────────────────────────────────────────────────
67
72
  /** Read or write user configuration (githubUsername, languages, labels, etc). */
68
73
  export { runConfig } from './config.js';
@@ -27,6 +27,7 @@
27
27
  */
28
28
  /** The only ref namespace this command ever pushes to. */
29
29
  export declare const PREP_REF_PREFIX = "refs/heads/prep/";
30
+ export declare const GIT_TIMEOUT_MS = 60000;
30
31
  export interface RemoteOwnerRepo {
31
32
  owner: string;
32
33
  repo: string;
@@ -98,6 +99,6 @@ export declare function prepBranchName(ref: string): string;
98
99
  /** Pure: `<fork>/compare/<pr-head>...prep/<branch>`. */
99
100
  export declare function compareUrlFor(target: RemoteOwnerRepo, prHead: string, prepBranch: string): string;
100
101
  /** Run `git -C <worktree> <args>` and return its stdout. Also the runner `cleanup` uses. */
101
- export declare function git(worktree: string, args: string[], timeoutMs?: number): string;
102
+ export declare function git(worktree: string, args: string[], timeoutMs?: number, extraEnv?: Record<string, string>): string;
102
103
  /** Push every prepared branch of the latest overnight run to `prep/*` on the user's fork. */
103
104
  export declare function runOvernightPushPrep(options: OvernightPushPrepOptions): Promise<OvernightPushPrepOutput>;
@@ -37,7 +37,7 @@ import { publishReport, reportDateFor, writePreparedSection } from './overnight.
37
37
  const MODULE = 'overnight-push-prep';
38
38
  /** The only ref namespace this command ever pushes to. */
39
39
  export const PREP_REF_PREFIX = 'refs/heads/prep/';
40
- const GIT_TIMEOUT_MS = 60_000;
40
+ export const GIT_TIMEOUT_MS = 60_000;
41
41
  // Inherited, any of these would point `git -C <worktree>` at another repository.
42
42
  const GIT_REDIRECTS = new Set(['GIT_DIR', 'GIT_WORK_TREE', 'GIT_INDEX_FILE', 'GIT_COMMON_DIR']);
43
43
  // `ls-files` on a large repository outgrows the 1 MiB default.
@@ -128,7 +128,7 @@ export function compareUrlFor(target, prHead, prepBranch) {
128
128
  return `https://github.com/${target.owner}/${target.repo}/compare/${prHead}...${prepBranch}`;
129
129
  }
130
130
  /** Run `git -C <worktree> <args>` and return its stdout. Also the runner `cleanup` uses. */
131
- export function git(worktree, args, timeoutMs = GIT_TIMEOUT_MS) {
131
+ export function git(worktree, args, timeoutMs = GIT_TIMEOUT_MS, extraEnv = {}) {
132
132
  const inherited = Object.entries(process.env).filter(([name]) => !GIT_REDIRECTS.has(name));
133
133
  return execFileSync('git', ['-C', worktree, ...args], {
134
134
  encoding: 'utf8',
@@ -136,7 +136,7 @@ export function git(worktree, args, timeoutMs = GIT_TIMEOUT_MS) {
136
136
  maxBuffer: GIT_MAX_BUFFER,
137
137
  stdio: ['ignore', 'pipe', 'pipe'],
138
138
  // Unattended: a credential prompt must fail, not hang until the timeout.
139
- env: { ...Object.fromEntries(inherited), GIT_TERMINAL_PROMPT: '0' },
139
+ env: { ...Object.fromEntries(inherited), ...extraEnv, GIT_TERMINAL_PROMPT: '0' },
140
140
  });
141
141
  }
142
142
  /** Where the preparer puts its worktrees (agents/overnight-preparer.md). */
@@ -14,8 +14,10 @@ export interface PolicyGetOutput {
14
14
  updatedAt: string;
15
15
  /** True when the repo is in `config.aiPolicyBlocklist`; `policy set` cannot lift that ban. */
16
16
  blocklisted: boolean;
17
- /** The disclosure line the repo asks for, inside a `<github-content>` fence. */
17
+ /** The disclosure line the user recorded, inside a `<github-content>` fence; the repo's rule is in `sources`. */
18
18
  disclosureText?: string;
19
+ /** The issue label the user recorded as the maintainer-label gate, inside a `<github-content>` fence. */
20
+ gateLabel?: string;
19
21
  /** `file: quoted line` per rule, inside a `<github-content>` fence. */
20
22
  sources?: string;
21
23
  }) | null;
@@ -24,6 +26,8 @@ export interface PolicySetOptions {
24
26
  repo: string;
25
27
  aiPolicy?: string;
26
28
  disclosureText?: string;
29
+ /** The issue label a maintainer-label gate waits for; an empty string clears it. */
30
+ gateLabel?: string;
27
31
  cla?: string;
28
32
  prGate?: string;
29
33
  /** Replaces the list; an empty string clears it. */
@@ -9,6 +9,7 @@
9
9
  import { getStateManager, maybeCheckpoint, warn, errorMessage } from '../core/index.js';
10
10
  import { ValidationError, assertAttended } from '../core/errors.js';
11
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 { GATE_LABEL_MAX } from '../core/state-schema.js';
12
13
  import { validateRepoIdentifier } from './validation.js';
13
14
  const MODULE = 'policy';
14
15
  function oneOf(value, allowed, flag) {
@@ -58,6 +59,16 @@ function parseMax(value) {
58
59
  }
59
60
  return value;
60
61
  }
62
+ /** The label name, trimmed; '' clears it. Refuses a name GitHub could not have. */
63
+ function parseGateLabel(value) {
64
+ if (value === undefined)
65
+ return undefined;
66
+ const name = value.trim();
67
+ if (name.length > GATE_LABEL_MAX || /\p{Cc}/u.test(name)) {
68
+ throw new ValidationError(`Invalid --gate-label "${quote(value)}". Expected an issue label name of at most ${GATE_LABEL_MAX} characters ("" clears it).`);
69
+ }
70
+ return name;
71
+ }
61
72
  /** The fields `options` sets; an absent flag leaves the stored value. */
62
73
  function changes(options) {
63
74
  const fields = {
@@ -67,6 +78,7 @@ function changes(options) {
67
78
  commitRules: parseCommitRules(options.commitRules),
68
79
  maxOpenAiPRs: parseMax(options.maxOpenAiPRs),
69
80
  disclosureText: options.disclosureText === undefined ? undefined : quote(options.disclosureText),
81
+ gateLabel: parseGateLabel(options.gateLabel),
70
82
  };
71
83
  const entries = Object.entries(fields);
72
84
  return Object.fromEntries(entries.filter(([, v]) => v !== undefined));
@@ -74,12 +86,13 @@ function changes(options) {
74
86
  function applySet(current, options, now) {
75
87
  const merged = { ...current, ...changes(options) };
76
88
  const source = options.source === undefined ? [] : [{ file: 'user', quotedLine: quote(options.source) }];
77
- const { maxOpenAiPRs, disclosureText, ...rest } = merged;
89
+ const { maxOpenAiPRs, disclosureText, gateLabel, ...rest } = merged;
78
90
  return {
79
91
  ...rest,
80
92
  // 0 and '' clear these.
81
93
  ...(maxOpenAiPRs !== undefined && maxOpenAiPRs > 0 && { maxOpenAiPRs }),
82
94
  ...(disclosureText && { disclosureText }),
95
+ ...(gateLabel && { gateLabel }),
83
96
  source: [...source, ...current.source].slice(0, 10),
84
97
  reviewedByUser: true,
85
98
  updatedAt: now,
@@ -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
+ }
@@ -3,7 +3,8 @@
3
3
  * is opened. Gathers facts from the local clone (read-only commands) and from
4
4
  * GitHub (read-only API), then runs the pure checks in core/pr-preflight.ts:
5
5
  * upstream drift, base branch, head branch, working tree, competing work on
6
- * the issue, the per-repo open-PR cap, the repo policy and its commit rules.
6
+ * the issue, the per-repo open-PR cap, the pacing caps, the repo policy and
7
+ * its commit rules.
7
8
  *
8
9
  * It only reads, so it runs in unattended mode. Without a GitHub token, or
9
10
  * with `--local`, the local checks still run and the network checks come back
@@ -11,7 +12,8 @@
11
12
  * thing it can change is remote-tracking refs, and only when `--fetch` is
12
13
  * passed; without it a stale `<remote>/<base>` is reported, not refreshed.
13
14
  */
14
- import { type PreflightCheck, type PreflightVerdict } from '../core/pr-preflight.js';
15
+ import { type PreflightCheck, type PreflightFacts, type PreflightVerdict } from '../core/pr-preflight.js';
16
+ import { type GitRemote } from './overnight-push-prep.js';
15
17
  export interface PrPreflightOptions {
16
18
  /** Local clone or worktree; defaults to the current directory. */
17
19
  dir?: string;
@@ -23,7 +25,21 @@ export interface PrPreflightOptions {
23
25
  fetch: boolean;
24
26
  /** Skip every GitHub read; for callers that only want the local numbers. */
25
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;
26
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'>;
27
43
  export interface PrPreflightOutput {
28
44
  verdict: PreflightVerdict;
29
45
  dir: string;
@@ -39,5 +55,15 @@ export interface PrPreflightOutput {
39
55
  }
40
56
  /** Run every preflight check for the branch checked out in `options.dir`. */
41
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>;
42
68
  /** Text mode: the verdict, then one line per check. */
43
69
  export declare function printPrPreflight(data: PrPreflightOutput): void;