@oss-autopilot/core 3.31.1 → 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.
@@ -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
  });
@@ -47,6 +47,7 @@
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';
@@ -794,7 +795,7 @@ export class GistStateStore {
794
795
  */
795
796
  async createGist() {
796
797
  const freshState = createFreshState();
797
- const stateContent = JSON.stringify(freshState, null, 2);
798
+ const stateContent = serializeState(freshState);
798
799
  const { data } = await this.octokit.gists.create({
799
800
  description: GIST_DESCRIPTION,
800
801
  public: false,
@@ -819,7 +820,7 @@ export class GistStateStore {
819
820
  * Create a new private Gist seeded with the provided state (for migration).
820
821
  */
821
822
  async createGistFromState(seedState) {
822
- const stateContent = JSON.stringify(seedState, null, 2);
823
+ const stateContent = serializeState(seedState);
823
824
  const { data } = await this.octokit.gists.create({
824
825
  description: GIST_DESCRIPTION,
825
826
  public: false,
@@ -869,7 +870,7 @@ export class GistStateStore {
869
870
  writeLocalStateCache(state) {
870
871
  try {
871
872
  const cachePath = getStateCachePath();
872
- atomicWriteFileSync(cachePath, JSON.stringify(state, null, 2), 0o600);
873
+ atomicWriteFileSync(cachePath, serializeState(state), 0o600);
873
874
  debug(MODULE, `Wrote state cache to ${cachePath}`);
874
875
  }
875
876
  catch (err) {
@@ -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,6 +5,7 @@
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';
@@ -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,7 +314,7 @@ 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
+ this.gistStore.setState(serializeState(this.state));
317
318
  let isPushed;
318
319
  try {
319
320
  isPushed = await this.gistStore.push();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oss-autopilot/core",
3
- "version": "3.31.1",
3
+ "version": "3.31.2",
4
4
  "description": "CLI and core library for managing open source contributions",
5
5
  "type": "module",
6
6
  "bin": {