@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
@@ -0,0 +1,113 @@
1
+ /**
2
+ * PR preflight checks (#1952): the gate that runs before a branch is pushed
3
+ * and a PR is opened in someone else's repository.
4
+ *
5
+ * Every check is a pure function over `PreflightFacts`, which the
6
+ * `pr-preflight` command gathers from the local clone and read-only GitHub calls.
7
+ * A new check is one more function in `PREFLIGHT_CHECKS` (plus the facts it
8
+ * needs); the verdict and the output shape do not change.
9
+ */
10
+ import type { IssueVerification } from './issue-verification.js';
11
+ import type { RepoCapStatus } from './repo-cap.js';
12
+ import { type RepoPolicy } from './repo-policy.js';
13
+ export type PreflightStatus = 'pass' | 'warn' | 'fail' | 'skipped';
14
+ export type PreflightVerdict = 'pass' | 'warn' | 'fail';
15
+ export interface PreflightCheck {
16
+ id: string;
17
+ status: PreflightStatus;
18
+ /** One line a user can read. */
19
+ summary: string;
20
+ /** The facts behind the status. Commit subjects in it arrive inside a `<github-content>` fence. */
21
+ details?: Record<string, unknown>;
22
+ }
23
+ /** What GitHub says about the upstream repository; absent without a token. */
24
+ export interface PreflightGitHubFacts {
25
+ defaultBranch: string;
26
+ /** `owner/repo` the upstream repository was forked from, or null. */
27
+ parent: string | null;
28
+ /** The token can push to the upstream repository. */
29
+ canPush: boolean;
30
+ /** Head commit of the target branch on GitHub; null when the branch does not exist there. */
31
+ baseHeadSha: string | null;
32
+ }
33
+ export interface PreflightFacts {
34
+ /** Upstream `owner/repo`: from the issue URL, else from the remote. Null when neither names a GitHub repository. */
35
+ repo: string | null;
36
+ /** Remote the drift is measured against; null when the clone has none. */
37
+ remote: string | null;
38
+ /** `owner/repo` that remote's URL points at. */
39
+ remoteRepo: string | null;
40
+ /** Current branch; null on a detached HEAD. */
41
+ branch: string | null;
42
+ /** Branch the PR will target: `--base`, else the default branch. */
43
+ base: string | null;
44
+ /** Default branch the clone records for the remote (`refs/remotes/<remote>/HEAD`). */
45
+ localDefault: string | null;
46
+ /** Entries in `git status --porcelain`. */
47
+ dirtyCount: number;
48
+ /** Commit the local `<remote>/<base>` ref points at; null when it is not fetched. */
49
+ remoteRefSha: string | null;
50
+ behind: number | null;
51
+ ahead: number | null;
52
+ mergeBase: string | null;
53
+ /** `git log --oneline` lines for upstream commits since the merge base that touch files this branch changed. */
54
+ overlappingCommits: string[];
55
+ /** Full messages of this branch's own commits (`git log <mergeBase>..HEAD`, merges left out); null without a merge base. */
56
+ branchCommits: string[] | null;
57
+ /** Set when `--fetch` was passed and the fetch failed. */
58
+ fetchError: string | null;
59
+ /** Configured GitHub username. */
60
+ login: string | null;
61
+ /** Remote whose URL owner is `login`. */
62
+ pushRemote: string | null;
63
+ issueUrl: string | null;
64
+ /** Why GitHub was not consulted at all (`--local`, no token, no GitHub remote); null when it was. */
65
+ networkSkip: string | null;
66
+ /** Why one GitHub read failed; that check degrades and the others still run. */
67
+ githubError: string | null;
68
+ issueError: string | null;
69
+ capError: string | null;
70
+ github: PreflightGitHubFacts | null;
71
+ issue: IssueVerification | null;
72
+ cap: RepoCapStatus | null;
73
+ /** The repo's contribution policy (`effectivePolicy`: stored record plus the blocklist); null when none is recorded. */
74
+ policy: RepoPolicy | null;
75
+ /** The user has no merged PR in the repo. */
76
+ isFirstContribution: boolean;
77
+ }
78
+ /** Past this many commits behind, the drift check warns even when no upstream commit touches the branch's files. */
79
+ export declare const BEHIND_WARN_THRESHOLD = 20;
80
+ /**
81
+ * Commits on the upstream target branch that this branch does not have. Never fetches: a stale ref is reported.
82
+ * The local ref is compared with GitHub only when its remote points at the upstream repository; in a
83
+ * fork-only clone the two are different branches, and "stale, fetch again" would never clear.
84
+ */
85
+ export declare function checkDrift(facts: PreflightFacts): PreflightCheck;
86
+ /** The PR targets a branch that exists upstream and is the default branch, on the repository the remote points at. */
87
+ export declare function checkBaseBranch(facts: PreflightFacts): PreflightCheck;
88
+ /** The head is a real feature branch, and the user has somewhere to push it. */
89
+ export declare function checkHeadBranch(facts: PreflightFacts): PreflightCheck;
90
+ export declare function checkWorkingTree(facts: PreflightFacts): PreflightCheck;
91
+ /** Someone else's open closing PR, an assignment, or a closed issue, from the same verification `verify-issue` runs. */
92
+ export declare function checkCompetingWork(facts: PreflightFacts): PreflightCheck;
93
+ /** The user's own open-PR cap and `excludeRepos`, as `repo-cap` reports them. Runs only for an issue: it gates a new PR. */
94
+ export declare function checkRepoCap(facts: PreflightFacts): PreflightCheck;
95
+ /**
96
+ * The repo's contribution policy (#1953): `banned` fails, a rule the PR has
97
+ * not met warns with the action that meets it. Quoted repo text arrives fenced.
98
+ */
99
+ export declare function checkRepoPolicy(facts: PreflightFacts): PreflightCheck;
100
+ /**
101
+ * The repo's recorded commit rules over this branch's commits (local, no
102
+ * network). A rule the user confirmed fails; one read from the docs and not
103
+ * reviewed only warns. Commit subjects arrive fenced.
104
+ */
105
+ export declare function checkCommitRules(facts: PreflightFacts): PreflightCheck;
106
+ /** Every check, in output order. A new check is added here. */
107
+ export declare const PREFLIGHT_CHECKS: ReadonlyArray<(facts: PreflightFacts) => PreflightCheck>;
108
+ /** `fail` when any check fails, else `warn` when any warns, else `pass`. Skipped checks do not count. */
109
+ export declare function preflightVerdict(checks: readonly PreflightCheck[]): PreflightVerdict;
110
+ export declare function runPreflightChecks(facts: PreflightFacts): {
111
+ verdict: PreflightVerdict;
112
+ checks: PreflightCheck[];
113
+ };
@@ -0,0 +1,364 @@
1
+ /**
2
+ * PR preflight checks (#1952): the gate that runs before a branch is pushed
3
+ * and a PR is opened in someone else's repository.
4
+ *
5
+ * Every check is a pure function over `PreflightFacts`, which the
6
+ * `pr-preflight` command gathers from the local clone and read-only GitHub calls.
7
+ * A new check is one more function in `PREFLIGHT_CHECKS` (plus the facts it
8
+ * needs); the verdict and the output shape do not change.
9
+ */
10
+ import { banNote, fencePolicyText, quote, summarizePolicy } from './repo-policy.js';
11
+ import { wrapUntrustedContent } from './untrusted-content.js';
12
+ import { isOwnRepo, splitRepo } from './urls.js';
13
+ /** Past this many commits behind, the drift check warns even when no upstream commit touches the branch's files. */
14
+ export const BEHIND_WARN_THRESHOLD = 20;
15
+ function check(id, status, summary, details) {
16
+ return details ? { id, status, summary, details } : { id, status, summary };
17
+ }
18
+ /** Why a network check has nothing to judge: GitHub was not consulted, or the read failed. */
19
+ function skipReason(facts, error, fallback) {
20
+ if (facts.networkSkip !== null)
21
+ return facts.networkSkip;
22
+ return error === null ? fallback : `GitHub request failed: ${error}`;
23
+ }
24
+ function driftSummary(facts, ref, behind) {
25
+ if (facts.fetchError !== null) {
26
+ return { status: 'warn', summary: `git fetch failed (${facts.fetchError}); ${ref} may be stale` };
27
+ }
28
+ const upstreamSha = facts.github?.baseHeadSha;
29
+ if (upstreamSha && upstreamSha !== facts.remoteRefSha) {
30
+ return {
31
+ status: 'warn',
32
+ summary: `${ref} is stale (GitHub is at ${upstreamSha.slice(0, 9)}), so ${behind} behind is a lower bound; run again with --fetch`,
33
+ };
34
+ }
35
+ if (facts.overlappingCommits.length > 0) {
36
+ return {
37
+ status: 'warn',
38
+ summary: `${facts.overlappingCommits.length} commit(s) on ${ref} since the branch point touch files this branch changes; the same fix may have landed`,
39
+ };
40
+ }
41
+ if (behind > BEHIND_WARN_THRESHOLD) {
42
+ return { status: 'warn', summary: `${behind} commits behind ${ref}; rebase to lower the conflict risk` };
43
+ }
44
+ const unverified = facts.github
45
+ ? ''
46
+ : ` (freshness of ${ref} not verified: ${skipReason(facts, facts.githubError, 'no GitHub data')})`;
47
+ const position = behind === 0 ? `up to date with ${ref}` : `${behind} commit(s) behind ${ref}, none touching this branch's files`;
48
+ return { status: 'pass', summary: position + unverified };
49
+ }
50
+ /** The measurements, or undefined when the ref is not fetched. Commit subjects are third-party text, so they are fenced. */
51
+ function driftDetails(facts, ref) {
52
+ if (facts.remoteRefSha === null || facts.behind === null)
53
+ return undefined;
54
+ const subjects = facts.overlappingCommits;
55
+ const measured = { ref, behind: facts.behind, ahead: facts.ahead, mergeBase: facts.mergeBase };
56
+ if (subjects.length === 0)
57
+ return { ...measured, overlapCount: 0 };
58
+ return {
59
+ ...measured,
60
+ overlapCount: subjects.length,
61
+ overlappingCommits: wrapUntrustedContent(subjects.join('\n'), 'commit-subjects'),
62
+ };
63
+ }
64
+ /**
65
+ * Commits on the upstream target branch that this branch does not have. Never fetches: a stale ref is reported.
66
+ * The local ref is compared with GitHub only when its remote points at the upstream repository; in a
67
+ * fork-only clone the two are different branches, and "stale, fetch again" would never clear.
68
+ */
69
+ export function checkDrift(facts) {
70
+ const id = 'upstream-drift';
71
+ if (!facts.remote)
72
+ return check(id, 'warn', 'no git remote to compare against');
73
+ if (!facts.base)
74
+ return check(id, 'warn', 'could not determine the default branch; pass --base <branch>');
75
+ const ref = `${facts.remote}/${facts.base}`;
76
+ const details = driftDetails(facts, ref);
77
+ if (facts.repo !== null && !isSameRepo(facts.remoteRepo, facts.repo)) {
78
+ const measured = details
79
+ ? `drift was measured against ${ref} instead (${facts.behind} behind)`
80
+ : 'drift was not measured';
81
+ return check(id, 'warn', `no remote points at ${facts.repo}, so ${measured}; add a remote for ${facts.repo}`, details);
82
+ }
83
+ if (!details || facts.behind === null) {
84
+ const why = facts.fetchError === null ? '' : ` (git fetch failed: ${facts.fetchError})`;
85
+ return check(id, 'warn', `${ref} is not fetched locally${why}; run again with --fetch`);
86
+ }
87
+ const { status, summary } = driftSummary(facts, ref, facts.behind);
88
+ return check(id, status, summary, details);
89
+ }
90
+ function isSameRepo(a, b) {
91
+ return a !== null && b !== null && a.toLowerCase() === b.toLowerCase();
92
+ }
93
+ /** The target branch is missing upstream or is not the default branch. */
94
+ function baseTargetProblem(repo, base, github) {
95
+ const { defaultBranch } = github;
96
+ if (github.baseHeadSha === null) {
97
+ return { status: 'fail', summary: `branch ${base} does not exist on ${repo} (default branch: ${defaultBranch})` };
98
+ }
99
+ if (base === defaultBranch)
100
+ return null;
101
+ return {
102
+ status: 'warn',
103
+ summary: `the PR would target ${base}, not ${defaultBranch}, the default branch of ${repo}; right only if the contribution guide says so`,
104
+ };
105
+ }
106
+ /** The clone does not line up with the upstream repository: wrong repository, renamed default branch. */
107
+ function baseCloneProblem(facts, repo, github) {
108
+ if (github.parent && !facts.issueUrl) {
109
+ return `${repo} is a fork of ${github.parent}; add a remote for the parent or pass the issue URL so the checks run against it`;
110
+ }
111
+ const remote = facts.remote ?? '(none)';
112
+ if (facts.localDefault !== null && facts.localDefault !== github.defaultBranch) {
113
+ return `${repo} now defaults to ${github.defaultBranch} but the clone records ${facts.localDefault}; run git remote set-head ${remote} -a`;
114
+ }
115
+ return null;
116
+ }
117
+ /** The PR targets a branch that exists upstream and is the default branch, on the repository the remote points at. */
118
+ export function checkBaseBranch(facts) {
119
+ const id = 'base-branch';
120
+ const { github, repo, base } = facts;
121
+ if (!github || !repo || !base) {
122
+ const guess = base ? `; local guess: ${base}` : '';
123
+ return check(id, 'skipped', skipReason(facts, facts.githubError, 'no upstream repository') + guess);
124
+ }
125
+ const details = { repo, base, defaultBranch: github.defaultBranch };
126
+ const target = baseTargetProblem(repo, base, github);
127
+ if (target)
128
+ return check(id, target.status, target.summary, details);
129
+ const clone = baseCloneProblem(facts, repo, github);
130
+ if (clone)
131
+ return check(id, 'warn', clone, details);
132
+ return check(id, 'pass', `targets ${base}, the default branch of ${repo}`, details);
133
+ }
134
+ /** The head is a real feature branch, and the user has somewhere to push it. */
135
+ export function checkHeadBranch(facts) {
136
+ const id = 'head-branch';
137
+ const { branch, repo, login } = facts;
138
+ if (branch === null)
139
+ return check(id, 'fail', 'detached HEAD: check out a feature branch before opening a PR');
140
+ if (branch === facts.base) {
141
+ return check(id, 'fail', `on ${branch}, the branch the PR would target; create a feature branch`);
142
+ }
143
+ if (branch === (facts.github?.defaultBranch ?? facts.localDefault)) {
144
+ return check(id, 'warn', `on ${branch}, the default branch; a PR is normally opened from a feature branch`);
145
+ }
146
+ if (!login) {
147
+ return check(id, 'warn', 'githubUsername is not configured, so no fork remote could be confirmed; run setup');
148
+ }
149
+ if (repo && (facts.github?.canPush || isOwnRepo(splitRepo(repo).owner, login))) {
150
+ return check(id, 'pass', `${branch} can be pushed to ${repo} directly`);
151
+ }
152
+ if (facts.pushRemote) {
153
+ return check(id, 'pass', `${branch} can be pushed to your fork (remote ${facts.pushRemote})`);
154
+ }
155
+ return check(id, 'warn', `no remote is owned by ${login}; fork the repository and add the fork as a remote`);
156
+ }
157
+ export function checkWorkingTree(facts) {
158
+ const id = 'working-tree';
159
+ if (facts.dirtyCount === 0)
160
+ return check(id, 'pass', 'working tree is clean');
161
+ return check(id, 'warn', `${facts.dirtyCount} uncommitted change(s) would not be part of the PR`, {
162
+ dirtyCount: facts.dirtyCount,
163
+ });
164
+ }
165
+ const COMPETING_STATUS = {
166
+ available: 'pass',
167
+ 'own-open-pr': 'warn',
168
+ 'at-risk': 'warn',
169
+ taken: 'fail',
170
+ closed: 'fail',
171
+ };
172
+ /** Someone else's open closing PR, an assignment, or a closed issue, from the same verification `verify-issue` runs. */
173
+ export function checkCompetingWork(facts) {
174
+ const id = 'competing-work';
175
+ if (!facts.issueUrl)
176
+ return check(id, 'skipped', 'no issue given');
177
+ const { issue } = facts;
178
+ if (!issue && facts.issueError !== null) {
179
+ // The duplicate-PR guard did not run: a warn, so nobody pushes on a skipped check.
180
+ return check(id, 'warn', `could not verify the issue (${facts.issueError}); check it for competing work by hand`);
181
+ }
182
+ if (!issue)
183
+ return check(id, 'skipped', facts.networkSkip ?? 'the issue was not verified');
184
+ const openPRs = issue.linkedPRs
185
+ .filter((pr) => pr.state === 'open')
186
+ // Titles are left out: they are untrusted text and the URL identifies the PR.
187
+ .map((pr) => ({ number: pr.number, url: pr.url, author: pr.author, isOwn: pr.isOwn, linkType: pr.linkType }));
188
+ return check(id, COMPETING_STATUS[issue.verdict], `${issue.verdict}: ${issue.verdictReason}`, {
189
+ issueUrl: issue.url,
190
+ verdict: issue.verdict,
191
+ state: issue.state,
192
+ assignees: issue.assignees,
193
+ openPRs,
194
+ });
195
+ }
196
+ function capSkipReason(facts) {
197
+ if (!facts.issueUrl)
198
+ return 'no issue given (the cap gates a new PR)';
199
+ return skipReason(facts, facts.capError, 'githubUsername is not configured; run setup');
200
+ }
201
+ /** The user's own open-PR cap and `excludeRepos`, as `repo-cap` reports them. Runs only for an issue: it gates a new PR. */
202
+ export function checkRepoCap(facts) {
203
+ const id = 'repo-cap';
204
+ const { cap } = facts;
205
+ if (!cap)
206
+ return check(id, 'skipped', capSkipReason(facts));
207
+ const details = { ...cap };
208
+ if (cap.reason)
209
+ return check(id, 'warn', cap.reason, details);
210
+ const limit = cap.cap > 0 ? `of ${cap.cap} allowed` : '(no cap set)';
211
+ return check(id, 'pass', `${cap.openPRCount} open PR(s) in ${cap.repo} ${limit}`, details);
212
+ }
213
+ /** Each rule the policy states that this PR has not met, as the action that meets it. */
214
+ function policyAsks(facts, policy, repo) {
215
+ const isFirst = facts.isFirstContribution;
216
+ const login = facts.login?.toLowerCase();
217
+ const isAssigned = (facts.issue?.assignees ?? []).some((a) => a.toLowerCase() === login);
218
+ const rules = [
219
+ [
220
+ policy.aiPolicy === 'disclosure-required',
221
+ `${repo} requires an AI-use disclosure: add the line in details.disclosureText to the PR body`,
222
+ ],
223
+ [
224
+ isFirst && policy.aiPolicy === 'unknown',
225
+ `${repo}'s AI policy is unknown and this is your first PR there: read its CONTRIBUTING and README, then record it with policy set --repo ${repo} --ai-policy <value>`,
226
+ ],
227
+ [
228
+ !isAssigned && policy.prGate === 'claim-first',
229
+ `${repo} wants the issue claimed first: comment on it and get assigned before opening the PR`,
230
+ ],
231
+ [
232
+ policy.prGate === 'maintainer-label',
233
+ `${repo} wants a maintainer to accept the issue first: confirm it carries their approval label`,
234
+ ],
235
+ [isFirst && policy.cla === 'required', `${repo} requires a signed CLA: sign it when the CLA bot asks on the PR`],
236
+ [policy.prGate === 'collaborators-only' && facts.github?.canPush !== true, collaboratorsAsk(facts, policy, repo)],
237
+ ...maxOpenAsk(facts, policy, repo),
238
+ ];
239
+ return rules.filter(([applies]) => applies).map(([, ask]) => ask);
240
+ }
241
+ /** The open AI-PR limit when it cannot fail: the count is unknown, or the limit was read from the docs and not reviewed. */
242
+ function maxOpenAsk(facts, policy, repo) {
243
+ const max = policy.maxOpenAiPRs;
244
+ if (max === undefined)
245
+ return [];
246
+ if (!facts.cap)
247
+ return [[true, `${repo} allows ${max} open AI-assisted PR(s): count yours there before opening another`]];
248
+ const isOver = !policy.reviewedByUser && facts.cap.openPRCount >= max;
249
+ const ask = `${repo}'s docs read as allowing ${max} open AI-assisted PR(s) and you have ${facts.cap.openPRCount}: wait for one to close, or record the limit with policy set --repo ${repo} --ai-policy <value> --max-open-ai-prs <n|0> if the docs were misread`;
250
+ return [[isOver, ask]];
251
+ }
252
+ /** The warn for `collaborators-only` when it cannot fail: push access unknown, or the rule not reviewed. */
253
+ function collaboratorsAsk(facts, policy, repo) {
254
+ if (!facts.github) {
255
+ return `${repo} only takes PRs from collaborators and push access could not be checked: confirm you are one before opening the PR`;
256
+ }
257
+ const record = policy.reviewedByUser ? '' : `, or record it with policy set --repo ${repo} if the docs were misread`;
258
+ return `${repo}'s docs read as collaborators-only and you cannot push there: check the rule${record}`;
259
+ }
260
+ /** What the policy forbids outright; null when nothing does. */
261
+ function policyStop(facts, policy, repo) {
262
+ if (policy.aiPolicy === 'banned') {
263
+ return `${repo} does not accept AI-assisted contributions: do not open this PR${banNote(policy, repo)}`;
264
+ }
265
+ // Only a rule the user confirmed, checked against known push access, stops the PR.
266
+ if (policy.prGate === 'collaborators-only' && policy.reviewedByUser && facts.github?.canPush === false) {
267
+ return `${repo} only takes PRs from collaborators: do not open this PR`;
268
+ }
269
+ // Only a limit the user confirmed stops the PR; one read from the docs warns (policyAsks).
270
+ const max = policy.reviewedByUser ? policy.maxOpenAiPRs : undefined;
271
+ if (max !== undefined && facts.cap && facts.cap.openPRCount >= max) {
272
+ return `${repo} allows ${max} open AI-assisted PR(s) and you have ${facts.cap.openPRCount}: wait for one to close`;
273
+ }
274
+ return null;
275
+ }
276
+ function noPolicyCheck(id, repo, isFirst) {
277
+ if (!isFirst)
278
+ return check(id, 'pass', `no contribution policy recorded for ${repo}`);
279
+ return check(id, 'warn', `no contribution policy recorded for ${repo} and this is your first PR there: vet the issue or read its CONTRIBUTING, then record it with policy set --repo ${repo}`);
280
+ }
281
+ /**
282
+ * The repo's contribution policy (#1953): `banned` fails, a rule the PR has
283
+ * not met warns with the action that meets it. Quoted repo text arrives fenced.
284
+ */
285
+ export function checkRepoPolicy(facts) {
286
+ const id = 'repo-policy';
287
+ const { repo, policy } = facts;
288
+ if (!repo)
289
+ return check(id, 'skipped', 'no upstream repository');
290
+ if (!policy)
291
+ return noPolicyCheck(id, repo, facts.isFirstContribution);
292
+ const details = { ...summarizePolicy(policy), ...fencePolicyText(repo, policy) };
293
+ const stop = policyStop(facts, policy, repo);
294
+ if (stop)
295
+ return check(id, 'fail', stop, details);
296
+ const asks = policyAsks(facts, policy, repo);
297
+ if (asks.length > 0)
298
+ return check(id, 'warn', asks.join('; '), details);
299
+ return check(id, 'pass', `${repo}: AI policy ${policy.aiPolicy}, PR gate ${policy.prGate}`, details);
300
+ }
301
+ const AUTO_SUBJECT = /^(?:Revert "|Reapply "|(?:fixup|squash|amend)! )/;
302
+ /** A GitHub closing keyword, on the same line as `#12`, `owner/repo#12` or an issue URL. */
303
+ const CLOSING_KEYWORD = String.raw `\b(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?):?[ \t]+`;
304
+ const CLOSING_REFS = [
305
+ new RegExp(String.raw `${CLOSING_KEYWORD}\S*#\d+`, 'i'),
306
+ new RegExp(String.raw `${CLOSING_KEYWORD}https?://github\.com/[^/\s]+/[^/\s]+/issues/\d+`, 'i'),
307
+ ];
308
+ /** Per commit rule id: true when a commit message breaks it. An id this release does not know is not checked. */
309
+ const COMMIT_RULE_BROKEN = {
310
+ // Reverts and autosquash commits keep the subject Git wrote.
311
+ 'conventional-commits': (m) => !AUTO_SUBJECT.test(m) && !/^\w+(?:\([^)\n]*\))?!?: \S/.test(m),
312
+ 'dco-signoff': (m) => !/^Signed-off-by: .+ <[^>\n]+>\s*$/im.test(m),
313
+ 'no-closing-keyword-in-commit': (m) => CLOSING_REFS.some((re) => re.test(m)),
314
+ };
315
+ const MAX_LISTED_VIOLATIONS = 10;
316
+ /**
317
+ * The repo's recorded commit rules over this branch's commits (local, no
318
+ * network). A rule the user confirmed fails; one read from the docs and not
319
+ * reviewed only warns. Commit subjects arrive fenced.
320
+ */
321
+ export function checkCommitRules(facts) {
322
+ const id = 'commit-rules';
323
+ const { repo, policy, branchCommits } = facts;
324
+ const rules = (policy?.commitRules ?? []).filter((rule) => Object.hasOwn(COMMIT_RULE_BROKEN, rule));
325
+ if (!repo || !policy || rules.length === 0)
326
+ return check(id, 'skipped', 'no commit rules recorded for this repo');
327
+ if (branchCommits === null) {
328
+ return check(id, 'skipped', 'the branch point is unknown (target branch not fetched); run again with --fetch');
329
+ }
330
+ const broken = branchCommits.flatMap((message) => rules
331
+ .filter((rule) => COMMIT_RULE_BROKEN[rule](message))
332
+ .map((rule) => `${rule}: ${quote(message.split('\n', 1)[0])}`));
333
+ if (broken.length === 0) {
334
+ return check(id, 'pass', `${branchCommits.length} commit(s) follow ${rules.join(', ')}`, { rules });
335
+ }
336
+ const unreviewed = policy.reviewedByUser
337
+ ? ''
338
+ : ` (rules read from the repo docs, not reviewed: record them with policy set --repo ${repo} --ai-policy <value> --commit-rules <ids> if misread)`;
339
+ return check(id, policy.reviewedByUser ? 'fail' : 'warn', `${broken.length} commit rule violation(s): reword those commits${unreviewed}`, {
340
+ rules,
341
+ violations: wrapUntrustedContent(broken.slice(0, MAX_LISTED_VIOLATIONS).join('\n'), 'commit-subjects'),
342
+ });
343
+ }
344
+ /** Every check, in output order. A new check is added here. */
345
+ export const PREFLIGHT_CHECKS = [
346
+ checkDrift,
347
+ checkBaseBranch,
348
+ checkHeadBranch,
349
+ checkWorkingTree,
350
+ checkCompetingWork,
351
+ checkRepoCap,
352
+ checkRepoPolicy,
353
+ checkCommitRules,
354
+ ];
355
+ /** `fail` when any check fails, else `warn` when any warns, else `pass`. Skipped checks do not count. */
356
+ export function preflightVerdict(checks) {
357
+ if (checks.some((c) => c.status === 'fail'))
358
+ return 'fail';
359
+ return checks.some((c) => c.status === 'warn') ? 'warn' : 'pass';
360
+ }
361
+ export function runPreflightChecks(facts) {
362
+ const checks = PREFLIGHT_CHECKS.map((run) => run(facts));
363
+ return { verdict: preflightVerdict(checks), checks };
364
+ }
@@ -56,12 +56,6 @@ export declare const TITLE_LENGTH_BUDGET = 72;
56
56
  * checklist in; the weights total 100 across the scored entries.
57
57
  */
58
58
  export declare const PR_QUALITY_RUBRIC: readonly PRQualityCheck[];
59
- /**
60
- * Look up a check by id. Used by `compliance-score.ts` to wire the
61
- * scored checks to their canonical weight without hardcoding the
62
- * value in two places.
63
- */
64
- export declare function getRubricCheck(id: PRQualityCheck['id']): PRQualityCheck | undefined;
65
59
  /**
66
60
  * Sum of the weights for scored checks. Should equal 100. Tests pin
67
61
  * this so a future edit that fails to balance the weights surfaces
@@ -103,14 +103,6 @@ export const PR_QUALITY_RUBRIC = [
103
103
  weight: null,
104
104
  },
105
105
  ];
106
- /**
107
- * Look up a check by id. Used by `compliance-score.ts` to wire the
108
- * scored checks to their canonical weight without hardcoding the
109
- * value in two places.
110
- */
111
- export function getRubricCheck(id) {
112
- return PR_QUALITY_RUBRIC.find((c) => c.id === id);
113
- }
114
106
  /**
115
107
  * Sum of the weights for scored checks. Should equal 100. Tests pin
116
108
  * this so a future edit that fails to balance the weights surfaces
@@ -19,6 +19,8 @@ export interface PRTemplateResult {
19
19
  /** If non-null, an error prevented a complete check of all template paths. */
20
20
  error?: string;
21
21
  }
22
+ /** UTF-8 text of a base64 `content` field from the contents API. */
23
+ export declare function decodeBase64(content: string): string;
22
24
  /**
23
25
  * Fetch a repository's PR template by trying each standard location.
24
26
  * Returns on the first successful match. Rate limit and auth errors
@@ -20,6 +20,10 @@ const TEMPLATE_PATHS = [
20
20
  'docs/pull_request_template.md',
21
21
  'pull_request_template.md',
22
22
  ];
23
+ /** UTF-8 text of a base64 `content` field from the contents API. */
24
+ export function decodeBase64(content) {
25
+ return Buffer.from(content, 'base64').toString('utf8');
26
+ }
23
27
  /**
24
28
  * Fetch a repository's PR template by trying each standard location.
25
29
  * Returns on the first successful match. Rate limit and auth errors
@@ -43,7 +47,7 @@ export async function fetchPRTemplate(octokit, owner, repo) {
43
47
  debug(MODULE, `${path} has no content, skipping`);
44
48
  continue;
45
49
  }
46
- const template = Buffer.from(data.content, 'base64').toString('utf8');
50
+ const template = decodeBase64(data.content);
47
51
  debug(MODULE, `Found PR template at ${path} (${template.length} chars)`);
48
52
  return { template, source: path };
49
53
  }
@@ -0,0 +1,105 @@
1
+ /**
2
+ * Per-repo contribution policy (#1953): AI policy, disclosure line, CLA,
3
+ * commit rules and the gate before a PR, as one record per repo.
4
+ *
5
+ * `derivePolicy` runs the anti-LLM / disclosure scans (anti-llm-policy.ts)
6
+ * and the CONTRIBUTING requirement extraction (contributing.ts) over a repo's
7
+ * docs. `vet` and `vet-list` store the result unreviewed, `policy set` stores the user's
8
+ * record, and `pr-preflight` enforces it (including the commit rules).
9
+ *
10
+ * Policy text comes from other people's repos, so a record holds only
11
+ * enumerated values plus short quoted lines ({@link quote}). The older
12
+ * `config.aiPolicyBlocklist` is read as a ban on top of any stored record:
13
+ * nothing stored can lift it ({@link effectivePolicy}).
14
+ */
15
+ import { type AgentState, type RepoPolicy } from './state-schema.js';
16
+ export type { RepoPolicy } from './state-schema.js';
17
+ export type AiPolicy = RepoPolicy['aiPolicy'];
18
+ export type PrGate = RepoPolicy['prGate'];
19
+ export type ClaPolicy = RepoPolicy['cla'];
20
+ export declare const AI_POLICIES: readonly AiPolicy[];
21
+ export declare const PR_GATES: readonly PrGate[];
22
+ export declare const CLA_POLICIES: readonly ClaPolicy[];
23
+ export declare const COMMIT_RULES: readonly ["conventional-commits", "dco-signoff", "no-closing-keyword-in-commit"];
24
+ /** Source label for a ban that comes from `config.aiPolicyBlocklist`. */
25
+ export declare const BLOCKLIST_SOURCE = "config aiPolicyBlocklist";
26
+ type PolicyState = Pick<AgentState, 'config' | 'repoPolicies'>;
27
+ /** One repo document the parsers read: a path and its text. */
28
+ export interface PolicyDoc {
29
+ file: string;
30
+ content: string;
31
+ }
32
+ /** Enumerated fields only: safe to show without a fence. */
33
+ export interface RepoPolicySummary {
34
+ aiPolicy: AiPolicy;
35
+ cla: ClaPolicy;
36
+ prGate: PrGate;
37
+ commitRules: string[];
38
+ maxOpenAiPRs?: number;
39
+ reviewedByUser: boolean;
40
+ }
41
+ /** One line, control characters removed, capped at {@link POLICY_QUOTE_MAX}. */
42
+ export declare function quote(text: string): string;
43
+ /**
44
+ * Derive a policy from a repo's docs (CONTRIBUTING, PR template, ...). With no
45
+ * docs every field is `unknown`; a doc that is silent on CLA or a PR gate reads
46
+ * as `none`. Silence on AI stays `unknown`: it is not permission.
47
+ */
48
+ export declare function derivePolicy(docs: readonly PolicyDoc[], now?: Date): RepoPolicy;
49
+ /**
50
+ * Up to `max` paths in `repo` that its README links to and that look like a
51
+ * contribution guide or AI policy (relative links, or github.com blob links to
52
+ * the same repo). Links to other sites, other repos or outside the repo root
53
+ * are dropped, as are the CONTRIBUTING paths scout reads anyway.
54
+ */
55
+ export declare function linkedPolicyDocs(readme: string, repo: string, max?: number): string[];
56
+ /** Fields of the stored entry this release does not know (a newer release added them), to keep across an edit. */
57
+ export declare function unknownFields(state: PolicyState, repo: string): Record<string, unknown>;
58
+ /** A stored entry this release cannot parse, e.g. one a newer release wrote with a value added since. */
59
+ export declare function isUnreadable(state: PolicyState, repo: string): boolean;
60
+ /**
61
+ * The stored record for `repo`, or null when there is none. An entry that does
62
+ * not parse but says `aiPolicy: 'banned'` still reads as a ban (every other
63
+ * field unknown): a newer release's record must not lift a ban here.
64
+ */
65
+ export declare function storedPolicy(state: PolicyState, repo: string): RepoPolicy | null;
66
+ /** True when the raw stored entry says the user set it, even when this release cannot parse the rest. */
67
+ export declare function isUserReviewed(state: PolicyState, repo: string): boolean;
68
+ export declare function isBlocklisted(state: PolicyState, repo: string): boolean;
69
+ /**
70
+ * The policy that applies to `repo`: the user's record, else a stored ban,
71
+ * else a freshly derived one when given, else the stored unreviewed one. A repo
72
+ * in `config.aiPolicyBlocklist` is banned whatever is stored: the blocklist is
73
+ * the older ban list, still synced to clients that predate policy records, and
74
+ * a record never relaxes it. Null when nothing is known.
75
+ */
76
+ export declare function effectivePolicy(state: PolicyState, repo: string, fresh?: RepoPolicy): RepoPolicy | null;
77
+ /**
78
+ * Where a ban came from, for the user: nothing for one they confirmed; how to
79
+ * lift it otherwise. A blocklist ban is lifted in config, an unreviewed one
80
+ * with `policy set`.
81
+ */
82
+ export declare function banNote(policy: RepoPolicy, repo: string): string;
83
+ /** Stored `banned` records (lowercase keys), reviewed or not. */
84
+ export declare function storedBans(state: PolicyState): Array<{
85
+ repo: string;
86
+ reviewedByUser: boolean;
87
+ }>;
88
+ /**
89
+ * Repos search leaves out: the blocklist as written, then bans the user
90
+ * confirmed. A ban vet read from the docs but nobody reviewed stays searchable
91
+ * (a heuristic must not shrink discovery on its own); vet still says skip.
92
+ */
93
+ export declare function bannedRepos(state: PolicyState): string[];
94
+ export declare function summarizePolicy(policy: RepoPolicy): RepoPolicySummary;
95
+ /** `{ policy }` with the summary to spread into an output, or `{}` when there is no policy. */
96
+ export declare function policyField(policy: RepoPolicy | null): {
97
+ policy?: RepoPolicySummary;
98
+ };
99
+ /** Quoted lines and disclosure text inside `<github-content>` fences, for agent-facing output. */
100
+ export declare function fencePolicyText(repo: string, policy: RepoPolicy): {
101
+ disclosureText?: string;
102
+ sources?: string;
103
+ };
104
+ /** Same rules, ignoring when they were recorded. */
105
+ export declare function isSamePolicy(a: RepoPolicy, b: RepoPolicy): boolean;