From 463df4d9786c2059d1f46c0cd7f0f48efd56f1ee Mon Sep 17 00:00:00 2001 From: repo-worker-code-k Date: Sun, 8 Nov 2026 01:09:11 -0600 Subject: [PATCH] fix(opencode): guard Go leaf seating credentials and attempts --- .github/ci-policy.md | 7 + .github/workflows/opencode-config-guard.yml | 8 + bin/check-opencode-go-seating.mjs | 408 ++++++++++++++++++ bin/check-opencode-go-seating.test.mjs | 292 +++++++++++++ doc/fleet-schedule-registry.md | 3 +- nixos/hosts/default.nix | 7 + .../opencode-go-seating-guard/default.nix | 121 ++++++ 7 files changed, 845 insertions(+), 1 deletion(-) create mode 100644 bin/check-opencode-go-seating.mjs create mode 100644 bin/check-opencode-go-seating.test.mjs create mode 100644 nixos/services/opencode-go-seating-guard/default.nix diff --git a/.github/ci-policy.md b/.github/ci-policy.md index 3e10797aad..2a4a8f3906 100644 --- a/.github/ci-policy.md +++ b/.github/ci-policy.md @@ -125,6 +125,13 @@ selections, top-level defaults, and agent model/fallback fields. Disabled providers are still checked: disabling a seat today must not make a later re-enable silently restore metered exposure. +It also runs the `opencode-go.*` seating-guard regression fixtures +(`bin/check-opencode-go-seating.test.mjs`) on pull requests using Node 24. +Those fixtures use a synthetic SQLite store and pin the exact-id credential +and post-config-change successful-attempt assertions; CI never attempts to +read the laptop's live OpenCode database. The live-store check is the hourly +`opencode-go-seating-guard.timer` on the laptop. + An explicitly approved one-off use must carry a standalone comment directly above that specific selection, with a non-empty reason: diff --git a/.github/workflows/opencode-config-guard.yml b/.github/workflows/opencode-config-guard.yml index 3ce765f3e5..c5936ede9e 100644 --- a/.github/workflows/opencode-config-guard.yml +++ b/.github/workflows/opencode-config-guard.yml @@ -19,7 +19,15 @@ jobs: timeout-minutes: 5 steps: - uses: actions/checkout@v7 + - uses: actions/setup-node@v7 + with: + node-version: 24 - name: Run guard fixtures run: node --test bin/check-opencode-metered-providers.test.mjs - name: Check canonical OpenCode config run: node bin/check-opencode-metered-providers.mjs .opencode/opencode.jsonc + # #5611: regression fixtures cover the exact-id credential requirement + # and the successful-attempt window. The live-store check runs on the + # laptop timer; CI must not pretend it can read the laptop's database. + - name: Run opencode-go seating fixtures + run: node --test bin/check-opencode-go-seating.test.mjs diff --git a/bin/check-opencode-go-seating.mjs b/bin/check-opencode-go-seating.mjs new file mode 100644 index 0000000000..96010f4a9d --- /dev/null +++ b/bin/check-opencode-go-seating.mjs @@ -0,0 +1,408 @@ +#!/usr/bin/env node +// check-opencode-go-seating — registration/seating guard for `opencode-go.*` +// instance leaves (developing-today/code#5611). +// +// The failure this pins (2026-11-03/04): provisioning the popesdrew Go +// instance stored its console-login OAuth credential under the bare +// integration id `opencode` instead of `opencode-go.popesdrew`. The route +// selector matches credentials by the EXACT leaf provider id +// (`WHERE integration_id = AND active = 1`), so every attempt on +// that leaf failed with "no credential for provider opencode-go.popesdrew": +// 23 failed attempts, the account served 0% for ~16h, and nothing noticed — +// provisioning ended at "rows created" and the weighted pool config +// (drewrypope 2 : popesdrew 1) was correct as deployed. +// +// The guard asserts, for every `opencode-go.*` leaf the config seats in a +// pool (a provider-route group's `providers` list or a model-route target): +// +// 1. credential A credential row exists under the EXACT leaf integration +// id (never the bare `opencode` console-login key) with +// active = 1. Missing → registration fails loudly. +// 2. attempt A SUCCESSFUL route attempt for that leaf is recorded +// after the active config's latest modification (a +// conservative seating-time proxy), within a bounded window. +// Absent → the leaf is not seated; raise an alert. +// +// Surface substitution (#5611 scope note): the standalone route proxy whose +// ledger the issue named was retired under opencode#1153; the successor +// surface is the `route_attempt` table in the OpenCode history store +// (`~/.local/share/opencode/opencode.db`), which the in-fork route selector +// writes for every attempt and the usage aggregator reads. The attempt +// assertion therefore reads `route_attempt` by `provider_id = ` +// and `outcome = 'success'`. Recorded on issue #5611. +// +// Read-only. Prints provider ids, credential ids/labels and attempt counts — +// never token values. +// +// Usage: +// check-opencode-go-seating.mjs [--config ] [--db ] +// [--leaf opencode-go.] [--window-hours 24] +// [--stage ] +// --stage pre-seat credential assertion only (run before seating a new +// leaf: no attempt can exist yet) +// --stage post-seat credential + a successful attempt within the window +// --stage periodic same as post-seat; what the timer/service runs +// (default) +// --leaf add an explicit registration target. Use with +// --stage pre-seat BEFORE adding the leaf to a pool; +// after seating, --stage post-seat requires a recent +// success as well. +// --skip-attempts shorthand for --stage pre-seat +// --json machine-readable report on stdout +// +// Exit: 0 healthy, 1 violation (not seated), 2 check error (config or store +// unreadable — loud, never a silent pass). + +import { existsSync, realpathSync, statSync } from 'node:fs'; +import { readFile } from 'node:fs/promises'; +import { homedir } from 'node:os'; +import { resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { DatabaseSync } from 'node:sqlite'; + +import { parseJsonc } from './provider-catalog-sync.mjs'; + +export const DEFAULT_CONFIG = '.opencode/opencode.jsonc'; +export const DEFAULT_STORE = '~/.local/share/opencode/opencode.db'; +export const DEFAULT_WINDOW_HOURS = 24; +export const LEAF_PREFIX = 'opencode-go.'; + +const isObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value); + +function expandHome(path) { + return path.startsWith('~') ? resolve(homedir(), `.${path.slice(1)}`) : path; +} + +/** Collect `provider/model` strings from a route definition's selections. + * Mirrors the shape the metered-provider guard walks: model targets may be + * plain strings or `{ model }` objects. */ +function collectSelections(node, out) { + if (typeof node === 'string') { + out.push(node); + return; + } + if (Array.isArray(node)) { + for (const item of node) collectSelections(item, out); + return; + } + if (isObject(node)) { + if (typeof node.model === 'string') out.push(node.model); + for (const key of ['targets', 'fallback', 'fallbacks']) { + if (key in node) collectSelections(node[key], out); + } + } +} + +/** Every `opencode-go.*` provider id the config seats in a pool. + * + * Seating is membership, not mention: a leaf is seated when it appears in a + * provider-route group's `providers` list or as the provider of a model-route + * target. A catalog/`provider` block alone does not seat it. + * + * `requestedLeaves` are explicit registration targets. They matter for + * pre-seat checks, when a new instance is intentionally not in any pool yet. + * Returns a Map leafId -> Set of seat descriptions. + */ +export function seatedGoLeaves(config, requestedLeaves = []) { + const seats = new Map(); + const seat = (leaf, where) => { + if (!seats.has(leaf)) seats.set(leaf, new Set()); + seats.get(leaf).add(where); + }; + + // The experimental map wins when present; otherwise the top-level map is + // the active runtime input (same fallback as the route proxy and the + // metered-provider guard). + const experimental = isObject(config?.experimental) ? config.experimental : {}; + const providerRoutes = isObject(experimental.provider_routes) + ? experimental.provider_routes + : isObject(config?.provider_routes) + ? config.provider_routes + : {}; + const modelRoutes = isObject(experimental.model_routes) + ? experimental.model_routes + : isObject(config?.model_routes) + ? config.model_routes + : {}; + + const walkGroups = (node, path) => { + if (Array.isArray(node)) { + node.forEach((item, index) => walkGroups(item, `${path}[${index}]`)); + return; + } + if (!isObject(node)) return; + // Group maps key by group NAME, so a group literally named "providers" is + // still a group: iterate entries as names, then walk each value as a + // group definition. + for (const [name, value] of Object.entries(node)) { + walkGroupDefinition(value, `${path}.${name}`); + } + }; + const walkGroupDefinition = (node, path) => { + if (Array.isArray(node)) { + node.forEach((item, index) => walkGroupDefinition(item, `${path}[${index}]`)); + return; + } + if (!isObject(node)) return; + for (const [key, value] of Object.entries(node)) { + if (key === 'providers') { + for (const provider of Array.isArray(value) ? value : [value]) { + if (typeof provider === 'string' && provider.startsWith(LEAF_PREFIX)) { + seat(provider, `${path}.providers`); + } + } + } else { + walkGroupDefinition(value, `${path}.${key}`); + } + } + }; + walkGroups(providerRoutes, '$' + (isObject(experimental.provider_routes) ? '.experimental' : '') + '.provider_routes'); + + for (const [name, definition] of Object.entries(modelRoutes)) { + const selections = []; + collectSelections(definition, selections); + selections.forEach((selection) => { + const provider = selection.split('/', 1)[0]; + if (provider.startsWith(LEAF_PREFIX)) { + seat(provider, `$.model_routes.${name}`); + } + }); + } + + for (const leaf of requestedLeaves) { + if (typeof leaf !== 'string' || !leaf.startsWith(LEAF_PREFIX) || leaf.length === LEAF_PREFIX.length) { + throw new Error(`invalid --leaf ${JSON.stringify(leaf)}; expected an opencode-go. leaf`); + } + seat(leaf, 'requested registration target (not yet seated)'); + } + + return seats; +} + +/** Rows shaped { integrationId, credentialId, label, active }. */ +export function credentialViolations(leaf, rows) { + const violations = []; + const exact = rows.filter((row) => row.integrationId === leaf); + const active = exact.filter((row) => row.active === true || row.active === 1); + if (exact.length === 0) { + const bare = rows + .filter((row) => row.integrationId === 'opencode') + .map((row) => `id=${row.credentialId} active=${row.active === true || row.active === 1}`); + violations.push( + `${leaf}: no credential row exists under the exact instance id` + + (bare.length + ? ` (a bare "opencode" console-login row exists: ${bare.join(', ')} — the selector matches the leaf id, not the console-login key)` + : ''), + ); + } else if (active.length === 0) { + violations.push( + `${leaf}: credential row exists under the exact id but none is active (rows: ` + + exact.map((row) => `id=${row.credentialId} active=${row.active}`).join(', ') + + ')', + ); + } + return violations; +} + +/** attempts shaped { outcome, timeStarted (ms), errorTag }. */ +export function attemptViolations(leaf, attempts, { now, windowHours, configUpdatedAt = 0 }) { + const cutoff = now - windowHours * 3600 * 1000; + const afterSeat = Math.max(cutoff, configUpdatedAt); + const recent = attempts.filter((attempt) => attempt.timeStarted >= afterSeat); + if (recent.some((attempt) => attempt.outcome === 'success')) return []; + const last = attempts.reduce( + (latest, attempt) => (latest === null || attempt.timeStarted > latest.timeStarted ? attempt : latest), + null, + ); + const detail = last + ? `most recent attempt ${new Date(last.timeStarted).toISOString()} outcome=${last.outcome}` + + (last.errorTag ? ` error_tag=${last.errorTag}` : '') + : 'no attempt recorded at all'; + return [ + `${leaf}: no successful route attempt within ${windowHours}h and after the active config's latest modification (${detail}) — the leaf is seated in a pool but has not served`, + ]; +} + +/** Full report over a config + store snapshot. + * + * `store` is { credentialRows, attemptsByProvider } and may be omitted with + * stage='pre-seat' (credential assertion only). + */ +export function inspectSeating({ config, store, stage = 'periodic', now = Date.now(), windowHours = DEFAULT_WINDOW_HOURS, leafIds = [], configUpdatedAt = 0 }) { + const seats = seatedGoLeaves(config, leafIds); + const checkAttempts = stage !== 'pre-seat'; + const violations = []; + const leaves = [...seats.keys()].sort(); + for (const leaf of leaves) { + const rows = store?.credentialRows ?? []; + violations.push(...credentialViolations(leaf, rows)); + if (checkAttempts && store) { + const attempts = store.attemptsByProvider.get?.(leaf) ?? store.attemptsByProvider[leaf] ?? []; + violations.push(...attemptViolations(leaf, attempts, { now, windowHours, configUpdatedAt })); + } + } + return { + leaves: leaves.map((leaf) => ({ leaf, seats: [...seats.get(leaf)].sort() })), + stage, + windowHours, + violations, + }; +} + +function readStore(dbPath, leaves) { + const db = new DatabaseSync(dbPath, { readOnly: true }); + try { + const credentialRows = db + .prepare('SELECT id, integration_id, label, active FROM credential') + .all() + .map((row) => ({ + credentialId: row.id, + integrationId: row.integration_id, + label: row.label, + active: row.active, + })); + const attemptsByProvider = new Map(); + const stmt = db.prepare( + 'SELECT provider_id, outcome, time_started, error_tag FROM route_attempt WHERE provider_id = ?', + ); + for (const leaf of leaves) { + const rows = stmt.all(leaf).map((row) => ({ + outcome: row.outcome, + timeStarted: Number(row.time_started) < 1e12 ? Number(row.time_started) * 1000 : Number(row.time_started), + errorTag: row.error_tag, + })); + attemptsByProvider.set(leaf, rows); + } + return { credentialRows, attemptsByProvider }; + } finally { + db.close(); + } +} + +export function parseArgs(argv) { + const options = { + config: DEFAULT_CONFIG, + db: DEFAULT_STORE, + windowHours: DEFAULT_WINDOW_HOURS, + stage: 'periodic', + json: false, + leafIds: [], + }; + // A bare positional is the config path, matching the metered-provider guard's + // `check-opencode-metered-providers.mjs ` invocation. + if (argv.length && !argv[0].startsWith('-')) { + options.config = argv[0]; + argv = argv.slice(1); + } + for (let i = 0; i < argv.length; i += 1) { + const arg = argv[i]; + const next = () => { + const value = argv[i + 1]; + if (value === undefined) throw new Error(`${arg} needs a value`); + i += 1; + return value; + }; + switch (arg) { + case '--config': + options.config = next(); + break; + case '--db': + options.db = next(); + break; + case '--leaf': + options.leafIds.push(next()); + break; + case '--window-hours': { + const value = Number(next()); + if (!Number.isFinite(value) || value <= 0) throw new Error('--window-hours must be a positive number'); + options.windowHours = value; + break; + } + case '--stage': { + const value = next(); + if (!['pre-seat', 'post-seat', 'periodic'].includes(value)) { + throw new Error('--stage must be pre-seat, post-seat or periodic'); + } + options.stage = value; + break; + } + case '--skip-attempts': + options.stage = 'pre-seat'; + break; + case '--json': + options.json = true; + break; + case '--help': + case '-h': + options.help = true; + break; + default: + throw new Error(`unknown argument: ${arg}`); + } + } + if (options.stage === 'pre-seat' && options.leafIds.length === 0) { + throw new Error('--stage pre-seat requires at least one --leaf registration target'); + } + return options; +} + +async function main(argv) { + const options = parseArgs(argv); + if (options.help) { + console.log( + 'usage: check-opencode-go-seating.mjs [--config ] [--db ] ' + + '[--leaf opencode-go.] [--window-hours 24] [--stage pre-seat|post-seat|periodic] [--json]', + ); + return 0; + } + const configPath = resolve(options.config); + const dbPath = expandHome(options.db); + const config = parseJsonc(await readFile(configPath, 'utf8')); + // A success must postdate the active config's latest write. This is a + // conservative proxy for pool seating time: any later config edit resets + // the proof window rather than allowing a pre-seating success to count. + const configUpdatedAt = statSync(configPath).mtimeMs; + const seats = seatedGoLeaves(config, options.leafIds); + const leaves = [...seats.keys()].sort(); + if (options.stage !== 'pre-seat' && !existsSync(dbPath)) { + console.error(`VIOLATION: credential store not found: ${dbPath}`); + return 2; + } + const store = leaves.length === 0 ? { credentialRows: [], attemptsByProvider: new Map() } : readStore(dbPath, leaves); + const report = inspectSeating({ config, store, stage: options.stage, windowHours: options.windowHours, leafIds: options.leafIds, configUpdatedAt }); + if (options.json) { + console.log(JSON.stringify({ config: configPath, db: dbPath, ...report }, null, 2)); + } else if (report.violations.length) { + console.error(`Go instance seating guard failed for ${configPath}:`); + for (const violation of report.violations) console.error(`- ${violation}`); + } else { + const attemptNote = options.stage === 'pre-seat' ? 'credential rows only (pre-seat)' : `credential rows + a successful attempt within ${options.windowHours}h`; + console.log( + `Go instance seating guard passed: ${configPath} (${leaves.length} seated leaf/leaves; ${attemptNote})`, + ); + } + return report.violations.length ? 1 : 0; +} + +// Entry-point check: compare realpaths, not the raw strings (#4694; same +// pattern as check-opencode-metered-providers.mjs / #2235). +const isMain = (() => { + try { + if (!process.argv[1]) return false; + return realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url)); + } catch { + return false; + } +})(); + +if (isMain) { + main(process.argv.slice(2)).then( + (code) => { + process.exitCode = code; + }, + (error) => { + console.error(`VIOLATION: Go instance seating check failed: ${error?.message ?? error}`); + process.exitCode = 2; + }, + ); +} diff --git a/bin/check-opencode-go-seating.test.mjs b/bin/check-opencode-go-seating.test.mjs new file mode 100644 index 0000000000..428fe9996b --- /dev/null +++ b/bin/check-opencode-go-seating.test.mjs @@ -0,0 +1,292 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdtempSync, rmSync, utimesSync, writeFileSync } from 'node:fs'; +import { createRequire } from 'node:module'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { spawnSync } from 'node:child_process'; +import { fileURLToPath } from 'node:url'; + +import { + attemptViolations, + credentialViolations, + inspectSeating, + parseArgs, + seatedGoLeaves, +} from './check-opencode-go-seating.mjs'; + +const require = createRequire(import.meta.url); + +// The popesdrew shape (#5611): the weighted pool config is CORRECT — both Go +// leaves are seated as peers — but the credential was provisioned under the +// bare console-login key `opencode`, so the exact-id selector finds nothing. +const seatedPoolConfig = `{ + "provider": { + "opencode-go.drewrypope": { "instanceOf": "opencode-go" }, + "opencode-go.popesdrew": { "instanceOf": "opencode-go" }, + }, + "experimental": { + "provider_routes": { + "opencode-go-plans": { + "providers": ["opencode-go.drewrypope", "opencode-go.popesdrew"], + "selection": "weighted", + "weights": { "opencode-go.drewrypope": 2, "opencode-go.popesdrew": 1 }, + }, + }, + }, +}`; + +const NOW = Date.parse('2026-11-04T09:00:00Z'); +const HOUR = 3600 * 1000; + +function store({ credentialRows, attempts }) { + const attemptsByProvider = new Map(); + for (const [provider, rows] of Object.entries(attempts ?? {})) { + attemptsByProvider.set(provider, rows); + } + return { credentialRows, attemptsByProvider }; +} + +const credential = (integrationId, active = true) => ({ + credentialId: `cred-${integrationId}`, + integrationId, + label: integrationId, + active, +}); + +test('the popesdrew failure shape fails: bare-key credential, correct pool config', () => { + // This is issue #5611 exactly: pool config correct as deployed, credential + // under `opencode`, nothing serves the leaf. + const report = inspectSeating({ + config: JSON.parse(JSON.stringify({ experimental: { provider_routes: { + 'opencode-go-plans': { providers: ['opencode-go.drewrypope', 'opencode-go.popesdrew'] }, + } } })), + store: store({ + credentialRows: [credential('opencode'), credential('opencode-go.drewrypope')], + attempts: { + 'opencode-go.drewrypope': [{ outcome: 'success', timeStarted: NOW - HOUR }], + }, + }), + stage: 'pre-seat', + now: NOW, + }); + assert.equal(report.violations.length, 1); + assert.match(report.violations[0], /opencode-go\.popesdrew: no credential row exists under the exact instance id/); + assert.match(report.violations[0], /bare "opencode" console-login row exists/); +}); + +test('exact-id active credential passes the credential assertion', () => { + const rows = [credential('opencode'), credential('opencode-go.popesdrew')]; + assert.deepEqual(credentialViolations('opencode-go.popesdrew', rows), []); +}); + +test('an exact-id credential that is inactive does not seat the leaf', () => { + const rows = [credential('opencode'), credential('opencode-go.popesdrew', false)]; + const violations = credentialViolations('opencode-go.popesdrew', rows); + assert.equal(violations.length, 1); + assert.match(violations[0], /none is active/); +}); + +test('a successful attempt inside the window passes; outside does not', () => { + const leaf = 'opencode-go.popesdrew'; + const fresh = [{ outcome: 'success', timeStarted: NOW - 2 * HOUR }]; + const stale = [{ outcome: 'success', timeStarted: NOW - 48 * HOUR }]; + const failing = [ + { outcome: 'failure', timeStarted: NOW - HOUR, errorTag: 'QuotaExceeded' }, + { outcome: 'failure', timeStarted: NOW - 2 * HOUR, errorTag: 'QuotaExceeded' }, + ]; + const opts = { now: NOW, windowHours: 24 }; + assert.deepEqual(attemptViolations(leaf, fresh, opts), []); + assert.match(attemptViolations(leaf, stale, opts)[0], /no successful route attempt within 24h/); + assert.match( + attemptViolations(leaf, fresh, { ...opts, configUpdatedAt: NOW - HOUR })[0], + /after the active config's latest modification/, + ); + assert.match(attemptViolations(leaf, failing, opts)[0], /error_tag=QuotaExceeded/); + assert.match(attemptViolations(leaf, [], opts)[0], /no attempt recorded at all/); +}); + +test('the second assertion is not optional: seated leaf with a credential but no attempt fails', () => { + const report = inspectSeating({ + config: { experimental: { provider_routes: { + 'opencode-go-plans': { providers: ['opencode-go.popesdrew'] }, + } } }, + store: store({ + credentialRows: [credential('opencode-go.popesdrew')], + attempts: {}, + }), + stage: 'periodic', + now: NOW, + }); + assert.equal(report.violations.length, 1); + assert.match(report.violations[0], /no attempt recorded at all/); +}); + +test('pre-seat stage skips the attempt assertion (a new leaf has no attempts yet)', () => { + const report = inspectSeating({ + config: { experimental: { provider_routes: { + 'opencode-go-plans': { providers: ['opencode-go.popesdrew'] }, + } } }, + store: store({ credentialRows: [credential('opencode-go.popesdrew')], attempts: {} }), + stage: 'pre-seat', + now: NOW, + }); + assert.deepEqual(report.violations, []); +}); + +test('both assertions pass for a healthy seated pair', () => { + const report = inspectSeating({ + config: JSON.parse(JSON.stringify({ experimental: { provider_routes: { + 'opencode-go-plans': { providers: ['opencode-go.drewrypope', 'opencode-go.popesdrew'] }, + } } })), + store: store({ + credentialRows: [credential('opencode'), credential('opencode-go.drewrypope'), credential('opencode-go.popesdrew')], + attempts: { + 'opencode-go.drewrypope': [{ outcome: 'success', timeStarted: NOW - HOUR }], + 'opencode-go.popesdrew': [{ outcome: 'success', timeStarted: NOW - HOUR }], + }, + }), + stage: 'periodic', + now: NOW, + }); + assert.deepEqual(report.violations, []); + assert.deepEqual(report.leaves.map((entry) => entry.leaf), ['opencode-go.drewrypope', 'opencode-go.popesdrew']); +}); + +test('seating is membership, not mention: a provider block or catalog entry alone is not a seat', () => { + const config = { + provider: { + 'opencode-go.popesdrew': { instanceOf: 'opencode-go' }, + }, + model_routes: { some: { targets: ['opencode-go.popesdrew/deepseek-v4.1-flash'] } }, + }; + const seats = seatedGoLeaves(config); + assert.deepEqual([...seats.keys()], ['opencode-go.popesdrew']); + assert.deepEqual([...seats.get('opencode-go.popesdrew')], ['$.model_routes.some']); + + const unseated = seatedGoLeaves({ provider: { 'opencode-go.popesdrew': {} } }); + assert.equal(unseated.size, 0); +}); + +test('provider-route group names that look like definition fields are still groups', () => { + const seats = seatedGoLeaves({ + experimental: { provider_routes: { providers: { providers: ['opencode-go.popesdrew'] } } }, + }); + assert.deepEqual([...seats.keys()], ['opencode-go.popesdrew']); +}); + +test('parseArgs: bare positional is the config, --skip-attempts means pre-seat', () => { + const options = parseArgs(['.opencode/opencode.jsonc', '--leaf', 'opencode-go.popesdrew', '--skip-attempts', '--json']); + assert.equal(options.config, '.opencode/opencode.jsonc'); + assert.equal(options.stage, 'pre-seat'); + assert.equal(options.json, true); + assert.deepEqual(options.leafIds, ['opencode-go.popesdrew']); + assert.throws(() => parseArgs(['--stage', 'nonsense']), /--stage/); + assert.throws(() => parseArgs(['--window-hours', '0']), /--window-hours/); + assert.throws(() => parseArgs(['--stage', 'pre-seat']), /requires at least one --leaf/); +}); + +// --- end-to-end: the real binary against a fixture sqlite store ------------ + +const guardPath = fileURLToPath(new URL('./check-opencode-go-seating.mjs', import.meta.url)); + +function makeStore({ credentialRows, attempts }) { + const dir = mkdtempSync(join(tmpdir(), 'go-seating-')); + const dbPath = join(dir, 'opencode.db'); + const { DatabaseSync } = require('node:sqlite'); + const db = new DatabaseSync(dbPath); + try { + db.exec( + 'CREATE TABLE credential (id TEXT PRIMARY KEY, integration_id TEXT, label TEXT NOT NULL, active INTEGER)', + ); + db.exec( + 'CREATE TABLE route_attempt (id INTEGER PRIMARY KEY AUTOINCREMENT, time_started INTEGER NOT NULL, ' + + 'provider_id TEXT NOT NULL, outcome TEXT NOT NULL, error_tag TEXT)', + ); + const insertCredential = db.prepare('INSERT INTO credential VALUES (?, ?, ?, ?)'); + for (const row of credentialRows) { + insertCredential.run(row.credentialId, row.integrationId, row.label, row.active ? 1 : 0); + } + const insertAttempt = db.prepare('INSERT INTO route_attempt (time_started, provider_id, outcome, error_tag) VALUES (?, ?, ?, ?)'); + for (const [provider, rows] of Object.entries(attempts ?? {})) { + for (const attempt of rows) { + insertAttempt.run(attempt.timeStarted, provider, attempt.outcome, attempt.errorTag ?? null); + } + } + } finally { + db.close(); + } + return { dir, dbPath }; +} + +function runGuard(args) { + return spawnSync(process.execPath, [guardPath, ...args], { encoding: 'utf8' }); +} + +function writeConfig(dir, source) { + const configPath = join(dir, 'opencode.jsonc'); + writeFileSync(configPath, source); + const beforeSeating = new Date(Date.now() - 2 * HOUR); + utimesSync(configPath, beforeSeating, beforeSeating); + return configPath; +} + +test('end-to-end: the popesdrew store fails the check with exit 1', () => { + const { dir, dbPath } = makeStore({ + credentialRows: [credential('opencode'), credential('opencode-go.drewrypope')], + attempts: { 'opencode-go.drewrypope': [{ outcome: 'success', timeStarted: Date.now() - HOUR }] }, + }); + const configPath = writeConfig(dir, seatedPoolConfig); + try { + const res = runGuard([configPath, '--db', dbPath]); + assert.equal(res.status, 1, res.stderr); + assert.match(res.stderr, /opencode-go\.popesdrew: no credential row exists under the exact instance id/); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); + +test('end-to-end: exact-id credentials plus fresh successes pass with exit 0', () => { + const { dir, dbPath } = makeStore({ + credentialRows: [credential('opencode-go.drewrypope'), credential('opencode-go.popesdrew')], + attempts: { + 'opencode-go.drewrypope': [{ outcome: 'success', timeStarted: Date.now() - HOUR }], + 'opencode-go.popesdrew': [{ outcome: 'success', timeStarted: Date.now() - HOUR }], + }, + }); + const configPath = writeConfig(dir, seatedPoolConfig); + try { + const res = runGuard([configPath, '--db', dbPath]); + assert.equal(res.status, 0, res.stderr); + assert.match(res.stdout, /Go instance seating guard passed/); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); + +test('end-to-end: a missing store is a loud check error (exit 2), not a silent pass', () => { + const dir = mkdtempSync(join(tmpdir(), 'go-seating-missing-')); + const configPath = writeConfig(dir, seatedPoolConfig); + try { + const res = runGuard([configPath, '--db', join(dir, 'nope.db')]); + assert.equal(res.status, 2); + assert.match(res.stderr, /credential store not found/); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); + +test('pre-seat registration can check a new leaf before it is added to any pool', () => { + const { dir, dbPath } = makeStore({ + credentialRows: [credential('opencode-go.popesdrew')], + attempts: {}, + }); + const configPath = writeConfig(dir, '{"provider": {"opencode-go.popesdrew": {"instanceOf": "opencode-go"}}}'); + try { + const res = runGuard([configPath, '--db', dbPath, '--leaf', 'opencode-go.popesdrew', '--stage', 'pre-seat']); + assert.equal(res.status, 0, res.stderr); + assert.match(res.stdout, /credential rows only \(pre-seat\)/); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); diff --git a/doc/fleet-schedule-registry.md b/doc/fleet-schedule-registry.md index 8cc270bede..760e9b3009 100644 --- a/doc/fleet-schedule-registry.md +++ b/doc/fleet-schedule-registry.md @@ -235,7 +235,7 @@ Execution route/pool is recorded separately from work scope: the repo-health que | `aea12c82-c5af-4e5a-9b66-f8e360f87177` | Queue lane (scheduled) - code | `*/40 * * * *` | True | `~/.config/openchamber/projects/path_L2hvbWUvdXNlci9naXQvY29kZQ.json` | not recorded | not recorded | not recorded | not recorded | 2026-11-03 | | `f1b4a33b-14d5-4a69-9ad6-d221e42e3ac9` | Opencode lane claimant/executor - #3026 | `*/10 * * * *` | True | `~/.config/openchamber/projects/path_L2hvbWUvdXNlci9naXQvY29kZQ.json` | opencode-route / workhorse | not recorded | not recorded | not recorded | 2026-11-03 | -### 2b. Laptop systemd user timers (39 timers: 38 enabled, 1 installed-but-disabled) +### 2b. Laptop systemd user timers (39 loaded: 38 enabled, 1 installed-but-disabled; 1 Nix-configured pending deployment) The OS-timer half of surface 2. Cadence is the unit's own `OnCalendar`/`OnUnitActiveUSec` spec, read live from `systemctl --user show`. Specs are recorded **complete** — the full effective calendar expression, date **and** time components (e.g. `*-*-* *:*:00`); never truncate a spec to a date-only prefix, because a bare `*-*-*` normalizes to daily at midnight and misstates the cadence (issue #5313). Prompt/brief pointer is the unit file in `~/.config/systemd/user/` (or its Nix store target for linked units). Installed-but-disabled timer units ARE listed in this table and marked `(disabled)` after the unit name: the registry inventories what is installed on the laptop, not only what is currently scheduled, so a disabled unit stays visible until it is uninstalled (reconciled 2026-11-04, issue #5661). @@ -264,6 +264,7 @@ The OS-timer half of surface 2. Cadence is the unit's own `OnCalendar`/`OnUnitAc | `laptop-untracked-review.timer` | `OnCalendar=*-*-* 07:37:00` | `laptop-untracked-review.service` | laptop (user systemd) | not recorded | not recorded | not recorded | 2026-11-04 | | `meta-quota-export.timer` | `OnCalendar=*-*-* *:00/15:00` | `meta-quota-export.service` | laptop (user systemd) | not recorded | not recorded | not recorded | 2026-11-05 | | `openai-cred-watchdog.timer` | `OnCalendar=*-*-* *:00:00` | `openai-cred-watchdog.service` | laptop (user systemd) | not recorded | not recorded | not recorded | 2026-11-04 | +| `opencode-go-seating-guard.timer` (Nix-configured; not yet loaded) | `OnCalendar=hourly (not live-verified)` | `opencode-go-seating-guard.service` | laptop (user systemd; code#5611) | not recorded | not recorded | 2026-11-08 | 2026-11-08 | | `openclaw-backup.timer` | `OnCalendar=*-*-* 04:05:00` | `openclaw-backup.service` | laptop (user systemd) | not recorded | not recorded | not recorded | 2026-11-04 | | `opencode-quota-freshness-summary.timer` (disabled) | `OnCalendar=*-*-* *:00:00` | `opencode-quota-freshness-summary.service` | laptop (user systemd) | not recorded | not recorded | not recorded | 2026-11-04 | | `opencode-usage-export.timer` | `OnCalendar=*-*-* *:00/15:00` | `opencode-usage-export.service` | laptop (user systemd) | not recorded | not recorded | not recorded | 2026-11-04 | diff --git a/nixos/hosts/default.nix b/nixos/hosts/default.nix index 1db20be62f..ed6598e2c5 100644 --- a/nixos/hosts/default.nix +++ b/nixos/hosts/default.nix @@ -28,6 +28,7 @@ in "services/pm-apps" "services/power-guard" "services/openai-cred-watchdog" + "services/opencode-go-seating-guard" # "microvm" # "server" "networking/dhcp-nat" @@ -84,6 +85,12 @@ in # active token-sharing credential for the GPT providers. services.openai-cred-watchdog.enable = true; } + { + # OpenCode Go seating guard (code#5611): hourly user timer + # asserting every Go leaf seated in a pool has an exact-id active + # credential and has recorded a successful route attempt recently. + services.opencode-go-seating-guard.enable = true; + } { # Laptop backups (code#1516, dezren39/nix#976): the dashboard # backup (local + R2 + Drive) and the repo-archive restic job, diff --git a/nixos/services/opencode-go-seating-guard/default.nix b/nixos/services/opencode-go-seating-guard/default.nix new file mode 100644 index 0000000000..1b8d94fe15 --- /dev/null +++ b/nixos/services/opencode-go-seating-guard/default.nix @@ -0,0 +1,121 @@ +# opencode-go-seating-guard — hourly seat check for the OpenCode Go +# leaves (developing-today/code#5611). +# +# The failure this guards (2026-11-03/04): provisioning the popesdrew Go +# instance stored its OAuth credential under the bare integration id +# `opencode` instead of `opencode-go.popesdrew`. The route selector matches +# credentials by the EXACT leaf provider id, so every attempt failed with +# "no credential for provider opencode-go.popesdrew": 23 failed attempts, +# the account served 0% for ~16h, and nothing noticed. Provisioning ended at +# "rows created" and the weighted pool config was correct as deployed — the +# gap was that nothing asserted the leaf could actually serve. +# +# The check itself lives in the repo's bin/ directory +# (bin/check-opencode-go-seating.mjs, read from the primary checkout at +# latest origin/main — the keep-primaries-clean model pm-stack uses) and +# asserts, for every `opencode-go.*` leaf the config seats in a pool: +# +# 1. credential A credential row under the EXACT leaf integration id with +# active = 1 (never the bare `opencode` console-login key). +# 2. attempt A successful `route_attempt` for the leaf after the +# active config's latest modification (a conservative +# seating-time proxy) and within the window. Surface +# substitution recorded on #5611: the +# standalone route proxy whose ledger the issue named was +# retired under opencode#1153; the successor surface is the +# `route_attempt` table in the OpenCode history store, which +# the in-fork route selector writes and the usage aggregator +# reads. +# +# Read-only: one sqlite read of the store plus one config parse. Prints +# provider ids, credential ids/labels and attempt counts — never token +# values. Exit 0 healthy, 1 a seated leaf is not serving, 2 check error +# (config or store unreadable). There is no separate alert surface beyond +# the failed unit + journal, the same surface openai-cred-watchdog relies on, +# so a violation fails this unit naming the offending leaf. +{ + config, + lib, + pkgs, + ... +}: +let + cfg = config.services.opencode-go-seating-guard; + home = "/home/${cfg.user}"; + repo = "${home}/git/code"; + guard = pkgs.writeShellApplication { + name = "opencode-go-seating-guard"; + runtimeInputs = [ pkgs.nodejs_24 ]; + text = '' + # The guard reads the tracked config and the live store; both paths are + # defaults of the script itself, overridable by the module for tests. + exec node ${repo}/bin/check-opencode-go-seating.mjs \ + "${cfg.configPath}" \ + --db "${cfg.storePath}" \ + --window-hours ${toString cfg.windowHours} \ + --stage ${cfg.stage} + ''; + }; +in +{ + options.services.opencode-go-seating-guard = { + enable = lib.mkEnableOption "the OpenCode Go seating guard (hourly assertion that every seated opencode-go.* leaf has an exact-id credential and has served, code#5611)"; + + user = lib.mkOption { + type = lib.types.str; + default = "user"; + description = "The user whose home holds the OpenCode credential store and the code checkout."; + }; + + configPath = lib.mkOption { + type = lib.types.str; + default = "${home}/.local/share/opencode/opencode.jsonc"; + description = "Active OpenCode JSONC config whose seated opencode-go.* leaves are checked."; + }; + + storePath = lib.mkOption { + type = lib.types.str; + default = "${home}/.local/share/opencode/opencode.db"; + description = "OpenCode history store holding the credential and route_attempt tables."; + }; + + windowHours = lib.mkOption { + type = lib.types.ints.positive; + default = 24; + description = "How far back a successful route_attempt counts as the leaf serving."; + }; + + stage = lib.mkOption { + type = lib.types.enum [ + "post-seat" + "periodic" + ]; + default = "periodic"; + description = "Assertion stage. 'pre-seat' is a registration-time mode (credential only) and is not a timer stage."; + }; + }; + + config = lib.mkIf cfg.enable { + home-manager.users.${cfg.user} = { + systemd.user.services.opencode-go-seating-guard = { + Unit.Description = "OpenCode Go seating guard — every seated opencode-go.* leaf has an exact-id active credential and has served (code#5611)"; + Service = { + Type = "oneshot"; + TimeoutStartSec = 120; + ExecStart = "${guard}/bin/opencode-go-seating-guard"; + }; + }; + + systemd.user.timers.opencode-go-seating-guard = { + Unit.Description = "Run the OpenCode Go seating guard hourly (code#5611)"; + Timer = { + OnCalendar = "hourly"; + RandomizedDelaySec = 20; + Persistent = true; + Unit = "opencode-go-seating-guard.service"; + }; + Install.WantedBy = [ "timers.target" ]; + }; + }; + }; +}