pantheon-opencode 1.6.0-beta.9 → 1.6.0

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 (131) hide show
  1. package/AGENTS.global.md +118 -0
  2. package/AGENTS.md +18 -168
  3. package/CHANGELOG.md +126 -376
  4. package/README.md +83 -610
  5. package/README.pt-BR.md +120 -345
  6. package/bin/pantheon-init.mjs +366 -132
  7. package/commands/pantheon-deepwork.md +14 -3
  8. package/commands/pantheon-vision.md +61 -12
  9. package/package.json +19 -11
  10. package/plugin.json +1 -1
  11. package/pyproject.toml +6 -2
  12. package/scripts/_pantheon_paths.py +24 -0
  13. package/scripts/build-agents-md.mjs +368 -69
  14. package/scripts/changelog-merge.mjs +161 -0
  15. package/scripts/check-plugin-v2-coverage.mjs +11 -8
  16. package/scripts/docs-check-changelog.mjs +204 -0
  17. package/scripts/docs-link-check.mjs +314 -0
  18. package/scripts/docs-media.mjs +157 -0
  19. package/scripts/doctor.mjs +828 -40
  20. package/scripts/install/agents-md.mjs +2 -2
  21. package/scripts/install/backup.mjs +648 -0
  22. package/scripts/install/cli-ui.mjs +303 -72
  23. package/scripts/install/component-selection.mjs +61 -0
  24. package/scripts/install/config-migration.mjs +583 -27
  25. package/scripts/install/exit-codes.mjs +26 -0
  26. package/scripts/install/file-inventory.mjs +555 -0
  27. package/scripts/install/health-check.mjs +31 -25
  28. package/scripts/install/interactive.mjs +78 -383
  29. package/scripts/install/migrate.mjs +49 -25
  30. package/scripts/install/model-picker.mjs +218 -250
  31. package/scripts/install/opencode-version.mjs +83 -21
  32. package/scripts/install/opencode.mjs +1413 -154
  33. package/scripts/install/plan-artifact.mjs +517 -0
  34. package/scripts/install/plan.mjs +475 -0
  35. package/scripts/install/plugin.mjs +214 -27
  36. package/scripts/install/prompt-result.mjs +2 -0
  37. package/scripts/install/shared.mjs +256 -99
  38. package/scripts/install/state.mjs +63 -8
  39. package/scripts/install/strings.mjs +60 -4
  40. package/scripts/install/venv.mjs +90 -47
  41. package/scripts/install/verify.mjs +128 -0
  42. package/scripts/install/vision-prompt.mjs +173 -0
  43. package/scripts/install-mcp.mjs +2 -2
  44. package/scripts/manifest-inventory.mjs +49 -3
  45. package/scripts/mcp_persistence.py +1535 -1050
  46. package/scripts/memory_mcp.py +12 -843
  47. package/scripts/node-engine-policy.mjs +85 -0
  48. package/scripts/package-evidence.mjs +10 -2
  49. package/scripts/postinstall.mjs +26 -26
  50. package/scripts/probe-pantheon-cost.mjs +118 -19
  51. package/scripts/prune.mjs +9 -3
  52. package/scripts/reconcile.mjs +325 -0
  53. package/scripts/release-gates.mjs +682 -0
  54. package/scripts/restore.mjs +222 -0
  55. package/scripts/run-node-tests.mjs +24 -8
  56. package/scripts/sync-artifacts.mjs +19 -7
  57. package/scripts/sync-tui.mjs +5 -1
  58. package/scripts/test-opencode-v2-sandbox.sh +36 -123
  59. package/scripts/uninstall.mjs +369 -34
  60. package/scripts/update.mjs +164 -0
  61. package/scripts/validate-node-engine-policy.mjs +13 -0
  62. package/scripts/version-check.mjs +34 -1
  63. package/scripts/versioning.mjs +23 -3
  64. package/scripts/vision-status.mjs +682 -0
  65. package/skills-lock.json +8 -8
  66. package/src/agents/aphrodite.md +13 -10
  67. package/src/agents/apollo.md +4 -5
  68. package/src/agents/athena.md +74 -46
  69. package/src/agents/demeter.md +10 -7
  70. package/src/agents/gaia.md +0 -1
  71. package/src/agents/hephaestus.md +4 -3
  72. package/src/agents/hermes.md +10 -9
  73. package/src/agents/iris.md +6 -1
  74. package/src/agents/mnemosyne.md +10 -4
  75. package/src/agents/nyx.md +4 -4
  76. package/src/agents/prometheus.md +12 -11
  77. package/src/agents/talos.md +6 -0
  78. package/src/agents/zeus.md +84 -56
  79. package/src/instructions/agent-return-format.instructions.md +12 -41
  80. package/src/instructions/memory-protocol.instructions.md +5 -11
  81. package/src/instructions/test-economy.instructions.md +12 -0
  82. package/src/instructions/yagni.instructions.md +6 -15
  83. package/src/instructions/zeus-anti-stall.instructions.md +6 -6
  84. package/src/instructions/zeus-communication-rules.instructions.md +6 -6
  85. package/src/instructions/zeus-council-synthesis.instructions.md +11 -12
  86. package/src/instructions/zeus-memory-operations.instructions.md +13 -7
  87. package/src/instructions/zeus-timeout-retry.instructions.md +36 -10
  88. package/src/mcp/_pantheon_paths.py +24 -0
  89. package/src/mcp/mcp_codemap_module.py +86 -18
  90. package/src/mcp/mcp_persistence.py +1535 -1050
  91. package/src/mcp/memory_mcp.py +444 -94
  92. package/src/mcp/pantheon_vision.py +285 -41
  93. package/src/mcp/requirements-mcp.txt +5 -0
  94. package/src/pantheon/context-pruner.ts +541 -0
  95. package/src/pantheon/cost-command.ts +814 -60
  96. package/src/pantheon/goal-loop.ts +11 -8
  97. package/src/pantheon/memory-context.ts +1017 -0
  98. package/src/pantheon/model-agents.ts +19 -0
  99. package/src/pantheon/model-command.ts +218 -56
  100. package/src/pantheon/model-pricing.ts +536 -0
  101. package/src/pantheon/presets.mjs +2 -0
  102. package/src/pantheon/task-result-guard.ts +50 -14
  103. package/src/pantheon/v2-bounded-read.ts +640 -0
  104. package/src/pantheon/v2-delegation-enforce.ts +133 -6
  105. package/src/pantheon/v2-execute-after.ts +135 -24
  106. package/src/pantheon/v2-model-overrides.ts +275 -0
  107. package/src/pantheon/v2-tools.ts +89 -35
  108. package/src/pantheon/v2-unsupported.mjs +2 -3
  109. package/src/pantheon/v2-vision.ts +622 -0
  110. package/src/pantheon/vision-local.ts +531 -0
  111. package/src/pantheon/vision.ts +1160 -115
  112. package/src/plugin-v2.ts +654 -162
  113. package/src/plugin.ts +15 -11
  114. package/src/plugins/tui/dist/tui-v2.d.ts +1029 -2
  115. package/src/plugins/tui/dist/tui-v2.d.ts.map +1 -1
  116. package/src/plugins/tui/dist/tui-v2.js +3742 -85
  117. package/src/plugins/tui/dist/tui.js +1 -1
  118. package/src/plugins/tui/package-lock.json +6 -6
  119. package/src/plugins/tui/package.json +5 -4
  120. package/src/plugins/tui/src/index-v2.tsx +4314 -50
  121. package/src/plugins/tui/tsconfig.typecheck.json +5 -0
  122. package/src/routing.yml +50 -5
  123. package/src/skills/agent-coordination/SKILL.md +7 -2
  124. package/src/skills/artifact-management/SKILL.md +5 -1
  125. package/src/skills/auto-continue/SKILL.md +14 -6
  126. package/src/skills/codemap/SKILL.md +1 -1
  127. package/src/skills/memory-bank/SKILL.md +21 -13
  128. package/src/skills/session-goal/SKILL.md +12 -22
  129. package/src/skills/spec-driven-development/SKILL.md +3 -1
  130. package/src/skills/worktrees/SKILL.md +30 -11
  131. package/scripts/probe-context-rehydrate.mjs +0 -263
@@ -30,6 +30,10 @@ import { basename, dirname, isAbsolute, join, resolve } from 'node:path'
30
30
  import { fileURLToPath } from 'node:url'
31
31
 
32
32
  import { listV2UnsupportedFeatures } from '../src/pantheon/v2-unsupported.mjs'
33
+ import { classifyFileInventory } from './install/file-inventory.mjs'
34
+ import { staleTuiRefs } from './install/plugin.mjs'
35
+ import { readState } from './install/state.mjs'
36
+ import { isSupportedNodeVersion, MIN_SUPPORTED_NODE_VERSION } from './node-engine-policy.mjs'
33
37
 
34
38
  // ---------------------------------------------------------------------------
35
39
  // Paths
@@ -47,6 +51,9 @@ const counts = { pass: 0, warn: 0, error: 0, info: 0 }
47
51
 
48
52
  const results = []
49
53
  let exitCode = 0
54
+ let jsonMode = false
55
+ let jsonOriginalWrite = null
56
+ let jsonArgs = null
50
57
 
51
58
  // ---------------------------------------------------------------------------
52
59
  // CLI arg parsing
@@ -58,6 +65,7 @@ function parseArgs(argv) {
58
65
  platform: null,
59
66
  fix: false,
60
67
  verbose: false,
68
+ json: false,
61
69
  help: false,
62
70
  profile: process.env.PANTHEON_PROFILE ?? 'auto',
63
71
  }
@@ -73,6 +81,9 @@ function parseArgs(argv) {
73
81
  case '--verbose':
74
82
  args.verbose = true
75
83
  break
84
+ case '--json':
85
+ args.json = true
86
+ break
76
87
  case '--profile':
77
88
  args.profile = argv[++i] ?? 'auto'
78
89
  break
@@ -123,29 +134,51 @@ const ICON = {
123
134
  info: '\u2139\uFE0F', // ℹ️
124
135
  }
125
136
 
126
- function emit(category, message) {
137
+ // Per-section tally of PASS checks. Without --verbose the individual passing
138
+ // lines are suppressed, so a section used to print its header and then nothing
139
+ // — indistinguishable from a check that never ran. The tally is flushed when
140
+ // the next section starts (and before the summary) so every section accounts
141
+ // for itself.
142
+ let sectionPasses = 0
143
+
144
+ function verboseOutput() {
145
+ return process.argv.includes('--verbose')
146
+ }
147
+
148
+ function flushSectionPasses() {
149
+ const passed = sectionPasses
150
+ sectionPasses = 0
151
+ if (passed === 0 || verboseOutput()) return
152
+ console.log(` ${ICON.pass} ${passed} ${passed === 1 ? 'check' : 'checks'} passed`)
153
+ }
154
+
155
+ function emit(category, message, metadata = {}) {
127
156
  counts[category]++
128
- results.push({ category, message })
129
- if (category === 'pass' && !process.argv.includes('--verbose')) return
157
+ results.push({ category, message, ...metadata })
158
+ if (category === 'pass' && !verboseOutput()) {
159
+ sectionPasses++
160
+ return
161
+ }
130
162
  const prefix = ICON[category] ?? category
131
163
  console.log(` ${prefix} ${message}`)
132
164
  }
133
165
 
134
- function pass(msg) {
135
- emit('pass', msg)
166
+ function pass(msg, metadata = {}) {
167
+ emit('pass', msg, metadata)
136
168
  }
137
- function warn(msg) {
138
- emit('warn', msg)
169
+ function warn(msg, metadata = {}) {
170
+ emit('warn', msg, metadata)
139
171
  }
140
- function error(msg) {
141
- emit('error', msg)
172
+ function error(msg, metadata = {}) {
173
+ emit('error', msg, metadata)
142
174
  exitCode = 2
143
175
  }
144
- function info(msg) {
145
- emit('info', msg)
176
+ function info(msg, metadata = {}) {
177
+ emit('info', msg, metadata)
146
178
  }
147
179
 
148
180
  function section(title) {
181
+ flushSectionPasses()
149
182
  console.log(`\n${'='.repeat(60)}`)
150
183
  console.log(` ${title}`)
151
184
  console.log(`${'='.repeat(60)}`)
@@ -159,7 +192,8 @@ function showHelp() {
159
192
  node scripts/doctor.mjs auto-detect, cwd
160
193
  node scripts/doctor.mjs --target /path/to/project target project
161
194
  node scripts/doctor.mjs --profile global|lite|sandbox profile policy
162
- node scripts/doctor.mjs --fix attempt auto-fixes
195
+ node scripts/doctor.mjs --fix attempt auto-fixes
196
+ node scripts/doctor.mjs --json read-only JSON report
163
197
  node scripts/doctor.mjs --verbose detailed output
164
198
  node scripts/doctor.mjs --help show this help
165
199
 
@@ -173,6 +207,7 @@ function showHelp() {
173
207
  E. Git Status — uncommitted changes
174
208
  F. Runtime Layer — runtime Python + pinned pip dependencies
175
209
  H3. Plugin Drift — registered plugin version vs this package
210
+ H5. TUI Plugin — copied TUI payload + host registration (fail-closed)
176
211
  K. Node Runtime — node:sqlite availability for pantheon_cost
177
212
 
178
213
  Exit codes:
@@ -322,7 +357,10 @@ function checkMcpConfig(args) {
322
357
  section('B. MCP Configuration')
323
358
 
324
359
  const configs = collectMcpConfigs(args)
325
- const requiredMcpNames = args.profile === 'lite' ? [] : ['pantheon-memory', 'pantheon-resources']
360
+ // This required-server check tests config-entry presence only. It does not
361
+ // verify enabled state, command/transport usability, connectivity, or health.
362
+ const requiredMcpNames =
363
+ args.profile === 'lite' ? [] : ['pantheon-memory', 'pantheon-resources', 'pantheon-persistence']
326
364
 
327
365
  if (configs.length === 0) {
328
366
  if (requiredMcpNames.length > 0) {
@@ -436,7 +474,9 @@ function checkMcpConfig(args) {
436
474
  const configured = new Set(configs.flatMap((cfg) => Object.keys(cfg.data.mcp ?? {})))
437
475
  for (const required of requiredMcpNames) {
438
476
  if (configured.has(required))
439
- pass(`Required MCP "${required}" configured in an available config`)
477
+ pass(
478
+ `Required MCP "${required}" entry is present (presence check only; this check does not verify enabled state, command/transport usability, connectivity, or health)`,
479
+ )
440
480
  else error(`Required MCP "${required}" not configured in any available config`)
441
481
  }
442
482
  }
@@ -1265,6 +1305,7 @@ export function checkInstallVersionDrift(args) {
1265
1305
  warn(
1266
1306
  `Package v${pkgVersion} is newer than the last-synced installation (v${installed}) — ` +
1267
1307
  'run `npx pantheon-opencode update` (or re-run init) to refresh config, venv and MCP entries',
1308
+ { code: 'install_version_drift', classification: 'advisory' },
1268
1309
  )
1269
1310
  return 'package-newer'
1270
1311
  }
@@ -1272,6 +1313,7 @@ export function checkInstallVersionDrift(args) {
1272
1313
  warn(
1273
1314
  `Installation marker (v${installed}) is newer than this package (v${pkgVersion}) — ` +
1274
1315
  'the doctor is running from a different install than the last sync',
1316
+ { code: 'install_version_drift', classification: 'advisory' },
1275
1317
  )
1276
1318
  return 'install-newer'
1277
1319
  }
@@ -1315,6 +1357,80 @@ export function resolveInstalledPackageRoot(pluginPath) {
1315
1357
  return normalized.slice(0, index + INSTALLED_PACKAGE_MARKER.length - 1)
1316
1358
  }
1317
1359
 
1360
+ /**
1361
+ * The plugin identities the installer writes into the host config
1362
+ * (`resolveInstalledPlugin` in scripts/install/opencode.mjs). Only these refs —
1363
+ * and absolute paths to them inside an installed package — are owned by
1364
+ * Pantheon; anything else belongs to the user and is never checked here.
1365
+ */
1366
+ const MANAGED_PLUGIN_IDENTITIES = new Set([
1367
+ 'src/plugin.ts',
1368
+ 'src/plugins/pantheon-hooks.ts',
1369
+ 'src/plugin-v2',
1370
+ // Legacy V2 file ref from before the directory contract (still migrated by
1371
+ // the installer, so a pre-migration config is ours too).
1372
+ 'src/plugin-v2.ts',
1373
+ ])
1374
+
1375
+ /**
1376
+ * Return the normalized path of a Pantheon-owned plugin registration, or null
1377
+ * when the ref is not a filesystem path this installer writes.
1378
+ *
1379
+ * P0-6: the installer stores an ABSOLUTE path (`join(ROOT, identity)`) and only
1380
+ * `init` re-resolves it. A dangling registration is therefore a real install
1381
+ * defect, and telling it apart from a third-party path requires this identity
1382
+ * check rather than a basename test — an unrelated user plugin may legitimately
1383
+ * end in `src/plugin.ts`.
1384
+ *
1385
+ * npm specs (`pantheon-opencode`, `pantheon-opencode/plugin-v2`) and
1386
+ * third-party paths are NOT paths this installer owns, so they return null and
1387
+ * are never reported.
1388
+ *
1389
+ * @param {unknown} ref
1390
+ * @returns {string|null}
1391
+ */
1392
+ export function managedPluginPath(ref) {
1393
+ if (typeof ref !== 'string') return null
1394
+ const normalized = ref.replaceAll('\\', '/').replace(/\/$/, '')
1395
+ if (MANAGED_PLUGIN_IDENTITIES.has(normalized)) return normalized
1396
+ const index = normalized.toLowerCase().lastIndexOf(INSTALLED_PACKAGE_MARKER.toLowerCase())
1397
+ if (index === -1) return null
1398
+ const suffix = normalized.slice(index + INSTALLED_PACKAGE_MARKER.length)
1399
+ return MANAGED_PLUGIN_IDENTITIES.has(suffix) ? normalized : null
1400
+ }
1401
+
1402
+ /**
1403
+ * Report every Pantheon-owned plugin registration whose target is missing.
1404
+ *
1405
+ * Fail-closed by design: the host drops a plugin it cannot load without an
1406
+ * error, so a dangling registration silently downgrades the install to "no
1407
+ * Pantheon tool surface at all". A version comparison cannot catch this — there
1408
+ * is no package to read a version from — which is exactly how the defect stayed
1409
+ * invisible.
1410
+ *
1411
+ * @param {{path: string, configPath: string, configLabel: string}[]} refs
1412
+ * @returns {boolean} true when at least one dangling registration was reported
1413
+ */
1414
+ function reportDanglingPluginRegistrations(refs) {
1415
+ let reported = false
1416
+ for (const ref of refs) {
1417
+ if (managedPluginPath(ref.path) === null) continue
1418
+ // Relative refs resolve against the config directory, never the doctor's
1419
+ // cwd — the same rule the host loader and the drift comparison use.
1420
+ const absolute = isAbsolute(ref.path) ? ref.path : resolve(dirname(ref.configPath), ref.path)
1421
+ if (existsSync(absolute)) continue
1422
+ reported = true
1423
+ error(
1424
+ `${ref.configLabel}: Pantheon plugin is registered at ${ref.path}, which does not exist — ` +
1425
+ 'the host silently drops a plugin it cannot load, so this install runs without the Pantheon tool surface ' +
1426
+ '(an upgrade that did not run `init` leaves the previous absolute path behind). ' +
1427
+ 'Run `pantheon-opencode init` to re-resolve the registration to the installed tree',
1428
+ { code: 'plugin_path_missing', classification: 'error' },
1429
+ )
1430
+ }
1431
+ return reported
1432
+ }
1433
+
1318
1434
  /**
1319
1435
  * Read the version of the installed pantheon-opencode package a registered
1320
1436
  * plugin path points into.
@@ -1360,14 +1476,21 @@ export function collectRegisteredPluginRefs(configs) {
1360
1476
  if (!Array.isArray(list)) continue
1361
1477
  for (const ref of list) {
1362
1478
  if (typeof ref === 'string') {
1363
- refs.push({ path: ref, configPath: cfg.path, configLabel: cfg.label })
1479
+ refs.push({ path: ref, key, configPath: cfg.path, configLabel: cfg.label })
1364
1480
  } else if (ref && typeof ref === 'object') {
1365
- // Object-shaped entries carry their path under `path`/`source`.
1366
- const objectPath = ['path', 'source', 'id', 'name'].find(
1481
+ // Object-shaped entries carry their path under `package` (what the
1482
+ // V2 writer emits when it preserves plugin options), `path`/`source`
1483
+ // (host spellings) or `id`/`name`.
1484
+ const objectPath = ['package', 'path', 'source', 'id', 'name'].find(
1367
1485
  (k) => typeof ref[k] === 'string',
1368
1486
  )
1369
1487
  if (objectPath) {
1370
- refs.push({ path: ref[objectPath], configPath: cfg.path, configLabel: cfg.label })
1488
+ refs.push({
1489
+ path: ref[objectPath],
1490
+ key,
1491
+ configPath: cfg.path,
1492
+ configLabel: cfg.label,
1493
+ })
1371
1494
  }
1372
1495
  }
1373
1496
  }
@@ -1379,27 +1502,34 @@ export function collectRegisteredPluginRefs(configs) {
1379
1502
  /**
1380
1503
  * Compare the version of the package each registered plugin points into (when
1381
1504
  * it is an installed copy under node_modules/pantheon-opencode) against this
1382
- * package's own version, and warn on divergence. Advisory only — a drift
1383
- * warning never changes the exit code, and a healthy install stays silent.
1505
+ * package's own version, and warn on divergence. A drift warning is advisory
1506
+ * (a pinned copy is a legitimate choice); a Pantheon registration that points
1507
+ * at a path that no longer exists is a blocking error ('stale').
1384
1508
  * @param {object} args
1385
- * @returns {'drift'|'sync'|'skip'|'no-plugin'|'no-version'}
1509
+ * @returns {'stale'|'drift'|'sync'|'skip'|'no-plugin'|'no-version'}
1386
1510
  */
1387
1511
  export function checkPluginVersionDrift(args) {
1388
1512
  section('H3. Plugin Version Drift')
1389
1513
 
1390
- const pkg = readJson(join(ROOT, 'package.json'))
1391
- const packageVersion = pkg?.version
1392
- if (!packageVersion) {
1393
- info('Plugin version drift skipped — this package has no readable version')
1394
- return 'no-version'
1395
- }
1396
-
1397
1514
  const refs = collectRegisteredPluginRefs(collectMcpConfigs(args))
1398
1515
  if (refs.length === 0) {
1399
1516
  info('No plugin registrations found in opencode.json — version drift skipped')
1400
1517
  return 'no-plugin'
1401
1518
  }
1402
1519
 
1520
+ // P0-6: a missing tree has no version to compare, so the comparison loop
1521
+ // below used to `continue` past it and report "skipped" — the defect was
1522
+ // silent. Check existence first so the dangling case fails closed regardless
1523
+ // of whether this package's own version is readable.
1524
+ const staleReported = reportDanglingPluginRegistrations(refs)
1525
+
1526
+ const pkg = readJson(join(ROOT, 'package.json'))
1527
+ const packageVersion = pkg?.version
1528
+ if (!packageVersion) {
1529
+ info('Plugin version drift skipped — this package has no readable version')
1530
+ return staleReported ? 'stale' : 'no-version'
1531
+ }
1532
+
1403
1533
  const seen = new Set()
1404
1534
  let compared = 0
1405
1535
  let driftReported = false
@@ -1421,6 +1551,7 @@ export function checkPluginVersionDrift(args) {
1421
1551
  )
1422
1552
  }
1423
1553
 
1554
+ if (staleReported) return 'stale'
1424
1555
  if (driftReported) return 'drift'
1425
1556
  if (compared === 0) {
1426
1557
  info(
@@ -1579,6 +1710,126 @@ export function checkV2UnsupportedFeatures(args) {
1579
1710
  return verdict.status
1580
1711
  }
1581
1712
 
1713
+ /**
1714
+ * Where the TUI checker must look for a config dir's plugin payload.
1715
+ *
1716
+ * Mirrors the installer's own layout rule (`isGlobalConfigDir` + flat global
1717
+ * layout vs `.opencode/` project layout) through the installer exports rather
1718
+ * than re-deriving it, so the check cannot drift from what init writes.
1719
+ *
1720
+ * @param {{target: string}} args
1721
+ * @returns {Promise<{isGlobal: boolean, configDir: string, copyDir: string, tuiJsonPath: string}>}
1722
+ */
1723
+ export async function resolveTuiInstallPaths(args) {
1724
+ const { isGlobalConfigDir, resolveTuiCopyTarget } = await import('./install/opencode.mjs')
1725
+ const isGlobal = isGlobalConfigDir(args.target)
1726
+ const configDir = isGlobal ? args.target : join(args.target, '.opencode')
1727
+ return {
1728
+ isGlobal,
1729
+ configDir,
1730
+ copyDir: resolveTuiCopyTarget(configDir),
1731
+ tuiJsonPath: join(configDir, 'tui.json'),
1732
+ }
1733
+ }
1734
+
1735
+ /** Resolve the module a copied TUI package.json advertises for its host. */
1736
+ function tuiExportTarget(pluginDir) {
1737
+ const pkg = readJson(join(pluginDir, 'package.json'))
1738
+ const exported = pkg?.exports?.['./tui'] ?? pkg?.main
1739
+ if (typeof exported !== 'string') return null
1740
+ const targetPath = isAbsolute(exported) ? exported : join(pluginDir, exported)
1741
+ return existsSync(targetPath) ? targetPath : null
1742
+ }
1743
+
1744
+ function samePath(left, right) {
1745
+ if (typeof left !== 'string') return false
1746
+ return resolve(left) === resolve(right)
1747
+ }
1748
+
1749
+ /**
1750
+ * Check H5: the installed TUI plugin (fail-closed).
1751
+ *
1752
+ * The TUI is the one component whose failure is silent: a missing payload or a
1753
+ * stale `tui.json` entry leaves the host loading nothing, with no error
1754
+ * anywhere. Every defect here gets its own `code` so a report can be acted on.
1755
+ *
1756
+ * Detection reuses the installer's own classifiers — `isPantheonTuiRef` /
1757
+ * `staleTuiRefs` for ownership — instead of a second, weaker notion of "looks
1758
+ * like our plugin".
1759
+ *
1760
+ * @param {{target:string, env?:object}} args
1761
+ * @returns {Promise<'not-installed'|'missing-dir'|'missing-dist'|'unregistered'|'stale-ref'|'ok'>}
1762
+ */
1763
+ export async function checkTuiPlugin(args) {
1764
+ section('H5. TUI Plugin')
1765
+
1766
+ const state = readState(args.target)
1767
+ const { copyDir, tuiJsonPath } = await resolveTuiInstallPaths(args)
1768
+ const pluginsInstalled = state?.components?.plugins?.status === 'installed'
1769
+
1770
+ if (!pluginsInstalled && !existsSync(copyDir) && !existsSync(tuiJsonPath)) {
1771
+ info('TUI plugin is not installed for this target — check skipped')
1772
+ return 'not-installed'
1773
+ }
1774
+
1775
+ if (!existsSync(copyDir)) {
1776
+ error(
1777
+ `TUI plugin directory is missing: ${copyDir} — the plugins component is recorded as ` +
1778
+ 'installed but its payload is absent. Run `npx pantheon-opencode init` to restore it.',
1779
+ { code: 'tui_plugin_dir_missing', classification: 'missing' },
1780
+ )
1781
+ return 'missing-dir'
1782
+ }
1783
+
1784
+ const v1Bundle = join(copyDir, 'dist', 'tui.js')
1785
+ const v2Bundle = join(copyDir, 'dist', 'tui-v2.js')
1786
+ if (!existsSync(v1Bundle) && !existsSync(v2Bundle)) {
1787
+ error(
1788
+ `TUI bundle is missing under ${join(copyDir, 'dist')} — the copied plugin cannot be ` +
1789
+ 'loaded by either host. Run `npx pantheon-opencode init` to reinstall it.',
1790
+ { code: 'tui_plugin_dist_missing', classification: 'missing' },
1791
+ )
1792
+ return 'missing-dist'
1793
+ }
1794
+
1795
+ const tuiConfig = readJson(tuiJsonPath)
1796
+ const pluginRefs = Array.isArray(tuiConfig?.plugin) ? tuiConfig.plugin : []
1797
+ const registered = pluginRefs.some((ref) => samePath(ref, copyDir))
1798
+ // V2 discovers local plugins from the plugins directory instead of tui.json;
1799
+ // its payload is identified by the sibling index.ts server entrypoint plus a
1800
+ // package export that resolves to the compiled V2 bundle.
1801
+ const v2Target = tuiExportTarget(copyDir)
1802
+ const v2Discovered =
1803
+ existsSync(join(copyDir, 'index.ts')) &&
1804
+ typeof v2Target === 'string' &&
1805
+ v2Target.endsWith('tui-v2.js')
1806
+
1807
+ if (!registered && !v2Discovered) {
1808
+ error(
1809
+ `TUI plugin is copied to ${copyDir} but no host discovery finds it: ` +
1810
+ `${tuiJsonPath} does not reference it and the V2 discovery files are incomplete. ` +
1811
+ 'Run `npx pantheon-opencode init` to re-register it.',
1812
+ { code: 'tui_plugin_not_registered', classification: 'ambiguous' },
1813
+ )
1814
+ return 'unregistered'
1815
+ }
1816
+
1817
+ // Anything our classifier still owns that is NOT the current registration is
1818
+ // a leftover the host would also load — stale copies accumulate per init run.
1819
+ const stale = staleTuiRefs(pluginRefs, [copyDir]).filter((ref) => !samePath(ref, copyDir))
1820
+ if (stale.length > 0) {
1821
+ error(
1822
+ `tui.json still registers ${stale.length} stale Pantheon TUI reference(s): ` +
1823
+ `${stale.join(', ')} — run \`npx pantheon-opencode init\` to clean them.`,
1824
+ { code: 'tui_plugin_stale_ref', classification: 'ambiguous' },
1825
+ )
1826
+ return 'stale-ref'
1827
+ }
1828
+
1829
+ pass(`TUI plugin installed at ${copyDir} and discoverable by the host`)
1830
+ return 'ok'
1831
+ }
1832
+
1582
1833
  // ---------------------------------------------------------------------------
1583
1834
  // Check G: AGENTS.md freshness
1584
1835
  // ---------------------------------------------------------------------------
@@ -1832,7 +2083,7 @@ export function classifyNodeSqliteProbe(probe) {
1832
2083
  if (probe.available) {
1833
2084
  return {
1834
2085
  status: 'ok',
1835
- message: `node:sqlite available on ${probe.version} — pantheon_cost read-only backend supported`,
2086
+ message: `node:sqlite available on ${probe.version} — pantheon_cost read-only backend available`,
1836
2087
  }
1837
2088
  }
1838
2089
  return {
@@ -1841,17 +2092,376 @@ export function classifyNodeSqliteProbe(probe) {
1841
2092
  }
1842
2093
  }
1843
2094
 
1844
- function checkNodeRuntime() {
2095
+ // ---------------------------------------------------------------------------
2096
+ // Tool registration — a SEPARATE fact from backend capability (P0-3)
2097
+ // ---------------------------------------------------------------------------
2098
+
2099
+ /**
2100
+ * Where each plugin generation declares its tool surface, relative to the
2101
+ * package root a registered plugin points into.
2102
+ *
2103
+ * The backend probe answers "can this Node read opencode.db?". It does NOT
2104
+ * answer "is `pantheon_cost` registered on the host at all?" — a tool removed
2105
+ * from (or never added to) the surface still had a green doctor before P0-3.
2106
+ * These files are the surface the doctor already ships and can inspect without
2107
+ * importing or executing plugin code.
2108
+ *
2109
+ * The V2 generation has TWO surfaces: `src/pantheon/v2-tools.ts` from beta.3
2110
+ * and the 1.5.0+ entry `src/plugin-v2.ts`, which declares the tools itself.
2111
+ * Reading only the first reported a healthy 1.5 tree as "pantheon_cost is NOT
2112
+ * declared", so every declared surface of the generation is inspected and their
2113
+ * declarations are unioned.
2114
+ */
2115
+ const TOOL_SURFACE_FILES = Object.freeze({
2116
+ v1: Object.freeze([join('src', 'plugin.ts')]),
2117
+ v2: Object.freeze([join('src', 'plugin-v2.ts'), join('src', 'pantheon', 'v2-tools.ts')]),
2118
+ })
2119
+
2120
+ /** The published package name — the only package identity this installer owns. */
2121
+ const PANTHEON_PACKAGE_NAME = 'pantheon-opencode'
2122
+
2123
+ /** Remove comments so a name mentioned only in prose never counts as a tool. */
2124
+ function stripSourceComments(source) {
2125
+ return source.replace(/\/\*[\s\S]*?\*\//g, '').replace(/^\s*\/\/.*$/gm, '')
2126
+ }
2127
+
2128
+ /** Extract the first `key: { ... }` object-literal body, or null. */
2129
+ function extractObjectLiteralBody(source, key) {
2130
+ const match = new RegExp(`\\b${key}\\s*:\\s*\\{`).exec(source)
2131
+ if (!match) return null
2132
+ let depth = 0
2133
+ const start = match.index + match[0].length - 1
2134
+ for (let index = start; index < source.length; index++) {
2135
+ if (source[index] === '{') depth++
2136
+ else if (source[index] === '}') {
2137
+ depth--
2138
+ if (depth === 0) return source.slice(start + 1, index)
2139
+ }
2140
+ }
2141
+ return null
2142
+ }
2143
+
2144
+ /**
2145
+ * Tool names declared by a plugin-generation source file.
2146
+ *
2147
+ * V2 declares each tool as `name: 'x'` in `createV2ToolDefinitions`, or — from
2148
+ * the 1.5.0 entry — as quoted elements of a `toolNames` array. V1 keys the
2149
+ * `tool:` object by tool name. Returns null when the generation's shape cannot
2150
+ * be located (unverifiable), which the classifier treats as a failure rather
2151
+ * than a pass: "cannot prove registration" is not "registered".
2152
+ *
2153
+ * @param {string} source
2154
+ * @param {'v1'|'v2'} generation
2155
+ * @returns {string[]|null}
2156
+ */
2157
+ export function readDeclaredToolNames(source, generation) {
2158
+ const body = stripSourceComments(source)
2159
+ if (generation === 'v2') {
2160
+ const names = new Set(
2161
+ [...body.matchAll(/\bname:\s*['"]([A-Za-z0-9_-]+)['"]/g)].map((match) => match[1]),
2162
+ )
2163
+ for (const match of body.matchAll(/^\s*['"]([A-Za-z0-9_-]+)['"],?\s*$/gm)) names.add(match[1])
2164
+ return [...names]
2165
+ }
2166
+ const toolBlock = extractObjectLiteralBody(body, 'tool')
2167
+ if (toolBlock === null) return null
2168
+ return [...toolBlock.matchAll(/^\s*([a-z][a-z0-9_]*)\s*:/gm)].map((match) => match[1])
2169
+ }
2170
+
2171
+ /**
2172
+ * Return the Pantheon package specifier a ref names, or null when it is not
2173
+ * one. Covers `pantheon-opencode`, `pantheon-opencode@1.2.3` and an export
2174
+ * subpath (`pantheon-opencode/plugin-v2`): the host resolves all of them
2175
+ * through its own module graph, not from a path this process can inspect.
2176
+ *
2177
+ * @param {unknown} refPath
2178
+ * @returns {string|null}
2179
+ */
2180
+ export function pantheonPackageSpecifier(refPath) {
2181
+ if (typeof refPath !== 'string' || refPath.length === 0) return null
2182
+ if (isAbsolute(refPath) || refPath.startsWith('.') || refPath.includes('\\')) return null
2183
+ return refPath.split('/')[0].split('@')[0] === PANTHEON_PACKAGE_NAME ? refPath : null
2184
+ }
2185
+
2186
+ /**
2187
+ * Resolve the package root a registered plugin ref points into.
2188
+ *
2189
+ * Path-shaped refs resolve against the config that declares them, exactly as
2190
+ * the loader does. A bare package specifier cannot be located from here, so it
2191
+ * resolves to null: the package the host loads is NOT necessarily the package
2192
+ * running this doctor, and standing ROOT in for it validated a surface the host
2193
+ * may never load (a false green, not evidence).
2194
+ *
2195
+ * @param {{path:string, configPath:string}} ref
2196
+ * @returns {string|null}
2197
+ */
2198
+ export function resolveRegisteredPluginRoot(ref) {
2199
+ const refPath = typeof ref === 'string' ? ref : ref?.path
2200
+ if (typeof refPath !== 'string' || refPath.length === 0) return null
2201
+
2202
+ let absolute = null
2203
+ if (isAbsolute(refPath)) {
2204
+ absolute = refPath
2205
+ } else if (ref?.configPath && /[\\/]/.test(refPath)) {
2206
+ absolute = resolve(dirname(ref.configPath), refPath)
2207
+ }
2208
+ if (!absolute) return null
2209
+
2210
+ const normalized = absolute.replaceAll('\\', '/').replace(/\/+$/, '')
2211
+ const marker =
2212
+ /^(.*?)\/src\/plugin-v2(?:\/index\.ts|\.ts)?$/.exec(normalized) ??
2213
+ /^(.*?)\/src\/plugin(?:-v2)?\.ts$/.exec(normalized)
2214
+ const root = marker ? marker[1] : normalized
2215
+ return existsSync(join(root, 'package.json')) ? root : null
2216
+ }
2217
+
2218
+ /**
2219
+ * Whether a registered ref belongs to Pantheon — the subject of this check.
2220
+ *
2221
+ * The same ownership criterion P0-6 uses: the plugin identity the installer
2222
+ * writes (or a path inside an installed `pantheon-opencode` tree), or a
2223
+ * `package.json` naming this package. Everything else belongs to the user, so a
2224
+ * third-party plugin registered under `plugins` is ignored instead of being
2225
+ * read as a Pantheon surface with a missing `src/pantheon/v2-tools.ts` (which
2226
+ * failed a healthy installation as blocking).
2227
+ *
2228
+ * @param {{path:string, configPath:string}} ref
2229
+ * @returns {boolean}
2230
+ */
2231
+ export function isPantheonPluginRef(ref) {
2232
+ const refPath = typeof ref === 'string' ? ref : ref?.path
2233
+ if (typeof refPath !== 'string' || refPath.length === 0) return false
2234
+ if (managedPluginPath(refPath) !== null) return true
2235
+ if (pantheonPackageSpecifier(refPath) !== null) return true
2236
+ const root = resolveRegisteredPluginRoot(ref)
2237
+ if (!root) return false
2238
+ return readJson(join(root, 'package.json'))?.name === PANTHEON_PACKAGE_NAME
2239
+ }
2240
+
2241
+ /** Describe one registered surface for a finding message. */
2242
+ function describeSurface(surface) {
2243
+ if (surface.files.length === 0) {
2244
+ return `${surface.generation}: no tool surface under ${surface.root}`
2245
+ }
2246
+ return `${surface.generation}: ${surface.files.join(' + ')}`
2247
+ }
2248
+
2249
+ /**
2250
+ * Inspect every registered Pantheon plugin and report the tool names its
2251
+ * declared surface contains. Non-Pantheon refs are ignored rather than failed:
2252
+ * they are not this check's subject. An npm specifier is Pantheon's own subject
2253
+ * but cannot be inspected, so it is carried as an explicit unverifiable surface
2254
+ * instead of being skipped or passed against the running package.
2255
+ *
2256
+ * @param {{target:string, env?:object}} args
2257
+ * @returns {{generation:'v1'|'v2'|null, root:string|null, files:string[], declared:string[]|null, unverifiable?:string}[]}
2258
+ */
2259
+ export function resolveRegisteredToolSurfaces(args) {
2260
+ const refs = collectRegisteredPluginRefs(collectMcpConfigs(args))
2261
+ const surfaces = []
2262
+ const seen = new Set()
2263
+ for (const ref of refs) {
2264
+ if (!isPantheonPluginRef(ref)) continue
2265
+
2266
+ if (pantheonPackageSpecifier(ref.path) !== null) {
2267
+ const key = `spec:${ref.path}`
2268
+ if (seen.has(key)) continue
2269
+ seen.add(key)
2270
+ surfaces.push({
2271
+ generation: null,
2272
+ root: null,
2273
+ files: [],
2274
+ declared: null,
2275
+ unverifiable:
2276
+ `"${ref.path}" is an npm specifier, not a path — the host resolves it through its own ` +
2277
+ 'module graph, so the surface it loads cannot be inspected from here',
2278
+ })
2279
+ continue
2280
+ }
2281
+
2282
+ const root = resolveRegisteredPluginRoot(ref)
2283
+ if (!root) continue
2284
+ const generation = ref.path?.includes('plugin-v2') || ref.key === 'plugins' ? 'v2' : 'v1'
2285
+ const key = `${generation}:${root}`
2286
+ if (seen.has(key)) continue
2287
+ seen.add(key)
2288
+
2289
+ const files = TOOL_SURFACE_FILES[generation]
2290
+ .map((relative) => join(root, relative))
2291
+ .filter((file) => existsSync(file))
2292
+ const declared = new Set()
2293
+ let readable = 0
2294
+ for (const file of files) {
2295
+ let source = null
2296
+ try {
2297
+ source = readFileSync(file, 'utf8')
2298
+ } catch {
2299
+ continue
2300
+ }
2301
+ const names = readDeclaredToolNames(source, generation)
2302
+ if (names === null) continue
2303
+ readable++
2304
+ for (const name of names) declared.add(name)
2305
+ }
2306
+ surfaces.push({
2307
+ generation,
2308
+ root,
2309
+ files,
2310
+ // No readable surface stays null so the classifier fails closed. With
2311
+ // several generation files present the declarations are unioned, so a
2312
+ // tool any of them declares is never reported absent.
2313
+ declared: readable === 0 ? null : [...declared],
2314
+ })
2315
+ }
2316
+ return surfaces
2317
+ }
2318
+
2319
+ /**
2320
+ * Decide the registration verdict for one tool. Backend availability is NOT an
2321
+ * input: this answers only "is the tool in the registered surface?". A missing
2322
+ * registration is a blocking error, never a warning (P0-3). A registration that
2323
+ * cannot be inspected (npm specifier) is an explicit informative finding — it
2324
+ * is neither proof of registration nor a blocking defect.
2325
+ *
2326
+ * `lite` is the only profile where no registration is expected: it describes a
2327
+ * checkout, not a managed OpenCode install.
2328
+ *
2329
+ * @param {{profile:string, surfaces:{generation:string|null, files:string[], root:string|null, declared:string[]|null, unverifiable?:string}[], toolName:string}} input
2330
+ * @returns {{status:'skip'|'unregistered'|'missing'|'registered'|'unverifiable'|'partially-verified', level:'info'|'error'|'pass', message:string}}
2331
+ */
2332
+ export function classifyToolRegistration({ profile, surfaces, toolName }) {
2333
+ if (surfaces.length === 0) {
2334
+ if (profile === 'lite') {
2335
+ return {
2336
+ status: 'skip',
2337
+ level: 'info',
2338
+ message: `${toolName} registration check skipped — a lite checkout has no managed plugin registration`,
2339
+ }
2340
+ }
2341
+ return {
2342
+ status: 'unregistered',
2343
+ level: 'error',
2344
+ message: `${toolName} is not registered: no Pantheon plugin is declared in any reachable opencode.json, so an available backend does not expose the tool (run \`pantheon-opencode init\`)`,
2345
+ }
2346
+ }
2347
+
2348
+ const unverifiable = surfaces.filter((surface) => typeof surface.unverifiable === 'string')
2349
+ const inspectable = surfaces.filter((surface) => typeof surface.unverifiable !== 'string')
2350
+ const unverifiableDetail = unverifiable.map(({ unverifiable: reason }) => reason).join('; ')
2351
+
2352
+ const missing = inspectable.filter(
2353
+ (surface) => surface.declared === null || !surface.declared.includes(toolName),
2354
+ )
2355
+ if (missing.length > 0) {
2356
+ const detail = missing.map(describeSurface).join(', ')
2357
+ return {
2358
+ status: 'missing',
2359
+ level: 'error',
2360
+ message: `${toolName} is NOT declared in the registered tool surface (${detail}) — a working read-only backend does not register the tool`,
2361
+ }
2362
+ }
2363
+
2364
+ if (inspectable.length === 0) {
2365
+ return {
2366
+ status: 'unverifiable',
2367
+ level: 'info',
2368
+ message: `${toolName} registration cannot be verified: ${unverifiableDetail} — this is NOT a registration pass`,
2369
+ }
2370
+ }
2371
+
2372
+ const detail = inspectable.map(describeSurface).join(', ')
2373
+ if (unverifiable.length > 0) {
2374
+ return {
2375
+ status: 'partially-verified',
2376
+ level: 'info',
2377
+ message: `${toolName} is declared in the inspectable Pantheon tool surface (${detail}), but another registration cannot be verified: ${unverifiableDetail} — not a full registration pass`,
2378
+ }
2379
+ }
2380
+
2381
+ return {
2382
+ status: 'registered',
2383
+ level: 'pass',
2384
+ message: `${toolName} is registered in the Pantheon tool surface (${detail})`,
2385
+ }
2386
+ }
2387
+
2388
+ /** Classify the Node package-support policy independently of feature probes. */
2389
+ export function classifyNodePackageRuntime(version) {
2390
+ if (isSupportedNodeVersion(version)) {
2391
+ return {
2392
+ status: 'supported',
2393
+ code: 'node_version_supported',
2394
+ message: `Node.js v${String(version).replace(/^v/, '')} meets Pantheon's package requirement (>= ${MIN_SUPPORTED_NODE_VERSION})`,
2395
+ }
2396
+ }
2397
+ return {
2398
+ status: 'unsupported',
2399
+ code: 'node_version_unsupported',
2400
+ message: `Pantheon requires Node.js >= ${MIN_SUPPORTED_NODE_VERSION}; current runtime is v${String(version).replace(/^v/, '')}`,
2401
+ }
2402
+ }
2403
+
2404
+ function checkNodeRuntime(args = {}) {
1845
2405
  section('K. Node Runtime')
2406
+ const packageRuntime = classifyNodePackageRuntime(process.versions.node)
2407
+ if (packageRuntime.status === 'supported') {
2408
+ pass(packageRuntime.message, {
2409
+ code: packageRuntime.code,
2410
+ classification: 'runtime',
2411
+ })
2412
+ } else {
2413
+ error(packageRuntime.message, { code: packageRuntime.code, classification: 'runtime' })
2414
+ }
2415
+
2416
+ // This capability check is independent of the package support floor: it
2417
+ // describes pantheon_cost's optional backend, not Pantheon's Node support.
1846
2418
  const outcome = classifyNodeSqliteProbe(probeNodeSqlite())
1847
2419
  if (outcome.status === 'ok') {
1848
- pass(outcome.message)
2420
+ pass(outcome.message, {
2421
+ code: 'node_sqlite_supported',
2422
+ classification: 'capability',
2423
+ })
1849
2424
  } else {
1850
- warn(outcome.message)
2425
+ warn(outcome.message, {
2426
+ code: 'node_sqlite_unsupported',
2427
+ classification: 'capability',
2428
+ })
1851
2429
  info(
1852
2430
  `Upgrade to Node >= ${NODE_SQLITE_MIN} (or a runtime with node:sqlite) to enable pantheon_cost`,
1853
2431
  )
1854
2432
  }
2433
+
2434
+ // Backend capability is NOT tool health (P0-3). A working node:sqlite with a
2435
+ // tool absent from the registered surface used to produce a green doctor;
2436
+ // this second, independent finding refuses to pass without registration.
2437
+ const registration = classifyToolRegistration({
2438
+ profile: args.profile,
2439
+ surfaces: resolveRegisteredToolSurfaces(args),
2440
+ toolName: 'pantheon_cost',
2441
+ })
2442
+ if (registration.level === 'pass') {
2443
+ pass(registration.message, {
2444
+ code: 'tool_registration_present',
2445
+ classification: 'capability',
2446
+ })
2447
+ } else if (registration.level === 'error') {
2448
+ error(registration.message, {
2449
+ code: 'tool_registration_missing',
2450
+ classification: 'capability',
2451
+ })
2452
+ } else if (
2453
+ registration.status === 'unverifiable' ||
2454
+ registration.status === 'partially-verified'
2455
+ ) {
2456
+ // Never a registration PASS: an npm specifier names a package the host may
2457
+ // resolve elsewhere, so reporting it as registered would be a false green.
2458
+ info(registration.message, {
2459
+ code: 'tool_registration_unverifiable',
2460
+ classification: 'capability',
2461
+ })
2462
+ } else {
2463
+ info(registration.message)
2464
+ }
1855
2465
  }
1856
2466
 
1857
2467
  /**
@@ -1879,6 +2489,7 @@ export function summaryMessage(summaryCounts, summaryExitCode) {
1879
2489
  }
1880
2490
 
1881
2491
  function printSummary(targetPath) {
2492
+ flushSectionPasses()
1882
2493
  console.log(`\n${'='.repeat(60)}`)
1883
2494
  console.log(' Summary')
1884
2495
  console.log(`${'='.repeat(60)}`)
@@ -1898,22 +2509,156 @@ function printSummary(targetPath) {
1898
2509
  // Main
1899
2510
  // ---------------------------------------------------------------------------
1900
2511
 
2512
+ async function checkInstallerFileInventory(args) {
2513
+ const state = readState(args.target)
2514
+ if (!state) return
2515
+ const selectedComponents = [
2516
+ 'agents',
2517
+ 'skills',
2518
+ 'instructions',
2519
+ 'prompts',
2520
+ 'commands',
2521
+ 'plugins',
2522
+ 'runtime',
2523
+ ]
2524
+ let desiredFiles = new Map()
2525
+ let desiredUnavailable = true
2526
+ let selectedLayouts = {}
2527
+ try {
2528
+ const { installOpenCode, isGlobalConfigDir } = await import('./install/opencode.mjs')
2529
+ const preview = await installOpenCode(args.target, true, false, selectedComponents, {
2530
+ version: 'auto',
2531
+ quiet: true,
2532
+ quietPlan: true,
2533
+ planOnly: true,
2534
+ headless: true,
2535
+ })
2536
+ desiredFiles = new Map(
2537
+ (preview?.files ?? [])
2538
+ .filter((file) => typeof file.outputFingerprint === 'string')
2539
+ .map((file) => [file.path, { sha256: file.outputFingerprint }]),
2540
+ )
2541
+ const layout = isGlobalConfigDir(args.target)
2542
+ ? 'global'
2543
+ : preview?.openCodeVersion === 'v2'
2544
+ ? 'project-v2'
2545
+ : 'project-v1'
2546
+ selectedLayouts = Object.fromEntries(selectedComponents.map((component) => [component, layout]))
2547
+ desiredUnavailable = false
2548
+ } catch {
2549
+ // Doctor remains advisory if a source/layout preview cannot be computed.
2550
+ // The fallback labels equal recorded hashes explicitly, never as current.
2551
+ }
2552
+ let report
2553
+ try {
2554
+ report = classifyFileInventory(args.target, state, {
2555
+ desiredFiles,
2556
+ desiredUnavailable,
2557
+ selectedComponents,
2558
+ selectedLayouts,
2559
+ })
2560
+ } catch {
2561
+ warn('Installer file inventory could not be safely inspected.', {
2562
+ code: 'installer_inventory_unreadable',
2563
+ classification: 'ambiguous',
2564
+ })
2565
+ return
2566
+ }
2567
+ if (report.legacyAmbiguous) {
2568
+ warn('Legacy installed files have no ownership inventory; cleanup requires manual review.', {
2569
+ code: 'installer_inventory_legacy_unknown',
2570
+ classification: 'ambiguous',
2571
+ })
2572
+ }
2573
+ const recordedCurrent = report.entries.filter(
2574
+ (entry) => entry.classification === 'recorded-current',
2575
+ ).length
2576
+ if (recordedCurrent > 0) {
2577
+ emit(
2578
+ 'info',
2579
+ `${recordedCurrent} inventoried file(s) match their recorded install hashes; current package payload was not compared.`,
2580
+ { code: 'installer_file_recorded_current', classification: 'recorded-current' },
2581
+ )
2582
+ }
2583
+ for (const entry of report.entries) {
2584
+ if (entry.classification === 'modified') {
2585
+ warn(`Installer-owned file was modified and will be preserved: ${entry.path}`, {
2586
+ code: 'installer_file_modified',
2587
+ classification: 'modified',
2588
+ })
2589
+ } else if (entry.classification === 'missing') {
2590
+ warn(`Previously installer-owned file is missing: ${entry.path}`, {
2591
+ code: 'installer_file_missing',
2592
+ classification: 'missing',
2593
+ })
2594
+ } else if (entry.classification === 'update-drift') {
2595
+ warn(`Installer source has a newer version of an unchanged owned file: ${entry.path}`, {
2596
+ code: 'installer_file_update_available',
2597
+ classification: 'update-drift',
2598
+ })
2599
+ } else if (entry.classification === 'stale-owned') {
2600
+ warn(`Stale installer-owned file is eligible for reviewed cleanup: ${entry.path}`, {
2601
+ code: 'installer_file_stale_owned',
2602
+ classification: 'stale-owned',
2603
+ })
2604
+ } else if (entry.classification === 'ambiguous') {
2605
+ warn(`Installer ownership is ambiguous for ${entry.path}; file preserved.`, {
2606
+ code: 'installer_file_ambiguous',
2607
+ classification: 'ambiguous',
2608
+ })
2609
+ }
2610
+ }
2611
+ }
2612
+
1901
2613
  async function main() {
1902
2614
  const args = parseArgs(process.argv)
2615
+ jsonMode = args.json
2616
+ jsonArgs = args
2617
+ if (jsonMode) {
2618
+ jsonOriginalWrite = process.stdout.write
2619
+ process.stdout.write = () => true
2620
+ }
1903
2621
 
1904
2622
  if (args.help) {
2623
+ if (jsonMode) {
2624
+ process.stdout.write = jsonOriginalWrite
2625
+ jsonOriginalWrite = null
2626
+ }
1905
2627
  showHelp()
1906
- process.exit(0)
2628
+ process.exitCode = 0
2629
+ return
2630
+ }
2631
+
2632
+ if (args.json && args.fix) {
2633
+ writeDoctorJson(
2634
+ {
2635
+ schema_version: 1,
2636
+ command: 'doctor',
2637
+ status: 'error',
2638
+ target: resolve(args.target),
2639
+ profile: args.profile,
2640
+ summary: { ...counts, exit_code: 1 },
2641
+ findings: [{ category: 'error', code: 'json_fix_unsupported', classification: 'usage' }],
2642
+ },
2643
+ 1,
2644
+ )
2645
+ return
1907
2646
  }
1908
2647
 
1909
2648
  // Report the resolved validation profile up front (auto → global/sandbox)
1910
2649
  // so callers — including the `doctor` CLI wrapper — can see which policy
1911
2650
  // gate applied before any check output.
1912
- console.log(`Validation profile: ${args.profile}`)
2651
+ if (!jsonMode) console.log(`Validation profile: ${args.profile}`)
1913
2652
 
1914
2653
  if (!existsSync(args.target)) {
1915
- console.error(`❌ Target directory does not exist: ${args.target}`)
1916
- process.exit(2)
2654
+ if (jsonMode) {
2655
+ error(`Target directory does not exist: ${args.target}`)
2656
+ writeDoctorJson(createDoctorJsonReport(args), exitCode)
2657
+ } else {
2658
+ console.error(`❌ Target directory does not exist: ${args.target}`)
2659
+ process.exitCode = 2
2660
+ }
2661
+ return
1917
2662
  }
1918
2663
 
1919
2664
  // Verify it looks like a Pantheon project or an OpenCode install target.
@@ -1944,7 +2689,15 @@ async function main() {
1944
2689
  checkCodeModeManifest(args)
1945
2690
  checkInstallVersionDrift(args)
1946
2691
  checkPluginVersionDrift(args)
1947
- await checkMcpRuntimeSmoke(args)
2692
+ await checkTuiPlugin(args)
2693
+ await checkInstallerFileInventory(args)
2694
+ if (jsonMode) {
2695
+ info('MCP runtime smoke skipped to keep --json read-only')
2696
+ results.at(-1).code = 'mcp_runtime_smoke_skipped'
2697
+ results.at(-1).classification = 'not_run'
2698
+ } else {
2699
+ await checkMcpRuntimeSmoke(args)
2700
+ }
1948
2701
  checkPermissionMismatches(args)
1949
2702
  checkSyncStatus(args)
1950
2703
  checkGitStatus(args)
@@ -1954,13 +2707,48 @@ async function main() {
1954
2707
  checkV2UnsupportedFeatures(args)
1955
2708
 
1956
2709
  printSummary(args.target)
2710
+ if (jsonMode) writeDoctorJson(createDoctorJsonReport(args), exitCode)
2711
+ else process.exitCode = exitCode
2712
+ }
1957
2713
 
1958
- process.exit(exitCode)
2714
+ function createDoctorJsonReport(args) {
2715
+ return {
2716
+ schema_version: 1,
2717
+ command: 'doctor',
2718
+ status: exitCode === 2 ? 'error' : counts.warn > 0 ? 'warning' : 'ok',
2719
+ target: resolve(args.target),
2720
+ profile: args.profile,
2721
+ summary: { ...counts, exit_code: exitCode },
2722
+ findings: results,
2723
+ }
2724
+ }
2725
+
2726
+ function writeDoctorJson(report, code) {
2727
+ const writer = jsonOriginalWrite ?? process.stdout.write
2728
+ process.stdout.write = writer
2729
+ jsonOriginalWrite = null
2730
+ writer.call(process.stdout, `${JSON.stringify(report)}\n`)
2731
+ process.exitCode = code
1959
2732
  }
1960
2733
 
1961
2734
  if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
1962
2735
  main().catch((err) => {
1963
- console.error(`❌ Doctor crashed: ${err.stack ?? err.message}`)
1964
- process.exit(2)
2736
+ if (jsonMode) {
2737
+ writeDoctorJson(
2738
+ {
2739
+ schema_version: 1,
2740
+ command: 'doctor',
2741
+ status: 'error',
2742
+ target: jsonArgs ? resolve(jsonArgs.target) : null,
2743
+ profile: jsonArgs?.profile ?? null,
2744
+ summary: { ...counts, exit_code: 2 },
2745
+ findings: [{ category: 'error', code: 'doctor_failure', classification: 'error' }],
2746
+ },
2747
+ 2,
2748
+ )
2749
+ } else {
2750
+ console.error(`❌ Doctor crashed: ${err.stack ?? err.message}`)
2751
+ process.exitCode = 2
2752
+ }
1965
2753
  })
1966
2754
  }