pantheon-opencode 2.0.0-beta.1 → 2.0.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,198 @@
1
+ /**
2
+ * doctor-state.ts — the Doctor section of the settings window (read-only).
3
+ *
4
+ * TUI-local replica (the bundle must stay self-contained — the installed copy
5
+ * physically lacks the repo tree, so doctor.mjs itself is unreachable). Only
6
+ * the FILE-DERIVABLE checks are mirrored here; everything that spawns
7
+ * processes, reads the network, or writes (MCP smoke, python validators, git,
8
+ * venv pins, --fix quarantines) stays in the CLI and the section says so.
9
+ *
10
+ * The install-state path mirrors doctor's checkInstallVersionDrift
11
+ * (`<config>/opencode/.pantheon/install-state.json`); the Node floor is
12
+ * drift-pinned against scripts/node-engine-policy.mjs by
13
+ * tests/tui-doctor-state.test.mjs.
14
+ */
15
+ import { existsSync, readFileSync } from 'node:fs'
16
+ import { join } from 'node:path'
17
+ import { readDecisionRouterConfig } from './decision-router-state.ts'
18
+ import type { OverridesLoad } from './pantheon-settings-state.ts'
19
+ import {
20
+ SETTINGS_BEHAVIORS,
21
+ type SettingsRow,
22
+ type SettingsSection,
23
+ } from './pantheon-settings-state.ts'
24
+ import { comparePantheonVersions } from './update-notice.ts'
25
+
26
+ /** Drift-pinned against scripts/node-engine-policy.mjs MIN_SUPPORTED_NODE_VERSION. */
27
+ export const MIN_SUPPORTED_NODE_VERSION = '26.4.0'
28
+
29
+ export function opencodePantheonDir(env: Record<string, string | undefined> = process.env) {
30
+ const xdg = env.XDG_CONFIG_HOME
31
+ const home = env.HOME ?? ''
32
+ const root = xdg ?? join(home, '.config')
33
+ return join(root, 'opencode', '.pantheon')
34
+ }
35
+
36
+ export interface InstallVersionHealth {
37
+ status: 'ok' | 'older' | 'newer' | 'unknown'
38
+ installed: string | null
39
+ }
40
+
41
+ /**
42
+ * H2: the installed package version (install-state) vs the running one.
43
+ * Fail-open: a missing/unreadable state file means "unknown", not a failure —
44
+ * pre-2.0 installs may not have one.
45
+ */
46
+ export function classifyInstallVersion(
47
+ runningVersion: string,
48
+ env: Record<string, string | undefined> = process.env,
49
+ ): InstallVersionHealth {
50
+ let installed: string | null = null
51
+ try {
52
+ const path = join(opencodePantheonDir(env), 'install-state.json')
53
+ const raw = JSON.parse(readFileSync(path, 'utf8')) as { pantheon_version?: unknown }
54
+ if (typeof raw?.pantheon_version === 'string' && raw.pantheon_version !== '') {
55
+ installed = raw.pantheon_version
56
+ }
57
+ } catch {
58
+ installed = null
59
+ }
60
+ if (installed === null) return { status: 'unknown', installed: null }
61
+ const compared = comparePantheonVersions(installed, runningVersion)
62
+ if (compared === 0) return { status: 'ok', installed }
63
+ return { status: compared < 0 ? 'older' : 'newer', installed }
64
+ }
65
+
66
+ export function isSupportedNodeFloor(version: string): boolean {
67
+ // Same shape as the canonical parser: a prerelease is outside the floor.
68
+ const match = /^v?(\d+)\.(\d+)\.(\d+)(?:-([^+]+))?(?:\+([\w.-]+))?$/.exec(String(version))
69
+ const minimum = /^v?(\d+)\.(\d+)\.(\d+)/.exec(MIN_SUPPORTED_NODE_VERSION)
70
+ if (!match || !minimum) return false
71
+ const [, major = '', minor = '', patch = '', prerelease = ''] = match
72
+ if (prerelease !== '') return false
73
+ const [, minMajor = '0', minMinor = '0', minPatch = '0'] = minimum
74
+ const currentParts = [+major, +minor, +patch]
75
+ const minimumParts = [+minMajor, +minMinor, +minPatch]
76
+ for (let index = 0; index < 3; index += 1) {
77
+ const currentPart = currentParts[index] ?? 0
78
+ const minimumPart = minimumParts[index] ?? 0
79
+ if (currentPart !== minimumPart) return currentPart > minimumPart
80
+ }
81
+ return true
82
+ }
83
+
84
+ export interface OverridesHealth {
85
+ status: 'clean' | 'unknown-ids' | 'corrupt'
86
+ unknownIds: string[]
87
+ }
88
+
89
+ /** K: validate both overrides files against the window's registry. */
90
+ export function classifyOverridesHealth(load: OverridesLoad): OverridesHealth {
91
+ if (load.corruptGlobal) return { status: 'corrupt', unknownIds: [] }
92
+ const known = new Set(SETTINGS_BEHAVIORS.map((behavior) => behavior.id))
93
+ const unknownIds = Object.keys({ ...load.global, ...load.project }).filter((id) => !known.has(id))
94
+ return { status: unknownIds.length > 0 ? 'unknown-ids' : 'clean', unknownIds }
95
+ }
96
+
97
+ export interface DecisionConfigHealth {
98
+ status: 'ok' | 'corrupt' | 'absent'
99
+ }
100
+
101
+ export function classifyDecisionConfigHealth(
102
+ env: Record<string, string | undefined> = process.env,
103
+ ): DecisionConfigHealth {
104
+ if (
105
+ !existsSync(
106
+ join(
107
+ env.XDG_CONFIG_HOME ?? join(env.HOME ?? '', '.config'),
108
+ 'pantheon',
109
+ 'decision-router.json',
110
+ ),
111
+ )
112
+ ) {
113
+ return { status: 'absent' }
114
+ }
115
+ return readDecisionRouterConfig(env).corrupt ? { status: 'corrupt' } : { status: 'ok' }
116
+ }
117
+
118
+ export interface DoctorSectionInput {
119
+ runningVersion: string
120
+ nodeVersion: string
121
+ load: OverridesLoad
122
+ env?: Record<string, string | undefined>
123
+ }
124
+
125
+ export function buildDoctorSection(input: DoctorSectionInput): SettingsSection {
126
+ const env = input.env ?? process.env
127
+ const rows: SettingsRow[] = []
128
+
129
+ const version = classifyInstallVersion(input.runningVersion, env)
130
+ rows.push({
131
+ id: 'doctor.version',
132
+ title:
133
+ version.status === 'ok'
134
+ ? `Installed version: v${version.installed} — matches`
135
+ : version.status === 'older'
136
+ ? `Installed v${version.installed} is older than the runtime v${input.runningVersion}`
137
+ : version.status === 'newer'
138
+ ? `Installed v${version.installed} is newer than the runtime v${input.runningVersion}`
139
+ : 'Installed version: unknown (no install-state)',
140
+ description:
141
+ version.status === 'older'
142
+ ? 'refresh with `pantheon-opencode update`'
143
+ : 'read from <config>/opencode/.pantheon/install-state.json',
144
+ marker: version.status === 'ok' ? '[✓]' : version.status === 'older' ? '[!]' : '[i]',
145
+ selectable: false,
146
+ })
147
+
148
+ const nodeOk = isSupportedNodeFloor(input.nodeVersion)
149
+ rows.push({
150
+ id: 'doctor.node',
151
+ title: `Node runtime: ${input.nodeVersion.replace(/^v/, '')}`,
152
+ description: nodeOk
153
+ ? `meets the >= ${MIN_SUPPORTED_NODE_VERSION} floor`
154
+ : `below the >= ${MIN_SUPPORTED_NODE_VERSION} floor — tooling may refuse`,
155
+ marker: nodeOk ? '[✓]' : '[!]',
156
+ selectable: false,
157
+ })
158
+
159
+ const overrides = classifyOverridesHealth(input.load)
160
+ rows.push({
161
+ id: 'doctor.overrides',
162
+ title:
163
+ overrides.status === 'clean'
164
+ ? 'Overrides: valid'
165
+ : overrides.status === 'corrupt'
166
+ ? 'Overrides: global file unreadable'
167
+ : `Overrides: ${overrides.unknownIds.length} unknown id(s)`,
168
+ description:
169
+ overrides.status === 'unknown-ids'
170
+ ? `${overrides.unknownIds.join(', ')} — harmless; repair with doctor --fix`
171
+ : overrides.status === 'corrupt'
172
+ ? 'writes are refused until repaired (doctor --fix)'
173
+ : 'both files parse against the behavior registry',
174
+ marker: overrides.status === 'clean' ? '[✓]' : overrides.status === 'corrupt' ? '[✗]' : '[!]',
175
+ selectable: false,
176
+ })
177
+
178
+ const decision = classifyDecisionConfigHealth(env)
179
+ rows.push({
180
+ id: 'doctor.decision',
181
+ title:
182
+ decision.status === 'ok'
183
+ ? 'Decision config: valid'
184
+ : decision.status === 'corrupt'
185
+ ? 'Decision config: unreadable — runtime fail-closes'
186
+ : 'Decision config: absent (local defaults)',
187
+ description: 'read from <config>/pantheon/decision-router.json',
188
+ marker: decision.status === 'corrupt' ? '[✗]' : '[✓]',
189
+ selectable: false,
190
+ })
191
+
192
+ return {
193
+ id: 'doctor',
194
+ title: 'Doctor',
195
+ rows,
196
+ hint: 'file checks only — the full doctor (MCP smoke, venv, git) is `pantheon-opencode doctor`',
197
+ }
198
+ }
@@ -3050,7 +3050,7 @@ async function checkForPantheonUpdate(context: any): Promise<void> {
3050
3050
  mkdirSync(join(stateDir, 'pantheon'), { recursive: true })
3051
3051
  writeFileSync(
3052
3052
  statePath,
3053
- JSON.stringify(nextCheckState(readState(), notice, Date.now()), null, 2) + '\n',
3053
+ `${JSON.stringify(nextCheckState(readState(), notice, Date.now()), null, 2)}\n`,
3054
3054
  )
3055
3055
  }
3056
3056
  const response = await fetch('https://registry.npmjs.org/pantheon-opencode/latest', {
@@ -0,0 +1,85 @@
1
+ /**
2
+ * j1-gate-status.ts — the J1 Risk Gate section of the settings window.
3
+ *
4
+ * TUI-local replica of the ladder in src/pantheon/jev-risk-gate.ts (the
5
+ * bundle must stay self-contained); tests/tui-settings-j1.test.mjs pins the
6
+ * env names, the ladder values and the default threshold against that source.
7
+ *
8
+ * STATUS ONLY by design: the ladder has no file surface yet — mode and
9
+ * threshold are env-only and read once at plugin setup — so nothing here
10
+ * writes, and the section says so. A file surface is a runtime-plugin change
11
+ * (beta.3 candidate), not a window change.
12
+ */
13
+ import type { SettingsRow, SettingsSection } from './pantheon-settings-state.ts'
14
+
15
+ export const J1_FLAG_ENV = 'PANTHEON_J1_RISK_SCORE'
16
+ export const J1_THRESHOLD_ENV = 'PANTHEON_J1_ENFORCE_THRESHOLD'
17
+ export const J1_THRESHOLD_DEFAULT = 0.8
18
+
19
+ export type J1Mode = 'off' | 'shadow' | 'warn' | 'enforce'
20
+
21
+ /** `1`/`on`/`true` map to `shadow` for back-compatibility with the shipped setup. */
22
+ const FLAG_ON = new Set(['1', 'on', 'true', 'shadow'])
23
+
24
+ export function j1ModeFromEnv(env: Record<string, string | undefined> = process.env): J1Mode {
25
+ const raw = (env[J1_FLAG_ENV] ?? '').trim().toLowerCase()
26
+ if (raw === 'enforce') return 'enforce'
27
+ if (raw === 'warn') return 'warn'
28
+ return FLAG_ON.has(raw) ? 'shadow' : 'off'
29
+ }
30
+
31
+ /** Invalid or out-of-range values fall back to the default — a typo must not disable the gate. */
32
+ export function j1ThresholdFromEnv(env: Record<string, string | undefined> = process.env): number {
33
+ const text = (env[J1_THRESHOLD_ENV] ?? '').trim()
34
+ if (text === '') return J1_THRESHOLD_DEFAULT
35
+ const raw = Number(text)
36
+ if (!Number.isFinite(raw) || raw < 0 || raw > 1) return J1_THRESHOLD_DEFAULT
37
+ return raw
38
+ }
39
+
40
+ const MODE_DESCRIPTION: Record<J1Mode, string> = {
41
+ off: 'nothing fires (hard zero)',
42
+ shadow: 'observe + record; invisible in the session',
43
+ warn: 'RESERVED — behaves as shadow in this release',
44
+ enforce: 'high-risk scores DENY the tool call (fail-open on gate unavailability)',
45
+ }
46
+
47
+ export function buildJ1Section(
48
+ env: Record<string, string | undefined>,
49
+ disabledByOverride: boolean,
50
+ ): SettingsSection {
51
+ const mode = j1ModeFromEnv(env)
52
+ const threshold = j1ThresholdFromEnv(env)
53
+ const gateState = disabledByOverride
54
+ ? 'disabled via overrides'
55
+ : mode === 'off'
56
+ ? 'off (env unset)'
57
+ : 'active'
58
+ const rows: SettingsRow[] = [
59
+ {
60
+ id: 'j1.mode',
61
+ title: `Mode: ${mode}`,
62
+ description: MODE_DESCRIPTION[mode],
63
+ ...(disabledByOverride ? { marker: '[!]' } : {}),
64
+ selectable: false,
65
+ },
66
+ {
67
+ id: 'j1.threshold',
68
+ title: `Enforce threshold: ${threshold}`,
69
+ description: 'deny at or above; 0..1, default 0.8',
70
+ selectable: false,
71
+ },
72
+ {
73
+ id: 'j1.gate',
74
+ title: `Gate: ${gateState}`,
75
+ description: 'the runtime plugin reads this once at startup',
76
+ selectable: false,
77
+ },
78
+ ]
79
+ return {
80
+ id: 'j1',
81
+ title: 'J1 Risk Gate',
82
+ hint: `set ${J1_FLAG_ENV} / ${J1_THRESHOLD_ENV} — restart applies`,
83
+ rows,
84
+ }
85
+ }
@@ -3,10 +3,15 @@
3
3
  *
4
4
  * TUI-local copy doctrine (same as cost-data.ts): the bundle must stay
5
5
  * self-contained. The behaviors registry mirrors routing.yml's `behaviors:`
6
- * (drift-pinned by tests/settings-registry.test.mjs); the Overrides tab reads
7
- * and writes the GLOBAL overrides file — the same one
6
+ * (drift-pinned by tests/pantheon-settings-state.test.mjs); the Gates section
7
+ * reads and writes the GLOBAL overrides file — the same one
8
8
  * `pantheon-opencode`'s installer and doctor consume
9
9
  * (`<config-dir>/pantheon-overrides.json`).
10
+ *
11
+ * Sections: the window renders one section per page. This module owns the
12
+ * section/row model and the Gates section; other sections live in sibling
13
+ * TUI-local modules (j1-gate-status.ts, update-status.ts, …) and follow the
14
+ * same shape.
10
15
  */
11
16
 
12
17
  export interface SettingsBehavior {
@@ -77,15 +82,106 @@ export function isBehaviorDisabled(effective: EffectiveOverrides, id: string): b
77
82
  return effective[id]?.action === 'disable'
78
83
  }
79
84
 
80
- /** Toggle: disabled -> enabled (entry removed); enabled -> disabled (entry written). */
85
+ // ── Section / row model ────────────────────────────────────────────────
86
+
87
+ export interface SettingsRow {
88
+ /** Namespaced action key (`gate.<behavior-id>`, `update.check`, …). */
89
+ id: string
90
+ title: string
91
+ description: string
92
+ /** Gates rows: the override disables the behavior (`[x]` marker). */
93
+ disabled?: boolean
94
+ /** Overrides the `[x]`/`[ ]` marker (`→` action, `✓`/`!` status). */
95
+ marker?: string
96
+ /** false → skipped by up/down and never dispatched by enter (info lines). */
97
+ selectable?: boolean
98
+ /** The effective entry comes from the PROJECT overrides file (read-only). */
99
+ source?: 'global' | 'project'
100
+ }
101
+
102
+ export interface SettingsSection {
103
+ id: string
104
+ title: string
105
+ /** One muted hint line under the rows. */
106
+ hint?: string
107
+ rows: SettingsRow[]
108
+ }
109
+
110
+ /** The rows up/down can reach and enter can dispatch on, in order. */
111
+ export function selectableRows(section: SettingsSection): SettingsRow[] {
112
+ return section.rows.filter((row) => row.selectable !== false)
113
+ }
114
+
115
+ /** Flat selection order across every section of the window. */
116
+ export function flatSelectableRows(sections: readonly SettingsSection[]): SettingsRow[] {
117
+ return sections.flatMap((section) => selectableRows(section))
118
+ }
119
+
120
+ export function firstSelectableId(sections: readonly SettingsSection[]): string | undefined {
121
+ return flatSelectableRows(sections)[0]?.id
122
+ }
123
+
124
+ // ── Overrides load (global + project files) ────────────────────────────
125
+
126
+ export interface OverridesLoad {
127
+ global: EffectiveOverrides
128
+ project: EffectiveOverrides
129
+ /** The GLOBAL file exists but does not parse — writes are refused. */
130
+ corruptGlobal: boolean
131
+ }
132
+
133
+ /**
134
+ * Merge for DISPLAY only, mirroring the runtime precedence: the project file
135
+ * wins per id (whole entry). The window still writes only the global file.
136
+ */
137
+ export function mergedOverrides(load: OverridesLoad): EffectiveOverrides {
138
+ return { ...load.global, ...load.project }
139
+ }
140
+
141
+ export function canWriteOverrides(load: OverridesLoad): boolean {
142
+ return !load.corruptGlobal
143
+ }
144
+
145
+ // ── Toggle semantics ───────────────────────────────────────────────────
146
+
147
+ export const TOGGLE_REASON = 'toggled in /pantheon-settings'
148
+
149
+ /**
150
+ * Toggle: disabled -> enabled; enabled -> disabled.
151
+ *
152
+ * A `replace` entry is never destroyed by a toggle ("never trap user state"):
153
+ * disabling keeps its `content` under the disable entry, and re-enabling
154
+ * restores the replace. A settings-written disable (no content) is removed
155
+ * outright so the overrides file does not accumulate toggle noise.
156
+ */
81
157
  export function toggledOverrides(
82
158
  effective: EffectiveOverrides,
83
159
  id: string,
84
- reason = 'toggled in /pantheon-settings',
160
+ reason: string = TOGGLE_REASON,
85
161
  ): EffectiveOverrides {
86
162
  const next: EffectiveOverrides = { ...effective }
87
- if (next[id]?.action === 'disable') delete next[id]
88
- else next[id] = { action: 'disable', reason }
163
+ const entry = next[id]
164
+ if (entry?.action === 'disable') {
165
+ if (entry.content !== undefined) {
166
+ // A settings-written disable restores a clean replace; a hand-authored
167
+ // disable+content keeps its own provenance reason.
168
+ next[id] =
169
+ entry.reason === reason
170
+ ? { action: 'replace', content: entry.content }
171
+ : {
172
+ action: 'replace',
173
+ content: entry.content,
174
+ ...(entry.reason !== undefined ? { reason: entry.reason } : {}),
175
+ }
176
+ } else {
177
+ delete next[id]
178
+ }
179
+ } else {
180
+ next[id] =
181
+ entry?.content !== undefined
182
+ ? { action: 'disable', reason, content: entry.content }
183
+ : { action: 'disable', reason }
184
+ }
89
185
  return next
90
186
  }
91
187
 
@@ -95,17 +191,55 @@ export function serializeOverrides(effective: EffectiveOverrides): string {
95
191
  return `${JSON.stringify(ordered, null, 2)}\n`
96
192
  }
97
193
 
98
- export interface AboutData {
99
- version: string
100
- skillCount: number
101
- agentCount: number
194
+ // ── Gates section ──────────────────────────────────────────────────────
195
+
196
+ /**
197
+ * The Gates & Overrides page: behavior state from BOTH overrides files.
198
+ * A project-owned entry wins the runtime merge and the window only writes
199
+ * the global file, so project rows are marked and not togglable here.
200
+ */
201
+ export function buildGatesSection(load: OverridesLoad): SettingsSection {
202
+ const merged = mergedOverrides(load)
203
+ const rows: SettingsRow[] = SETTINGS_BEHAVIORS.map((behavior) => {
204
+ const fromProject = load.project[behavior.id] !== undefined
205
+ return {
206
+ id: `gate.${behavior.id}`,
207
+ title: fromProject ? `${behavior.title} (project)` : behavior.title,
208
+ description: behavior.description,
209
+ disabled: isBehaviorDisabled(merged, behavior.id),
210
+ selectable: !fromProject,
211
+ source: fromProject ? 'project' : 'global',
212
+ }
213
+ })
214
+ return {
215
+ id: 'gates',
216
+ title: 'Gates & Overrides',
217
+ hint: canWriteOverrides(load)
218
+ ? 'enter: disable/enable · writes pantheon-overrides.json (global)'
219
+ : 'overrides file unreadable — writes refused; repair with `pantheon-opencode doctor --fix`',
220
+ rows,
221
+ }
102
222
  }
103
223
 
104
- export function aboutRows(data: AboutData): string[] {
105
- return [
106
- `Pantheon v${data.version}`,
107
- `${data.skillCount} skills · 14 agents · 5 MCP servers`,
108
- 'OpenCode 2.x only — the V1 contract is removed.',
109
- 'Docs: docs/design/2.0-settings-and-install.md',
110
- ]
224
+ // ── About section ──────────────────────────────────────────────────────
225
+
226
+ export function buildAboutSection(version: string): SettingsSection {
227
+ return {
228
+ id: 'about',
229
+ title: 'About',
230
+ rows: [
231
+ {
232
+ id: 'about.version',
233
+ title: `Pantheon v${version}`,
234
+ description: 'OpenCode 2.x only — the V1 contract is removed.',
235
+ selectable: false,
236
+ },
237
+ {
238
+ id: 'about.behaviors',
239
+ title: `${SETTINGS_BEHAVIORS.length} togglable behaviors`,
240
+ description: 'Docs: docs/design/2.0-settings-and-install.md',
241
+ selectable: false,
242
+ },
243
+ ],
244
+ }
111
245
  }