@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.
@@ -96,8 +96,8 @@ export declare class PRMonitor {
96
96
  private fetchCommitInfo;
97
97
  /**
98
98
  * Assemble a {@link FetchedPR} from GraphQL-batched {@link NormalizedPRData}.
99
- * No network calls: the batch already carries the commit info, so the shared
100
- * pipeline's lazy commit thunk just returns it.
99
+ * No network calls: the batch already carries the commit info, so it is
100
+ * passed directly and always recorded on the PR.
101
101
  */
102
102
  private assembleFromNormalized;
103
103
  /**
@@ -369,6 +369,11 @@ export class PRMonitor {
369
369
  // The commit date is only consulted (and only fetched) when the PR has an
370
370
  // unresponded maintainer comment or a changes-requested review — the shared
371
371
  // pipeline decides via `needCommitDate` and invokes this thunk lazily.
372
+ // A PR with a status override is the exception: override auto-clear keys
373
+ // on the commit date (#1713), so fetch it up front for those PRs only.
374
+ const commitInfo = config.statusOverrides?.[prUrl]
375
+ ? await this.fetchCommitInfo(owner, repo, ghPR.head.sha)
376
+ : () => this.fetchCommitInfo(owner, repo, ghPR.head.sha);
372
377
  return assembleFetchedPR({
373
378
  prUrl,
374
379
  owner,
@@ -384,7 +389,7 @@ export class PRMonitor {
384
389
  reviews,
385
390
  reviewComments,
386
391
  ciStatus,
387
- }, config, () => this.fetchCommitInfo(owner, repo, ghPR.head.sha));
392
+ }, config, commitInfo);
388
393
  }
389
394
  /**
390
395
  * Fetch the HEAD commit's author date and login via REST `repos.getCommit`.
@@ -419,8 +424,8 @@ export class PRMonitor {
419
424
  }
420
425
  /**
421
426
  * Assemble a {@link FetchedPR} from GraphQL-batched {@link NormalizedPRData}.
422
- * No network calls: the batch already carries the commit info, so the shared
423
- * pipeline's lazy commit thunk just returns it.
427
+ * No network calls: the batch already carries the commit info, so it is
428
+ * passed directly and always recorded on the PR.
424
429
  */
425
430
  assembleFromNormalized(ref, data) {
426
431
  const config = this.stateManager.getState().config;
@@ -439,7 +444,7 @@ export class PRMonitor {
439
444
  reviews: data.reviews,
440
445
  reviewComments: data.reviewComments,
441
446
  ciStatus: data.ciStatus,
442
- }, config, async () => data.commitInfo);
447
+ }, config, data.commitInfo);
443
448
  }
444
449
  /**
445
450
  * Fetch merged PR counts and latest merge dates per repository for the configured user.
@@ -98,7 +98,7 @@ export const PR_QUALITY_RUBRIC = [
98
98
  {
99
99
  id: 'screenshots',
100
100
  label: 'Screenshots',
101
- description: 'Included for UI changes',
101
+ description: 'Only for visible changes when the template or a maintainer asks',
102
102
  tier: 'optional',
103
103
  weight: null,
104
104
  },
@@ -6,6 +6,7 @@
6
6
  import * as fs from 'node:fs';
7
7
  import * as path from 'node:path';
8
8
  import { AgentStateSchema } from './state-schema.js';
9
+ import { serializeState } from './state-prune.js';
9
10
  import { getStatePath, getBackupDir, getDataDir, getLegacyStatePath, getLegacyBackupDir } from './paths.js';
10
11
  import { errorMessage, ConcurrencyError } from './errors.js';
11
12
  import { debug, warn } from './logger.js';
@@ -297,7 +298,7 @@ function tryRestoreFromBackup() {
297
298
  debug(MODULE, `Restored state v${state.version}: ${repoCount} repo scores`);
298
299
  // Overwrite the corrupted main state file with the restored backup (atomic write)
299
300
  const statePath = getStatePath();
300
- atomicWriteFileSync(statePath, JSON.stringify(state, null, 2), 0o600);
301
+ atomicWriteFileSync(statePath, serializeState(state), 0o600);
301
302
  debug(MODULE, 'Restored backup written to main state file');
302
303
  return state;
303
304
  }
@@ -398,7 +399,7 @@ export function loadState() {
398
399
  }
399
400
  // Save migrated state only after validation succeeds
400
401
  if (wasMigrated) {
401
- atomicWriteFileSync(statePath, JSON.stringify(parsed.data, null, 2), 0o600);
402
+ atomicWriteFileSync(statePath, serializeState(parsed.data), 0o600);
402
403
  mtimeMs = safeGetMtimeMs(statePath); // our own write: what we hold is what is on disk
403
404
  debug(MODULE, 'Migrated and validated state saved');
404
405
  }
@@ -417,7 +418,7 @@ export function loadState() {
417
418
  }
418
419
  }
419
420
  if (needsCleanupSave) {
420
- atomicWriteFileSync(statePath, JSON.stringify(state, null, 2), 0o600);
421
+ atomicWriteFileSync(statePath, serializeState(state), 0o600);
421
422
  mtimeMs = safeGetMtimeMs(statePath); // our own write, as above
422
423
  warn(MODULE, 'Cleaned up dismissed PR URLs from persisted state');
423
424
  }
@@ -550,7 +551,7 @@ export function saveState(state, expectedMtimeMs = null) {
550
551
  // Continue with save — losing a backup is acceptable, losing the save is not
551
552
  }
552
553
  // Atomic write: write to temp file then rename to prevent corruption on crash
553
- atomicWriteFileSync(statePath, JSON.stringify(state, null, 2), 0o600);
554
+ atomicWriteFileSync(statePath, serializeState(state), 0o600);
554
555
  const mtimeMs = safeGetMtimeMs(statePath);
555
556
  debug(MODULE, 'State saved successfully');
556
557
  return mtimeMs;
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Keeps the persisted AgentState small (the Gist API truncates file content
3
+ * at 1 MB). Pruning runs on a copy at serialization time, so the in-memory
4
+ * state a running command works with is never touched.
5
+ */
6
+ import type { AgentState } from './state-schema.js';
7
+ /** Rotation TTL autopilot passes to oss-scout's search (pinned, not scout's default). */
8
+ export declare const SCOUT_ROTATION_TTL_DAYS = 7;
9
+ /**
10
+ * searchSeen's only reader is scout's rotation, which ignores entries older
11
+ * than {@link SCOUT_ROTATION_TTL_DAYS}. One day of margin covers clock skew.
12
+ */
13
+ export declare const SEARCH_SEEN_RETENTION_DAYS: number;
14
+ /**
15
+ * A repo score with no merge/close history and no tracked PR or issue is only
16
+ * scout's cached observation; scout re-creates it the next time it sees the repo.
17
+ */
18
+ export declare const REPO_SCORE_RETENTION_DAYS = 14;
19
+ /** Returns a pruned shallow copy of `state`; the input is not mutated. */
20
+ export declare function pruneStateForPersist(state: AgentState, now?: number): AgentState;
21
+ /** Compact JSON of the pruned state, for every state write (Gist, cache, local file). */
22
+ export declare function serializeState(state: AgentState): string;
@@ -0,0 +1,58 @@
1
+ import { parseGitHubUrl } from './urls.js';
2
+ const DAY_MS = 24 * 60 * 60 * 1000;
3
+ /** Rotation TTL autopilot passes to oss-scout's search (pinned, not scout's default). */
4
+ export const SCOUT_ROTATION_TTL_DAYS = 7;
5
+ /**
6
+ * searchSeen's only reader is scout's rotation, which ignores entries older
7
+ * than {@link SCOUT_ROTATION_TTL_DAYS}. One day of margin covers clock skew.
8
+ */
9
+ export const SEARCH_SEEN_RETENTION_DAYS = SCOUT_ROTATION_TTL_DAYS + 1;
10
+ /**
11
+ * A repo score with no merge/close history and no tracked PR or issue is only
12
+ * scout's cached observation; scout re-creates it the next time it sees the repo.
13
+ */
14
+ export const REPO_SCORE_RETENTION_DAYS = 14;
15
+ /** Repos the user has any tracked work in. Their scores are never pruned. */
16
+ function trackedRepos(state) {
17
+ const digest = state.lastDigest;
18
+ const direct = [...(digest?.openPRs ?? []), ...(digest?.shelvedPRs ?? []), ...state.activeIssues].map((x) => x.repo);
19
+ const urls = [
20
+ ...(state.mergedPRs ?? []).map((pr) => pr.url),
21
+ ...(state.closedPRs ?? []).map((pr) => pr.url),
22
+ ...(state.config.shelvedPRUrls ?? []),
23
+ ];
24
+ const fromUrls = urls.flatMap((url) => {
25
+ const parsed = parseGitHubUrl(url);
26
+ return parsed ? [`${parsed.owner}/${parsed.repo}`] : [];
27
+ });
28
+ const repos = new Set(direct);
29
+ for (const repo of fromUrls)
30
+ repos.add(repo);
31
+ return repos;
32
+ }
33
+ /** Returns a pruned shallow copy of `state`; the input is not mutated. */
34
+ export function pruneStateForPersist(state, now = Date.now()) {
35
+ const seenCutoff = now - SEARCH_SEEN_RETENTION_DAYS * DAY_MS;
36
+ const searchSeen = state.searchSeen.filter((e) => Date.parse(e.lastSeenAt) >= seenCutoff);
37
+ const scoreCutoff = now - REPO_SCORE_RETENTION_DAYS * DAY_MS;
38
+ const keep = trackedRepos(state);
39
+ const repoScores = Object.fromEntries(Object.entries(state.repoScores).filter(([repo, s]) => {
40
+ const hasHistory = s.mergedPRCount > 0 || s.closedWithoutMergeCount > 0;
41
+ const evaluatedAt = Date.parse(s.lastEvaluatedAt);
42
+ const isFresh = Number.isNaN(evaluatedAt) || evaluatedAt >= scoreCutoff; // unparseable: keep
43
+ return hasHistory || keep.has(repo) || isFresh;
44
+ }));
45
+ // The status partitions are filters of openPRs (PRMonitor.generateDigest),
46
+ // so persist each PR once; DailyDigestSchema re-derives them on load.
47
+ // Written as [] (not omitted) so older clients still parse the state.
48
+ const lastDigest = state.lastDigest && {
49
+ ...state.lastDigest,
50
+ needsAddressingPRs: [],
51
+ waitingOnMaintainerPRs: [],
52
+ };
53
+ return { ...state, searchSeen, repoScores, lastDigest };
54
+ }
55
+ /** Compact JSON of the pruned state, for every state write (Gist, cache, local file). */
56
+ export function serializeState(state) {
57
+ return JSON.stringify(pruneStateForPersist(state));
58
+ }
@@ -356,7 +356,7 @@ export declare const FetchedPRSchema: z.ZodObject<{
356
356
  waiting_on_maintainer: "waiting_on_maintainer";
357
357
  }>;
358
358
  }, z.core.$loose>;
359
- export declare const DailyDigestSchema: z.ZodObject<{
359
+ export declare const DailyDigestSchema: z.ZodPreprocess<z.ZodObject<{
360
360
  generatedAt: z.ZodString;
361
361
  openPRs: z.ZodType<FetchedPR[], unknown, z.core.$ZodTypeInternals<FetchedPR[], unknown>>;
362
362
  needsAddressingPRs: z.ZodType<FetchedPR[], unknown, z.core.$ZodTypeInternals<FetchedPR[], unknown>>;
@@ -406,7 +406,7 @@ export declare const DailyDigestSchema: z.ZodObject<{
406
406
  totalMergedAllTime: z.ZodNumber;
407
407
  mergeRate: z.ZodNumber;
408
408
  }, z.core.$strip>;
409
- }, z.core.$strip>;
409
+ }, z.core.$strip>, unknown>;
410
410
  /**
411
411
  * One entry in the search seen-set (#1528). Records that an issue URL was
412
412
  * surfaced by a recent `search` so the next search can rotate past it instead
@@ -586,7 +586,7 @@ export declare const AgentStateSchema: z.ZodObject<{
586
586
  lastRunAt: z.ZodDefault<z.ZodString>;
587
587
  lastDigestAt: z.ZodOptional<z.ZodString>;
588
588
  lastStrategyAt: z.ZodOptional<z.ZodString>;
589
- lastDigest: z.ZodOptional<z.ZodObject<{
589
+ lastDigest: z.ZodOptional<z.ZodPreprocess<z.ZodObject<{
590
590
  generatedAt: z.ZodString;
591
591
  openPRs: z.ZodType<FetchedPR[], unknown, z.core.$ZodTypeInternals<FetchedPR[], unknown>>;
592
592
  needsAddressingPRs: z.ZodType<FetchedPR[], unknown, z.core.$ZodTypeInternals<FetchedPR[], unknown>>;
@@ -636,7 +636,7 @@ export declare const AgentStateSchema: z.ZodObject<{
636
636
  totalMergedAllTime: z.ZodNumber;
637
637
  mergeRate: z.ZodNumber;
638
638
  }, z.core.$strip>;
639
- }, z.core.$strip>>;
639
+ }, z.core.$strip>, unknown>>;
640
640
  monthlyMergedCounts: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodNumber>>;
641
641
  monthlyClosedCounts: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodNumber>>;
642
642
  monthlyOpenedCounts: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodNumber>>;
@@ -358,7 +358,23 @@ export const FetchedPRSchema = z
358
358
  * while actually validating the fields the dashboard dereferences.
359
359
  */
360
360
  const FetchedPRArraySchema = z.array(FetchedPRSchema);
361
- export const DailyDigestSchema = z.object({
361
+ /**
362
+ * The status partitions are filters of openPRs (PRMonitor.generateDigest), so
363
+ * the persisted state stores them empty (state-prune.ts) and they are
364
+ * re-derived here on load. Each open PR is persisted once.
365
+ */
366
+ function derivePartitions(raw) {
367
+ const openPRs = raw?.openPRs;
368
+ // No open PRs: nothing to derive; keep what is stored (legacy digests).
369
+ if (!Array.isArray(openPRs) || openPRs.length === 0)
370
+ return raw;
371
+ return {
372
+ ...raw,
373
+ needsAddressingPRs: openPRs.filter((pr) => pr?.status === 'needs_addressing'),
374
+ waitingOnMaintainerPRs: openPRs.filter((pr) => pr?.status === 'waiting_on_maintainer'),
375
+ };
376
+ }
377
+ const DailyDigestObjectSchema = z.object({
362
378
  generatedAt: z.string(),
363
379
  // FetchedPR arrays — ephemeral, regenerated each run. Validated for the
364
380
  // identity/status core the dashboard dereferences; loose on the rest.
@@ -371,6 +387,7 @@ export const DailyDigestSchema = z.object({
371
387
  autoUnshelvedPRs: z.array(ShelvedPRRefSchema),
372
388
  summary: DailyDigestSummarySchema,
373
389
  });
390
+ export const DailyDigestSchema = z.preprocess(derivePartitions, DailyDigestObjectSchema);
374
391
  // ── 8. Root schema ───────────────────────────────────────────────────
375
392
  /**
376
393
  * One entry in the search seen-set (#1528). Records that an issue URL was
@@ -5,10 +5,11 @@
5
5
  */
6
6
  import * as fs from 'node:fs';
7
7
  import { AgentStateSchema } from './state-schema.js';
8
+ import { serializeState } from './state-prune.js';
8
9
  import { loadState, saveState, reloadStateIfChanged, createFreshState, atomicWriteFileSync, } from './state-persistence.js';
9
10
  import * as repoScoring from './repo-score-manager.js';
10
11
  import { debug, warn } from './logger.js';
11
- import { errorMessage, ConfigurationError, ConcurrencyError, isTransientNetworkError } from './errors.js';
12
+ import { errorMessage, ConfigurationError, ConcurrencyError, isTransientNetworkError, GistFileSizeError, GIST_FILE_SIZE_REMEDY, } from './errors.js';
12
13
  import { GistStateStore } from './gist-state-store.js';
13
14
  import * as guidelinesStoreModule from './guidelines-store.js';
14
15
  /** Gist file that carries the rendered overnight report across machines (#1698). */
@@ -287,7 +288,7 @@ export class StateManager {
287
288
  // `refreshFromGist()` or `checkpoint()` re-syncs from the authoritative
288
289
  // Gist. The trade-off is a transiently-stale offline bootstrap (#1030).
289
290
  try {
290
- atomicWriteFileSync(getStateCachePath(), JSON.stringify(this.state, null, 2), 0o600);
291
+ atomicWriteFileSync(getStateCachePath(), serializeState(this.state), 0o600);
291
292
  }
292
293
  catch (err) {
293
294
  // Cache write failure is non-fatal (Gist remains source of truth), but
@@ -313,8 +314,18 @@ export class StateManager {
313
314
  async checkpoint() {
314
315
  if (!this.gistStore)
315
316
  return true; // not in Gist mode
316
- this.gistStore.setState(JSON.stringify(this.state, null, 2));
317
- const pushed = await this.gistStore.push();
317
+ this.gistStore.setState(serializeState(this.state));
318
+ let isPushed;
319
+ try {
320
+ isPushed = await this.gistStore.push();
321
+ }
322
+ catch (err) {
323
+ // A file too large to sync fails every checkpoint until state shrinks,
324
+ // so it is a degradation, not a one-off error.
325
+ if (err instanceof GistFileSizeError)
326
+ this.gistDegraded = true;
327
+ throw err;
328
+ }
318
329
  // A push that fails after its internal retry means the Gist is no longer
319
330
  // the authoritative copy of our in-memory state — surface that as degraded
320
331
  // so `state --show`, the daily check, and doctor stop reporting healthy
@@ -324,8 +335,8 @@ export class StateManager {
324
335
  // unnecessary re-bootstrap. A thrown GistConcurrencyError is deliberately
325
336
  // left untouched here — a concurrent remote write is recoverable (refresh +
326
337
  // retry), not a degradation of the Gist itself.
327
- this.gistDegraded = !pushed;
328
- return pushed;
338
+ this.gistDegraded = !isPushed;
339
+ return isPushed;
329
340
  }
330
341
  /** Whether this StateManager is backed by a Gist. */
331
342
  isGistMode() {
@@ -1246,11 +1257,14 @@ export async function bootstrapGistBestEffort(fetchToken) {
1246
1257
  cause = 'init-fallback';
1247
1258
  }
1248
1259
  catch (err) {
1249
- cause = {
1250
- reason: err instanceof ConfigurationError
1251
- ? `Gist initialization failed (${errorMessage(err)}) — fix the Gist setup (check the token's gist scope, or run state-show / setup) before relying on sync`
1252
- : `Gist initialization failed: ${errorMessage(err)}`,
1253
- };
1260
+ let reason = `Gist initialization failed: ${errorMessage(err)}`;
1261
+ if (err instanceof GistFileSizeError) {
1262
+ reason = `Gist initialization failed (${errorMessage(err)}). To fix it, ${GIST_FILE_SIZE_REMEDY}.`;
1263
+ }
1264
+ else if (err instanceof ConfigurationError) {
1265
+ reason = `Gist initialization failed (${errorMessage(err)}) — fix the Gist setup (check the token's gist scope, or run state-show / setup) before relying on sync`;
1266
+ }
1267
+ cause = { reason };
1254
1268
  }
1255
1269
  if (cause === null)
1256
1270
  return null;
@@ -105,10 +105,28 @@ function recommendForOverExtension(openPRCount, dormantPRCount, overExtended) {
105
105
  return 'open_more';
106
106
  return null;
107
107
  }
108
+ /**
109
+ * Same activity timestamp as `latestActivityAt` in daily-logic.ts (latest
110
+ * commit or maintainer comment, falling back to `updatedAt`), over the
111
+ * loosely typed persisted digest. Kept local so this module stays free of
112
+ * the state imports daily-logic pulls in.
113
+ */
114
+ function activityAt(pr) {
115
+ const commentAt = pr.lastMaintainerComment?.createdAt;
116
+ let latest;
117
+ for (const d of [pr.latestCommitDate, commentAt]) {
118
+ if (typeof d === 'string' && d !== '' && (latest === undefined || d > latest))
119
+ latest = d;
120
+ }
121
+ if (latest !== undefined)
122
+ return latest;
123
+ return typeof pr.updatedAt === 'string' ? pr.updatedAt : undefined;
124
+ }
108
125
  /**
109
126
  * Read-only mirror of the status-override lookup (#1416): same staleness
110
- * rule as `StateManager.getStatusOverride` (an override recorded against
111
- * older activity than the PR's `updatedAt` is ignored), but with NO
127
+ * rule the daily pipeline applies via `StateManager.getStatusOverride` and
128
+ * `latestActivityAt` (an override recorded against older activity than the
129
+ * PR's latest commit or maintainer comment is ignored), but with NO
112
130
  * auto-clear write — this module stays pure/no-I/O, and the daily and
113
131
  * dashboard pipelines own clearing stale overrides.
114
132
  */
@@ -118,7 +136,8 @@ function effectiveStatus(pr, state) {
118
136
  const override = state.config.statusOverrides?.[pr.url];
119
137
  if (!override)
120
138
  return pr.status;
121
- if (typeof pr.updatedAt === 'string' && pr.updatedAt > override.lastActivityAt)
139
+ const lastActivity = activityAt(pr);
140
+ if (lastActivity !== undefined && lastActivity > override.lastActivityAt)
122
141
  return pr.status;
123
142
  if (override.status !== 'needs_addressing' && override.status !== 'waiting_on_maintainer')
124
143
  return pr.status;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oss-autopilot/core",
3
- "version": "3.31.0",
3
+ "version": "3.31.2",
4
4
  "description": "CLI and core library for managing open source contributions",
5
5
  "type": "module",
6
6
  "bin": {