@in-the-loop-labs/pair-review 5.2.0 → 5.2.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.
package/src/main.js CHANGED
@@ -3,7 +3,7 @@ const fs = require('fs');
3
3
  const path = require('path');
4
4
  const crypto = require('crypto');
5
5
  const { v4: uuidv4 } = require('uuid');
6
- const { loadConfig, getConfigDir, showWelcomeMessage, resolveDbName, resolveRepoOptions, resolvePoolConfig, getRepoResetScript, getRepoSkipBulkFetch, getRepoFetchTimeout, resolveLoadSkills, buildCouncilProviderOverrides } = require('./config');
6
+ const { loadConfig, getConfigDir, showWelcomeMessage, resolveDbName, resolveRepoOptions, resolvePoolConfig, getRepoResetScript, getRepoSkipBulkFetch, getRepoFetchTimeout, resolveLoadSkills, buildCouncilProviderOverrides, resolveBindingRepositoryFromPR } = require('./config');
7
7
  const { initializeDatabase, run, queryOne, query, migrateExistingWorktrees, WorktreeRepository, ReviewRepository, RepoSettingsRepository, GitHubReviewRepository, WorktreePoolRepository, CouncilRepository, CommentRepository, AnalysisRunRepository, PRMetadataRepository } = require('./database');
8
8
  const { PRArgumentParser } = require('./github/parser');
9
9
  const { GitHubClient } = require('./github/client');
@@ -26,7 +26,7 @@ const { getChangedFiles } = require('./routes/executable-analysis');
26
26
  const { safeParseJson } = require('./utils/safe-parse-json');
27
27
  const { includesBranch, parseScopeArg, VALID_SCOPE_RANGES, EMPTY_SCOPE_MESSAGE } = require('./local-scope');
28
28
  const { storePRData, resolvePrHostBinding, registerRepositoryLocation, findRepositoryPath } = require('./setup/pr-setup');
29
- const { isDualHostRepo, resolvePreflightBinding, hostSetupParamValue } = require('./utils/host-resolution');
29
+ const { resolvePreflightBinding, setupHostParam, bindingRepositoryForHost } = require('./utils/host-resolution');
30
30
  const { fireReviewStartedHook } = require('./hooks/payloads');
31
31
  const { normalizeRepository, resolveRenamedFile, resolveRenamedFileOld } = require('./utils/paths');
32
32
  const { rejectUrlLikeLocalReviewPath } = require('./utils/local-path-input');
@@ -229,7 +229,8 @@ OPTIONS:
229
229
  The web UI also starts for the human reviewer.
230
230
  --model <name> Override the AI model. Claude Code is the default provider.
231
231
  Available models: opus, sonnet, haiku (Claude Code);
232
- also: fable-5-xhigh, fable-5-high, opus-5-xhigh,
232
+ also: fable-5.1-xhigh, fable-5.1-high,
233
+ fable-5-xhigh, fable-5-high, opus-5-xhigh,
233
234
  opus-5-high, opus-4.8-xhigh, opus-4.8-high,
234
235
  opus-4.7-xhigh, opus-4.7-high, opus-4.6-high,
235
236
  opus-4.6-1m, sonnet-5-xhigh, sonnet-5-high,
@@ -1154,6 +1155,38 @@ AI PROVIDERS:
1154
1155
  }
1155
1156
  }
1156
1157
 
1158
+ /**
1159
+ * Resolve the `repos[...]` config-lookup key for a PR named on the CLI.
1160
+ *
1161
+ * Shared by every in-process PR entry point (`handlePullRequest`,
1162
+ * `performHeadlessReview`, and the headless PR path) so they cannot drift. The
1163
+ * key drives the token/api_host binding AND the repo's local configuration
1164
+ * (path, checkout script, worktree pool, reset script), so both halves have to
1165
+ * agree on it.
1166
+ *
1167
+ * Two corrections over the raw parse result:
1168
+ * - `PRArgumentParser` deliberately drops `bindingRepository` for a canonical
1169
+ * github.com / Graphite URL, so resolve it from owner/repo in that case.
1170
+ * Without this a github.com PR served by a DUAL monorepo entry would lose
1171
+ * that entry's local configuration, and a bare PR number on a pattern-only
1172
+ * alt repo would preflight against the identity instead of its entry.
1173
+ * - The result is filtered by the PR's known host, so an EXCLUSIVE alt entry
1174
+ * that only `url_pattern`-claimed this owner/repo never binds a PR that
1175
+ * lives on github.com (see `bindingRepositoryForHost`).
1176
+ *
1177
+ * @param {{owner: string, repo: string, host?: string|null, bindingRepository?: string}} prInfo
1178
+ * @param {Object} config - Application configuration
1179
+ * @returns {string} The `repos[...]` config-lookup key
1180
+ */
1181
+ function resolveCliBindingRepository(prInfo, config) {
1182
+ return bindingRepositoryForHost(
1183
+ config,
1184
+ normalizeRepository(prInfo.owner, prInfo.repo),
1185
+ prInfo.bindingRepository || resolveBindingRepositoryFromPR(prInfo.owner, prInfo.repo, config),
1186
+ prInfo.host
1187
+ );
1188
+ }
1189
+
1157
1190
  /**
1158
1191
  * Handle pull request processing
1159
1192
  * @param {Array<string>} args - Command line arguments
@@ -1174,13 +1207,9 @@ async function handlePullRequest(args, config, db, flags = {}, poolLifecycle = n
1174
1207
  const parser = new PRArgumentParser(config);
1175
1208
  const prInfo = await parser.parsePRArguments(args);
1176
1209
 
1177
- // Resolve token via repo-aware host binding so alt-host and
1178
- // repo-scoped credentials are respected. When a per-repo
1179
- // `url_pattern` matched, prefer its `bindingRepository` — that's the
1180
- // matched `repos[...]` config key, which may differ from the
1181
- // captured `${owner}/${repo}` for monorepo-style patterns.
1182
- const repositoryForBinding = prInfo.bindingRepository
1183
- || normalizeRepository(prInfo.owner, prInfo.repo);
1210
+ // Resolve the config key via the shared helper so the token binding and the
1211
+ // repo's local configuration agree (see resolveCliBindingRepository).
1212
+ const repositoryForBinding = resolveCliBindingRepository(prInfo, config);
1184
1213
  // A pasted URL tells us the host up front (alt-host `url_pattern` match →
1185
1214
  // api_host string; github/graphite URL → null), so preflight the token
1186
1215
  // against that host. A bare number leaves host undefined → ambiguity rule,
@@ -1248,10 +1277,11 @@ async function handlePullRequest(args, config, db, flags = {}, poolLifecycle = n
1248
1277
  }
1249
1278
 
1250
1279
  // Thread the pasted URL's host to setup so it binds directly instead of
1251
- // probing (shared mapping — see hostSetupParamValue): an alt-host string
1252
- // forwards the api_host; a github URL on a DUAL repo forwards the 'github'
1253
- // sentinel; bare numbers / plain / exclusive repos omit it.
1254
- const hostParam = hostSetupParamValue(prInfo.host, isDualHostRepo(config, repositoryForBinding));
1280
+ // probing (shared mapping — see setupHostParam): an alt-host string forwards
1281
+ // the api_host; a github URL forwards the 'github' sentinel whenever an
1282
+ // api_host entry could otherwise claim this repo; bare numbers and plain
1283
+ // github repos omit it.
1284
+ const hostParam = setupHostParam(config, prInfo.owner, prInfo.repo, prInfo.host);
1255
1285
  if (hostParam) {
1256
1286
  url += (url.includes('?') ? '&' : '?') + `host=${encodeURIComponent(hostParam)}`;
1257
1287
  }
@@ -1354,12 +1384,10 @@ async function performHeadlessReview(args, config, db, flags, options, externalP
1354
1384
  }
1355
1385
  }
1356
1386
 
1357
- // Resolve host binding for the target repo (handles alt-host).
1358
- // Prefer `bindingRepository` (from url_pattern match) over the raw
1359
- // `${owner}/${repo}` since they can differ when one config entry
1360
- // serves many monorepo-shaped URLs.
1361
- const repositoryForBinding = prInfo.bindingRepository
1362
- || normalizeRepository(prInfo.owner, prInfo.repo);
1387
+ // Resolve the config key via the shared helper (see
1388
+ // resolveCliBindingRepository): it drives the host binding below AND this
1389
+ // PR's local path / checkout / pool / reset configuration.
1390
+ const repositoryForBinding = resolveCliBindingRepository(prInfo, config);
1363
1391
  // Preflight the token so a missing credential fails fast before any network
1364
1392
  // work. Tolerates a dual repo with only an alt token when the host is
1365
1393
  // unknown (the setup probe tries the alt host first).
@@ -2010,8 +2038,10 @@ async function preparePrHeadless(db, config, flags, prArgs, externalPoolLifecycl
2010
2038
  }
2011
2039
  }
2012
2040
 
2013
- const repositoryForBinding = prInfo.bindingRepository
2014
- || normalizeRepository(prInfo.owner, prInfo.repo);
2041
+ // Resolve the config key via the shared helper (see
2042
+ // resolveCliBindingRepository): the same key drives the host binding and this
2043
+ // PR's local path / checkout / pool / reset configuration.
2044
+ const repositoryForBinding = resolveCliBindingRepository(prInfo, config);
2015
2045
  // Preflight the token so a missing credential fails fast before any network
2016
2046
  // work. Tolerates a dual repo with only an alt token when the host is unknown
2017
2047
  // (the setup probe tries the alt host first).
@@ -3005,4 +3035,4 @@ if (require.main === module) {
3005
3035
  main();
3006
3036
  }
3007
3037
 
3008
- module.exports = { main, parseArgs, detectPRFromGitHubEnvironment, printCouncilList, handleHeadlessAnalysis, handleHeadlessDelegated, runHeadlessAnalysis, buildHeadlessJson, buildHeadlessErrorJson, emitHeadlessResult, resolveCliInstructions, startPoolBackgroundFetches, isPoolEntryDueForFetch, POOL_FETCH_TICK_MS, MAX_POOL_FETCH_BACKOFF_MS };
3038
+ module.exports = { main, parseArgs, detectPRFromGitHubEnvironment, printCouncilList, handleHeadlessAnalysis, handleHeadlessDelegated, runHeadlessAnalysis, buildHeadlessJson, buildHeadlessErrorJson, emitHeadlessResult, resolveCliInstructions, resolveCliBindingRepository, startPoolBackgroundFetches, isPoolEntryDueForFetch, POOL_FETCH_TICK_MS, MAX_POOL_FETCH_BACKOFF_MS };
@@ -21,7 +21,11 @@ const {
21
21
  modelMatches
22
22
  } = require('../ai');
23
23
  const { normalizeRepository } = require('../utils/paths');
24
- const { resolvePreflightBinding } = require('../utils/host-resolution');
24
+ const {
25
+ resolvePreflightBinding,
26
+ resolveRecordedHost,
27
+ resolveBindingRepositoryForHost
28
+ } = require('../utils/host-resolution');
25
29
  const {
26
30
  isRunningViaNpx,
27
31
  getGitHubToken,
@@ -347,23 +351,33 @@ router.get('/api/repos/:owner/:repo/links', async (req, res) => {
347
351
  const repository = normalizeRepository(owner, repo);
348
352
  const config = req.app.get('config') || {};
349
353
  // Resolve via bindingRepository so monorepo-style configs (one
350
- // `repos[...]` entry serving many captured owner/repo via
351
- // url_pattern) surface the right link config.
352
- const bindingRepository = resolveBindingRepositoryFromPR(owner, repo, config);
353
-
354
- // Per-PR host awareness: when the caller names a PR, look up its stored
355
- // host so a dual-host repo shows the correct link set (github links for a
356
- // github-hosted PR, the external link for an alt-hosted one). A missing
357
- // row leaves `host` undefined, which resolveRepoLinks treats as the
358
- // repo-level default — so non-dual repos are unaffected regardless.
354
+ // `repos[...]` entry serving many captured owner/repo via url_pattern)
355
+ // surface the right link config.
356
+ //
357
+ // Per-PR host awareness: when the caller names a PR, resolve the host it is
358
+ // recorded on so a dual-host repo shows the correct link set (github links
359
+ // for a github-hosted PR, the external link for an alt-hosted one), and an
360
+ // exclusive alt entry that only pattern-claimed this owner/repo does not
361
+ // lend its links to a PR proven to be on github.com. A missing row leaves
362
+ // `host` undefined (the repo-level default), while an unprovable legacy
363
+ // NULL resolves to `null` (github.com) — the same value the raw column
364
+ // carried, so `resolveRepoLinks` sees byte-identical input to before.
359
365
  let host;
360
366
  const prNumber = parseInt(req.query.number, 10);
361
367
  if (Number.isInteger(prNumber) && prNumber > 0) {
362
368
  const prMetadataRepo = new PRMetadataRepository(req.app.get('db'));
363
- const storedHost = await prMetadataRepo.getPRHost(repository, prNumber);
364
- if (storedHost !== undefined) host = storedHost;
369
+ const recorded = await prMetadataRepo.getPRHostWithRecordedUrl(repository, prNumber);
370
+ if (recorded !== undefined) {
371
+ host = resolveRecordedHost(
372
+ config,
373
+ resolveBindingRepositoryFromPR(owner, repo, config),
374
+ recorded.host,
375
+ recorded.recordedUrl
376
+ );
377
+ }
365
378
  }
366
379
 
380
+ const bindingRepository = resolveBindingRepositoryForHost(owner, repo, config, host);
367
381
  const links = resolveRepoLinks(config, bindingRepository, host);
368
382
  res.json({ repository, links });
369
383
  } catch (error) {
@@ -26,6 +26,8 @@ const {
26
26
  const { getAdapter } = require('../external');
27
27
  const { GitHubApiError } = require('../github/client');
28
28
  const logger = require('../utils/logger');
29
+ const { resolveBindingRepositoryFromPR } = require('../config');
30
+ const { resolveRecordedHost } = require('../utils/host-resolution');
29
31
 
30
32
  const router = express.Router();
31
33
 
@@ -136,15 +138,25 @@ async function executeSync({ db, config, review, source, _deps }) {
136
138
  );
137
139
  }
138
140
 
139
- // Look up the PR's stored host so a DUAL repo's alt-hosted PR binds to the
140
- // alt host (and its line-based anchoring path) rather than api.github.com.
141
- // Pass the raw stored value through to the adapter, which applies the
142
- // legacy-NULL convention against its resolved binding key. `undefined`
143
- // (no row / unknown) preserves the two-arg ambiguity behaviour.
141
+ // Look up the host the PR is recorded on so a DUAL repo's alt-hosted PR binds
142
+ // to the alt host (and its line-based anchoring path) rather than
143
+ // api.github.com. `resolveRecordedHost` reads the stored host plus the recorded
144
+ // html_url, which is what distinguishes a pre-stamping row from a github.com
145
+ // one; the adapter then applies the legacy-NULL convention against the binding
146
+ // key it resolves for that host. `undefined` (no row) preserves the two-arg
147
+ // ambiguity behaviour.
144
148
  let storedHost;
145
149
  if (Number.isInteger(review.pr_number)) {
146
150
  const prMetadataRepo = new PRMetadataRepository(db);
147
- storedHost = await prMetadataRepo.getPRHost(review.repository, review.pr_number);
151
+ const recorded = await prMetadataRepo.getPRHostWithRecordedUrl(review.repository, review.pr_number);
152
+ if (recorded !== undefined) {
153
+ storedHost = resolveRecordedHost(
154
+ config || {},
155
+ resolveBindingRepositoryFromPR(owner, repo, config || {}),
156
+ recorded.host,
157
+ recorded.recordedUrl
158
+ );
159
+ }
148
160
  }
149
161
 
150
162
  // Delegate credential resolution to the adapter so the route stays
@@ -18,6 +18,8 @@ const { query, run, withTransaction } = require('../database');
18
18
  const { GitHubClient } = require('../github/client');
19
19
  const { getGitHubToken, resolveHostBinding } = require('../config');
20
20
  const logger = require('../utils/logger');
21
+ const { resolveRepoLinks } = require('../links/repo-links');
22
+ const { resolveBindingRepositoryForHost, setupHostParam } = require('../utils/host-resolution');
21
23
 
22
24
  const router = express.Router();
23
25
 
@@ -235,6 +237,30 @@ async function getCachedRows(db, collection) {
235
237
  );
236
238
  }
237
239
 
240
+ /**
241
+ * Attach the host-aware repository link configuration consumed by the landing
242
+ * page, plus the `?host=` value its rows navigate with. Resolution is an
243
+ * in-memory config lookup, so this avoids per-row HTTP requests while keeping
244
+ * cached and refreshed responses identical.
245
+ *
246
+ * A row's `host` is authoritative here, unlike a legacy `pr_metadata` NULL:
247
+ * every refresh re-derives these rows, stamping NULL from the github.com search
248
+ * branch and the `api_host` from the alt-host sweep. Both the links and the
249
+ * navigation target are therefore resolved for that known host, through the
250
+ * same two helpers the setup route uses — so a row's action icon and its click
251
+ * always reach the system the PR actually lives on.
252
+ */
253
+ function attachRepoLinks(rows, config) {
254
+ return rows.map((row) => {
255
+ const bindingRepository = resolveBindingRepositoryForHost(row.owner, row.repo, config, row.host);
256
+ return {
257
+ ...row,
258
+ repo_links: resolveRepoLinks(config, bindingRepository, row.host),
259
+ setup_host: setupHostParam(config, row.owner, row.repo, row.host)
260
+ };
261
+ });
262
+ }
263
+
238
264
  /**
239
265
  * Register the GET (cached) and POST (refresh) routes for a single collection.
240
266
  * @param {Object} def - Collection definition
@@ -259,8 +285,9 @@ function registerCollection(def) {
259
285
 
260
286
  const db = req.app.get('db');
261
287
  const rows = await getCachedRows(db, cacheKey(name, team));
288
+ const prs = attachRepoLinks(rows, req.app.get('config') || {});
262
289
  const fetchedAt = rows.length > 0 ? rows[0].fetched_at : null;
263
- res.json({ success: true, prs: rows, fetched_at: fetchedAt });
290
+ res.json({ success: true, prs, fetched_at: fetchedAt });
264
291
  } catch (error) {
265
292
  logger.error(`Failed to fetch ${label}:`, error);
266
293
  res.status(500).json({ success: false, error: `Failed to fetch ${label}` });
@@ -344,13 +371,13 @@ function registerCollection(def) {
344
371
  });
345
372
 
346
373
  const rows = await getCachedRows(db, key);
374
+ const resolvedRows = attachRepoLinks(rows, config);
347
375
  const fetchedAt = rows.length > 0 ? rows[0].fetched_at : null;
348
376
  // `hosts` is additive; omit it entirely when every source is healthy (no
349
- // alt-host repos and a working github token) so the github-only happy-path
350
- // response shape is byte-identical to before. A skipped github source or
351
- // any alt-host status makes it appear.
377
+ // alt-host repos and a working github token) so the happy path gains no
378
+ // `hosts` key. A skipped github source or any alt-host status adds it.
352
379
  const allStatuses = sourceStatuses.concat(hosts);
353
- const payload = { success: true, prs: rows, fetched_at: fetchedAt };
380
+ const payload = { success: true, prs: resolvedRows, fetched_at: fetchedAt };
354
381
  if (allStatuses.length > 0) payload.hosts = allStatuses;
355
382
  res.json(payload);
356
383
  } catch (error) {
package/src/routes/pr.js CHANGED
@@ -26,8 +26,8 @@ const Analyzer = require('../ai/analyzer');
26
26
  const { v4: uuidv4 } = require('uuid');
27
27
  const fs = require('fs').promises;
28
28
  const path = require('path');
29
- const { resolveHostBinding, resolveBindingRepositoryFromPR, getWorktreeDisplayName, resolveLoadSkills, buildCouncilProviderOverrides, getSummaryEnabled, getTourEnabled } = require('../config');
30
- const { storedHostToOption, isDualHostRepo } = require('../utils/host-resolution');
29
+ const { resolveHostBinding, getWorktreeDisplayName, resolveLoadSkills, buildCouncilProviderOverrides, getSummaryEnabled, getTourEnabled, resolveBindingRepositoryFromPR } = require('../config');
30
+ const { storedHostToOption, resolveRecordedHost, resolveBindingRepositoryForHost, setupHostParam } = require('../utils/host-resolution');
31
31
  const { resolveHostName } = require('../links/repo-links');
32
32
  const { resolveHostListText } = require('../links/host-names');
33
33
  const { backgroundQueue } = require('../ai/background-queue');
@@ -140,28 +140,46 @@ module.exports._attachHunkHashes = attachHunkHashes;
140
140
  */
141
141
  async function resolveBindingForRequest(req, repository) {
142
142
  const config = req.app.get('config') || {};
143
- // `repository` here is the PR-identity `${owner}/${repo}`. For
144
- // monorepo-style configs the binding-key in `config.repos` can differ;
145
- // resolve it via `resolveBindingRepositoryFromPR` before looking up
146
- // the host binding so per-repo tokens/api_host/features apply.
143
+ // `repository` here is the PR-identity `${owner}/${repo}`. For monorepo-style
144
+ // configs the binding-key in `config.repos` can differ, so it is resolved
145
+ // through the shared helper before looking up the host binding — per-repo
146
+ // tokens/api_host/features then apply. The lookup is host-aware: an exclusive
147
+ // alt entry that only `url_pattern`-claimed this owner/repo cannot serve a PR
148
+ // proven to be on github.com, and must not bind it (same rule the dashboard
149
+ // rows and the setup route use).
147
150
  const [owner, repo] = String(repository).split('/');
148
- const bindingRepository = resolveBindingRepositoryFromPR(owner, repo, config);
149
151
 
150
152
  // PR-aware host resolution. Every caller is an `/:owner/:repo/:number` route,
151
- // so a per-PR host may already be stored. When a pr_metadata row exists, bind
152
- // to its stored host (github for NULL, the api_host string for an alt host);
153
- // when no row exists, fall back to the ambiguity rule (two-arg resolve). A
154
- // stale stored host (config changed) makes resolveHostBinding throw — that
155
- // surfaces to the route's error handler as a clear failure rather than a
156
- // silent bind to a dead host.
153
+ // so a per-PR host may already be recorded. `resolveRecordedHost` reads the
154
+ // stored host plus the recorded html_url, upgrading a NULL to the alt host
155
+ // only where the URL proves it — an unprovable legacy NULL resolves to `null`
156
+ // (github.com), the same value the raw column carried, so those reviews bind
157
+ // exactly as before. A stale stored host (config changed) makes
158
+ // resolveHostBinding throw — that surfaces to the route's error handler
159
+ // rather than a silent bind to a dead host.
157
160
  const prNumber = parseInt(req.params && req.params.number, 10);
158
- let hostOptions;
161
+ let recordedHost;
159
162
  if (Number.isInteger(prNumber) && prNumber > 0) {
160
163
  const prMetadataRepo = new PRMetadataRepository(req.app.get('db'));
161
- const storedHost = await prMetadataRepo.getPRHost(repository, prNumber);
162
- // Apply the legacy-NULL back-compat convention (see storedHostToOption).
163
- hostOptions = storedHostToOption(config, bindingRepository, storedHost);
164
+ const recorded = await prMetadataRepo.getPRHostWithRecordedUrl(repository, prNumber);
165
+ if (recorded !== undefined) {
166
+ recordedHost = resolveRecordedHost(
167
+ config,
168
+ resolveBindingRepositoryFromPR(owner, repo, config),
169
+ recorded.host,
170
+ recorded.recordedUrl
171
+ );
172
+ }
164
173
  }
174
+ const bindingRepository = resolveBindingRepositoryForHost(owner, repo, config, recordedHost);
175
+ // Bind the host the evidence resolved to, NOT the raw column: a pre-stamping
176
+ // row whose recorded URL is on the alt host resolves to that host, and
177
+ // reapplying its NULL here would force a github.com binding while the row's
178
+ // links point at the alt host. `storedHostToOption` still applies the
179
+ // legacy-NULL convention against the entry that survived the check above.
180
+ const hostOptions = recordedHost === undefined
181
+ ? undefined
182
+ : storedHostToOption(config, bindingRepository, recordedHost);
165
183
  const binding = resolveHostBinding(bindingRepository, config, hostOptions || {});
166
184
  if (binding.token) {
167
185
  return { binding, token: binding.token, bindingRepository };
@@ -1770,7 +1788,11 @@ router.post('/api/pr/:owner/:repo/:number/submit-review', async (req, res) => {
1770
1788
  // string=alt) so a dual-host repo names the system this PR was submitted
1771
1789
  // to rather than its repo-level default.
1772
1790
  const cfg = req.app.get('config') || {};
1773
- const hostName = resolveHostName(cfg, resolveBindingRepositoryFromPR(owner, repo, cfg), binding.host);
1791
+ const hostName = resolveHostName(
1792
+ cfg,
1793
+ resolveBindingRepositoryForHost(owner, repo, cfg, binding.host),
1794
+ binding.host
1795
+ );
1774
1796
  res.json({
1775
1797
  success: true,
1776
1798
  message: `${event === 'DRAFT' ? 'Draft review created' : 'Review submitted'} successfully ${event === 'DRAFT' ? 'on' : 'to'} ${hostName}`,
@@ -1967,15 +1989,11 @@ router.post('/api/parse-pr-url', (req, res) => {
1967
1989
  const result = parser.parsePRUrl(url);
1968
1990
 
1969
1991
  if (result) {
1970
- // Report whether the resolved repo is DUAL (github + alt-host). A github URL
1971
- // (host === null) for a dual repo must be forwarded to setup as an explicit
1972
- // github pick (the "github" sentinel) so it does not probe alt-first; for a
1973
- // plain or exclusive repo the client omits host (no probe / avoids the
1974
- // exclusive-null throw). Resolve the binding key first (url_pattern match
1975
- // supplies it; otherwise derive from owner/repo).
1992
+ // `setupHost` is the resolved `?host=` value for this URL (see
1993
+ // setupHostParam): an alt api_host string, the 'github' sentinel when any
1994
+ // api_host entry could otherwise claim this repo, or null to omit. Computed
1995
+ // here so the browser never has to reason about repo configuration.
1976
1996
  const safeConfig = config || {};
1977
- const bindingRepository = result.bindingRepository
1978
- || resolveBindingRepositoryFromPR(result.owner, result.repo, safeConfig);
1979
1997
  return res.json({
1980
1998
  valid: true,
1981
1999
  owner: result.owner,
@@ -1988,7 +2006,7 @@ router.post('/api/parse-pr-url', (req, res) => {
1988
2006
  // from owner/repo for monorepo-style url_pattern configs).
1989
2007
  host: result.host,
1990
2008
  bindingRepository: result.bindingRepository,
1991
- isDualHost: isDualHostRepo(safeConfig, bindingRepository)
2009
+ setupHost: setupHostParam(safeConfig, result.owner, result.repo, result.host)
1992
2010
  });
1993
2011
  }
1994
2012
 
@@ -15,8 +15,8 @@ const crypto = require('crypto');
15
15
  const { activeSetups, broadcastSetupProgress } = require('./shared');
16
16
  const { setupPRReview } = require('../setup/pr-setup');
17
17
  const { setupLocalReview } = require('../setup/local-setup');
18
- const { expandPath, resolveBindingRepositoryFromPR } = require('../config');
19
- const { resolvePreflightBinding } = require('../utils/host-resolution');
18
+ const { expandPath } = require('../config');
19
+ const { resolvePreflightBinding, explicitHostForBinding, resolveBindingRepositoryForHost } = require('../utils/host-resolution');
20
20
  const { queryOne, ReviewRepository } = require('../database');
21
21
  const { normalizeRepository } = require('../utils/paths');
22
22
  const { rejectUrlLikeLocalReviewPath } = require('../utils/local-path-input');
@@ -130,13 +130,20 @@ router.post('/api/setup/pr/:owner/:repo/:number', async (req, res) => {
130
130
 
131
131
  // GitHub token is required for PR setup. Resolve the binding key first so
132
132
  // monorepo-style `repos[...]` entries (matched via `url_pattern` named
133
- // captures) supply their per-repo token even when the captured owner/repo
134
- // differs from the config key.
135
- const repositoryForToken = resolveBindingRepositoryFromPR(owner, repo, config);
133
+ // captures) supply their per-repo token — and their path, checkout script,
134
+ // pool, and reset script — even when the captured owner/repo differs from
135
+ // the config key. The lookup is host-aware: an explicit github.com host
136
+ // rejects an EXCLUSIVE alt entry that only pattern-claimed this owner/repo,
137
+ // matching the parser's invariant that such an entry never binds a
138
+ // canonical github.com PR. Dual entries are kept for either host.
139
+ const repositoryForToken = resolveBindingRepositoryForHost(owner, repo, config, bodyHost);
140
+ // Then normalise the hint against the entry that survived: a github.com hint
141
+ // for a repo whose own config says alt-host-only is ignored with a warning.
142
+ const effectiveHost = explicitHostForBinding(config, repositoryForToken, bodyHost);
136
143
  // Preflight the credential. resolvePreflightBinding gates on ANY usable
137
144
  // binding — including a dual repo's alt-only token or a token pinned by an
138
145
  // explicit body host — so an alt-host setup isn't falsely 401'd.
139
- const preflightBinding = resolvePreflightBinding(repositoryForToken, config, bodyHost);
146
+ const preflightBinding = resolvePreflightBinding(repositoryForToken, config, effectiveHost);
140
147
  if (!preflightBinding.token) {
141
148
  return res.status(401).json({ error: 'GitHub token not configured' });
142
149
  }
@@ -226,7 +233,7 @@ router.post('/api/setup/pr/:owner/:repo/:number', async (req, res) => {
226
233
  githubToken,
227
234
  bindingRepository: repositoryForToken,
228
235
  config,
229
- host: bodyHost,
236
+ host: effectiveHost,
230
237
  poolLifecycle: req.app.get('poolLifecycle'),
231
238
  restoreMetadata,
232
239
  onProgress: (progress) => {
@@ -20,7 +20,7 @@ const { mergeInstructions } = require('../utils/instructions');
20
20
  const { GitWorktreeManager } = require('../git/worktree');
21
21
  const { GitHubClient } = require('../github/client');
22
22
  const { getGitHubToken, resolveHostBinding, resolveBindingRepositoryFromPR, resolveRepoOptions, resolveLoadSkills, buildCouncilProviderOverrides } = require('../config');
23
- const { storedHostToOption } = require('../utils/host-resolution');
23
+ const { storedHostToOption, resolveRecordedHost, resolveBindingRepositoryForHost } = require('../utils/host-resolution');
24
24
  const { setupStackPR } = require('../setup/stack-setup');
25
25
  const Analyzer = require('../ai/analyzer');
26
26
  const { getProviderClass, createProvider } = require('../ai/provider');
@@ -255,14 +255,27 @@ async function executeStackAnalysis(params) {
255
255
  // monorepo-style `url_pattern` configs (one `repos[...]` entry serves many
256
256
  // captured owner/repo pairs). The PR identity is still used for DB rows and
257
257
  // worktree identity.
258
- // Resolve the stack binding from the MAIN (trigger) PR's stored host so every
259
- // sibling is fetched from — and later stamped with — the same host. Stacks
260
- // don't span systems, so a dual repo's alt-hosted stack must not fall back to
261
- // github via the two-arg ambiguity rule. `storedHostToOption` applies the
262
- // legacy-NULL convention; `undefined` (no row) preserves the ambiguity rule.
263
- const mainStoredHost = await new PRMetadataRepository(db).getPRHost(repository, triggerPRNumber);
264
- const stackHostOption = storedHostToOption(config, bindingRepository, mainStoredHost);
265
- const stackBinding = deps.resolveHostBinding(bindingRepository, config, stackHostOption || {});
258
+ // Resolve the stack binding from the MAIN (trigger) PR's recorded host so
259
+ // every sibling is fetched from — and later stamped with — the same host.
260
+ // Stacks don't span systems, so a dual repo's alt-hosted stack must not fall
261
+ // back to github via the two-arg ambiguity rule. `storedHostToOption` applies
262
+ // the legacy-NULL convention; `undefined` (no row) preserves it.
263
+ //
264
+ // The HOST key is resolved separately from `bindingRepository` above: that
265
+ // one is this PR's config identity (worktree options, pool, reset script) and
266
+ // must not move, while an exclusive alt entry that only `url_pattern`-claimed
267
+ // this owner/repo cannot serve a stack proven to be on github.com.
268
+ const mainRecorded = await new PRMetadataRepository(db).getPRHostWithRecordedUrl(repository, triggerPRNumber);
269
+ const mainRecordedHost = mainRecorded === undefined
270
+ ? undefined
271
+ : resolveRecordedHost(config, bindingRepository, mainRecorded.host, mainRecorded.recordedUrl);
272
+ const stackBindingRepository = resolveBindingRepositoryForHost(owner, repo, config, mainRecordedHost);
273
+ // Bind the resolved host, not the raw column: a pre-stamping trigger PR whose
274
+ // recorded URL is on the alt host must keep the stack on the alt host.
275
+ const stackHostOption = mainRecordedHost === undefined
276
+ ? undefined
277
+ : storedHostToOption(config, stackBindingRepository, mainRecordedHost);
278
+ const stackBinding = deps.resolveHostBinding(stackBindingRepository, config, stackHostOption || {});
266
279
  const githubToken = stackBinding.token;
267
280
  const prDataMap = new Map();
268
281
  if (githubToken) {
@@ -17,6 +17,12 @@ const { activeAnalyses, reviewToAnalysisId, killProcesses, broadcastProgress } =
17
17
  const fs = require('fs').promises;
18
18
  const logger = require('../utils/logger');
19
19
  const { resolvePoolConfig } = require('../config');
20
+ const { resolveRepoLinks } = require('../links/repo-links');
21
+ const {
22
+ resolveRecordedHost,
23
+ resolveBindingRepositoryForHost,
24
+ setupHostParam
25
+ } = require('../utils/host-resolution');
20
26
 
21
27
  const router = express.Router();
22
28
 
@@ -140,6 +146,7 @@ router.get('/api/worktrees/recent', async (req, res) => {
140
146
  const limit = Math.min(parseInt(req.query.limit) || 10, 50);
141
147
  const before = req.query.before || null;
142
148
  const db = req.app.get('db');
149
+ const config = req.app.get('config') || {};
143
150
 
144
151
  // Fetch limit + 1 to determine hasMore
145
152
  const fetchCount = limit + 1;
@@ -152,10 +159,13 @@ router.get('/api/worktrees/recent', async (req, res) => {
152
159
  pm.pr_number,
153
160
  pm.title,
154
161
  pm.author,
162
+ pm.base_branch,
155
163
  pm.head_branch,
156
164
  pm.last_accessed_at,
157
165
  pm.created_at,
158
166
  json_extract(pm.pr_data, '$.html_url') as html_url,
167
+ json_extract(pm.pr_data, '$.head_sha') as head_sha,
168
+ pm.host,
159
169
  w.id as worktree_id,
160
170
  w.path as worktree_path,
161
171
  w.branch,
@@ -195,6 +205,27 @@ router.get('/api/worktrees/recent', async (req, res) => {
195
205
  }
196
206
  }
197
207
  }
208
+ const [owner, repo] = row.repository.split('/');
209
+ // Host stamping (schema v50) was never backfilled, so a stored NULL can
210
+ // mean "github.com" OR "recorded before stamping existed".
211
+ // `resolveRecordedHost` upgrades a NULL to the alt host only where the
212
+ // recorded html_url proves it; an unprovable legacy row resolves to
213
+ // `null` (github.com), the stored convention, rather than to a host this
214
+ // row's click would not bind. Links, navigation, and the /pr binding all
215
+ // derive from this one value.
216
+ const host = resolveRecordedHost(
217
+ config,
218
+ resolveBindingRepositoryForHost(owner, repo, config, undefined),
219
+ row.host,
220
+ row.html_url
221
+ );
222
+ // With the host settled, resolve links and navigation from it through the
223
+ // same helpers the setup route uses, so the row's icon and its click
224
+ // cannot reach different systems. /pr's applyHostQueryCorrection also
225
+ // stamps the value on the way through, healing the legacy NULL.
226
+ const bindingRepository = resolveBindingRepositoryForHost(owner, repo, config, host);
227
+ const repoLinks = resolveRepoLinks(config, bindingRepository, host);
228
+ const setupHost = setupHostParam(config, owner, repo, host);
198
229
  reviews.push({
199
230
  id: row.id,
200
231
  repository: row.repository,
@@ -202,10 +233,15 @@ router.get('/api/worktrees/recent', async (req, res) => {
202
233
  pr_title: row.title,
203
234
  author: row.author || null,
204
235
  head_branch: row.head_branch || row.branch || null,
236
+ base_branch: row.base_branch || null,
205
237
  last_accessed_at: row.last_accessed_at,
206
238
  created_at: row.created_at,
207
239
  storage_status: storageStatus,
208
240
  html_url: row.html_url || null,
241
+ head_sha: row.head_sha || null,
242
+ host: host,
243
+ setup_host: setupHost,
244
+ repo_links: repoLinks,
209
245
  review_id: row.review_id || null
210
246
  });
211
247
  }
package/src/server.js CHANGED
@@ -1,9 +1,10 @@
1
1
  // Copyright 2026 Tim Perkins (tjwp) | SPDX-License-Identifier: Apache-2.0
2
2
  const express = require('express');
3
3
  const path = require('path');
4
- const { loadConfig, getGitHubToken, resolveDbName, warnIfDevModeWithoutDbName, getRepoConfig, resolveBindingRepositoryFromPR, isExclusiveAltHost } = require('./config');
4
+ const { loadConfig, getGitHubToken, resolveDbName, warnIfDevModeWithoutDbName, getRepoConfig, isExclusiveAltHost } = require('./config');
5
5
  const { initializeDatabase, getDatabaseStatus, queryOne, run, PRMetadataRepository } = require('./database');
6
6
  const { normalizeRepository } = require('./utils/paths');
7
+ const { resolveBindingRepositoryForHost } = require('./utils/host-resolution');
7
8
  const { GlobalSettingsService } = require('./settings/global-settings-service');
8
9
  const { applyConfigOverrides, checkAllProviders } = require('./ai');
9
10
  const { checkAllChatProviders } = require('./chat/chat-providers');
@@ -79,8 +80,12 @@ async function applyHostQueryCorrection(db, config, owner, repo, repository, prN
79
80
  const targetHost = rawHost === 'github' ? null : rawHost;
80
81
 
81
82
  // Resolve the repo's config entry (handles monorepo-style keys matched via
82
- // url_pattern) to learn its configured api_host.
83
- const bindingRepo = resolveBindingRepositoryFromPR(owner, repo, config);
83
+ // url_pattern) to learn its configured api_host. Host-aware: an explicit
84
+ // github.com correction is authoritative — the dashboard row it came from was
85
+ // sourced from the github.com search, or the user pasted a github.com URL —
86
+ // so an exclusive alt entry that merely `url_pattern`-claimed this owner/repo
87
+ // is rejected here too, and the correction is accepted instead of dropped.
88
+ const bindingRepo = resolveBindingRepositoryForHost(owner, repo, config, targetHost);
84
89
  const repoConfig = getRepoConfig(config, bindingRepo);
85
90
  const configuredApiHost = (repoConfig && typeof repoConfig.api_host === 'string' && repoConfig.api_host)
86
91
  ? repoConfig.api_host