@oss-autopilot/core 3.37.0 → 3.38.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.
@@ -126,6 +126,7 @@ function collectRows(state) {
126
126
  return {
127
127
  url: e.url,
128
128
  repo,
129
+ issueUrl: e.issueUrl,
129
130
  firstInRepo: e.pick?.firstInRepo ?? isFirstAt(repo, Date.parse(e.openedAt ?? at)),
130
131
  pick: e.pick,
131
132
  grade: e.pick?.grade,
@@ -182,6 +183,7 @@ export function computeEvalReport(state, now = new Date()) {
182
183
  }
183
184
  }
184
185
  const picked = rows.filter((r) => r.pick);
186
+ const closesIssue = rows.filter((r) => r.issueUrl && r.outcome !== 'dormant');
185
187
  const reviewed = rows.filter((r) => r.changesRequested !== undefined);
186
188
  const ciKnown = rows.filter((r) => r.ciFailing !== undefined);
187
189
  const byGrade = groupBy(rows, (r) => (r.gradeSource ? `${r.gradeSource} ${gradeRange(r.grade)}` : 'no prediction'), [
@@ -207,6 +209,7 @@ export function computeEvalReport(state, now = new Date()) {
207
209
  headlines: {
208
210
  mergeRate1kStars: bucket('>=1k stars', rows.filter((r) => (r.stars ?? 0) >= 1000)),
209
211
  calibration: { gap, highN: high.length, lowN: low.length },
212
+ vetCoverage: { graded: closesIssue.filter((r) => r.gradeSource === 'vet').length, of: closesIssue.length },
210
213
  approachClosuresByMonth,
211
214
  },
212
215
  byGrade,
@@ -263,6 +266,7 @@ export function formatEvalMarkdown(r) {
263
266
  '',
264
267
  `- Merge rate on repos with 1k+ stars: **${pct(h.mergeRate1kStars.mergeRate)}** (n=${h.mergeRate1kStars.n})`,
265
268
  `- Calibration gap, vet grades (grade>=7 minus grade<=5 merge rate): **${h.calibration.gap ?? 'n/a'}** (n=${h.calibration.highN} vs ${h.calibration.lowN}; needs ${MIN_FLAG_N} each)`,
269
+ `- Vet grade recorded at pick: **${h.vetCoverage.graded} of ${h.vetCoverage.of}** merged or closed PRs that close an issue`,
266
270
  `- Approach or AI-policy closures by month: ${recentMonths.length ? recentMonths.map((m) => `${m}: ${h.approachClosuresByMonth[m]}`).join(', ') : 'none'}`,
267
271
  `- Overall: ${r.totals.n} outcomes, merge rate ${pct(r.totals.mergeRate)} (dormant counted as not merged)`,
268
272
  '',
@@ -271,10 +271,13 @@ export declare class GistStateStore {
271
271
  * outcomes that previously collapsed into a single boolean (#1209 L9):
272
272
  * - `{ status: 'refreshed' }` — fresh data loaded successfully.
273
273
  * - `{ status: 'no-gist' }` — store not in Gist mode (e.g. degraded).
274
- * - `{ status: 'throttled', sinceLastMs }` — within the 30s throttle.
274
+ * - `{ status: 'throttled', sinceLastMs }` — within the 30s throttle
275
+ * (skipped when `options.force` is set).
275
276
  * - `{ status: 'error', error }` — fetch attempt failed.
276
277
  */
277
- refreshFromGist(): Promise<RefreshResult>;
278
+ refreshFromGist(options?: {
279
+ force?: boolean;
280
+ }): Promise<RefreshResult>;
278
281
  /**
279
282
  * Refuse to write a file the Gist could no longer serve back (raw_url stops
280
283
  * at 10 MB), and warn once a file passes ~900 KB so growth is visible before
@@ -577,17 +577,20 @@ export class GistStateStore {
577
577
  * outcomes that previously collapsed into a single boolean (#1209 L9):
578
578
  * - `{ status: 'refreshed' }` — fresh data loaded successfully.
579
579
  * - `{ status: 'no-gist' }` — store not in Gist mode (e.g. degraded).
580
- * - `{ status: 'throttled', sinceLastMs }` — within the 30s throttle.
580
+ * - `{ status: 'throttled', sinceLastMs }` — within the 30s throttle
581
+ * (skipped when `options.force` is set).
581
582
  * - `{ status: 'error', error }` — fetch attempt failed.
582
583
  */
583
- async refreshFromGist() {
584
+ async refreshFromGist(options = {}) {
584
585
  if (!this.gistId)
585
586
  return { status: 'no-gist' };
586
587
  const now = Date.now();
587
588
  const sinceLastMs = now - this.lastRefreshAt;
588
589
  // Throttle hits are not failures — preserve any previous lastRefreshError
589
- // for the caller to inspect.
590
- if (sinceLastMs < GistStateStore.REFRESH_THROTTLE_MS) {
590
+ // for the caller to inspect. `force` bypasses the throttle for the
591
+ // conflict-recovery path: a retry that re-reads the same stale baseline
592
+ // fails identically (audit 2026-10-30 M1).
593
+ if (sinceLastMs < GistStateStore.REFRESH_THROTTLE_MS && !options.force) {
591
594
  return { status: 'throttled', sinceLastMs };
592
595
  }
593
596
  // Stamp the ATTEMPT, success or failure (#1443): the success-only stamp
@@ -72,6 +72,6 @@ export async function persistPickSnapshots(stateManager, snapshots) {
72
72
  warn(MODULE, pickRecordError);
73
73
  return { pickRecordError };
74
74
  }
75
- const gistSyncWarning = await maybeCheckpoint(stateManager, MODULE);
75
+ const gistSyncWarning = await maybeCheckpoint(stateManager, MODULE, () => stateManager.recordPickSnapshots(snapshots));
76
76
  return gistSyncWarning ? { gistSyncWarning } : {};
77
77
  }
@@ -86,7 +86,10 @@ export function releaseLock(lockPath) {
86
86
  * preventing partial/corrupt state files if the process crashes mid-write.
87
87
  */
88
88
  export function atomicWriteFileSync(filePath, data, mode) {
89
- const tmpPath = filePath + '.tmp';
89
+ // Per-process name: two unlocked writers (MCP server + a CLI run, both in
90
+ // Gist mode) sharing one `<file>.tmp` could publish each other's partial
91
+ // write via rename (audit 2026-10-30 L2).
92
+ const tmpPath = `${filePath}.${process.pid}.tmp`;
90
93
  fs.writeFileSync(tmpPath, data, { mode: mode ?? 0o600 });
91
94
  fs.renameSync(tmpPath, filePath);
92
95
  // Ensure permissions are correct (rename preserves the tmp file's mode,
@@ -31,8 +31,12 @@ export declare const MAX_PICK_SNAPSHOTS = 300;
31
31
  * after its retry — previously that was discarded everywhere except
32
32
  * `state --sync`, so a failed cross-machine sync reported clean success
33
33
  * (#1370). stderr `warn()` alone is invisible to MCP/dashboard consumers.
34
+ *
35
+ * Pass `reapply` (the same mutation the caller just performed) to make a
36
+ * `GistConcurrencyError` recoverable: the state is force-refreshed from the
37
+ * Gist, `reapply` runs on the fresh baseline, and the push is retried once.
34
38
  */
35
- export declare function maybeCheckpoint(stateManager: StateManager, callerModule: string): Promise<string | null>;
39
+ export declare function maybeCheckpoint(stateManager: StateManager, callerModule: string, reapply?: () => void): Promise<string | null>;
36
40
  /**
37
41
  * Singleton manager for persistent agent state stored in ~/.oss-autopilot/state.json.
38
42
  *
@@ -68,6 +72,10 @@ export declare class StateManager {
68
72
  protected gistDegraded: boolean;
69
73
  private staleness;
70
74
  private lastSuccessfulRefreshAt;
75
+ private mutationDepth;
76
+ /** Gist mode: a mutation was saved since the last successful push. */
77
+ private unpushed;
78
+ private refreshCount;
71
79
  private loadRecovery;
72
80
  /**
73
81
  * Create a new StateManager instance.
@@ -193,11 +201,36 @@ export declare class StateManager {
193
201
  * fresh state because the main file was corrupt or invalid (#1371).
194
202
  */
195
203
  getLoadRecovery(): LoadRecoveryInfo | null;
204
+ /**
205
+ * Run `fn` as an in-flight mutation: non-forced `refreshFromGist()` calls
206
+ * are skipped until it settles so a concurrent refresh cannot swap
207
+ * `this.state` out from under it (audit 2026-10-30 M2).
208
+ *
209
+ * Deliberately a counter, not a serializing promise chain: parallel MCP
210
+ * tool bodies from one host message may depend on each other through the
211
+ * host, so queuing them would deadlock. The gap that leaves (a sibling's
212
+ * *forced* conflict-recovery refresh swaps the state object mid-body) is
213
+ * closed by `maybeCheckpoint` re-applying every mutation right before its
214
+ * push; bodies that cannot re-apply (`daily`) watch `refreshGeneration`.
215
+ */
216
+ runMutation<T>(fn: () => Promise<T>): Promise<T>;
217
+ /**
218
+ * Number of times a Gist refresh replaced the in-memory state. A successful
219
+ * push resolves earlier un-pushed changes only if this did not advance in
220
+ * between (the #1443 loss-notice invariant); a long run compares it to the
221
+ * value at its start to learn its mutations were swapped out.
222
+ */
223
+ get refreshGeneration(): number;
224
+ /** Gist mode: whether a saved mutation has not reached the Gist yet. */
225
+ hasUnpushedChanges(): boolean;
196
226
  /**
197
227
  * Re-fetch state from the backing Gist (if in Gist mode).
198
- * Throttled to once per 30 seconds by GistStateStore. Returns true if state was refreshed.
228
+ * Throttled to once per 30 seconds by GistStateStore unless `force` is set.
229
+ * Returns true if state was refreshed.
199
230
  */
200
- refreshFromGist(): Promise<boolean>;
231
+ refreshFromGist(options?: {
232
+ force?: boolean;
233
+ }): Promise<boolean>;
201
234
  /**
202
235
  * Returns a staleness marker when the in-memory state diverged from the
203
236
  * canonical Gist (refresh failure or degraded bootstrap), or `null` when
@@ -9,7 +9,7 @@ import { serializeState } from './state-prune.js';
9
9
  import { loadState, saveState, reloadStateIfChanged, createFreshState, atomicWriteFileSync, } from './state-persistence.js';
10
10
  import * as repoScoring from './repo-score-manager.js';
11
11
  import { debug, warn } from './logger.js';
12
- import { errorMessage, ConfigurationError, ConcurrencyError, isTransientNetworkError, GistFileSizeError, GIST_FILE_SIZE_REMEDY, } from './errors.js';
12
+ import { errorMessage, ConfigurationError, ConcurrencyError, GistConcurrencyError, isTransientNetworkError, GistFileSizeError, GIST_FILE_SIZE_REMEDY, } from './errors.js';
13
13
  import { GistStateStore } from './gist-state-store.js';
14
14
  import * as guidelinesStoreModule from './guidelines-store.js';
15
15
  /** Gist file that carries the rendered overnight report across machines (#1698). */
@@ -85,24 +85,77 @@ export const MAX_PICK_SNAPSHOTS = 300;
85
85
  * after its retry — previously that was discarded everywhere except
86
86
  * `state --sync`, so a failed cross-machine sync reported clean success
87
87
  * (#1370). stderr `warn()` alone is invisible to MCP/dashboard consumers.
88
+ *
89
+ * Pass `reapply` (the same mutation the caller just performed) to make a
90
+ * `GistConcurrencyError` recoverable: the state is force-refreshed from the
91
+ * Gist, `reapply` runs on the fresh baseline, and the push is retried once.
88
92
  */
89
- export async function maybeCheckpoint(stateManager, callerModule) {
93
+ export async function maybeCheckpoint(stateManager, callerModule, reapply) {
90
94
  if (!stateManager.isGistMode())
91
95
  return null;
96
+ // Re-apply before the push, not only on conflict: a sibling mutation's
97
+ // conflict recovery (another MCP tool body running in parallel) may have
98
+ // swapped `this.state` since the caller mutated, orphaning its change.
99
+ // `reapply` is an absolute set, so this is a no-op in the common case.
100
+ reapply?.();
92
101
  try {
93
- const pushed = await stateManager.checkpoint();
94
- if (!pushed) {
95
- const msg = 'Gist checkpoint push failed after retry; the local mutation is saved and will sync on the next successful push';
96
- warn(callerModule, msg);
97
- return msg;
98
- }
102
+ return await pushOrWarn(stateManager, callerModule);
103
+ }
104
+ catch (err) {
105
+ if (err instanceof GistConcurrencyError && reapply)
106
+ return recoverConflict(stateManager, callerModule, reapply, err);
107
+ return notSynced(callerModule, err);
108
+ }
109
+ }
110
+ async function pushOrWarn(stateManager, callerModule) {
111
+ if (await stateManager.checkpoint())
99
112
  return null;
113
+ const msg = 'Gist checkpoint push failed after retry; the local mutation is saved and will sync on the next successful push';
114
+ warn(callerModule, msg);
115
+ return msg;
116
+ }
117
+ /**
118
+ * Cross-machine conflict: another machine pushed since our last fetch. The
119
+ * in-memory mutation would otherwise be dropped by the next refresh or
120
+ * bootstrap with nothing ever retrying it (audit 2026-10-30 H1), so re-fetch
121
+ * (bypassing the 30s throttle), re-apply the caller's mutation on the fresh
122
+ * baseline, and push once more. Every caller's `reapply` is an absolute set
123
+ * operation, so re-running it is safe.
124
+ */
125
+ async function recoverConflict(stateManager, callerModule, reapply, conflict) {
126
+ let isRefreshed;
127
+ try {
128
+ // Inside runMutation so the refresh counts as mutation-driven: a reapply
129
+ // follows, which is what distinguishes it from the depth-0 forced reload
130
+ // that refreshFromGist refuses while changes are un-pushed.
131
+ isRefreshed = await stateManager.runMutation(() => stateManager.refreshFromGist({ force: true }));
100
132
  }
101
133
  catch (err) {
102
- const msg = `Gist checkpoint failed (local mutation succeeded, will retry on next push): ${errorMessage(err)}`;
134
+ return notSynced(callerModule, err);
135
+ }
136
+ if (!isRefreshed)
137
+ return notSynced(callerModule, conflict);
138
+ // From here the in-memory state is the Gist's copy: a reapply failure
139
+ // means the mutation is gone, not "saved".
140
+ try {
141
+ reapply();
142
+ }
143
+ catch (err) {
144
+ const msg = `Gist conflict recovery failed; state was refreshed from the Gist and re-applying the mutation threw, so the mutation was LOST, re-run the command: ${errorMessage(err)}`;
103
145
  warn(callerModule, msg);
104
146
  return msg;
105
147
  }
148
+ try {
149
+ return await pushOrWarn(stateManager, callerModule);
150
+ }
151
+ catch (err) {
152
+ return notSynced(callerModule, err);
153
+ }
154
+ }
155
+ function notSynced(callerModule, err) {
156
+ const msg = `Gist checkpoint failed; the local mutation is saved but NOT synced to the Gist, re-run the command to retry: ${errorMessage(err)}`;
157
+ warn(callerModule, msg);
158
+ return msg;
106
159
  }
107
160
  export class StateManager {
108
161
  state;
@@ -114,6 +167,10 @@ export class StateManager {
114
167
  gistDegraded = false;
115
168
  staleness = null;
116
169
  lastSuccessfulRefreshAt = null;
170
+ mutationDepth = 0;
171
+ /** Gist mode: a mutation was saved since the last successful push. */
172
+ unpushed = false;
173
+ refreshCount = 0;
117
174
  loadRecovery = null;
118
175
  /**
119
176
  * Create a new StateManager instance.
@@ -290,6 +347,8 @@ export class StateManager {
290
347
  */
291
348
  save(options = {}) {
292
349
  this.state.lastRunAt = new Date().toISOString();
350
+ if (this.gistStore)
351
+ this.unpushed = true;
293
352
  if (this.inMemoryOnly) {
294
353
  return;
295
354
  }
@@ -349,6 +408,8 @@ export class StateManager {
349
408
  // left untouched here — a concurrent remote write is recoverable (refresh +
350
409
  // retry), not a degradation of the Gist itself.
351
410
  this.gistDegraded = !isPushed;
411
+ if (isPushed)
412
+ this.unpushed = false;
352
413
  return isPushed;
353
414
  }
354
415
  /** Whether this StateManager is backed by a Gist. */
@@ -459,14 +520,63 @@ export class StateManager {
459
520
  getLoadRecovery() {
460
521
  return this.loadRecovery;
461
522
  }
523
+ /**
524
+ * Run `fn` as an in-flight mutation: non-forced `refreshFromGist()` calls
525
+ * are skipped until it settles so a concurrent refresh cannot swap
526
+ * `this.state` out from under it (audit 2026-10-30 M2).
527
+ *
528
+ * Deliberately a counter, not a serializing promise chain: parallel MCP
529
+ * tool bodies from one host message may depend on each other through the
530
+ * host, so queuing them would deadlock. The gap that leaves (a sibling's
531
+ * *forced* conflict-recovery refresh swaps the state object mid-body) is
532
+ * closed by `maybeCheckpoint` re-applying every mutation right before its
533
+ * push; bodies that cannot re-apply (`daily`) watch `refreshGeneration`.
534
+ */
535
+ async runMutation(fn) {
536
+ this.mutationDepth++;
537
+ try {
538
+ return await fn();
539
+ }
540
+ finally {
541
+ this.mutationDepth--;
542
+ }
543
+ }
544
+ /**
545
+ * Number of times a Gist refresh replaced the in-memory state. A successful
546
+ * push resolves earlier un-pushed changes only if this did not advance in
547
+ * between (the #1443 loss-notice invariant); a long run compares it to the
548
+ * value at its start to learn its mutations were swapped out.
549
+ */
550
+ get refreshGeneration() {
551
+ return this.refreshCount;
552
+ }
553
+ /** Gist mode: whether a saved mutation has not reached the Gist yet. */
554
+ hasUnpushedChanges() {
555
+ return this.unpushed;
556
+ }
462
557
  /**
463
558
  * Re-fetch state from the backing Gist (if in Gist mode).
464
- * Throttled to once per 30 seconds by GistStateStore. Returns true if state was refreshed.
559
+ * Throttled to once per 30 seconds by GistStateStore unless `force` is set.
560
+ * Returns true if state was refreshed.
465
561
  */
466
- async refreshFromGist() {
562
+ async refreshFromGist(options = {}) {
467
563
  if (!this.gistStore)
468
564
  return false;
469
- const result = await this.gistStore.refreshFromGist();
565
+ // A refresh replaces `this.state`, orphaning every mutation an in-flight
566
+ // command (e.g. a long `daily` run in the MCP server) has made so far
567
+ // (audit 2026-10-30 M2). Skip it while one is running; `force` is for
568
+ // the conflict-recovery path, which the mutation itself drives.
569
+ if (this.mutationDepth > 0 && !options.force)
570
+ return false;
571
+ // A forced refresh outside any mutation (the MCP/dashboard conflict
572
+ // retry) has nothing that will re-apply un-pushed changes afterwards, so
573
+ // it would silently push the remote back over them: refuse, and let the
574
+ // retried body surface the conflict honestly.
575
+ if (options.force && this.mutationDepth === 0 && this.unpushed) {
576
+ warn(MODULE, 'Forced Gist refresh refused: local changes are not pushed yet and nothing would re-apply them');
577
+ return false;
578
+ }
579
+ const result = await this.gistStore.refreshFromGist(options);
470
580
  // StateManager keeps its boolean shape (callers rely on truthy-check
471
581
  // semantics) but consults the discriminated union internally to know
472
582
  // whether to reload state.json from the now-fresh cache (#1209 L9).
@@ -486,9 +596,9 @@ export class StateManager {
486
596
  };
487
597
  return false;
488
598
  }
599
+ const wasUnpushed = this.unpushed;
489
600
  try {
490
601
  this.state = AgentStateSchema.parse(JSON.parse(raw));
491
- this.tryReconcilePRCounts();
492
602
  }
493
603
  catch (err) {
494
604
  warn(MODULE, `Failed to parse refreshed Gist state: ${errorMessage(err)}`);
@@ -502,9 +612,30 @@ export class StateManager {
502
612
  };
503
613
  return false;
504
614
  }
615
+ // Derived bookkeeping on the fresh copy, not a user change: it must
616
+ // not count as un-pushed, so the flag is reset after it runs.
617
+ this.tryReconcilePRCounts();
618
+ this.unpushed = false;
505
619
  // Successful refresh clears any prior staleness (#1193).
506
- this.lastSuccessfulRefreshAt = new Date().toISOString();
620
+ const now = new Date();
621
+ this.lastSuccessfulRefreshAt = now.toISOString();
507
622
  this.staleness = null;
623
+ this.refreshCount++;
624
+ // Only the throttled depth-0 refresh gets here with un-pushed changes
625
+ // (a forced one is conflict recovery, which re-applies its mutation).
626
+ // Their push already failed once; this is the moment they are gone, so
627
+ // say so where commands and the dashboard read staleness (#1193).
628
+ if (wasUnpushed && !options.force) {
629
+ const reason = 'A Gist refresh replaced local state that still had un-pushed changes; they were NOT synced. ' +
630
+ 'Re-run the command that made the change.';
631
+ warn(MODULE, reason);
632
+ this.staleness = {
633
+ reason,
634
+ source: 'cache',
635
+ lastSuccessfulRefresh: this.lastSuccessfulRefreshAt,
636
+ detectedAt: now.toISOString(),
637
+ };
638
+ }
508
639
  }
509
640
  else if (this.gistStore.lastRefreshError) {
510
641
  // Distinguish "fetch failed" (set marker) from "throttled" (preserve
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oss-autopilot/core",
3
- "version": "3.37.0",
3
+ "version": "3.38.0",
4
4
  "description": "CLI and core library for managing open source contributions",
5
5
  "type": "module",
6
6
  "bin": {