@oss-autopilot/core 3.31.0 → 3.31.2

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.
@@ -14,7 +14,7 @@ import * as http from 'node:http';
14
14
  import * as fs from 'node:fs';
15
15
  import * as path from 'node:path';
16
16
  import * as crypto from 'node:crypto';
17
- import { getGitHubToken, getCLIVersion, maybeCheckpoint } from '../core/index.js';
17
+ import { getGitHubToken, getCLIVersion } from '../core/index.js';
18
18
  import { errorMessage, ValidationError, ConcurrencyError, GistConcurrencyError } from '../core/errors.js';
19
19
  import { warn } from '../core/logger.js';
20
20
  import { validateUrl, validateGitHubUrl, PR_URL_PATTERN, ISSUE_URL_PATTERN } from './validation.js';
@@ -469,13 +469,11 @@ export async function startDashboardServer(options) {
469
469
  };
470
470
  }
471
471
  else {
472
- // dismiss_issue_response
472
+ // dismiss_issue_response: same command the CLI and MCP surfaces run.
473
+ const { runDismiss } = await import('./dismiss.js');
473
474
  applyMutation = async () => {
474
- gistSync.stateManager.dismissIssue(body.url, new Date().toISOString());
475
- // Mirror runMove's contract: every mutating surface checkpoints to
476
- // Gist and surfaces the warning. Never throws — failures come back
477
- // as the warning string.
478
- gistSyncWarning = await maybeCheckpoint(gistSync.stateManager, MODULE);
475
+ const output = await runDismiss({ url: body.url });
476
+ gistSyncWarning = output.gistSyncWarning ?? null;
479
477
  };
480
478
  }
481
479
  // Reload state before mutating to avoid overwriting external CLI changes.
@@ -51,12 +51,7 @@ interface SearchOptions {
51
51
  * @throws {Error} If any token is not a valid scout strategy.
52
52
  */
53
53
  export declare function parseSearchStrategies(raw: string | undefined): SearchStrategy[] | undefined;
54
- /**
55
- * Retention window for the search seen-set (#1528). Entries older than this are
56
- * culled so the list stays bounded. Set well beyond oss-scout's rotation TTL
57
- * (default 7 days) so an entry scout would still exclude is never dropped early.
58
- */
59
- export declare const SEARCH_SEEN_RETENTION_DAYS = 30;
54
+ export { SEARCH_SEEN_RETENTION_DAYS } from '../core/state-prune.js';
60
55
  /**
61
56
  * Record the issues surfaced by a search into the durable seen-set (#1528) so
62
57
  * the next search rotates past them, and cull entries older than
@@ -9,6 +9,7 @@ import { gradeFromCandidate, reconcileRecommendation } from '../core/issue-gradi
9
9
  import { computeStrategy } from '../core/strategy.js';
10
10
  import { refreshStarredReposIfStale } from '../core/starred-repos.js';
11
11
  import { debug, warn } from '../core/logger.js';
12
+ import { SCOUT_ROTATION_TTL_DAYS, SEARCH_SEEN_RETENTION_DAYS } from '../core/state-prune.js';
12
13
  const MODULE = 'search';
13
14
  /**
14
15
  * Hard cap on issue-search result count. Shared between CLI (`cli-registry.ts`),
@@ -115,12 +116,8 @@ function readScoutDelayOverride(envVar) {
115
116
  }
116
117
  return parsed;
117
118
  }
118
- /**
119
- * Retention window for the search seen-set (#1528). Entries older than this are
120
- * culled so the list stays bounded. Set well beyond oss-scout's rotation TTL
121
- * (default 7 days) so an entry scout would still exclude is never dropped early.
122
- */
123
- export const SEARCH_SEEN_RETENTION_DAYS = 30;
119
+ // Retention for the search seen-set (#1528) lives with the persist-time prune.
120
+ export { SEARCH_SEEN_RETENTION_DAYS } from '../core/state-prune.js';
124
121
  /**
125
122
  * Record the issues surfaced by a search into the durable seen-set (#1528) so
126
123
  * the next search rotates past them, and cull entries older than
@@ -180,6 +177,8 @@ export async function runSearch(options) {
180
177
  preferLanguages,
181
178
  preferRepos,
182
179
  diversityRatio: SEARCH_DIVERSITY_RATIO,
180
+ // Pinned so searchSeen's retention (state-prune.ts) always outlives it.
181
+ recentlySurfacedTtlDays: SCOUT_ROTATION_TTL_DAYS,
183
182
  ...(interPhaseDelayMs !== undefined ? { interPhaseDelayMs } : {}),
184
183
  ...(broadPhaseDelayMs !== undefined ? { broadPhaseDelayMs } : {}),
185
184
  });
@@ -204,7 +204,21 @@ export function analyzeCheckRuns(checkRuns) {
204
204
  failingCheckNames.push(check.name);
205
205
  failingCheckConclusions.set(check.name, check.conclusion);
206
206
  }
207
- else if (check.status === 'in_progress' || check.status === 'queued') {
207
+ else if (check.conclusion === null && check.status === 'waiting') {
208
+ // `waiting` is an environment protection rule holding the job for a
209
+ // deployment approval. Like an action_required run, only a maintainer
210
+ // can clear it, so it is an auth gate: not passing, but not pending
211
+ // either, which would turn into a stuck-CI rerun nudge the contributor
212
+ // cannot act on. Recorded as action_required so classifyCICheck files
213
+ // it under auth_gate.
214
+ hasFailingChecks = true;
215
+ failingCheckNames.push(check.name);
216
+ failingCheckConclusions.set(check.name, 'action_required');
217
+ }
218
+ else if (check.conclusion === null && check.status !== 'completed') {
219
+ // Any other run without a conclusion that has not completed is
220
+ // pending: in_progress and queued, but also pending (concurrency
221
+ // group) and requested.
208
222
  hasPendingChecks = true;
209
223
  }
210
224
  else if (check.conclusion === 'success') {
@@ -156,28 +156,108 @@ function checkIssueReference(meta, repoContext) {
156
156
  }
157
157
  const SECTION_WHAT = /(?:^|\n)#{1,3}\s*(?:summary|overview|what(?:\s+changed)?)\b/i;
158
158
  const SECTION_WHY = /(?:^|\n)#{1,3}\s*(?:why|motivation|context|background|rationale)\b/i;
159
- const SECTION_TEST = /(?:^|\n)#{1,3}\s*(?:test\s*plan|how\s+to\s+test|testing|tests?)\b/i;
159
+ const CLOSING_REF = /\b(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\s+(?:[\w.-]+\/[\w.-]+)?#\d+/gi;
160
+ // Closed code fences: a line opening with 3+ backticks, closed by a later line
161
+ // opening with at least as many. An unclosed fence is text.
162
+ function fenceSpans(body) {
163
+ const spans = [];
164
+ let open;
165
+ let offset = 0;
166
+ for (const line of body.split('\n')) {
167
+ const len = /^ {0,3}(`{3,})/.exec(line)?.[1].length ?? 0;
168
+ if (len > 0 && !open) {
169
+ open = { start: offset, len };
170
+ }
171
+ else if (len > 0 && open && len >= open.len) {
172
+ spans.push([open.start, offset + line.length]);
173
+ open = undefined;
174
+ }
175
+ offset += line.length + 1;
176
+ }
177
+ return spans;
178
+ }
179
+ // Balanced inline code spans in body[from, to): a run of N backticks closes at
180
+ // the next run of exactly N. An unmatched run is text.
181
+ function inlineSpans(body, from, to) {
182
+ const runs = [...body.slice(from, to).matchAll(/`+/g)].map((m) => ({ start: from + m.index, len: m[0].length }));
183
+ const closer = new Map();
184
+ const nextByLen = new Map();
185
+ for (let r = runs.length - 1; r >= 0; r--) {
186
+ const next = nextByLen.get(runs[r].len);
187
+ if (next !== undefined)
188
+ closer.set(r, next);
189
+ nextByLen.set(runs[r].len, r);
190
+ }
191
+ const spans = [];
192
+ let r = 0;
193
+ while (r < runs.length) {
194
+ const close = closer.get(r);
195
+ if (close === undefined) {
196
+ r += 1;
197
+ }
198
+ else {
199
+ spans.push([runs[r].start, runs[close].start + runs[close].len]);
200
+ r = close + 1;
201
+ }
202
+ }
203
+ return spans;
204
+ }
205
+ // 1 for each character inside code (fenced or inline). Linear time.
206
+ function codeMask(body) {
207
+ const mask = new Uint8Array(body.length);
208
+ const fences = fenceSpans(body);
209
+ const gaps = [];
210
+ let from = 0;
211
+ for (const [start, end] of fences) {
212
+ gaps.push([from, start]);
213
+ from = end;
214
+ }
215
+ gaps.push([from, body.length]);
216
+ const inline = gaps.flatMap(([start, end]) => inlineSpans(body, start, end));
217
+ for (const [start, end] of [...fences, ...inline])
218
+ mask.fill(1, start, end);
219
+ return mask;
220
+ }
221
+ function proseOf(body) {
222
+ // Drop closed `<!-- ... -->` comments outside code; an unclosed opener, or
223
+ // one in code, is text.
224
+ const code = codeMask(body);
225
+ let uncommented = '';
226
+ let hasClosers = true;
227
+ let i = 0;
228
+ while (i < body.length) {
229
+ const end = hasClosers && code[i] === 0 && body.startsWith('<!--', i) ? body.indexOf('-->', i + 4) : -1;
230
+ if (end === -1) {
231
+ // An opener with no closer means no later opener can close either.
232
+ if (code[i] === 0 && body.startsWith('<!--', i))
233
+ hasClosers = false;
234
+ uncommented += body[i];
235
+ i += 1;
236
+ }
237
+ else {
238
+ i = end + 3;
239
+ }
240
+ }
241
+ return (uncommented
242
+ // A heading is a short title line, not a sentence that starts with "# ".
243
+ .replace(/^ {0,3}#{1,6}[ \t]+[^\n]{0,60}$/gm, (line) => (/[.!?。]\s*$/.test(line) ? line : ''))
244
+ .replace(CLOSING_REF, '')
245
+ .trim());
246
+ }
247
+ // Headings are never required: a sentence or two of what and why is a full
248
+ // description, and requiring a heading set pads small PRs with filler sections.
160
249
  function checkDescription(meta) {
161
250
  const weight = WEIGHTS.description;
162
251
  const trimmed = meta.body.trim();
163
252
  if (trimmed.length === 0) {
164
253
  return { status: 'fail', weight, detail: 'description is empty' };
165
254
  }
166
- const what = SECTION_WHAT.test(meta.body);
167
- const why = SECTION_WHY.test(meta.body);
168
- const test = SECTION_TEST.test(meta.body);
169
- const present = [what, why, test].filter(Boolean).length;
170
- if (present === 3) {
171
- return { status: 'pass', weight, detail: 'what / why / test sections present' };
172
- }
173
- if (present >= 1 || trimmed.length >= 80) {
174
- return {
175
- status: 'warn',
176
- weight,
177
- detail: `${present} of 3 sections present (what/why/test)`,
178
- };
255
+ const prose = proseOf(meta.body);
256
+ const hasHeading = SECTION_WHAT.test(meta.body) || SECTION_WHY.test(meta.body);
257
+ if (prose.length >= 80 || (hasHeading && /\p{L}/u.test(prose))) {
258
+ return { status: 'pass', weight, detail: 'describes the change' };
179
259
  }
180
- return { status: 'fail', weight, detail: 'minimal description, no recognizable sections' };
260
+ return { status: 'warn', weight, detail: 'short description; say what changed and why' };
181
261
  }
182
262
  function checkFocusedChanges(meta) {
183
263
  const weight = WEIGHTS.focusedChanges;
@@ -91,6 +91,20 @@ export declare class GistConcurrencyError extends OssAutopilotError {
91
91
  readonly remoteEtag: string | null;
92
92
  constructor(expectedEtag: string | null, remoteEtag: string | null);
93
93
  }
94
+ /**
95
+ * A Gist file is too large to round-trip: the Gist API truncated it (over
96
+ * 1 MB inline) and `raw_url` is missing, off-host, or refused (404/413), or
97
+ * a push would exceed the 10 MB `raw_url` limit. A {@link ConfigurationError}
98
+ * because retrying cannot fix it: bootstrap halts with this message instead
99
+ * of degrading and re-bootstrapping forever, and the repair commands
100
+ * (config, setup, state-unlink) still run. Transient raw_url failures are
101
+ * not wrapped in this error and stay retryable.
102
+ */
103
+ /** What a user can do about a {@link GistFileSizeError}. Shared by every surface that renders one. */
104
+ export declare const GIST_FILE_SIZE_REMEDY: string;
105
+ export declare class GistFileSizeError extends ConfigurationError {
106
+ constructor(message: string);
107
+ }
94
108
  /**
95
109
  * Extract a human-readable message from an unknown error value.
96
110
  */
@@ -139,6 +139,24 @@ export class GistConcurrencyError extends OssAutopilotError {
139
139
  this.name = 'GistConcurrencyError';
140
140
  }
141
141
  }
142
+ /**
143
+ * A Gist file is too large to round-trip: the Gist API truncated it (over
144
+ * 1 MB inline) and `raw_url` is missing, off-host, or refused (404/413), or
145
+ * a push would exceed the 10 MB `raw_url` limit. A {@link ConfigurationError}
146
+ * because retrying cannot fix it: bootstrap halts with this message instead
147
+ * of degrading and re-bootstrapping forever, and the repair commands
148
+ * (config, setup, state-unlink) still run. Transient raw_url failures are
149
+ * not wrapped in this error and stay retryable.
150
+ */
151
+ /** What a user can do about a {@link GistFileSizeError}. Shared by every surface that renders one. */
152
+ export const GIST_FILE_SIZE_REMEDY = 'trim the large state fields in the Gist (repoScores and searchSeen are usually the biggest), ' +
153
+ 'or run state-unlink to fall back to local state';
154
+ export class GistFileSizeError extends ConfigurationError {
155
+ constructor(message) {
156
+ super(message);
157
+ this.name = 'GistFileSizeError';
158
+ }
159
+ }
142
160
  /**
143
161
  * Extract a human-readable message from an unknown error value.
144
162
  */
@@ -118,6 +118,16 @@ export interface OctokitLike {
118
118
  headers?: Record<string, string | undefined>;
119
119
  }>;
120
120
  };
121
+ /**
122
+ * Generic request, used only to fetch the `raw_url` of a file the Gist API
123
+ * truncated. Optional so test mocks that never truncate can omit it.
124
+ */
125
+ request?: (route: {
126
+ method: 'GET';
127
+ url: string;
128
+ }) => Promise<{
129
+ data: unknown;
130
+ }>;
121
131
  }
122
132
  /** Shape of a single Gist in a list response (subset). */
123
133
  interface GistListItem {
@@ -131,6 +141,8 @@ interface GistResponseData {
131
141
  files: Record<string, {
132
142
  filename: string;
133
143
  content?: string;
144
+ truncated?: boolean;
145
+ raw_url?: string;
134
146
  } | null>;
135
147
  }
136
148
  /**
@@ -263,6 +275,12 @@ export declare class GistStateStore {
263
275
  * - `{ status: 'error', error }` — fetch attempt failed.
264
276
  */
265
277
  refreshFromGist(): Promise<RefreshResult>;
278
+ /**
279
+ * Refuse to write a file the Gist could no longer serve back (raw_url stops
280
+ * at 10 MB), and warn once a file passes ~900 KB so growth is visible before
281
+ * reads start depending on the truncated-file path.
282
+ */
283
+ private checkPushSize;
266
284
  /**
267
285
  * Preflight check: verify the token has Gist API scope.
268
286
  * Costs one cheap API call; catches permission issues early with a clear message.
@@ -273,6 +291,18 @@ export declare class GistStateStore {
273
291
  * and write the local cache file.
274
292
  */
275
293
  private fetchAndCache;
294
+ /**
295
+ * Fetch the full body of a file the Gist API truncated (>1 MB of content).
296
+ *
297
+ * Throws {@link GistFileSizeError} when the body cannot be read for a
298
+ * reason a retry will not fix (no raw_url, off-host raw_url, a non-text
299
+ * body, or a non-transient HTTP error such as 404/413). Rate limits and
300
+ * transient network errors (5xx, ECONNRESET, timeouts) are rethrown as-is
301
+ * so callers keep treating them as retryable: bootstrap degrades to the
302
+ * local cache and the pre-write re-read reports a GistConcurrencyError.
303
+ * Either way the cache is left unchanged.
304
+ */
305
+ private fetchRawContent;
276
306
  /**
277
307
  * Parse `state.json` from the in-memory cache. Handles v1→v4 migration
278
308
  * by running through the Zod schema (which requires version: 4).
@@ -47,10 +47,11 @@
47
47
  */
48
48
  import * as fs from 'node:fs';
49
49
  import { AgentStateSchema } from './state-schema.js';
50
+ import { serializeState } from './state-prune.js';
50
51
  import { atomicWriteFileSync, createFreshState, migrateV1ToV2, migrateV2ToV3, migrateV3ToV4, } from './state-persistence.js';
51
52
  import { getGistIdPath, getStateCachePath } from './paths.js';
52
53
  import { debug, warn } from './logger.js';
53
- import { ConfigurationError, GistPermissionError, GistConcurrencyError, GistCorruptError, isRateLimitError, } from './errors.js';
54
+ import { ConfigurationError, GistPermissionError, GistConcurrencyError, GistCorruptError, GistFileSizeError, isRateLimitError, isTransientNetworkError, errorMessage, } from './errors.js';
54
55
  const MODULE = 'gist-store';
55
56
  /**
56
57
  * Extract the ETag header from an Octokit response, tolerating both lower-
@@ -84,6 +85,18 @@ function preserveRejectedGistContent(raw, gistId) {
84
85
  export const GIST_DESCRIPTION = 'oss-autopilot-state';
85
86
  /** Primary state file name inside the Gist. */
86
87
  export const STATE_FILE_NAME = 'state.json';
88
+ /**
89
+ * The Gist API returns at most 1 MB of `content` per file and sets
90
+ * `truncated: true` past that; the full body (up to 10 MB) is only available
91
+ * from `raw_url`. Above 10 MB even `raw_url` stops working, so `push()`
92
+ * refuses to write a file that large and warns as it approaches 1 MB.
93
+ */
94
+ const GIST_CONTENT_WARN_BYTES = 900 * 1024;
95
+ const GIST_RAW_MAX_BYTES = 10 * 1024 * 1024;
96
+ const GIST_RAW_HOST = 'gist.githubusercontent.com';
97
+ const SIZE_WARN_BAND_BYTES = 100 * 1024;
98
+ /** Highest size band already warned about, per filename, for this process. */
99
+ const warnedSizeBands = new Map();
87
100
  /**
88
101
  * Gist-backed state store with in-memory file cache and local write-through.
89
102
  */
@@ -407,6 +420,7 @@ export class GistStateStore {
407
420
  if (this.gistId === null) {
408
421
  throw new Error('GistStateStore: cannot push before bootstrap — gistId is null');
409
422
  }
423
+ this.checkPushSize();
410
424
  const buildFiles = () => {
411
425
  const out = {};
412
426
  for (const filename of this.dirtyFiles) {
@@ -474,13 +488,9 @@ export class GistStateStore {
474
488
  this.cachedFiles.set(filename, content);
475
489
  }
476
490
  };
477
- try {
478
- await this.fetchAndCache(this.gistId);
479
- }
480
- catch (readErr) {
481
- warn(MODULE, `Pre-write re-read failed: ${readErr}`);
482
- // Roll back any partial mutation so the caller's retry path sees the
483
- // prior in-memory state with local mutations re-applied on top.
491
+ // Restore the pre-read cache, baseline, and ETag, then re-apply the
492
+ // staged edits on top, so the caller sees the prior in-memory state.
493
+ const rollBackPreRead = () => {
484
494
  this.cachedFiles.clear();
485
495
  for (const [filename, content] of preReadCache) {
486
496
  this.cachedFiles.set(filename, content);
@@ -488,6 +498,15 @@ export class GistStateStore {
488
498
  this.baselineFiles = preReadBaseline;
489
499
  this.lastFetchedEtag = preReadEtag;
490
500
  reapplyStaged();
501
+ };
502
+ try {
503
+ await this.fetchAndCache(this.gistId);
504
+ }
505
+ catch (readErr) {
506
+ warn(MODULE, `Pre-write re-read failed: ${errorMessage(readErr)}`);
507
+ // Roll back any partial mutation so the caller's retry path sees the
508
+ // prior in-memory state with local mutations re-applied on top.
509
+ rollBackPreRead();
491
510
  // Preserve GistCorruptError so callers don't retry against a corrupt
492
511
  // remote, and let rate-limit errors propagate unchanged so they aren't
493
512
  // mistaken for a concurrency conflict — a "refresh + retry" remediation
@@ -496,6 +515,10 @@ export class GistStateStore {
496
515
  // caller can refresh + retry.
497
516
  if (readErr instanceof GistCorruptError)
498
517
  throw readErr;
518
+ // An unreadable oversized file is not a conflict: refresh + retry
519
+ // would hit the same wall, so surface it as-is.
520
+ if (readErr instanceof GistFileSizeError)
521
+ throw readErr;
499
522
  if (isRateLimitError(readErr))
500
523
  throw readErr;
501
524
  throw new GistConcurrencyError(preReadEtag, null);
@@ -504,9 +527,14 @@ export class GistStateStore {
504
527
  if (baselineStateJson !== remoteStateJson) {
505
528
  warn(MODULE, 'state.json changed remotely since our last fetch; surfacing GistConcurrencyError instead of clobbering (#1235, #1510)');
506
529
  // Preserve local state.json (and other staged dirty files) in memory
507
- // so the caller can refresh and reapply if appropriate.
508
- reapplyStaged();
509
- throw new GistConcurrencyError(preReadEtag, this.lastFetchedEtag);
530
+ // so the caller can refresh and reapply if appropriate. The baseline
531
+ // must go back to the pre-read snapshot too: leaving it at the remote
532
+ // we just refused to overwrite would let the next push() pass this
533
+ // comparison and clobber the other machine's write with the same
534
+ // stale local state.
535
+ const remoteEtag = this.lastFetchedEtag;
536
+ rollBackPreRead();
537
+ throw new GistConcurrencyError(preReadEtag, remoteEtag);
510
538
  }
511
539
  // No conflict — re-apply our staged dirty contents on top of the
512
540
  // refreshed remote so the write carries our edits.
@@ -579,6 +607,34 @@ export class GistStateStore {
579
607
  }
580
608
  }
581
609
  // ── Private helpers ─────────────────────────────────────────────────
610
+ /**
611
+ * Refuse to write a file the Gist could no longer serve back (raw_url stops
612
+ * at 10 MB), and warn once a file passes ~900 KB so growth is visible before
613
+ * reads start depending on the truncated-file path.
614
+ */
615
+ checkPushSize() {
616
+ for (const filename of this.dirtyFiles) {
617
+ const content = this.cachedFiles.get(filename);
618
+ if (content === undefined)
619
+ continue;
620
+ const bytes = Buffer.byteLength(content, 'utf8');
621
+ if (bytes > GIST_RAW_MAX_BYTES) {
622
+ throw new GistFileSizeError(`Refusing to push Gist file ${filename}: ${bytes} bytes exceeds the ${GIST_RAW_MAX_BYTES}-byte limit ` +
623
+ 'the Gist API can serve back. The local change is kept in memory but was not synced.');
624
+ }
625
+ if (bytes > GIST_CONTENT_WARN_BYTES) {
626
+ // Once per file per 100 KB band per process, so a long-lived server
627
+ // warns as the file grows instead of on every push.
628
+ const band = Math.floor(bytes / SIZE_WARN_BAND_BYTES);
629
+ if ((warnedSizeBands.get(filename) ?? -1) < band) {
630
+ warnedSizeBands.set(filename, band);
631
+ warn(MODULE, `Gist file ${filename} is ${bytes} bytes, near or past the 1 MB the Gist API returns inline. ` +
632
+ 'Reads fall back to raw_url, which works up to 10 MB; to stay well under that, trim large ' +
633
+ 'state fields (repoScores and searchSeen are usually the biggest).');
634
+ }
635
+ }
636
+ }
637
+ }
582
638
  /**
583
639
  * Preflight check: verify the token has Gist API scope.
584
640
  * Costs one cheap API call; catches permission issues early with a clear message.
@@ -604,15 +660,23 @@ export class GistStateStore {
604
660
  async fetchAndCache(gistId) {
605
661
  const response = await this.octokit.gists.get({ gist_id: gistId });
606
662
  this.gistId = gistId;
663
+ // Resolve every file's full content before touching the cache or ETag, so
664
+ // a truncated file we cannot read leaves the store as it was.
665
+ const contents = new Map();
666
+ for (const [filename, file] of Object.entries(response.data.files)) {
667
+ if (!file)
668
+ continue;
669
+ const content = file.truncated ? await this.fetchRawContent(filename, file.raw_url) : file.content;
670
+ if (content != null)
671
+ contents.set(filename, content);
672
+ }
607
673
  // Capture the ETag for optimistic-concurrency push (#1115). Header
608
674
  // names from Octokit are lower-cased; tolerate both shapes for robustness.
609
675
  this.lastFetchedEtag = extractEtag(response.headers);
610
676
  // Populate in-memory cache with ALL files from the Gist
611
677
  this.cachedFiles.clear();
612
- for (const [filename, file] of Object.entries(response.data.files)) {
613
- if (file && file.content != null) {
614
- this.cachedFiles.set(filename, file.content);
615
- }
678
+ for (const [filename, content] of contents) {
679
+ this.cachedFiles.set(filename, content);
616
680
  }
617
681
  // Snapshot the just-fetched contents as the per-file baseline (#1235).
618
682
  // The 412 merge path uses this to detect whether a concurrent write
@@ -624,6 +688,42 @@ export class GistStateStore {
624
688
  this.writeLocalStateCache(state);
625
689
  return state;
626
690
  }
691
+ /**
692
+ * Fetch the full body of a file the Gist API truncated (>1 MB of content).
693
+ *
694
+ * Throws {@link GistFileSizeError} when the body cannot be read for a
695
+ * reason a retry will not fix (no raw_url, off-host raw_url, a non-text
696
+ * body, or a non-transient HTTP error such as 404/413). Rate limits and
697
+ * transient network errors (5xx, ECONNRESET, timeouts) are rethrown as-is
698
+ * so callers keep treating them as retryable: bootstrap degrades to the
699
+ * local cache and the pre-write re-read reports a GistConcurrencyError.
700
+ * Either way the cache is left unchanged.
701
+ */
702
+ async fetchRawContent(filename, rawUrl) {
703
+ const fail = (reason) => new GistFileSizeError(`Gist file ${filename} is larger than the 1 MB the Gist API returns inline and its full content ` +
704
+ `could not be read from raw_url (${reason}). Local state was left unchanged.`);
705
+ if (!this.octokit.request)
706
+ throw fail('no HTTP client available');
707
+ if (!rawUrl)
708
+ throw fail('the API returned no raw_url');
709
+ const parsed = URL.canParse(rawUrl) ? new URL(rawUrl) : undefined;
710
+ const host = parsed?.protocol === 'https:' ? parsed.hostname : '';
711
+ // The request carries the GitHub token, so only send it to the Gist raw host.
712
+ if (host !== GIST_RAW_HOST)
713
+ throw fail(`unexpected raw_url host`);
714
+ let data;
715
+ try {
716
+ ({ data } = await this.octokit.request({ method: 'GET', url: rawUrl }));
717
+ }
718
+ catch (err) {
719
+ if (isRateLimitError(err) || isTransientNetworkError(err))
720
+ throw err;
721
+ throw fail(errorMessage(err));
722
+ }
723
+ if (typeof data !== 'string')
724
+ throw fail('response body was not text');
725
+ return data;
726
+ }
627
727
  /**
628
728
  * Parse `state.json` from the in-memory cache. Handles v1→v4 migration
629
729
  * by running through the Zod schema (which requires version: 4).
@@ -695,7 +795,7 @@ export class GistStateStore {
695
795
  */
696
796
  async createGist() {
697
797
  const freshState = createFreshState();
698
- const stateContent = JSON.stringify(freshState, null, 2);
798
+ const stateContent = serializeState(freshState);
699
799
  const { data } = await this.octokit.gists.create({
700
800
  description: GIST_DESCRIPTION,
701
801
  public: false,
@@ -720,7 +820,7 @@ export class GistStateStore {
720
820
  * Create a new private Gist seeded with the provided state (for migration).
721
821
  */
722
822
  async createGistFromState(seedState) {
723
- const stateContent = JSON.stringify(seedState, null, 2);
823
+ const stateContent = serializeState(seedState);
724
824
  const { data } = await this.octokit.gists.create({
725
825
  description: GIST_DESCRIPTION,
726
826
  public: false,
@@ -770,7 +870,7 @@ export class GistStateStore {
770
870
  writeLocalStateCache(state) {
771
871
  try {
772
872
  const cachePath = getStateCachePath();
773
- atomicWriteFileSync(cachePath, JSON.stringify(state, null, 2), 0o600);
873
+ atomicWriteFileSync(cachePath, serializeState(state), 0o600);
774
874
  debug(MODULE, `Wrote state cache to ${cachePath}`);
775
875
  }
776
876
  catch (err) {
@@ -16,7 +16,7 @@ export { daysBetween, formatRelativeTime, byDateDescending } from './dates.js';
16
16
  export { getCLIVersion, getDataDir, getStatePath, getBackupDir, getCacheDir, stateFileExists } from './paths.js';
17
17
  export { getGitHubToken, getGitHubTokenAsync, requireGitHubToken, resetGitHubTokenCache, detectGitHubUsername, } from './auth.js';
18
18
  export { DEFAULT_CONCURRENCY } from './concurrency.js';
19
- export { OssAutopilotError, ConfigurationError, ValidationError, GistPermissionError, ConcurrencyError, GistConcurrencyError, errorMessage, getHttpStatusCode, isRateLimitError, isRateLimitOrAuthError, nonFatalCatch, resolveErrorCode, } from './errors.js';
19
+ export { OssAutopilotError, ConfigurationError, ValidationError, GistPermissionError, ConcurrencyError, GistConcurrencyError, GistFileSizeError, GIST_FILE_SIZE_REMEDY, errorMessage, getHttpStatusCode, isRateLimitError, isRateLimitOrAuthError, nonFatalCatch, resolveErrorCode, } from './errors.js';
20
20
  export { enableDebug, isDebugEnabled, debug, info, warn, timed } from './logger.js';
21
21
  export { HttpCache, getHttpCache, cachedRequest, type CacheEntry } from './http-cache.js';
22
22
  export { CRITICAL_STATUSES, applyStatusOverrides, computeRepoSignals, groupPRsByRepo, assessCapacity, collectActionableIssues, computeActionMenu, toShelvedPRRef, buildStarFilter, firstMaintainerResponseFromDigest, formatActionHint, formatBriefSummary, formatSummary, printDigest, } from './daily-logic.js';
@@ -17,7 +17,7 @@ export { daysBetween, formatRelativeTime, byDateDescending } from './dates.js';
17
17
  export { getCLIVersion, getDataDir, 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, errorMessage, getHttpStatusCode, isRateLimitError, isRateLimitOrAuthError, nonFatalCatch, resolveErrorCode, } from './errors.js';
20
+ export { OssAutopilotError, ConfigurationError, ValidationError, GistPermissionError, ConcurrencyError, GistConcurrencyError, GistFileSizeError, GIST_FILE_SIZE_REMEDY, 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
23
  export { CRITICAL_STATUSES, applyStatusOverrides, computeRepoSignals, groupPRsByRepo, assessCapacity, collectActionableIssues, computeActionMenu, toShelvedPRRef, buildStarFilter, firstMaintainerResponseFromDigest, formatActionHint, formatBriefSummary, formatSummary, printDigest, } from './daily-logic.js';
@@ -68,12 +68,14 @@ export interface CommitInfo {
68
68
  /**
69
69
  * Assemble a {@link FetchedPR} from normalized signals.
70
70
  *
71
- * `getCommitInfo` is invoked lazily — and only when the status logic actually
71
+ * `commitInfo` is either the HEAD commit already in hand (the GraphQL batch
72
+ * carries it) or a thunk the REST path uses to avoid an extra
73
+ * `repos.getCommit` call. The thunk is invoked only when the status logic
72
74
  * needs the HEAD commit date (an unresponded maintainer comment or a
73
- * changes-requested review). The REST path uses this to avoid an extra
74
- * `repos.getCommit` call; the GraphQL path already has the commit in the batch
75
- * and simply returns it. Because `determineStatus` consults the commit date
76
- * only in those same branches, always-providing it (GraphQL) versus
77
- * lazily-providing it (REST) yields an identical result.
75
+ * changes-requested review). `determineStatus` consults the date only in
76
+ * those same branches, so status is identical either way; the difference is
77
+ * that a known commit is always recorded on the PR, which keeps
78
+ * `latestActivityAt` (override auto-clear, #1713) off `updatedAt` for PRs
79
+ * with no human comments.
78
80
  */
79
- export declare function assembleFetchedPR(signals: PRSignals, config: AssemblyConfig, getCommitInfo: () => Promise<CommitInfo | undefined>): Promise<FetchedPR>;
81
+ export declare function assembleFetchedPR(signals: PRSignals, config: AssemblyConfig, commitInfo: CommitInfo | undefined | (() => Promise<CommitInfo | undefined>)): Promise<FetchedPR>;
@@ -19,15 +19,17 @@ import { computeDisplayLabel } from './display-utils.js';
19
19
  /**
20
20
  * Assemble a {@link FetchedPR} from normalized signals.
21
21
  *
22
- * `getCommitInfo` is invoked lazily — and only when the status logic actually
22
+ * `commitInfo` is either the HEAD commit already in hand (the GraphQL batch
23
+ * carries it) or a thunk the REST path uses to avoid an extra
24
+ * `repos.getCommit` call. The thunk is invoked only when the status logic
23
25
  * needs the HEAD commit date (an unresponded maintainer comment or a
24
- * changes-requested review). The REST path uses this to avoid an extra
25
- * `repos.getCommit` call; the GraphQL path already has the commit in the batch
26
- * and simply returns it. Because `determineStatus` consults the commit date
27
- * only in those same branches, always-providing it (GraphQL) versus
28
- * lazily-providing it (REST) yields an identical result.
26
+ * changes-requested review). `determineStatus` consults the date only in
27
+ * those same branches, so status is identical either way; the difference is
28
+ * that a known commit is always recorded on the PR, which keeps
29
+ * `latestActivityAt` (override auto-clear, #1713) off `updatedAt` for PRs
30
+ * with no human comments.
29
31
  */
30
- export async function assembleFetchedPR(signals, config, getCommitInfo) {
32
+ export async function assembleFetchedPR(signals, config, commitInfo) {
31
33
  const { comments, reviews, reviewComments } = signals;
32
34
  // Determine review decision (delegated to review-analysis module)
33
35
  const reviewDecision = determineReviewDecision(reviews);
@@ -42,9 +44,11 @@ export async function assembleFetchedPR(signals, config, getCommitInfo) {
42
44
  // no new commits pushed). Fetched lazily so the REST path skips the call when
43
45
  // it isn't needed.
44
46
  const needCommitDate = hasUnrespondedComment || reviewDecision === 'changes_requested';
45
- const commitInfo = needCommitDate ? await getCommitInfo() : undefined;
46
- const latestCommitDate = commitInfo?.date;
47
- const latestCommitAuthor = commitInfo?.author;
47
+ let headCommit = typeof commitInfo === 'function' ? undefined : commitInfo;
48
+ if (typeof commitInfo === 'function' && needCommitDate)
49
+ headCommit = await commitInfo();
50
+ const latestCommitDate = headCommit?.date;
51
+ const latestCommitAuthor = headCommit?.author;
48
52
  // Analyze PR body for incomplete checklists (delegated to checklist-analysis module)
49
53
  const { hasIncompleteChecklist, checklistStats } = analyzeChecklist(signals.body || '');
50
54
  // Extract maintainer action hints from comments (delegated to maintainer-analysis module)