@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
@@ -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;
@@ -37,6 +39,10 @@ export declare class GistSyncCoordinator {
37
39
  /** Push-before-pull (#1417): an un-pushed mutation would be silently
38
40
  * reverted by the next Gist pull. Retry the checkpoint first so a recovered
39
41
  * network turns the pending warning into a real push before any pull runs.
42
+ * Also pushes saves that never recorded a warning: fetchDashboardData
43
+ * writes the digest and merged/closed caches through save() with no
44
+ * checkpoint, and the pull right after it reverted them and raised the
45
+ * "un-pushed changes" stale banner on every refresh.
40
46
  * No-op when nothing is pending. */
41
47
  flushPendingGistSync(): Promise<void>;
42
48
  /** One health snapshot from the one source (#1444). Defensive: this is an
@@ -66,7 +72,9 @@ export declare class GistSyncCoordinator {
66
72
  * notice when the pull actually replaced state (#1443). All dashboard pull
67
73
  * sites go through here; callers flush pending pushes first (#1417), so a
68
74
  * warning that is still pending at pull time means the flush failed. */
69
- pullFromGist(): Promise<boolean>;
75
+ pullFromGist(options?: {
76
+ force?: boolean;
77
+ }): Promise<boolean>;
70
78
  /** Re-attempt gist init while degraded (#1433). The serve process used to
71
79
  * bootstrap exactly once at CLI preAction — with its stderr discarded by
72
80
  * 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
  }
@@ -100,9 +110,13 @@ export class GistSyncCoordinator {
100
110
  /** Push-before-pull (#1417): an un-pushed mutation would be silently
101
111
  * reverted by the next Gist pull. Retry the checkpoint first so a recovered
102
112
  * network turns the pending warning into a real push before any pull runs.
113
+ * Also pushes saves that never recorded a warning: fetchDashboardData
114
+ * writes the digest and merged/closed caches through save() with no
115
+ * checkpoint, and the pull right after it reverted them and raised the
116
+ * "un-pushed changes" stale banner on every refresh.
103
117
  * No-op when nothing is pending. */
104
118
  async flushPendingGistSync() {
105
- if (this.pendingGistSyncWarnings.length === 0)
119
+ if (this.pendingGistSyncWarnings.length === 0 && !this.manager.hasUnpushedChanges())
106
120
  return;
107
121
  this.recordGistSyncOutcome(await maybeCheckpoint(this.manager, this.module));
108
122
  }
@@ -153,8 +167,8 @@ export class GistSyncCoordinator {
153
167
  * notice when the pull actually replaced state (#1443). All dashboard pull
154
168
  * sites go through here; callers flush pending pushes first (#1417), so a
155
169
  * warning that is still pending at pull time means the flush failed. */
156
- async pullFromGist() {
157
- const refreshed = await this.manager.refreshFromGist();
170
+ async pullFromGist(options = {}) {
171
+ const refreshed = await this.manager.refreshFromGist(options);
158
172
  if (refreshed)
159
173
  this.convertPendingWarningsToLossNotices();
160
174
  return refreshed;
@@ -189,7 +203,14 @@ export class GistSyncCoordinator {
189
203
  try {
190
204
  await ensureGistPersistence(currentToken);
191
205
  // The upgrade replaced the core singleton — re-resolve our reference.
206
+ const previous = this.manager;
192
207
  this.manager = getStateManager();
208
+ // A swapped manager starts its own refreshGeneration; re-anchor any
209
+ // still-pending warnings to it so the next successful push is not
210
+ // misread as a loss (or a loss missed) against the old counter.
211
+ if (this.manager !== previous && this.pendingGistSyncWarnings.length > 0) {
212
+ this.pendingSince = this.manager.refreshGeneration;
213
+ }
193
214
  // Genuinely armed only: a retry can resolve via ANOTHER degraded
194
215
  // bootstrap (gist-backed, store disarmed) — that is not a recovery
195
216
  // 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)) {
@@ -2,6 +2,14 @@
2
2
  * Dismiss/Undismiss commands
3
3
  * Manages dismissing issue notifications without posting a comment.
4
4
  * Dismissed URLs resurface automatically when new responses arrive after the dismiss timestamp.
5
+ *
6
+ * PR URLs are accepted too: dismissing a merged PR's URL declines the
7
+ * "merged PR with maintainer notes" nudge (#1861), and dismissing a PR the
8
+ * user reviewed declines its review follow-up (#1857), for the activity
9
+ * posted so far, with the same stamp-based resurfacing when newer activity
10
+ * lands. A review follow-up dismissed with `--head <sha>` also records the
11
+ * PR's head, so a push (new head) brings it back while bot, label and
12
+ * bystander updates do not; see `daily-reviewed-prs.ts`.
5
13
  */
6
14
  export interface DismissOutput {
7
15
  dismissed: boolean;
@@ -19,21 +27,33 @@ export interface UndismissOutput {
19
27
  * Dismiss an issue's reply notifications without posting a comment.
20
28
  * The dismissal auto-resurfaces when new responses arrive after the dismiss timestamp.
21
29
  *
30
+ * A PR URL is always re-stamped: the merged-PR notes and review follow-up
31
+ * phases compare the stamp with the newest activity, so a second "skip" after
32
+ * newer activity has to move the stamp forward or it would be a no-op. Issue dismissals keep their first
33
+ * stamp (the issue path auto-undismisses on new activity instead).
34
+ *
22
35
  * @param options - Dismiss options
23
- * @param options.url - Full GitHub issue URL
24
- * @returns Whether the issue was newly dismissed (false if already dismissed)
25
- * @throws {ValidationError} If the URL is not a valid GitHub issue URL
36
+ * @param options.url - Full GitHub issue or PR URL
37
+ * @param options.head - For a PR URL: the PR's full head SHA at dismiss time
38
+ * (the review follow-up entry's `headSha`). Recorded so the follow-up stays
39
+ * hidden until the head moves or someone comments after the dismiss.
40
+ * Without it, only the stamp decides, and any update to the PR can resurface it.
41
+ * @returns Whether the issue was newly dismissed (false if already dismissed);
42
+ * always true for a PR URL
43
+ * @throws {ValidationError} If the URL is not a valid GitHub issue or PR URL,
44
+ * if `head` is not a full 40-hex SHA, or if `head` is given with an issue URL
26
45
  */
27
46
  export declare function runDismiss(options: {
28
47
  url: string;
48
+ head?: string;
29
49
  }): Promise<DismissOutput>;
30
50
  /**
31
51
  * Restore a dismissed issue to notifications.
32
52
  *
33
53
  * @param options - Undismiss options
34
- * @param options.url - Full GitHub issue URL
54
+ * @param options.url - Full GitHub issue or PR URL
35
55
  * @returns Whether the issue was undismissed (false if not currently dismissed)
36
- * @throws {ValidationError} If the URL is not a valid GitHub issue URL
56
+ * @throws {ValidationError} If the URL is not a valid GitHub issue or PR URL
37
57
  */
38
58
  export declare function runUndismiss(options: {
39
59
  url: string;
@@ -2,40 +2,69 @@
2
2
  * Dismiss/Undismiss commands
3
3
  * Manages dismissing issue notifications without posting a comment.
4
4
  * Dismissed URLs resurface automatically when new responses arrive after the dismiss timestamp.
5
+ *
6
+ * PR URLs are accepted too: dismissing a merged PR's URL declines the
7
+ * "merged PR with maintainer notes" nudge (#1861), and dismissing a PR the
8
+ * user reviewed declines its review follow-up (#1857), for the activity
9
+ * posted so far, with the same stamp-based resurfacing when newer activity
10
+ * lands. A review follow-up dismissed with `--head <sha>` also records the
11
+ * PR's head, so a push (new head) brings it back while bot, label and
12
+ * bystander updates do not; see `daily-reviewed-prs.ts`.
5
13
  */
6
14
  import { getStateManager, maybeCheckpoint } from '../core/index.js';
7
- import { ISSUE_URL_PATTERN, validateGitHubUrl, validateUrl } from './validation.js';
15
+ import { ValidationError } from '../core/errors.js';
16
+ import { ISSUE_OR_PR_URL_PATTERN, PR_URL_PATTERN, validateCommitSha, validateGitHubUrl, validateUrl, } from './validation.js';
8
17
  const MODULE = 'dismiss';
9
18
  /**
10
19
  * Dismiss an issue's reply notifications without posting a comment.
11
20
  * The dismissal auto-resurfaces when new responses arrive after the dismiss timestamp.
12
21
  *
22
+ * A PR URL is always re-stamped: the merged-PR notes and review follow-up
23
+ * phases compare the stamp with the newest activity, so a second "skip" after
24
+ * newer activity has to move the stamp forward or it would be a no-op. Issue dismissals keep their first
25
+ * stamp (the issue path auto-undismisses on new activity instead).
26
+ *
13
27
  * @param options - Dismiss options
14
- * @param options.url - Full GitHub issue URL
15
- * @returns Whether the issue was newly dismissed (false if already dismissed)
16
- * @throws {ValidationError} If the URL is not a valid GitHub issue URL
28
+ * @param options.url - Full GitHub issue or PR URL
29
+ * @param options.head - For a PR URL: the PR's full head SHA at dismiss time
30
+ * (the review follow-up entry's `headSha`). Recorded so the follow-up stays
31
+ * hidden until the head moves or someone comments after the dismiss.
32
+ * Without it, only the stamp decides, and any update to the PR can resurface it.
33
+ * @returns Whether the issue was newly dismissed (false if already dismissed);
34
+ * always true for a PR URL
35
+ * @throws {ValidationError} If the URL is not a valid GitHub issue or PR URL,
36
+ * if `head` is not a full 40-hex SHA, or if `head` is given with an issue URL
17
37
  */
18
38
  export async function runDismiss(options) {
19
39
  validateUrl(options.url);
20
- validateGitHubUrl(options.url, ISSUE_URL_PATTERN, 'issue');
40
+ validateGitHubUrl(options.url, ISSUE_OR_PR_URL_PATTERN, 'issue or PR');
41
+ const isPR = PR_URL_PATTERN.test(options.url);
42
+ if (!isPR && options.head !== undefined) {
43
+ throw new ValidationError('--head applies to PR URLs only: a dismissed issue has no head commit');
44
+ }
21
45
  const stateManager = getStateManager();
22
- const added = stateManager.dismissIssue(options.url, new Date().toISOString());
23
- const gistSyncWarning = await maybeCheckpoint(stateManager, MODULE);
46
+ const dismissedAt = new Date().toISOString();
47
+ const dismissOptions = {
48
+ refresh: isPR,
49
+ ...(options.head !== undefined && { headSha: validateCommitSha(options.head) }),
50
+ };
51
+ const added = stateManager.dismissIssue(options.url, dismissedAt, dismissOptions);
52
+ const gistSyncWarning = await maybeCheckpoint(stateManager, MODULE, () => stateManager.dismissIssue(options.url, dismissedAt, dismissOptions));
24
53
  return { dismissed: added, url: options.url, ...(gistSyncWarning && { gistSyncWarning }) };
25
54
  }
26
55
  /**
27
56
  * Restore a dismissed issue to notifications.
28
57
  *
29
58
  * @param options - Undismiss options
30
- * @param options.url - Full GitHub issue URL
59
+ * @param options.url - Full GitHub issue or PR URL
31
60
  * @returns Whether the issue was undismissed (false if not currently dismissed)
32
- * @throws {ValidationError} If the URL is not a valid GitHub issue URL
61
+ * @throws {ValidationError} If the URL is not a valid GitHub issue or PR URL
33
62
  */
34
63
  export async function runUndismiss(options) {
35
64
  validateUrl(options.url);
36
- validateGitHubUrl(options.url, ISSUE_URL_PATTERN, 'issue');
65
+ validateGitHubUrl(options.url, ISSUE_OR_PR_URL_PATTERN, 'issue or PR');
37
66
  const stateManager = getStateManager();
38
67
  const removed = stateManager.undismissIssue(options.url);
39
- const gistSyncWarning = await maybeCheckpoint(stateManager, MODULE);
68
+ const gistSyncWarning = await maybeCheckpoint(stateManager, MODULE, () => stateManager.undismissIssue(options.url));
40
69
  return { undismissed: removed, url: options.url, ...(gistSyncWarning && { gistSyncWarning }) };
41
70
  }
@@ -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()) {
@@ -107,6 +107,19 @@ function loadListItems() {
107
107
  return null;
108
108
  }
109
109
  }
110
+ /** How the user is tied to the issue, by engagement reason (#1862). */
111
+ const ENGAGEMENT_LABEL = {
112
+ claim: 'claimed',
113
+ open_pr: 'have an open PR for',
114
+ closed_pr: 'had a PR on',
115
+ merged_pr: 'had a PR on',
116
+ };
117
+ /** Who replied, and whether the user is working on the issue (#1862) or only commented. */
118
+ function issueReplyReason(issue) {
119
+ const who = issue.isFromMaintainer ? 'a maintainer' : issue.lastResponseAuthor;
120
+ const where = issue.engagement ? ENGAGEMENT_LABEL[issue.engagement.reason] : 'commented on';
121
+ return `${who} replied on an issue you ${where}`;
122
+ }
110
123
  /** Pure: split the daily check into prepare vs judgment items. */
111
124
  export function bucketize(daily, languageOf = () => { }) {
112
125
  const prepare = [];
@@ -131,7 +144,7 @@ export function bucketize(daily, languageOf = () => { }) {
131
144
  url: c.url,
132
145
  type: 'issue_reply',
133
146
  label: `[Issue reply] ${c.repo}#${c.number}`,
134
- reason: `${c.isFromMaintainer ? 'a maintainer' : c.lastResponseAuthor} replied on an issue you commented on`,
147
+ reason: issueReplyReason(c),
135
148
  });
136
149
  }
137
150
  return { prepare, judgment };
@@ -252,7 +265,7 @@ export async function runOvernight() {
252
265
  }
253
266
  // executeDailyCheck already checkpointed the Gist; this write came after it,
254
267
  // and in Gist mode setLastOvernight only reaches the local cache (#1629 class).
255
- const gistSyncWarning = await maybeCheckpoint(sm, MODULE);
268
+ const gistSyncWarning = await maybeCheckpoint(sm, MODULE, () => sm.setLastOvernight(record));
256
269
  return {
257
270
  ...body,
258
271
  reportPath,
@@ -303,16 +316,28 @@ export async function runOvernightImplementBlocked(options) {
303
316
  throw new Error(`${options.url} is not tonight's implement item (${last.implementUrl ?? 'none queued'})`);
304
317
  }
305
318
  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 });
319
+ const attempt = { url: options.url, attemptedAt: new Date().toISOString(), outcome: 'blocked', note };
320
+ // Reads the live record each time so a re-apply after a Gist refresh lands
321
+ // on the refreshed copy, not on the `last` captured above; idempotent.
322
+ const apply = () => {
323
+ const base = sm.getLastOvernight() ?? last;
324
+ const attempts = base.implementAttempts ?? [];
325
+ const record = attempts.some((a) => a.attemptedAt === attempt.attemptedAt)
326
+ ? base
327
+ : { ...base, implementAttempts: [...attempts, attempt] };
328
+ sm.setLastOvernight(record);
329
+ return record;
330
+ };
331
+ const record = apply();
311
332
  const dropDir = handoffDir();
312
333
  if (dropDir)
313
- exportHandoff(dropDir, { ...last, implementAttempts });
314
- const gistSyncWarning = await maybeCheckpoint(sm, MODULE);
315
- return { url: options.url, attemptCount: implementAttempts.length, ...(gistSyncWarning && { gistSyncWarning }) };
334
+ exportHandoff(dropDir, record);
335
+ const gistSyncWarning = await maybeCheckpoint(sm, MODULE, apply);
336
+ return {
337
+ url: options.url,
338
+ attemptCount: record.implementAttempts?.length ?? 0,
339
+ ...(gistSyncWarning && { gistSyncWarning }),
340
+ };
316
341
  }
317
342
  /** Append one prepared branch to state and to the report of the latest run. */
318
343
  export async function runOvernightRecord(options) {
@@ -342,21 +367,34 @@ export async function runOvernightRecord(options) {
342
367
  throw new ValidationError('No worktree to bundle: pass --worktree, or a report with WORKTREE:.');
343
368
  writeHandoffBundle(dropDir, entry.worktree, branch);
344
369
  }
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);
370
+ // Reads the live record each time so a re-apply after a Gist refresh lands
371
+ // on the refreshed copy, not on the `last` captured above; idempotent.
372
+ const apply = () => {
373
+ const base = sm.getLastOvernight() ?? last;
374
+ if (base.prepared.some((p) => p.branch === entry.branch)) {
375
+ sm.setLastOvernight(base);
376
+ return base;
377
+ }
378
+ const prepared = [...base.prepared, entry];
379
+ // Recording the branch for tonight's list issue is what marks the attempt
380
+ // as prepared, so the next run moves on to the next Pursue item.
381
+ const implementAttempts = options.url === base.implementUrl
382
+ ? [
383
+ ...(base.implementAttempts ?? []),
384
+ { url: options.url, attemptedAt: entry.recordedAt, outcome: 'prepared' },
385
+ ]
386
+ : base.implementAttempts;
387
+ const record = { ...base, prepared, implementAttempts };
388
+ sm.setLastOvernight(record);
389
+ return record;
390
+ };
391
+ const record = apply();
392
+ const { prepared } = record;
393
+ const { reportRecreated } = writePreparedSection(record.reportPath, prepared);
394
+ publishReport(sm, record.reportPath);
357
395
  if (dropDir)
358
- exportHandoff(dropDir, { ...last, prepared, implementAttempts });
359
- const gistSyncWarning = await maybeCheckpoint(sm, MODULE);
396
+ exportHandoff(dropDir, record);
397
+ const gistSyncWarning = await maybeCheckpoint(sm, MODULE, apply);
360
398
  return {
361
399
  reportPath: last.reportPath,
362
400
  preparedCount: prepared.length,
@@ -8,6 +8,7 @@ import { getStateManager, isLinkedPRStalled, parseGitHubUrl, requireGitHubToken
8
8
  import { SearchRotationSchema } from '../core/state-schema.js';
9
9
  import { computeStrategy } from '../core/strategy.js';
10
10
  import { loadSkippedIssuesDetailed } from './skip-file-parser.js';
11
+ import { ISSUE_URL_PATTERN } from './validation.js';
11
12
  /**
12
13
  * Fraction of search slots reserved for candidates that matched neither
13
14
  * strategy-preferred languages nor repos (#1244). Counterweight against
@@ -95,10 +96,12 @@ export function buildScoutState(diagnostics) {
95
96
  // window lapsed. `undismiss` deletes the map entry, so only current
96
97
  // dismissals are merged. Scout filters by URL alone; repo/number are
97
98
  // best-effort from the URL and title is unknown, same as the skip file.
99
+ // The same map also holds dismissed merged-PR URLs (#1861); those are not
100
+ // issues scout could surface, so only `/issues/` URLs are forwarded.
98
101
  const skippedIssues = [...skippedIssuesLoad.issues];
99
102
  const skippedUrls = new Set(skippedIssues.map((s) => s.url));
100
103
  for (const [url, dismissedAt] of Object.entries(config.dismissedIssues ?? {})) {
101
- if (skippedUrls.has(url))
104
+ if (skippedUrls.has(url) || !ISSUE_URL_PATTERN.test(url))
102
105
  continue;
103
106
  const parsed = parseGitHubUrl(url);
104
107
  skippedIssues.push({
@@ -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