@boyingliu01/xp-gate 0.41.67 → 0.41.69

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,893 @@
1
+ /**
2
+ * @module doctor-delphi — the Delphi review chain checks (#414 / #574 / #646 / #711 / #712)
3
+ *
4
+ * Split out of `doctor.js`, which had reached 5201 lines against a 1050-line gate
5
+ * threshold. This block is the cleanest seam in that file: 25 functions that
6
+ * answer one question ("can the Delphi chain still run?") and share no state with
7
+ * the gate/hook diagnosis around them.
8
+ *
9
+ * Everything it needs from the host module is INJECTED rather than required back:
10
+ * `doctor.js` re-exports the entry points, so requiring it from here would create
11
+ * the cycle Node resolves by handing out a partially-built exports object -- the
12
+ * failure mode that silently turns a constant into `undefined` at load time.
13
+ */
14
+ 'use strict';
15
+
16
+ const fs = require('fs');
17
+ const path = require('path');
18
+
19
+ const {
20
+ HOME_DIR, MIN_DISTINCT_MODELS, DELPHI_ROLES, PKG_DIR,
21
+ } = require('./doctor-constants.js');
22
+ const { detectInstalledPlatforms, getSkillsDirs } = require('./detect-deps.js');
23
+ const { detectPlatform } = require('./shared-paths.js');
24
+
25
+ /**
26
+ * The one helper this module borrows from `doctor.js`.
27
+ *
28
+ * Injected through `configure()` instead of required back, because `doctor.js`
29
+ * re-exports doctorDelphi: a require in that direction is a cycle, and Node's
30
+ * answer to a cycle -- handing out a partially-built exports object -- turns the
31
+ * helper into `undefined` at load time rather than failing loudly.
32
+ */
33
+ let execWithTimeout = null;
34
+
35
+ // Host-owned constants. They live in doctor.js next to the code that also uses
36
+ // them; copying their values here would be a second source of truth that drifts
37
+ // silently the day one side changes.
38
+ let MIN_NODE_MAJOR_VALUE = 18;
39
+ let NPM_PROBE_TIMEOUT_MS_VALUE = 8000;
40
+
41
+ /**
42
+ * Wire the host module's shared pieces. Called once by doctor.js at load time.
43
+ *
44
+ * @param {{execWithTimeout: Function, MIN_NODE_MAJOR?: number, NPM_PROBE_TIMEOUT_MS?: number}} deps
45
+ */
46
+ function configure(deps) {
47
+ execWithTimeout = deps.execWithTimeout;
48
+ if (Number.isFinite(deps.MIN_NODE_MAJOR)) MIN_NODE_MAJOR_VALUE = deps.MIN_NODE_MAJOR;
49
+ if (Number.isFinite(deps.NPM_PROBE_TIMEOUT_MS)) NPM_PROBE_TIMEOUT_MS_VALUE = deps.NPM_PROBE_TIMEOUT_MS;
50
+ }
51
+
52
+ function disabledBindingVerdict(agentsDir, channelResolution) {
53
+ const leftover = countNativeAgentFiles(agentsDir);
54
+ const head = `native channel disabled (channels=${channelResolution.channels.join(',')} `
55
+ + `via ${channelResolution.source}) — `;
56
+ if (leftover > 0) {
57
+ return ['WARN', head + `${leftover} native agent file(s) still present in ${agentsDir}; they are `
58
+ + 'not used but Qoder still loads them — run `xp-gate delphi-setup --uninstall`'];
59
+ }
60
+ return ['SKIP', head + 'Delphi review runs through the external provider'];
61
+ }
62
+
63
+ /**
64
+ * How many native Delphi agent files exist in `agentsDir` (#711).
65
+ *
66
+ * Used only to tell "disabled cleanly" from "disabled with leftovers" -- a distinction
67
+ * the SKIP line could not express, and one that matters because Qoder still loads the
68
+ * files as custom agents.
69
+ *
70
+ * @param {string} agentsDir directory that may hold `delphi-*.md`
71
+ * @returns {number} matching file count, 0 when unreadable
72
+ */
73
+ function countNativeAgentFiles(agentsDir) {
74
+ try {
75
+ return fs.readdirSync(agentsDir).filter((f) => /^delphi-.*\.md$/.test(f)).length;
76
+ } catch {
77
+ return 0;
78
+ }
79
+ }
80
+
81
+ function resolveAgentTarget(options) {
82
+ const delphiChannel = require('./delphi-channel.js');
83
+ const channelHome = process.env.XDG_CONFIG_HOME
84
+ ? path.dirname(process.env.XDG_CONFIG_HOME)
85
+ : undefined;
86
+ // #711: pass the project directory so a project-level `channels` field is
87
+ // REPORTED even though it never applies. Before this, a repo whose
88
+ // .delphi-config.json declared channels looked configured and did nothing.
89
+ const channelResolution = delphiChannel.resolveChannels({
90
+ home: channelHome,
91
+ projectDir: options.projectDir || process.cwd(),
92
+ });
93
+
94
+ const homeAgentsDir = path.join(HOME_DIR(), '.qoder', 'agents');
95
+ // Injectable for tests; defaults to the cwd the doctor runs from.
96
+ const projectAgentsDir = path.join(options.projectDir || process.cwd(), '.qoder', 'agents');
97
+ const homeComplete = DELPHI_ROLES.every((r) => fs.existsSync(path.join(homeAgentsDir, `delphi-${r}.md`)));
98
+ const projectComplete = DELPHI_ROLES.every((r) => fs.existsSync(path.join(projectAgentsDir, `delphi-${r}.md`)));
99
+ const agentsDir = projectComplete ? projectAgentsDir : homeAgentsDir;
100
+ const agentsSource = projectComplete
101
+ ? `project-level ${agentsDir}`
102
+ : `user-level ${agentsDir}`;
103
+
104
+ return {
105
+ nativeDisabled: !channelResolution.nativeEnabled,
106
+ channelResolution,
107
+ agentsDir,
108
+ agentsSource,
109
+ agentDetails: [agentsSource],
110
+ };
111
+ }
112
+
113
+ /**
114
+ * Inspect ONE role's installed agent file against the bundled template.
115
+ *
116
+ * The three failure classes are reported separately because each has its own remedy
117
+ * (#414 R1 MI-02): a missing file needs an install, an unparseable binding needs
118
+ * `delphi-setup`, and a bundle without a parseable template is install CORRUPTION --
119
+ * skipping that comparison would hide it behind a healthy-looking id (#414 R1 FC-08).
120
+ *
121
+ * @param {string} role
122
+ * @param {string} agentsDir
123
+ * @param {(p: string) => string|null} readId
124
+ * @returns {{ok: boolean, detail: string, id?: string}}
125
+ */
126
+ function inspectAgentBinding(role, agentsDir, readId) {
127
+ const agentPath = path.join(agentsDir, `delphi-${role}.md`);
128
+ if (!fs.existsSync(agentPath)) {
129
+ return {
130
+ ok: false,
131
+ detail: `delphi-${role}.md missing (run: xp-gate init --global, or delphi-setup --local --project for project scope)`,
132
+ };
133
+ }
134
+ const id = readId(agentPath);
135
+ if (id === null) {
136
+ return { ok: false, detail: `delphi-${role}.md has no quoted model binding (repair: xp-gate delphi-setup)` };
137
+ }
138
+ const bundledId = readId(path.join(PKG_DIR, 'plugins', 'qoder', 'agents', `delphi-${role}.md`));
139
+ if (bundledId === null) {
140
+ return { ok: false, detail: `delphi-${role}: bundled template missing/unreadable — reinstall xp-gate` };
141
+ }
142
+ if (bundledId !== id) {
143
+ return { ok: true, id, detail: `delphi-${role}: ${id} (this version ships ${bundledId} — repair: xp-gate delphi-setup)` };
144
+ }
145
+ return { ok: true, id, detail: `delphi-${role}: ${id}` };
146
+ }
147
+
148
+ function checkDelphiAgentBindings(add, options) {
149
+ // 2. Qoder agent bindings: present, parseable, three distinct ids, matching
150
+ // what this version ships. A stale binding is a repair, not an error to
151
+ // retype: the detail names delphi-setup. Project-level agents (from
152
+ // `delphi-setup --local --project`) take precedence when a complete set
153
+ // exists there, so the doctor agrees with the repair command (#414 R1 FC-09).
154
+ const target = resolveAgentTarget(options);
155
+ const { nativeDisabled, channelResolution, agentsDir } = target;
156
+
157
+ // #646: when the machine is configured for the external channel only, the
158
+ // native path is DISABLED BY CHOICE, not broken. Reporting FAIL here told
159
+ // external users their working setup was broken and pointed them at a repair
160
+ // command that reinstalls the thing they just removed.
161
+ if (nativeDisabled) {
162
+ add('Qoder Delphi agent bindings', ...disabledBindingVerdict(agentsDir, channelResolution));
163
+ } else {
164
+ add('Qoder Delphi agent bindings', ...nativeBindingVerdict(target));
165
+ }
166
+
167
+ // #711: the channel preference resolves from the machine config and the env
168
+ // var only. A project that puts `channels` in ITS OWN .delphi-config.json gets
169
+ // no effect from it, and before this line got no warning either -- the file
170
+ // looked authoritative and did nothing.
171
+ if (channelResolution.warning) add('Delphi channel preference', 'WARN', channelResolution.warning);
172
+ }
173
+
174
+ /**
175
+ * The verdict for the native binding set, when that channel is enabled.
176
+ *
177
+ * Extracted from checkDelphiAgentBindings, which measured 53 lines against a
178
+ * 50-line rule once the surrounding 5201-line file stopped hiding it. The two
179
+ * halves answer different questions -- "are the files healthy" and "does the
180
+ * channel preference have anything to say" -- and only this one walks the roles.
181
+ *
182
+ * @param {{agentsDir: string, agentDetails: string[]}} target
183
+ * @returns {[string, string]} status and detail, spread into add()
184
+ */
185
+ function nativeBindingVerdict(target) {
186
+ const { agentsDir, agentDetails } = target;
187
+ const { readQoderModelId } = require('./init.js');
188
+ const agentIds = [];
189
+ let status = 'PASS';
190
+ for (const role of DELPHI_ROLES) {
191
+ const outcome = inspectAgentBinding(role, agentsDir, readQoderModelId);
192
+ if (!outcome.ok) status = 'FAIL';
193
+ agentDetails.push(outcome.detail);
194
+ if (outcome.id) agentIds.push(outcome.id);
195
+ }
196
+ // Report every problem class independently: missing files, unparseable
197
+ // bindings and duplicates can coexist, and each has a different remedy
198
+ // (#414 R1 MI-02).
199
+ if (agentIds.length !== DELPHI_ROLES.length) status = 'FAIL';
200
+ if (new Set(agentIds).size !== agentIds.length) {
201
+ status = 'FAIL';
202
+ agentDetails.push('duplicate model binding across experts — three DISTINCT ids are required');
203
+ }
204
+ return [status, agentDetails.join('; ') || 'all three bound'];
205
+ }
206
+
207
+ function listBundledSkillFiles(dir, base = dir, out = []) {
208
+ if (!fs.existsSync(dir)) return out;
209
+ let entries;
210
+ try {
211
+ entries = fs.readdirSync(dir, { withFileTypes: true });
212
+ } catch {
213
+ return out;
214
+ }
215
+ for (const entry of entries) {
216
+ const p = path.join(dir, entry.name);
217
+ if (entry.isDirectory()) listBundledSkillFiles(p, base, out);
218
+ else out.push(path.relative(base, p));
219
+ }
220
+ return out;
221
+ }
222
+
223
+ /**
224
+ * Compare every deployed copy against the bundle and report the verdict.
225
+ *
226
+ * #725: EVERY platform with the skill deployed is checked, not only the one
227
+ * `detectPlatform()` selects. On a machine with both Qoder and OpenCode the OpenCode
228
+ * copy was frozen at an old version while this check reported PASS, because it never
229
+ * looked there -- the drifted copy was invisible to both `update-skill` and `doctor`.
230
+ */
231
+ function reportSkillParity(add, deployedDirs, bundledFiles, bundledSkillDir, sha256) {
232
+ // #725: check every platform that has the skill deployed, not only the one
233
+ // `detectPlatform()` selects. On a machine with both Qoder and OpenCode the
234
+ // OpenCode copy was frozen at an old version and this check reported PASS,
235
+ // because it never looked there -- the drifted copy was invisible to both
236
+ // `update-skill` and `doctor`.
237
+ const drifted = [];
238
+ for (const dir of deployedDirs) {
239
+ const dirDrift = collectSkillDrift(dir, bundledFiles, bundledSkillDir, sha256);
240
+ if (dirDrift.length > 0) {
241
+ drifted.push(`${platformTag(dir)}: ${dirDrift.join(', ')}`);
242
+ }
243
+ }
244
+ if (drifted.length > 0) {
245
+ add('Delphi skill install parity', 'FAIL',
246
+ `installed copy differs from the ${getCliVersionSafe()} bundle — `
247
+ + `${drifted.slice(0, 3).join('; ')}${drifted.length > 3 ? '; ...' : ''} `
248
+ + '(reinstall: xp-gate install-skill delphi-review --force)');
249
+ } else {
250
+ add('Delphi skill install parity', 'PASS',
251
+ `${bundledFiles.length} file(s) match the bundle across ${deployedDirs.length} platform(s)`);
252
+ }
253
+ }
254
+
255
+ function checkSkillInstallParity(add, options) {
256
+ // 3. Skill install parity: a drifted installed copy is how "reinstall from
257
+ // an old local repo" became a downgrade (#414 B4). Every bundled file is
258
+ // compared, not just SKILL.md — the install script copies *.json and
259
+ // references/ too, and B4-style drift hits those equally (#414 R1 MI-03).
260
+ //
261
+ // #635 follow-up: this was a THIRD hand-written platform→directory table
262
+ // (after PLATFORM_PROFILES and install-skill's own), and it had no `dsh` arm,
263
+ // so on a DSH machine it resolved to `~/.config/opencode/skills/delphi-review`
264
+ // — a directory that does not exist. `otherDeployedSkillDirs()` below rescued
265
+ // the parity check, but the runner-locate check further down read this path
266
+ // directly and never consulted the full platform set. Derive it instead, so
267
+ // the mapping has one source of truth and a new platform needs no edit here.
268
+ const platform = detectPlatform();
269
+ const installedSkillDir = path.join(getSkillsDirs(platform)[0], 'delphi-review');
270
+ // Injectable for tests (#414 R3 FC-01/FC-02): the empty-bundle branch is a
271
+ // real failure mode and must be drivable without mutating the package.
272
+ const bundledSkillDir = options.bundledSkillDir || path.join(PKG_DIR, 'skills', 'delphi-review');
273
+ const sha256 = (p) => fileSha256(p);
274
+ // A bundle we cannot read is reported as an empty bundle, which the parity check
275
+ // already treats as "every installed file is extra" -- a truthful, loud outcome.
276
+ // #725 follow-up: decide "installed anywhere?" from the full platform set, not
277
+ // just the directory `detectPlatform()` selects — a dsh-only machine has no
278
+ // marker detectPlatform() keys on, so the opencode fallback directory never
279
+ // exists and the old check falsely reported "not installed" even though the
280
+ // copy IS deployed under ~/.dsh/skills.
281
+ const deployedDirs = otherDeployedSkillDirs(installedSkillDir);
282
+ if (deployedDirs.length === 0) {
283
+ add('Delphi skill install parity', 'FAIL',
284
+ `not installed at ${installedSkillDir} (install: xp-gate install-skill delphi-review)`);
285
+ } else {
286
+ const bundledFiles = listBundledSkillFiles(bundledSkillDir);
287
+ if (bundledFiles.length === 0) {
288
+ // An installed copy next to an empty bundle is install corruption —
289
+ // "0 files match" must never read as healthy (#414 R2 MN-R2-01). The
290
+ // bundled dir ships inside the installed package itself, so an
291
+ // unreachable one is a broken install, not a transient condition
292
+ // (#414 R3 FC-05): FAILing is the doctor's job here.
293
+ add('Delphi skill install parity', 'FAIL',
294
+ `bundled skill directory missing or empty: ${bundledSkillDir} — reinstall xp-gate`);
295
+ } else {
296
+ reportSkillParity(add, deployedDirs, bundledFiles, bundledSkillDir, sha256);
297
+ }
298
+ }
299
+ return installedSkillDir;
300
+ }
301
+
302
+ /**
303
+ * Check 5: the Delphi config parses and names three distinct callable models.
304
+ *
305
+ * Pulled out of `doctorDelphi` because it is the largest single check and the
306
+ * least related to the others: everything above asks "is this installed", this
307
+ * one asks "will a review actually run".
308
+ *
309
+ * @param {(name: string, status: string, detail?: string) => void} add
310
+ */
311
+ /**
312
+ * Problems with a Delphi profile's expert model bindings.
313
+ *
314
+ * Pure: profile in, problem list out. It was inline inside a try/catch inside an
315
+ * if/else inside the config check, four levels down, where the three distinct
316
+ * failure modes (missing role, duplicate model, unusable provider) were one
317
+ * compound condition.
318
+ *
319
+ * @param {object} profile
320
+ * @returns {string[]} human-readable problems; empty when the profile is usable
321
+ */
322
+ function delphiModelProblems(profile) {
323
+ const experts = profile.experts || {};
324
+ const providers = profile.providers || {};
325
+ const models = DELPHI_ROLES.map((r) => experts[r] && experts[r].model);
326
+
327
+ const missingRoles = DELPHI_ROLES.filter((r, i) => !models[i]);
328
+ const duplicates = models.filter((m, i) => m && models.indexOf(m) !== i);
329
+ const badProviders = DELPHI_ROLES.filter((r) => !isSeatUsable(experts[r], providers));
330
+
331
+ // Collected as data and filtered once: three `if`s over three lists is three
332
+ // branches to say "report whichever are non-empty".
333
+ return [
334
+ [missingRoles, `missing experts: ${missingRoles.join(', ')}`],
335
+ [duplicates, `duplicate models: ${[...new Set(duplicates)].join(', ')}`],
336
+ [badProviders, `unusable provider binding: ${badProviders.join(', ')}`],
337
+ ].filter(([items]) => items.length > 0).map(([, message]) => message);
338
+ }
339
+
340
+ /**
341
+ * Whether one expert seat points at a provider that can actually be called.
342
+ *
343
+ * Three ways to fail, and they are reported as one because the remedy is the same
344
+ * (fix the binding): no expert entry, a provider name the config does not define, or
345
+ * a base_url that is missing or not an http(s) URL. The last check is `indexOf('http')
346
+ * === 0` rather than a URL parse on purpose -- a config with `ftp://` or a bare host
347
+ * both fail, and rejecting it early beats a network error later.
348
+ *
349
+ * @param {{provider?: string}|undefined} expert
350
+ * @param {Object<string, {base_url?: string}>} providers
351
+ * @returns {boolean}
352
+ */
353
+ function isSeatUsable(expert, providers) {
354
+ if (!expert) return false;
355
+ const provider = providers[expert.provider];
356
+ if (!provider || !provider.base_url) return false;
357
+ return String(provider.base_url).indexOf('http') === 0;
358
+ }
359
+
360
+ /**
361
+ * Report whether the installed xp-gate matches npm's latest.
362
+ *
363
+ * The npm probe is opt-in (`probeNpmLatest`) or pre-supplied (`npmLatest`): the
364
+ * doctor never blocks on the network, which an offline CI or a restricted shell
365
+ * would otherwise hit (#414 R1 FC-03).
366
+ *
367
+ * @param {(name: string, status: string, detail?: string) => void} add
368
+ * @param {object} options
369
+ * @param {string|null|undefined} npmLatest
370
+ */
371
+ async function checkDelphiVersionConsistency(add, options, npmLatest) {
372
+ const localVersion = getCliVersionSafe();
373
+ let versionStatus = 'PASS';
374
+ let versionDetail = `xp-gate ${localVersion}`;
375
+
376
+ if (npmLatest === undefined && options.probeNpmLatest === true) {
377
+ try {
378
+ // `execWithTimeout` is async; reading `.trim()` off the Promise threw, and the
379
+ // catch below swallowed it -- so a WORKING npm probe reported 'offline?' every
380
+ // time. Measured: `Promise.prototype.trim` is undefined.
381
+ const probed = await execWithTimeout('npm view @boyingliu01/xp-gate version', NPM_PROBE_TIMEOUT_MS_VALUE);
382
+ versionDetail += `; npm latest probe: ${String(probed).trim()}`;
383
+ } catch {
384
+ versionStatus = 'SKIP';
385
+ versionDetail += '; npm latest probe unavailable (offline?) — skipped';
386
+ }
387
+ } else if (typeof npmLatest === 'string' && npmLatest !== localVersion) {
388
+ versionStatus = 'FAIL';
389
+ versionDetail += `; npm latest ${npmLatest} differs from local ${localVersion} — update (npm install -g @boyingliu01/xp-gate@latest) or verify which side is stale`;
390
+ } else if (npmLatest === null || options.probeNpmLatest !== true) {
391
+ versionDetail += '; npm latest probe skipped (pass --npm-check or options.probeNpmLatest to run it)';
392
+ }
393
+ add('Delphi version consistency', versionStatus, versionDetail);
394
+ }
395
+
396
+
397
+ /**
398
+ * Check 7: DSH native-channel readiness (#443 REQ-6).
399
+ *
400
+ * Only meaningful when a DSH home exists. The two-layer switch (preset
401
+ * capability plus host setting) defaults to DISABLED, and a review that
402
+ * assumes native will silently run three same-model seats -- the failure this
403
+ * check exists to make visible before a review spends money on it.
404
+ *
405
+ * @param {(name: string, status: string, detail?: string) => void} add
406
+ */
407
+ /**
408
+ * The per-profile configuration layers under a DSH home, if any.
409
+ *
410
+ * DSH stores configuration as a loader patch layer per profile:
411
+ * `profiles/<profile>/cordis.patch.yml`. An empty `[]` is a layer that adds nothing,
412
+ * which is a valid configuration, so existence alone is what this reports -- parsing
413
+ * the YAML to look for a seat override would tie this check to a schema it does not own.
414
+ *
415
+ * @param {string} dshHome the resolved `~/.dsh`
416
+ * @returns {string[]} absolute paths to the layers found
417
+ */
418
+ function listDshProfileConfigs(dshHome) {
419
+ const profilesDir = path.join(dshHome, 'profiles');
420
+ let entries;
421
+ try {
422
+ entries = fs.readdirSync(profilesDir, { withFileTypes: true });
423
+ } catch {
424
+ return [];
425
+ }
426
+ const found = [];
427
+ for (const entry of entries) {
428
+ if (!entry.isDirectory() || entry.name.endsWith('.bak') || entry.name.includes('.bak-')) continue;
429
+ const layer = path.join(profilesDir, entry.name, 'cordis.patch.yml');
430
+ if (fs.existsSync(layer)) found.push(layer);
431
+ }
432
+ return found;
433
+ }
434
+
435
+ function checkDshChannelReadiness(add) {
436
+ // 7. DSH native-channel readiness (#443 REQ-6): only meaningful when a DSH home
437
+ // exists. The two-layer switch (preset capability + host setting) defaults to
438
+ // disabled, and a review that assumes native will silently run three same-model
439
+ // seats.
440
+ const label = 'DSH subagent model selection';
441
+ const dshHome = path.join(HOME_DIR(), '.dsh');
442
+ if (!fs.existsSync(dshHome)) {
443
+ add(label, 'SKIP', `no ${dshHome} — not a DSH environment`);
444
+ return;
445
+ }
446
+
447
+ const settingsCandidates = [
448
+ path.join(dshHome, 'settings.json'),
449
+ path.join(dshHome, 'settings', 'settings.json'),
450
+ path.join(dshHome, 'config.json'),
451
+ ];
452
+ const settingsFile = settingsCandidates.find((p) => fs.existsSync(p));
453
+ if (!settingsFile) {
454
+ // #812: the three names above are not where DSH keeps its configuration. Measured
455
+ // on this machine: `~/.dsh/profiles/<profile>/cordis.patch.yml` -- `headless` holds
456
+ // an empty `[]`, `web` holds 628 lines. The directory existed, the configuration
457
+ // existed, and this check called it absent while asserting a CONSEQUENCE
458
+ // ("defaults to disabled") about a setting it had never looked at.
459
+ const profileFiles = listDshProfileConfigs(dshHome);
460
+ if (profileFiles.length > 0) {
461
+ // A profile layer that does not mention subagents is the PLATFORM DEFAULT, not a
462
+ // misconfiguration. Saying FAIL here told a working setup it was broken, which is
463
+ // the same bug family as #646 one level down: "not mentioned" is not "disabled".
464
+ add(label, 'SKIP',
465
+ `${profileFiles.length} DSH profile layer(s) present and no seat override in them `
466
+ + `(e.g. ${path.relative(dshHome, profileFiles[0])}) — subagent model selection `
467
+ + 'is at its platform default, which is not a defect (#812)');
468
+ return;
469
+ }
470
+ add(label, 'FAIL',
471
+ `${dshHome} exists but no settings file found — subagent model selection defaults to disabled (#443)`);
472
+ return;
473
+ }
474
+
475
+ let settings;
476
+ try {
477
+ settings = JSON.parse(fs.readFileSync(settingsFile, 'utf8'));
478
+ } catch (err) {
479
+ add(label, 'SKIP', `${settingsFile} unparseable: ${err.message}`);
480
+ return;
481
+ }
482
+ reportDshSelection(add, label, settingsFile, settings.subagentModelSelection);
483
+ }
484
+
485
+ /**
486
+ * Report whether the DSH switch is on AND properly provisioned.
487
+ *
488
+ * The switch shipping OFF is the platform default, not a defect: only an operator who
489
+ * explicitly enables it and under-provisions `allowedModels` has a real
490
+ * misconfiguration (#414 R1 FC-07). Collapsing those two into one FAIL is what told
491
+ * working setups they were broken.
492
+ */
493
+ function reportDshSelection(add, label, settingsFile, selection) {
494
+ const allowed = selection && Array.isArray(selection.allowedModels) ? selection.allowedModels : [];
495
+ const ids = allowed.map((m) => (typeof m === 'string' ? m : m && m.id)).filter(Boolean);
496
+ const distinct = new Set(ids).size;
497
+
498
+ if (!selection || selection.enabled !== true) {
499
+ add(label, 'SKIP',
500
+ `${settingsFile}: native model selection disabled (platform default) — the external channel is the contract path (#443)`);
501
+ return;
502
+ }
503
+ if (distinct >= MIN_DISTINCT_MODELS) {
504
+ add(label, 'PASS', `${settingsFile}: enabled, ${distinct} distinct allowed models`);
505
+ return;
506
+ }
507
+ add(label, 'FAIL',
508
+ `${settingsFile}: enabled but only ${distinct} distinct allowedModels (need >=${MIN_DISTINCT_MODELS}) — native channel unusable`);
509
+ }
510
+
511
+ /**
512
+ * Report seats that are not `local-*`, as a WARN.
513
+ *
514
+ * #574: the local-only rule is an operator preference (the 2026-10-03 quota burn),
515
+ * so doctor surfaces the cost exposure without failing a deliberately hosted seat.
516
+ * The HARD enforcement lives in Gate MW, which binds evidence to whatever the config
517
+ * declares rather than to a `local-` prefix. `scripts/check_delphi_local_models.py`
518
+ * holds the same rule with the same allowlist and exit code; reporting it here is
519
+ * what finally gives that guard a caller instead of leaving it in its docstring.
520
+ *
521
+ * @param {Function} add
522
+ * @param {Array<string|undefined>} models one per DELPHI_ROLES entry
523
+ */
524
+ function reportHostedSeats(add, models) {
525
+ const label = 'Delphi local-model guard (#574)';
526
+ const hosted = DELPHI_ROLES
527
+ .map((role, i) => ({ role, model: models[i] }))
528
+ .filter(({ model }) => model && !String(model).toLowerCase().startsWith('local-'));
529
+
530
+ if (hosted.length === 0) {
531
+ add(label, 'PASS', `all ${DELPHI_ROLES.length} seats are local-*`);
532
+ return;
533
+ }
534
+ add(label, 'WARN',
535
+ `hosted (non local-*) seats: ${hosted.map(({ role, model }) => `${role}=${model}`).join(', ')} — `
536
+ + 'local-only review is the standing rule; check the seats with: xp-gate doctor delphi');
537
+ }
538
+
539
+ /**
540
+ * Compare the configured seats against the models a project PINNED (#712).
541
+ *
542
+ * WHY A PROJECT-LEVEL DECLARATION
543
+ * The local-only rule above is a fixed WARN, which is right for a preference.
544
+ * A consumer project often has a HARD requirement instead — "these three seats
545
+ * must be exactly these three models" — and had no way to say so: each repo
546
+ * re-implemented the check in its own script, so the constraint lived nowhere
547
+ * upstream and drifted per project.
548
+ *
549
+ * `pinned_models` is that declaration. When it is ABSENT nothing changes (the
550
+ * WARN above stands), so existing configs keep their exact behaviour.
551
+ *
552
+ * A mismatch is FAIL, not WARN: if the project said "exactly these", anything
553
+ * else is a defect the project already decided is unacceptable. Both sides of
554
+ * every difference are printed — "seat differs" without the two values leaves
555
+ * the operator to diff the config by hand.
556
+ *
557
+ * @param {Function} add
558
+ * @param {object} pinned reported `pinned_models`
559
+ * @param {Array<string|undefined>} models one per DELPHI_ROLES entry
560
+ */
561
+ function reportPinnedSeats(add, pinned, models) {
562
+ const label = 'Delphi pinned seats (#712)';
563
+ if (!pinned || typeof pinned !== 'object' || Array.isArray(pinned)) {
564
+ add(label, 'FAIL', 'pinned_models must be an object of role -> model id');
565
+ return;
566
+ }
567
+ const unknown = Object.keys(pinned).filter((r) => !DELPHI_ROLES.includes(r));
568
+ if (unknown.length > 0) {
569
+ // A typo'd role pins nothing and reads as satisfied. Name it.
570
+ add(label, 'FAIL', `pinned_models names unknown role(s): ${unknown.join(', ')} (known: ${DELPHI_ROLES.join(', ')})`);
571
+ return;
572
+ }
573
+ const diffs = DELPHI_ROLES
574
+ .map((role, i) => ({ role, want: pinned[role], got: models[i] }))
575
+ .filter(({ want, got }) => want !== undefined && want !== got);
576
+ if (diffs.length === 0) {
577
+ add(label, 'PASS', `all ${Object.keys(pinned).length} pinned seat(s) match the configured profile`);
578
+ return;
579
+ }
580
+ add(label, 'FAIL', diffs
581
+ .map(({ role, want, got }) => `${role}: pinned ${want}, configured ${got ?? '(none)'}`)
582
+ .join('; '));
583
+ }
584
+
585
+ /**
586
+ * Warn when a project config shadows a global one whose seats differ.
587
+ *
588
+ * #541: loaders fall back to the global config only on ENOENT, so this project file
589
+ * always wins here. If the machine-wide config exists AND its seats differ, the
590
+ * effective model mix depends on cwd -- the cross-project drift class behind the
591
+ * 2026-10-03 quota burn. WARN, never FAIL: intentional overrides are legal, and only
592
+ * the cwd-dependence is the hazard.
593
+ *
594
+ * Seat shape is object-keyed OR array in the wild (`delphi-config.ts` accepts both),
595
+ * so both sides are normalized before comparing.
596
+ *
597
+ * @param {{add: Function, cfgPath: string, globalConfigPath: string, models: Array}} p
598
+ */
599
+ function reportConfigShadow(p) {
600
+ const { add, cfgPath, globalConfigPath, models } = p;
601
+ try {
602
+ if (!fs.existsSync(globalConfigPath) || path.resolve(globalConfigPath) === path.resolve(cfgPath)) return;
603
+
604
+ const gRaw = JSON.parse(fs.readFileSync(globalConfigPath, 'utf8'));
605
+ const gProfile = gRaw.profiles && gRaw.profiles[gRaw.active_profile || 'default'];
606
+ const gExperts = (gProfile && gProfile.experts) || {};
607
+ const pickExpert = (experts, role, idx) => {
608
+ if (!experts) return null;
609
+ if (Array.isArray(experts)) {
610
+ const seat = experts.find((x) => x && x.role === role) || experts[idx];
611
+ return (seat && seat.model) || null;
612
+ }
613
+ return (experts[role] && experts[role].model) || null;
614
+ };
615
+ const gModels = DELPHI_ROLES.map((role, i) => pickExpert(gExperts, role, i));
616
+ // Compare only roles BOTH sides define: a role missing on one side is an
617
+ // incomplete config (already FAILed above), not drift.
618
+ const differing = DELPHI_ROLES.filter((role, i) => gModels[i] && models[i] && gModels[i] !== models[i]);
619
+ if (differing.length === 0) return;
620
+
621
+ add('Delphi config shadow (#541)', 'WARN',
622
+ `project config shadows ${globalConfigPath}; seats differ (${differing.join(', ')}) — `
623
+ + 'reviews run from other directories will use different models');
624
+ } catch {
625
+ // A broken global config is not this check's failure mode; claiming nothing is
626
+ // better than claiming agreement.
627
+ }
628
+ }
629
+
630
+ /**
631
+ * Read the Delphi config and report whether a review can run from it.
632
+ *
633
+ * The file that was actually read is always named. With both scopes present a user
634
+ * cannot otherwise tell which one the review will take, and that ambiguity is what
635
+ * made #684 hard to see.
636
+ *
637
+ * @param {{add: Function, cfgPath: string, cfgLabel: string,
638
+ * usingGlobalConfig: boolean, globalConfigPath: string}} p
639
+ */
640
+ function reportConfigFile(p) {
641
+ const { add, cfgPath, cfgLabel, usingGlobalConfig, globalConfigPath } = p;
642
+ if (!fs.existsSync(cfgPath)) {
643
+ add(cfgLabel, 'FAIL',
644
+ `${cfgPath} not found (copy .delphi-config.json.example from the skill directory)`);
645
+ return;
646
+ }
647
+ let raw;
648
+ try {
649
+ raw = JSON.parse(fs.readFileSync(cfgPath, 'utf8'));
650
+ } catch (err) {
651
+ add(cfgLabel, 'FAIL', `unparseable: ${err.message}`);
652
+ return;
653
+ }
654
+ // Early returns rather than nested else-branches: the four outcomes (missing,
655
+ // unparseable, no profile, usable profile) are independent, and expressing them
656
+ // as one chain read as five levels of nesting once the file was split out from
657
+ // the 5201-line doctor.js that had been hiding it.
658
+ const profileName = raw.active_profile || 'default';
659
+ const profile = raw.profiles && raw.profiles[profileName];
660
+ if (!profile) {
661
+ add(cfgLabel, 'FAIL', `profile "${profileName}" not found`);
662
+ return;
663
+ }
664
+ const models = DELPHI_ROLES.map((r) => (profile.experts || {})[r] && profile.experts[r].model);
665
+ const problems = delphiModelProblems(profile);
666
+ const scopeNote = usingGlobalConfig ? ` [global: ${cfgPath}]` : ` [project: ${cfgPath}]`;
667
+ if (problems.length > 0) {
668
+ // The file WAS read, so the scope still has to be named: without it a user
669
+ // with both scopes present cannot tell which one the review will use (#684).
670
+ add(cfgLabel, 'FAIL', `${problems.join('; ')}${scopeNote}`);
671
+ } else {
672
+ add(cfgLabel, 'PASS', `profile "${profileName}": ${models.join(' / ')}${scopeNote}`);
673
+ // #574: hosted (non local-*) seats are REPORTED, not blocked. The local-only
674
+ // rule is an operator preference; the hard enforcement lives in Gate MW.
675
+ reportHostedSeats(add, models);
676
+ // #712: a project may PIN the three seats. Absent means "no opinion".
677
+ if (Object.prototype.hasOwnProperty.call(raw, 'pinned_models')) {
678
+ reportPinnedSeats(add, raw.pinned_models, models);
679
+ }
680
+ }
681
+ reportConfigShadow({ add, cfgPath, globalConfigPath, models });
682
+ }
683
+
684
+ async function checkDelphiConfigPing(add, options, globalConfigPath) {
685
+ const { configPath, npmLatest } = options;
686
+ // 5. Config ping: parseable, three distinct callable models. A duplicate
687
+ // model here is a review that will BLOCK later — say so now.
688
+ //
689
+ // #684: resolve the SAME way the runner does. A project-local config wins; a
690
+ // machine-level one under XDG_CONFIG_HOME (or ~/.config) is the documented
691
+ // fallback, and a review keeps working on it. Checking only `cwd` reported
692
+ // FAIL on the layout SKILL.md recommends and told the user to copy the example
693
+ // into the project — manufacturing the drifted duplicate #541 warns about.
694
+ //
695
+ // An explicit `configPath` is an ANSWER, not a hint: a caller that names a
696
+ // file means that file, so it disables the fallback. Otherwise a test (or a
697
+ // caller) pinning an absent path silently reads the developer's real global
698
+ // config and reports PASS — the same vacuous-pass shape this batch is fixing.
699
+ const projectCfgPath = configPath
700
+ || path.join(options.projectDir || process.cwd(), '.delphi-config.json');
701
+ const usingGlobalConfig = !configPath
702
+ && !fs.existsSync(projectCfgPath)
703
+ && fs.existsSync(globalConfigPath);
704
+ const cfgPath = usingGlobalConfig ? globalConfigPath : projectCfgPath;
705
+ const cfgLabel = 'Delphi config (.delphi-config.json)';
706
+ reportConfigFile({ add, cfgPath, cfgLabel, usingGlobalConfig, globalConfigPath });
707
+
708
+ // 6. Version consistency.
709
+ await checkDelphiVersionConsistency(add, options, npmLatest);
710
+
711
+
712
+ // 7. DSH native-channel readiness.
713
+ checkDshChannelReadiness(add);
714
+
715
+ }
716
+
717
+ async function doctorDelphi(options = {}) {
718
+ const { configPath, npmLatest } = options;
719
+ // #541: the shadow check needs the loader's global fallback path. It is
720
+ // injectable for tests; the default mirrors delphi-config.ts /
721
+ // delphi-external-review.cjs resolution (XDG_CONFIG_HOME honored).
722
+ const globalConfigPath = options.globalConfigPath
723
+ || path.join(process.env.XDG_CONFIG_HOME || path.join(require('os').homedir(), '.config'), 'xp-gate', '.delphi-config.json');
724
+ const checks = [];
725
+ const add = (name, status, detail) => checks.push({ name, status, detail });
726
+
727
+ // 1. Node >= 18: the runner gates on it and exits 1 mid-review otherwise.
728
+ const nodeMajor = parseInt(process.versions.node.split('.')[0], 10);
729
+ add(`Node.js >= ${MIN_NODE_MAJOR_VALUE}`, nodeMajor >= MIN_NODE_MAJOR_VALUE ? 'PASS' : 'FAIL',
730
+ `current: ${process.versions.node}`);
731
+
732
+ // 2. Qoder agent bindings.
733
+ checkDelphiAgentBindings(add, options);
734
+
735
+ // 3. Skill install parity. It also resolves the installed skill dir, which
736
+ // the runner-locate check below needs.
737
+ const installedSkillDir = checkSkillInstallParity(add, options);
738
+
739
+ // 4. Runner script locate: the runner must be findable from the places a
740
+ // review actually starts.
741
+ const runnerCandidates = [
742
+ ['package bundle', path.join(PKG_DIR, 'scripts', 'delphi-external-review.cjs')],
743
+ ['project', path.join(process.cwd(), 'scripts', 'delphi-external-review.cjs')],
744
+ ['installed skill', path.join(installedSkillDir, 'scripts', 'delphi-external-review.cjs')],
745
+ ];
746
+ const foundRunner = runnerCandidates.filter(([, p]) => fs.existsSync(p));
747
+ add('delphi-external-review runner', foundRunner.length > 0 ? 'PASS' : 'FAIL',
748
+ foundRunner.length > 0
749
+ ? foundRunner.map(([label, p]) => `${label}: ${p}`).join('; ')
750
+ : 'not found in package bundle, project, or installed skill');
751
+
752
+ // 5. Config ping.
753
+ await checkDelphiConfigPing(add, options, globalConfigPath);
754
+
755
+ for (const check of checks) {
756
+ const mark = check.status === 'PASS' ? '✓' : check.status === 'SKIP' ? '○' : check.status === 'WARN' ? '⚠' : '✗';
757
+ console.log(` ${mark} ${check.name}: ${check.detail || check.status}`);
758
+ }
759
+ const failed = checks.filter((c) => c.status === 'FAIL').length;
760
+ console.log('');
761
+ console.log(failed === 0
762
+ ? ' Delphi review chain: healthy.'
763
+ : ` Delphi review chain: ${failed} check(s) FAILED.`);
764
+ return failed === 0 ? 0 : 1;
765
+ }
766
+
767
+ function getCliVersionSafe() {
768
+ try {
769
+ return require('../package.json').version || '0.0.0';
770
+ } catch {
771
+ return '0.0.0';
772
+ }
773
+ }
774
+
775
+ /**
776
+ * Skills directories that hold the delphi-review skill, including the detected one.
777
+ *
778
+ * #725: `detectPlatform()` returns a single platform, so on a machine carrying
779
+ * both Qoder and OpenCode the OpenCode copy of the skill was never examined —
780
+ * `update-skill` did not refresh it and `doctor` reported PASS anyway. Both were
781
+ * looking at the same one directory. A migration period (user moved between AI
782
+ * tools, both trees still live) is the normal case that produces this, and the
783
+ * frozen copy is exactly what a parity check exists to catch.
784
+ *
785
+ * The original fix still hardcoded the three pre-dsh platforms, so the DSH copy
786
+ * (`~/.dsh/skills/delphi-review`) — which `detectPlatform()` never returns and
787
+ * `PLATFORM_PROFILES` does carry — stayed invisible. Derive the candidates from
788
+ * the profiles so every installed platform is examined.
789
+ *
790
+ * @param {string} detectedDir the platform `detectPlatform()` selected
791
+ * @returns {string[]} directories that actually contain the skill
792
+ */
793
+ function otherDeployedSkillDirs(detectedDir) {
794
+ const candidates = [detectedDir];
795
+ for (const platform of detectInstalledPlatforms()) {
796
+ candidates.push(path.join(getSkillsDirs(platform)[0], 'delphi-review'));
797
+ }
798
+ const seen = new Set();
799
+ const found = [];
800
+ for (const dir of candidates) {
801
+ if (seen.has(dir)) continue;
802
+ seen.add(dir);
803
+ if (fs.existsSync(path.join(dir, 'SKILL.md'))) found.push(dir);
804
+ }
805
+ return found;
806
+ }
807
+
808
+ /**
809
+ * A short label for a skills directory: the platform segment, not the full path.
810
+ * Keeps the doctor line readable when two platforms disagree.
811
+ */
812
+ function platformTag(skillDir) {
813
+ const parent = path.basename(path.dirname(path.dirname(skillDir)));
814
+ return parent === 'opencode' ? 'opencode' : parent;
815
+ }
816
+
817
+ /**
818
+ * Files in `skillDir` that are missing or differ from the bundle.
819
+ * @returns {string[]} `rel: reason` entries; empty when the copy is clean
820
+ */
821
+ /**
822
+ * Files where an installed skill copy differs from the bundle.
823
+ *
824
+ * An unreadable file is reported as `unreadable` rather than skipped: a copy we
825
+ * cannot check is not a copy we can call matching, and silence here would let a
826
+ * permissions problem pass as parity.
827
+ */
828
+ /**
829
+ * SHA-256 of a file, or a thrown error naming the path.
830
+ *
831
+ * A digest is used to compare two copies; a read failure must not yield a digest
832
+ * that happens to differ, because "cannot read" and "differs" need different
833
+ * repairs.
834
+ *
835
+ * @param {string} filePath
836
+ * @returns {string}
837
+ */
838
+ function fileSha256(filePath) {
839
+ let content;
840
+ try {
841
+ content = fs.readFileSync(filePath);
842
+ } catch (err) {
843
+ throw new Error(`cannot hash ${filePath}: ${err.message}`);
844
+ }
845
+ return require('crypto').createHash('sha256').update(content).digest('hex');
846
+ }
847
+
848
+ function collectSkillDrift(skillDir, bundledFiles, bundledSkillDir, sha256) {
849
+ const drifted = [];
850
+ for (const rel of bundledFiles) {
851
+ const installedPath = path.join(skillDir, rel);
852
+ const bundledPath = path.join(bundledSkillDir, rel);
853
+ if (!fs.existsSync(installedPath)) {
854
+ drifted.push(`${rel}: missing`);
855
+ continue;
856
+ }
857
+ try {
858
+ if (sha256(installedPath) !== sha256(bundledPath)) drifted.push(`${rel}: differs`);
859
+ } catch {
860
+ drifted.push(`${rel}: unreadable`);
861
+ }
862
+ }
863
+ return drifted;
864
+ }
865
+
866
+ module.exports = {
867
+ configure,
868
+ doctorDelphi,
869
+ checkDelphiAgentBindings,
870
+ checkSkillInstallParity,
871
+ checkDshChannelReadiness,
872
+ reportDshSelection,
873
+ reportHostedSeats,
874
+ reportPinnedSeats,
875
+ disabledBindingVerdict,
876
+ countNativeAgentFiles,
877
+ resolveAgentTarget,
878
+ inspectAgentBinding,
879
+ delphiModelProblems,
880
+ isSeatUsable,
881
+ checkDelphiVersionConsistency,
882
+ listDshProfileConfigs,
883
+ listBundledSkillFiles,
884
+ reportSkillParity,
885
+ reportConfigFile,
886
+ reportConfigShadow,
887
+ checkDelphiConfigPing,
888
+ getCliVersionSafe,
889
+ otherDeployedSkillDirs,
890
+ platformTag,
891
+ fileSha256,
892
+ collectSkillDrift,
893
+ };