@oss-autopilot/core 3.37.0 → 3.39.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 (78) hide show
  1. package/dist/cli-registry.js +7 -4
  2. package/dist/cli.bundle.cjs +134 -127
  3. package/dist/commands/comments.js +4 -3
  4. package/dist/commands/config.js +18 -11
  5. package/dist/commands/daily-dismiss-filter.d.ts +37 -0
  6. package/dist/commands/daily-dismiss-filter.js +80 -0
  7. package/dist/commands/daily-merged-pr-notes.d.ts +27 -0
  8. package/dist/commands/daily-merged-pr-notes.js +166 -0
  9. package/dist/commands/daily-reviewed-prs.d.ts +41 -0
  10. package/dist/commands/daily-reviewed-prs.js +270 -0
  11. package/dist/commands/daily-warnings.d.ts +28 -0
  12. package/dist/commands/daily-warnings.js +37 -0
  13. package/dist/commands/daily.d.ts +22 -1
  14. package/dist/commands/daily.js +299 -108
  15. package/dist/commands/dashboard-cache.js +9 -2
  16. package/dist/commands/dashboard-data.js +40 -20
  17. package/dist/commands/dashboard-gist-sync.d.ts +9 -1
  18. package/dist/commands/dashboard-gist-sync.js +24 -3
  19. package/dist/commands/dashboard-server.js +9 -5
  20. package/dist/commands/dismiss.d.ts +25 -5
  21. package/dist/commands/dismiss.js +40 -11
  22. package/dist/commands/guidelines.js +21 -14
  23. package/dist/commands/init.js +3 -2
  24. package/dist/commands/ledger-backfill.js +4 -3
  25. package/dist/commands/move.js +9 -6
  26. package/dist/commands/overnight-push-prep.js +5 -2
  27. package/dist/commands/overnight.js +62 -24
  28. package/dist/commands/scout-bridge.js +4 -1
  29. package/dist/commands/search.js +9 -6
  30. package/dist/commands/setup.js +7 -3
  31. package/dist/commands/validation.d.ts +11 -0
  32. package/dist/commands/validation.js +38 -0
  33. package/dist/core/checklist-analysis.js +34 -0
  34. package/dist/core/closed-pr-status.d.ts +73 -0
  35. package/dist/core/closed-pr-status.js +113 -0
  36. package/dist/core/comment-decision.d.ts +10 -3
  37. package/dist/core/comment-decision.js +13 -5
  38. package/dist/core/comment-utils.d.ts +38 -1
  39. package/dist/core/comment-utils.js +124 -1
  40. package/dist/core/concurrency.d.ts +6 -0
  41. package/dist/core/concurrency.js +13 -0
  42. package/dist/core/daily-logic.d.ts +13 -1
  43. package/dist/core/daily-logic.js +59 -2
  44. package/dist/core/engaged-issues.d.ts +93 -0
  45. package/dist/core/engaged-issues.js +183 -0
  46. package/dist/core/errors.d.ts +4 -0
  47. package/dist/core/errors.js +11 -1
  48. package/dist/core/eval-report.d.ts +9 -0
  49. package/dist/core/eval-report.js +4 -0
  50. package/dist/core/gist-state-store.d.ts +5 -2
  51. package/dist/core/gist-state-store.js +7 -4
  52. package/dist/core/github-stats.d.ts +10 -0
  53. package/dist/core/github-stats.js +35 -0
  54. package/dist/core/index.d.ts +10 -5
  55. package/dist/core/index.js +9 -4
  56. package/dist/core/issue-conversation.d.ts +83 -12
  57. package/dist/core/issue-conversation.js +306 -118
  58. package/dist/core/merged-pr-notes.d.ts +192 -0
  59. package/dist/core/merged-pr-notes.js +340 -0
  60. package/dist/core/pick-snapshot.js +1 -1
  61. package/dist/core/pr-assembly.js +3 -0
  62. package/dist/core/pr-monitor.d.ts +62 -0
  63. package/dist/core/pr-monitor.js +113 -3
  64. package/dist/core/reviewed-prs-fetch.d.ts +91 -0
  65. package/dist/core/reviewed-prs-fetch.js +271 -0
  66. package/dist/core/reviewed-prs.d.ts +244 -0
  67. package/dist/core/reviewed-prs.js +380 -0
  68. package/dist/core/state-persistence.js +8 -24
  69. package/dist/core/state-schema.d.ts +6 -0
  70. package/dist/core/state-schema.js +9 -0
  71. package/dist/core/state.d.ts +106 -11
  72. package/dist/core/state.js +246 -24
  73. package/dist/core/types.d.ts +47 -0
  74. package/dist/core/urls.d.ts +13 -0
  75. package/dist/core/urls.js +16 -0
  76. package/dist/formatters/json.d.ts +186 -1
  77. package/dist/formatters/json.js +78 -0
  78. package/package.json +1 -1
@@ -342,6 +342,7 @@ export declare const AgentConfigSchema: z.ZodPipe<z.ZodObject<{
342
342
  aiPolicyBlocklist: z.ZodDefault<z.ZodArray<z.ZodString>>;
343
343
  shelvedPRUrls: z.ZodDefault<z.ZodArray<z.ZodString>>;
344
344
  dismissedIssues: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodString>>;
345
+ dismissedPRHeads: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodString>>;
345
346
  statusOverrides: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
346
347
  status: z.ZodEnum<{
347
348
  needs_addressing: "needs_addressing";
@@ -402,6 +403,7 @@ export declare const AgentConfigSchema: z.ZodPipe<z.ZodObject<{
402
403
  aiPolicyBlocklist: string[];
403
404
  shelvedPRUrls: string[];
404
405
  dismissedIssues: Record<string, string>;
406
+ dismissedPRHeads: Record<string, string>;
405
407
  projectCategories: ("nonprofit" | "devtools" | "infrastructure" | "web-frameworks" | "data-ml" | "education")[];
406
408
  preferredOrgs: string[];
407
409
  diffTool: "inline" | "custom" | "sourcetree" | "vscode";
@@ -452,6 +454,7 @@ export declare const AgentConfigSchema: z.ZodPipe<z.ZodObject<{
452
454
  aiPolicyBlocklist: string[];
453
455
  shelvedPRUrls: string[];
454
456
  dismissedIssues: Record<string, string>;
457
+ dismissedPRHeads: Record<string, string>;
455
458
  projectCategories: ("nonprofit" | "devtools" | "infrastructure" | "web-frameworks" | "data-ml" | "education")[];
456
459
  preferredOrgs: string[];
457
460
  diffTool: "inline" | "custom" | "sourcetree" | "vscode";
@@ -736,6 +739,7 @@ export declare const AgentStateSchema: z.ZodObject<{
736
739
  aiPolicyBlocklist: z.ZodDefault<z.ZodArray<z.ZodString>>;
737
740
  shelvedPRUrls: z.ZodDefault<z.ZodArray<z.ZodString>>;
738
741
  dismissedIssues: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodString>>;
742
+ dismissedPRHeads: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodString>>;
739
743
  statusOverrides: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
740
744
  status: z.ZodEnum<{
741
745
  needs_addressing: "needs_addressing";
@@ -796,6 +800,7 @@ export declare const AgentStateSchema: z.ZodObject<{
796
800
  aiPolicyBlocklist: string[];
797
801
  shelvedPRUrls: string[];
798
802
  dismissedIssues: Record<string, string>;
803
+ dismissedPRHeads: Record<string, string>;
799
804
  projectCategories: ("nonprofit" | "devtools" | "infrastructure" | "web-frameworks" | "data-ml" | "education")[];
800
805
  preferredOrgs: string[];
801
806
  diffTool: "inline" | "custom" | "sourcetree" | "vscode";
@@ -846,6 +851,7 @@ export declare const AgentStateSchema: z.ZodObject<{
846
851
  aiPolicyBlocklist: string[];
847
852
  shelvedPRUrls: string[];
848
853
  dismissedIssues: Record<string, string>;
854
+ dismissedPRHeads: Record<string, string>;
849
855
  projectCategories: ("nonprofit" | "devtools" | "infrastructure" | "web-frameworks" | "data-ml" | "education")[];
850
856
  preferredOrgs: string[];
851
857
  diffTool: "inline" | "custom" | "sourcetree" | "vscode";
@@ -329,6 +329,15 @@ export const AgentConfigSchema = z
329
329
  aiPolicyBlocklist: z.array(z.string()).default(['matplotlib/matplotlib']),
330
330
  shelvedPRUrls: z.array(z.string()).default([]),
331
331
  dismissedIssues: z.record(z.string(), z.string()).default({}),
332
+ /**
333
+ * PR URL -> head SHA the PR had when its review follow-up was dismissed
334
+ * (#1857). Set by `dismiss <pr-url> --head <sha>`; the follow-up stays
335
+ * hidden while the head is unchanged and no comment newer than the
336
+ * dismiss stamp in `dismissedIssues` qualifies, and a different head
337
+ * resurfaces it. Cleared by `undismiss` and by a dismiss without `--head`
338
+ * (that one goes back to the stamp-only rule). Older states lack the key.
339
+ */
340
+ dismissedPRHeads: z.record(z.string(), z.string()).default({}),
332
341
  statusOverrides: z.record(z.string(), StatusOverrideSchema).optional(),
333
342
  issueListPath: z.string().optional(),
334
343
  skippedIssuesPath: z.string().optional(),
@@ -13,6 +13,12 @@ import { type GistHealth } from './gist-health.js';
13
13
  export { acquireLock, releaseLock, atomicWriteFileSync } from './state-persistence.js';
14
14
  export type { LoadRecoveryInfo } from './state-persistence.js';
15
15
  export type { Stats } from './repo-score-manager.js';
16
+ /**
17
+ * Outcome of {@link StateManager.releaseIssue} (#1863): the claim was
18
+ * removed, the issue was never tracked, or a claim recorded at/after the
19
+ * cutoff was deliberately kept.
20
+ */
21
+ export type ReleaseIssueResult = 'released' | 'not_tracked' | 'newer_claim';
16
22
  /** Cap on `state.pickSnapshots` (#1824): ~180 bytes each, so ~55 KB at the cap. */
17
23
  export declare const MAX_PICK_SNAPSHOTS = 300;
18
24
  /**
@@ -31,8 +37,12 @@ export declare const MAX_PICK_SNAPSHOTS = 300;
31
37
  * after its retry — previously that was discarded everywhere except
32
38
  * `state --sync`, so a failed cross-machine sync reported clean success
33
39
  * (#1370). stderr `warn()` alone is invisible to MCP/dashboard consumers.
40
+ *
41
+ * Pass `reapply` (the same mutation the caller just performed) to make a
42
+ * `GistConcurrencyError` recoverable: the state is force-refreshed from the
43
+ * Gist, `reapply` runs on the fresh baseline, and the push is retried once.
34
44
  */
35
- export declare function maybeCheckpoint(stateManager: StateManager, callerModule: string): Promise<string | null>;
45
+ export declare function maybeCheckpoint(stateManager: StateManager, callerModule: string, reapply?: () => void): Promise<string | null>;
36
46
  /**
37
47
  * Singleton manager for persistent agent state stored in ~/.oss-autopilot/state.json.
38
48
  *
@@ -68,6 +78,10 @@ export declare class StateManager {
68
78
  protected gistDegraded: boolean;
69
79
  private staleness;
70
80
  private lastSuccessfulRefreshAt;
81
+ private mutationDepth;
82
+ /** Gist mode: a mutation was saved since the last successful push. */
83
+ private unpushed;
84
+ private refreshCount;
71
85
  private loadRecovery;
72
86
  /**
73
87
  * Create a new StateManager instance.
@@ -193,11 +207,36 @@ export declare class StateManager {
193
207
  * fresh state because the main file was corrupt or invalid (#1371).
194
208
  */
195
209
  getLoadRecovery(): LoadRecoveryInfo | null;
210
+ /**
211
+ * Run `fn` as an in-flight mutation: non-forced `refreshFromGist()` calls
212
+ * are skipped until it settles so a concurrent refresh cannot swap
213
+ * `this.state` out from under it (audit 2026-10-30 M2).
214
+ *
215
+ * Deliberately a counter, not a serializing promise chain: parallel MCP
216
+ * tool bodies from one host message may depend on each other through the
217
+ * host, so queuing them would deadlock. The gap that leaves (a sibling's
218
+ * *forced* conflict-recovery refresh swaps the state object mid-body) is
219
+ * closed by `maybeCheckpoint` re-applying every mutation right before its
220
+ * push; bodies that cannot re-apply (`daily`) watch `refreshGeneration`.
221
+ */
222
+ runMutation<T>(fn: () => Promise<T>): Promise<T>;
223
+ /**
224
+ * Number of times a Gist refresh replaced the in-memory state. A successful
225
+ * push resolves earlier un-pushed changes only if this did not advance in
226
+ * between (the #1443 loss-notice invariant); a long run compares it to the
227
+ * value at its start to learn its mutations were swapped out.
228
+ */
229
+ get refreshGeneration(): number;
230
+ /** Gist mode: whether a saved mutation has not reached the Gist yet. */
231
+ hasUnpushedChanges(): boolean;
196
232
  /**
197
233
  * 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.
234
+ * Throttled to once per 30 seconds by GistStateStore unless `force` is set.
235
+ * Returns true if state was refreshed.
199
236
  */
200
- refreshFromGist(): Promise<boolean>;
237
+ refreshFromGist(options?: {
238
+ force?: boolean;
239
+ }): Promise<boolean>;
201
240
  /**
202
241
  * Returns a staleness marker when the in-memory state diverged from the
203
242
  * canonical Gist (refresh failure or degraded bootstrap), or `null` when
@@ -311,10 +350,44 @@ export declare class StateManager {
311
350
  */
312
351
  updateConfig(config: Partial<AgentState['config']>): void;
313
352
  /**
314
- * Track a new issue. No-op if the issue URL is already tracked.
353
+ * Track a new issue, or refresh the claim on one already tracked.
354
+ *
355
+ * Matching uses {@link issueRefKey} (same normalization as
356
+ * {@link releaseIssue}), so a re-claim through a differently cased or
357
+ * suffixed URL updates the existing entry instead of adding a duplicate.
358
+ * On a match only `status` and `updatedAt` are taken from `issue`:
359
+ * `updatedAt` is the claim stamp `releaseIssue` compares against the PR's
360
+ * close time (#1863), so a re-claim after the close must move it forward
361
+ * or the daily run would release the new claim as if it were the old one.
362
+ *
315
363
  * @param issue - The issue to track
316
364
  */
317
365
  addIssue(issue: TrackedIssue): void;
366
+ /**
367
+ * Release a claim: drop the issue from `activeIssues` (#1863). Called by
368
+ * the daily run when the user closed their own PR for the issue unmerged.
369
+ *
370
+ * What changes: the issue leaves the tracked set that
371
+ * `IssueConversationMonitor.fetchCommentedIssues` excludes, so from the
372
+ * next run it re-enters the commented-issue monitor like any other issue
373
+ * the user has commented on, and it stops reading as in progress wherever
374
+ * `activeIssues` is listed. Capacity is NOT affected: `assessCapacity`
375
+ * counts open PRs only, never tracked issues.
376
+ *
377
+ * Matching uses {@link issueRefKey} (case-insensitive owner/repo, trailing
378
+ * slash and fragment ignored), falling back to the exact string for a URL
379
+ * that does not parse. The removal cannot be undone, so with
380
+ * `claimedBefore` set the entry is kept when its `updatedAt` is at or after
381
+ * that instant: `updatedAt` is the claim stamp the `claim` command writes
382
+ * (`createdAt` there is the issue's GitHub creation date), so a claim made
383
+ * after the PR closed is a deliberate re-claim that must survive.
384
+ * Unparseable timestamps keep the entry for the same reason.
385
+ *
386
+ * @param issueUrl - URL of the issue to release
387
+ * @param claimedBefore - ISO instant (the PR's close time); only a claim
388
+ * recorded strictly before it is released
389
+ */
390
+ releaseIssue(issueUrl: string, claimedBefore?: string): ReleaseIssueResult;
318
391
  /**
319
392
  * Add a repository to the trusted projects list. No-op if already trusted.
320
393
  * @param repo - Repository in "owner/repo" format
@@ -355,14 +428,27 @@ export declare class StateManager {
355
428
  */
356
429
  isPRShelved(url: string): boolean;
357
430
  /**
358
- * Dismiss an issue's notifications. Auto-resurfaces on new activity.
359
- * @param url - The issue URL to dismiss
431
+ * Dismiss an issue's (or merged PR's, #1861) notifications. Auto-resurfaces
432
+ * on new activity.
433
+ * @param url - The issue or PR URL to dismiss
360
434
  * @param timestamp - ISO timestamp of dismissal
361
- * @returns true if newly dismissed, false if already dismissed
362
- */
363
- dismissIssue(url: string, timestamp: string): boolean;
364
- /**
365
- * Restore a dismissed issue to notifications.
435
+ * @param options.refresh - When set, an existing dismissal is re-stamped with
436
+ * `timestamp` instead of being left alone, so a second "skip" after newer
437
+ * activity moves the cutoff forward. Default keeps the original stamp.
438
+ * @param options.headSha - For a reviewed PR (#1857): the head SHA the PR
439
+ * had when it was dismissed, recorded in `config.dismissedPRHeads` so the
440
+ * follow-up stays hidden until the head moves. Any head recorded earlier
441
+ * is replaced, or dropped when this dismiss names none.
442
+ * @returns true if newly dismissed (or re-stamped under `refresh`), false if
443
+ * already dismissed
444
+ */
445
+ dismissIssue(url: string, timestamp: string, options?: {
446
+ refresh?: boolean;
447
+ headSha?: string;
448
+ }): boolean;
449
+ /**
450
+ * Restore a dismissed issue to notifications. A recorded dismiss head
451
+ * (#1857) goes with it.
366
452
  * @param url - The issue URL to undismiss
367
453
  * @returns true if undismissed, false if not currently dismissed
368
454
  */
@@ -372,6 +458,15 @@ export declare class StateManager {
372
458
  * @param url - The issue URL to check
373
459
  */
374
460
  getIssueDismissedAt(url: string): string | undefined;
461
+ /**
462
+ * The head SHA recorded when a reviewed PR's follow-up was dismissed
463
+ * (#1857), or undefined when the PR is not dismissed or was dismissed
464
+ * without one.
465
+ * @param url - The PR URL to check
466
+ */
467
+ getDismissedPRHead(url: string): string | undefined;
468
+ /** Record or (with `undefined`) drop the dismiss head for `url`; no save. */
469
+ private setDismissedPRHead;
375
470
  /**
376
471
  * Set a manual status override for a PR. Auto-clears when the PR has new activity.
377
472
  * @param url - The PR URL
@@ -9,14 +9,14 @@ 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). */
16
16
  export const OVERNIGHT_REPORT_DOCUMENT = 'overnight-report.md';
17
17
  import { renderGistWarning } from './gist-health.js';
18
18
  import { getStatePath, getStateCachePath, getGistIdPath } from './paths.js';
19
- import { parseGitHubUrl } from './urls.js';
19
+ import { parseGitHubUrl, issueRefKey } from './urls.js';
20
20
  export { acquireLock, releaseLock, atomicWriteFileSync } from './state-persistence.js';
21
21
  const MODULE = 'state';
22
22
  /**
@@ -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 }));
132
+ }
133
+ catch (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();
100
142
  }
101
143
  catch (err) {
102
- const msg = `Gist checkpoint failed (local mutation succeeded, will retry on next push): ${errorMessage(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
@@ -760,19 +891,77 @@ export class StateManager {
760
891
  }
761
892
  // === Issue Management ===
762
893
  /**
763
- * Track a new issue. No-op if the issue URL is already tracked.
894
+ * Track a new issue, or refresh the claim on one already tracked.
895
+ *
896
+ * Matching uses {@link issueRefKey} (same normalization as
897
+ * {@link releaseIssue}), so a re-claim through a differently cased or
898
+ * suffixed URL updates the existing entry instead of adding a duplicate.
899
+ * On a match only `status` and `updatedAt` are taken from `issue`:
900
+ * `updatedAt` is the claim stamp `releaseIssue` compares against the PR's
901
+ * close time (#1863), so a re-claim after the close must move it forward
902
+ * or the daily run would release the new claim as if it were the old one.
903
+ *
764
904
  * @param issue - The issue to track
765
905
  */
766
906
  addIssue(issue) {
767
- const existing = this.state.activeIssues.find((i) => i.url === issue.url);
907
+ const key = issueRefKey(issue.url);
908
+ const existing = this.state.activeIssues.find((i) => (key ? issueRefKey(i.url) === key : i.url === issue.url));
768
909
  if (existing) {
769
- debug(MODULE, `Issue ${issue.url} already tracked`);
910
+ existing.status = issue.status;
911
+ existing.updatedAt = issue.updatedAt;
912
+ debug(MODULE, `Issue ${issue.url} already tracked; refreshed claim stamp to ${issue.updatedAt}`);
913
+ this.autoSave();
770
914
  return;
771
915
  }
772
916
  this.state.activeIssues.push(issue);
773
917
  debug(MODULE, `Added issue: ${issue.repo}#${issue.number}`);
774
918
  this.autoSave();
775
919
  }
920
+ /**
921
+ * Release a claim: drop the issue from `activeIssues` (#1863). Called by
922
+ * the daily run when the user closed their own PR for the issue unmerged.
923
+ *
924
+ * What changes: the issue leaves the tracked set that
925
+ * `IssueConversationMonitor.fetchCommentedIssues` excludes, so from the
926
+ * next run it re-enters the commented-issue monitor like any other issue
927
+ * the user has commented on, and it stops reading as in progress wherever
928
+ * `activeIssues` is listed. Capacity is NOT affected: `assessCapacity`
929
+ * counts open PRs only, never tracked issues.
930
+ *
931
+ * Matching uses {@link issueRefKey} (case-insensitive owner/repo, trailing
932
+ * slash and fragment ignored), falling back to the exact string for a URL
933
+ * that does not parse. The removal cannot be undone, so with
934
+ * `claimedBefore` set the entry is kept when its `updatedAt` is at or after
935
+ * that instant: `updatedAt` is the claim stamp the `claim` command writes
936
+ * (`createdAt` there is the issue's GitHub creation date), so a claim made
937
+ * after the PR closed is a deliberate re-claim that must survive.
938
+ * Unparseable timestamps keep the entry for the same reason.
939
+ *
940
+ * @param issueUrl - URL of the issue to release
941
+ * @param claimedBefore - ISO instant (the PR's close time); only a claim
942
+ * recorded strictly before it is released
943
+ */
944
+ releaseIssue(issueUrl, claimedBefore) {
945
+ const key = issueRefKey(issueUrl);
946
+ const index = this.state.activeIssues.findIndex((i) => (key ? issueRefKey(i.url) === key : i.url === issueUrl));
947
+ if (index === -1) {
948
+ debug(MODULE, `releaseIssue: ${issueUrl} is not tracked; nothing to release`);
949
+ return 'not_tracked';
950
+ }
951
+ const entry = this.state.activeIssues[index];
952
+ if (claimedBefore !== undefined) {
953
+ const claimedMs = Date.parse(entry.updatedAt);
954
+ const cutoffMs = Date.parse(claimedBefore);
955
+ if (Number.isNaN(claimedMs) || Number.isNaN(cutoffMs) || claimedMs >= cutoffMs) {
956
+ debug(MODULE, `releaseIssue: keeping ${entry.repo}#${entry.number}; claim stamp ${entry.updatedAt} is not before ${claimedBefore}`);
957
+ return 'newer_claim';
958
+ }
959
+ }
960
+ this.state.activeIssues.splice(index, 1);
961
+ debug(MODULE, `Released issue claim: ${entry.repo}#${entry.number}`);
962
+ this.autoSave();
963
+ return 'released';
964
+ }
776
965
  // === Trusted Projects ===
777
966
  /**
778
967
  * Add a repository to the trusted projects list. No-op if already trusted.
@@ -878,24 +1067,35 @@ export class StateManager {
878
1067
  }
879
1068
  // === Dismiss / Undismiss Issues ===
880
1069
  /**
881
- * Dismiss an issue's notifications. Auto-resurfaces on new activity.
882
- * @param url - The issue URL to dismiss
1070
+ * Dismiss an issue's (or merged PR's, #1861) notifications. Auto-resurfaces
1071
+ * on new activity.
1072
+ * @param url - The issue or PR URL to dismiss
883
1073
  * @param timestamp - ISO timestamp of dismissal
884
- * @returns true if newly dismissed, false if already dismissed
1074
+ * @param options.refresh - When set, an existing dismissal is re-stamped with
1075
+ * `timestamp` instead of being left alone, so a second "skip" after newer
1076
+ * activity moves the cutoff forward. Default keeps the original stamp.
1077
+ * @param options.headSha - For a reviewed PR (#1857): the head SHA the PR
1078
+ * had when it was dismissed, recorded in `config.dismissedPRHeads` so the
1079
+ * follow-up stays hidden until the head moves. Any head recorded earlier
1080
+ * is replaced, or dropped when this dismiss names none.
1081
+ * @returns true if newly dismissed (or re-stamped under `refresh`), false if
1082
+ * already dismissed
885
1083
  */
886
- dismissIssue(url, timestamp) {
1084
+ dismissIssue(url, timestamp, options = {}) {
887
1085
  if (!this.state.config.dismissedIssues) {
888
1086
  this.state.config.dismissedIssues = {};
889
1087
  }
890
- if (url in this.state.config.dismissedIssues) {
1088
+ if (url in this.state.config.dismissedIssues && !options.refresh) {
891
1089
  return false;
892
1090
  }
893
1091
  this.state.config.dismissedIssues[url] = timestamp;
1092
+ this.setDismissedPRHead(url, options.headSha);
894
1093
  this.autoSave();
895
1094
  return true;
896
1095
  }
897
1096
  /**
898
- * Restore a dismissed issue to notifications.
1097
+ * Restore a dismissed issue to notifications. A recorded dismiss head
1098
+ * (#1857) goes with it.
899
1099
  * @param url - The issue URL to undismiss
900
1100
  * @returns true if undismissed, false if not currently dismissed
901
1101
  */
@@ -904,6 +1104,7 @@ export class StateManager {
904
1104
  return false;
905
1105
  }
906
1106
  delete this.state.config.dismissedIssues[url];
1107
+ this.setDismissedPRHead(url, undefined);
907
1108
  this.autoSave();
908
1109
  return true;
909
1110
  }
@@ -914,6 +1115,27 @@ export class StateManager {
914
1115
  getIssueDismissedAt(url) {
915
1116
  return this.state.config.dismissedIssues?.[url];
916
1117
  }
1118
+ /**
1119
+ * The head SHA recorded when a reviewed PR's follow-up was dismissed
1120
+ * (#1857), or undefined when the PR is not dismissed or was dismissed
1121
+ * without one.
1122
+ * @param url - The PR URL to check
1123
+ */
1124
+ getDismissedPRHead(url) {
1125
+ return this.state.config.dismissedPRHeads?.[url];
1126
+ }
1127
+ /** Record or (with `undefined`) drop the dismiss head for `url`; no save. */
1128
+ setDismissedPRHead(url, headSha) {
1129
+ if (!this.state.config.dismissedPRHeads) {
1130
+ this.state.config.dismissedPRHeads = {};
1131
+ }
1132
+ if (headSha === undefined) {
1133
+ delete this.state.config.dismissedPRHeads[url];
1134
+ }
1135
+ else {
1136
+ this.state.config.dismissedPRHeads[url] = headSha;
1137
+ }
1138
+ }
917
1139
  // === Status Overrides ===
918
1140
  /**
919
1141
  * Set a manual status override for a PR. Auto-clears when the PR has new activity.