@oss-autopilot/core 3.42.4 → 3.43.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 (172) hide show
  1. package/dist/cli-pre-action.js +8 -3
  2. package/dist/cli-registry.js +272 -25
  3. package/dist/cli.bundle.cjs +183 -154
  4. package/dist/commands/check-integration.js +1 -0
  5. package/dist/commands/cleanup.d.ts +76 -0
  6. package/dist/commands/cleanup.js +269 -0
  7. package/dist/commands/comments.d.ts +6 -0
  8. package/dist/commands/comments.js +6 -2
  9. package/dist/commands/config.js +37 -5
  10. package/dist/commands/daily-dismiss-filter.d.ts +7 -0
  11. package/dist/commands/daily-dismiss-filter.js +17 -1
  12. package/dist/commands/daily-ledger.d.ts +122 -0
  13. package/dist/commands/daily-ledger.js +225 -0
  14. package/dist/commands/daily-recent-prs.d.ts +26 -0
  15. package/dist/commands/daily-recent-prs.js +55 -0
  16. package/dist/commands/daily.d.ts +2 -1
  17. package/dist/commands/daily.js +59 -89
  18. package/dist/commands/dashboard-cache.d.ts +2 -0
  19. package/dist/commands/dashboard-cache.js +33 -8
  20. package/dist/commands/dashboard-data.js +71 -36
  21. package/dist/commands/dashboard-gist-sync.js +3 -1
  22. package/dist/commands/dashboard-lifecycle.js +1 -1
  23. package/dist/commands/dashboard-process.d.ts +14 -1
  24. package/dist/commands/dashboard-process.js +46 -7
  25. package/dist/commands/dashboard-server.js +89 -23
  26. package/dist/commands/detect-formatters.js +1 -0
  27. package/dist/commands/dismiss.js +5 -2
  28. package/dist/commands/doctor.d.ts +15 -1
  29. package/dist/commands/doctor.js +73 -5
  30. package/dist/commands/draft.d.ts +77 -0
  31. package/dist/commands/draft.js +218 -0
  32. package/dist/commands/eval.js +1 -0
  33. package/dist/commands/guidelines.d.ts +23 -1
  34. package/dist/commands/guidelines.js +49 -4
  35. package/dist/commands/index.d.ts +24 -4
  36. package/dist/commands/index.js +15 -3
  37. package/dist/commands/issue-thread.d.ts +46 -0
  38. package/dist/commands/issue-thread.js +123 -0
  39. package/dist/commands/ledger-backfill.d.ts +9 -0
  40. package/dist/commands/ledger-backfill.js +44 -1
  41. package/dist/commands/list-mark-done.d.ts +2 -1
  42. package/dist/commands/list-mark-done.js +3 -1
  43. package/dist/commands/list-move-tier.d.ts +2 -1
  44. package/dist/commands/list-move-tier.js +3 -1
  45. package/dist/commands/local-repos.js +10 -5
  46. package/dist/commands/locate-issue-list.d.ts +40 -17
  47. package/dist/commands/locate-issue-list.js +148 -88
  48. package/dist/commands/move.js +7 -1
  49. package/dist/commands/overnight-handoff.d.ts +17 -7
  50. package/dist/commands/overnight-handoff.js +36 -14
  51. package/dist/commands/overnight-push-prep.d.ts +13 -8
  52. package/dist/commands/overnight-push-prep.js +106 -34
  53. package/dist/commands/overnight-tool-rules.d.ts +54 -0
  54. package/dist/commands/overnight-tool-rules.js +217 -0
  55. package/dist/commands/overnight.d.ts +5 -6
  56. package/dist/commands/overnight.js +61 -140
  57. package/dist/commands/parse-list.js +7 -1
  58. package/dist/commands/policy.d.ts +86 -0
  59. package/dist/commands/policy.js +263 -0
  60. package/dist/commands/pr-preflight.d.ts +43 -0
  61. package/dist/commands/pr-preflight.js +294 -0
  62. package/dist/commands/repo-vet.d.ts +9 -0
  63. package/dist/commands/repo-vet.js +36 -11
  64. package/dist/commands/scout-bridge.js +18 -8
  65. package/dist/commands/search.js +7 -0
  66. package/dist/commands/setup.d.ts +3 -3
  67. package/dist/commands/setup.js +46 -18
  68. package/dist/commands/skip-add.js +10 -1
  69. package/dist/commands/startup.d.ts +5 -3
  70. package/dist/commands/startup.js +65 -49
  71. package/dist/commands/state-cmd.d.ts +2 -0
  72. package/dist/commands/state-cmd.js +5 -1
  73. package/dist/commands/stats.js +1 -0
  74. package/dist/commands/status.js +1 -0
  75. package/dist/commands/strategy.js +1 -0
  76. package/dist/commands/vet-list.d.ts +6 -0
  77. package/dist/commands/vet-list.js +25 -0
  78. package/dist/commands/vet.d.ts +12 -0
  79. package/dist/commands/vet.js +118 -1
  80. package/dist/core/__fixtures__/prompt-injection-payloads.js +31 -0
  81. package/dist/core/anti-llm-policy.d.ts +3 -0
  82. package/dist/core/anti-llm-policy.js +3 -0
  83. package/dist/core/auth.js +2 -0
  84. package/dist/core/checklist-analysis.js +50 -12
  85. package/dist/core/ci-analysis.d.ts +7 -2
  86. package/dist/core/ci-analysis.js +76 -21
  87. package/dist/core/comment-utils.d.ts +1 -1
  88. package/dist/core/comment-utils.js +7 -1
  89. package/dist/core/commit-date.d.ts +19 -0
  90. package/dist/core/commit-date.js +17 -0
  91. package/dist/core/compliance-score.js +11 -7
  92. package/dist/core/config-registry.js +11 -5
  93. package/dist/core/contributing.d.ts +2 -3
  94. package/dist/core/contributing.js +2 -3
  95. package/dist/core/daily-logic.d.ts +27 -5
  96. package/dist/core/daily-logic.js +57 -19
  97. package/dist/core/errors.d.ts +37 -3
  98. package/dist/core/errors.js +54 -5
  99. package/dist/core/gist-health.d.ts +15 -3
  100. package/dist/core/gist-health.js +8 -0
  101. package/dist/core/gist-state-store.d.ts +24 -4
  102. package/dist/core/gist-state-store.js +97 -46
  103. package/dist/core/github-stats.d.ts +104 -16
  104. package/dist/core/github-stats.js +282 -97
  105. package/dist/core/http-cache.d.ts +0 -10
  106. package/dist/core/http-cache.js +0 -19
  107. package/dist/core/index.d.ts +12 -5
  108. package/dist/core/index.js +15 -5
  109. package/dist/core/issue-conversation.d.ts +8 -2
  110. package/dist/core/issue-conversation.js +31 -12
  111. package/dist/core/local-config.d.ts +95 -0
  112. package/dist/core/local-config.js +271 -0
  113. package/dist/core/merged-pr-notes.d.ts +2 -2
  114. package/dist/core/pagination.d.ts +55 -0
  115. package/dist/core/pagination.js +59 -0
  116. package/dist/core/paths.d.ts +7 -0
  117. package/dist/core/paths.js +9 -0
  118. package/dist/core/pr-assembly.js +6 -2
  119. package/dist/core/pr-graphql.d.ts +37 -3
  120. package/dist/core/pr-graphql.js +73 -12
  121. package/dist/core/pr-monitor.d.ts +29 -12
  122. package/dist/core/pr-monitor.js +71 -23
  123. package/dist/core/pr-preflight.d.ts +113 -0
  124. package/dist/core/pr-preflight.js +364 -0
  125. package/dist/core/pr-quality-rubric.d.ts +0 -6
  126. package/dist/core/pr-quality-rubric.js +0 -8
  127. package/dist/core/pr-template.d.ts +2 -0
  128. package/dist/core/pr-template.js +5 -1
  129. package/dist/core/repo-policy.d.ts +105 -0
  130. package/dist/core/repo-policy.js +400 -0
  131. package/dist/core/repo-score-manager.d.ts +48 -0
  132. package/dist/core/repo-score-manager.js +111 -1
  133. package/dist/core/review-analysis.d.ts +34 -19
  134. package/dist/core/review-analysis.js +74 -19
  135. package/dist/core/reviewed-prs-fetch.js +11 -29
  136. package/dist/core/reviewed-prs.js +8 -15
  137. package/dist/core/stale-data.d.ts +41 -0
  138. package/dist/core/stale-data.js +115 -0
  139. package/dist/core/state-persistence.d.ts +62 -27
  140. package/dist/core/state-persistence.js +338 -117
  141. package/dist/core/state-schema.d.ts +113 -210
  142. package/dist/core/state-schema.js +165 -80
  143. package/dist/core/state.d.ts +60 -8
  144. package/dist/core/state.js +192 -46
  145. package/dist/core/status-determination.js +26 -8
  146. package/dist/core/strategy.js +3 -1
  147. package/dist/core/types.d.ts +22 -1
  148. package/dist/core/types.js +1 -0
  149. package/dist/core/untrusted-content.d.ts +30 -11
  150. package/dist/core/untrusted-content.js +77 -42
  151. package/dist/core/urls.d.ts +9 -0
  152. package/dist/core/urls.js +18 -0
  153. package/dist/dashboard/assets/{chart-panel-DPKNBUts.js → chart-panel-C_C1lFTI.js} +1 -1
  154. package/dist/dashboard/assets/{index-B25bZOYX.js → index-B--H66Jk.js} +1 -1
  155. package/dist/dashboard/index.html +1 -1
  156. package/dist/formatters/json.d.ts +262 -6
  157. package/dist/formatters/json.js +77 -1
  158. package/package.json +1 -1
  159. package/dist/core/ci-enforced-tools.d.ts +0 -35
  160. package/dist/core/ci-enforced-tools.js +0 -109
  161. package/dist/core/comment-decision.d.ts +0 -79
  162. package/dist/core/comment-decision.js +0 -82
  163. package/dist/core/extraction-categories.d.ts +0 -55
  164. package/dist/core/extraction-categories.js +0 -108
  165. package/dist/core/follow-up-history.d.ts +0 -40
  166. package/dist/core/follow-up-history.js +0 -71
  167. package/dist/core/issue-effort.d.ts +0 -29
  168. package/dist/core/issue-effort.js +0 -47
  169. package/dist/core/maintainer-hints.d.ts +0 -23
  170. package/dist/core/maintainer-hints.js +0 -36
  171. package/dist/core/workflow-state.d.ts +0 -56
  172. package/dist/core/workflow-state.js +0 -101
@@ -9,9 +9,8 @@ function isBotReview(review) {
9
9
  return isBotAuthor(review.user?.login ?? '', review.user?.type);
10
10
  }
11
11
  /**
12
- * Determine review decision from reviews list.
13
- * Groups reviews by user, keeping each user's latest verdict, then checks
14
- * for CHANGES_REQUESTED or APPROVED states.
12
+ * Each human reviewer's standing verdict: their latest APPROVED or
13
+ * CHANGES_REQUESTED review, dropped again by a later DISMISSED one.
15
14
  *
16
15
  * Only APPROVED, CHANGES_REQUESTED and DISMISSED change a reviewer's standing
17
16
  * verdict on GitHub. COMMENTED is also what GitHub records for every inline
@@ -20,11 +19,7 @@ function isBotReview(review) {
20
19
  * Bot-authored reviews (e.g. an AI review bot posting APPROVE) are ignored so a
21
20
  * bot alone never reads as maintainer approval or a changes request (#1840).
22
21
  */
23
- export function determineReviewDecision(reviews) {
24
- if (reviews.length === 0) {
25
- return 'review_required';
26
- }
27
- // Group reviews by user, keeping each user's latest verdict
22
+ function standingVerdicts(reviews) {
28
23
  const latestByUser = new Map();
29
24
  for (const review of reviews) {
30
25
  const login = review.user?.login;
@@ -35,10 +30,18 @@ export function determineReviewDecision(reviews) {
35
30
  latestByUser.delete(login);
36
31
  }
37
32
  else if (state === 'APPROVED' || state === 'CHANGES_REQUESTED') {
38
- latestByUser.set(login, state);
33
+ latestByUser.set(login, review);
39
34
  }
40
35
  }
41
- const states = Array.from(latestByUser.values());
36
+ return Array.from(latestByUser.values());
37
+ }
38
+ /**
39
+ * Determine review decision from reviews list: changes requested when any
40
+ * reviewer's standing verdict ({@link standingVerdicts}) is CHANGES_REQUESTED,
41
+ * otherwise approved when any is APPROVED.
42
+ */
43
+ export function determineReviewDecision(reviews) {
44
+ const states = standingVerdicts(reviews).map((review) => review.state);
42
45
  if (states.includes('CHANGES_REQUESTED')) {
43
46
  return 'changes_requested';
44
47
  }
@@ -47,6 +50,19 @@ export function determineReviewDecision(reviews) {
47
50
  }
48
51
  return 'review_required';
49
52
  }
53
+ /**
54
+ * When `login`'s standing approval (see {@link standingVerdicts}) was
55
+ * submitted, or undefined when that account has no standing APPROVED verdict.
56
+ * Logins compare case-insensitively. Lets the status logic tell whether the
57
+ * author of an unanswered comment approved at or after writing it (#1920).
58
+ */
59
+ export function getStandingApprovalDate(reviews, login) {
60
+ const wanted = login?.toLowerCase();
61
+ if (!wanted)
62
+ return undefined;
63
+ const approval = standingVerdicts(reviews).find((review) => review.state === 'APPROVED' && review.user?.login?.toLowerCase() === wanted);
64
+ return approval?.submitted_at ?? undefined;
65
+ }
50
66
  /**
51
67
  * Get the date of the latest CHANGES_REQUESTED review (from any human reviewer).
52
68
  * Used to detect needs_changes status when review feedback is in inline comments.
@@ -135,15 +151,50 @@ export function getFirstMaintainerResponseAt(comments, reviews, username) {
135
151
  }
136
152
  return earliest;
137
153
  }
154
+ /**
155
+ * Associations GitHub reports for an account with no tie to the repository.
156
+ * CONTRIBUTOR is not one of them: an outside token sees a maintainer whose
157
+ * organization membership is private as CONTRIBUTOR.
158
+ */
159
+ const NO_STANDING_ASSOCIATIONS = new Set([
160
+ 'NONE',
161
+ 'FIRST_TIMER',
162
+ 'FIRST_TIME_CONTRIBUTOR',
163
+ 'MANNEQUIN',
164
+ ]);
165
+ /** Lower-cased logins of everyone who submitted a review, in any state, or an inline review comment on the PR. */
166
+ function prReviewers(reviews, reviewComments) {
167
+ const logins = new Set();
168
+ for (const list of [reviews, reviewComments]) {
169
+ for (const item of list) {
170
+ const login = item.user?.login;
171
+ if (login)
172
+ logins.add(login.toLowerCase());
173
+ }
174
+ }
175
+ return logins;
176
+ }
138
177
  /**
139
178
  * Check if there are unresponded comments from maintainers.
140
179
  * Combines issue comments and review comments into a timeline,
141
180
  * then finds maintainer comments after the user's last comment.
181
+ *
182
+ * Whose items count (#1921): every review from another human, and every issue
183
+ * comment from another human except a passer-by's. A passer-by is an account
184
+ * whose association is NONE, FIRST_TIMER, FIRST_TIME_CONTRIBUTOR or MANNEQUIN
185
+ * ({@link NO_STANDING_ASSOCIATIONS}) and that has submitted no review (in any
186
+ * state) and no inline review comment on this PR. So an OWNER, MEMBER,
187
+ * COLLABORATOR or CONTRIBUTOR always counts, anyone who reviewed the PR counts
188
+ * whatever their association, and an issue comment with no association data
189
+ * counts: missing a maintainer costs more than surfacing a passer-by. This is
190
+ * deliberately wider than {@link isMaintainerEngagement}, which drives the
191
+ * dormancy clock.
142
192
  */
143
193
  export function checkUnrespondedComments(comments, reviews, reviewComments, username) {
144
194
  // Combine comments and reviews into a timeline
145
195
  const timeline = [];
146
196
  const usernameLower = username.toLowerCase();
197
+ const reviewers = prReviewers(reviews, reviewComments);
147
198
  for (const comment of comments) {
148
199
  const author = comment.user?.login || 'unknown';
149
200
  timeline.push({
@@ -152,6 +203,7 @@ export function checkUnrespondedComments(comments, reviews, reviewComments, user
152
203
  body: comment.body || '',
153
204
  createdAt: comment.created_at,
154
205
  isUser: author.toLowerCase() === usernameLower,
206
+ isPasserBy: NO_STANDING_ASSOCIATIONS.has(comment.author_association ?? '') && !reviewers.has(author.toLowerCase()),
155
207
  });
156
208
  }
157
209
  for (const review of reviews) {
@@ -196,7 +248,7 @@ export function checkUnrespondedComments(comments, reviews, reviewComments, user
196
248
  }
197
249
  // Find maintainer comments after the user's last comment
198
250
  let lastMaintainerComment;
199
- let lastMaintainerReviewId;
251
+ const unrespondedComments = [];
200
252
  for (const item of timeline) {
201
253
  if (item.isUser)
202
254
  continue; // Skip user's own comments
@@ -204,26 +256,29 @@ export function checkUnrespondedComments(comments, reviews, reviewComments, user
204
256
  continue; // Skip deleted/null accounts
205
257
  if (isBotAuthor(item.author, item.userType))
206
258
  continue; // Skip bots
259
+ if (item.isPasserBy)
260
+ continue; // Skip accounts with no tie to the repository or the PR (#1921)
261
+ // Skip pure acknowledgments here, not after the loop, so a later "thanks"
262
+ // does not clear an earlier unanswered request (#1916). A review with
263
+ // inline comments is never skipped: those carry feedback beyond the
264
+ // summary body that likely needs a response (#829).
265
+ const hasInlineComments = item.reviewId != null && reviewHasInlineComments(item.reviewId, reviewComments);
266
+ if (isAcknowledgmentComment(item.body) && !hasInlineComments)
267
+ continue;
207
268
  const itemTime = new Date(item.createdAt);
208
269
  if (!lastUserCommentTime || itemTime > lastUserCommentTime) {
270
+ unrespondedComments.push({ author: item.author, createdAt: item.createdAt });
209
271
  lastMaintainerComment = {
210
272
  author: item.author,
211
273
  body: item.body.slice(0, 200) + (item.body.length > 200 ? '...' : ''),
212
274
  createdAt: item.createdAt,
213
275
  };
214
- lastMaintainerReviewId = item.reviewId;
215
276
  }
216
277
  }
217
- // Filter out pure acknowledgment comments that don't require a response.
218
- // Skip the filter when the review has inline comments — those indicate
219
- // feedback beyond the summary body that likely needs a response (#829).
220
- const lastReviewHasInlineComments = lastMaintainerReviewId != null && reviewHasInlineComments(lastMaintainerReviewId, reviewComments);
221
- if (lastMaintainerComment && isAcknowledgmentComment(lastMaintainerComment.body) && !lastReviewHasInlineComments) {
222
- lastMaintainerComment = undefined;
223
- }
224
278
  return {
225
279
  hasUnrespondedComment: !!lastMaintainerComment,
226
280
  lastMaintainerComment,
281
+ unrespondedComments,
227
282
  };
228
283
  }
229
284
  /**
@@ -8,7 +8,7 @@
8
8
  import { rethrowRejections } from './concurrency.js';
9
9
  import { ConfigurationError, ValidationError, describeError, getHttpStatusCode, isRateLimitOrAuthError, } from './errors.js';
10
10
  import { debug, warn } from './logger.js';
11
- import { paginateAllDetailed } from './pagination.js';
11
+ import { paginateAllDetailed, searchAllPages } from './pagination.js';
12
12
  import { isOwnRepo, isUntrackedOrg, parseGitHubUrl } from './urls.js';
13
13
  const MODULE = 'reviewed-prs';
14
14
  /**
@@ -83,38 +83,20 @@ class ReviewedPRFilter {
83
83
  }
84
84
  /**
85
85
  * Read one search page by page, most recently updated first, up to
86
- * {@link REVIEWED_PR_SEARCH_MAX_PAGES}. A page that fails ends the search
87
- * with what was read so far and the failure recorded; a rate-limit or auth
86
+ * {@link REVIEWED_PR_SEARCH_MAX_PAGES} (`searchAllPages`). A page that fails
87
+ * ends the search with what was read so far and the failure recorded, the
88
+ * first page included: the other search still runs. A rate-limit or auth
88
89
  * error propagates instead.
89
90
  */
90
91
  async function searchPages(octokit, q) {
91
- const result = { items: [], totalCount: 0, pagesRead: 0, incomplete: false };
92
- for (let page = 1; page <= REVIEWED_PR_SEARCH_MAX_PAGES; page++) {
93
- let data;
94
- try {
95
- ({ data } = await octokit.search.issuesAndPullRequests({
96
- q,
97
- page,
98
- sort: 'updated',
99
- order: 'desc',
100
- per_page: SEARCH_PER_PAGE,
101
- }));
102
- }
103
- catch (error) {
104
- if (isRateLimitOrAuthError(error))
105
- throw error;
106
- result.failure = { page, error };
107
- return result;
108
- }
109
- result.pagesRead = page;
110
- result.totalCount = data.total_count;
111
- if (data.incomplete_results)
112
- result.incomplete = true;
113
- result.items.push(...data.items);
114
- if (data.items.length < SEARCH_PER_PAGE || result.items.length >= result.totalCount)
115
- break;
92
+ try {
93
+ return await searchAllPages((page) => octokit.search.issuesAndPullRequests({ q, page, sort: 'updated', order: 'desc', per_page: SEARCH_PER_PAGE }), REVIEWED_PR_SEARCH_MAX_PAGES, SEARCH_PER_PAGE);
94
+ }
95
+ catch (error) {
96
+ if (isRateLimitOrAuthError(error))
97
+ throw error;
98
+ return { items: [], totalCount: 0, pagesRead: 0, incomplete: false, truncated: true, failure: { page: 1, error } };
116
99
  }
117
- return result;
118
100
  }
119
101
  /** Why a search did not cover every result: a failed page, else the page cap; undefined when it did. */
120
102
  function coverageWarning(subject, pages) {
@@ -29,6 +29,7 @@
29
29
  * and `PRMonitor.fetchCompareStatus`; orchestration, the compare call, the
30
30
  * dismiss check and the warnings live in commands/daily-reviewed-prs.ts.
31
31
  */
32
+ import { commitDateOf } from './commit-date.js';
32
33
  import { isBotAuthor, isQuoteReplyTo, isReactionOnlyComment, proseWithoutCode } from './comment-utils.js';
33
34
  import { debug } from './logger.js';
34
35
  const MODULE = 'reviewed-prs';
@@ -124,20 +125,6 @@ function scanUser(entries, usernameLower) {
124
125
  }
125
126
  return user;
126
127
  }
127
- /**
128
- * The date a commit was pushed under: the committer date when the author
129
- * also committed it (their own amend or rebase moved it, which is the
130
- * force-push case this feature exists for), the author date when someone
131
- * else rewrote it (a maintainer's rebase does not make the author's old
132
- * work new). Either falls back to the other when missing.
133
- */
134
- function commitDateOf(entry) {
135
- const authorDate = entry.commit.author?.date;
136
- const committerDate = entry.commit.committer?.date;
137
- const login = entry.author?.login?.toLowerCase();
138
- const isOwnRewrite = login !== undefined && entry.committer?.login?.toLowerCase() === login;
139
- return isOwnRewrite ? (committerDate ?? authorDate) : (authorDate ?? committerDate);
140
- }
141
128
  /** More than one parent: an "Update branch" or upstream merge, which carries no new work of its own. */
142
129
  function isMergeCommit(entry) {
143
130
  return (entry.parents?.length ?? 0) > 1;
@@ -146,7 +133,13 @@ function isMergeCommit(entry) {
146
133
  function toDatedCommit(entry, usernameLower) {
147
134
  if (isMergeCommit(entry))
148
135
  return undefined;
149
- const date = commitDateOf(entry);
136
+ // Committer date only for the author's own amend or rebase (the force-push case this feature exists for).
137
+ const date = commitDateOf({
138
+ authorDate: entry.commit.author?.date,
139
+ committerDate: entry.commit.committer?.date,
140
+ authorLogin: entry.author?.login,
141
+ committerLogin: entry.committer?.login,
142
+ });
150
143
  const atMs = parseMs(date);
151
144
  if (!date || atMs === undefined)
152
145
  return undefined;
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Retention for the rejected state copies under `~/.oss-autopilot` (#1956).
3
+ *
4
+ * `state.json.rejected-<ms>` (state-persistence.ts),
5
+ * `state-cache.json.rejected-<ms>` (gist-state-store.ts) and
6
+ * `local-config.json.rejected-<ms>` (local-config.ts) preserve a file that
7
+ * failed validation so the user can recover it by hand. Nothing
8
+ * reads them back, and one bad night can write dozens.
9
+ *
10
+ * Kept: the newest {@link REJECTED_KEEP} of each kind, the oldest of each kind
11
+ * (the first copy of an incident is the one most likely to hold the state
12
+ * from before it), and every copy younger than {@link REJECTED_MIN_AGE_DAYS}.
13
+ * Only direct children of the data
14
+ * directory whose names match what the code itself writes are considered, and
15
+ * only regular files: a symlink or a directory with a matching name is left
16
+ * alone.
17
+ */
18
+ export declare const REJECTED_KEEP = 5;
19
+ export declare const REJECTED_MIN_AGE_DAYS = 7;
20
+ export declare const DAY_MS: number;
21
+ /** Directory names the overnight preparer gives its worktrees: `<owner>-<repo>-<n>`, `...-issue-<n>`. */
22
+ export declare const WORKTREE_NAME: RegExp;
23
+ /** True when `child`, with every symlink resolved, sits strictly inside `parent`. */
24
+ export declare function isInside(parent: string, child: string): boolean;
25
+ /**
26
+ * Rejected copies in `dataDir` that retention no longer covers, in no order.
27
+ * Read-only. Throws on an unreadable directory; a missing one is empty.
28
+ */
29
+ export declare function staleRejectedCopies(dataDir: string, now?: number): string[];
30
+ export interface PruneResult {
31
+ /** Paths deleted (or, from a dry run, the paths that would be). */
32
+ removed: string[];
33
+ errors: string[];
34
+ }
35
+ /**
36
+ * Delete what {@link staleRejectedCopies} lists. Never throws: it runs beside
37
+ * state loading and the overnight run, and a failed prune must not fail
38
+ * either. Every failure, and every prune that deleted something, is logged at
39
+ * warn, so an automatic delete always leaves a trace.
40
+ */
41
+ export declare function pruneRejectedCopies(dataDir: string, now?: number): PruneResult;
@@ -0,0 +1,115 @@
1
+ /**
2
+ * Retention for the rejected state copies under `~/.oss-autopilot` (#1956).
3
+ *
4
+ * `state.json.rejected-<ms>` (state-persistence.ts),
5
+ * `state-cache.json.rejected-<ms>` (gist-state-store.ts) and
6
+ * `local-config.json.rejected-<ms>` (local-config.ts) preserve a file that
7
+ * failed validation so the user can recover it by hand. Nothing
8
+ * reads them back, and one bad night can write dozens.
9
+ *
10
+ * Kept: the newest {@link REJECTED_KEEP} of each kind, the oldest of each kind
11
+ * (the first copy of an incident is the one most likely to hold the state
12
+ * from before it), and every copy younger than {@link REJECTED_MIN_AGE_DAYS}.
13
+ * Only direct children of the data
14
+ * directory whose names match what the code itself writes are considered, and
15
+ * only regular files: a symlink or a directory with a matching name is left
16
+ * alone.
17
+ */
18
+ import * as fs from 'node:fs';
19
+ import path from 'node:path';
20
+ import { errorMessage } from './errors.js';
21
+ import { warn } from './logger.js';
22
+ const MODULE = 'stale-data';
23
+ export const REJECTED_KEEP = 5;
24
+ export const REJECTED_MIN_AGE_DAYS = 7;
25
+ export const DAY_MS = 24 * 60 * 60 * 1000;
26
+ /** Directory names the overnight preparer gives its worktrees: `<owner>-<repo>-<n>`, `...-issue-<n>`. */
27
+ export const WORKTREE_NAME = /^[\w.-]+-\d+$/;
28
+ const REJECTED_PATTERN = /^(state|state-cache|local-config)\.json\.rejected-(\d+)$/;
29
+ /** True when `child`, with every symlink resolved, sits strictly inside `parent`. */
30
+ export function isInside(parent, child) {
31
+ const rel = path.relative(fs.realpathSync(parent), fs.realpathSync(child));
32
+ return rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel);
33
+ }
34
+ function readRejectedCopy(dataDir, name) {
35
+ const match = REJECTED_PATTERN.exec(name);
36
+ if (!match)
37
+ return null;
38
+ const file = path.join(dataDir, name);
39
+ const stat = fs.lstatSync(file);
40
+ if (!stat.isFile() || !isInside(dataDir, file))
41
+ return null;
42
+ return { file, kind: match[1], lastTouchedMs: Math.max(Number(match[2]), stat.mtimeMs) };
43
+ }
44
+ /** One unreadable entry (a file that vanished mid-scan) is skipped, not fatal. */
45
+ function tryReadRejectedCopy(dataDir, name) {
46
+ try {
47
+ return readRejectedCopy(dataDir, name);
48
+ }
49
+ catch (err) {
50
+ warn(MODULE, `Skipping ${name} in ${dataDir}: ${errorMessage(err)}`);
51
+ return null;
52
+ }
53
+ }
54
+ /** A total order, so copies with equal timestamps still rank: by time, then by name. */
55
+ function isNewer(a, b) {
56
+ if (a.kind !== b.kind || a.lastTouchedMs < b.lastTouchedMs)
57
+ return false;
58
+ return a.lastTouchedMs > b.lastTouchedMs || a.file.localeCompare(b.file) > 0;
59
+ }
60
+ /**
61
+ * Rejected copies in `dataDir` that retention no longer covers, in no order.
62
+ * Read-only. Throws on an unreadable directory; a missing one is empty.
63
+ */
64
+ export function staleRejectedCopies(dataDir, now = Date.now()) {
65
+ if (!fs.existsSync(dataDir))
66
+ return [];
67
+ const copies = [];
68
+ for (const name of fs.readdirSync(dataDir)) {
69
+ const copy = tryReadRejectedCopy(dataDir, name);
70
+ if (copy)
71
+ copies.push(copy);
72
+ }
73
+ const cutoff = now - REJECTED_MIN_AGE_DAYS * DAY_MS;
74
+ // ponytail: O(n^2) rank instead of a sort; n is a handful of files.
75
+ const isCovered = (copy) => copy.lastTouchedMs >= cutoff ||
76
+ copies.filter((other) => isNewer(other, copy)).length < REJECTED_KEEP ||
77
+ copies.every((other) => !isNewer(copy, other));
78
+ return copies.filter((copy) => !isCovered(copy)).map((copy) => copy.file);
79
+ }
80
+ function didRemove(file, errors) {
81
+ try {
82
+ fs.unlinkSync(file);
83
+ }
84
+ catch (err) {
85
+ errors.push(`Could not delete rejected state copy ${file}: ${errorMessage(err)}`);
86
+ return false;
87
+ }
88
+ return true;
89
+ }
90
+ function listStale(dataDir, now, errors) {
91
+ try {
92
+ return staleRejectedCopies(dataDir, now);
93
+ }
94
+ catch (err) {
95
+ errors.push(`Could not prune rejected state copies in ${dataDir}: ${errorMessage(err)}`);
96
+ return [];
97
+ }
98
+ }
99
+ /**
100
+ * Delete what {@link staleRejectedCopies} lists. Never throws: it runs beside
101
+ * state loading and the overnight run, and a failed prune must not fail
102
+ * either. Every failure, and every prune that deleted something, is logged at
103
+ * warn, so an automatic delete always leaves a trace.
104
+ */
105
+ export function pruneRejectedCopies(dataDir, now = Date.now()) {
106
+ const errors = [];
107
+ const removed = listStale(dataDir, now, errors).filter((file) => didRemove(file, errors));
108
+ for (const error of errors)
109
+ warn(MODULE, error);
110
+ if (removed.length > 0) {
111
+ const names = removed.map((file) => path.basename(file)).join(', ');
112
+ warn(MODULE, `Pruned ${removed.length} rejected state copy(ies) from ${dataDir}, keeping the newest ${REJECTED_KEEP} and the oldest of each kind and all younger than ${REJECTED_MIN_AGE_DAYS} days: ${names}`);
113
+ }
114
+ return { removed, errors };
115
+ }
@@ -6,16 +6,20 @@
6
6
  import { AgentState } from './types.js';
7
7
  /**
8
8
  * Acquire an advisory file lock using exclusive-create (`wx` flag).
9
- * If the lock file already exists but is stale (older than LOCK_TIMEOUT_MS or corrupt),
10
- * it is removed and re-acquired.
11
- * @throws Error if the lock is held by another active process.
9
+ * A held lock is retried for about a second; a stale one (see
10
+ * {@link readStaleLock}) is taken over through an atomic rename.
11
+ * @returns The lock content written, for {@link releaseLock} and for
12
+ * re-checking ownership before the write the lock protects.
13
+ * @throws StateLockTimeoutError (a ConcurrencyError) if the lock is still
14
+ * held after the wait. Nothing has been written at that point.
12
15
  */
13
- export declare function acquireLock(lockPath: string): void;
16
+ export declare function acquireLock(lockPath: string): string;
14
17
  /**
15
- * Release an advisory file lock, but only if this process owns it.
16
- * Silently ignores missing lock files or locks owned by other processes.
18
+ * Release an advisory file lock, but only if it still holds `held`, the
19
+ * content {@link acquireLock} returned. A missing lock is ignored; any other
20
+ * failure is warned about, never thrown (this runs in a `finally`).
17
21
  */
18
- export declare function releaseLock(lockPath: string): void;
22
+ export declare function releaseLock(lockPath: string, held: string): void;
19
23
  /**
20
24
  * Write data to `filePath` atomically by first writing to a temporary file
21
25
  * in the same directory and then renaming. Rename is atomic on POSIX filesystems,
@@ -61,12 +65,31 @@ export interface LoadRecoveryInfo {
61
65
  reason: string;
62
66
  }
63
67
  /**
64
- * Result of {@link loadState}: the loaded state, the file's mtime for change
65
- * detection, and (only when the main file was rejected) recovery details.
68
+ * What saveState's compare-and-swap and reloadStateIfChanged compare (#2006).
69
+ * mtime alone misses two writes in one timestamp quantum (whole seconds on
70
+ * FAT and some network or synced mounts). Every write here is an atomic
71
+ * rename, which usually lands on a new inode; size catches in-place writers.
72
+ * Where the file system synthesizes or reuses inode numbers (FAT/vfat, cifs
73
+ * with noserverino, FUSE without use_ino, ext4 reusing a freed inode), or
74
+ * reports `ino` as 0 on both sides, the check degrades to mtime + size.
75
+ * `ino` is the decimal string of a bigint stat: a 64-bit NTFS file ID does
76
+ * not fit a double, and two IDs that round to the same number would match.
77
+ */
78
+ export interface StateFileIdentity {
79
+ mtimeMs: number;
80
+ ino: string;
81
+ size: number;
82
+ }
83
+ /**
84
+ * Result of {@link loadState}: the loaded state, the file's identity for
85
+ * change detection, and (only when the main file was rejected) recovery
86
+ * details. `fileId` is null only when there was no state file to take a
87
+ * baseline from. Fresh state that replaces a rejected file keeps the
88
+ * rejected file's identity, so an intervening valid write is not clobbered.
66
89
  */
67
90
  export interface LoadStateResult {
68
91
  state: AgentState;
69
- mtimeMs: number;
92
+ fileId: StateFileIdentity | null;
70
93
  recovery?: LoadRecoveryInfo;
71
94
  }
72
95
  /**
@@ -77,39 +100,51 @@ export interface LoadStateResult {
77
100
  * dropped silently. `source` names the copy in the warning.
78
101
  */
79
102
  export declare function warnMalformedWorkClaims(raw: unknown, state: AgentState, source: string): void;
103
+ /**
104
+ * Refuse stored state whose schema version is above this release's. Treating
105
+ * it as invalid would restore an older backup (or fresh state) over newer
106
+ * data. `source` names the copy in the message.
107
+ */
108
+ export declare function assertNotNewerVersion(raw: unknown, source: string): void;
80
109
  /**
81
110
  * Load state from file, or create initial state if none exists.
82
111
  * If the main state file is corrupted, attempts to restore from the most recent backup.
83
112
  * Performs migration from legacy ./data/ location if needed.
84
- * @returns Object with the loaded state, the file's mtime (for change detection),
113
+ * @returns Object with the loaded state, the file's identity (for change detection),
85
114
  * and recovery details when the main file was rejected.
86
- * @throws Error when the state file exists but cannot be read due to a
87
- * permission error (EACCES/EPERM) — that is an environment problem, not
88
- * corruption, so restore-or-fresh would mask it and risk clobbering data.
115
+ * @throws Error when the state file exists but cannot be read due to a file
116
+ * system error (EACCES/EPERM get guidance, others are rethrown as they are)
117
+ * or was written by a newer release. Neither is corruption, so
118
+ * restore-or-fresh would mask it and risk clobbering data. No file is touched.
89
119
  */
90
120
  export declare function loadState(): LoadStateResult;
91
121
  /**
92
122
  * Persist state to disk, creating a timestamped backup of the previous
93
123
  * state file first. Retains at most 10 backup files.
94
124
  *
95
- * When `expectedMtimeMs` is provided (non-null, non-zero), implements
96
- * optimistic compare-and-swap: if the on-disk file has been modified since
97
- * the caller last loaded it, throws `ConcurrencyError` instead of
98
- * overwriting. This prevents the classic read-modify-write lost-update
99
- * race across processes (see issue #1030). Pass `null` / `0` to disable
100
- * the check (first write, or when the caller has already reloaded).
125
+ * When `expected` is provided (non-null), implements optimistic
126
+ * compare-and-swap: if the on-disk file's identity (mtime, inode, size)
127
+ * differs from the one the caller last loaded or saved, throws
128
+ * `ConcurrencyError` instead of overwriting. This prevents the classic
129
+ * read-modify-write lost-update race across processes (see issues #1030,
130
+ * #2006). Pass `null` to disable the check (no file at load).
101
131
  *
102
132
  * The check runs *inside* the advisory lock so the compare-and-swap is
103
133
  * atomic with respect to the write.
104
134
  *
105
- * @returns The file's mtime after writing (for change detection).
106
- * @throws ConcurrencyError when `expectedMtimeMs` is provided and the
107
- * on-disk mtime no longer matches.
135
+ * @returns The file's identity after writing (for change detection).
136
+ * @throws ConcurrencyError when `expected` is provided and the on-disk
137
+ * identity no longer matches, or the file cannot be stat'ed.
108
138
  */
109
- export declare function saveState(state: Readonly<AgentState>, expectedMtimeMs?: number | null): number;
139
+ export declare function saveState(state: Readonly<AgentState>, expected?: StateFileIdentity | null): StateFileIdentity;
110
140
  /**
111
141
  * Re-read state from disk if the file has been modified since the last load/save.
112
- * Uses mtime comparison (single statSync call) to avoid unnecessary JSON parsing.
113
- * @returns The new state and mtime if reloaded, or null if no change detected.
142
+ * Compares file identity (single statSync call) to avoid unnecessary JSON parsing;
143
+ * a null baseline always reloads.
144
+ * @returns The new state and identity if reloaded, or null if no change detected
145
+ * (or the file is gone).
146
+ * @throws What {@link loadState} throws, after one retry for transient
147
+ * resource errors: a newer-version state file or a persistent file system
148
+ * error must reach the caller, not be served as stale state.
114
149
  */
115
- export declare function reloadStateIfChanged(lastLoadedMtimeMs: number): LoadStateResult | null;
150
+ export declare function reloadStateIfChanged(lastLoaded: StateFileIdentity | null): LoadStateResult | null;