@hearsay-tools/squawk 0.18.0-dev.8297 → 0.18.0-dev.8304

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.
@@ -0,0 +1,224 @@
1
+ import { productEnv } from '../../core/product-env.js';
2
+ import { githubContext } from './github-cli.js';
3
+ import { CACHE_MS, firstLine, mockGithub, refStatusGraphql, resolveRepoHandleStrict, } from './github-shared.js';
4
+ import { derivePrReferenceStatus, fetchRefStatuses, GH_REF_STATUS_MAX, } from './github-ref-status-derive.js';
5
+ const refStatusCache = new Map();
6
+ const REF_STATUS_CACHE_MAX = 500;
7
+ const refStatusFlights = new Map();
8
+ /** Test-only: drop the per-reference cache so cases don't leak state into each other. */
9
+ export function __clearRefStatusCacheForTests() {
10
+ refStatusCache.clear();
11
+ refStatusFlights.clear();
12
+ }
13
+ /** Test-only: warm the cache the way the lazy route would have. */
14
+ export function __seedRefStatusCacheForTests(repoRoot, entries) {
15
+ for (const [number, resolved] of entries) {
16
+ refStatusCache.set(refStatusKey(repoRoot, number), { at: Date.now(), resolved });
17
+ }
18
+ }
19
+ /**
20
+ * Invalidate one reference after a known mutation.
21
+ */
22
+ export function forgetRefStatus(repoRoot, number) {
23
+ refStatusCache.delete(refStatusKey(repoRoot, number));
24
+ refStatusFlights.delete(refStatusKey(repoRoot, number));
25
+ }
26
+ /**
27
+ * Everything the cache ALREADY knows about these numbers. Never spawns `gh`, never awaits.
28
+ */
29
+ export function readCachedRefStatuses(repoRoot, numbers) {
30
+ const out = { prs: {}, issues: {} };
31
+ const now = Date.now();
32
+ for (const number of new Set(numbers)) {
33
+ const hit = refStatusCache.get(refStatusKey(repoRoot, number));
34
+ if (!hit || !hit.resolved || now - hit.at >= refStatusTtl(hit.resolved, hit.unknownSince, now))
35
+ continue;
36
+ out[hit.resolved.kind === 'pr' ? 'prs' : 'issues'][number] = hit.resolved.status;
37
+ }
38
+ return out;
39
+ }
40
+ const REF_STATUS_CLOSED_TTL = 10 * 60_000;
41
+ const REF_STATUS_MERGED_TTL = 24 * 60 * 60_000;
42
+ const MERGEABILITY_UNKNOWN_TTL_MS = 5_000;
43
+ const MERGEABILITY_UNKNOWN_WINDOW_MS = 60_000;
44
+ const REF_STATUS_RETRY_MS = 5 * 60_000;
45
+ function refStatusTtl(entry, unknownSince, now = Date.now()) {
46
+ if (!entry)
47
+ return CACHE_MS;
48
+ if (entry.mergeable === 'unknown' &&
49
+ unknownSince !== undefined &&
50
+ now - unknownSince < MERGEABILITY_UNKNOWN_WINDOW_MS) {
51
+ return MERGEABILITY_UNKNOWN_TTL_MS;
52
+ }
53
+ switch (entry.status) {
54
+ case 'merged':
55
+ return REF_STATUS_MERGED_TTL;
56
+ case 'closed':
57
+ case 'completed':
58
+ case 'not-planned':
59
+ return REF_STATUS_CLOSED_TTL;
60
+ default:
61
+ return CACHE_MS;
62
+ }
63
+ }
64
+ function refStatusRecheckAfter(entry, unknownSince, now = Date.now()) {
65
+ if (entry?.status === 'merged')
66
+ return null;
67
+ return refStatusTtl(entry, unknownSince, now);
68
+ }
69
+ function batchRecheckAfter(rechecks) {
70
+ let soonest = null;
71
+ for (const after of rechecks) {
72
+ if (after === null)
73
+ continue;
74
+ soonest = soonest === null ? after : Math.min(soonest, after);
75
+ }
76
+ return soonest;
77
+ }
78
+ async function sharedRefStatusMisses(repoRoot, numbers, context) {
79
+ const pending = new Map();
80
+ const owned = [];
81
+ for (const n of numbers) {
82
+ const flight = refStatusFlights.get(refStatusKey(repoRoot, n, context));
83
+ if (flight)
84
+ pending.set(n, flight);
85
+ else
86
+ owned.push(n);
87
+ }
88
+ if (owned.length) {
89
+ const batch = (async () => {
90
+ const handle = await resolveRepoHandleStrict(repoRoot, context);
91
+ if (!handle)
92
+ throw new Error('repository handle unavailable');
93
+ return fetchRefStatuses(refStatusGraphql(repoRoot, context), handle.owner, handle.name, owned);
94
+ })();
95
+ for (const n of owned) {
96
+ const key = refStatusKey(repoRoot, n, context);
97
+ const tracked = refStatusFlights.size < REF_STATUS_CACHE_MAX;
98
+ const promise = batch.then(result => {
99
+ if (result.failed.includes(n))
100
+ return { reason: result.reason ?? 'GitHub could not be reached' };
101
+ const storedAt = Date.now();
102
+ const entry = result.resolved[n] ?? null;
103
+ const unknownSince = entry?.mergeable === 'unknown'
104
+ ? (refStatusCache.get(key)?.unknownSince ?? storedAt) : undefined;
105
+ const value = { resolved: entry, ...(unknownSince === undefined ? {} : { unknownSince }) };
106
+ if (tracked && refStatusFlights.get(key) === promise) {
107
+ refStatusCache.set(key, { at: storedAt, ...value });
108
+ while (refStatusCache.size > REF_STATUS_CACHE_MAX)
109
+ refStatusCache.delete(refStatusCache.keys().next().value);
110
+ }
111
+ return value;
112
+ }).finally(() => {
113
+ if (refStatusFlights.get(key) === promise)
114
+ refStatusFlights.delete(key);
115
+ });
116
+ if (tracked)
117
+ refStatusFlights.set(key, promise);
118
+ pending.set(n, promise);
119
+ }
120
+ }
121
+ return Promise.all(numbers.map(async (n) => [n, await pending.get(n)]));
122
+ }
123
+ /**
124
+ * Route-facing reference status.
125
+ */
126
+ export async function fetchGithubRefStatus(repoRoot, input) {
127
+ const context = githubContext(repoRoot);
128
+ const asPrs = sanitizeRefNumbers(input.prs);
129
+ const asIssues = sanitizeRefNumbers(input.issues);
130
+ if (productEnv('DRY_RUN') === '1')
131
+ return mockGithubRefStatus(asPrs, asIssues);
132
+ const wanted = [...new Set([...asPrs, ...asIssues])];
133
+ const resolved = { prs: {}, issues: {} };
134
+ const rechecks = [];
135
+ const conflicts = [];
136
+ const file = (number, entry, unknownSince) => {
137
+ rechecks.push(refStatusRecheckAfter(entry, unknownSince));
138
+ if (!entry)
139
+ return;
140
+ resolved[entry.kind === 'pr' ? 'prs' : 'issues'][number] = entry.status;
141
+ if (entry.mergeable === 'conflicting')
142
+ conflicts.push(number);
143
+ };
144
+ const misses = [];
145
+ const now = Date.now();
146
+ for (const n of wanted) {
147
+ const hit = refStatusCache.get(refStatusKey(repoRoot, n, context));
148
+ if (!hit || now - hit.at >= refStatusTtl(hit.resolved, hit.unknownSince, now))
149
+ misses.push(n);
150
+ else
151
+ file(n, hit.resolved, hit.unknownSince);
152
+ }
153
+ if (misses.length === 0) {
154
+ return {
155
+ available: true,
156
+ prs: resolved.prs,
157
+ issues: resolved.issues,
158
+ conflicts,
159
+ recheckAfterMs: batchRecheckAfter(rechecks),
160
+ };
161
+ }
162
+ try {
163
+ const entries = await sharedRefStatusMisses(repoRoot, misses, context);
164
+ let failure;
165
+ for (const [n, result] of entries) {
166
+ if ('reason' in result)
167
+ failure ??= result.reason;
168
+ else
169
+ file(n, result.resolved, result.unknownSince);
170
+ }
171
+ if (failure !== undefined) {
172
+ return {
173
+ available: false,
174
+ reason: failure,
175
+ recheckAfterMs: REF_STATUS_RETRY_MS,
176
+ };
177
+ }
178
+ return {
179
+ available: true,
180
+ prs: resolved.prs,
181
+ issues: resolved.issues,
182
+ conflicts,
183
+ recheckAfterMs: batchRecheckAfter(rechecks),
184
+ };
185
+ }
186
+ catch (err) {
187
+ const message = err instanceof Error ? err.message : String(err);
188
+ return {
189
+ available: false,
190
+ reason: /ENOENT/.test(message)
191
+ ? 'gh CLI not found — install it and run `gh auth login`'
192
+ : firstLine(message),
193
+ recheckAfterMs: REF_STATUS_RETRY_MS,
194
+ };
195
+ }
196
+ }
197
+ function refStatusKey(repoRoot, number, context = githubContext(repoRoot)) {
198
+ return `${context.key}\0#${number}`;
199
+ }
200
+ function sanitizeRefNumbers(numbers) {
201
+ return [...new Set(numbers ?? [])].filter((n) => Number.isInteger(n) && n > 0).slice(0, GH_REF_STATUS_MAX);
202
+ }
203
+ function mockGithubRefStatus(prs, issues) {
204
+ const catalog = mockGithub();
205
+ const byPr = new Map(catalog.prs.map((p) => [p.number, p]));
206
+ const byIssue = new Set(catalog.issues.map((i) => i.number));
207
+ const out = { available: true, prs: {}, issues: {}, recheckAfterMs: CACHE_MS };
208
+ for (const n of prs) {
209
+ const pr = byPr.get(n);
210
+ if (pr) {
211
+ out.prs[n] = derivePrReferenceStatus({
212
+ state: 'OPEN',
213
+ isDraft: pr.isDraft,
214
+ reviewDecision: null,
215
+ checks: (pr.checks ?? null),
216
+ });
217
+ }
218
+ }
219
+ for (const n of issues)
220
+ if (byIssue.has(n))
221
+ out.issues[n] = 'open';
222
+ return out;
223
+ }
224
+ //# sourceMappingURL=github-ref-status.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"github-ref-status.js","sourceRoot":"","sources":["../../../src/server/forge/github-ref-status.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,2BAA2B,CAAC;AACvD,OAAO,EAAE,aAAa,EAAsB,MAAM,iBAAiB,CAAC;AACpE,OAAO,EACL,QAAQ,EACR,SAAS,EACT,UAAU,EACV,gBAAgB,EAChB,uBAAuB,GACxB,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EACL,uBAAuB,EACvB,gBAAgB,EAChB,iBAAiB,GAIlB,MAAM,+BAA+B,CAAC;AAEvC,MAAM,cAAc,GAAG,IAAI,GAAG,EAG3B,CAAC;AACJ,MAAM,oBAAoB,GAAG,GAAG,CAAC;AAGjC,MAAM,gBAAgB,GAAG,IAAI,GAAG,EAAoC,CAAC;AAErE,yFAAyF;AACzF,MAAM,UAAU,6BAA6B;IAC3C,cAAc,CAAC,KAAK,EAAE,CAAC;IACvB,gBAAgB,CAAC,KAAK,EAAE,CAAC;AAC3B,CAAC;AAED,mEAAmE;AACnE,MAAM,UAAU,4BAA4B,CAC1C,QAAgB,EAChB,OAA2C;IAE3C,KAAK,MAAM,CAAC,MAAM,EAAE,QAAQ,CAAC,IAAI,OAAO,EAAE,CAAC;QACzC,cAAc,CAAC,GAAG,CAAC,YAAY,CAAC,QAAQ,EAAE,MAAM,CAAC,EAAE,EAAE,EAAE,EAAE,IAAI,CAAC,GAAG,EAAE,EAAE,QAAQ,EAAE,CAAC,CAAC;IACnF,CAAC;AACH,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,eAAe,C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AAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;IAC5D,MAAM,OAAO,GAAG,IAAI,GAAG,CAAC,OAAO,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;IAC7D,MAAM,GAAG,GAAwB,EAAE,SAAS,EAAE,IAAI,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,cAAc,EAAE,QAAQ,EAAE,CAAC;IACpG,KAAK,MAAM,CAAC,IAAI,GAAG,EAAE,CAAC;QACpB,MAAM,EAAE,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;QACvB,IAAI,EAAE,EAAE,CAAC;YACP,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,uBAAuB,CAAC;gBACnC,KAAK,EAAE,MAAM;gBACb,OAAO,EAAE,EAAE,CAAC,OAAO;gBACnB,cAAc,EAAE,IAAI;gBACpB,MAAM,EAAE,CAAC,EAAE,CAAC,MAAM,IAAI,IAAI,CAAgB;aAC3C,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IACD,KAAK,MAAM,CAAC,IAAI,MAAM;QAAE,IAAI,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC;YAAE,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,MAAM,CAAC;IACnE,OAAO,GAAG,CAAC;AACb,CAAC"}
@@ -1,209 +1,22 @@
1
+ import { type GithubRepoRef } from './github-shared.ts';
2
+ import type { ForgeDriver } from './types.ts';
1
3
  export type { RepoHandleDiscovery } from './repo-handle-discovery.ts';
2
4
  export { createDraftPr, buildPrBody } from './draft-pr.ts';
3
- import type { ArchivePullRequestIdentity, MergedPullRequest } from '../../contract/index.js';
4
5
  export { parseOwnerName } from './github-cli.ts';
5
6
  export { __clearRepoHandleCacheForTests, discoverRepoHandle, forgetRepoHandle, resolveRepoHandle } from './github-repo-handle.ts';
6
- import { type GithubCommentCountsData, type GithubItemResponse } from '../../contract/index.js';
7
7
  export { normalizeMergeState } from './github-merge-state.ts';
8
8
  export { fetchTimelinePages, ghTimelineEventSchema, normalizeEvents, TIMELINE_BUDGET_MS, TIMELINE_EVENT_CAP, TIMELINE_EVENT_KINDS, TIMELINE_MAX_PAGES, TIMELINE_MIN_PAGE_MS, } from './github-timeline.ts';
9
- import { type GithubRepoRef, type GraphqlRunner } from './github-shared.ts';
9
+ export { refNumberFromUrl } from '../../contract/index.js';
10
10
  export { detectGithubCached, ghCheckRunSchema, ghFailureReason, ghGraphqlArgs, HEALTH_AVAILABILITY_TTL_MS, rollupToChecks, type GithubData, type GithubItem, type GithubRepoRef, type GraphqlRunner, } from './github-shared.ts';
11
11
  export { fetchGithubPrDiff, fetchPrFilePages, GH_PR_DIFF_FILE_CAP, GH_PR_DIFF_JSON_CAP, GH_PR_PATCH_CAP, GithubPrNotFoundError, type PrFilesPageRunner, } from './github-pr-diff.ts';
12
12
  export { fetchGithub, fetchGithubProjects, fetchListConnection, GH_GRAPHQL_PAGE_MAX, GH_MAX_LIMIT, GH_SEARCH_MAX, searchGithubItems, viewGithubItem, type GithubPageRequest, type ListNode, type ListSide, } from './github-list.ts';
13
- import { type ChecksGlyph } from './github-checks.ts';
14
13
  export { __clearChecksCacheForTests, COMMIT_CHECKS_CHUNK, fetchCommitChecks, fetchGithubChecks, fetchPrChecks, GH_CHECKS_MAX, type ChecksGlyph, type GithubChecksData, } from './github-checks.ts';
15
- import type { ForgeComment, ForgeCommentsData, ForgeDriver, ForgePrMergeState } from './types.ts';
16
- /** First 200 thread entries, then `truncated`; each body sliced to 8 000 chars (same cap as
17
- * item bodies). */
18
- export declare const THREAD_ENTRY_CAP = 200;
19
- /** `gh api …/issues/{n}/comments` JSON → `ForgeComment[]`. Exported for unit tests. */
20
- export declare function normalizeComments(raw: unknown): ForgeComment[];
21
- /** `gh api …/pulls/{n}/reviews` JSON → `ForgeComment[]`. Reviews with an empty body AND state
22
- * COMMENTED/PENDING carry no signal in a flat thread and are dropped; the rest map to
23
- * `kind: 'review'` (Q4). Exported for unit tests. */
24
- export declare function normalizeReviews(raw: unknown): ForgeComment[];
25
- /** Merge comment/review lists chronologically (oldest first) and apply the entry cap. Exported
26
- * for unit tests. */
27
- export declare function mergeThread(parts: ForgeComment[][], cap?: number): {
28
- comments: ForgeComment[];
29
- truncated: boolean;
30
- };
31
- /** Test-only: drop the per-thread cache so cases don't leak state into each other. */
32
- export declare function __clearCommentsCacheForTests(): void;
33
- export declare function forgetGithubItem(repoRoot: string, kind: 'issue' | 'pr', number: number): void;
34
- /** Test-only: drop the single-item cache. */
35
- export declare function __clearGithubItemCacheForTests(): void;
36
- export declare function fetchGithubItem(repoRoot: string, kind: 'issue' | 'pr', number: number, refresh?: boolean): Promise<GithubItemResponse>;
37
- /**
38
- * Comment counts for the given issue or PR numbers, in one aliased GraphQL query. A number GitHub
39
- * does not know is absent (unknown), never 0. Degrades to `{ available: false, reason }` — never a
40
- * throw. Numbers are de-duplicated, validated and capped at `GITHUB_COMMENT_COUNTS_MAX`.
41
- */
42
- export declare function fetchGithubCommentCounts(repoRoot: string, kind: 'issue' | 'pr', numbers: number[], refresh?: boolean): Promise<GithubCommentCountsData>;
43
- /** Where a referenced PR or issue stands. Mirrored by `referenceStatusSchema` in the contract —
44
- * see there for why PR `closed` and issue `completed` are separate words. */
45
- export type ReferenceStatus = 'draft' | 'review-required' | 'changes-requested' | 'checks-pending' | 'checks-failing' | 'ready' | 'merged' | 'closed' | 'open' | 'completed' | 'not-planned';
46
- export type GithubRefStatusData = {
47
- available: true;
48
- prs: Record<number, ReferenceStatus>;
49
- issues: Record<number, ReferenceStatus>;
50
- /** The OPEN pull requests among them that do not merge into their base — the second axis,
51
- * never folded into a status. Optional on the wire, and absent means "nothing is known"
52
- * rather than "no conflicts"; see `conflicts` in the contract. */
53
- conflicts?: number[];
54
- /** When to ask again, or `null` when nothing here can change. See `recheckAfterMs` in the
55
- * contract for why the SERVER answers this. */
56
- recheckAfterMs: number | null;
57
- } | {
58
- available: false;
59
- reason: string;
60
- recheckAfterMs: number | null;
61
- };
62
- /** Numbers per kind in one ref-status query — the same bound, and for the same reasons, as
63
- * `GH_CHECKS_MAX`: aliases resolve independently, and the query size stays finite. Taken from the
64
- * contract rather than restated, because the cockpit caps its batches by the same number and a
65
- * client that guessed high would have every chip in a batch 400 instead of losing its tail. */
66
- export declare const GH_REF_STATUS_MAX = 100;
67
- /**
68
- * Derive whose action is pending: terminal, draft, pending checks, current requested changes,
69
- * failing checks, review, then ready. Use dated review/work evidence; mergeability remains a
70
- * separate axis.
71
- */
72
- export declare function derivePrReferenceStatus(pr: {
73
- state: string;
74
- isDraft?: boolean | null | undefined;
75
- reviewDecision?: string | null | undefined;
76
- checks: ChecksGlyph;
77
- /** ISO-8601 commit date of the head commit. `committedDate`, not a push time: GitHub's
78
- * `pushedDate` is deprecated and comes back null on new PRs. */
79
- headCommittedAt?: string | null | undefined;
80
- /** How many parents the head commit has. 2+ means a MERGE — "Update branch" pulling the base in,
81
- * not work on the review. See `answered` below. Absent reads as an ordinary commit: the push
82
- * rule is the common path and must not switch off on a field GitHub declined to send. */
83
- headParentCount?: number | null | undefined;
84
- /** ISO-8601 `committedDate` of the head's FIRST parent, which on a merge is the branch's previous
85
- * tip — the newest commit that is actual work. Only read when the head is a merge. */
86
- headFirstParentCommittedAt?: string | null | undefined;
87
- /** ISO-8601 `submittedAt` of the most recent CHANGES_REQUESTED review, when there is one. */
88
- changesRequestedAt?: string | null | undefined;
89
- /** Is a reviewer currently ON THE HOOK — `reviewRequests.totalCount > 0`? True after the author
90
- * clicks re-request, which is the one thing that says so while `reviewDecision` still reads
91
- * `CHANGES_REQUESTED` — but also true of a reviewer asked long ago who never looked, hence
92
- * `reviewRequestedAt`. */
93
- reviewRequested?: boolean | null;
94
- /** ISO-8601 `createdAt` of the most recent `ReviewRequestedEvent`, which is WHEN the standing
95
- * request was made. Only a request younger than the review can be an answer to it. */
96
- reviewRequestedAt?: string | null;
97
- }): ReferenceStatus;
98
- /**
99
- * Whether this pull request's branch merges into its base — the OTHER axis, kept out of
100
- * `derivePrReferenceStatus` on purpose (see `conflicts` in the contract).
101
- *
102
- * Three values, and the third is the one that matters. GitHub does not store mergeability; it
103
- * COMPUTES it when asked, and answers `UNKNOWN` while the background job runs — which is the
104
- * normal answer for the first seconds after every push, and therefore for exactly the moment a
105
- * cockpit is most likely to be looking. `UNKNOWN` means *we were not told*, never *it is clean*,
106
- * and the caller must be able to tell those apart: it is what decides how soon to ask again
107
- * (`refStatusTtl`), and answering it as "not conflicting" with a one-minute TTL is precisely how a
108
- * conflicting pull request came to sit there wearing "Ready to merge".
109
- *
110
- * `undefined` for anything the question does not apply to: an issue, and a merged or closed pull
111
- * request (GitHub says `UNKNOWN` for those too, forever, and a terminal PR has no conflict left to
112
- * resolve — a merged PR wearing a conflict chip is a lie the state alone rules out).
113
- */
114
- export type Mergeability = 'mergeable' | 'conflicting' | 'unknown';
115
- export declare function mergeabilityOf(state: string, mergeable: string | null | undefined): Mergeability | undefined;
116
- /**
117
- * An issue's two signals as one word. `NOT_PLANNED` is kept apart from `completed` because they
118
- * are opposite outcomes — "we did it" vs "we won't" — and a task whose issue was declined must
119
- * not read as a task that landed.
120
- */
121
- export declare function deriveIssueReferenceStatus(issue: {
122
- state: string;
123
- stateReason?: string | null | undefined;
124
- }): ReferenceStatus;
125
- /** What one number turned out to be, and where it stands. `kind` is the forge's answer, not the
126
- * caller's guess — see `refStatusQuery`. */
127
- export interface ResolvedReference {
128
- kind: 'pr' | 'issue';
129
- status: ReferenceStatus;
130
- /** Where this pull request stands on the OTHER axis, or absent when the question does not
131
- * apply (an issue, a merged or closed PR). Deliberately not folded into `status`; see
132
- * `mergeabilityOf`, and `conflicts` in the contract. `unknown` is kept as a value rather than
133
- * collapsed into "not conflicting", because it is the difference between an answer and a
134
- * question GitHub has not finished answering. */
135
- mergeable?: Mergeability;
136
- }
137
- /**
138
- * The outcome of one batched lookup. `failed` is what separates *this number is not in the
139
- * repository* from *we could not ask about this number* — an absence and a failure, which look
140
- * identical in a `number → status` map and mean opposite things to a reader ("that reference is
141
- * bogus" vs "GitHub is down"). Keeping them apart is what stops a transient error being cached,
142
- * and shown, as "not found".
143
- */
144
- export interface RefStatusBatch {
145
- resolved: Record<number, ResolvedReference>;
146
- /** Numbers whose chunk threw. Nothing is known about them either way. */
147
- failed: number[];
148
- /** First failure's message, for the payload's `reason`. */
149
- reason?: string;
150
- }
151
- /**
152
- * Status per NUMBER, resolved to whatever that number actually is.
153
- *
154
- * Batched and aliased like `fetchPrChecks`: one subprocess per chunk, each alias resolving
155
- * independently, and a number the forge does not have simply staying absent from `resolved` (its
156
- * chip then renders neutral, as it did before this seam existed). A failed chunk costs only its
157
- * own numbers, and says so rather than letting them look absent. Exported for tests; `runGraphql`
158
- * is injected so this is testable without shelling out.
159
- */
160
- export declare function fetchRefStatuses(runGraphql: GraphqlRunner, owner: string, name: string, numbers: number[], chunkSize?: number): Promise<RefStatusBatch>;
161
- /** Test-only: drop the per-reference cache so cases don't leak state into each other. */
162
- export declare function __clearRefStatusCacheForTests(): void;
163
- /** Test-only: warm the cache the way the lazy route would have, so a reader can be tested
164
- * without a forge behind it. */
165
- export declare function __seedRefStatusCacheForTests(repoRoot: string, entries: Array<[number, ResolvedReference]>): void;
166
- /**
167
- * Invalidate one reference after a known mutation. Let the next forge read establish status
168
- * rather than caching a guessed result.
169
- */
170
- export declare function forgetRefStatus(repoRoot: string, number: number): void;
171
- /**
172
- * Everything the cache ALREADY knows about these numbers. Never spawns `gh`, never awaits.
173
- *
174
- * This is what lets a status ride along with the rows that carry the references, instead of the
175
- * cockpit fetching it separately a moment later: the run index reads whatever is warm and ships
176
- * it, and a cold entry is simply absent — the lazy `/github/ref-status` route stays the thing that
177
- * actually goes and asks.
178
- *
179
- * Because it cannot cost anything, the caller may pass a SUPERSET of the numbers it will really
180
- * display. That matters: deciding which of a run's references a chip shows is the cockpit's rule
181
- * (#407, #526), deliberately not duplicated server-side, and a cache read does not need to know —
182
- * it can look up every number a run mentions and let the client pick.
183
- */
184
- export declare function readCachedRefStatuses(repoRoot: string, numbers: Iterable<number>): {
185
- prs: Record<number, ReferenceStatus>;
186
- issues: Record<number, ReferenceStatus>;
187
- };
188
- export { refNumberFromUrl } from '../../contract/index.js';
14
+ export { __clearCommentsCacheForTests, __clearGithubItemCacheForTests, fetchGithubCommentCounts, fetchGithubComments, fetchGithubItem, forgetGithubItem, mergeThread, normalizeComments, normalizeReviews, THREAD_ENTRY_CAP, } from './github-comments.ts';
15
+ export { deriveIssueReferenceStatus, derivePrReferenceStatus, fetchRefStatuses, GH_REF_STATUS_MAX, mergeabilityOf, type GithubRefStatusData, type Mergeability, type ReferenceStatus, type RefStatusBatch, type ResolvedReference, } from './github-ref-status-derive.ts';
16
+ export { __clearRefStatusCacheForTests, __seedRefStatusCacheForTests, fetchGithubRefStatus, forgetRefStatus, readCachedRefStatuses, } from './github-ref-status.ts';
17
+ export { evictGithubProjectCaches, fetchMergedPullRequests, lookupMergedPullRequests, mergePreflightAllowed, } from './github-mutations.ts';
189
18
  /**
190
- * Route-facing reference status. Resolves the repo handle once, serves fresh cache entries,
191
- * queries only the misses, and degrades to `{ available: false, reason }` when `gh` or the handle
192
- * is unavailable — never a throw, never a 5xx.
193
- *
194
- * The two request lists are merged into ONE set of numbers: issues and pull requests share a
195
- * repository's numbering space, so a number is one thing and asking about it twice would be asking
196
- * the same question twice. What comes back is filed by what each number turned out to BE, which is
197
- * why a chip whose kind the cockpit guessed wrong still gets the right status.
19
+ * The GitHub forge driver — coordinates the sibling transport, list, comment, check, ref-status,
20
+ * and mutation modules behind the `ForgeDriver` seam.
198
21
  */
199
- export declare function fetchGithubRefStatus(repoRoot: string, input: {
200
- prs?: number[];
201
- issues?: number[];
202
- }): Promise<GithubRefStatusData>;
203
- export declare function fetchGithubComments(repoRoot: string, kind: 'issue' | 'pr', number: number, refresh?: boolean): Promise<ForgeCommentsData>;
204
- export declare function evictGithubProjectCaches(repoRoot: string): void;
205
- export declare function mergePreflightAllowed(current: ForgePrMergeState, overrideRules?: boolean): boolean;
206
22
  export declare function createGithubDriver(repoRoot: string, repoRef: GithubRepoRef | null): ForgeDriver;
207
- /** Strict archive authority: no partial GraphQL success, redirects, guessed identity or date. */
208
- export declare function fetchMergedPullRequests(runGraphql: GraphqlRunner, identities: readonly ArchivePullRequestIdentity[]): Promise<MergedPullRequest[]>;
209
- export declare function lookupMergedPullRequests(repoRoot: string, identities: ArchivePullRequestIdentity[], signal: AbortSignal): Promise<MergedPullRequest[]>;