@in-the-loop-labs/pair-review 5.2.0 → 5.2.1

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.
@@ -18,7 +18,7 @@ const { GitHubClient } = require('../github/client');
18
18
  const { normalizeRepository } = require('../utils/paths');
19
19
  const { findMainGitRoot } = require('../local-review');
20
20
  const { getConfigDir, getRepoPath, resolveRepoOptions, resolvePoolConfig, getRepoResetScript, resolveHostBinding, resolveBindingRepositoryFromPR, getRepoConfig, DEFAULT_CHECKOUT_TIMEOUT_MS } = require('../config');
21
- const { storedHostToOption, isDualHostRepoConfig } = require('../utils/host-resolution');
21
+ const { storedHostToOption, isDualHostRepoConfig, resolveRecordedHost, bindingRepositoryForHost } = require('../utils/host-resolution');
22
22
  const logger = require('../utils/logger');
23
23
  const { fireReviewStartedHook } = require('../hooks/payloads');
24
24
  const simpleGit = require('simple-git');
@@ -270,7 +270,49 @@ async function storePRData(db, prInfo, prData, diff, changedFiles, worktreePath,
270
270
  async function resolvePrHostBinding({ db, config, bindingRepository, owner, repo, prNumber, host, githubToken, deps = {} }) {
271
271
  const Client = deps.GitHubClient || GitHubClient;
272
272
  const repository = normalizeRepository(owner, repo);
273
- const repoConfig = getRepoConfig(config, bindingRepository);
273
+
274
+ // Apply host precedence FIRST, because the resolved host selects which config
275
+ // entry may be bound through: an exclusive alt entry that only
276
+ // `url_pattern`-claimed this owner/repo cannot serve a PR that lives on
277
+ // github.com. The caller's `bindingRepository` arrives already filtered
278
+ // against the host known at entry (the setup route and CLI both apply this
279
+ // rule), and that same key selects the repo's local configuration — path,
280
+ // checkout script, pool, reset script — as well as credentials. The local
281
+ // `hostBindingRepository` below re-applies the filter with the RECORDED host,
282
+ // which only this function resolves.
283
+ let effectiveHost;
284
+ let hostKnown = false;
285
+ let recordedHost;
286
+ if (host !== undefined) {
287
+ effectiveHost = host;
288
+ hostKnown = true;
289
+ recordedHost = host;
290
+ } else {
291
+ const prMetadataRepo = new PRMetadataRepository(db);
292
+ const recorded = await prMetadataRepo.getPRHostWithRecordedUrl(repository, prNumber);
293
+ if (recorded !== undefined) {
294
+ // resolveRecordedHost reads the stored host against the recorded html_url,
295
+ // which is what separates a pre-stamping row from a github.com one.
296
+ recordedHost = resolveRecordedHost(config, bindingRepository, recorded.host, recorded.recordedUrl);
297
+ // storedHostToOption applies the legacy-NULL convention: `undefined` means
298
+ // "host unknown" (leave hostKnown false → ambiguity/probe path), while a
299
+ // returned option object pins the host. It receives the RESOLVED host, not
300
+ // the raw column — a pre-stamping row whose recorded URL is on the alt host
301
+ // must fetch from there instead of being forced to github.com.
302
+ const storedOption = storedHostToOption(
303
+ config,
304
+ bindingRepositoryForHost(config, repository, bindingRepository, recordedHost),
305
+ recordedHost
306
+ );
307
+ if (storedOption !== undefined) {
308
+ effectiveHost = storedOption.host;
309
+ hostKnown = true;
310
+ }
311
+ }
312
+ }
313
+
314
+ const hostBindingRepository = bindingRepositoryForHost(config, repository, bindingRepository, recordedHost);
315
+ const repoConfig = getRepoConfig(config, hostBindingRepository);
274
316
  const configuredApiHost = (repoConfig && typeof repoConfig.api_host === 'string' && repoConfig.api_host)
275
317
  ? repoConfig.api_host
276
318
  : null;
@@ -289,34 +331,15 @@ async function resolvePrHostBinding({ db, config, bindingRepository, owner, repo
289
331
  if (binding.token) return binding;
290
332
  if (binding.apiHost === null) return githubToken;
291
333
  throw new Error(
292
- `No token configured for alt host ${binding.apiHost} (repo ${bindingRepository}). ` +
293
- `Configure repos["${bindingRepository}"].token or token_command.`
334
+ `No token configured for alt host ${binding.apiHost} (repo ${hostBindingRepository}). ` +
335
+ `Configure repos["${hostBindingRepository}"].token or token_command.`
294
336
  );
295
337
  };
296
338
 
297
- // Apply host precedence to decide whether we know the host up front.
298
- let effectiveHost;
299
- let hostKnown = false;
300
- if (host !== undefined) {
301
- effectiveHost = host;
302
- hostKnown = true;
303
- } else {
304
- const prMetadataRepo = new PRMetadataRepository(db);
305
- const storedHost = await prMetadataRepo.getPRHost(repository, prNumber);
306
- // storedHostToOption applies the legacy-NULL convention: `undefined` means
307
- // "host unknown" (leave hostKnown false → ambiguity/probe path), while a
308
- // returned option object pins the host.
309
- const storedOption = storedHostToOption(config, bindingRepository, storedHost);
310
- if (storedOption !== undefined) {
311
- effectiveHost = storedOption.host;
312
- hostKnown = true;
313
- }
314
- }
315
-
316
339
  // Fixed-binding path: host is known, OR the repo can only live on one host
317
340
  // (plain github / exclusive alt) so the ambiguity rule is unambiguous.
318
341
  if (hostKnown || !isDual) {
319
- const binding = resolveHostBinding(bindingRepository, config, hostKnown ? { host: effectiveHost } : {});
342
+ const binding = resolveHostBinding(hostBindingRepository, config, hostKnown ? { host: effectiveHost } : {});
320
343
  const client = new Client(clientArgFor(binding));
321
344
  const repoExists = await client.repositoryExists(owner, repo);
322
345
  if (!repoExists) {
@@ -329,7 +352,7 @@ async function resolvePrHostBinding({ db, config, bindingRepository, owner, repo
329
352
  // Probe path: dual repo, host unknown. Try the alt host first. `clientArgFor`
330
353
  // errors clearly if the alt binding has no token rather than silently probing
331
354
  // github.com disguised as the alt host.
332
- const altBinding = resolveHostBinding(bindingRepository, config, { host: configuredApiHost });
355
+ const altBinding = resolveHostBinding(hostBindingRepository, config, { host: configuredApiHost });
333
356
  const altClient = new Client(clientArgFor(altBinding));
334
357
  try {
335
358
  const prData = await altClient.fetchPullRequest(owner, repo, prNumber);
@@ -338,7 +361,7 @@ async function resolvePrHostBinding({ db, config, bindingRepository, owner, repo
338
361
  } catch (altErr) {
339
362
  if (altErr && altErr.status === 404) {
340
363
  logger.info(`PR #${prNumber} (${repository}) not found on alt host ${configuredApiHost}; falling back to github.com`);
341
- const githubBinding = resolveHostBinding(bindingRepository, config, { host: null });
364
+ const githubBinding = resolveHostBinding(hostBindingRepository, config, { host: null });
342
365
  const githubClient = new Client(clientArgFor(githubBinding));
343
366
  const prData = await githubClient.fetchPullRequest(owner, repo, prNumber);
344
367
  return { binding: githubBinding, prData, githubClient };
@@ -6,7 +6,7 @@ const { PRArgumentParser } = require('./github/parser');
6
6
  const logger = require('./utils/logger');
7
7
  const { rejectUrlLikeLocalReviewPath } = require('./utils/local-path-input');
8
8
  const { normalizeRepository } = require('./utils/paths');
9
- const { isDualHostRepo, hostSetupParamValue } = require('./utils/host-resolution');
9
+ const { setupHostParam } = require('./utils/host-resolution');
10
10
  const { buildInteractiveAnalysisConfig } = require('./interactive-analysis-config');
11
11
  const { version: packageVersion } = require('../package.json');
12
12
 
@@ -172,7 +172,7 @@ function storeAnalysisConfigRemote(port, analysisConfig, _deps) {
172
172
  * mirroring the cold-start precedence in handlePullRequest/handleLocalReview.
173
173
  * @param {string} [context.host] - Setup `?host=` value (alt api_host string or the
174
174
  * 'github' sentinel) so a pasted alt URL binds directly instead of re-probing.
175
- * Already resolved by the caller via `hostSetupParamValue`; omitted when null.
175
+ * Already resolved by the caller via `setupHostParam`; omitted when null.
176
176
  * @param {string} [context.provider] - CLI provider override to carry to the running server
177
177
  * @param {string} [context.model] - CLI model override to carry to the running server
178
178
  * @param {string} [context.scope] - Local-mode only: the `--scope` range to carry
@@ -340,10 +340,10 @@ async function attemptDelegation(config, flags, prArgs, _deps, options = {}) {
340
340
  const repository = normalizeRepository(prInfo.owner, prInfo.repo);
341
341
  const analysisConfigId = await handoffAnalysisConfigId(repository);
342
342
  // Thread the parsed host so a pasted alt URL binds directly (no re-probe) —
343
- // same mapping as the cold-start handlePullRequest path. bindingRepository
344
- // (from a url_pattern match) is the config key that determines dual-ness.
345
- const bindingRepository = prInfo.bindingRepository || repository;
346
- const host = hostSetupParamValue(prInfo.host, isDualHostRepo(config, bindingRepository));
343
+ // same mapping as the cold-start handlePullRequest path. See setupHostParam:
344
+ // a github.com URL announces itself whenever an api_host entry could
345
+ // otherwise claim this repo, so setup never falls back to the alt host.
346
+ const host = setupHostParam(config, prInfo.owner, prInfo.repo, prInfo.host);
347
347
  url = buildDelegationUrl(port, 'pr', {
348
348
  ...prInfo, analyze, councilId, analysisConfigId, host,
349
349
  provider: flags.provider, model: flags.model
@@ -9,7 +9,8 @@
9
9
  * here stops the copies from drifting.
10
10
  */
11
11
 
12
- const { getRepoConfig, isExclusiveAltHost, resolveHostBinding } = require('../config');
12
+ const { getRepoConfig, isExclusiveAltHost, resolveHostBinding, resolveBindingRepositoryFromPR } = require('../config');
13
+ const logger = require('./logger');
13
14
 
14
15
  /**
15
16
  * Translate a stored `pr_metadata.host` value into the `options` object for
@@ -38,6 +39,176 @@ function storedHostToOption(config, bindingRepository, storedHost) {
38
39
  return { host: storedHost };
39
40
  }
40
41
 
42
+ /**
43
+ * Normalise an EXPLICIT host hint (a setup request body, a `?host=` sentinel, a
44
+ * pasted URL's parsed host) against config. The explicit-hint sibling of
45
+ * {@link storedHostToOption}:
46
+ *
47
+ * - `undefined` → `undefined` (no hint; the ambiguity rule applies).
48
+ * - a URL string → unchanged; `resolveHostBinding` validates it against the
49
+ * repo's `api_host` and reports a mismatch.
50
+ * - `null` (github.com) on a plain or dual repo → `null`.
51
+ * - `null` on an EXCLUSIVE alt-host repo → `undefined` + a warning. The repo
52
+ * config asserts there is no github.com presence (`exclusive` defaults to
53
+ * true whenever `api_host` is set), so the hint contradicts configuration.
54
+ * Ignoring it matches `applyHostQueryCorrection` in `src/server.js`, which
55
+ * warns and ignores the same sentinel rather than acting on it, and keeps
56
+ * `resolveHostBinding`'s exclusive-null guard unreachable from user input —
57
+ * a clickable dashboard row must never 500 on a config contradiction.
58
+ *
59
+ * @param {Object} config - Application config
60
+ * @param {string} bindingRepository - `repos[...]` config-lookup key
61
+ * @param {string|null|undefined} host - The explicit hint
62
+ * @returns {string|null|undefined} The host to bind with
63
+ */
64
+ function explicitHostForBinding(config, bindingRepository, host) {
65
+ if (host !== null) return host;
66
+ if (!isExclusiveAltHost(getRepoConfig(config, bindingRepository))) return null;
67
+ logger.warn(
68
+ `Ignoring github.com host hint for "${bindingRepository}": it is configured as an ` +
69
+ 'exclusive alt-host repo (api_host without "exclusive": false), so it has no github.com ' +
70
+ 'binding. Set "exclusive": false on that repo if its PRs can live on github.com too.'
71
+ );
72
+ return undefined;
73
+ }
74
+
75
+ /**
76
+ * Resolve the host a RECORDED PR lives on, from its stored `host` column plus
77
+ * its recorded `html_url`.
78
+ *
79
+ * Mirrors the convention {@link storedHostToOption} encodes, which already says
80
+ * which stored NULLs are ambiguous: dual-host support shipped WITH host stamping
81
+ * (schema v50), so a NULL on a dual or plain repo means github.com. What a NULL
82
+ * cannot tell us is whether an older row predates stamping — and the recorded
83
+ * `html_url` settles that in ONE direction, since a URL that is not on
84
+ * github.com cannot be a github.com PR:
85
+ *
86
+ * - a URL string → that host (already stamped; nothing to infer).
87
+ * - NULL on a repo with no `api_host` → `null`; there is no other host.
88
+ * - NULL with a non-github `html_url` → the configured `api_host`. This is the
89
+ * pre-stamping row (or a repo that was exclusive-alt before gaining
90
+ * `exclusive: false`), so github.com would be wrong.
91
+ * - NULL otherwise → `null` (github.com), per the convention above.
92
+ * - `undefined` (no row) → `undefined`.
93
+ *
94
+ * One resolver serves links, navigation, AND binding on purpose: a row that
95
+ * renders a github.com icon must bind github.com when clicked, and the only way
96
+ * to guarantee that is to derive every one of them from the same value.
97
+ *
98
+ * @param {Object} config - Application config
99
+ * @param {string} bindingRepository - `repos[...]` config-lookup key
100
+ * @param {string|null|undefined} storedHost - Value from the `host` column
101
+ * @param {string|null|undefined} recordedUrl - The PR's stored `html_url`
102
+ * @returns {string|null|undefined} The host this PR is recorded on
103
+ */
104
+ function resolveRecordedHost(config, bindingRepository, storedHost, recordedUrl) {
105
+ if (storedHost !== null) return storedHost;
106
+ const apiHost = getConfiguredApiHost(config, bindingRepository);
107
+ if (!apiHost) return null;
108
+ if (typeof recordedUrl !== 'string' || !recordedUrl) return null;
109
+ let hostname;
110
+ try {
111
+ hostname = new URL(recordedUrl).hostname.toLowerCase();
112
+ } catch {
113
+ return null;
114
+ }
115
+ return (hostname === 'github.com' || hostname.endsWith('.github.com')) ? null : apiHost;
116
+ }
117
+
118
+ /**
119
+ * Resolve the `repos[...]` config key for a PR whose host is KNOWN.
120
+ *
121
+ * `resolveBindingRepositoryFromPR` answers "which entry serves this
122
+ * owner/repo?" with no host context: its slow path probes each entry's
123
+ * `url_pattern` against a URL built from that entry's OWN `api_host`, so a
124
+ * correctly anchored monorepo-style pattern claims EVERY owner/repo — including
125
+ * repos that exist only on github.com.
126
+ *
127
+ * `PRArgumentParser.parsePRUrl` already refuses the same overreach in the URL
128
+ * dimension (see its INVARIANT: "an `api_host`-bearing `url_pattern` must NEVER
129
+ * bind a canonical github.com / Graphite URL"), discarding the match so a
130
+ * pasted github.com URL resolves to its own `owner/repo`. This applies that
131
+ * settled rule to the owner/repo dimension, for the one case that can be
132
+ * decided safely:
133
+ *
134
+ * - `host` unknown or an alt-host string → the matched key, unchanged.
135
+ * - `host === null` (github.com) and the entry was claimed by its
136
+ * `url_pattern` probe (its key is not this PR's identity) and it is an
137
+ * EXCLUSIVE alt-host entry → the PR's own `owner/repo`. Such an entry has
138
+ * no github.com presence, so it describes neither this PR's API host nor
139
+ * its checkout.
140
+ * - a DUAL entry is kept for either host: `resolveHostBinding` has a
141
+ * first-class github.com binding for dual repos, so the entry does serve
142
+ * this PR (and its path/pool/reset config still applies).
143
+ * - a directly-keyed exclusive entry is kept: there the configuration itself
144
+ * asserts this exact repo is alt-host-only, and config wins over inference.
145
+ *
146
+ * Two entry points share the rule: this one resolves the key itself, while
147
+ * {@link bindingRepositoryForHost} filters a key a caller already holds (from a
148
+ * `url_pattern` parse, say) without re-deriving it.
149
+ *
150
+ * @param {string} owner
151
+ * @param {string} repo
152
+ * @param {Object} config
153
+ * @param {string|null|undefined} host
154
+ * @returns {string} The `repos[...]` config-lookup key
155
+ */
156
+ function resolveBindingRepositoryForHost(owner, repo, config, host) {
157
+ const identity = `${String(owner || '').toLowerCase()}/${String(repo || '').toLowerCase()}`;
158
+ return bindingRepositoryForHost(
159
+ config,
160
+ identity,
161
+ resolveBindingRepositoryFromPR(owner, repo, config),
162
+ host
163
+ );
164
+ }
165
+
166
+ /**
167
+ * Filter form of {@link resolveBindingRepositoryForHost}: applies the same rule
168
+ * to a binding key the caller already resolved. Used where re-deriving the key
169
+ * from owner/repo could lose it — a `url_pattern` entry whose captures do not
170
+ * reproduce its config key, for instance.
171
+ *
172
+ * @param {Object} config
173
+ * @param {string} identity - The PR's own normalized `owner/repo`
174
+ * @param {string} bindingRepository - Key the caller resolved
175
+ * @param {string|null|undefined} host
176
+ * @returns {string} The key to bind through
177
+ */
178
+ function bindingRepositoryForHost(config, identity, bindingRepository, host) {
179
+ if (host !== null) return bindingRepository;
180
+ if (String(bindingRepository).toLowerCase() === String(identity).toLowerCase()) return bindingRepository;
181
+ return isExclusiveAltHost(getRepoConfig(config, bindingRepository)) ? identity : bindingRepository;
182
+ }
183
+
184
+ /**
185
+ * The single mapping from a PR's KNOWN host to the setup `?host=` param value.
186
+ * Used by every entry point that can name a PR's host up front: dashboard
187
+ * collection rows, recent-review rows, the pasted-URL flow, the CLI cold start,
188
+ * and single-port delegation.
189
+ *
190
+ * - an alt-host string → that string (setup binds it directly, no probe).
191
+ * - `null` (github.com) with ANY `api_host`-bearing entry in play → the
192
+ * `'github'` sentinel. Staying silent here leaves setup on the ambiguity
193
+ * rule, which probes a dual repo and binds an exclusive one to its alt host;
194
+ * announcing it is also what lets setup apply the host-aware key rule above.
195
+ * - `null` on a plain github.com repo → `null` (omit; the ambiguity rule
196
+ * already binds github.com, so there is nothing to say).
197
+ * - unknown host → `null` (omit; the server derives it).
198
+ *
199
+ * @param {Object} config
200
+ * @param {string} owner
201
+ * @param {string} repo
202
+ * @param {string|null|undefined} host - The PR's resolved host
203
+ * @returns {string|null} `?host=` value, or null to omit
204
+ */
205
+ function setupHostParam(config, owner, repo, host) {
206
+ if (typeof host === 'string' && host) return host;
207
+ if (host !== null) return null;
208
+ const matched = resolveBindingRepositoryFromPR(owner, repo, config);
209
+ return getConfiguredApiHost(config, matched) ? 'github' : null;
210
+ }
211
+
41
212
  /**
42
213
  * A DUAL repo has an `api_host` configured but is NOT exclusive — its PRs may
43
214
  * live on github.com OR the alt host, so a host-unknown setup must probe.
@@ -122,36 +293,15 @@ function resolvePreflightBinding(bindingRepository, config, host) {
122
293
  return primary;
123
294
  }
124
295
 
125
- /**
126
- * Map a parser/stored host to the VALUE for the setup `?host=` query param, or
127
- * `null` to omit the param. Single source for the CLI cold-start, single-port
128
- * delegation, and (mirrored) the web paste flow — so a pasted alt URL binds the
129
- * alt host directly instead of re-probing at setup.
130
- *
131
- * - alt api_host URL string → that string (setup binds the alt host)
132
- * - `null` on a DUAL repo → the `'github'` sentinel (setup binds github.com,
133
- * no probe — avoids a loud failure if the alt host is down for a PR we KNOW
134
- * is on github)
135
- * - anything else (plain/exclusive repo, or unknown host) → `null` (omit; no
136
- * probe happens for those, and omitting avoids the exclusive-null throw)
137
- *
138
- * Callers append the value as `host=${encodeURIComponent(value)}`.
139
- *
140
- * @param {string|null|undefined} host - parser/stored host
141
- * @param {boolean} isDual - whether the repo is dual (github + alt-host)
142
- * @returns {string|null} the param value, or null to omit
143
- */
144
- function hostSetupParamValue(host, isDual) {
145
- if (typeof host === 'string' && host) return host;
146
- if (host === null && isDual) return 'github';
147
- return null;
148
- }
149
-
150
296
  module.exports = {
151
297
  storedHostToOption,
298
+ explicitHostForBinding,
299
+ resolveRecordedHost,
300
+ resolveBindingRepositoryForHost,
301
+ bindingRepositoryForHost,
302
+ setupHostParam,
152
303
  isDualHostRepo,
153
304
  isDualHostRepoConfig,
154
305
  getConfiguredApiHost,
155
306
  resolvePreflightBinding,
156
- hostSetupParamValue,
157
307
  };