@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.
@@ -245,7 +245,7 @@ export async function runClaim(options) {
245
245
  let stateSaveWarning;
246
246
  try {
247
247
  const stateManager = getStateManager();
248
- stateManager.addIssue({
248
+ const issue = {
249
249
  id: number,
250
250
  url: options.issueUrl,
251
251
  repo: `${owner}/${repo}`,
@@ -256,11 +256,12 @@ export async function runClaim(options) {
256
256
  createdAt: issueCreatedAt,
257
257
  updatedAt: new Date().toISOString(),
258
258
  vetted: false,
259
- });
259
+ };
260
+ stateManager.addIssue(issue);
260
261
  // Push state to Gist if in Gist mode. Best-effort — the warning is
261
262
  // threaded into the structured output so MCP/dashboard consumers see
262
263
  // the degraded-sync signal, not just the stderr log (#1036 audit H1, #1370).
263
- gistSyncWarning = await maybeCheckpoint(stateManager, MODULE);
264
+ gistSyncWarning = await maybeCheckpoint(stateManager, MODULE, () => stateManager.addIssue(issue));
264
265
  }
265
266
  catch (error) {
266
267
  // The claim comment is live on GitHub but local state never tracked it —
@@ -34,17 +34,29 @@ export async function runConfig(options) {
34
34
  return { keys: CONFIG_KEY_REGISTRY };
35
35
  }
36
36
  const stateManager = getStateManager();
37
- const currentConfig = stateManager.getState().config;
38
37
  if (!options.key) {
39
38
  // Show current config
40
- return { config: currentConfig };
39
+ return { config: stateManager.getState().config };
41
40
  }
42
41
  if (!options.value) {
43
42
  throw new Error('Value required');
44
43
  }
45
- const value = options.value;
46
- // Handle specific config keys
47
- switch (options.key) {
44
+ const { key, value } = options;
45
+ const apply = () => applyConfigKey(stateManager, key, value);
46
+ apply();
47
+ // Push the config mutation to the Gist in gist mode (no-op locally).
48
+ // Without this the change only hits the local cache and the next
49
+ // bootstrap reverts it from the Gist (#1440).
50
+ const gistSyncWarning = await maybeCheckpoint(stateManager, MODULE, apply);
51
+ return { success: true, key, value, ...(gistSyncWarning && { gistSyncWarning }) };
52
+ }
53
+ /**
54
+ * Apply one config key. Reads the current config fresh so the Gist conflict
55
+ * path can re-run it on a refreshed baseline without stale array merges.
56
+ */
57
+ function applyConfigKey(stateManager, key, value) {
58
+ const currentConfig = stateManager.getState().config;
59
+ switch (key) {
48
60
  case 'username': {
49
61
  stateManager.updateConfig({ githubUsername: validateGitHubUsername(value) });
50
62
  break;
@@ -177,12 +189,7 @@ export async function runConfig(options) {
177
189
  break;
178
190
  }
179
191
  default: {
180
- throw new ValidationError(formatUnknownKeyError(options.key, 'config'));
192
+ throw new ValidationError(formatUnknownKeyError(key, 'config'));
181
193
  }
182
194
  }
183
- // Push the config mutation to the Gist in gist mode (no-op locally).
184
- // Without this the change only hits the local cache and the next
185
- // bootstrap reverts it from the Gist (#1440).
186
- const gistSyncWarning = await maybeCheckpoint(stateManager, MODULE);
187
- return { success: true, key: options.key, value, ...(gistSyncWarning && { gistSyncWarning }) };
188
195
  }
@@ -6,7 +6,7 @@
6
6
  * Domain logic lives in src/core/daily-logic.ts; this file is a thin
7
7
  * orchestration layer that wires up the phases and handles I/O.
8
8
  */
9
- import { getStateManager, parseGitHubUrl, PRMonitor, IssueConversationMonitor, requireGitHubToken, renderGistWarning, CRITICAL_STATUSES, applyStatusOverrides, computeRepoSignals, computeLedgerRepoSignals, groupPRsByRepo, assessCapacity, collectActionableIssues, computeActionMenu, toShelvedPRRef, formatBriefSummary, formatSummary, summarizeAttentionBuckets, shouldSuggestClose, } from '../core/index.js';
9
+ import { getStateManager, parseGitHubUrl, PRMonitor, IssueConversationMonitor, requireGitHubToken, renderGistWarning, CRITICAL_STATUSES, applyStatusOverrides, computeRepoSignals, computeLedgerRepoSignals, GistConcurrencyError, groupPRsByRepo, assessCapacity, collectActionableIssues, computeActionMenu, toShelvedPRRef, formatBriefSummary, formatSummary, summarizeAttentionBuckets, shouldSuggestClose, } from '../core/index.js';
10
10
  import { errorMessage, isRateLimitOrAuthError } from '../core/errors.js';
11
11
  import { wrapUntrustedContent } from '../core/untrusted-content.js';
12
12
  import { computeStrategy, shouldComputeStrategy } from '../core/strategy.js';
@@ -637,6 +637,9 @@ async function executeDailyCheckInternal(token) {
637
637
  // One collector shared by every phase — threaded through explicitly so the
638
638
  // callgraph documents which phases can produce non-fatal warnings. See #1042.
639
639
  const warnings = [];
640
+ // This run's mutations cannot be re-applied, so if a concurrent tool's
641
+ // conflict recovery refreshes state mid-run they are gone; say so at the end.
642
+ const generationAtStart = getStateManager().refreshGeneration;
640
643
  // Surface gist-mode degradation in the machine-readable envelope (#1431):
641
644
  // a degraded process (local-only under a gist config, or a #1443 degraded
642
645
  // bootstrap) writes mutations that will not sync. Previously the only
@@ -788,6 +791,9 @@ async function executeDailyCheckInternal(token) {
788
791
  try {
789
792
  const sm = getStateManager();
790
793
  if (sm.isGistMode()) {
794
+ if (sm.refreshGeneration !== generationAtStart) {
795
+ recordWarning(warnings, 'gist-checkpoint', 'Gist checkpoint', new Error('state was refreshed from the Gist while this run was in progress; its state changes were dropped, re-run daily'));
796
+ }
791
797
  // checkpoint() resolves false (no throw) when the push failed after
792
798
  // its retry — previously discarded, reporting clean success while
793
799
  // cross-machine state silently drifted (#1370).
@@ -798,7 +804,12 @@ async function executeDailyCheckInternal(token) {
798
804
  }
799
805
  }
800
806
  catch (err) {
801
- recordWarning(warnings, 'gist-checkpoint', 'Gist checkpoint', err);
807
+ // A conflict cannot be recovered here (nothing re-applies a daily run):
808
+ // the next refresh drops this run's changes, so say that, not "retry".
809
+ const cause = err instanceof GistConcurrencyError
810
+ ? new Error("another machine pushed during this run; this run's state changes were NOT synced and will be dropped, re-run daily")
811
+ : err;
812
+ recordWarning(warnings, 'gist-checkpoint', 'Gist checkpoint', cause);
802
813
  }
803
814
  return result;
804
815
  }
@@ -15,6 +15,8 @@ export declare class GistSyncCoordinator {
15
15
  private readonly module;
16
16
  private manager;
17
17
  private pendingGistSyncWarnings;
18
+ /** `refreshGeneration` when the oldest pending warning was recorded. */
19
+ private pendingSince;
18
20
  private lastRecoveryAttemptAt;
19
21
  private recoveryHaltedReason;
20
22
  private degradedMutationCount;
@@ -66,7 +68,9 @@ export declare class GistSyncCoordinator {
66
68
  * notice when the pull actually replaced state (#1443). All dashboard pull
67
69
  * sites go through here; callers flush pending pushes first (#1417), so a
68
70
  * warning that is still pending at pull time means the flush failed. */
69
- pullFromGist(): Promise<boolean>;
71
+ pullFromGist(options?: {
72
+ force?: boolean;
73
+ }): Promise<boolean>;
70
74
  /** Re-attempt gist init while degraded (#1433). The serve process used to
71
75
  * bootstrap exactly once at CLI preAction — with its stderr discarded by
72
76
  * the detached spawn — and never retry, so one blip at startup meant
@@ -37,6 +37,8 @@ export class GistSyncCoordinator {
37
37
  // exactly the event that can destroy it (refreshFromGist wholesale-replaces
38
38
  // state). These clear only when a checkpoint PUSH succeeds.
39
39
  pendingGistSyncWarnings = [];
40
+ /** `refreshGeneration` when the oldest pending warning was recorded. */
41
+ pendingSince = 0;
40
42
  lastRecoveryAttemptAt = 0;
41
43
  recoveryHaltedReason = null;
42
44
  // Mutations acknowledged while degraded (#1433 review): a successful
@@ -65,9 +67,17 @@ export class GistSyncCoordinator {
65
67
  * so any previously pending warning is resolved with it. */
66
68
  recordGistSyncOutcome(warning) {
67
69
  if (warning === null) {
70
+ // ...unless a Gist refresh replaced state since the warning was
71
+ // recorded (a mutation's own conflict recovery does that without going
72
+ // through pullFromGist): the push then carried the Gist's copy, not the
73
+ // un-pushed change, so it is a loss, not a resolution (#1443 invariant).
74
+ if (this.manager.refreshGeneration !== this.pendingSince)
75
+ this.convertPendingWarningsToLossNotices();
68
76
  this.pendingGistSyncWarnings = [];
69
77
  return;
70
78
  }
79
+ if (this.pendingGistSyncWarnings.length === 0)
80
+ this.pendingSince = this.manager.refreshGeneration;
71
81
  if (!this.pendingGistSyncWarnings.includes(warning)) {
72
82
  this.pendingGistSyncWarnings.push(warning);
73
83
  }
@@ -153,8 +163,8 @@ export class GistSyncCoordinator {
153
163
  * notice when the pull actually replaced state (#1443). All dashboard pull
154
164
  * sites go through here; callers flush pending pushes first (#1417), so a
155
165
  * warning that is still pending at pull time means the flush failed. */
156
- async pullFromGist() {
157
- const refreshed = await this.manager.refreshFromGist();
166
+ async pullFromGist(options = {}) {
167
+ const refreshed = await this.manager.refreshFromGist(options);
158
168
  if (refreshed)
159
169
  this.convertPendingWarningsToLossNotices();
160
170
  return refreshed;
@@ -189,7 +199,14 @@ export class GistSyncCoordinator {
189
199
  try {
190
200
  await ensureGistPersistence(currentToken);
191
201
  // The upgrade replaced the core singleton — re-resolve our reference.
202
+ const previous = this.manager;
192
203
  this.manager = getStateManager();
204
+ // A swapped manager starts its own refreshGeneration; re-anchor any
205
+ // still-pending warnings to it so the next successful push is not
206
+ // misread as a loss (or a loss missed) against the old counter.
207
+ if (this.manager !== previous && this.pendingGistSyncWarnings.length > 0) {
208
+ this.pendingSince = this.manager.refreshGeneration;
209
+ }
193
210
  // Genuinely armed only: a retry can resolve via ANOTHER degraded
194
211
  // bootstrap (gist-backed, store disarmed) — that is not a recovery
195
212
  // and must not produce a recovery notice (#1443).
@@ -338,7 +338,7 @@ export async function startDashboardServer(options) {
338
338
  * Returns true when the state source changed (gist pull refreshed, local
339
339
  * file reloaded, or a gist recovery completed) — GET /api/data uses this
340
340
  * to decide whether to rebuild the cached payload (#1446 item 5). */
341
- async function reloadState() {
341
+ async function reloadState(options = {}) {
342
342
  if (gistSync.stateManager.isGistMode()) {
343
343
  await gistSync.flushPendingGistSync();
344
344
  // Both post-pull steps consume the same refreshFromGist outcome, in
@@ -350,7 +350,7 @@ export async function startDashboardServer(options) {
350
350
  // because the background-refresh path also pulls but replaces
351
351
  // cachedDigest unconditionally right after — adoption is a
352
352
  // reloadState-path concern only.
353
- const refreshed = await gistSync.pullFromGist();
353
+ const refreshed = await gistSync.pullFromGist(options);
354
354
  if (refreshed)
355
355
  cache.adoptNewerPulledDigest(gistSync.stateManager.getState().lastDigest);
356
356
  if (gistSync.gistBootstrapDegraded()) {
@@ -481,8 +481,9 @@ export async function startDashboardServer(options) {
481
481
  // never the loaded state) so the read-modify-write window excludes the
482
482
  // body-streaming time (#1397).
483
483
  await reloadState();
484
+ const sm = gistSync.stateManager;
484
485
  try {
485
- await applyMutation();
486
+ await sm.runMutation(async () => applyMutation());
486
487
  }
487
488
  catch (error) {
488
489
  if (!isConcurrencyConflict(error)) {
@@ -498,9 +499,12 @@ export async function startDashboardServer(options) {
498
499
  // in state-concurrency.test.ts. A second consecutive conflict means
499
500
  // sustained contention; surface it as a retryable 409 and let the SPA
500
501
  // re-prime and retry.
502
+ // The retry bypasses the 30s Gist refresh throttle: the reload above
503
+ // stamped it seconds ago, so a throttled reload would re-run the
504
+ // mutation against the same stale baseline (audit 2026-10-30 M1).
501
505
  try {
502
- await reloadState();
503
- await applyMutation();
506
+ await reloadState({ force: true });
507
+ await sm.runMutation(async () => applyMutation());
504
508
  }
505
509
  catch (retryError) {
506
510
  if (isConcurrencyConflict(retryError)) {
@@ -19,8 +19,9 @@ export async function runDismiss(options) {
19
19
  validateUrl(options.url);
20
20
  validateGitHubUrl(options.url, ISSUE_URL_PATTERN, 'issue');
21
21
  const stateManager = getStateManager();
22
- const added = stateManager.dismissIssue(options.url, new Date().toISOString());
23
- const gistSyncWarning = await maybeCheckpoint(stateManager, MODULE);
22
+ const dismissedAt = new Date().toISOString();
23
+ const added = stateManager.dismissIssue(options.url, dismissedAt);
24
+ const gistSyncWarning = await maybeCheckpoint(stateManager, MODULE, () => stateManager.dismissIssue(options.url, dismissedAt));
24
25
  return { dismissed: added, url: options.url, ...(gistSyncWarning && { gistSyncWarning }) };
25
26
  }
26
27
  /**
@@ -36,6 +37,6 @@ export async function runUndismiss(options) {
36
37
  validateGitHubUrl(options.url, ISSUE_URL_PATTERN, 'issue');
37
38
  const stateManager = getStateManager();
38
39
  const removed = stateManager.undismissIssue(options.url);
39
- const gistSyncWarning = await maybeCheckpoint(stateManager, MODULE);
40
+ const gistSyncWarning = await maybeCheckpoint(stateManager, MODULE, () => stateManager.undismissIssue(options.url));
40
41
  return { undismissed: removed, url: options.url, ...(gistSyncWarning && { gistSyncWarning }) };
41
42
  }
@@ -73,7 +73,7 @@ export async function runGuidelinesStore(options) {
73
73
  // Push to Gist — autoSave only writes the local state-cache mirror in Gist
74
74
  // mode, so without this checkpoint the change never propagates across
75
75
  // machines (#1200).
76
- const gistSyncWarning = await maybeCheckpoint(sm, MODULE);
76
+ const gistSyncWarning = await maybeCheckpoint(sm, MODULE, () => sm.setGuidelines(options.repo, options.content));
77
77
  return {
78
78
  repo: options.repo,
79
79
  byteSize: Buffer.byteLength(options.content, 'utf8'),
@@ -93,14 +93,18 @@ export async function runMarkExtracted(options) {
93
93
  const sm = getStateManager();
94
94
  const repoUrlPrefix = `https://github.com/${options.repo}/`;
95
95
  const now = new Date().toISOString();
96
- let marked = 0;
97
- for (const pr of [...(sm.getMergedPRs() ?? []), ...(sm.getClosedPRs() ?? [])]) {
98
- if (!pr.url.startsWith(repoUrlPrefix) || !pr.commentsFetchedAt || pr.learningsExtractedAt)
99
- continue;
100
- sm.markPRLearningsExtracted(pr.url, now);
101
- marked++;
102
- }
103
- const gistSyncWarning = marked > 0 ? await maybeCheckpoint(sm, MODULE) : null;
96
+ const mark = () => {
97
+ let n = 0;
98
+ for (const pr of [...(sm.getMergedPRs() ?? []), ...(sm.getClosedPRs() ?? [])]) {
99
+ if (!pr.url.startsWith(repoUrlPrefix) || !pr.commentsFetchedAt || pr.learningsExtractedAt)
100
+ continue;
101
+ sm.markPRLearningsExtracted(pr.url, now);
102
+ n++;
103
+ }
104
+ return n;
105
+ };
106
+ const marked = mark();
107
+ const gistSyncWarning = marked > 0 ? await maybeCheckpoint(sm, MODULE, mark) : null;
104
108
  return { repo: options.repo, marked, ...(gistSyncWarning && { gistSyncWarning }) };
105
109
  }
106
110
  /** Tombstone the guidelines file for `repo`. */
@@ -115,7 +119,7 @@ export async function runGuidelinesReset(options) {
115
119
  if (existed) {
116
120
  sm.deleteGuidelines(options.repo);
117
121
  // Push to Gist — see runGuidelinesStore note (#1200).
118
- gistSyncWarning = await maybeCheckpoint(sm, MODULE);
122
+ gistSyncWarning = await maybeCheckpoint(sm, MODULE, () => sm.deleteGuidelines(options.repo));
119
123
  }
120
124
  return { repo: options.repo, deleted: existed, ...(gistSyncWarning && { gistSyncWarning }) };
121
125
  }
@@ -180,15 +184,18 @@ export async function runFetchCorpus(options) {
180
184
  // list mirrors the input order until paginateAll fan-out, so we mark on
181
185
  // a per-bundle basis to be safe.
182
186
  const now = new Date().toISOString();
183
- for (const bundle of bundles) {
184
- sm.markPRCommentsFetched(bundle.prUrl, now);
185
- }
187
+ const stamp = () => {
188
+ for (const bundle of bundles) {
189
+ sm.markPRCommentsFetched(bundle.prUrl, now);
190
+ }
191
+ };
192
+ stamp();
186
193
  // Push commentsFetchedAt stamps to Gist so other machines don't re-fetch
187
194
  // the same PRs forever. autoSave only writes the local mirror in Gist
188
195
  // mode (#1200).
189
196
  let gistSyncWarning = null;
190
197
  if (bundles.length > 0) {
191
- gistSyncWarning = await maybeCheckpoint(sm, MODULE);
198
+ gistSyncWarning = await maybeCheckpoint(sm, MODULE, stamp);
192
199
  }
193
200
  // Surface pagination truncation per bundle (#1456): a truncated bundle is
194
201
  // missing its newest comments, so the host should know the corpus for that
@@ -17,11 +17,12 @@ export async function runInit(options) {
17
17
  validateGitHubUsername(options.username);
18
18
  const stateManager = getStateManager();
19
19
  // Set username in config
20
- stateManager.updateConfig({ githubUsername: options.username });
20
+ const apply = () => stateManager.updateConfig({ githubUsername: options.username });
21
+ apply();
21
22
  // Push the config mutation to the Gist in gist mode (no-op locally).
22
23
  // Without this the change only hits the local cache and the next
23
24
  // bootstrap reverts it from the Gist (#1440).
24
- const gistSyncWarning = await maybeCheckpoint(stateManager, MODULE);
25
+ const gistSyncWarning = await maybeCheckpoint(stateManager, MODULE, apply);
25
26
  return {
26
27
  username: options.username,
27
28
  message: 'Username saved. Run `daily` to fetch your open PRs from GitHub.',
@@ -288,7 +288,7 @@ export async function runLedgerBackfill(options = {}) {
288
288
  ...(node && { backfilledAt: now }),
289
289
  };
290
290
  };
291
- stateManager.batch(() => {
291
+ const applyLedger = () => {
292
292
  stateManager.addMergedPRs(merged.map((e) => ({ url: e.url, title: e.title, mergedAt: e.mergedAt, ...recovered(e) })));
293
293
  stateManager.addClosedPRs(closed.map((e) => {
294
294
  const node = nodes.get(e.url);
@@ -309,9 +309,10 @@ export async function runLedgerBackfill(options = {}) {
309
309
  // Overwrite, not fill-missing: a value recorded under an older rule is replaced.
310
310
  for (const [url, at] of responses)
311
311
  stateManager.setLedgerResponse(url, at, MAINTAINER_RESPONSE_RULE);
312
- });
312
+ };
313
+ stateManager.batch(applyLedger);
313
314
  const after = countFilled([...stateManager.getMergedPRs(), ...stateManager.getClosedPRs()]);
314
- const gistSyncWarning = await maybeCheckpoint(stateManager, 'ledger-backfill');
315
+ const gistSyncWarning = await maybeCheckpoint(stateManager, 'ledger-backfill', () => stateManager.batch(applyLedger));
315
316
  if (fatal)
316
317
  throw fatal;
317
318
  return {
@@ -36,19 +36,21 @@ export async function runMove(options) {
36
36
  // Use current time — the CLI doesn't have cached PR data. The override
37
37
  // will auto-clear on the next daily run if the PR has new activity after this.
38
38
  const lastActivityAt = new Date().toISOString();
39
- stateManager.batch(() => {
39
+ const apply = () => stateManager.batch(() => {
40
40
  stateManager.setStatusOverride(options.prUrl, status, lastActivityAt);
41
41
  stateManager.unshelvePR(options.prUrl);
42
42
  });
43
- const gistSyncWarning = await maybeCheckpoint(stateManager, MODULE);
43
+ apply();
44
+ const gistSyncWarning = await maybeCheckpoint(stateManager, MODULE, apply);
44
45
  return withGistSyncWarning({ url: options.prUrl, target, description: `Moved to ${label}` }, gistSyncWarning);
45
46
  }
46
47
  case 'shelved': {
47
- stateManager.batch(() => {
48
+ const apply = () => stateManager.batch(() => {
48
49
  stateManager.shelvePR(options.prUrl);
49
50
  stateManager.clearStatusOverride(options.prUrl);
50
51
  });
51
- const gistSyncWarning = await maybeCheckpoint(stateManager, MODULE);
52
+ apply();
53
+ const gistSyncWarning = await maybeCheckpoint(stateManager, MODULE, apply);
52
54
  return withGistSyncWarning({
53
55
  url: options.prUrl,
54
56
  target,
@@ -56,11 +58,12 @@ export async function runMove(options) {
56
58
  }, gistSyncWarning);
57
59
  }
58
60
  case 'auto': {
59
- stateManager.batch(() => {
61
+ const apply = () => stateManager.batch(() => {
60
62
  stateManager.clearStatusOverride(options.prUrl);
61
63
  stateManager.unshelvePR(options.prUrl);
62
64
  });
63
- const gistSyncWarning = await maybeCheckpoint(stateManager, MODULE);
65
+ apply();
66
+ const gistSyncWarning = await maybeCheckpoint(stateManager, MODULE, apply);
64
67
  return withGistSyncWarning({
65
68
  url: options.prUrl,
66
69
  target,
@@ -348,7 +348,10 @@ export async function runOvernightPushPrep(options) {
348
348
  async function persist() {
349
349
  if (options.dryRun)
350
350
  return;
351
- sm.setLastOvernight({ ...lastRun, prepared });
351
+ // Live record, not the `lastRun` snapshot: the re-apply below may run
352
+ // after a Gist refresh replaced it.
353
+ const record = () => sm.setLastOvernight({ ...(sm.getLastOvernight() ?? lastRun), prepared });
354
+ record();
352
355
  try {
353
356
  reportRecreated = writePreparedSection(lastRun.reportPath, prepared).reportRecreated;
354
357
  }
@@ -362,7 +365,7 @@ export async function runOvernightPushPrep(options) {
362
365
  // mistaken for a failed report write.
363
366
  if (!reportWarning)
364
367
  publishReport(sm, lastRun.reportPath);
365
- gistSyncWarning = await maybeCheckpoint(sm, MODULE);
368
+ gistSyncWarning = await maybeCheckpoint(sm, MODULE, record);
366
369
  }
367
370
  try {
368
371
  for (const [i, entry] of last.prepared.entries()) {
@@ -252,7 +252,7 @@ export async function runOvernight() {
252
252
  }
253
253
  // executeDailyCheck already checkpointed the Gist; this write came after it,
254
254
  // and in Gist mode setLastOvernight only reaches the local cache (#1629 class).
255
- const gistSyncWarning = await maybeCheckpoint(sm, MODULE);
255
+ const gistSyncWarning = await maybeCheckpoint(sm, MODULE, () => sm.setLastOvernight(record));
256
256
  return {
257
257
  ...body,
258
258
  reportPath,
@@ -303,16 +303,28 @@ export async function runOvernightImplementBlocked(options) {
303
303
  throw new Error(`${options.url} is not tonight's implement item (${last.implementUrl ?? 'none queued'})`);
304
304
  }
305
305
  const note = options.note ?? (options.fromReport ? readPreparerReport(options.fromReport).note : undefined);
306
- const implementAttempts = [
307
- ...(last.implementAttempts ?? []),
308
- { url: options.url, attemptedAt: new Date().toISOString(), outcome: 'blocked', note },
309
- ];
310
- sm.setLastOvernight({ ...last, implementAttempts });
306
+ const attempt = { url: options.url, attemptedAt: new Date().toISOString(), outcome: 'blocked', note };
307
+ // Reads the live record each time so a re-apply after a Gist refresh lands
308
+ // on the refreshed copy, not on the `last` captured above; idempotent.
309
+ const apply = () => {
310
+ const base = sm.getLastOvernight() ?? last;
311
+ const attempts = base.implementAttempts ?? [];
312
+ const record = attempts.some((a) => a.attemptedAt === attempt.attemptedAt)
313
+ ? base
314
+ : { ...base, implementAttempts: [...attempts, attempt] };
315
+ sm.setLastOvernight(record);
316
+ return record;
317
+ };
318
+ const record = apply();
311
319
  const dropDir = handoffDir();
312
320
  if (dropDir)
313
- exportHandoff(dropDir, { ...last, implementAttempts });
314
- const gistSyncWarning = await maybeCheckpoint(sm, MODULE);
315
- return { url: options.url, attemptCount: implementAttempts.length, ...(gistSyncWarning && { gistSyncWarning }) };
321
+ exportHandoff(dropDir, record);
322
+ const gistSyncWarning = await maybeCheckpoint(sm, MODULE, apply);
323
+ return {
324
+ url: options.url,
325
+ attemptCount: record.implementAttempts?.length ?? 0,
326
+ ...(gistSyncWarning && { gistSyncWarning }),
327
+ };
316
328
  }
317
329
  /** Append one prepared branch to state and to the report of the latest run. */
318
330
  export async function runOvernightRecord(options) {
@@ -342,21 +354,34 @@ export async function runOvernightRecord(options) {
342
354
  throw new ValidationError('No worktree to bundle: pass --worktree, or a report with WORKTREE:.');
343
355
  writeHandoffBundle(dropDir, entry.worktree, branch);
344
356
  }
345
- const prepared = [...last.prepared, entry];
346
- // Recording the branch for tonight's list issue is what marks the attempt
347
- // as prepared, so the next run moves on to the next Pursue item.
348
- const implementAttempts = options.url === last.implementUrl
349
- ? [
350
- ...(last.implementAttempts ?? []),
351
- { url: options.url, attemptedAt: entry.recordedAt, outcome: 'prepared' },
352
- ]
353
- : last.implementAttempts;
354
- sm.setLastOvernight({ ...last, prepared, implementAttempts });
355
- const { reportRecreated } = writePreparedSection(last.reportPath, prepared);
356
- publishReport(sm, last.reportPath);
357
+ // Reads the live record each time so a re-apply after a Gist refresh lands
358
+ // on the refreshed copy, not on the `last` captured above; idempotent.
359
+ const apply = () => {
360
+ const base = sm.getLastOvernight() ?? last;
361
+ if (base.prepared.some((p) => p.branch === entry.branch)) {
362
+ sm.setLastOvernight(base);
363
+ return base;
364
+ }
365
+ const prepared = [...base.prepared, entry];
366
+ // Recording the branch for tonight's list issue is what marks the attempt
367
+ // as prepared, so the next run moves on to the next Pursue item.
368
+ const implementAttempts = options.url === base.implementUrl
369
+ ? [
370
+ ...(base.implementAttempts ?? []),
371
+ { url: options.url, attemptedAt: entry.recordedAt, outcome: 'prepared' },
372
+ ]
373
+ : base.implementAttempts;
374
+ const record = { ...base, prepared, implementAttempts };
375
+ sm.setLastOvernight(record);
376
+ return record;
377
+ };
378
+ const record = apply();
379
+ const { prepared } = record;
380
+ const { reportRecreated } = writePreparedSection(record.reportPath, prepared);
381
+ publishReport(sm, record.reportPath);
357
382
  if (dropDir)
358
- exportHandoff(dropDir, { ...last, prepared, implementAttempts });
359
- const gistSyncWarning = await maybeCheckpoint(sm, MODULE);
383
+ exportHandoff(dropDir, record);
384
+ const gistSyncWarning = await maybeCheckpoint(sm, MODULE, apply);
360
385
  return {
361
386
  reportPath: last.reportPath,
362
387
  preparedCount: prepared.length,
@@ -192,15 +192,18 @@ export async function runSearch(options) {
192
192
  // hidden-but-surfaced issues also rotate out. Persists to AgentState.
193
193
  let gistSyncWarning = null;
194
194
  if (options.record !== false) {
195
- recordSearchSeen(stateManager, result.candidates.map((c) => c.issue.url));
196
- // Scout advanced its broad-phase language cursor in its own (provided,
197
- // non-persisted) state; copy it back so the next run starts from the next
198
- // language slice instead of offset 0 every time (#1630).
199
- stateManager.setSearchRotation(scout.getState().searchRotation);
195
+ const record = () => {
196
+ recordSearchSeen(stateManager, result.candidates.map((c) => c.issue.url));
197
+ // Scout advanced its broad-phase language cursor in its own (provided,
198
+ // non-persisted) state; copy it back so the next run starts from the next
199
+ // language slice instead of offset 0 every time (#1630).
200
+ stateManager.setSearchRotation(scout.getState().searchRotation);
201
+ };
202
+ record();
200
203
  // In Gist mode setSearchSeen only writes the local cache; without a
201
204
  // checkpoint the seen-set never reaches the Gist and the next startup's
202
205
  // Gist refetch overwrites the cache with the empty remote copy (#1629).
203
- gistSyncWarning = await maybeCheckpoint(stateManager, MODULE);
206
+ gistSyncWarning = await maybeCheckpoint(stateManager, MODULE, record);
204
207
  }
205
208
  // #1354: never surface issues the user already has an open PR for. Uses
206
209
  // scout's structured linked-PR metadata when present; candidates without it
@@ -54,7 +54,10 @@ export async function runSetup(options) {
54
54
  throw new ValidationError(formatUnknownKeyError(key, 'setup'));
55
55
  }
56
56
  }
57
- stateManager.batch(() => {
57
+ // Named so the Gist conflict path can re-apply the same settings on a
58
+ // refreshed baseline (maybeCheckpoint below).
59
+ const applySettings = () => {
60
+ warnings.length = 0;
58
61
  for (const setting of options.set) {
59
62
  const [key, ...valueParts] = setting.split('=');
60
63
  const value = valueParts.join('=');
@@ -368,11 +371,12 @@ export async function runSetup(options) {
368
371
  }
369
372
  }
370
373
  }
371
- });
374
+ };
375
+ stateManager.batch(applySettings);
372
376
  // Push the settings mutation to the Gist in gist mode (no-op locally).
373
377
  // Without this the change only hits the local cache and the next
374
378
  // bootstrap reverts it from the Gist (#1440).
375
- const gistSyncWarning = await maybeCheckpoint(stateManager, MODULE);
379
+ const gistSyncWarning = await maybeCheckpoint(stateManager, MODULE, () => stateManager.batch(applySettings));
376
380
  return {
377
381
  success: true,
378
382
  settings: results,
@@ -58,8 +58,30 @@ export function validateMessage(message) {
58
58
  if (message.length > MAX_MESSAGE_LENGTH) {
59
59
  throw new ValidationError(`Message exceeds maximum length of ${MAX_MESSAGE_LENGTH} characters`);
60
60
  }
61
+ // The no-AI-attribution rule (CLAUDE.md, skills/contribution-ethics) was
62
+ // prompt-level only; this is the one write boundary every post/claim
63
+ // crosses, so enforce it here (audit 2026-10-30 L1).
64
+ // Best-effort guard, not enforcement: the prompt-level rule stays the
65
+ // contract; this catches the common pasted shapes. Format characters are
66
+ // stripped so "C\u200Blaude" is seen, and fenced code blocks are ignored
67
+ // so a reply quoting the trailer it removed is not rejected.
68
+ const cleaned = message.replace(/\p{Cf}/gu, '').replace(/```[\s\S]*?```/g, '');
69
+ if (AI_ATTRIBUTION_PATTERNS.some((pattern) => pattern.test(cleaned))) {
70
+ throw new ValidationError('Message contains AI attribution (a Co-Authored-By / Claude-Session trailer or "Generated with Claude Code"); remove it');
71
+ }
61
72
  return message;
62
73
  }
74
+ /**
75
+ * Markers the contribution-ethics skill forbids in anything posted to GitHub:
76
+ * trailer lines and the "Generated/Made/Built with|by Claude Code" footer,
77
+ * both anchored to line start (leading indent allowed, so a pasted Git log
78
+ * still matches) so quoting or negating one mid-sentence is fine.
79
+ */
80
+ const AI_ATTRIBUTION_PATTERNS = [
81
+ /^[ \t]*co-authored-by:.*\b(?:claude|anthropic)\b/im,
82
+ /^[ \t]*claude-session:/im,
83
+ /^[ \t]*(?:\u{1F916} ?)?(?:generated|made|built) (?:with|by) [[*]*claude code\b/imu,
84
+ ];
63
85
  /**
64
86
  * Validate that a repository identifier matches the "owner/repo" format.
65
87
  * Returns the identifier if valid, throws if invalid.
@@ -133,7 +133,7 @@ export class GistConcurrencyError extends OssAutopilotError {
133
133
  remoteEtag;
134
134
  constructor(expectedEtag, remoteEtag) {
135
135
  super('Another machine pushed to the state Gist while this push was in flight, and the merge attempt also collided. ' +
136
- 'Re-run `oss-autopilot state --sync` to retry — your local mutations are still in memory.', 'CONCURRENCY_ERROR');
136
+ 'Your local mutations are still in memory, but `state --sync` cannot merge them: re-run the command that made the change.', 'CONCURRENCY_ERROR');
137
137
  this.expectedEtag = expectedEtag;
138
138
  this.remoteEtag = remoteEtag;
139
139
  this.name = 'GistConcurrencyError';
@@ -34,6 +34,15 @@ export interface EvalReport {
34
34
  highN: number;
35
35
  lowN: number;
36
36
  };
37
+ /**
38
+ * Merged and closed PRs that close an issue, and how many of them carry a
39
+ * vet-time grade. A low share means picks skipped `vet`, so calibration
40
+ * cannot be measured.
41
+ */
42
+ vetCoverage: {
43
+ graded: number;
44
+ of: number;
45
+ };
37
46
  /** Closures as ai-policy or rejected, per close month. */
38
47
  approachClosuresByMonth: Record<string, number>;
39
48
  };