@oss-autopilot/core 3.28.0 → 3.29.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 (50) hide show
  1. package/dist/cli-pre-action.d.ts +9 -0
  2. package/dist/cli-pre-action.js +95 -0
  3. package/dist/cli-registry.js +5 -1
  4. package/dist/cli.bundle.cjs +116 -116
  5. package/dist/cli.js +4 -87
  6. package/dist/commands/comments.js +3 -1
  7. package/dist/commands/daily.js +32 -6
  8. package/dist/commands/dashboard-server.js +1 -1
  9. package/dist/commands/dashboard.d.ts +2 -2
  10. package/dist/commands/dashboard.js +13 -5
  11. package/dist/commands/guidelines.d.ts +8 -0
  12. package/dist/commands/guidelines.js +2 -1
  13. package/dist/commands/overnight-handoff.d.ts +59 -0
  14. package/dist/commands/overnight-handoff.js +212 -0
  15. package/dist/commands/overnight-push-prep.d.ts +7 -0
  16. package/dist/commands/overnight-push-prep.js +97 -25
  17. package/dist/commands/overnight.d.ts +22 -1
  18. package/dist/commands/overnight.js +68 -7
  19. package/dist/core/ci-analysis.js +11 -4
  20. package/dist/core/errors.d.ts +17 -0
  21. package/dist/core/errors.js +25 -0
  22. package/dist/core/pr-monitor.d.ts +2 -2
  23. package/dist/core/pr-monitor.js +9 -6
  24. package/dist/core/repo-score-manager.js +23 -2
  25. package/dist/core/review-analysis.d.ts +6 -2
  26. package/dist/core/review-analysis.js +13 -4
  27. package/dist/core/state-persistence.js +25 -11
  28. package/dist/core/status-determination.js +10 -1
  29. package/dist/core/types.d.ts +1 -1
  30. package/dist/dashboard/assets/chart-panel-0drzwc3-.js +3 -0
  31. package/dist/dashboard/assets/confetti.module-BYDB1iN2.js +2 -0
  32. package/dist/dashboard/assets/index-C0LCGMVi.js +50 -0
  33. package/dist/dashboard/assets/index-CTiG-vjC.css +1 -0
  34. package/dist/dashboard/assets/jetbrains-mono-latin-400-normal-6-qcROiO.woff +0 -0
  35. package/dist/dashboard/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
  36. package/dist/dashboard/assets/jetbrains-mono-latin-500-normal-BWZEU5yA.woff2 +0 -0
  37. package/dist/dashboard/assets/jetbrains-mono-latin-500-normal-CJOVTJB7.woff +0 -0
  38. package/dist/dashboard/assets/plus-jakarta-sans-latin-400-normal-BDKaGhyp.woff +0 -0
  39. package/dist/dashboard/assets/plus-jakarta-sans-latin-400-normal-Dhut76fR.woff2 +0 -0
  40. package/dist/dashboard/assets/plus-jakarta-sans-latin-500-normal-Bf-nb4oT.woff2 +0 -0
  41. package/dist/dashboard/assets/plus-jakarta-sans-latin-500-normal-DYtqi0QS.woff +0 -0
  42. package/dist/dashboard/assets/plus-jakarta-sans-latin-600-normal-BR_Ojra4.woff +0 -0
  43. package/dist/dashboard/assets/plus-jakarta-sans-latin-600-normal-DLTa1BUW.woff2 +0 -0
  44. package/dist/dashboard/assets/plus-jakarta-sans-latin-700-normal-CfpNZvy6.woff2 +0 -0
  45. package/dist/dashboard/assets/plus-jakarta-sans-latin-700-normal-DqEcQeE5.woff +0 -0
  46. package/dist/dashboard/assets/plus-jakarta-sans-latin-800-normal-BRNHt2w0.woff +0 -0
  47. package/dist/dashboard/assets/plus-jakarta-sans-latin-800-normal-CusIZhrK.woff2 +0 -0
  48. package/dist/dashboard/favicon.svg +83 -0
  49. package/dist/dashboard/index.html +54 -0
  50. package/package.json +3 -2
@@ -15,12 +15,22 @@
15
15
  * so the user's own source repos never grow `prep/*` branches.
16
16
  * 3. The ref is always `refs/heads/prep/<branch>` and never `--force`; a
17
17
  * non-fast-forward is a skip with a reason.
18
+ *
19
+ * With `OSS_AUTOPILOT_HANDOFF_DIR` set the tick ran as another user, and the
20
+ * branches arrive as bundles (overnight-handoff.ts). Then there is no
21
+ * worktree to read remotes from: the target is the PR's head repo (or
22
+ * `<login>/<repo>` for an issue), which must also be a fork of the PR's repo,
23
+ * and the push goes out of a private repo filled from the bundle.
18
24
  */
19
25
  import { execFileSync } from 'node:child_process';
20
26
  import * as fs from 'node:fs';
27
+ import * as path from 'node:path';
21
28
  import { errorMessage, getOctokit, getStateManager, isRateLimitError, maybeCheckpoint, parseGitHubUrl, requireGitHubToken, } from '../core/index.js';
29
+ import { assertAttended } from '../core/errors.js';
22
30
  import { warn } from '../core/logger.js';
23
- import { publishReport, writePreparedSection } from './overnight.js';
31
+ import { getReportsDir } from '../core/paths.js';
32
+ import { handoffDir, importHandoffBundle, loadHandoff } from './overnight-handoff.js';
33
+ import { publishReport, reportDateFor, writePreparedSection } from './overnight.js';
24
34
  const MODULE = 'overnight-push-prep';
25
35
  /** The only ref namespace this command ever pushes to. */
26
36
  export const PREP_REF_PREFIX = 'refs/heads/prep/';
@@ -153,11 +163,23 @@ function skip(entry, reason, target, ref) {
153
163
  }
154
164
  /** Push every prepared branch of the latest overnight run to `prep/*` on the user's fork. */
155
165
  export async function runOvernightPushPrep(options) {
166
+ // A scheduler runs this after the model tick has ended, in its own
167
+ // environment. Inside the tick it must not run at all.
168
+ assertAttended('push prepared branches');
156
169
  const sm = getStateManager();
157
- const last = sm.getLastOvernight();
170
+ const dropDir = handoffDir();
171
+ const handoff = dropDir ? loadHandoff(dropDir) : null;
172
+ const last = handoff
173
+ ? {
174
+ ...handoff.record,
175
+ reportPath: path.join(getReportsDir(), `overnight-${reportDateFor(new Date(handoff.record.runAt))}.md`),
176
+ }
177
+ : sm.getLastOvernight();
158
178
  if (!last)
159
179
  throw new Error('No overnight run recorded yet; run `overnight` first.');
160
180
  const lastRun = last; // narrowed binding for the closures below
181
+ if (handoff?.report != null && !options.dryRun)
182
+ fs.writeFileSync(lastRun.reportPath, handoff.report, { mode: 0o600 });
161
183
  const octokit = getOctokit(requireGitHubToken());
162
184
  const { data: viewer } = await octokit.users.getAuthenticated();
163
185
  const login = viewer.login?.trim();
@@ -175,8 +197,8 @@ export async function runOvernightPushPrep(options) {
175
197
  * GitHub redirects a transferred or renamed repo, so a stale
176
198
  * `github.com/<login>/<repo>` URL can resolve to someone else's repo.
177
199
  */
178
- async function forkSkipReason(target) {
179
- const key = `${target.owner}/${target.repo}`.toLowerCase();
200
+ async function forkSkipReason(target, upstream) {
201
+ const key = `${target.owner}/${target.repo}|${upstream ?? ''}`.toLowerCase();
180
202
  const cached = forkVerdicts.get(key);
181
203
  if (cached !== undefined)
182
204
  return cached;
@@ -187,6 +209,8 @@ export async function runOvernightPushPrep(options) {
187
209
  reason = `${target.owner}/${target.repo} is not a fork`;
188
210
  else if (data.owner.login.toLowerCase() !== login.toLowerCase())
189
211
  reason = `${target.owner}/${target.repo} resolved to ${data.full_name}, not owned by ${login}`;
212
+ else if (upstream && data.parent?.full_name?.toLowerCase() !== upstream.toLowerCase())
213
+ reason = `${data.full_name} is not a fork of ${upstream}`;
190
214
  else
191
215
  reason = null;
192
216
  }
@@ -201,31 +225,66 @@ export async function runOvernightPushPrep(options) {
201
225
  forkVerdicts.set(key, reason);
202
226
  return reason;
203
227
  }
204
- /** PR head branch for the compare URL; undefined (with a warning) when it cannot be read. */
205
- async function prHeadFor(url) {
228
+ const pulls = new Map();
229
+ /** The PR's head (branch and repo), read once per URL; undefined (with a warning) when it cannot be read. */
230
+ function pullFor(url) {
206
231
  const parsed = parseGitHubUrl(url);
207
232
  if (!parsed || parsed.type !== 'pull')
208
- return undefined;
209
- try {
210
- const { data } = await octokit.pulls.get({ owner: parsed.owner, repo: parsed.repo, pull_number: parsed.number });
211
- return data.head.ref;
233
+ return Promise.resolve(undefined);
234
+ let pending = pulls.get(url);
235
+ if (!pending) {
236
+ pending = octokit.pulls
237
+ .get({ owner: parsed.owner, repo: parsed.repo, pull_number: parsed.number })
238
+ .then(({ data }) => data.head)
239
+ .catch((err) => {
240
+ if (isRateLimitError(err))
241
+ throw err;
242
+ warn(MODULE, `Could not read the head of ${url}: ${errorMessage(err)}`);
243
+ return undefined;
244
+ });
245
+ pulls.set(url, pending);
212
246
  }
213
- catch (err) {
214
- if (isRateLimitError(err))
215
- throw err;
216
- warn(MODULE, `Could not read the head branch of ${url}; no compare URL: ${errorMessage(err)}`);
217
- return undefined;
247
+ return pending;
248
+ }
249
+ /** Handoff mode: push to the PR's head repo, or `<login>/<repo>` for an issue; a string is a skip reason. */
250
+ async function handoffTarget(url) {
251
+ const parsed = parseGitHubUrl(url);
252
+ if (!parsed)
253
+ return `${url} is not a GitHub PR or issue URL`;
254
+ const upstream = `${parsed.owner}/${parsed.repo}`;
255
+ let owner = login;
256
+ let repo = parsed.repo;
257
+ if (parsed.type === 'pull') {
258
+ const head = (await pullFor(url))?.repo;
259
+ if (!head)
260
+ return `could not read the head repository of ${url}`;
261
+ if (head.owner.login.toLowerCase() !== login.toLowerCase())
262
+ return `the head of ${url} is ${head.full_name}, not a repo owned by ${login}`;
263
+ owner = head.owner.login;
264
+ repo = head.name;
218
265
  }
266
+ return { target: { owner, repo, remote: `https://github.com/${owner}/${repo}.git` }, upstream };
219
267
  }
220
268
  async function pushOne(entry) {
221
- if (!entry.worktree)
222
- return skip(entry, 'no worktree recorded');
223
- if (!fs.existsSync(entry.worktree))
224
- return skip(entry, `worktree ${entry.worktree} does not exist`);
225
- const target = resolvePushRemote(parseRemotesOutput(git(entry.worktree, ['remote', '-v'])), login);
226
- if (!target)
227
- return skip(entry, `no remote in ${entry.worktree} is owned by ${login}`);
228
- const notFork = await forkSkipReason(target);
269
+ let target;
270
+ let upstream;
271
+ if (dropDir) {
272
+ const resolved = await handoffTarget(entry.url);
273
+ if (typeof resolved === 'string')
274
+ return skip(entry, resolved);
275
+ ({ target, upstream } = resolved);
276
+ }
277
+ else {
278
+ if (!entry.worktree)
279
+ return skip(entry, 'no worktree recorded');
280
+ if (!fs.existsSync(entry.worktree))
281
+ return skip(entry, `worktree ${entry.worktree} does not exist`);
282
+ const found = resolvePushRemote(parseRemotesOutput(git(entry.worktree, ['remote', '-v'])), login);
283
+ if (!found)
284
+ return skip(entry, `no remote in ${entry.worktree} is owned by ${login}`);
285
+ target = found;
286
+ }
287
+ const notFork = await forkSkipReason(target, upstream);
229
288
  if (notFork)
230
289
  return skip(entry, notFork, target);
231
290
  // A recorded name git would reject is a gate saying no, not a broken push.
@@ -239,7 +298,7 @@ export async function runOvernightPushPrep(options) {
239
298
  return skip(entry, errorMessage(err), target);
240
299
  }
241
300
  const prepBranch = prepBranchName(ref);
242
- const head = await prHeadFor(entry.url);
301
+ const head = (await pullFor(entry.url))?.ref;
243
302
  const base = {
244
303
  url: entry.url,
245
304
  branch: entry.branch,
@@ -255,14 +314,27 @@ export async function runOvernightPushPrep(options) {
255
314
  // from writing refs/tags/*; `--` keeps the remote name out of option
256
315
  // parsing.
257
316
  assertPrepRef(ref);
317
+ // Handoff: push out of a private repo filled from the bundle, never out
318
+ // of anything the tick can write. A bundle that cannot be imported is a
319
+ // failure (the tick recorded a branch it did not deliver), not a gate.
320
+ let source;
321
+ try {
322
+ source = dropDir ? importHandoffBundle(dropDir, entry.branch) : { repo: entry.worktree, cleanup: () => { } };
323
+ }
324
+ catch (err) {
325
+ return notPushed('failed', entry, `bundle import failed: ${errorMessage(err)}`, target, ref);
326
+ }
258
327
  try {
259
- git(entry.worktree, ['push', '--no-follow-tags', '--', target.remote, `refs/heads/${entry.branch}:${ref}`]);
328
+ git(source.repo, ['push', '--no-follow-tags', '--', target.remote, `refs/heads/${entry.branch}:${ref}`]);
260
329
  }
261
330
  catch (err) {
262
331
  return isNonFastForward(err)
263
332
  ? skip(entry, `non-fast-forward: ${prepBranch} on ${target.remote} has commits this worktree lacks; not forced`, target, ref)
264
333
  : notPushed('failed', entry, pushFailureReason(err), target, ref);
265
334
  }
335
+ finally {
336
+ source.cleanup();
337
+ }
266
338
  return { ...base, status: 'pushed' };
267
339
  }
268
340
  const results = [];
@@ -128,9 +128,27 @@ export declare function renderReport(out: ReportBody, prepared?: OvernightPrepar
128
128
  /** Local calendar date: the job fires at a local hour, so the report is filed under the local day. */
129
129
  export declare function reportDateFor(d: Date): string;
130
130
  export declare function runOvernight(): Promise<OvernightOutput>;
131
+ /** The fields of the preparer agent's four-line report (agents/overnight-preparer.md). */
132
+ export interface PreparerReport {
133
+ branch?: string;
134
+ worktree?: string;
135
+ status?: string;
136
+ note?: string;
137
+ }
138
+ /**
139
+ * Parse the preparer's `KEY: value` report. The agent that writes it has read
140
+ * CI logs and review comments from other people's repos, so its text is
141
+ * untrusted. The orchestrating command saves the report with the Write tool and
142
+ * passes the path (`--from-report`); nothing from it is ever spliced into a
143
+ * shell command line, where `$(...)` or backticks inside double quotes would run.
144
+ * Unknown lines are ignored and the first occurrence of a key wins.
145
+ */
146
+ export declare function parsePreparerReport(text: string): PreparerReport;
131
147
  export interface OvernightImplementBlockedOptions {
132
148
  url: string;
133
149
  note?: string;
150
+ /** Path to the saved preparer report; supplies `note` when it is not given. */
151
+ fromReport?: string;
134
152
  }
135
153
  export interface OvernightImplementBlockedOutput {
136
154
  url: string;
@@ -146,9 +164,12 @@ export interface OvernightImplementBlockedOutput {
146
164
  export declare function runOvernightImplementBlocked(options: OvernightImplementBlockedOptions): Promise<OvernightImplementBlockedOutput>;
147
165
  export interface OvernightRecordOptions {
148
166
  url: string;
149
- branch: string;
167
+ /** Required unless `fromReport` supplies it. */
168
+ branch?: string;
150
169
  worktree?: string;
151
170
  note?: string;
171
+ /** Path to the saved preparer report; supplies branch, worktree and note when they are not given. */
172
+ fromReport?: string;
152
173
  }
153
174
  export interface OvernightRecordOutput {
154
175
  reportPath: string;
@@ -22,11 +22,13 @@ import * as fs from 'node:fs';
22
22
  import * as os from 'node:os';
23
23
  import * as path from 'node:path';
24
24
  import { errorMessage, getStateManager, maybeCheckpoint, parseGitHubUrl, requireGitHubToken } from '../core/index.js';
25
+ import { UNATTENDED_ENV, ValidationError } from '../core/errors.js';
25
26
  import { warn } from '../core/logger.js';
26
27
  import { getReportsDir } from '../core/paths.js';
27
28
  import { detectIssueListPath } from './locate-issue-list.js';
28
29
  import { parseIssueList } from './parse-list.js';
29
30
  import { executeDailyCheck } from './daily.js';
31
+ import { exportHandoff, handoffDir, pruneHandoffBundles, writeHandoffBundle } from './overnight-handoff.js';
30
32
  const MODULE = 'overnight';
31
33
  // ponytail: static table, not a classifier. Every ActionableIssueType is
32
34
  // listed: the Record key type makes a new variant fail typecheck here.
@@ -238,7 +240,7 @@ export async function runOvernight() {
238
240
  const carried = previous?.reportPath === reportPath ? previous.prepared : [];
239
241
  fs.writeFileSync(reportPath, renderReport(body, carried), { mode: 0o600 });
240
242
  publishReport(sm, reportPath);
241
- sm.setLastOvernight({
243
+ const record = {
242
244
  runAt,
243
245
  reportPath,
244
246
  prepareCount: prepare.length,
@@ -246,7 +248,13 @@ export async function runOvernight() {
246
248
  prepared: carried,
247
249
  ...(implement ? { implementUrl: implement.url } : {}),
248
250
  implementAttempts: attempts,
249
- });
251
+ };
252
+ sm.setLastOvernight(record);
253
+ const dropDir = handoffDir();
254
+ if (dropDir) {
255
+ pruneHandoffBundles(dropDir, carried.map((p) => p.branch));
256
+ exportHandoff(dropDir, record);
257
+ }
250
258
  // executeDailyCheck already checkpointed the Gist; this write came after it,
251
259
  // and in Gist mode setLastOvernight only reaches the local cache (#1629 class).
252
260
  const gistSyncWarning = await maybeCheckpoint(sm, MODULE);
@@ -258,6 +266,33 @@ export async function runOvernight() {
258
266
  ...(daily.pendingLearnings ? { pendingLearnings: daily.pendingLearnings } : {}),
259
267
  };
260
268
  }
269
+ /**
270
+ * Parse the preparer's `KEY: value` report. The agent that writes it has read
271
+ * CI logs and review comments from other people's repos, so its text is
272
+ * untrusted. The orchestrating command saves the report with the Write tool and
273
+ * passes the path (`--from-report`); nothing from it is ever spliced into a
274
+ * shell command line, where `$(...)` or backticks inside double quotes would run.
275
+ * Unknown lines are ignored and the first occurrence of a key wins.
276
+ */
277
+ export function parsePreparerReport(text) {
278
+ const report = {};
279
+ for (const line of text.split(/\r?\n/)) {
280
+ const match = /^(BRANCH|WORKTREE|STATUS|NOTE):(.*)$/.exec(line); // value is trimmed below
281
+ if (!match)
282
+ continue;
283
+ const key = match[1].toLowerCase();
284
+ const value = match[2].trim();
285
+ if (value && report[key] === undefined)
286
+ report[key] = value;
287
+ }
288
+ return report;
289
+ }
290
+ function readPreparerReport(reportFile) {
291
+ return parsePreparerReport(fs.readFileSync(reportFile, 'utf8'));
292
+ }
293
+ // Conservative on purpose: a preparer branch is `prep/...`-style. Anything
294
+ // outside this set in a name that came from an agent is a reason to stop.
295
+ const SAFE_BRANCH = /^(?!-)[\w./@+-]+$/;
261
296
  /**
262
297
  * `overnight implement-blocked` (#1715): the preparer could not produce a
263
298
  * branch for tonight's list issue. Remember that so the next run picks the
@@ -272,11 +307,15 @@ export async function runOvernightImplementBlocked(options) {
272
307
  if (options.url !== last.implementUrl) {
273
308
  throw new Error(`${options.url} is not tonight's implement item (${last.implementUrl ?? 'none queued'})`);
274
309
  }
310
+ const note = options.note ?? (options.fromReport ? readPreparerReport(options.fromReport).note : undefined);
275
311
  const implementAttempts = [
276
312
  ...(last.implementAttempts ?? []),
277
- { url: options.url, attemptedAt: new Date().toISOString(), outcome: 'blocked', note: options.note },
313
+ { url: options.url, attemptedAt: new Date().toISOString(), outcome: 'blocked', note },
278
314
  ];
279
315
  sm.setLastOvernight({ ...last, implementAttempts });
316
+ const dropDir = handoffDir();
317
+ if (dropDir)
318
+ exportHandoff(dropDir, { ...last, implementAttempts });
280
319
  const gistSyncWarning = await maybeCheckpoint(sm, MODULE);
281
320
  return { url: options.url, attemptCount: implementAttempts.length, ...(gistSyncWarning ? { gistSyncWarning } : {}) };
282
321
  }
@@ -286,13 +325,28 @@ export async function runOvernightRecord(options) {
286
325
  const last = sm.getLastOvernight();
287
326
  if (!last)
288
327
  throw new Error('No overnight run recorded yet; run `overnight` first.');
328
+ const report = options.fromReport ? readPreparerReport(options.fromReport) : {};
329
+ const branch = options.branch ?? report.branch;
330
+ if (!branch)
331
+ throw new ValidationError('No branch to record: pass --branch, or --from-report with a BRANCH: line.');
332
+ if (!SAFE_BRANCH.test(branch))
333
+ throw new ValidationError(`Refusing to record an unusual branch name: ${branch}`);
289
334
  const entry = {
290
335
  url: options.url,
291
- branch: options.branch,
292
- worktree: options.worktree,
293
- note: options.note,
336
+ branch,
337
+ worktree: options.worktree ?? report.worktree,
338
+ note: options.note ?? report.note,
294
339
  recordedAt: new Date().toISOString(),
295
340
  };
341
+ // Split-user box: the pusher cannot read this worktree, so the branch
342
+ // travels as a bundle. Written before state, so a branch that could not be
343
+ // bundled is never recorded as prepared.
344
+ const dropDir = handoffDir();
345
+ if (dropDir) {
346
+ if (!entry.worktree)
347
+ throw new ValidationError('No worktree to bundle: pass --worktree, or a report with WORKTREE:.');
348
+ writeHandoffBundle(dropDir, entry.worktree, branch);
349
+ }
296
350
  const prepared = [...last.prepared, entry];
297
351
  // Recording the branch for tonight's list issue is what marks the attempt
298
352
  // as prepared, so the next run moves on to the next Pursue item.
@@ -305,6 +359,8 @@ export async function runOvernightRecord(options) {
305
359
  sm.setLastOvernight({ ...last, prepared, implementAttempts });
306
360
  const { reportRecreated } = writePreparedSection(last.reportPath, prepared);
307
361
  publishReport(sm, last.reportPath);
362
+ if (dropDir)
363
+ exportHandoff(dropDir, { ...last, prepared, implementAttempts });
308
364
  const gistSyncWarning = await maybeCheckpoint(sm, MODULE);
309
365
  return {
310
366
  reportPath: last.reportPath,
@@ -551,7 +607,12 @@ export function renderLaunchdPlist(options, logPath, settingsPath) {
551
607
  ' <key>EnvironmentVariables</key>',
552
608
  // launchd inherits no shell PATH; include the dir of the node that ran
553
609
  // `schedule` so a version-manager node resolves for the CLI and tests.
554
- ` <dict><key>PATH</key><string>${xmlEscape(`${path.dirname(process.execPath)}:/usr/local/bin:/opt/homebrew/bin:/usr/bin:/bin`)}</string></dict>`,
610
+ ' <dict>',
611
+ ` <key>PATH</key><string>${xmlEscape(`${path.dirname(process.execPath)}:/usr/local/bin:/opt/homebrew/bin:/usr/bin:/bin`)}</string>`,
612
+ // The CLI's own GitHub-writing commands refuse while this is set (see
613
+ // assertAttended): `Bash(node *)` has to stay allowed, so the gate is in code.
614
+ ` <key>${UNATTENDED_ENV}</key><string>1</string>`,
615
+ ' </dict>',
555
616
  '</dict>',
556
617
  '</plist>',
557
618
  '',
@@ -4,6 +4,7 @@
4
4
  */
5
5
  import { getHttpStatusCode, errorMessage } from './errors.js';
6
6
  import { debug, warn } from './logger.js';
7
+ import { paginateAll } from './pagination.js';
7
8
  /** Return a fresh unknown CI status (avoids shared mutable state between callers). */
8
9
  function unknownCIStatus() {
9
10
  return { status: 'unknown', failingCheckNames: [], failingCheckConclusions: new Map() };
@@ -315,10 +316,16 @@ export async function getCIStatus(octokit, owner, repo, sha) {
315
316
  return unknownCIStatus();
316
317
  try {
317
318
  // Fetch both combined status and check runs in parallel
318
- const [statusResponse, checksResponse] = await Promise.all([
319
- octokit.repos.getCombinedStatusForRef({ owner, repo, ref: sha }),
319
+ const [statusResponse, checkRuns] = await Promise.all([
320
+ // per_page 100: the default page holds 30 statuses, and analyzeCombinedStatus
321
+ // only sees the page it is given.
322
+ octokit.repos.getCombinedStatusForRef({ owner, repo, ref: sha, per_page: 100 }),
320
323
  // 404 is expected for repos without check runs configured; log other errors for debugging
321
- octokit.checks.listForRef({ owner, repo, ref: sha }).catch((err) => {
324
+ // Paginated: the default page is 30 check runs, and a failing check on a
325
+ // later page would otherwise read as passing.
326
+ paginateAll((page) => octokit.checks
327
+ .listForRef({ owner, repo, ref: sha, per_page: 100, page })
328
+ .then((res) => ({ data: res.data.check_runs }))).catch((err) => {
322
329
  const status = getHttpStatusCode(err);
323
330
  // Rate limit errors must propagate — matches listReviewComments pattern (#481)
324
331
  if (status === 429)
@@ -338,7 +345,7 @@ export async function getCIStatus(octokit, owner, repo, sha) {
338
345
  }),
339
346
  ]);
340
347
  const combinedStatus = statusResponse.data;
341
- const allCheckRuns = checksResponse?.data?.check_runs || [];
348
+ const allCheckRuns = checkRuns ?? [];
342
349
  return computeCIStatus(allCheckRuns, combinedStatus);
343
350
  }
344
351
  catch (error) {
@@ -20,6 +20,23 @@ export declare class OssAutopilotError extends Error {
20
20
  export declare class ConfigurationError extends OssAutopilotError {
21
21
  constructor(message: string);
22
22
  }
23
+ /**
24
+ * Set by the scheduled overnight job (see `renderLaunchdPlist`). Any defined
25
+ * value, even an empty one, marks the run as unattended. Nobody
26
+ * is present to approve anything in that run, so the commands that write to
27
+ * GitHub refuse while it is set.
28
+ */
29
+ export declare const UNATTENDED_ENV = "OSS_AUTOPILOT_UNATTENDED";
30
+ /**
31
+ * Refuse a GitHub-writing action during an unattended run.
32
+ *
33
+ * The overnight allowlist has to permit `node`, because the run itself calls
34
+ * this CLI, so a deny rule on the command line cannot keep the model away from
35
+ * `post`, `claim` or `overnight push-prep`. The check lives here instead, where
36
+ * every route to the write (CLI, MCP tool, library import) passes through it.
37
+ * This closes the direct path; it is not a sandbox against arbitrary code.
38
+ */
39
+ export declare function assertAttended(action: string): void;
23
40
  /**
24
41
  * Input validation errors (invalid URLs, out-of-range values).
25
42
  */
@@ -28,6 +28,31 @@ export class ConfigurationError extends OssAutopilotError {
28
28
  this.name = 'ConfigurationError';
29
29
  }
30
30
  }
31
+ /**
32
+ * Set by the scheduled overnight job (see `renderLaunchdPlist`). Any defined
33
+ * value, even an empty one, marks the run as unattended. Nobody
34
+ * is present to approve anything in that run, so the commands that write to
35
+ * GitHub refuse while it is set.
36
+ */
37
+ export const UNATTENDED_ENV = 'OSS_AUTOPILOT_UNATTENDED';
38
+ /**
39
+ * Refuse a GitHub-writing action during an unattended run.
40
+ *
41
+ * The overnight allowlist has to permit `node`, because the run itself calls
42
+ * this CLI, so a deny rule on the command line cannot keep the model away from
43
+ * `post`, `claim` or `overnight push-prep`. The check lives here instead, where
44
+ * every route to the write (CLI, MCP tool, library import) passes through it.
45
+ * This closes the direct path; it is not a sandbox against arbitrary code.
46
+ */
47
+ export function assertAttended(action) {
48
+ // Any defined value counts, including '' and '0'. If a value could switch the
49
+ // guard off, prefixing the command with `${UNATTENDED_ENV}=0` would be the
50
+ // shortest way around it.
51
+ if (process.env[UNATTENDED_ENV] !== undefined) {
52
+ throw new ConfigurationError(`Refusing to ${action} during an unattended run (${UNATTENDED_ENV} is set). ` +
53
+ 'Run it yourself in an interactive session.');
54
+ }
55
+ }
31
56
  /**
32
57
  * Input validation errors (invalid URLs, out-of-range values).
33
58
  */
@@ -40,8 +40,8 @@ export interface FetchPRsResult {
40
40
  * - Post-fetch viewer-mismatch guardrail (configured username differs
41
41
  * from the authenticated viewer when the search returned zero PRs).
42
42
  * - Search API 1000-result truncation (#1057 M25).
43
- * - Per-PR comment pagination truncation (#1456) — newest comments
44
- * dropped, so unresponded-comment detection may be incomplete.
43
+ * - Per-PR comment or review pagination truncation (#1456) — newest entries
44
+ * dropped, so review-decision / unresponded-comment detection may be incomplete.
45
45
  * Callers (daily, dashboard) surface these so users see the signal.
46
46
  */
47
47
  warnings?: string[];
@@ -317,10 +317,13 @@ export class PRMonitor {
317
317
  // Fetch PR data, comments, reviews, and inline review comments in parallel.
318
318
  // listReviewComments is non-critical (used for self-reply detection), so degrade
319
319
  // gracefully on failure rather than dropping the entire PR (#199).
320
- const [prResponse, commentsResult, reviewsResponse, reviewCommentsResult] = await Promise.all([
320
+ const [prResponse, commentsResult, reviewsResult, reviewCommentsResult] = await Promise.all([
321
321
  this.octokit.pulls.get({ owner, repo, pull_number: number }),
322
322
  paginateAllDetailed((page) => this.octokit.issues.listComments({ owner, repo, issue_number: number, per_page: 100, page })),
323
- this.octokit.pulls.listReviews({ owner, repo, pull_number: number }),
323
+ // Paginated: PRs land on this REST path precisely when GraphQL's review
324
+ // cap overflowed, and listReviews returns oldest-first, so an unpaginated
325
+ // call would drop the newest verdicts.
326
+ paginateAllDetailed((page) => this.octokit.pulls.listReviews({ owner, repo, pull_number: number, per_page: 100, page })),
324
327
  paginateAllDetailed((page) => this.octokit.pulls.listReviewComments({ owner, repo, pull_number: number, per_page: 100, page })).catch((err) => {
325
328
  const status = getHttpStatusCode(err);
326
329
  // Rate limit errors must propagate — silently swallowing them hides
@@ -352,14 +355,14 @@ export class PRMonitor {
352
355
  // (#1456): comments arrive oldest-first, so hitting the cap drops the
353
356
  // NEWEST maintainer feedback — status determination (unresponded-comment
354
357
  // detection) may be wrong for this PR.
355
- if (commentsResult.truncated || reviewCommentsResult.truncated) {
356
- const message = `Comment pagination cap reached for ${owner}/${repo}#${number}; the newest comments were not ` +
357
- `fetched and unresponded-comment detection may be incomplete.`;
358
+ if (commentsResult.truncated || reviewsResult.truncated || reviewCommentsResult.truncated) {
359
+ const message = `Comment pagination cap reached for ${owner}/${repo}#${number}; the newest comments or reviews were not ` +
360
+ `fetched and review-decision / unresponded-comment detection may be incomplete.`;
358
361
  warnings?.push(message);
359
362
  warn(MODULE, message);
360
363
  }
361
364
  const ghPR = prResponse.data;
362
- const reviews = reviewsResponse.data;
365
+ const reviews = reviewsResult.items;
363
366
  const ciStatus = await getCIStatus(this.octokit, owner, repo, ghPR.head.sha);
364
367
  // The commit date is only consulted (and only fetched) when the PR has an
365
368
  // unresponded maintainer comment or a changes-requested review — the shared
@@ -103,16 +103,35 @@ export function calculateScore(repoScore) {
103
103
  export function getRepoScore(state, repo) {
104
104
  return state.repoScores[repo];
105
105
  }
106
+ /** The outcome evidence behind a score, as a comparable string. Excludes stars and language. */
107
+ function outcomeFingerprint(rs) {
108
+ return JSON.stringify([
109
+ rs.mergedPRCount,
110
+ rs.closedWithoutMergeCount,
111
+ rs.avgResponseDays ?? null,
112
+ rs.lastMergedAt ?? null,
113
+ rs.signals.hasActiveMaintainers,
114
+ rs.signals.isResponsive,
115
+ rs.signals.hasHostileComments,
116
+ ]);
117
+ }
106
118
  /**
107
119
  * Update a repository's score with partial updates. If the repo has no existing score,
108
120
  * a default score record is created first (base score 5). After applying updates, the
109
121
  * numeric score is recalculated.
110
122
  */
111
123
  export function updateRepoScore(state, repo, updates) {
112
- if (!state.repoScores[repo]) {
124
+ const isNew = !state.repoScores[repo];
125
+ if (isNew) {
113
126
  state.repoScores[repo] = createDefaultRepoScore(repo);
114
127
  }
115
128
  const repoScore = state.repoScores[repo];
129
+ // The fields the score is computed from. `lastEvaluatedAt` moves only when
130
+ // one of them actually changes value: getLowScoringRepos uses it to expire a
131
+ // low score after 30 days (#487), and daily calls this for every known repo
132
+ // on every run (star/language refresh, re-writing the same merged counts).
133
+ // Bumping on every touch meant the expiry could never be reached.
134
+ const outcomeBefore = outcomeFingerprint(repoScore);
116
135
  // Apply explicit field updates (skip undefined values to preserve existing data)
117
136
  if (updates.mergedPRCount !== undefined)
118
137
  repoScore.mergedPRCount = updates.mergedPRCount;
@@ -131,7 +150,9 @@ export function updateRepoScore(state, repo, updates) {
131
150
  }
132
151
  // Recalculate score
133
152
  repoScore.score = calculateScore(repoScore);
134
- repoScore.lastEvaluatedAt = new Date().toISOString();
153
+ if (isNew || outcomeFingerprint(repoScore) !== outcomeBefore) {
154
+ repoScore.lastEvaluatedAt = new Date().toISOString();
155
+ }
135
156
  debug(MODULE, `Updated repo score for ${repo}: ${repoScore.score}/10`);
136
157
  }
137
158
  /**
@@ -17,8 +17,12 @@ export interface ReviewComment {
17
17
  }
18
18
  /**
19
19
  * Determine review decision from reviews list.
20
- * Groups reviews by user, keeping only the latest from each user,
21
- * then checks for CHANGES_REQUESTED or APPROVED states.
20
+ * Groups reviews by user, keeping each user's latest verdict, then checks
21
+ * for CHANGES_REQUESTED or APPROVED states.
22
+ *
23
+ * Only APPROVED, CHANGES_REQUESTED and DISMISSED change a reviewer's standing
24
+ * verdict on GitHub. COMMENTED is also what GitHub records for every inline
25
+ * reply, so it must not overwrite an earlier verdict from the same reviewer.
22
26
  */
23
27
  export declare function determineReviewDecision(reviews: Array<{
24
28
  state?: string | null;
@@ -6,19 +6,28 @@
6
6
  import { isBotAuthor, isAcknowledgmentComment } from './comment-utils.js';
7
7
  /**
8
8
  * Determine review decision from reviews list.
9
- * Groups reviews by user, keeping only the latest from each user,
10
- * then checks for CHANGES_REQUESTED or APPROVED states.
9
+ * Groups reviews by user, keeping each user's latest verdict, then checks
10
+ * for CHANGES_REQUESTED or APPROVED states.
11
+ *
12
+ * Only APPROVED, CHANGES_REQUESTED and DISMISSED change a reviewer's standing
13
+ * verdict on GitHub. COMMENTED is also what GitHub records for every inline
14
+ * reply, so it must not overwrite an earlier verdict from the same reviewer.
11
15
  */
12
16
  export function determineReviewDecision(reviews) {
13
17
  if (reviews.length === 0) {
14
18
  return 'review_required';
15
19
  }
16
- // Group reviews by user, keeping only the latest from each user
20
+ // Group reviews by user, keeping each user's latest verdict
17
21
  const latestByUser = new Map();
18
22
  for (const review of reviews) {
19
23
  const login = review.user?.login;
20
24
  const state = review.state;
21
- if (login && state) {
25
+ if (!login || !state)
26
+ continue;
27
+ if (state === 'DISMISSED') {
28
+ latestByUser.delete(login);
29
+ }
30
+ else if (state === 'APPROVED' || state === 'CHANGES_REQUESTED') {
22
31
  latestByUser.set(login, state);
23
32
  }
24
33
  }