@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
@@ -4,6 +4,7 @@
4
4
  */
5
5
  import * as http from 'node:http';
6
6
  import * as fs from 'node:fs';
7
+ import { execFileSync } from 'node:child_process';
7
8
  import * as path from 'node:path';
8
9
  import { getDataDir } from '../core/index.js';
9
10
  import { warn } from '../core/logger.js';
@@ -122,10 +123,10 @@ export function isDashboardServerRunning(port, pid) {
122
123
  });
123
124
  });
124
125
  }
125
- export async function findRunningDashboardServer() {
126
+ export async function probeDashboardServer() {
126
127
  const info = readDashboardServerInfo();
127
128
  if (!info)
128
- return null;
129
+ return { status: 'none' };
129
130
  // Check if process is alive (signal 0 = existence check only)
130
131
  try {
131
132
  process.kill(info.pid, 0);
@@ -138,15 +139,74 @@ export async function findRunningDashboardServer() {
138
139
  // ESRCH = no process at that PID; EPERM = PID recycled to another user's process
139
140
  // Either way, our dashboard server is no longer running — clean up stale PID file
140
141
  removeDashboardServerInfo();
141
- return null;
142
+ return { status: 'none' };
142
143
  }
143
144
  // Process exists — verify it's actually our server via HTTP probe
144
145
  if (await isDashboardServerRunning(info.port, info.pid)) {
145
- return { port: info.port, url: `http://oss.localhost:${info.port}` };
146
+ return { info, status: 'running', port: info.port, url: `http://oss.localhost:${info.port}` };
146
147
  }
148
+ return { status: 'unverified', info };
149
+ }
150
+ export async function findRunningDashboardServer() {
151
+ const probe = await probeDashboardServer();
152
+ if (probe.status === 'running')
153
+ return { port: probe.port, url: probe.url };
147
154
  // Process exists but is not answering as our server on the expected port:
148
155
  // stale. Never signal it. The PID file outlives crashes and reboots, so the
149
156
  // PID may have been recycled to an unrelated process (#1927).
150
- removeDashboardServerInfo();
157
+ if (probe.status === 'unverified')
158
+ removeDashboardServerInfo();
151
159
  return null;
152
160
  }
161
+ const PS_PATHS = ['/bin/ps', '/usr/bin/ps'];
162
+ /** The CLI entries a server is started from: the bundle, a source entry, or the npm bin. */
163
+ const EVAL_FLAGS = new Set(['-e', '--eval', '-p', '--print']);
164
+ const CLI_ENTRY = /^(?:cli\.(?:bundle\.cjs|ts|js)|oss-autopilot)$/;
165
+ /**
166
+ * True only for the command line the launchers spawn: `node [--flags] <cli
167
+ * entry> dashboard serve ...`. Matching "dashboard serve" anywhere in argv
168
+ * would accept a recycled PID now running e.g. `grep -rn "dashboard serve"`
169
+ * or a shell wrapper. Anything else, including paths with spaces and a tsx
170
+ * dev server, reads as false, which only ever means "never signal".
171
+ */
172
+ export function isDashboardServeCommand(command) {
173
+ const tokens = command.trim().split(/\s+/);
174
+ if (!/^node(?:js)?$/.test(path.basename(tokens[0])))
175
+ return false;
176
+ let i = 1;
177
+ while (tokens[i]?.startsWith('-')) {
178
+ // With -e / -p the next token is code, not the script.
179
+ if (EVAL_FLAGS.has(tokens[i].split('=', 1)[0]))
180
+ return false;
181
+ i++;
182
+ }
183
+ return (i + 2 < tokens.length &&
184
+ CLI_ENTRY.test(path.basename(tokens[i])) &&
185
+ tokens[i + 1] === 'dashboard' &&
186
+ tokens[i + 2] === 'serve');
187
+ }
188
+ /**
189
+ * True only when the process at `pid` is a `dashboard serve` process, read
190
+ * from its command line (see isDashboardServeCommand). This is what lets a
191
+ * caller signal a server that does not answer `/api/health` (#1882) without
192
+ * ever signalling a PID that was recycled to an unrelated program (#1927).
193
+ * Anything that cannot be checked (no `ps`, as on Windows, or an exited PID)
194
+ * reads as false.
195
+ */
196
+ export function isDashboardServeProcess(pid) {
197
+ // An absolute path, so a `ps` earlier on PATH cannot answer for it.
198
+ const ps = PS_PATHS.find((candidate) => fs.existsSync(candidate));
199
+ if (!ps)
200
+ return false;
201
+ try {
202
+ const command = execFileSync(ps, ['-o', 'command=', '-p', String(pid)], {
203
+ encoding: 'utf8',
204
+ timeout: 2000,
205
+ stdio: ['ignore', 'pipe', 'ignore'],
206
+ });
207
+ return isDashboardServeCommand(command);
208
+ }
209
+ catch {
210
+ return false;
211
+ }
212
+ }
@@ -20,7 +20,7 @@
20
20
  */
21
21
  import { getStateManager, maybeCheckpoint } from '../core/index.js';
22
22
  import { ValidationError } from '../core/errors.js';
23
- import { findRefKey } from '../core/urls.js';
23
+ import { findRefKey, issueRefKey } from '../core/urls.js';
24
24
  import { ISSUE_OR_PR_URL_PATTERN, PR_URL_PATTERN, validateCommitSha, validateGitHubUrl, validateUrl, } from './validation.js';
25
25
  const MODULE = 'dismiss';
26
26
  /**
@@ -30,14 +30,15 @@ const MODULE = 'dismiss';
30
30
  * when the PR is shelved: `daily` keeps shelved PRs in `openPRs` but out of
31
31
  * Needs Attention, and `move <pr-url> waiting` would unshelve one.
32
32
  *
33
- * URL validation accepts any owner/repo casing while `openPRs` holds GitHub's,
34
- * so the match is case-insensitive and the suggested `move` command uses the
35
- * stored URL, which is the one `daily` checks against the shelf.
33
+ * URL validation accepts any owner/repo casing, and the `/issues/N` form of a
34
+ * PR already dismissed as `/pull/N`, while `openPRs` holds GitHub's URL, so
35
+ * the match is by {@link issueRefKey} and the suggested `move` command uses
36
+ * the stored URL, which is the one `daily` checks against the shelf.
36
37
  */
37
38
  function openPRDismissWarning(stateManager, url) {
38
39
  const openPRs = stateManager.getState().lastDigest?.openPRs ?? [];
39
- const wanted = url.toLowerCase();
40
- const openPR = openPRs.find((pr) => pr.url.toLowerCase() === wanted);
40
+ const wanted = issueRefKey(url);
41
+ const openPR = wanted === null ? undefined : openPRs.find((pr) => issueRefKey(pr.url) === wanted);
41
42
  if (!openPR || stateManager.isPRShelved(openPR.url))
42
43
  return undefined;
43
44
  return (`${openPR.url} is one of your open PRs. dismiss records it but does not clear the PR from Needs Attention; ` +
@@ -18,7 +18,7 @@ import { getGitHubTokenAsync, getOctokit, getStatePath } from '../core/index.js'
18
18
  import { AgentStateSchema } from '../core/state-schema.js';
19
19
  import { errorMessage } from '../core/errors.js';
20
20
  import { resolveDataDir } from '../core/paths.js';
21
- import { WORKTREE_NAME, staleRejectedCopies } from '../core/stale-data.js';
21
+ import { countStaleData } from '../core/stale-data.js';
22
22
  import { LAUNCHD_LABEL, isScheduleCurrent } from './overnight.js';
23
23
  const execFileAsync = promisify(execFile);
24
24
  const GH_CMD_TIMEOUT_MS = 3000;
@@ -309,13 +309,6 @@ export async function checkGitHubRateLimit(preloadedToken) {
309
309
  };
310
310
  }
311
311
  }
312
- function countStaleData(dataDir) {
313
- const root = path.join(dataDir, 'worktrees');
314
- const hasRoot = fs.existsSync(root) && fs.lstatSync(root).isDirectory();
315
- const entries = hasRoot ? fs.readdirSync(root, { withFileTypes: true }) : [];
316
- const worktrees = entries.filter((entry) => entry.isDirectory() && WORKTREE_NAME.test(entry.name));
317
- return { worktrees: worktrees.length, rejected: staleRejectedCopies(dataDir).length };
318
- }
319
312
  /**
320
313
  * Stale data under the data directory (#1956): counts only, from the file
321
314
  * system; no Git runs here. Which worktrees are safe to remove, and why the
@@ -0,0 +1,58 @@
1
+ /**
2
+ * fork-prune (#1912): list the user's forks that no longer back any open PR
3
+ * or unmerged work, and with `--apply` delete them.
4
+ *
5
+ * Dry run by default. `--apply` needs `--expect <digest>` from a dry run and
6
+ * refuses when the prunable set computed now has a different digest, so it
7
+ * deletes exactly the set the user reviewed. Right before each delete it
8
+ * re-evaluates that fork from fresh reads and skips it if it is no longer
9
+ * prunable, then re-reads the repository over REST and deletes it only when
10
+ * GitHub still says it is a fork the user owns. Never in an unattended run,
11
+ * never over MCP.
12
+ */
13
+ import type { AgentState } from '../core/types.js';
14
+ import { type ForkVerdict } from '../core/fork-prune.js';
15
+ export interface ForkPruneOptions {
16
+ /** Delete the prunable set. */
17
+ apply?: boolean;
18
+ /** Digest of the prunable set a dry run printed; required with `apply`. */
19
+ expect?: string;
20
+ /** Called after each successful delete, so a terminal shows it as it happens. */
21
+ onDeleted?: (repo: string) => void;
22
+ }
23
+ export interface ForkPruneOutput {
24
+ mode: 'dry-run' | 'apply';
25
+ login: string;
26
+ forks: ForkVerdict[];
27
+ prunable: number;
28
+ kept: number;
29
+ /** SHA-256 of the sorted prunable fork names; pass it to `--apply --expect`. */
30
+ setDigest: string;
31
+ /** The command that deletes exactly this set; dry run with at least one prunable fork only. */
32
+ applyCommand?: string;
33
+ /** GraphQL requests the scan made. */
34
+ requests: number;
35
+ deleted?: string[];
36
+ skipped?: Array<{
37
+ repo: string;
38
+ reasons: string[];
39
+ }>;
40
+ /** Why apply stopped before the end of the set. */
41
+ error?: string;
42
+ }
43
+ export declare const DELETE_SCOPE = "delete_repo";
44
+ export declare const SCOPE_COMMAND = "gh auth refresh -h github.com -s delete_repo";
45
+ /** The cached dry-run count the daily digest reads, so `daily` makes no fork scan. */
46
+ export declare const FORK_PRUNE_SUMMARY_FILE = "fork-prune-summary.json";
47
+ /** How long a cached count stays in the digest. */
48
+ export declare const FORK_PRUNE_SUMMARY_MAX_AGE_MS: number;
49
+ /** Lowercase repos local state refers to: claimed issues, work claims, prepared overnight branches. */
50
+ export declare function referencedRepos(state: Readonly<AgentState>): Set<string>;
51
+ /** A fingerprint of the prunable set that ignores order: the XOR of each lowercase name's SHA-256, then hashed with the count. */
52
+ export declare function setDigest(verdicts: readonly ForkVerdict[]): string;
53
+ /** The digest line from the last dry run, or null when there is none, it is stale, or nothing is prunable. */
54
+ export declare function cachedForkPruneLine(nowMs?: number): string | null;
55
+ /** List the prunable forks; with `apply`, delete them (see the module comment for the checks). */
56
+ export declare function runForkPrune(options?: ForkPruneOptions): Promise<ForkPruneOutput>;
57
+ /** Text mode: one row per fork, then the totals and what to run next. */
58
+ export declare function printForkPrune(data: ForkPruneOutput): void;
@@ -0,0 +1,247 @@
1
+ /**
2
+ * fork-prune (#1912): list the user's forks that no longer back any open PR
3
+ * or unmerged work, and with `--apply` delete them.
4
+ *
5
+ * Dry run by default. `--apply` needs `--expect <digest>` from a dry run and
6
+ * refuses when the prunable set computed now has a different digest, so it
7
+ * deletes exactly the set the user reviewed. Right before each delete it
8
+ * re-evaluates that fork from fresh reads and skips it if it is no longer
9
+ * prunable, then re-reads the repository over REST and deletes it only when
10
+ * GitHub still says it is a fork the user owns. Never in an unattended run,
11
+ * never over MCP.
12
+ */
13
+ import { createHash } from 'node:crypto';
14
+ import * as fs from 'node:fs';
15
+ import path from 'node:path';
16
+ import { getOctokit, getStateManager, parseGitHubUrl, requireGitHubToken } from '../core/index.js';
17
+ import { ConfigurationError, ValidationError, assertAttended, errorMessage, getHttpStatusCode, } from '../core/errors.js';
18
+ import { getDataDir } from '../core/paths.js';
19
+ import { CountingGraphQL, UNCHECKED_OPEN_PRS, evaluateAll, fetchBranchPRs, fetchFork, fetchForks, fetchOpenPRHeadRepos, } from '../core/fork-prune.js';
20
+ export const DELETE_SCOPE = 'delete_repo';
21
+ export const SCOPE_COMMAND = `gh auth refresh -h github.com -s ${DELETE_SCOPE}`;
22
+ /** The cached dry-run count the daily digest reads, so `daily` makes no fork scan. */
23
+ export const FORK_PRUNE_SUMMARY_FILE = 'fork-prune-summary.json';
24
+ /** How long a cached count stays in the digest. */
25
+ export const FORK_PRUNE_SUMMARY_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
26
+ /** Lowercase repos local state refers to: claimed issues, work claims, prepared overnight branches. */
27
+ export function referencedRepos(state) {
28
+ const urls = [
29
+ ...state.activeIssues.filter((issue) => issue.status !== 'candidate').map((issue) => issue.url),
30
+ ...(state.workClaims ?? []).map((claim) => claim.url),
31
+ ...(state.lastOvernight?.prepared ?? []).map((item) => item.url),
32
+ ];
33
+ const repos = new Set();
34
+ for (const url of urls) {
35
+ const parsed = parseGitHubUrl(url);
36
+ if (parsed)
37
+ repos.add(`${parsed.owner}/${parsed.repo}`.toLowerCase());
38
+ }
39
+ return repos;
40
+ }
41
+ /** A fingerprint of the prunable set that ignores order: the XOR of each lowercase name's SHA-256, then hashed with the count. */
42
+ export function setDigest(verdicts) {
43
+ const names = verdicts.filter((v) => v.verdict === 'PRUNE').map((v) => v.repo.toLowerCase());
44
+ const combined = Buffer.alloc(32);
45
+ for (const name of names) {
46
+ const hash = createHash('sha256').update(name).digest();
47
+ for (const [i, byte] of hash.entries())
48
+ combined[i] ^= byte;
49
+ }
50
+ return createHash('sha256').update(combined).update(String(names.length)).digest('hex');
51
+ }
52
+ async function contextFor(gql, login, forks, state) {
53
+ return {
54
+ login,
55
+ openPRHeadRepos: await fetchOpenPRHeadRepos(gql),
56
+ referencedRepos: referencedRepos(state),
57
+ keepForks: new Set((state.config.keepForks ?? []).map((repo) => repo.toLowerCase())),
58
+ branchPRs: await fetchBranchPRs(gql, forks, login),
59
+ };
60
+ }
61
+ /** The full scan, shared by the dry run and apply. */
62
+ async function scan(gql, state) {
63
+ const { login, forks } = await fetchForks(gql);
64
+ const ctx = await contextFor(gql, login, forks, state);
65
+ return { login, verdicts: await evaluateAll(gql, forks, ctx) };
66
+ }
67
+ /** Throw when the token lacks `delete_repo`. A token with no `X-OAuth-Scopes` header (fine-grained) is checked at the delete. */
68
+ async function assertDeleteScope(octokit) {
69
+ const response = await octokit.request('GET /user');
70
+ const header = response.headers['x-oauth-scopes'];
71
+ if (typeof header !== 'string')
72
+ return;
73
+ const scopes = header.split(',').map((scope) => scope.trim());
74
+ if (!scopes.includes(DELETE_SCOPE))
75
+ throw missingScopeError();
76
+ }
77
+ function missingScopeError() {
78
+ return new ConfigurationError(`Deleting forks needs the ${DELETE_SCOPE} token scope, which this token does not have. ` +
79
+ `Grant it yourself, then run the command again: ${SCOPE_COMMAND}`);
80
+ }
81
+ /** Why `repo` must not be deleted, judged from a fresh REST read; null when it is still the user's fork. */
82
+ async function freshForkProblem(octokit, repo, login) {
83
+ const [owner, name] = repo.split('/', 2);
84
+ const { data } = await octokit.repos.get({ owner, repo: name });
85
+ if (!data.fork || !data.parent)
86
+ return 'not a fork when read right before the delete';
87
+ if (data.owner.login.toLowerCase() !== login.toLowerCase())
88
+ return 'not owned by you';
89
+ return null;
90
+ }
91
+ /** Re-evaluate one fork from fresh reads; the reasons it must be kept, or [] when it is still prunable. */
92
+ async function recheck(gql, repo, login, state) {
93
+ const fork = await fetchFork(gql, repo);
94
+ if (!fork)
95
+ return ['no longer exists'];
96
+ const [verdict] = await evaluateAll(gql, [fork], await contextFor(gql, login, [fork], state));
97
+ return verdict.reasons;
98
+ }
99
+ /** Re-check one fork and delete it, or say why not. Throws on a failed read or delete. */
100
+ async function pruneOne(octokit, gql, login, repo) {
101
+ // Checked again here, where the delete is, not only by the caller.
102
+ assertAttended('delete forks');
103
+ const reasons = await recheck(gql, repo, login, getStateManager().getState());
104
+ if (reasons.length > 0)
105
+ return { reasons };
106
+ const problem = await freshForkProblem(octokit, repo, login);
107
+ if (problem)
108
+ return { reasons: [problem] };
109
+ const [owner, name] = repo.split('/', 2);
110
+ await octokit.repos.delete({ owner, repo: name });
111
+ return { isDeleted: true };
112
+ }
113
+ function stopReason(error, repo) {
114
+ if (getHttpStatusCode(error) === 403)
115
+ return missingScopeError().message;
116
+ return `stopped at ${repo}: ${errorMessage(error)}`;
117
+ }
118
+ /** Delete `targets` one by one; any error stops the run and is returned with what was done so far. */
119
+ async function applyDeletes(octokit, gql, login, targets, onDeleted) {
120
+ const deleted = [];
121
+ const skipped = [];
122
+ for (const repo of targets) {
123
+ let outcome;
124
+ try {
125
+ outcome = await pruneOne(octokit, gql, login, repo);
126
+ }
127
+ catch (error) {
128
+ return { deleted, skipped, error: stopReason(error, repo) };
129
+ }
130
+ if ('reasons' in outcome) {
131
+ skipped.push({ repo, reasons: outcome.reasons });
132
+ }
133
+ else {
134
+ deleted.push(repo);
135
+ onDeleted?.(repo);
136
+ }
137
+ }
138
+ return { deleted, skipped };
139
+ }
140
+ function summaryFile() {
141
+ return path.join(getDataDir(), FORK_PRUNE_SUMMARY_FILE);
142
+ }
143
+ function writeSummary(prunable) {
144
+ const now = new Date();
145
+ fs.writeFileSync(summaryFile(), JSON.stringify({ prunable, checkedAt: now.toISOString() }), { mode: 0o600 });
146
+ }
147
+ /** The cached summary as stored, or null when it is missing or unreadable. */
148
+ function readSummary() {
149
+ let text;
150
+ try {
151
+ text = fs.readFileSync(summaryFile(), 'utf8');
152
+ }
153
+ catch {
154
+ return null;
155
+ }
156
+ try {
157
+ return JSON.parse(text);
158
+ }
159
+ catch {
160
+ return null;
161
+ }
162
+ }
163
+ /** The digest line from the last dry run, or null when there is none, it is stale, or nothing is prunable. */
164
+ export function cachedForkPruneLine(nowMs = Date.now()) {
165
+ const summary = readSummary();
166
+ if (summary === null)
167
+ return null;
168
+ const { prunable, checkedAt } = summary;
169
+ if (typeof prunable !== 'number' || typeof checkedAt !== 'string' || prunable <= 0)
170
+ return null;
171
+ const checkedMs = Date.parse(checkedAt);
172
+ if (!Number.isFinite(checkedMs) || checkedMs > nowMs || nowMs - checkedMs > FORK_PRUNE_SUMMARY_MAX_AGE_MS)
173
+ return null;
174
+ const forks = prunable === 1 ? 'fork' : 'forks';
175
+ return `🍴 ${prunable} ${forks} prunable (checked ${checkedAt.slice(0, 10)}; run fork-prune to review)`;
176
+ }
177
+ /** List the prunable forks; with `apply`, delete them (see the module comment for the checks). */
178
+ export async function runForkPrune(options = {}) {
179
+ if (options.apply) {
180
+ assertAttended('delete forks');
181
+ if (!options.expect) {
182
+ throw new ValidationError('--apply needs --expect <digest> from a dry run, so it deletes the set you reviewed');
183
+ }
184
+ }
185
+ const octokit = getOctokit(requireGitHubToken());
186
+ if (options.apply)
187
+ await assertDeleteScope(octokit);
188
+ const gql = new CountingGraphQL(octokit.graphql);
189
+ const { login, verdicts } = await scan(gql, getStateManager().getState());
190
+ const digest = setDigest(verdicts);
191
+ const targets = verdicts.filter((v) => v.verdict === 'PRUNE').map((v) => v.repo);
192
+ const base = {
193
+ login,
194
+ forks: verdicts,
195
+ prunable: targets.length,
196
+ kept: verdicts.length - targets.length,
197
+ setDigest: digest,
198
+ };
199
+ if (!options.apply) {
200
+ writeSummary(targets.length);
201
+ return {
202
+ ...base,
203
+ mode: 'dry-run',
204
+ requests: gql.requests,
205
+ ...(targets.length > 0 && { applyCommand: `oss-autopilot fork-prune --apply --expect ${digest}` }),
206
+ };
207
+ }
208
+ if (digest !== options.expect) {
209
+ throw new ValidationError(`The prunable set changed since the dry run (${targets.length} fork(s) now); nothing was deleted. ` +
210
+ 'Run the dry run again and pass its new --expect value.');
211
+ }
212
+ const result = await applyDeletes(octokit, gql, login, targets, options.onDeleted);
213
+ // The digest line must not keep announcing forks that are gone.
214
+ writeSummary(targets.length - result.deleted.length);
215
+ return { ...base, mode: 'apply', requests: gql.requests, ...result };
216
+ }
217
+ function printRow(fork) {
218
+ const prs = `open PRs from fork: ${fork.hasOpenPRFromFork ? 'yes' : 'no'}, to fork: ${fork.openPRsToFork}`;
219
+ const own = fork.ownBranches.map((b) => `${b.name} [${b.prStates.join(',') || 'no PR'}]`).join('; ');
220
+ console.log(`${fork.verdict} ${fork.repo} parent: ${fork.parent ?? '(none)'} branches: ${fork.branchCount} ${prs}`);
221
+ if (own)
222
+ console.log(` your branches: ${own}`);
223
+ for (const reason of fork.reasons)
224
+ console.log(` keep: ${reason}`);
225
+ }
226
+ /** Text mode: one row per fork, then the totals and what to run next. */
227
+ export function printForkPrune(data) {
228
+ for (const fork of data.forks)
229
+ printRow(fork);
230
+ console.log(`\n${data.prunable} prunable, ${data.kept} kept (${data.requests} GraphQL requests)`);
231
+ if (data.mode === 'dry-run') {
232
+ console.log('A branch whose pull request was closed without merging counts as finished: its commits then remain only in that pull request on the parent repository.');
233
+ }
234
+ const unchecked = data.forks.filter((fork) => fork.reasons.includes(UNCHECKED_OPEN_PRS)).length;
235
+ if (unchecked > 0)
236
+ console.log(`${unchecked} fork(s) kept because their branches could not be checked for open PRs`);
237
+ if (data.applyCommand)
238
+ console.log(`To delete exactly these: ${data.applyCommand}`);
239
+ // Each delete was printed as it happened (onDeleted); this is the count.
240
+ if (data.deleted)
241
+ console.log(`${data.deleted.length} fork(s) deleted`);
242
+ if (data.skipped)
243
+ for (const skip of data.skipped)
244
+ console.log(`Skipped ${skip.repo}: ${skip.reasons.join('; ')}`);
245
+ if (data.error)
246
+ console.log(`Stopped: ${data.error}`);
247
+ }
@@ -1,4 +1,6 @@
1
+ import { type StoredMergedPR } from '../core/index.js';
1
2
  import { type PRCommentBundle } from '../core/pr-comments-fetcher.js';
3
+ import type { GuidelineProposalStatus } from '../formatters/json.js';
2
4
  export interface GuidelinesViewOutput {
3
5
  repo: string;
4
6
  /** Markdown content, or null when the repo has no guidelines stored. */
@@ -79,6 +81,15 @@ export interface FetchCorpusOutput {
79
81
  */
80
82
  warnings?: string[];
81
83
  }
84
+ export interface MarkProposedOutput {
85
+ repo: string;
86
+ /** The proposal file that was found, from {@link guidelineProposalPath}. */
87
+ path: string;
88
+ /** PRs stamped `learningsProposedAt` this call. */
89
+ marked: number;
90
+ /** Set when the post-mutation Gist checkpoint failed; the local mutation succeeded (#1370). */
91
+ gistSyncWarning?: string;
92
+ }
82
93
  interface RepoOption {
83
94
  repo: string;
84
95
  }
@@ -100,6 +111,27 @@ interface StoreOptions extends RepoOption {
100
111
  /** When set, refuse unless `content` hashes to it: the text the user approved via `draft show` (#1930). */
101
112
  expectSha256?: string;
102
113
  }
114
+ /** Whether `repo` is a name a proposal file can be named after (#2041); others get no proposal. */
115
+ export declare function isProposalRepo(repo: string): boolean;
116
+ /**
117
+ * Where this machine keeps the guideline proposal for `repo` (#1929, #2041):
118
+ * `guidelines-<owner>--<repo>.md` in the draft directory. The only place the
119
+ * name is computed; the prompts take it from `daily` or `draft path`.
120
+ */
121
+ export declare function guidelineProposalPath(repo: string): string;
122
+ /**
123
+ * Whether a guideline proposal for `repo` is waiting for review (#2041).
124
+ * `prs` are the repo's PRs that still lack `learningsExtractedAt`.
125
+ *
126
+ * A file at {@link guidelineProposalPath} is a proposal on this machine.
127
+ * Without one, a `learningsProposedAt` stamp written by another machine
128
+ * (`guidelines mark-proposed`, synced through the Gist) means a proposal for
129
+ * these PRs waits there, so this machine must not extract them again. Both
130
+ * expire with the draft retention, {@link MAX_DRAFT_AGE_MS}: `getDraftsDir`
131
+ * deletes an older file, and an older stamp is ignored. A stamp this machine
132
+ * wrote whose file is gone is ignored too, so the repo is extracted again.
133
+ */
134
+ export declare function guidelineProposalStatus(repo: string, prs: ReadonlyArray<Pick<StoredMergedPR, 'learningsProposedAt' | 'learningsProposedOn'>>, nowMs?: number): GuidelineProposalStatus;
103
135
  /** Read the per-repo guidelines for `repo`. Returns a `local-unavailable` envelope in non-Gist mode. */
104
136
  export declare function runGuidelinesView(options: RepoOption): Promise<GuidelinesViewOutput>;
105
137
  /**
@@ -128,7 +160,20 @@ export declare function runGuidelinesStore(options: StoreOptions): Promise<Guide
128
160
  * as unextracted. Idempotent: already-stamped PRs are left alone.
129
161
  */
130
162
  export declare function runMarkExtracted(options: RepoOption): Promise<MarkExtractedOutput>;
131
- /** Tombstone the guidelines file for `repo`. */
163
+ /**
164
+ * Record that the proposal file for `repo` is written and waits for review on
165
+ * this machine (#2041): stamp `learningsProposedAt` and this machine's id on
166
+ * the PRs it was built from (fetched, not yet extracted). The stamp is synced
167
+ * through the Gist, so another machine's `daily` reports the proposal as held
168
+ * elsewhere instead of extracting the same PRs again. Refuses when no file
169
+ * is at {@link guidelineProposalPath}.
170
+ */
171
+ export declare function runMarkProposed(options: RepoOption): Promise<MarkProposedOutput>;
172
+ /**
173
+ * Tombstone the guidelines file for `repo`. Refused during an unattended run,
174
+ * like {@link runGuidelinesStore}: the stored text is guidelines the user
175
+ * reviewed, and nobody is there to agree to losing them (#2036).
176
+ */
132
177
  export declare function runGuidelinesReset(options: RepoOption): Promise<GuidelinesResetOutput>;
133
178
  /**
134
179
  * Fetch raw PR comment bundles for the most recent merged/closed PRs in `repo`