@oss-autopilot/core 3.42.5 → 3.44.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (192) hide show
  1. package/dist/cli-pre-action.js +8 -3
  2. package/dist/cli-registry.js +428 -27
  3. package/dist/cli.bundle.cjs +212 -156
  4. package/dist/commands/check-integration.js +5 -1
  5. package/dist/commands/cleanup.d.ts +80 -0
  6. package/dist/commands/cleanup.js +334 -0
  7. package/dist/commands/comments.d.ts +14 -1
  8. package/dist/commands/comments.js +17 -5
  9. package/dist/commands/config.d.ts +2 -0
  10. package/dist/commands/config.js +63 -6
  11. package/dist/commands/daily-dismiss-filter.d.ts +7 -0
  12. package/dist/commands/daily-dismiss-filter.js +17 -1
  13. package/dist/commands/daily-ledger.d.ts +150 -0
  14. package/dist/commands/daily-ledger.js +248 -0
  15. package/dist/commands/daily-recent-prs.d.ts +26 -0
  16. package/dist/commands/daily-recent-prs.js +55 -0
  17. package/dist/commands/daily-render.d.ts +2 -1
  18. package/dist/commands/daily-render.js +4 -1
  19. package/dist/commands/daily.d.ts +5 -1
  20. package/dist/commands/daily.js +83 -93
  21. package/dist/commands/dashboard-cache.d.ts +2 -0
  22. package/dist/commands/dashboard-cache.js +33 -8
  23. package/dist/commands/dashboard-data.js +113 -69
  24. package/dist/commands/dashboard-gist-sync.js +3 -1
  25. package/dist/commands/dashboard-lifecycle.d.ts +36 -8
  26. package/dist/commands/dashboard-lifecycle.js +132 -39
  27. package/dist/commands/dashboard-process.d.ts +49 -1
  28. package/dist/commands/dashboard-process.js +111 -12
  29. package/dist/commands/dashboard-server.js +89 -23
  30. package/dist/commands/detect-formatters.js +1 -0
  31. package/dist/commands/dismiss.js +11 -7
  32. package/dist/commands/doctor.d.ts +15 -1
  33. package/dist/commands/doctor.js +66 -5
  34. package/dist/commands/draft.d.ts +77 -0
  35. package/dist/commands/draft.js +218 -0
  36. package/dist/commands/eval.js +1 -0
  37. package/dist/commands/fork-prune.d.ts +58 -0
  38. package/dist/commands/fork-prune.js +247 -0
  39. package/dist/commands/guidelines.d.ts +69 -2
  40. package/dist/commands/guidelines.js +158 -14
  41. package/dist/commands/index.d.ts +29 -4
  42. package/dist/commands/index.js +20 -3
  43. package/dist/commands/issue-thread.d.ts +46 -0
  44. package/dist/commands/issue-thread.js +123 -0
  45. package/dist/commands/ledger-backfill.d.ts +9 -0
  46. package/dist/commands/ledger-backfill.js +44 -1
  47. package/dist/commands/list-mark-done.d.ts +2 -1
  48. package/dist/commands/list-mark-done.js +3 -1
  49. package/dist/commands/list-move-tier.d.ts +2 -1
  50. package/dist/commands/list-move-tier.js +3 -1
  51. package/dist/commands/local-repos.js +10 -5
  52. package/dist/commands/locate-issue-list.d.ts +40 -17
  53. package/dist/commands/locate-issue-list.js +148 -88
  54. package/dist/commands/move.js +7 -1
  55. package/dist/commands/overnight-handoff.d.ts +17 -7
  56. package/dist/commands/overnight-handoff.js +36 -14
  57. package/dist/commands/overnight-push-prep.d.ts +14 -8
  58. package/dist/commands/overnight-push-prep.js +107 -35
  59. package/dist/commands/overnight-tool-rules.d.ts +54 -0
  60. package/dist/commands/overnight-tool-rules.js +217 -0
  61. package/dist/commands/overnight.d.ts +5 -6
  62. package/dist/commands/overnight.js +61 -140
  63. package/dist/commands/parse-list.js +7 -1
  64. package/dist/commands/policy.d.ts +90 -0
  65. package/dist/commands/policy.js +276 -0
  66. package/dist/commands/pr-create.d.ts +48 -0
  67. package/dist/commands/pr-create.js +200 -0
  68. package/dist/commands/pr-preflight.d.ts +69 -0
  69. package/dist/commands/pr-preflight.js +348 -0
  70. package/dist/commands/repo-vet.d.ts +9 -0
  71. package/dist/commands/repo-vet.js +36 -11
  72. package/dist/commands/scout-bridge.js +18 -8
  73. package/dist/commands/search.js +7 -0
  74. package/dist/commands/setup.d.ts +3 -3
  75. package/dist/commands/setup.js +160 -48
  76. package/dist/commands/skip-add.js +10 -1
  77. package/dist/commands/startup.d.ts +12 -3
  78. package/dist/commands/startup.js +82 -49
  79. package/dist/commands/state-cmd.d.ts +2 -0
  80. package/dist/commands/state-cmd.js +5 -1
  81. package/dist/commands/stats.js +1 -0
  82. package/dist/commands/status.js +6 -0
  83. package/dist/commands/strategy.js +1 -0
  84. package/dist/commands/validation.d.ts +5 -0
  85. package/dist/commands/validation.js +5 -0
  86. package/dist/commands/vet-list.d.ts +6 -0
  87. package/dist/commands/vet-list.js +26 -1
  88. package/dist/commands/vet.d.ts +20 -0
  89. package/dist/commands/vet.js +133 -2
  90. package/dist/commands/work.d.ts +4 -0
  91. package/dist/commands/work.js +34 -11
  92. package/dist/core/__fixtures__/prompt-injection-payloads.js +31 -0
  93. package/dist/core/anti-llm-policy.d.ts +3 -0
  94. package/dist/core/anti-llm-policy.js +3 -0
  95. package/dist/core/auth.js +2 -0
  96. package/dist/core/ci-analysis.d.ts +7 -2
  97. package/dist/core/ci-analysis.js +76 -21
  98. package/dist/core/commit-date.d.ts +45 -0
  99. package/dist/core/commit-date.js +45 -0
  100. package/dist/core/compliance-score.d.ts +3 -0
  101. package/dist/core/compliance-score.js +13 -9
  102. package/dist/core/config-registry.d.ts +27 -2
  103. package/dist/core/config-registry.js +94 -7
  104. package/dist/core/contributing.d.ts +2 -3
  105. package/dist/core/contributing.js +2 -3
  106. package/dist/core/daily-logic.d.ts +30 -5
  107. package/dist/core/daily-logic.js +68 -19
  108. package/dist/core/errors.d.ts +37 -3
  109. package/dist/core/errors.js +54 -5
  110. package/dist/core/fork-prune.d.ts +149 -0
  111. package/dist/core/fork-prune.js +333 -0
  112. package/dist/core/gist-health.d.ts +15 -3
  113. package/dist/core/gist-health.js +8 -0
  114. package/dist/core/gist-state-store.d.ts +24 -4
  115. package/dist/core/gist-state-store.js +98 -51
  116. package/dist/core/github-stats.d.ts +110 -16
  117. package/dist/core/github-stats.js +295 -110
  118. package/dist/core/http-cache.d.ts +0 -10
  119. package/dist/core/http-cache.js +0 -19
  120. package/dist/core/index.d.ts +13 -6
  121. package/dist/core/index.js +16 -6
  122. package/dist/core/issue-conversation.d.ts +8 -2
  123. package/dist/core/issue-conversation.js +31 -12
  124. package/dist/core/local-config.d.ts +95 -0
  125. package/dist/core/local-config.js +270 -0
  126. package/dist/core/merged-pr-notes.d.ts +2 -2
  127. package/dist/core/pacing.d.ts +41 -0
  128. package/dist/core/pacing.js +115 -0
  129. package/dist/core/pagination.d.ts +55 -0
  130. package/dist/core/pagination.js +59 -0
  131. package/dist/core/paths.d.ts +7 -0
  132. package/dist/core/paths.js +9 -0
  133. package/dist/core/pr-assembly.d.ts +2 -0
  134. package/dist/core/pr-assembly.js +6 -2
  135. package/dist/core/pr-graphql.d.ts +53 -4
  136. package/dist/core/pr-graphql.js +87 -14
  137. package/dist/core/pr-monitor.d.ts +35 -12
  138. package/dist/core/pr-monitor.js +110 -26
  139. package/dist/core/pr-preflight.d.ts +154 -0
  140. package/dist/core/pr-preflight.js +753 -0
  141. package/dist/core/pr-quality-rubric.d.ts +0 -6
  142. package/dist/core/pr-quality-rubric.js +0 -8
  143. package/dist/core/pr-template.d.ts +2 -0
  144. package/dist/core/pr-template.js +5 -1
  145. package/dist/core/prose-script.d.ts +72 -0
  146. package/dist/core/prose-script.js +223 -0
  147. package/dist/core/repo-policy.d.ts +111 -0
  148. package/dist/core/repo-policy.js +428 -0
  149. package/dist/core/repo-score-manager.d.ts +66 -0
  150. package/dist/core/repo-score-manager.js +140 -1
  151. package/dist/core/review-analysis.d.ts +49 -21
  152. package/dist/core/review-analysis.js +89 -15
  153. package/dist/core/reviewed-prs-fetch.js +11 -29
  154. package/dist/core/reviewed-prs.js +8 -15
  155. package/dist/core/stale-data.d.ts +78 -0
  156. package/dist/core/stale-data.js +153 -0
  157. package/dist/core/state-persistence.d.ts +62 -27
  158. package/dist/core/state-persistence.js +338 -119
  159. package/dist/core/state-schema.d.ts +152 -210
  160. package/dist/core/state-schema.js +232 -80
  161. package/dist/core/state.d.ts +81 -8
  162. package/dist/core/state.js +239 -46
  163. package/dist/core/status-determination.js +32 -12
  164. package/dist/core/strategy.js +3 -1
  165. package/dist/core/types.d.ts +22 -1
  166. package/dist/core/types.js +1 -0
  167. package/dist/core/untrusted-content.d.ts +30 -11
  168. package/dist/core/untrusted-content.js +95 -42
  169. package/dist/core/urls.d.ts +33 -0
  170. package/dist/core/urls.js +94 -0
  171. package/dist/dashboard/assets/chart-panel-B-nLVgzQ.js +3 -0
  172. package/dist/dashboard/assets/index-5IvMGokL.js +55 -0
  173. package/dist/dashboard/index.html +1 -1
  174. package/dist/formatters/json.d.ts +432 -10
  175. package/dist/formatters/json.js +156 -1
  176. package/package.json +6 -6
  177. package/dist/core/ci-enforced-tools.d.ts +0 -35
  178. package/dist/core/ci-enforced-tools.js +0 -109
  179. package/dist/core/comment-decision.d.ts +0 -79
  180. package/dist/core/comment-decision.js +0 -82
  181. package/dist/core/extraction-categories.d.ts +0 -55
  182. package/dist/core/extraction-categories.js +0 -108
  183. package/dist/core/follow-up-history.d.ts +0 -40
  184. package/dist/core/follow-up-history.js +0 -71
  185. package/dist/core/issue-effort.d.ts +0 -29
  186. package/dist/core/issue-effort.js +0 -47
  187. package/dist/core/maintainer-hints.d.ts +0 -23
  188. package/dist/core/maintainer-hints.js +0 -36
  189. package/dist/core/workflow-state.d.ts +0 -56
  190. package/dist/core/workflow-state.js +0 -101
  191. package/dist/dashboard/assets/chart-panel-DPKNBUts.js +0 -3
  192. package/dist/dashboard/assets/index-B25bZOYX.js +0 -55
@@ -0,0 +1,77 @@
1
+ /** Largest draft a command reads. GitHub caps a comment body at 65536 characters; each command's own cap still applies. */
2
+ export declare const MAX_DRAFT_BYTES: number;
3
+ /** Drafts the user never posted or discarded are removed after this long. */
4
+ export declare const MAX_DRAFT_AGE_MS: number;
5
+ export interface DraftPathOutput {
6
+ /** Absolute path for the draft. The file is not created. */
7
+ path: string;
8
+ /** The owner-only draft directory. */
9
+ dir: string;
10
+ }
11
+ export interface DraftContent {
12
+ path: string;
13
+ /** The file's text, from the same single read that produced `sha256`. */
14
+ content: string;
15
+ /** SHA-256 (hex) of the file's text as UTF-8. Pass it back as `--expect-sha256`. */
16
+ sha256: string;
17
+ byteSize: number;
18
+ }
19
+ export interface DraftShowOutput extends DraftContent {
20
+ /** True when `content` is wrapped in the untrusted-content fence (`--untrusted`). `sha256` is always of the unwrapped text. */
21
+ fenced: boolean;
22
+ }
23
+ export declare function sha256Hex(text: string): string;
24
+ /**
25
+ * Throw unless `content` hashes to `expected`. A no-op when `expected` is
26
+ * undefined. Callers run it before their first side effect.
27
+ */
28
+ export declare function assertSha256(content: string, expected: string | undefined): void;
29
+ /**
30
+ * The draft directory, `~/.oss-autopilot/tmp`, created owner-only. An existing
31
+ * directory with looser permissions (made by `mkdir -p` under a 022 umask) is
32
+ * tightened; a symlink, a file in the way, or a directory owned by someone
33
+ * else is refused. Returns the real path so callers can compare against it.
34
+ *
35
+ * Also unlinks the user's own regular files in it older than
36
+ * {@link MAX_DRAFT_AGE_MS}, so abandoned drafts do not pile up. Best effort.
37
+ */
38
+ export declare function getDraftsDir(): string;
39
+ /** `draft path <name>`: where to write a draft. Deterministic, so a later session can find a waiting proposal. */
40
+ export declare function runDraftPath(options: {
41
+ name: string;
42
+ }): DraftPathOutput;
43
+ /**
44
+ * Read a draft once and return its text with the hash of that text.
45
+ *
46
+ * Refuses a file that is not directly inside the draft directory, a symlink
47
+ * or other non-regular file, a file owned by another user, a world-writable
48
+ * or hard-linked file, invalid UTF-8, a byte order mark, and anything over
49
+ * {@link MAX_DRAFT_BYTES}. A bare name or relative path resolves against the
50
+ * draft directory, never the cwd.
51
+ */
52
+ export declare function readDraft(file: string): DraftContent;
53
+ /** What a command was given alongside `--body-file` / `--from-file`. */
54
+ export interface ApprovedDraftRequest {
55
+ file: string;
56
+ flag: '--body-file' | '--from-file';
57
+ expectSha256: string | undefined;
58
+ /** The text was also supplied another way (`--stdin`, positional words, `--content`). */
59
+ hasOtherInput: boolean;
60
+ }
61
+ /**
62
+ * The text of a draft a command is about to post or store. The file is the
63
+ * only source (no silent winner among several), the caller must say which
64
+ * text the user approved, and an empty file never falls back to a default.
65
+ * The hash itself is checked by the command, next to its other gates.
66
+ */
67
+ export declare function readApprovedDraft(request: ApprovedDraftRequest): string;
68
+ /**
69
+ * `draft show <file>`: the text to show the user and the hash to pass back,
70
+ * from one read. With `untrusted`, `content` comes back inside the
71
+ * untrusted-content fence: use it for text distilled from other people's
72
+ * writing (guideline proposals), not for a reply the user dictated.
73
+ */
74
+ export declare function runDraftShow(options: {
75
+ file: string;
76
+ untrusted: boolean;
77
+ }): DraftShowOutput;
@@ -0,0 +1,218 @@
1
+ /**
2
+ * Draft files (#1930): text an agent stages for the user to approve before a
3
+ * command posts or stores it.
4
+ *
5
+ * Drafts used to be staged at predictable paths under `/tmp`, where another
6
+ * local user can pre-create or symlink the path, and the content could change
7
+ * between the user approving it and a command reading it. They now live in
8
+ * `~/.oss-autopilot/tmp` (owner-only), a command reads the file itself
9
+ * (`--body-file`, `--from-file`) instead of taking the text as a shell
10
+ * argument, and `--expect-sha256` pins the read to the text the user saw.
11
+ *
12
+ * `draft path` and `draft show` only touch that directory: no GitHub access,
13
+ * no state, so they are safe in an unattended run.
14
+ */
15
+ import { createHash } from 'node:crypto';
16
+ import * as fs from 'node:fs';
17
+ import path from 'node:path';
18
+ import { getDataDir } from '../core/paths.js';
19
+ import { ValidationError } from '../core/errors.js';
20
+ import { wrapUntrustedContent } from '../core/untrusted-content.js';
21
+ /** Largest draft a command reads. GitHub caps a comment body at 65536 characters; each command's own cap still applies. */
22
+ export const MAX_DRAFT_BYTES = 64 * 1024;
23
+ /** A bare file name: no separators, no leading dot or dash. */
24
+ const SAFE_NAME = /^\w[\w.-]{0,199}$/;
25
+ const SHA256_HEX = /^[0-9a-f]{64}$/i;
26
+ /** Drafts the user never posted or discarded are removed after this long. */
27
+ export const MAX_DRAFT_AGE_MS = 30 * 24 * 60 * 60 * 1000;
28
+ const UTF8_BOM = Buffer.from([0xef, 0xbb, 0xbf]);
29
+ const STRICT_UTF8 = new TextDecoder('utf-8', { fatal: true });
30
+ export function sha256Hex(text) {
31
+ return createHash('sha256').update(text, 'utf8').digest('hex');
32
+ }
33
+ /**
34
+ * Throw unless `content` hashes to `expected`. A no-op when `expected` is
35
+ * undefined. Callers run it before their first side effect.
36
+ */
37
+ export function assertSha256(content, expected) {
38
+ if (expected === undefined)
39
+ return;
40
+ if (!SHA256_HEX.test(expected)) {
41
+ throw new ValidationError('--expect-sha256 must be 64 hex characters');
42
+ }
43
+ const actual = sha256Hex(content);
44
+ if (actual !== expected.toLowerCase()) {
45
+ throw new ValidationError(`Content does not match the approved text (expected sha256 ${expected.toLowerCase()}, got ${actual}). ` +
46
+ 'Nothing was posted or stored. Run `draft show` again and show the user the current text.');
47
+ }
48
+ }
49
+ /** False on platforms without POSIX uids (Windows), where the check cannot be made. */
50
+ function isOwnedBySomeoneElse(stat) {
51
+ const uid = process.getuid?.();
52
+ return uid !== undefined && stat.uid !== uid;
53
+ }
54
+ /** Create the directory if needed and stat it without following a symlink. Null when something is in the way. */
55
+ function makeAndStatDir(dir) {
56
+ try {
57
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
58
+ return fs.lstatSync(dir);
59
+ }
60
+ catch {
61
+ return null;
62
+ }
63
+ }
64
+ function removeStaleDrafts(dir) {
65
+ const cutoff = Date.now() - MAX_DRAFT_AGE_MS;
66
+ for (const name of fs.readdirSync(dir)) {
67
+ const file = path.join(dir, name);
68
+ const stat = fs.lstatSync(file);
69
+ if (stat.isFile() && !isOwnedBySomeoneElse(stat) && stat.mtimeMs < cutoff)
70
+ fs.unlinkSync(file);
71
+ }
72
+ }
73
+ /**
74
+ * The draft directory, `~/.oss-autopilot/tmp`, created owner-only. An existing
75
+ * directory with looser permissions (made by `mkdir -p` under a 022 umask) is
76
+ * tightened; a symlink, a file in the way, or a directory owned by someone
77
+ * else is refused. Returns the real path so callers can compare against it.
78
+ *
79
+ * Also unlinks the user's own regular files in it older than
80
+ * {@link MAX_DRAFT_AGE_MS}, so abandoned drafts do not pile up. Best effort.
81
+ */
82
+ export function getDraftsDir() {
83
+ const dir = path.join(getDataDir(), 'tmp');
84
+ const stat = makeAndStatDir(dir);
85
+ if (!stat?.isDirectory() || isOwnedBySomeoneElse(stat)) {
86
+ throw new ValidationError(`Draft directory ${dir} must be a real directory owned by the current user, not a symlink or a file. ` +
87
+ `Remove or rename ${dir} and rerun.`);
88
+ }
89
+ if ((stat.mode & 0o077) !== 0)
90
+ fs.chmodSync(dir, 0o700);
91
+ const real = fs.realpathSync(dir);
92
+ try {
93
+ removeStaleDrafts(real);
94
+ }
95
+ catch {
96
+ // Cleanup only: a file that vanished or cannot be removed must not fail the command.
97
+ }
98
+ return real;
99
+ }
100
+ /** `draft path <name>`: where to write a draft. Deterministic, so a later session can find a waiting proposal. */
101
+ export function runDraftPath(options) {
102
+ if (!SAFE_NAME.test(options.name)) {
103
+ throw new ValidationError(`Invalid draft name "${options.name}": use letters, digits, ".", "_" and "-" only, starting with a letter, digit or "_"`);
104
+ }
105
+ const dir = getDraftsDir();
106
+ return { path: path.join(dir, options.name), dir };
107
+ }
108
+ function realDirOf(file) {
109
+ try {
110
+ return fs.realpathSync(path.dirname(file));
111
+ }
112
+ catch {
113
+ return null;
114
+ }
115
+ }
116
+ /** Read at most the cap plus one byte, so an oversized or growing file is never read to its end. */
117
+ function readCapped(fd) {
118
+ const buffer = Buffer.alloc(MAX_DRAFT_BYTES + 1);
119
+ let length = 0;
120
+ let read = -1;
121
+ while (read !== 0 && length < buffer.length) {
122
+ read = fs.readSync(fd, buffer, length, buffer.length - length, null);
123
+ length += read;
124
+ }
125
+ return buffer.subarray(0, length);
126
+ }
127
+ function decodeUtf8(bytes, target) {
128
+ if (bytes.subarray(0, 3).equals(UTF8_BOM)) {
129
+ throw new ValidationError(`Refusing to read ${target}: it starts with a byte order mark; save it as plain UTF-8`);
130
+ }
131
+ try {
132
+ return STRICT_UTF8.decode(bytes);
133
+ }
134
+ catch {
135
+ throw new ValidationError(`Refusing to read ${target}: it is not valid UTF-8`);
136
+ }
137
+ }
138
+ /** Check the opened file (not the path, which could have been swapped since) and read it once. */
139
+ function readOpenDraft(fd, target) {
140
+ const stat = fs.fstatSync(fd);
141
+ // Group-writable is allowed: a 002 umask writes 0664, and the directory is
142
+ // owner-only, so group members cannot reach the file through this path.
143
+ if (!stat.isFile() || isOwnedBySomeoneElse(stat) || (stat.mode & 0o002) !== 0 || stat.nlink !== 1) {
144
+ throw new ValidationError(`Refusing to read ${target}: it must be a regular file owned by the current user, not world-writable, with no other hard link`);
145
+ }
146
+ const bytes = readCapped(fd);
147
+ if (bytes.length > MAX_DRAFT_BYTES) {
148
+ throw new ValidationError(`Refusing to read ${target}: larger than ${MAX_DRAFT_BYTES} bytes`);
149
+ }
150
+ const content = decodeUtf8(bytes, target);
151
+ return { content, path: target, sha256: sha256Hex(content), byteSize: bytes.length };
152
+ }
153
+ /**
154
+ * Read a draft once and return its text with the hash of that text.
155
+ *
156
+ * Refuses a file that is not directly inside the draft directory, a symlink
157
+ * or other non-regular file, a file owned by another user, a world-writable
158
+ * or hard-linked file, invalid UTF-8, a byte order mark, and anything over
159
+ * {@link MAX_DRAFT_BYTES}. A bare name or relative path resolves against the
160
+ * draft directory, never the cwd.
161
+ */
162
+ export function readDraft(file) {
163
+ const dir = getDraftsDir();
164
+ const requested = path.resolve(dir, file);
165
+ if (realDirOf(requested) !== dir) {
166
+ throw new ValidationError(`Refusing to read ${requested}: drafts must be files directly inside ${dir}`);
167
+ }
168
+ const target = path.join(dir, path.basename(requested));
169
+ const found = fs.lstatSync(target, { throwIfNoEntry: false });
170
+ if (!found) {
171
+ throw new ValidationError(`No draft at ${target}: write it first (see \`draft path\`)`);
172
+ }
173
+ if (!found.isFile()) {
174
+ throw new ValidationError(`Refusing to read ${target}: not a regular file (symlinks are not followed)`);
175
+ }
176
+ // O_NOFOLLOW closes the gap between the lstat above and the open; the
177
+ // fstat below checks the file that was actually opened.
178
+ const fd = fs.openSync(target, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK);
179
+ try {
180
+ return readOpenDraft(fd, target);
181
+ }
182
+ finally {
183
+ fs.closeSync(fd);
184
+ }
185
+ }
186
+ /**
187
+ * The text of a draft a command is about to post or store. The file is the
188
+ * only source (no silent winner among several), the caller must say which
189
+ * text the user approved, and an empty file never falls back to a default.
190
+ * The hash itself is checked by the command, next to its other gates.
191
+ */
192
+ export function readApprovedDraft(request) {
193
+ const { flag } = request;
194
+ if (request.hasOtherInput) {
195
+ throw new ValidationError(`${flag} cannot be combined with another source of the text (--stdin, positional words or --content)`);
196
+ }
197
+ if (request.expectSha256 === undefined) {
198
+ throw new ValidationError(`${flag} requires --expect-sha256: run \`draft show\` on the file, show the user its content, ` +
199
+ 'and pass the sha256 it returned');
200
+ }
201
+ const { content } = readDraft(request.file);
202
+ if (content.trim() === '')
203
+ throw new ValidationError('draft file is empty');
204
+ return content;
205
+ }
206
+ /**
207
+ * `draft show <file>`: the text to show the user and the hash to pass back,
208
+ * from one read. With `untrusted`, `content` comes back inside the
209
+ * untrusted-content fence: use it for text distilled from other people's
210
+ * writing (guideline proposals), not for a reply the user dictated.
211
+ */
212
+ export function runDraftShow(options) {
213
+ const draft = readDraft(options.file);
214
+ if (!options.untrusted)
215
+ return { ...draft, fenced: false };
216
+ const content = wrapUntrustedContent(draft.content, path.basename(draft.path), { source: 'draft' });
217
+ return { ...draft, content, fenced: true };
218
+ }
@@ -5,6 +5,7 @@
5
5
  */
6
6
  import { computeEvalReport, formatEvalMarkdown } from '../core/eval-report.js';
7
7
  import { getStateManager } from '../core/index.js';
8
+ // eslint-disable-next-line @typescript-eslint/require-await -- async keeps the Promise-returning contract callers rely on; the body has no await yet
8
9
  export async function runEval() {
9
10
  const report = computeEvalReport(getStateManager().getState());
10
11
  return { report, markdown: formatEvalMarkdown(report) };
@@ -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
+ }