@in-the-loop-labs/pair-review 5.1.1 → 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.
Files changed (41) hide show
  1. package/README.md +12 -4
  2. package/package.json +3 -2
  3. package/plugin/.claude-plugin/plugin.json +1 -1
  4. package/plugin-code-critic/.claude-plugin/plugin.json +1 -1
  5. package/plugin-pair-loop/.claude-plugin/plugin.json +1 -1
  6. package/public/index.html +6 -2
  7. package/public/js/index.js +251 -73
  8. package/public/js/repo-links.js +60 -11
  9. package/src/ai/index.js +1 -0
  10. package/src/ai/omp/review-config.yml +13 -0
  11. package/src/ai/omp-provider.js +279 -0
  12. package/src/ai/pi-format.js +535 -0
  13. package/src/ai/pi-provider.js +38 -963
  14. package/src/ai/pi-style-provider.js +526 -0
  15. package/src/ai/provider.js +2 -0
  16. package/src/chat/chat-providers.js +34 -11
  17. package/src/chat/omp-bridge.js +111 -0
  18. package/src/chat/pi-bridge.js +42 -34
  19. package/src/chat/session-manager.js +30 -4
  20. package/src/config.js +32 -3
  21. package/src/database.js +24 -0
  22. package/src/external/github-adapter.js +8 -10
  23. package/src/links/host-names.js +200 -0
  24. package/src/local-review.js +7 -3
  25. package/src/main.js +72 -23
  26. package/src/review-config.js +81 -5
  27. package/src/routes/config.js +42 -12
  28. package/src/routes/external-comments.js +18 -6
  29. package/src/routes/github-collections.js +32 -5
  30. package/src/routes/local.js +1 -1
  31. package/src/routes/pr.js +47 -28
  32. package/src/routes/setup.js +15 -8
  33. package/src/routes/stack-analysis.js +22 -9
  34. package/src/routes/worktrees.js +36 -0
  35. package/src/server.js +8 -3
  36. package/src/settings/registry.js +1 -1
  37. package/src/setup/local-setup.js +5 -3
  38. package/src/setup/pr-setup.js +49 -26
  39. package/src/single-port.js +7 -7
  40. package/src/utils/host-resolution.js +177 -27
  41. package/src/utils/local-path-input.js +64 -8
@@ -0,0 +1,200 @@
1
+ // Copyright 2026 Tim Perkins (tjwp) | SPDX-License-Identifier: Apache-2.0
2
+ /**
3
+ * Known PR Host Names
4
+ *
5
+ * Derives the list of code hosts pair-review will accept a pull request from,
6
+ * for use in copy that is rendered BEFORE any repository has been resolved —
7
+ * the landing-page PR input, the URL validation errors, and the
8
+ * "that's a URL, not a path" local-review error.
9
+ *
10
+ * `resolveHostName()` in ./repo-links.js answers the same question for a
11
+ * KNOWN repo. This module answers it for the whole configuration, which is
12
+ * what the pre-resolution surfaces need: at the point where a user is typing
13
+ * a URL there is no repo to look up yet.
14
+ *
15
+ * The list is derived, never hardcoded:
16
+ *
17
+ * - "GitHub" is always present. Unconfigured repos fall back to github.com
18
+ * with the top-level credentials, so github.com is always reachable.
19
+ * - "Graphite" appears only when `enable_graphite` is true. It defaults to
20
+ * false, so a default install must not advertise it.
21
+ * - Each distinct `repos[*].links.external.name` for a repo that also sets
22
+ * `api_host` — the alt-host display name (e.g. "Meteorite").
23
+ *
24
+ * Alt-host repos with no `links.external.name` resolve to "GitHub" via
25
+ * `resolveHostName` and are therefore de-duplicated away rather than
26
+ * appearing twice.
27
+ */
28
+
29
+ const { resolveHostName } = require('./repo-links');
30
+
31
+ const DEFAULT_HOST_NAME = 'GitHub';
32
+ const GRAPHITE_HOST_NAME = 'Graphite';
33
+
34
+ // Hostnames whose PR URLs are recognised even without a scheme. Alt hosts are
35
+ // appended from config by resolveUrlLikeHostnames().
36
+ const BUILTIN_PR_HOSTNAMES = Object.freeze([
37
+ 'github.com',
38
+ 'app.graphite.dev',
39
+ 'app.graphite.com'
40
+ ]);
41
+
42
+ /**
43
+ * Iterate every configured repo entry.
44
+ *
45
+ * `loadConfig()` lowercases the legacy `monorepos` map, merges it into `repos`,
46
+ * and deletes it, so for any loaded config that branch never fires — it is here
47
+ * only for raw/hand-built configs, mirroring `getRepoConfig`'s equivalent
48
+ * fallback.
49
+ *
50
+ * @param {Object} config
51
+ * @returns {Array<[string, Object]>} `[repoKey, repoEntry]` pairs
52
+ */
53
+ function configuredRepoEntries(config) {
54
+ const entries = [];
55
+ for (const section of [config.repos, config.monorepos]) {
56
+ if (!section || typeof section !== 'object') continue;
57
+ for (const [repoKey, repoEntry] of Object.entries(section)) {
58
+ if (!repoEntry || typeof repoEntry !== 'object') continue;
59
+ entries.push([repoKey, repoEntry]);
60
+ }
61
+ }
62
+ return entries;
63
+ }
64
+
65
+ /**
66
+ * True when a repo entry declares an alt host.
67
+ *
68
+ * @param {Object} repoEntry
69
+ * @returns {boolean}
70
+ */
71
+ function hasApiHost(repoEntry) {
72
+ return typeof repoEntry.api_host === 'string' && repoEntry.api_host.length > 0;
73
+ }
74
+
75
+ /**
76
+ * Resolve the ordered, de-duplicated list of host display names that
77
+ * pair-review can accept PR URLs for.
78
+ *
79
+ * @param {Object} [config] - Configuration object from loadConfig()
80
+ * @returns {string[]} Non-empty list, always starting with "GitHub"
81
+ */
82
+ function resolveKnownHostNames(config) {
83
+ const safeConfig = (config && typeof config === 'object') ? config : {};
84
+
85
+ const names = [DEFAULT_HOST_NAME];
86
+ if (safeConfig.enable_graphite === true) names.push(GRAPHITE_HOST_NAME);
87
+
88
+ const seen = new Set(names.map(name => name.toLowerCase()));
89
+
90
+ for (const [repoKey, repoEntry] of configuredRepoEntries(safeConfig)) {
91
+ if (!hasApiHost(repoEntry)) continue;
92
+ // Route through resolveHostName so the global list agrees with the
93
+ // per-repo name used in the submit toast and draft notices — including
94
+ // its validation (a `name` without a usable `label`/`url_template` pair
95
+ // does not register as an external link, and so does not appear here).
96
+ const name = resolveHostName(safeConfig, repoKey);
97
+ const dedupeKey = name.toLowerCase();
98
+ if (seen.has(dedupeKey)) continue;
99
+ seen.add(dedupeKey);
100
+ names.push(name);
101
+ }
102
+
103
+ return names;
104
+ }
105
+
106
+ /**
107
+ * Join host names into a user-facing fragment with an Oxford comma:
108
+ * "GitHub", "GitHub or Graphite", "GitHub, Graphite, or Meteorite".
109
+ *
110
+ * @param {string[]} names
111
+ * @returns {string}
112
+ */
113
+ function formatHostList(names) {
114
+ const list = Array.isArray(names) ? names.filter(name => typeof name === 'string' && name) : [];
115
+ if (list.length === 0) return DEFAULT_HOST_NAME;
116
+ if (list.length === 1) return list[0];
117
+ if (list.length === 2) return `${list[0]} or ${list[1]}`;
118
+ return `${list.slice(0, -1).join(', ')}, or ${list[list.length - 1]}`;
119
+ }
120
+
121
+ /**
122
+ * Convenience wrapper: the formatted host fragment for a config.
123
+ *
124
+ * @param {Object} [config]
125
+ * @returns {string}
126
+ */
127
+ function resolveHostListText(config) {
128
+ return formatHostList(resolveKnownHostNames(config));
129
+ }
130
+
131
+ /**
132
+ * Hostnames (lowercased) that belong to configured alt hosts, recorded both
133
+ * with and without an explicit port so either shape of paste is recognised.
134
+ *
135
+ * Derived from each alt-host repo's `api_host` and, when present, the web
136
+ * host in `links.external.url_template` — the API host and the web host are
137
+ * frequently different domains, and a user pastes the latter.
138
+ *
139
+ * @param {Object} [config]
140
+ * @returns {string[]}
141
+ */
142
+ function resolveAltHostHostnames(config) {
143
+ const safeConfig = (config && typeof config === 'object') ? config : {};
144
+ const hostnames = new Set();
145
+
146
+ const add = (value) => {
147
+ if (typeof value !== 'string' || !value) return;
148
+ // `api_host` is only validated as a non-empty string, so a bare
149
+ // `ghe.example.com` is a legitimate configuration — give it a scheme so
150
+ // `new URL()` can parse it rather than throwing into the catch below.
151
+ const absolute = /^[a-z][a-z0-9+.-]*:\/\//i.test(value) ? value : `https://${value}`;
152
+ let url;
153
+ try {
154
+ url = new URL(absolute);
155
+ } catch {
156
+ // Not parseable even with a scheme — nothing to derive.
157
+ return;
158
+ }
159
+ // A template can carry a placeholder in its authority section
160
+ // (`https://{owner}.example/…` parses, yielding hostname `{owner}.example`);
161
+ // no pasted input can start with that, so drop it rather than ship junk.
162
+ if (!url.hostname || url.hostname.includes('{')) return;
163
+ // `host` keeps a non-default port — what a user actually pastes for
164
+ // `https://ghe.example.com:8443/…`; `hostname` drops it.
165
+ hostnames.add(url.host.toLowerCase());
166
+ hostnames.add(url.hostname.toLowerCase());
167
+ };
168
+
169
+ for (const [, repoEntry] of configuredRepoEntries(safeConfig)) {
170
+ if (!hasApiHost(repoEntry)) continue;
171
+ add(repoEntry.api_host);
172
+ add(repoEntry.links?.external?.url_template);
173
+ }
174
+
175
+ return Array.from(hostnames);
176
+ }
177
+
178
+ /**
179
+ * Every hostname whose PR URLs should be recognised without a scheme —
180
+ * the built-ins plus every configured alt host. De-duplicated, lowercased.
181
+ *
182
+ * @param {Object} [config]
183
+ * @returns {string[]}
184
+ */
185
+ function resolveUrlLikeHostnames(config) {
186
+ const seen = new Set(BUILTIN_PR_HOSTNAMES);
187
+ for (const hostname of resolveAltHostHostnames(config)) seen.add(hostname);
188
+ return Array.from(seen);
189
+ }
190
+
191
+ module.exports = {
192
+ DEFAULT_HOST_NAME,
193
+ GRAPHITE_HOST_NAME,
194
+ BUILTIN_PR_HOSTNAMES,
195
+ resolveKnownHostNames,
196
+ formatHostList,
197
+ resolveHostListText,
198
+ resolveAltHostHostnames,
199
+ resolveUrlLikeHostnames,
200
+ };
@@ -1018,7 +1018,13 @@ async function handleLocalReview(targetPath, flags = {}) {
1018
1018
  let setupComplete = false;
1019
1019
 
1020
1020
  try {
1021
- rejectUrlLikeLocalReviewPath(targetPath);
1021
+ // Loaded before path validation so the "that's a URL" error can name the
1022
+ // configured hosts (GitHub, Graphite, alt hosts) and so scheme-less
1023
+ // alt-host URLs are recognised. The first-run welcome still waits until
1024
+ // the path has been validated.
1025
+ const { config, isFirstRun } = await loadConfig();
1026
+
1027
+ rejectUrlLikeLocalReviewPath(targetPath, config);
1022
1028
 
1023
1029
  const resolvedPath = path.resolve(targetPath || process.cwd());
1024
1030
 
@@ -1032,8 +1038,6 @@ async function handleLocalReview(targetPath, flags = {}) {
1032
1038
  const repoPath = await module.exports.findGitRoot(resolvedPath);
1033
1039
  console.log(`Found git repository at: ${repoPath}`);
1034
1040
 
1035
- const { config, isFirstRun } = await loadConfig();
1036
-
1037
1041
  if (isFirstRun) {
1038
1042
  showWelcomeMessage();
1039
1043
  }
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');
@@ -242,7 +242,7 @@ OPTIONS:
242
242
  --model when the model belongs to a non-default
243
243
  provider (e.g. --provider codex --model gpt-5.5).
244
244
  Available: claude, antigravity, codex, copilot,
245
- opencode, cursor-agent, pi, muse
245
+ opencode, cursor-agent, pi, omp, muse
246
246
  --council <handle> Run analysis with a saved council (multi-voice). Handle is a
247
247
  council name, name-slug, or id (prefix). See --list-councils.
248
248
  --list-councils List saved councils (handles to use with --council) and exit
@@ -277,6 +277,7 @@ ENVIRONMENT VARIABLES:
277
277
  PAIR_REVIEW_CLAUDE_CMD Custom command to invoke Claude CLI (default: claude)
278
278
  PAIR_REVIEW_ANTIGRAVITY_CMD Custom command to invoke Antigravity CLI (default: agy)
279
279
  PAIR_REVIEW_CODEX_CMD Custom command to invoke Codex CLI (default: codex)
280
+ PAIR_REVIEW_OMP_CMD Custom command to invoke OMP (Oh My Pi) CLI (default: omp)
280
281
  PAIR_REVIEW_MUSE_CMD Custom command to invoke Muse Code CLI (default: muse)
281
282
 
282
283
  CONFIGURATION:
@@ -566,6 +567,12 @@ function parseArgs(args) {
566
567
  flags.local = true;
567
568
  // Next argument is optional path (if not starting with -)
568
569
  if (i + 1 < args.length && !args[i + 1].startsWith('-')) {
570
+ // parseArgs() is deliberately config-free — it is exported and
571
+ // unit-tested as a pure argv parser — so this catches only explicit
572
+ // `scheme://` inputs, with host-neutral copy. A scheme-less alt-host
573
+ // URL needs config and is caught by the re-check in main() right after
574
+ // loadConfig() (and again downstream by handleLocalReview /
575
+ // attemptDelegation / the local routes).
569
576
  rejectUrlLikeLocalReviewPath(args[i + 1]);
570
577
  flags.localPath = args[i + 1];
571
578
  i++; // Skip next argument since we consumed it
@@ -667,6 +674,7 @@ ENVIRONMENT VARIABLES:
667
674
  PAIR_REVIEW_CLAUDE_CMD Custom Claude CLI command (default: claude)
668
675
  PAIR_REVIEW_ANTIGRAVITY_CMD Custom Antigravity CLI command (default: agy)
669
676
  PAIR_REVIEW_CODEX_CMD Custom Codex CLI command (default: codex)
677
+ PAIR_REVIEW_OMP_CMD Custom OMP (Oh My Pi) CLI command (default: omp)
670
678
  PAIR_REVIEW_MUSE_CMD Custom Muse Code CLI command (default: muse)
671
679
  PAIR_REVIEW_DB_NAME Custom database filename (overrides config)
672
680
 
@@ -678,6 +686,7 @@ AI PROVIDERS:
678
686
  Claude (default): Requires 'claude' CLI installed
679
687
  Antigravity: Requires 'agy' CLI installed
680
688
  Codex: Requires 'codex' CLI installed
689
+ OMP: Requires 'omp' CLI installed
681
690
  Muse: Requires 'muse' CLI installed
682
691
 
683
692
  Select provider per-repository in the web UI settings.
@@ -739,6 +748,17 @@ AI PROVIDERS:
739
748
  // single-port delegation can skip DB entirely)
740
749
  const { prArgs, flags } = parseArgs(args);
741
750
 
751
+ // parseArgs() ran config-free, so it could only reject `scheme://` inputs.
752
+ // Re-check now that config is loaded: a configured alt host makes
753
+ // `ghe.example.com/owner/repo/pull/1` a URL too, and the message can name
754
+ // the hosts this install actually accepts. Several branches below resolve
755
+ // flags.localPath directly (the instruction handoff at the delegation
756
+ // check, handleHeadlessDelegated, the headless local path), so the
757
+ // invariant has to hold here rather than only in handleLocalReview().
758
+ if (flags.local && flags.localPath) {
759
+ rejectUrlLikeLocalReviewPath(flags.localPath, config);
760
+ }
761
+
742
762
  // Headless-mode flag validation (fail fast, before any DB/server work).
743
763
  // --instructions and --instructions-file are mutually exclusive.
744
764
  if (flags.instructions && flags.instructionsFile) {
@@ -1134,6 +1154,38 @@ AI PROVIDERS:
1134
1154
  }
1135
1155
  }
1136
1156
 
1157
+ /**
1158
+ * Resolve the `repos[...]` config-lookup key for a PR named on the CLI.
1159
+ *
1160
+ * Shared by every in-process PR entry point (`handlePullRequest`,
1161
+ * `performHeadlessReview`, and the headless PR path) so they cannot drift. The
1162
+ * key drives the token/api_host binding AND the repo's local configuration
1163
+ * (path, checkout script, worktree pool, reset script), so both halves have to
1164
+ * agree on it.
1165
+ *
1166
+ * Two corrections over the raw parse result:
1167
+ * - `PRArgumentParser` deliberately drops `bindingRepository` for a canonical
1168
+ * github.com / Graphite URL, so resolve it from owner/repo in that case.
1169
+ * Without this a github.com PR served by a DUAL monorepo entry would lose
1170
+ * that entry's local configuration, and a bare PR number on a pattern-only
1171
+ * alt repo would preflight against the identity instead of its entry.
1172
+ * - The result is filtered by the PR's known host, so an EXCLUSIVE alt entry
1173
+ * that only `url_pattern`-claimed this owner/repo never binds a PR that
1174
+ * lives on github.com (see `bindingRepositoryForHost`).
1175
+ *
1176
+ * @param {{owner: string, repo: string, host?: string|null, bindingRepository?: string}} prInfo
1177
+ * @param {Object} config - Application configuration
1178
+ * @returns {string} The `repos[...]` config-lookup key
1179
+ */
1180
+ function resolveCliBindingRepository(prInfo, config) {
1181
+ return bindingRepositoryForHost(
1182
+ config,
1183
+ normalizeRepository(prInfo.owner, prInfo.repo),
1184
+ prInfo.bindingRepository || resolveBindingRepositoryFromPR(prInfo.owner, prInfo.repo, config),
1185
+ prInfo.host
1186
+ );
1187
+ }
1188
+
1137
1189
  /**
1138
1190
  * Handle pull request processing
1139
1191
  * @param {Array<string>} args - Command line arguments
@@ -1154,13 +1206,9 @@ async function handlePullRequest(args, config, db, flags = {}, poolLifecycle = n
1154
1206
  const parser = new PRArgumentParser(config);
1155
1207
  const prInfo = await parser.parsePRArguments(args);
1156
1208
 
1157
- // Resolve token via repo-aware host binding so alt-host and
1158
- // repo-scoped credentials are respected. When a per-repo
1159
- // `url_pattern` matched, prefer its `bindingRepository` — that's the
1160
- // matched `repos[...]` config key, which may differ from the
1161
- // captured `${owner}/${repo}` for monorepo-style patterns.
1162
- const repositoryForBinding = prInfo.bindingRepository
1163
- || normalizeRepository(prInfo.owner, prInfo.repo);
1209
+ // Resolve the config key via the shared helper so the token binding and the
1210
+ // repo's local configuration agree (see resolveCliBindingRepository).
1211
+ const repositoryForBinding = resolveCliBindingRepository(prInfo, config);
1164
1212
  // A pasted URL tells us the host up front (alt-host `url_pattern` match →
1165
1213
  // api_host string; github/graphite URL → null), so preflight the token
1166
1214
  // against that host. A bare number leaves host undefined → ambiguity rule,
@@ -1228,10 +1276,11 @@ async function handlePullRequest(args, config, db, flags = {}, poolLifecycle = n
1228
1276
  }
1229
1277
 
1230
1278
  // Thread the pasted URL's host to setup so it binds directly instead of
1231
- // probing (shared mapping — see hostSetupParamValue): an alt-host string
1232
- // forwards the api_host; a github URL on a DUAL repo forwards the 'github'
1233
- // sentinel; bare numbers / plain / exclusive repos omit it.
1234
- const hostParam = hostSetupParamValue(prInfo.host, isDualHostRepo(config, repositoryForBinding));
1279
+ // probing (shared mapping — see setupHostParam): an alt-host string forwards
1280
+ // the api_host; a github URL forwards the 'github' sentinel whenever an
1281
+ // api_host entry could otherwise claim this repo; bare numbers and plain
1282
+ // github repos omit it.
1283
+ const hostParam = setupHostParam(config, prInfo.owner, prInfo.repo, prInfo.host);
1235
1284
  if (hostParam) {
1236
1285
  url += (url.includes('?') ? '&' : '?') + `host=${encodeURIComponent(hostParam)}`;
1237
1286
  }
@@ -1334,12 +1383,10 @@ async function performHeadlessReview(args, config, db, flags, options, externalP
1334
1383
  }
1335
1384
  }
1336
1385
 
1337
- // Resolve host binding for the target repo (handles alt-host).
1338
- // Prefer `bindingRepository` (from url_pattern match) over the raw
1339
- // `${owner}/${repo}` since they can differ when one config entry
1340
- // serves many monorepo-shaped URLs.
1341
- const repositoryForBinding = prInfo.bindingRepository
1342
- || normalizeRepository(prInfo.owner, prInfo.repo);
1386
+ // Resolve the config key via the shared helper (see
1387
+ // resolveCliBindingRepository): it drives the host binding below AND this
1388
+ // PR's local path / checkout / pool / reset configuration.
1389
+ const repositoryForBinding = resolveCliBindingRepository(prInfo, config);
1343
1390
  // Preflight the token so a missing credential fails fast before any network
1344
1391
  // work. Tolerates a dual repo with only an alt token when the host is
1345
1392
  // unknown (the setup probe tries the alt host first).
@@ -1990,8 +2037,10 @@ async function preparePrHeadless(db, config, flags, prArgs, externalPoolLifecycl
1990
2037
  }
1991
2038
  }
1992
2039
 
1993
- const repositoryForBinding = prInfo.bindingRepository
1994
- || normalizeRepository(prInfo.owner, prInfo.repo);
2040
+ // Resolve the config key via the shared helper (see
2041
+ // resolveCliBindingRepository): the same key drives the host binding and this
2042
+ // PR's local path / checkout / pool / reset configuration.
2043
+ const repositoryForBinding = resolveCliBindingRepository(prInfo, config);
1995
2044
  // Preflight the token so a missing credential fails fast before any network
1996
2045
  // work. Tolerates a dual repo with only an alt token when the host is unknown
1997
2046
  // (the setup probe tries the alt host first).
@@ -2985,4 +3034,4 @@ if (require.main === module) {
2985
3034
  main();
2986
3035
  }
2987
3036
 
2988
- module.exports = { main, parseArgs, detectPRFromGitHubEnvironment, printCouncilList, handleHeadlessAnalysis, handleHeadlessDelegated, runHeadlessAnalysis, buildHeadlessJson, buildHeadlessErrorJson, emitHeadlessResult, resolveCliInstructions, startPoolBackgroundFetches, isPoolEntryDueForFetch, POOL_FETCH_TICK_MS, MAX_POOL_FETCH_BACKOFF_MS };
3037
+ 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 };
@@ -22,6 +22,14 @@
22
22
  const { RepoSettingsRepository, CouncilRepository } = require('./database');
23
23
  const { resolveCouncilHandle } = require('./councils/resolve-council');
24
24
  const { normalizeCouncilConfig, validateCouncilConfig } = require('./routes/councils');
25
+ // Require the ./ai index (not ./ai/provider) so the provider registry is
26
+ // populated by the provider files' self-registration before lookups here.
27
+ const {
28
+ getProviderClass,
29
+ getProviderConfigOverrides,
30
+ applyModelOverrides,
31
+ resolveDefaultModel
32
+ } = require('./ai');
25
33
  const logger = require('./utils/logger');
26
34
 
27
35
  /**
@@ -52,7 +60,7 @@ function _buildCouncilSelection(council) {
52
60
  * Precedence (highest first), per the global-settings design ("specificity
53
61
  * first, then in-app > files"):
54
62
  * provider: explicit › repo default › global in-app override › config.default_provider › config.provider › 'claude'
55
- * model: explicit › repo default › global in-app override › config.default_model › config.model › 'opus'
63
+ * model: explicit › repo default › global in-app override › config.default_model › provider's own default › 'opus'
56
64
  *
57
65
  * The global in-app override (from the /settings page, carried on
58
66
  * `config._globalOverrides`) sits ABOVE the config files but BELOW the repo
@@ -78,7 +86,22 @@ function _buildCouncilSelection(council) {
78
86
  *
79
87
  * Each field falls through independently, so supplying only `explicit.model`
80
88
  * still resolves the provider from repo/override/config defaults (and vice
81
- * versa).
89
+ * versa) — BUT a tier's `default_model` is *intended* to pair with that
90
+ * tier's `default_provider`, so a tier's model is only consulted when its
91
+ * provider agrees with the resolved provider. Without that guard, a
92
+ * provider-only pick (`--provider omp`) walks the model ladder down to the
93
+ * global default and hands OMP a foreign model id like 'opus' instead of the
94
+ * provider's own default mode. A tier that names no provider is treated as
95
+ * provider-agnostic and still applies (e.g. a model-only in-app override).
96
+ * Note `cfg` is the FLATTENED effective config, not a single layer:
97
+ * loadConfig() merges DEFAULT_CONFIG and the config files, then
98
+ * buildEffectiveConfig() dot-path-writes in-app overrides into the same flat
99
+ * object, so `cfg.default_provider` and `cfg.default_model` may come from
100
+ * different layers — see the `cfgPairSuspect` guard below for the case where
101
+ * that incoherence is provable. When no compatible tier supplies a model,
102
+ * the provider's own default is used (mirroring what the settings UI derives
103
+ * via `models.find(m => m.default)`), with the global model as the last
104
+ * resort for providers with no built-in default (e.g. OpenCode).
82
105
  *
83
106
  * @param {Object} explicit - { provider, model } (either may be undefined)
84
107
  * @param {Object|null} repoSettings - Row from RepoSettingsRepository.getRepoSettings
@@ -95,15 +118,67 @@ function _buildSingleSelection(explicit, repoSettings, config) {
95
118
  || cfg.default_provider
96
119
  || cfg.provider
97
120
  || 'claude';
121
+
122
+ // A tier's model applies only when that tier's provider matches the
123
+ // resolved provider (or the tier names no provider at all).
124
+ const tierModel = (tierProvider, model) =>
125
+ ((!tierProvider || tierProvider === provider) ? model : null);
126
+
127
+ // A provider-only in-app override proves the flattened `cfg` pair is
128
+ // incoherent: buildEffectiveConfig() wrote the new provider into `cfg` via
129
+ // setPath() but left the config-file/default model beneath it. In that
130
+ // case `cfg`'s provider matches the resolved provider by construction, so
131
+ // the tier guard cannot catch the mismatch — skip the `cfg` tier entirely
132
+ // and let the provider's own default supply the model. (A config FILE that
133
+ // sets only default_provider over DEFAULT_CONFIG's model has the same
134
+ // incoherence but is not detectable here; tracked separately.)
135
+ const cfgPairSuspect = Boolean(overrides.default_provider && !overrides.default_model);
136
+
137
+ // An explicit --model passes through verbatim: Pi/OMP fuzzy-match arbitrary
138
+ // ids ('opus', 'gpt-5.2') that are deliberately not in their model list, so
139
+ // it must never be second-guessed against the provider's models. The
140
+ // hardcoded 'claude'/'opus' pair sits BELOW the override-aware provider
141
+ // default as a last-resort rescue (e.g. no provider class registered for
142
+ // 'claude'), so a configured `providers.claude.default_model` or a
143
+ // disabled 'opus' is honored on the provider-default rung first.
98
144
  const model = explicit.model
99
- || repoSettings?.default_model
100
- || overrides.default_model
145
+ || tierModel(repoSettings?.default_provider, repoSettings?.default_model)
146
+ || tierModel(overrides.default_provider, overrides.default_model)
147
+ || (cfgPairSuspect ? null : tierModel(cfg.default_provider || cfg.provider, cfg.default_model || cfg.model))
148
+ || _resolveProviderDefaultModel(provider)
149
+ || tierModel('claude', 'opus')
101
150
  || cfg.default_model
102
151
  || cfg.model
103
152
  || 'opus';
104
153
  return { type: 'single', provider, model };
105
154
  }
106
155
 
156
+ /**
157
+ * Resolve a provider's own default model, honoring config overrides
158
+ * (`providers.<id>.models` / `default_model` / `disabled_models`) exactly the
159
+ * way `createProvider` does when handed a null model — so a provider-only
160
+ * selection lands on the same model the settings UI shows as that provider's
161
+ * default. Returns null for unknown providers and for providers with no
162
+ * default (e.g. OpenCode), letting the caller fall back to the global model.
163
+ *
164
+ * @param {string} providerId - Provider ID
165
+ * @returns {string|null} Default model id, or null
166
+ * @private
167
+ */
168
+ function _resolveProviderDefaultModel(providerId) {
169
+ const ProviderClass = getProviderClass(providerId);
170
+ if (!ProviderClass) return null;
171
+ try {
172
+ const overrides = getProviderConfigOverrides(providerId);
173
+ const effectiveModels = applyModelOverrides(ProviderClass.getModels(), overrides);
174
+ return resolveDefaultModel(effectiveModels, overrides?.default_model)
175
+ || ProviderClass.getDefaultModel();
176
+ } catch (error) {
177
+ logger.warn(`Could not resolve default model for provider "${providerId}": ${error.message}`);
178
+ return null;
179
+ }
180
+ }
181
+
107
182
  /**
108
183
  * Resolve the review configuration (council vs single provider/model) for a run.
109
184
  *
@@ -124,7 +199,8 @@ function _buildSingleSelection(explicit, repoSettings, config) {
124
199
  * single provider/model default.
125
200
  * 5. `repo_settings.default_provider` / `default_model`, then global in-app
126
201
  * override (`config._globalOverrides`) › global `config` defaults — single
127
- * selection (final hardcoded fallbacks 'claude' / 'opus').
202
+ * selection. The final fallback provider is 'claude' with that provider's
203
+ * own default model; 'opus' remains the hardcoded last-resort model floor.
128
204
  *
129
205
  * @param {Object} db - Database instance.
130
206
  * @param {string} repository - Repository in `owner/repo` form (may be null/undefined
@@ -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,
@@ -34,6 +38,7 @@ const {
34
38
  getTourAutoGenerate
35
39
  } = require('../config');
36
40
  const { resolveRepoLinks } = require('../links/repo-links');
41
+ const { resolveKnownHostNames, formatHostList, resolveUrlLikeHostnames } = require('../links/host-names');
37
42
  const { version } = require('../../package.json');
38
43
  const semver = require('semver');
39
44
  const { getAllChatProviders, getAllCachedChatAvailability } = require('../chat/chat-providers');
@@ -158,6 +163,8 @@ router.get('/api/config', (req, res) => {
158
163
  hasRepoGithubToken = Boolean(resolvePreflightBinding(repository, config, undefined).token);
159
164
  }
160
165
 
166
+ const hostNames = resolveKnownHostNames(config);
167
+
161
168
  // Only return safe configuration values (not secrets like github_token)
162
169
  res.json({
163
170
  version,
@@ -190,6 +197,19 @@ router.get('/api/config', (req, res) => {
190
197
  pi_available: getCachedAvailability('pi')?.available || false,
191
198
  assisted_by_url: config.assisted_by_url || 'https://github.com/in-the-loop-labs/pair-review',
192
199
  enable_graphite: config.enable_graphite === true,
200
+ // Code hosts pair-review accepts PR URLs from, derived from config
201
+ // (GitHub always; Graphite only when enabled; each alt host's
202
+ // `links.external.name`). Drives the landing-page placeholder, the help
203
+ // copy, and the client-side URL validation errors — surfaces that render
204
+ // before any repo is resolved and so cannot use resolveHostName().
205
+ // Both shapes are shipped so the Oxford-comma formatting has exactly one
206
+ // implementation (server-side) and cannot drift from the server's own copy.
207
+ pr_host_names: hostNames,
208
+ pr_host_list: formatHostList(hostNames),
209
+ // Hostnames the local-path input should recognise as scheme-less PR URLs
210
+ // (github.com, Graphite, and every configured alt host's API and web
211
+ // domains), so the client pre-flight matches the server's own check.
212
+ pr_url_hostnames: resolveUrlLikeHostnames(config),
193
213
  external_comments: config.external_comments !== false,
194
214
  chat_spinner: config.chat_spinner || 'dots',
195
215
  summaries: {
@@ -331,23 +351,33 @@ router.get('/api/repos/:owner/:repo/links', async (req, res) => {
331
351
  const repository = normalizeRepository(owner, repo);
332
352
  const config = req.app.get('config') || {};
333
353
  // Resolve via bindingRepository so monorepo-style configs (one
334
- // `repos[...]` entry serving many captured owner/repo via
335
- // url_pattern) surface the right link config.
336
- const bindingRepository = resolveBindingRepositoryFromPR(owner, repo, config);
337
-
338
- // Per-PR host awareness: when the caller names a PR, look up its stored
339
- // host so a dual-host repo shows the correct link set (github links for a
340
- // github-hosted PR, the external link for an alt-hosted one). A missing
341
- // row leaves `host` undefined, which resolveRepoLinks treats as the
342
- // 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.
343
365
  let host;
344
366
  const prNumber = parseInt(req.query.number, 10);
345
367
  if (Number.isInteger(prNumber) && prNumber > 0) {
346
368
  const prMetadataRepo = new PRMetadataRepository(req.app.get('db'));
347
- const storedHost = await prMetadataRepo.getPRHost(repository, prNumber);
348
- 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
+ }
349
378
  }
350
379
 
380
+ const bindingRepository = resolveBindingRepositoryForHost(owner, repo, config, host);
351
381
  const links = resolveRepoLinks(config, bindingRepository, host);
352
382
  res.json({ repository, links });
353
383
  } catch (error) {