@oss-autopilot/core - v3.7.0
    Preparing search index...

    Class StateManager

    Core module exports Re-exports all core functionality for convenient imports

    Index

    Constructors

    • Create a new StateManager instance.

      Parameters

      • inMemoryOnly: boolean = false

        When true, state is held only in memory and never read from or written to disk. Useful for unit tests that need isolated state without side effects. Defaults to false (normal persistent mode).

      Returns StateManager

    Methods

    • Add closed PRs to storage, deduplicating by URL. Entries with URLs that fail parseGitHubUrl are dropped before persistence (read-side filters in dashboard-data already skip them, but this prevents the bad data from reaching disk in the first place).

      Parameters

      • prs: {
            closedAt: string;
            commentsFetchedAt?: string;
            learningsExtractedAt?: string;
            title: string;
            url: string;
        }[]

        Closed PRs to add (duplicates by URL are ignored)

        • closedAt: string
        • OptionalcommentsFetchedAt?: string

          When the raw review-comment bundle for this PR was last fetched (#867).

        • OptionallearningsExtractedAt?: string

          When the host last ran LLM extraction over this PR's comment bundle (#867).

        • title: string
        • url: string

      Returns { added: number; dropped: number }

      count of entries added vs. dropped (invalid URL)

    • Track a new issue. No-op if the issue URL is already tracked.

      Parameters

      • issue: {
            createdAt: string;
            id: number;
            labels: string[];
            number: number;
            repo: string;
            status: "candidate" | "claimed" | "in_progress" | "pr_submitted";
            title: string;
            updatedAt: string;
            url: string;
            vetted: boolean;
            vettingResult?: {
                checks: {
                    clearRequirements: boolean;
                    contributionGuidelinesFound: boolean;
                    noExistingPR: boolean;
                    notClaimed: boolean;
                    projectActive: boolean;
                };
                contributionGuidelines?: {
                    branchNamingConvention?: string;
                    claRequired?: boolean;
                    commitMessageFormat?: string;
                    formatter?: string;
                    issueClaimProcess?: string;
                    linter?: string;
                    prTitleFormat?: string;
                    rawContent?: string;
                    requiredChecks?: string[];
                    reviewProcess?: string;
                    styleGuideUrl?: string;
                    testCoverageRequired?: boolean;
                    testFileNaming?: string;
                    testFramework?: string;
                };
                notes: string[];
                passedAllChecks: boolean;
            };
        }

        The issue to track

      Returns void

    • Add merged PRs to storage, deduplicating by URL. Entries with URLs that fail parseGitHubUrl are dropped before persistence (read-side filters in dashboard-data already skip them, but this prevents the bad data from reaching disk in the first place).

      Parameters

      • prs: {
            commentsFetchedAt?: string;
            learningsExtractedAt?: string;
            mergedAt: string;
            title: string;
            url: string;
        }[]

        Merged PRs to add (duplicates by URL are ignored)

        • OptionalcommentsFetchedAt?: string

          When the raw review-comment bundle for this PR was last fetched (#867).

        • OptionallearningsExtractedAt?: string

          When the host last ran LLM extraction over this PR's comment bundle (#867).

        • mergedAt: string
        • title: string
        • url: string

      Returns { added: number; dropped: number }

      count of entries added vs. dropped (invalid URL)

    • Add a repository to the trusted projects list. No-op if already trusted.

      Parameters

      • repo: string

        Repository in "owner/repo" format

      Returns void

    • Execute multiple mutations as a single batch, deferring disk I/O until the batch completes. Nested batch() calls are flattened — only the outermost saves.

      Parameters

      • fn: () => void

        The function containing mutations to batch

      Returns void

    • Push current state to Gist (async). Call at well-defined moments (end of daily, after claim).

      Returns Promise<boolean>

    • Remove excluded repos/orgs from trusted projects.

      Parameters

      • repos: string[]

        Repository names to exclude

      • orgs: string[]

        Organization names to exclude

      Returns void

    • Remove a manual status override for a PR.

      Parameters

      • url: string

        The PR URL

      Returns boolean

      true if an override was removed, false if none existed

    • Tombstone the guidelines file for repo so subsequent reads return null. Throws when not in Gist mode.

      Parameters

      • repo: string

      Returns void

    • Dismiss an issue's notifications. Auto-resurfaces on new activity.

      Parameters

      • url: string

        The issue URL to dismiss

      • timestamp: string

        ISO timestamp of dismissal

      Returns boolean

      true if newly dismissed, false if already dismissed

    • Returns all stored closed-without-merge PRs (sorted by close date descending via addClosedPRs).

      Returns {
          closedAt: string;
          commentsFetchedAt?: string;
          learningsExtractedAt?: string;
          title: string;
          url: string;
      }[]

      • closedAt: string
      • OptionalcommentsFetchedAt?: string

        When the raw review-comment bundle for this PR was last fetched (#867).

      • OptionallearningsExtractedAt?: string

        When the host last ran LLM extraction over this PR's comment bundle (#867).

      • title: string
      • url: string
    • Returns the most recent close date, used as a watermark for incremental fetching.

      Returns string | undefined

    • Read the per-repo guidelines for repo (#867). Returns null when in local mode, when no file exists, or when the file is empty (tombstoned).

      Parameters

      • repo: string

      Returns string | null

    • Returns repos above the score threshold.

      Parameters

      • OptionalminScore: number

        Minimum score (default: config.minRepoScoreThreshold)

      Returns string[]

    • Get the timestamp when an issue was dismissed, or undefined if not dismissed.

      Parameters

      • url: string

        The issue URL to check

      Returns string | undefined

    • Returns repos below the score threshold.

      Parameters

      • OptionalmaxScore: number

        Maximum score (default: config.minRepoScoreThreshold)

      Returns string[]

    • Returns all stored merged PRs (sorted by merge date descending via addMergedPRs).

      Returns {
          commentsFetchedAt?: string;
          learningsExtractedAt?: string;
          mergedAt: string;
          title: string;
          url: string;
      }[]

      • OptionalcommentsFetchedAt?: string

        When the raw review-comment bundle for this PR was last fetched (#867).

      • OptionallearningsExtractedAt?: string

        When the host last ran LLM extraction over this PR's comment bundle (#867).

      • mergedAt: string
      • title: string
      • url: string
    • Returns the most recent merge date, used as a watermark for incremental fetching.

      Returns string | undefined

    • Get the score record for a repository.

      Parameters

      • repo: string

        Repository in "owner/repo" format

      Returns
          | Readonly<
              {
                  avgResponseDays: number
                  | null;
                  closedWithoutMergeCount: number;
                  language?: string | null;
                  lastEvaluatedAt: string;
                  lastMergedAt?: string;
                  mergedPRCount: number;
                  repo: string;
                  score: number;
                  signals: {
                      hasActiveMaintainers: boolean;
                      hasHostileComments: boolean;
                      isResponsive: boolean;
                  };
                  stargazersCount?: number;
              },
          >
          | undefined

      Read-only score record, or undefined if not tracked

    • Returns repository names that have at least one merged PR.

      Returns string[]

    • Returns repository names with open PRs but no merged PRs yet.

      Returns string[]

    • Returns cached starred repository names.

      Returns string[]

    • Returns a staleness marker when the in-memory state diverged from the canonical Gist (refresh failure or degraded bootstrap), or null when state is current. Commands surface this via their --json warnings envelope (#1193).

      Returns StalenessInfo | null

    • Returns aggregate contribution statistics (merge rate, PR counts, repo breakdown).

      Returns Stats

    • Get the status override for a PR, auto-clearing if new activity has occurred.

      Parameters

      • url: string

        The PR URL

      • OptionalcurrentUpdatedAt: string

        PR's current updatedAt timestamp for staleness check

      Returns
          | {
              lastActivityAt: string;
              setAt: string;
              status: "needs_addressing"
              | "waiting_on_maintainer";
          }
          | undefined

      The override if still valid, undefined otherwise

    • Increment the closed-without-merge PR count.

      Parameters

      • repo: string

        Repository in "owner/repo" format

      Returns void

    • Increment the merged PR count for a repository.

      Parameters

      • repo: string

        Repository in "owner/repo" format

      Returns void

    • Initialize state with sensible defaults for zero-config onboarding. No-op if setup is already complete.

      Parameters

      • username: string

      Returns void

    • Whether the Gist is in degraded mode (using local cache fallback).

      Returns boolean

    • Whether this StateManager is backed by a Gist.

      Returns boolean

    • Whether per-repo guidelines (#867) are available. True iff the Gist store is initialized — in local-only mode, guidelines are unavailable and write operations would throw GuidelinesNotAvailableError.

      Returns boolean

    • Check if a PR is currently shelved.

      Parameters

      • url: string

        The PR URL to check

      Returns boolean

      true if the PR is shelved

    • Check if initial setup has been completed.

      Returns boolean

    • Returns true if starred repos cache is older than 24 hours.

      Returns boolean

    • List repos with non-empty guidelines stored in the Gist.

      Returns string[]

    • Stamp commentsFetchedAt on the merged or closed PR matching url (#867). No-op when no PR with that URL is stored.

      Parameters

      • url: string
      • fetchedAt: string

      Returns void

    • Stamp learningsExtractedAt on the merged or closed PR matching url (#867). No-op when no PR with that URL is stored.

      Parameters

      • url: string
      • extractedAt: string

      Returns void

    • Mark a repository as hostile (score zeroed).

      Parameters

      • repo: string

        Repository in "owner/repo" format

      Returns void

    • Mark setup as complete and record the completion timestamp.

      Returns void

    • Re-fetch state from the backing Gist (if in Gist mode). Throttled to once per 30 seconds by GistStateStore. Returns true if state was refreshed.

      Returns Promise<boolean>

    • Re-read state from disk if the file has been modified since the last load/save. Returns true if state was reloaded, false if unchanged or in-memory mode.

      Returns boolean

    • Persist the current state to disk, creating a timestamped backup of the previous state file first. In in-memory mode, only updates lastRunAt without any file I/O.

      In Gist mode, writes to a local cache file (not the main state file) so the Gist remains the source of truth. Use checkpoint() to push state to the Gist.

      Local-file mode uses optimistic compare-and-swap: if another process has written state.json since we last loaded/saved, saveState throws ConcurrencyError. See issue #1030.

      Parameters

      • options: { allowReloadAndLoseMutation?: boolean } = {}

      Returns void

      ConcurrencyError (local file mode only) when the on-disk state was modified externally between this StateManager's last load/save and now. Callers that tolerate silent merge can set { allowReloadAndLoseMutation: true } to downgrade the error into a warning — but note that doing so abandons any in-memory mutation made since the last load. Fail-loud (the default) is preferred.

    • Persist per-repo guidelines for repo. Throws when not in Gist mode or when content exceeds the byte budget.

      Parameters

      • repo: string
      • content: string

      Returns void

    • Store the latest daily digest and update the digest timestamp.

      Parameters

      • digest: {
            autoUnshelvedPRs: {
                daysSinceActivity: number;
                number: number;
                repo: string;
                status: "needs_addressing" | "waiting_on_maintainer";
                title: string;
                url: string;
            }[];
            generatedAt: string;
            needsAddressingPRs: any[];
            openPRs: any[];
            recentlyClosedPRs: {
                closedAt: string;
                closedBy?: string;
                number: number;
                repo: string;
                title: string;
                url: string;
            }[];
            recentlyMergedPRs: {
                mergedAt: string;
                number: number;
                repo: string;
                title: string;
                url: string;
            }[];
            shelvedPRs: {
                daysSinceActivity: number;
                number: number;
                repo: string;
                status: "needs_addressing"
                | "waiting_on_maintainer";
                title: string;
                url: string;
            }[];
            summary: {
                mergeRate: number;
                totalActivePRs: number;
                totalMergedAllTime: number;
                totalNeedingAttention: number;
            };
            waitingOnMaintainerPRs: any[];
        }

        The daily digest to store

      Returns void

    • Persist the timestamp of the most recent strategy snapshot embedded in a daily run output (#1270). Called from the daily pipeline after computeStrategy() succeeds; the cadence gate in shouldComputeStrategy reads this on the next run.

      Parameters

      • iso: string

      Returns void

    • Update the local repository cache.

      Parameters

      • cache: {
            cachedAt: string;
            repos: Record<
                string,
                { currentBranch: string
                | null; exists: boolean; path: string },
            >;
            scanPaths: string[];
        }

        Local repository cache mapping repo names to paths

      Returns void

    • Update monthly closed PR counts for dashboard display.

      Parameters

      • counts: Record<string, number>

        Monthly closed PR counts keyed by YYYY-MM

      Returns void

    • Update monthly merged PR counts for dashboard display.

      Parameters

      • counts: Record<string, number>

        Monthly merged PR counts keyed by YYYY-MM

      Returns void

    • Update monthly opened PR counts for dashboard display.

      Parameters

      • counts: Record<string, number>

        Monthly opened PR counts keyed by YYYY-MM

      Returns void

    • Update the cached starred repositories and timestamp.

      Parameters

      • repos: string[]

        Repository names in "owner/repo" format

      Returns void

    • Set a manual status override for a PR. Auto-clears when the PR has new activity.

      Parameters

      • url: string

        The PR URL

      • status: "needs_addressing" | "waiting_on_maintainer"

        The overridden status

      • lastActivityAt: string

        ISO timestamp of PR's last activity when override was set

      Returns void

    • Shelve a PR URL, hiding it from daily digest and capacity.

      Parameters

      • url: string

        The PR URL to shelve

      Returns boolean

      true if newly shelved, false if already shelved

    • Restore a dismissed issue to notifications.

      Parameters

      • url: string

        The issue URL to undismiss

      Returns boolean

      true if undismissed, false if not currently dismissed

    • Unshelve a PR URL, restoring it to daily digest.

      Parameters

      • url: string

        The PR URL to unshelve

      Returns boolean

      true if removed from shelf, false if not shelved

    • Merge partial config updates into the current configuration.

      Parameters

      • config: Partial<AgentState["config"]>

        Partial config object to merge

      Returns void

    • Update scoring data for a repository.

      Parameters

      • repo: string

        Repository in "owner/repo" format

      • updates: RepoScoreUpdate

        Partial score fields to merge

      Returns void

    • Async factory that creates a StateManager backed by a GitHub Gist.

      The regular constructor is synchronous (for backwards-compat), but Gist bootstrapping requires network calls, so this factory is async.

      Parameters

      • token: string

        GitHub personal access token with gist scope

      Returns Promise<StateManager>