@boyingliu01/xp-gate 0.41.66 → 0.41.68

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/lib/doctor.js CHANGED
@@ -4312,843 +4312,15 @@ function formatDoctorJson(checks, issues) {
4312
4312
  * @param {{channels: string[], source: string}} channelResolution how channels resolved
4313
4313
  * @returns {[string, string]} status and detail
4314
4314
  */
4315
- function disabledBindingVerdict(agentsDir, channelResolution) {
4316
- const leftover = countNativeAgentFiles(agentsDir);
4317
- const head = `native channel disabled (channels=${channelResolution.channels.join(',')} `
4318
- + `via ${channelResolution.source}) — `;
4319
- if (leftover > 0) {
4320
- return ['WARN', head + `${leftover} native agent file(s) still present in ${agentsDir}; they are `
4321
- + 'not used but Qoder still loads them — run `xp-gate delphi-setup --uninstall`'];
4322
- }
4323
- return ['SKIP', head + 'Delphi review runs through the external provider'];
4324
- }
4325
-
4326
- /**
4327
- * How many native Delphi agent files exist in `agentsDir` (#711).
4328
- *
4329
- * Used only to tell "disabled cleanly" from "disabled with leftovers" -- a distinction
4330
- * the SKIP line could not express, and one that matters because Qoder still loads the
4331
- * files as custom agents.
4332
- *
4333
- * @param {string} agentsDir directory that may hold `delphi-*.md`
4334
- * @returns {number} matching file count, 0 when unreadable
4335
- */
4336
- function countNativeAgentFiles(agentsDir) {
4337
- try {
4338
- return fs.readdirSync(agentsDir).filter((f) => /^delphi-.*\.md$/.test(f)).length;
4339
- } catch {
4340
- return 0;
4341
- }
4342
- }
4343
-
4344
- function resolveAgentTarget(options) {
4345
- const delphiChannel = require('./delphi-channel.js');
4346
- const channelHome = process.env.XDG_CONFIG_HOME
4347
- ? path.dirname(process.env.XDG_CONFIG_HOME)
4348
- : undefined;
4349
- // #711: pass the project directory so a project-level `channels` field is
4350
- // REPORTED even though it never applies. Before this, a repo whose
4351
- // .delphi-config.json declared channels looked configured and did nothing.
4352
- const channelResolution = delphiChannel.resolveChannels({
4353
- home: channelHome,
4354
- projectDir: options.projectDir || process.cwd(),
4355
- });
4356
-
4357
- const homeAgentsDir = path.join(HOME_DIR(), '.qoder', 'agents');
4358
- // Injectable for tests; defaults to the cwd the doctor runs from.
4359
- const projectAgentsDir = path.join(options.projectDir || process.cwd(), '.qoder', 'agents');
4360
- const homeComplete = DELPHI_ROLES.every((r) => fs.existsSync(path.join(homeAgentsDir, `delphi-${r}.md`)));
4361
- const projectComplete = DELPHI_ROLES.every((r) => fs.existsSync(path.join(projectAgentsDir, `delphi-${r}.md`)));
4362
- const agentsDir = projectComplete ? projectAgentsDir : homeAgentsDir;
4363
- const agentsSource = projectComplete
4364
- ? `project-level ${agentsDir}`
4365
- : `user-level ${agentsDir}`;
4366
-
4367
- return {
4368
- nativeDisabled: !channelResolution.nativeEnabled,
4369
- channelResolution,
4370
- agentsDir,
4371
- agentsSource,
4372
- agentDetails: [agentsSource],
4373
- };
4374
- }
4375
-
4376
- /**
4377
- * Inspect ONE role's installed agent file against the bundled template.
4378
- *
4379
- * The three failure classes are reported separately because each has its own remedy
4380
- * (#414 R1 MI-02): a missing file needs an install, an unparseable binding needs
4381
- * `delphi-setup`, and a bundle without a parseable template is install CORRUPTION --
4382
- * skipping that comparison would hide it behind a healthy-looking id (#414 R1 FC-08).
4383
- *
4384
- * @param {string} role
4385
- * @param {string} agentsDir
4386
- * @param {(p: string) => string|null} readId
4387
- * @returns {{ok: boolean, detail: string, id?: string}}
4388
- */
4389
- function inspectAgentBinding(role, agentsDir, readId) {
4390
- const agentPath = path.join(agentsDir, `delphi-${role}.md`);
4391
- if (!fs.existsSync(agentPath)) {
4392
- return {
4393
- ok: false,
4394
- detail: `delphi-${role}.md missing (run: xp-gate init --global, or delphi-setup --local --project for project scope)`,
4395
- };
4396
- }
4397
- const id = readId(agentPath);
4398
- if (id === null) {
4399
- return { ok: false, detail: `delphi-${role}.md has no quoted model binding (repair: xp-gate delphi-setup)` };
4400
- }
4401
- const bundledId = readId(path.join(PKG_DIR, 'plugins', 'qoder', 'agents', `delphi-${role}.md`));
4402
- if (bundledId === null) {
4403
- return { ok: false, detail: `delphi-${role}: bundled template missing/unreadable — reinstall xp-gate` };
4404
- }
4405
- if (bundledId !== id) {
4406
- return { ok: true, id, detail: `delphi-${role}: ${id} (this version ships ${bundledId} — repair: xp-gate delphi-setup)` };
4407
- }
4408
- return { ok: true, id, detail: `delphi-${role}: ${id}` };
4409
- }
4410
-
4411
- function checkDelphiAgentBindings(add, options) {
4412
- // 2. Qoder agent bindings: present, parseable, three distinct ids, matching
4413
- // what this version ships. A stale binding is a repair, not an error to
4414
- // retype: the detail names delphi-setup. Project-level agents (from
4415
- // `delphi-setup --local --project`) take precedence when a complete set
4416
- // exists there, so the doctor agrees with the repair command (#414 R1 FC-09).
4417
- //
4418
- // #646: when the machine is configured for the external channel only, the native
4419
- // path is DISABLED BY CHOICE, not broken. Reporting FAIL here is what told external
4420
- // users their working setup was broken and pointed them at a repair command that
4421
- // reinstalls the thing they just removed. SKIP carries the reason so the line can
4422
- // never be read as green either -- the same rule every other gate follows.
4423
- const { nativeDisabled, channelResolution, agentsDir, agentsSource, agentDetails } = resolveAgentTarget(options);
4424
- const { readQoderModelId } = require('./init.js');
4425
- const agentIds = [];
4426
- let agentsStatus = 'PASS';
4427
- // #646: skip the whole native binding check when the machine is external-only.
4428
- // The check exists to keep the native path healthy; when that path is switched off
4429
- // by configuration there is nothing to keep healthy, and reporting its absence as
4430
- // FAIL told users their working setup was broken.
4431
- if (nativeDisabled) {
4432
- add('Qoder Delphi agent bindings', ...disabledBindingVerdict(agentsDir, channelResolution));
4433
- }
4434
- for (const role of nativeDisabled ? [] : DELPHI_ROLES) {
4435
- const outcome = inspectAgentBinding(role, agentsDir, readQoderModelId);
4436
- if (!outcome.ok) agentsStatus = 'FAIL';
4437
- agentDetails.push(outcome.detail);
4438
- if (outcome.id) agentIds.push(outcome.id);
4439
- }
4440
- // Report every problem class independently: missing files, unparseable
4441
- // bindings and duplicates can coexist, and each has a different remedy
4442
- // (#414 R1 MI-02).
4443
- //
4444
- // #646: only when the native channel is actually enabled. Running this over an
4445
- // empty agentIds (the disabled path) would compute `0 !== 3` and re-report the very
4446
- // FAIL the SKIP above just replaced.
4447
- if (!nativeDisabled) {
4448
- if (agentIds.length !== DELPHI_ROLES.length) agentsStatus = 'FAIL';
4449
- if (new Set(agentIds).size !== agentIds.length) {
4450
- agentsStatus = 'FAIL';
4451
- agentDetails.push('duplicate model binding across experts — three DISTINCT ids are required');
4452
- }
4453
- add('Qoder Delphi agent bindings', agentsStatus, agentDetails.join('; ') || 'all three bound');
4454
- }
4455
- // #711: the channel preference resolves, so far, from the machine config and
4456
- // the env var. A project that puts `channels` in ITS OWN .delphi-config.json
4457
- // gets no effect from it, and before this line got no warning either -- the
4458
- // file looked authoritative and did nothing. Reported as its own row so the
4459
- // fact is visible whether or not the native path is enabled.
4460
- if (channelResolution.warning) {
4461
- add('Delphi channel preference', 'WARN', channelResolution.warning);
4462
- }
4463
- }
4464
-
4465
- /**
4466
- * Check 3: installed skill copies match what this version ships.
4467
- *
4468
- * A drifted installed copy is how "reinstall from an old local repo" became a
4469
- * downgrade (#414 B4). Every bundled file is compared, not just SKILL.md --
4470
- * the install script copies *.json and references/ too (#414 R1 MI-03).
4471
- *
4472
- * @param {(name: string, status: string, detail?: string) => void} add
4473
- * @param {object} options
4474
- * @returns {string} the resolved installed skill dir, which the runner-locate
4475
- * check below reads. Returning it keeps ONE resolution instead of duplicating
4476
- * the platform mapping at the second call site.
4477
- */
4478
- /**
4479
- * Every file in the bundled skill, relative to its root.
4480
- *
4481
- * A bundle we cannot read is reported as an EMPTY bundle, which the parity check
4482
- * already treats as "every installed file is extra" -- a truthful, loud outcome.
4483
- *
4484
- * @param {string} dir
4485
- * @param {string} [base]
4486
- * @param {string[]} [out]
4487
- * @returns {string[]}
4488
- */
4489
- function listBundledSkillFiles(dir, base = dir, out = []) {
4490
- if (!fs.existsSync(dir)) return out;
4491
- let entries;
4492
- try {
4493
- entries = fs.readdirSync(dir, { withFileTypes: true });
4494
- } catch {
4495
- return out;
4496
- }
4497
- for (const entry of entries) {
4498
- const p = path.join(dir, entry.name);
4499
- if (entry.isDirectory()) listBundledSkillFiles(p, base, out);
4500
- else out.push(path.relative(base, p));
4501
- }
4502
- return out;
4503
- }
4504
-
4505
- /**
4506
- * Compare every deployed copy against the bundle and report the verdict.
4507
- *
4508
- * #725: EVERY platform with the skill deployed is checked, not only the one
4509
- * `detectPlatform()` selects. On a machine with both Qoder and OpenCode the OpenCode
4510
- * copy was frozen at an old version while this check reported PASS, because it never
4511
- * looked there -- the drifted copy was invisible to both `update-skill` and `doctor`.
4512
- */
4513
- function reportSkillParity(add, deployedDirs, bundledFiles, bundledSkillDir, sha256) {
4514
- // #725: check every platform that has the skill deployed, not only the one
4515
- // `detectPlatform()` selects. On a machine with both Qoder and OpenCode the
4516
- // OpenCode copy was frozen at an old version and this check reported PASS,
4517
- // because it never looked there -- the drifted copy was invisible to both
4518
- // `update-skill` and `doctor`.
4519
- const drifted = [];
4520
- for (const dir of deployedDirs) {
4521
- const dirDrift = collectSkillDrift(dir, bundledFiles, bundledSkillDir, sha256);
4522
- if (dirDrift.length > 0) {
4523
- drifted.push(`${platformTag(dir)}: ${dirDrift.join(', ')}`);
4524
- }
4525
- }
4526
- if (drifted.length > 0) {
4527
- add('Delphi skill install parity', 'FAIL',
4528
- `installed copy differs from the ${getCliVersionSafe()} bundle — `
4529
- + `${drifted.slice(0, 3).join('; ')}${drifted.length > 3 ? '; ...' : ''} `
4530
- + '(reinstall: xp-gate install-skill delphi-review --force)');
4531
- } else {
4532
- add('Delphi skill install parity', 'PASS',
4533
- `${bundledFiles.length} file(s) match the bundle across ${deployedDirs.length} platform(s)`);
4534
- }
4535
- }
4536
-
4537
- function checkSkillInstallParity(add, options) {
4538
- // 3. Skill install parity: a drifted installed copy is how "reinstall from
4539
- // an old local repo" became a downgrade (#414 B4). Every bundled file is
4540
- // compared, not just SKILL.md — the install script copies *.json and
4541
- // references/ too, and B4-style drift hits those equally (#414 R1 MI-03).
4542
- //
4543
- // #635 follow-up: this was a THIRD hand-written platform→directory table
4544
- // (after PLATFORM_PROFILES and install-skill's own), and it had no `dsh` arm,
4545
- // so on a DSH machine it resolved to `~/.config/opencode/skills/delphi-review`
4546
- // — a directory that does not exist. `otherDeployedSkillDirs()` below rescued
4547
- // the parity check, but the runner-locate check further down read this path
4548
- // directly and never consulted the full platform set. Derive it instead, so
4549
- // the mapping has one source of truth and a new platform needs no edit here.
4550
- const platform = detectPlatform();
4551
- const installedSkillDir = path.join(getSkillsDirs(platform)[0], 'delphi-review');
4552
- // Injectable for tests (#414 R3 FC-01/FC-02): the empty-bundle branch is a
4553
- // real failure mode and must be drivable without mutating the package.
4554
- const bundledSkillDir = options.bundledSkillDir || path.join(PKG_DIR, 'skills', 'delphi-review');
4555
- const sha256 = (p) => fileSha256(p);
4556
- // A bundle we cannot read is reported as an empty bundle, which the parity check
4557
- // already treats as "every installed file is extra" -- a truthful, loud outcome.
4558
- // #725 follow-up: decide "installed anywhere?" from the full platform set, not
4559
- // just the directory `detectPlatform()` selects — a dsh-only machine has no
4560
- // marker detectPlatform() keys on, so the opencode fallback directory never
4561
- // exists and the old check falsely reported "not installed" even though the
4562
- // copy IS deployed under ~/.dsh/skills.
4563
- const deployedDirs = otherDeployedSkillDirs(installedSkillDir);
4564
- if (deployedDirs.length === 0) {
4565
- add('Delphi skill install parity', 'FAIL',
4566
- `not installed at ${installedSkillDir} (install: xp-gate install-skill delphi-review)`);
4567
- } else {
4568
- const bundledFiles = listBundledSkillFiles(bundledSkillDir);
4569
- if (bundledFiles.length === 0) {
4570
- // An installed copy next to an empty bundle is install corruption —
4571
- // "0 files match" must never read as healthy (#414 R2 MN-R2-01). The
4572
- // bundled dir ships inside the installed package itself, so an
4573
- // unreachable one is a broken install, not a transient condition
4574
- // (#414 R3 FC-05): FAILing is the doctor's job here.
4575
- add('Delphi skill install parity', 'FAIL',
4576
- `bundled skill directory missing or empty: ${bundledSkillDir} — reinstall xp-gate`);
4577
- } else {
4578
- reportSkillParity(add, deployedDirs, bundledFiles, bundledSkillDir, sha256);
4579
- }
4580
- }
4581
- return installedSkillDir;
4582
- }
4583
-
4584
- /**
4585
- * Check 5: the Delphi config parses and names three distinct callable models.
4586
- *
4587
- * Pulled out of `doctorDelphi` because it is the largest single check and the
4588
- * least related to the others: everything above asks "is this installed", this
4589
- * one asks "will a review actually run".
4590
- *
4591
- * @param {(name: string, status: string, detail?: string) => void} add
4592
- */
4593
- /**
4594
- * Problems with a Delphi profile's expert model bindings.
4595
- *
4596
- * Pure: profile in, problem list out. It was inline inside a try/catch inside an
4597
- * if/else inside the config check, four levels down, where the three distinct
4598
- * failure modes (missing role, duplicate model, unusable provider) were one
4599
- * compound condition.
4600
- *
4601
- * @param {object} profile
4602
- * @returns {string[]} human-readable problems; empty when the profile is usable
4603
- */
4604
- function delphiModelProblems(profile) {
4605
- const experts = profile.experts || {};
4606
- const providers = profile.providers || {};
4607
- const models = DELPHI_ROLES.map((r) => experts[r] && experts[r].model);
4608
-
4609
- const missingRoles = DELPHI_ROLES.filter((r, i) => !models[i]);
4610
- const duplicates = models.filter((m, i) => m && models.indexOf(m) !== i);
4611
- const badProviders = DELPHI_ROLES.filter((r) => !isSeatUsable(experts[r], providers));
4612
-
4613
- // Collected as data and filtered once: three `if`s over three lists is three
4614
- // branches to say "report whichever are non-empty".
4615
- return [
4616
- [missingRoles, `missing experts: ${missingRoles.join(', ')}`],
4617
- [duplicates, `duplicate models: ${[...new Set(duplicates)].join(', ')}`],
4618
- [badProviders, `unusable provider binding: ${badProviders.join(', ')}`],
4619
- ].filter(([items]) => items.length > 0).map(([, message]) => message);
4620
- }
4621
-
4622
- /**
4623
- * Whether one expert seat points at a provider that can actually be called.
4624
- *
4625
- * Three ways to fail, and they are reported as one because the remedy is the same
4626
- * (fix the binding): no expert entry, a provider name the config does not define, or
4627
- * a base_url that is missing or not an http(s) URL. The last check is `indexOf('http')
4628
- * === 0` rather than a URL parse on purpose -- a config with `ftp://` or a bare host
4629
- * both fail, and rejecting it early beats a network error later.
4630
- *
4631
- * @param {{provider?: string}|undefined} expert
4632
- * @param {Object<string, {base_url?: string}>} providers
4633
- * @returns {boolean}
4634
- */
4635
- function isSeatUsable(expert, providers) {
4636
- if (!expert) return false;
4637
- const provider = providers[expert.provider];
4638
- if (!provider || !provider.base_url) return false;
4639
- return String(provider.base_url).indexOf('http') === 0;
4640
- }
4641
-
4642
- /**
4643
- * Report whether the installed xp-gate matches npm's latest.
4644
- *
4645
- * The npm probe is opt-in (`probeNpmLatest`) or pre-supplied (`npmLatest`): the
4646
- * doctor never blocks on the network, which an offline CI or a restricted shell
4647
- * would otherwise hit (#414 R1 FC-03).
4648
- *
4649
- * @param {(name: string, status: string, detail?: string) => void} add
4650
- * @param {object} options
4651
- * @param {string|null|undefined} npmLatest
4652
- */
4653
- async function checkDelphiVersionConsistency(add, options, npmLatest) {
4654
- const localVersion = getCliVersionSafe();
4655
- let versionStatus = 'PASS';
4656
- let versionDetail = `xp-gate ${localVersion}`;
4657
-
4658
- if (npmLatest === undefined && options.probeNpmLatest === true) {
4659
- try {
4660
- // `execWithTimeout` is async; reading `.trim()` off the Promise threw, and the
4661
- // catch below swallowed it -- so a WORKING npm probe reported 'offline?' every
4662
- // time. Measured: `Promise.prototype.trim` is undefined.
4663
- const probed = await execWithTimeout('npm view @boyingliu01/xp-gate version', NPM_PROBE_TIMEOUT_MS);
4664
- versionDetail += `; npm latest probe: ${String(probed).trim()}`;
4665
- } catch {
4666
- versionStatus = 'SKIP';
4667
- versionDetail += '; npm latest probe unavailable (offline?) — skipped';
4668
- }
4669
- } else if (typeof npmLatest === 'string' && npmLatest !== localVersion) {
4670
- versionStatus = 'FAIL';
4671
- versionDetail += `; npm latest ${npmLatest} differs from local ${localVersion} — update (npm install -g @boyingliu01/xp-gate@latest) or verify which side is stale`;
4672
- } else if (npmLatest === null || options.probeNpmLatest !== true) {
4673
- versionDetail += '; npm latest probe skipped (pass --npm-check or options.probeNpmLatest to run it)';
4674
- }
4675
- add('Delphi version consistency', versionStatus, versionDetail);
4676
- }
4677
-
4678
-
4679
- /**
4680
- * Check 7: DSH native-channel readiness (#443 REQ-6).
4681
- *
4682
- * Only meaningful when a DSH home exists. The two-layer switch (preset
4683
- * capability plus host setting) defaults to DISABLED, and a review that
4684
- * assumes native will silently run three same-model seats -- the failure this
4685
- * check exists to make visible before a review spends money on it.
4686
- *
4687
- * @param {(name: string, status: string, detail?: string) => void} add
4688
- */
4689
- /**
4690
- * The per-profile configuration layers under a DSH home, if any.
4691
- *
4692
- * DSH stores configuration as a loader patch layer per profile:
4693
- * `profiles/<profile>/cordis.patch.yml`. An empty `[]` is a layer that adds nothing,
4694
- * which is a valid configuration, so existence alone is what this reports -- parsing
4695
- * the YAML to look for a seat override would tie this check to a schema it does not own.
4696
- *
4697
- * @param {string} dshHome the resolved `~/.dsh`
4698
- * @returns {string[]} absolute paths to the layers found
4699
- */
4700
- function listDshProfileConfigs(dshHome) {
4701
- const profilesDir = path.join(dshHome, 'profiles');
4702
- let entries;
4703
- try {
4704
- entries = fs.readdirSync(profilesDir, { withFileTypes: true });
4705
- } catch {
4706
- return [];
4707
- }
4708
- const found = [];
4709
- for (const entry of entries) {
4710
- if (!entry.isDirectory() || entry.name.endsWith('.bak') || entry.name.includes('.bak-')) continue;
4711
- const layer = path.join(profilesDir, entry.name, 'cordis.patch.yml');
4712
- if (fs.existsSync(layer)) found.push(layer);
4713
- }
4714
- return found;
4715
- }
4716
-
4717
- function checkDshChannelReadiness(add) {
4718
- // 7. DSH native-channel readiness (#443 REQ-6): only meaningful when a DSH home
4719
- // exists. The two-layer switch (preset capability + host setting) defaults to
4720
- // disabled, and a review that assumes native will silently run three same-model
4721
- // seats.
4722
- const label = 'DSH subagent model selection';
4723
- const dshHome = path.join(HOME_DIR(), '.dsh');
4724
- if (!fs.existsSync(dshHome)) {
4725
- add(label, 'SKIP', `no ${dshHome} — not a DSH environment`);
4726
- return;
4727
- }
4728
-
4729
- const settingsCandidates = [
4730
- path.join(dshHome, 'settings.json'),
4731
- path.join(dshHome, 'settings', 'settings.json'),
4732
- path.join(dshHome, 'config.json'),
4733
- ];
4734
- const settingsFile = settingsCandidates.find((p) => fs.existsSync(p));
4735
- if (!settingsFile) {
4736
- // #812: the three names above are not where DSH keeps its configuration. Measured
4737
- // on this machine: `~/.dsh/profiles/<profile>/cordis.patch.yml` -- `headless` holds
4738
- // an empty `[]`, `web` holds 628 lines. The directory existed, the configuration
4739
- // existed, and this check called it absent while asserting a CONSEQUENCE
4740
- // ("defaults to disabled") about a setting it had never looked at.
4741
- const profileFiles = listDshProfileConfigs(dshHome);
4742
- if (profileFiles.length > 0) {
4743
- // A profile layer that does not mention subagents is the PLATFORM DEFAULT, not a
4744
- // misconfiguration. Saying FAIL here told a working setup it was broken, which is
4745
- // the same bug family as #646 one level down: "not mentioned" is not "disabled".
4746
- add(label, 'SKIP',
4747
- `${profileFiles.length} DSH profile layer(s) present and no seat override in them `
4748
- + `(e.g. ${path.relative(dshHome, profileFiles[0])}) — subagent model selection `
4749
- + 'is at its platform default, which is not a defect (#812)');
4750
- return;
4751
- }
4752
- add(label, 'FAIL',
4753
- `${dshHome} exists but no settings file found — subagent model selection defaults to disabled (#443)`);
4754
- return;
4755
- }
4756
-
4757
- let settings;
4758
- try {
4759
- settings = JSON.parse(fs.readFileSync(settingsFile, 'utf8'));
4760
- } catch (err) {
4761
- add(label, 'SKIP', `${settingsFile} unparseable: ${err.message}`);
4762
- return;
4763
- }
4764
- reportDshSelection(add, label, settingsFile, settings.subagentModelSelection);
4765
- }
4766
-
4767
- /**
4768
- * Report whether the DSH switch is on AND properly provisioned.
4769
- *
4770
- * The switch shipping OFF is the platform default, not a defect: only an operator who
4771
- * explicitly enables it and under-provisions `allowedModels` has a real
4772
- * misconfiguration (#414 R1 FC-07). Collapsing those two into one FAIL is what told
4773
- * working setups they were broken.
4774
- */
4775
- function reportDshSelection(add, label, settingsFile, selection) {
4776
- const allowed = selection && Array.isArray(selection.allowedModels) ? selection.allowedModels : [];
4777
- const ids = allowed.map((m) => (typeof m === 'string' ? m : m && m.id)).filter(Boolean);
4778
- const distinct = new Set(ids).size;
4779
-
4780
- if (!selection || selection.enabled !== true) {
4781
- add(label, 'SKIP',
4782
- `${settingsFile}: native model selection disabled (platform default) — the external channel is the contract path (#443)`);
4783
- return;
4784
- }
4785
- if (distinct >= MIN_DISTINCT_MODELS) {
4786
- add(label, 'PASS', `${settingsFile}: enabled, ${distinct} distinct allowed models`);
4787
- return;
4788
- }
4789
- add(label, 'FAIL',
4790
- `${settingsFile}: enabled but only ${distinct} distinct allowedModels (need >=${MIN_DISTINCT_MODELS}) — native channel unusable`);
4791
- }
4792
-
4793
- /**
4794
- * Report seats that are not `local-*`, as a WARN.
4795
- *
4796
- * #574: the local-only rule is an operator preference (the 2026-10-03 quota burn),
4797
- * so doctor surfaces the cost exposure without failing a deliberately hosted seat.
4798
- * The HARD enforcement lives in Gate MW, which binds evidence to whatever the config
4799
- * declares rather than to a `local-` prefix. `scripts/check_delphi_local_models.py`
4800
- * holds the same rule with the same allowlist and exit code; reporting it here is
4801
- * what finally gives that guard a caller instead of leaving it in its docstring.
4802
- *
4803
- * @param {Function} add
4804
- * @param {Array<string|undefined>} models one per DELPHI_ROLES entry
4805
- */
4806
- function reportHostedSeats(add, models) {
4807
- const label = 'Delphi local-model guard (#574)';
4808
- const hosted = DELPHI_ROLES
4809
- .map((role, i) => ({ role, model: models[i] }))
4810
- .filter(({ model }) => model && !String(model).toLowerCase().startsWith('local-'));
4811
-
4812
- if (hosted.length === 0) {
4813
- add(label, 'PASS', `all ${DELPHI_ROLES.length} seats are local-*`);
4814
- return;
4815
- }
4816
- add(label, 'WARN',
4817
- `hosted (non local-*) seats: ${hosted.map(({ role, model }) => `${role}=${model}`).join(', ')} — `
4818
- + 'local-only review is the standing rule; check the seats with: xp-gate doctor delphi');
4819
- }
4820
-
4821
- /**
4822
- * Compare the configured seats against the models a project PINNED (#712).
4823
- *
4824
- * WHY A PROJECT-LEVEL DECLARATION
4825
- * The local-only rule above is a fixed WARN, which is right for a preference.
4826
- * A consumer project often has a HARD requirement instead — "these three seats
4827
- * must be exactly these three models" — and had no way to say so: each repo
4828
- * re-implemented the check in its own script, so the constraint lived nowhere
4829
- * upstream and drifted per project.
4830
- *
4831
- * `pinned_models` is that declaration. When it is ABSENT nothing changes (the
4832
- * WARN above stands), so existing configs keep their exact behaviour.
4833
- *
4834
- * A mismatch is FAIL, not WARN: if the project said "exactly these", anything
4835
- * else is a defect the project already decided is unacceptable. Both sides of
4836
- * every difference are printed — "seat differs" without the two values leaves
4837
- * the operator to diff the config by hand.
4838
- *
4839
- * @param {Function} add
4840
- * @param {object} pinned reported `pinned_models`
4841
- * @param {Array<string|undefined>} models one per DELPHI_ROLES entry
4842
- */
4843
- function reportPinnedSeats(add, pinned, models) {
4844
- const label = 'Delphi pinned seats (#712)';
4845
- if (!pinned || typeof pinned !== 'object' || Array.isArray(pinned)) {
4846
- add(label, 'FAIL', 'pinned_models must be an object of role -> model id');
4847
- return;
4848
- }
4849
- const unknown = Object.keys(pinned).filter((r) => !DELPHI_ROLES.includes(r));
4850
- if (unknown.length > 0) {
4851
- // A typo'd role pins nothing and reads as satisfied. Name it.
4852
- add(label, 'FAIL', `pinned_models names unknown role(s): ${unknown.join(', ')} (known: ${DELPHI_ROLES.join(', ')})`);
4853
- return;
4854
- }
4855
- const diffs = DELPHI_ROLES
4856
- .map((role, i) => ({ role, want: pinned[role], got: models[i] }))
4857
- .filter(({ want, got }) => want !== undefined && want !== got);
4858
- if (diffs.length === 0) {
4859
- add(label, 'PASS', `all ${Object.keys(pinned).length} pinned seat(s) match the configured profile`);
4860
- return;
4861
- }
4862
- add(label, 'FAIL', diffs
4863
- .map(({ role, want, got }) => `${role}: pinned ${want}, configured ${got ?? '(none)'}`)
4864
- .join('; '));
4865
- }
4866
-
4867
- /**
4868
- * Warn when a project config shadows a global one whose seats differ.
4869
- *
4870
- * #541: loaders fall back to the global config only on ENOENT, so this project file
4871
- * always wins here. If the machine-wide config exists AND its seats differ, the
4872
- * effective model mix depends on cwd -- the cross-project drift class behind the
4873
- * 2026-10-03 quota burn. WARN, never FAIL: intentional overrides are legal, and only
4874
- * the cwd-dependence is the hazard.
4875
- *
4876
- * Seat shape is object-keyed OR array in the wild (`delphi-config.ts` accepts both),
4877
- * so both sides are normalized before comparing.
4878
- *
4879
- * @param {{add: Function, cfgPath: string, globalConfigPath: string, models: Array}} p
4880
- */
4881
- function reportConfigShadow(p) {
4882
- const { add, cfgPath, globalConfigPath, models } = p;
4883
- try {
4884
- if (!fs.existsSync(globalConfigPath) || path.resolve(globalConfigPath) === path.resolve(cfgPath)) return;
4885
-
4886
- const gRaw = JSON.parse(fs.readFileSync(globalConfigPath, 'utf8'));
4887
- const gProfile = gRaw.profiles && gRaw.profiles[gRaw.active_profile || 'default'];
4888
- const gExperts = (gProfile && gProfile.experts) || {};
4889
- const pickExpert = (experts, role, idx) => {
4890
- if (!experts) return null;
4891
- if (Array.isArray(experts)) {
4892
- const seat = experts.find((x) => x && x.role === role) || experts[idx];
4893
- return (seat && seat.model) || null;
4894
- }
4895
- return (experts[role] && experts[role].model) || null;
4896
- };
4897
- const gModels = DELPHI_ROLES.map((role, i) => pickExpert(gExperts, role, i));
4898
- // Compare only roles BOTH sides define: a role missing on one side is an
4899
- // incomplete config (already FAILed above), not drift.
4900
- const differing = DELPHI_ROLES.filter((role, i) => gModels[i] && models[i] && gModels[i] !== models[i]);
4901
- if (differing.length === 0) return;
4902
-
4903
- add('Delphi config shadow (#541)', 'WARN',
4904
- `project config shadows ${globalConfigPath}; seats differ (${differing.join(', ')}) — `
4905
- + 'reviews run from other directories will use different models');
4906
- } catch {
4907
- // A broken global config is not this check's failure mode; claiming nothing is
4908
- // better than claiming agreement.
4909
- }
4910
- }
4911
-
4912
- /**
4913
- * Read the Delphi config and report whether a review can run from it.
4914
- *
4915
- * The file that was actually read is always named. With both scopes present a user
4916
- * cannot otherwise tell which one the review will take, and that ambiguity is what
4917
- * made #684 hard to see.
4918
- *
4919
- * @param {{add: Function, cfgPath: string, cfgLabel: string,
4920
- * usingGlobalConfig: boolean, globalConfigPath: string}} p
4921
- */
4922
- function reportConfigFile(p) {
4923
- const { add, cfgPath, cfgLabel, usingGlobalConfig, globalConfigPath } = p;
4924
- if (!fs.existsSync(cfgPath)) {
4925
- add(cfgLabel, 'FAIL',
4926
- `${cfgPath} not found (copy .delphi-config.json.example from the skill directory)`);
4927
- } else {
4928
- try {
4929
- const raw = JSON.parse(fs.readFileSync(cfgPath, 'utf8'));
4930
- const profileName = raw.active_profile || 'default';
4931
- const profile = raw.profiles && raw.profiles[profileName];
4932
- if (!profile) {
4933
- add(cfgLabel, 'FAIL', `profile "${profileName}" not found`);
4934
- } else {
4935
- const models = DELPHI_ROLES.map((r) => (profile.experts || {})[r] && profile.experts[r].model);
4936
- const problems = delphiModelProblems(profile);
4937
- if (problems.length > 0) {
4938
- add(cfgLabel, 'FAIL', problems.join('; '));
4939
- } else {
4940
- // Always name the file that was actually read. Without it a user with
4941
- // both scopes present cannot tell which one the review will use — the
4942
- // exact ambiguity that made #684 hard to see.
4943
- const scopeNote = usingGlobalConfig ? ` [global: ${cfgPath}]` : ` [project: ${cfgPath}]`;
4944
- add(cfgLabel, 'PASS',
4945
- `profile "${profileName}": ${models.join(' / ')}${scopeNote}`);
4946
- // #574: non-local seats are reported, not blocked. The local-only rule
4947
- // is an operator preference (the 2026-10-03 quota burn), so doctor
4948
- // surfaces the cost exposure without failing a deliberately hosted
4949
- // seat. The HARD enforcement lives in Gate MW, which binds evidence to
4950
- // whatever this file declares rather than to a local- prefix.
4951
- // `scripts/check_delphi_local_models.py` holds the same rule with the
4952
- // same allowlist and exit code; doctor reports it here so the guard
4953
- // finally has a caller (`xp-gate doctor delphi`) instead of existing
4954
- // only in its own docstring.
4955
- reportHostedSeats(add, models);
4956
- // #712: a project may PIN the three seats. Absent means "no opinion",
4957
- // which keeps every existing config's behaviour identical.
4958
- if (Object.prototype.hasOwnProperty.call(raw, 'pinned_models')) {
4959
- reportPinnedSeats(add, raw.pinned_models, models);
4960
- }
4961
- }
4962
- reportConfigShadow({ add, cfgPath, globalConfigPath, models });
4963
- }
4964
- } catch (err) {
4965
- add(cfgLabel, 'FAIL', `unparseable: ${err.message}`);
4966
- }
4967
- }
4968
-
4969
- }
4970
-
4971
- async function checkDelphiConfigPing(add, options, globalConfigPath) {
4972
- const { configPath, npmLatest } = options;
4973
- // 5. Config ping: parseable, three distinct callable models. A duplicate
4974
- // model here is a review that will BLOCK later — say so now.
4975
- //
4976
- // #684: resolve the SAME way the runner does. A project-local config wins; a
4977
- // machine-level one under XDG_CONFIG_HOME (or ~/.config) is the documented
4978
- // fallback, and a review keeps working on it. Checking only `cwd` reported
4979
- // FAIL on the layout SKILL.md recommends and told the user to copy the example
4980
- // into the project — manufacturing the drifted duplicate #541 warns about.
4981
- //
4982
- // An explicit `configPath` is an ANSWER, not a hint: a caller that names a
4983
- // file means that file, so it disables the fallback. Otherwise a test (or a
4984
- // caller) pinning an absent path silently reads the developer's real global
4985
- // config and reports PASS — the same vacuous-pass shape this batch is fixing.
4986
- const projectCfgPath = configPath
4987
- || path.join(options.projectDir || process.cwd(), '.delphi-config.json');
4988
- const usingGlobalConfig = !configPath
4989
- && !fs.existsSync(projectCfgPath)
4990
- && fs.existsSync(globalConfigPath);
4991
- const cfgPath = usingGlobalConfig ? globalConfigPath : projectCfgPath;
4992
- const cfgLabel = 'Delphi config (.delphi-config.json)';
4993
- reportConfigFile({ add, cfgPath, cfgLabel, usingGlobalConfig, globalConfigPath });
4994
-
4995
- // 6. Version consistency.
4996
- await checkDelphiVersionConsistency(add, options, npmLatest);
4997
-
4998
-
4999
- // 7. DSH native-channel readiness.
5000
- checkDshChannelReadiness(add);
5001
-
5002
- }
5003
-
5004
- async function doctorDelphi(options = {}) {
5005
- const { configPath, npmLatest } = options;
5006
- // #541: the shadow check needs the loader's global fallback path. It is
5007
- // injectable for tests; the default mirrors delphi-config.ts /
5008
- // delphi-external-review.cjs resolution (XDG_CONFIG_HOME honored).
5009
- const globalConfigPath = options.globalConfigPath
5010
- || path.join(process.env.XDG_CONFIG_HOME || path.join(require('os').homedir(), '.config'), 'xp-gate', '.delphi-config.json');
5011
- const checks = [];
5012
- const add = (name, status, detail) => checks.push({ name, status, detail });
5013
-
5014
- // 1. Node >= 18: the runner gates on it and exits 1 mid-review otherwise.
5015
- const nodeMajor = parseInt(process.versions.node.split('.')[0], 10);
5016
- add(`Node.js >= ${MIN_NODE_MAJOR}`, nodeMajor >= MIN_NODE_MAJOR ? 'PASS' : 'FAIL',
5017
- `current: ${process.versions.node}`);
5018
-
5019
- // 2. Qoder agent bindings.
5020
- checkDelphiAgentBindings(add, options);
5021
-
5022
- // 3. Skill install parity. It also resolves the installed skill dir, which
5023
- // the runner-locate check below needs.
5024
- const installedSkillDir = checkSkillInstallParity(add, options);
5025
-
5026
- // 4. Runner script locate: the runner must be findable from the places a
5027
- // review actually starts.
5028
- const runnerCandidates = [
5029
- ['package bundle', path.join(PKG_DIR, 'scripts', 'delphi-external-review.cjs')],
5030
- ['project', path.join(process.cwd(), 'scripts', 'delphi-external-review.cjs')],
5031
- ['installed skill', path.join(installedSkillDir, 'scripts', 'delphi-external-review.cjs')],
5032
- ];
5033
- const foundRunner = runnerCandidates.filter(([, p]) => fs.existsSync(p));
5034
- add('delphi-external-review runner', foundRunner.length > 0 ? 'PASS' : 'FAIL',
5035
- foundRunner.length > 0
5036
- ? foundRunner.map(([label, p]) => `${label}: ${p}`).join('; ')
5037
- : 'not found in package bundle, project, or installed skill');
5038
-
5039
- // 5. Config ping.
5040
- await checkDelphiConfigPing(add, options, globalConfigPath);
5041
-
5042
- for (const check of checks) {
5043
- const mark = check.status === 'PASS' ? '✓' : check.status === 'SKIP' ? '○' : check.status === 'WARN' ? '⚠' : '✗';
5044
- console.log(` ${mark} ${check.name}: ${check.detail || check.status}`);
5045
- }
5046
- const failed = checks.filter((c) => c.status === 'FAIL').length;
5047
- console.log('');
5048
- console.log(failed === 0
5049
- ? ' Delphi review chain: healthy.'
5050
- : ` Delphi review chain: ${failed} check(s) FAILED.`);
5051
- return failed === 0 ? 0 : 1;
5052
- }
5053
-
5054
- function getCliVersionSafe() {
5055
- try {
5056
- return require('../package.json').version || '0.0.0';
5057
- } catch {
5058
- return '0.0.0';
5059
- }
5060
- }
5061
-
5062
- /**
5063
- * Skills directories that hold the delphi-review skill, including the detected one.
5064
- *
5065
- * #725: `detectPlatform()` returns a single platform, so on a machine carrying
5066
- * both Qoder and OpenCode the OpenCode copy of the skill was never examined —
5067
- * `update-skill` did not refresh it and `doctor` reported PASS anyway. Both were
5068
- * looking at the same one directory. A migration period (user moved between AI
5069
- * tools, both trees still live) is the normal case that produces this, and the
5070
- * frozen copy is exactly what a parity check exists to catch.
5071
- *
5072
- * The original fix still hardcoded the three pre-dsh platforms, so the DSH copy
5073
- * (`~/.dsh/skills/delphi-review`) — which `detectPlatform()` never returns and
5074
- * `PLATFORM_PROFILES` does carry — stayed invisible. Derive the candidates from
5075
- * the profiles so every installed platform is examined.
5076
- *
5077
- * @param {string} detectedDir the platform `detectPlatform()` selected
5078
- * @returns {string[]} directories that actually contain the skill
5079
- */
5080
- function otherDeployedSkillDirs(detectedDir) {
5081
- const candidates = [detectedDir];
5082
- for (const platform of detectInstalledPlatforms()) {
5083
- candidates.push(path.join(getSkillsDirs(platform)[0], 'delphi-review'));
5084
- }
5085
- const seen = new Set();
5086
- const found = [];
5087
- for (const dir of candidates) {
5088
- if (seen.has(dir)) continue;
5089
- seen.add(dir);
5090
- if (fs.existsSync(path.join(dir, 'SKILL.md'))) found.push(dir);
5091
- }
5092
- return found;
5093
- }
5094
-
5095
- /**
5096
- * A short label for a skills directory: the platform segment, not the full path.
5097
- * Keeps the doctor line readable when two platforms disagree.
5098
- */
5099
- function platformTag(skillDir) {
5100
- const parent = path.basename(path.dirname(path.dirname(skillDir)));
5101
- return parent === 'opencode' ? 'opencode' : parent;
5102
- }
5103
-
5104
- /**
5105
- * Files in `skillDir` that are missing or differ from the bundle.
5106
- * @returns {string[]} `rel: reason` entries; empty when the copy is clean
5107
- */
5108
- /**
5109
- * Files where an installed skill copy differs from the bundle.
5110
- *
5111
- * An unreadable file is reported as `unreadable` rather than skipped: a copy we
5112
- * cannot check is not a copy we can call matching, and silence here would let a
5113
- * permissions problem pass as parity.
5114
- */
5115
- /**
5116
- * SHA-256 of a file, or a thrown error naming the path.
5117
- *
5118
- * A digest is used to compare two copies; a read failure must not yield a digest
5119
- * that happens to differ, because "cannot read" and "differs" need different
5120
- * repairs.
5121
- *
5122
- * @param {string} filePath
5123
- * @returns {string}
5124
- */
5125
- function fileSha256(filePath) {
5126
- let content;
5127
- try {
5128
- content = fs.readFileSync(filePath);
5129
- } catch (err) {
5130
- throw new Error(`cannot hash ${filePath}: ${err.message}`);
5131
- }
5132
- return require('crypto').createHash('sha256').update(content).digest('hex');
5133
- }
4315
+ // The Delphi review chain lives in doctor-delphi.js (#750 split of a 5201-line
4316
+ // file). It is wired here rather than required there, because this module
4317
+ // re-exports its entry points and a require in that direction is a cycle.
4318
+ const doctorDelphiModule = require('./doctor-delphi.js');
4319
+ if (typeof doctorDelphiModule.configure === 'function') doctorDelphiModule.configure({ execWithTimeout, MIN_NODE_MAJOR, NPM_PROBE_TIMEOUT_MS });
4320
+ const {
4321
+ doctorDelphi, checkDshChannelReadiness,
4322
+ } = doctorDelphiModule;
5134
4323
 
5135
- function collectSkillDrift(skillDir, bundledFiles, bundledSkillDir, sha256) {
5136
- const drifted = [];
5137
- for (const rel of bundledFiles) {
5138
- const installedPath = path.join(skillDir, rel);
5139
- const bundledPath = path.join(bundledSkillDir, rel);
5140
- if (!fs.existsSync(installedPath)) {
5141
- drifted.push(`${rel}: missing`);
5142
- continue;
5143
- }
5144
- try {
5145
- if (sha256(installedPath) !== sha256(bundledPath)) drifted.push(`${rel}: differs`);
5146
- } catch {
5147
- drifted.push(`${rel}: unreadable`);
5148
- }
5149
- }
5150
- return drifted;
5151
- }
5152
4324
 
5153
4325
  module.exports = {
5154
4326
  checkDshChannelReadiness,