@oss-autopilot/core 3.28.1 → 3.29.1

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.
@@ -22,12 +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 } from '../core/errors.js';
25
+ import { UNATTENDED_ENV, ValidationError } from '../core/errors.js';
26
26
  import { warn } from '../core/logger.js';
27
27
  import { getReportsDir } from '../core/paths.js';
28
28
  import { detectIssueListPath } from './locate-issue-list.js';
29
29
  import { parseIssueList } from './parse-list.js';
30
30
  import { executeDailyCheck } from './daily.js';
31
+ import { exportHandoff, handoffDir, pruneHandoffBundles, writeHandoffBundle } from './overnight-handoff.js';
31
32
  const MODULE = 'overnight';
32
33
  // ponytail: static table, not a classifier. Every ActionableIssueType is
33
34
  // listed: the Record key type makes a new variant fail typecheck here.
@@ -239,7 +240,7 @@ export async function runOvernight() {
239
240
  const carried = previous?.reportPath === reportPath ? previous.prepared : [];
240
241
  fs.writeFileSync(reportPath, renderReport(body, carried), { mode: 0o600 });
241
242
  publishReport(sm, reportPath);
242
- sm.setLastOvernight({
243
+ const record = {
243
244
  runAt,
244
245
  reportPath,
245
246
  prepareCount: prepare.length,
@@ -247,7 +248,13 @@ export async function runOvernight() {
247
248
  prepared: carried,
248
249
  ...(implement ? { implementUrl: implement.url } : {}),
249
250
  implementAttempts: attempts,
250
- });
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
+ }
251
258
  // executeDailyCheck already checkpointed the Gist; this write came after it,
252
259
  // and in Gist mode setLastOvernight only reaches the local cache (#1629 class).
253
260
  const gistSyncWarning = await maybeCheckpoint(sm, MODULE);
@@ -259,6 +266,33 @@ export async function runOvernight() {
259
266
  ...(daily.pendingLearnings ? { pendingLearnings: daily.pendingLearnings } : {}),
260
267
  };
261
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./@+-]+$/;
262
296
  /**
263
297
  * `overnight implement-blocked` (#1715): the preparer could not produce a
264
298
  * branch for tonight's list issue. Remember that so the next run picks the
@@ -273,11 +307,15 @@ export async function runOvernightImplementBlocked(options) {
273
307
  if (options.url !== last.implementUrl) {
274
308
  throw new Error(`${options.url} is not tonight's implement item (${last.implementUrl ?? 'none queued'})`);
275
309
  }
310
+ const note = options.note ?? (options.fromReport ? readPreparerReport(options.fromReport).note : undefined);
276
311
  const implementAttempts = [
277
312
  ...(last.implementAttempts ?? []),
278
- { url: options.url, attemptedAt: new Date().toISOString(), outcome: 'blocked', note: options.note },
313
+ { url: options.url, attemptedAt: new Date().toISOString(), outcome: 'blocked', note },
279
314
  ];
280
315
  sm.setLastOvernight({ ...last, implementAttempts });
316
+ const dropDir = handoffDir();
317
+ if (dropDir)
318
+ exportHandoff(dropDir, { ...last, implementAttempts });
281
319
  const gistSyncWarning = await maybeCheckpoint(sm, MODULE);
282
320
  return { url: options.url, attemptCount: implementAttempts.length, ...(gistSyncWarning ? { gistSyncWarning } : {}) };
283
321
  }
@@ -287,13 +325,28 @@ export async function runOvernightRecord(options) {
287
325
  const last = sm.getLastOvernight();
288
326
  if (!last)
289
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}`);
290
334
  const entry = {
291
335
  url: options.url,
292
- branch: options.branch,
293
- worktree: options.worktree,
294
- note: options.note,
336
+ branch,
337
+ worktree: options.worktree ?? report.worktree,
338
+ note: options.note ?? report.note,
295
339
  recordedAt: new Date().toISOString(),
296
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
+ }
297
350
  const prepared = [...last.prepared, entry];
298
351
  // Recording the branch for tonight's list issue is what marks the attempt
299
352
  // as prepared, so the next run moves on to the next Pursue item.
@@ -306,6 +359,8 @@ export async function runOvernightRecord(options) {
306
359
  sm.setLastOvernight({ ...last, prepared, implementAttempts });
307
360
  const { reportRecreated } = writePreparedSection(last.reportPath, prepared);
308
361
  publishReport(sm, last.reportPath);
362
+ if (dropDir)
363
+ exportHandoff(dropDir, { ...last, prepared, implementAttempts });
309
364
  const gistSyncWarning = await maybeCheckpoint(sm, MODULE);
310
365
  return {
311
366
  reportPath: last.reportPath,
@@ -474,6 +529,16 @@ export const OVERNIGHT_DISALLOWED_TOOLS = [
474
529
  // `pnpm --dir x exec`), mirroring the `git * push` deny.
475
530
  'Bash(node * -e *)',
476
531
  'Bash(node * --eval *)',
532
+ 'Bash(node * -p *)',
533
+ 'Bash(node * -pe *)',
534
+ 'Bash(node * --print *)',
535
+ 'Bash(npm * x *)',
536
+ // The `=` forms take no space, so the space-delimited denies above miss
537
+ // them: `node --eval=<js>` runs exactly like `node --eval <js>`.
538
+ 'Bash(node --eval=*)',
539
+ 'Bash(node * --eval=*)',
540
+ 'Bash(node --print=*)',
541
+ 'Bash(node * --print=*)',
477
542
  'AskUserQuestion',
478
543
  ].join(',');
479
544
  export const OVERNIGHT_ALLOWED_TOOLS = [
@@ -107,6 +107,8 @@ export function buildScoutState(diagnostics) {
107
107
  title: '',
108
108
  skippedAt: dismissedAt,
109
109
  reason: 'dismissed',
110
+ // A dismissal is a manual decision: never let scout's TTL cull age it out.
111
+ permanent: true,
110
112
  });
111
113
  }
112
114
  // Strategy-derived personalization (#1464). `computeStrategy` returns null
@@ -120,6 +122,10 @@ export function buildScoutState(diagnostics) {
120
122
  const strategy = computeStrategy(state);
121
123
  return {
122
124
  version: 1,
125
+ // Scout 1.8.1 made this required on the inferred ScoutState type. Scout
126
+ // does not schema-parse a provided initialState, so pass its current
127
+ // revision (1) explicitly: that marks the state as already migrated.
128
+ stateRevision: 1,
123
129
  preferences: {
124
130
  githubUsername: config.githubUsername,
125
131
  languages: config.languages,
@@ -71,6 +71,9 @@ export function parseSkippedIssuesContent(content) {
71
71
  number,
72
72
  title: '',
73
73
  skippedAt: new Date(dateMs).toISOString(),
74
+ // Skip-file entries are manual skips; scout 1.8.1 only TTL-culls
75
+ // entries explicitly marked non-permanent.
76
+ permanent: true,
74
77
  });
75
78
  }
76
79
  return results;
@@ -13,6 +13,15 @@ export function isConditionalChecklistItem(line) {
13
13
  }
14
14
  // Matches markdown headings; `\S` after whitespace prevents backtracking with `.*` (#1718)
15
15
  const HEADING_RE = /^#{1,6}\s+(\S.*)/;
16
+ /**
17
+ * Matches an HTML comment that introduces a pick-one (single-select) group of
18
+ * checkboxes. Supported phrases: "exactly one", "pick one", "choose one".
19
+ * Intentionally excludes bare "one of" to avoid false positives on explanatory
20
+ * prose like "Complete one of the following only if it applies". (#1760)
21
+ */
22
+ const PICK_ONE_COMMENT_RE = /<!--[^>]*(?:exactly\s+one|pick\s+one|choose\s+one)[^>]*-->/i;
23
+ /** Matches any checkbox line (checked or unchecked). */
24
+ const ANY_CHECKBOX_RE = /^.*- \[[ x]\].*$/i;
16
25
  /**
17
26
  * Matches headings that indicate a mutually-exclusive "type of change" radio group
18
27
  * where exactly one option should be selected. (#1718)
@@ -59,6 +68,48 @@ function hasLeaveUncheckedNote(section) {
59
68
  return lower.includes('leave unchecked') && (lower.includes('not applicable') || lower.includes('n/a'));
60
69
  });
61
70
  }
71
+ /**
72
+ * Mark unchecked lines in a single pick-one run as exempt if exactly one box is
73
+ * checked. Extracted to keep `collectPickOneExemptLineIndices` within complexity
74
+ * limits.
75
+ */
76
+ function markPickOneRunExempt(lines, runStart, runEnd, exempt) {
77
+ const checkedInRun = lines.slice(runStart, runEnd).filter((l) => /- \[x\]/i.test(l)).length;
78
+ if (checkedInRun !== 1)
79
+ return;
80
+ for (let k = runStart; k < runEnd; k++) {
81
+ if (/- \[ \]/.test(lines[k]))
82
+ exempt.add(k);
83
+ }
84
+ }
85
+ /**
86
+ * Returns the set of line indices (within `lines`) that are unchecked checkbox lines
87
+ * belonging to a satisfied pick-one group. A pick-one group is a contiguous checkbox
88
+ * run immediately following an HTML comment matching PICK_ONE_COMMENT_RE. The group is
89
+ * satisfied when exactly one box in the run is checked; in that case the unchecked
90
+ * alternatives are intentional and must not be counted as incomplete. (#1760)
91
+ */
92
+ function collectPickOneExemptLineIndices(lines) {
93
+ const exempt = new Set();
94
+ let i = 0;
95
+ while (i < lines.length) {
96
+ if (!PICK_ONE_COMMENT_RE.test(lines[i])) {
97
+ i++;
98
+ continue;
99
+ }
100
+ // Advance past the comment, skipping any blank lines before the checkbox run
101
+ let j = i + 1;
102
+ while (j < lines.length && lines[j].trim() === '')
103
+ j++;
104
+ // Collect the contiguous checkbox run
105
+ const runStart = j;
106
+ while (j < lines.length && ANY_CHECKBOX_RE.test(lines[j]))
107
+ j++;
108
+ markPickOneRunExempt(lines, runStart, j, exempt);
109
+ i = j;
110
+ }
111
+ return exempt;
112
+ }
62
113
  /**
63
114
  * Analyze a single checkbox section and return its effective counts.
64
115
  * Returns null if the section should be entirely skipped.
@@ -76,7 +127,9 @@ function analyzeSectionItems(section) {
76
127
  const isTypeOfChange = section.heading !== null && TYPE_OF_CHANGE_RE.test(section.heading);
77
128
  if (isTypeOfChange && checked >= 1)
78
129
  return { checked, nonConditionalUnchecked: 0 };
79
- const nonConditionalUnchecked = uncheckedLines.filter((l) => !isConditionalChecklistItem(l));
130
+ // Pick-one groups: unchecked alternatives in a satisfied pick-one group are exempt. (#1760)
131
+ const pickOneExempt = collectPickOneExemptLineIndices(section.lines);
132
+ const nonConditionalUnchecked = section.lines.filter((l, idx) => /^.*- \[ \].*$/.test(l) && !isConditionalChecklistItem(l) && !pickOneExempt.has(idx));
80
133
  return { checked, nonConditionalUnchecked: nonConditionalUnchecked.length };
81
134
  }
82
135
  /**
@@ -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
  /**
@@ -351,6 +351,13 @@ export function loadState() {
351
351
  const statePath = getStatePath();
352
352
  try {
353
353
  if (fs.existsSync(statePath)) {
354
+ // Baseline mtime for saveState's compare-and-swap. Taken BEFORE the read:
355
+ // if another process writes in between, we end up with a baseline older
356
+ // than our content, and the next save fails with a ConcurrencyError the
357
+ // caller can recover from by reloading. Taken after the read, the same
358
+ // race pairs stale content with the new mtime and the save silently
359
+ // overwrites the other writer.
360
+ let mtimeMs = safeGetMtimeMs(statePath);
354
361
  const data = fs.readFileSync(statePath, 'utf8');
355
362
  let raw = JSON.parse(data);
356
363
  // Chain migrations: v1 → v2 → v3 → v4
@@ -392,6 +399,7 @@ export function loadState() {
392
399
  // Save migrated state only after validation succeeds
393
400
  if (wasMigrated) {
394
401
  atomicWriteFileSync(statePath, JSON.stringify(parsed.data, null, 2), 0o600);
402
+ mtimeMs = safeGetMtimeMs(statePath); // our own write: what we hold is what is on disk
395
403
  debug(MODULE, 'Migrated and validated state saved');
396
404
  }
397
405
  const state = parsed.data;
@@ -410,6 +418,7 @@ export function loadState() {
410
418
  }
411
419
  if (needsCleanupSave) {
412
420
  atomicWriteFileSync(statePath, JSON.stringify(state, null, 2), 0o600);
421
+ mtimeMs = safeGetMtimeMs(statePath); // our own write, as above
413
422
  warn(MODULE, 'Cleaned up dismissed PR URLs from persisted state');
414
423
  }
415
424
  }
@@ -417,8 +426,6 @@ export function loadState() {
417
426
  warn(MODULE, `Failed to clean up removed features from state: ${errorMessage(cleanupError)}`);
418
427
  // Continue with loaded state — cleanup will be retried on next load
419
428
  }
420
- // Record file mtime so reloadIfChanged() can detect external writes
421
- const mtimeMs = safeGetMtimeMs(statePath);
422
429
  // Log appropriate message based on version
423
430
  const repoCount = Object.keys(state.repoScores).length;
424
431
  debug(MODULE, `Loaded state v${state.version}: ${repoCount} repo scores tracked`);
@@ -564,15 +571,22 @@ export function reloadStateIfChanged(lastLoadedMtimeMs) {
564
571
  if (currentMtimeMs === lastLoadedMtimeMs)
565
572
  return null;
566
573
  const result = loadState();
567
- // Ensure mtime is always current after reload (covers backup-restore and fresh-state paths)
568
- // to prevent repeated unnecessary reloads on every request.
569
- try {
570
- result.mtimeMs = fs.statSync(statePath).mtimeMs;
571
- }
572
- catch (err) {
573
- // If file was just loaded, stat should not fail. If it does,
574
- // next reloadIfChanged() will simply trigger another reload.
575
- debug(MODULE, 'Could not re-read mtime after reload (will retry next cycle)', err);
574
+ // Re-stat only on the recovery paths. There loadState rewrote the file
575
+ // itself (backup restore) or returned 0 (fresh state), and a current mtime
576
+ // stops a reload on every request. On the clean path the baseline was
577
+ // taken BEFORE the read on purpose: replacing it with a later stat would
578
+ // pair the content we hold with a newer writer's mtime, and the next save
579
+ // would overwrite that writer without a ConcurrencyError. A baseline that
580
+ // is merely old costs one more reload, which converges.
581
+ if (result.recovery) {
582
+ try {
583
+ result.mtimeMs = fs.statSync(statePath).mtimeMs;
584
+ }
585
+ catch (err) {
586
+ // If file was just loaded, stat should not fail. If it does,
587
+ // next reloadIfChanged() will simply trigger another reload.
588
+ debug(MODULE, 'Could not re-read mtime after reload (will retry next cycle)', err);
589
+ }
576
590
  }
577
591
  return result;
578
592
  }
@@ -142,7 +142,16 @@ function collectAllActionReasons(input) {
142
142
  * Determine the overall status of a PR based on its signals.
143
143
  */
144
144
  export function determineStatus(input) {
145
- const primary = determinePrimaryStatus(input);
145
+ let primary = determinePrimaryStatus(input);
146
+ // A merge conflict is always the contributor's to fix, and nothing can merge
147
+ // until it is. The priority tree returns several waiting statuses
148
+ // (changes_addressed, pending_merge, ci_blocked, stale_ci_failure) before it
149
+ // reaches its conflict check, which hid the conflict: consumers only act on
150
+ // `needs_addressing`, and a dormant PR in that state was auto-shelved. One
151
+ // guard here covers every early return, present and future.
152
+ if (primary.status === 'waiting_on_maintainer' && input.hasMergeConflict) {
153
+ primary = { status: 'needs_addressing', actionReason: 'merge_conflict', stalenessTier: primary.stalenessTier };
154
+ }
146
155
  const actionReasons = collectAllActionReasons(input);
147
156
  if (actionReasons) {
148
157
  return { ...primary, actionReasons };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oss-autopilot/core",
3
- "version": "3.28.1",
3
+ "version": "3.29.1",
4
4
  "description": "CLI and core library for managing open source contributions",
5
5
  "type": "module",
6
6
  "bin": {
@@ -55,7 +55,7 @@
55
55
  "@octokit/plugin-retry": "^8.1.1",
56
56
  "@octokit/plugin-throttling": "^11.0.5",
57
57
  "@octokit/rest": "^22.0.1",
58
- "@oss-scout/core": "^1.8.0",
58
+ "@oss-scout/core": "^1.8.1",
59
59
  "commander": "^15.0.0",
60
60
  "zod": "^4.5.4"
61
61
  },