pantheon-opencode 1.6.0-beta.9 → 1.6.1

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