diff --git a/plugins/ruflo-console/hooks/actions.ts b/plugins/ruflo-console/hooks/actions.ts index 5fb683024c..df929054ce 100644 --- a/plugins/ruflo-console/hooks/actions.ts +++ b/plugins/ruflo-console/hooks/actions.ts @@ -23,6 +23,12 @@ export type ActionSpec = { note?: string /** How long the CLI may take; 90 s when unset. */ timeoutMs?: number + /** The x.ruv.io board's result panel instead of the MetaHarness lab's, for a spec with a `lab` id. */ + board?: 'xruv' + /** What the result panel shows of the output, when not the lab's reading of it. */ + lines?: (stdout: string, stderr: string) => string[] + /** Called with what the CLI printed when the run succeeded: a board read fills its section from it. */ + onOutput?: (stdout: string) => void } export const exec = (tool: string, params: Record) => ['mcp', 'exec', '-t', tool, '-p', JSON.stringify(params)] as const diff --git a/plugins/ruflo-console/hooks/controller.ts b/plugins/ruflo-console/hooks/controller.ts index 3a53a91496..e1c7282cf1 100644 --- a/plugins/ruflo-console/hooks/controller.ts +++ b/plugins/ruflo-console/hooks/controller.ts @@ -6,6 +6,7 @@ import { actionsOf } from './bindings' import type { Catalog } from './data/catalog' import { PROBES, type ProbeResult } from './data/cli' +import { X_PROBES } from './data/xruv' import { diffEvents, record } from './data/events' import { plain } from './data/parse' import { readSnapshot } from './data/snapshot' @@ -21,6 +22,8 @@ import { picturesOf } from './views/frames' const ACTIVITY_BUCKET_MS = 5_000 const PANE_WATCH_MS = 1_000 const MAX_PARALLEL_PROBES = 2 +/** The CLI probes and the x.ruv.io board's two network reads, one cadence and one option gate for all. */ +const ALL_PROBES = [...PROBES, ...X_PROBES] const BAR_FRESH_MS = 10_000 const IDLE_REFRESH_MS = 30_000 const TOOLS_RECOUNT_MS = 30_000 @@ -177,7 +180,7 @@ export function createController(state: State, host: Host): Controller { const probesInFlight = new Map>() /** One probe run at a time per probe: a second ask while it runs joins it. */ - function runProbe(probe: (typeof PROBES)[number]): Promise { + function runProbe(probe: (typeof ALL_PROBES)[number]): Promise { const held = probesInFlight.get(probe.id) if (held !== undefined) return held @@ -189,7 +192,7 @@ export function createController(state: State, host: Host): Controller { return run } - async function runProbeOnce(probe: (typeof PROBES)[number]): Promise { + async function runProbeOnce(probe: (typeof ALL_PROBES)[number]): Promise { const held: ProbeResult = state.probes.get(probe.id) ?? { value: null, okAtMs: null, error: null, errorAtMs: null, isRunning: false } state.probes.set(probe.id, { ...held, isRunning: true }) @@ -220,7 +223,7 @@ export function createController(state: State, host: Host): Controller { /** Runs the probes the view in front draws, each no more often than its cadence; `force` ignores the cadence. */ async function probe(force = false): Promise { const now = Date.now() - const due = PROBES.filter( + const due = ALL_PROBES.filter( entry => (isVisible() || force) && entry.views.includes(state.view) && diff --git a/plugins/ruflo-console/hooks/data/xruv.ts b/plugins/ruflo-console/hooks/data/xruv.ts new file mode 100644 index 0000000000..3224819fd8 --- /dev/null +++ b/plugins/ruflo-console/hooks/data/xruv.ts @@ -0,0 +1,109 @@ +/** + * The x.ruv.io board's two reads beyond the registry and the roster: the work-claims board and the recent swarm + * messages. Both reach wss://relay.ruv.io through the gateway, so they run only with `federationNetwork` on, or once on + * the board's ▸ fetch (the click is the consent). What they return is third parties' text, wrapped by the gateway in + * its provenance envelope: every string is capped and stripped of control characters, and drawn as data. + */ +import { jsonAfter, type Probe } from './cli' +import { msOf, numberOf, plain, recordOf, stringOf } from './parse' + +const exec = (tool: string, params: Record) => ['mcp', 'exec', '-t', tool, '-p', JSON.stringify(params)] as const + +/** A pubkey as the board shows it: its first twelve hex digits, never the whole of it. */ +export const shortKey = (value: unknown): string | undefined => { + const key = stringOf(value, 64) + + return key === undefined ? undefined : key.length > 12 ? `${key.slice(0, 12)}…` : key +} + +/** The gateway's envelope (`untrusted`, `relay`, `retrievedAt`, `data`) as its data, keeping the relay and the date. */ +export function envelopeOf(stdout: string): { data: unknown; relay?: string; atMs?: number } | null { + const value = recordOf(jsonAfter(stdout)) + + if (value === null) return null + + const relay = stringOf(value.relay, 60) + const atMs = msOf(value.retrievedAt) + + return { data: value.untrusted === true ? value.data : value, ...(relay !== undefined && { relay }), ...(atMs !== undefined && { atMs }) } +} + +export type WorkClaims = { claims: { resource: string; owner: string; from?: string; expiresAtMs?: number }[]; relay?: string; atMs?: number } + +/** The claims board: one owner per resource, TTLs and handoffs already applied by the gateway. */ +export const workClaimsProbe: Probe = { + id: 'x-claims', + args: exec('x_federation_claims', {}), + views: ['xruv'], + everyMs: 120_000, + timeoutMs: 45_000, + isNetwork: true, + parse: stdout => { + const found = envelopeOf(stdout) + const board = recordOf(found?.data) + + if (found === null || board === null) return null + + return { + claims: Object.entries(board) + .slice(0, 40) + .flatMap(([resource, entry]) => { + const claim = recordOf(entry) + const owner = shortKey(claim?.owner) + const from = stringOf(claim?.from, 32) + const expiresAtMs = msOf(claim?.expiresAt) + + return claim === null || owner === undefined ? [] : [{ resource: plain(resource, 60), owner, ...(from !== undefined && { from }), ...(expiresAtMs !== undefined && { expiresAtMs }) }] + }), + ...(found.relay !== undefined && { relay: found.relay }), + ...(found.atMs !== undefined && { atMs: found.atMs }), + } + }, +} + +export type SwarmMessage = { type: string; from: string; text?: string; atMs?: number } +export type SwarmMessages = { messages: SwarmMessage[]; relay?: string; atMs?: number } + +const SAYS = ['text', 'message', 'summary', 'status', 'title', 'task', 'result', 'note'] as const + +/** One relay message as a line's worth: its type, who signed it, and the first field that says something. */ +export function messageOf(entry: unknown): SwarmMessage | null { + const body = recordOf(entry) + const from = shortKey(body?.pubkey) ?? stringOf(body?.from, 24) + + if (body === null || from === undefined) return null + + const said = SAYS.map(key => stringOf(body[key], 140)).find(value => value !== undefined) + const seconds = numberOf(body.created_at) + const atMs = seconds !== undefined ? seconds * 1000 : msOf(body.ts) + + return { type: stringOf(body.type, 24) ?? 'message', from, ...(said !== undefined && { text: said }), ...(atMs !== undefined && { atMs }) } +} + +/** The last hour of signed swarm messages, twenty at most, newest first. */ +export const swarmProbe: Probe = { + id: 'x-sync', + args: exec('x_federation_sync', { limit: 20 }), + views: ['xruv'], + everyMs: 120_000, + timeoutMs: 45_000, + isNetwork: true, + parse: stdout => { + const found = envelopeOf(stdout) + const list = recordOf(found?.data)?.messages + + if (found === null || !Array.isArray(list)) return null + + return { + messages: list + .slice(0, 20) + .flatMap(entry => messageOf(entry) ?? []) + .sort((a, b) => (b.atMs ?? 0) - (a.atMs ?? 0)), + ...(found.relay !== undefined && { relay: found.relay }), + ...(found.atMs !== undefined && { atMs: found.atMs }), + } + }, +} + +/** The board's network probes, run by the controller beside PROBES and gated by the same option. */ +export const X_PROBES = [workClaimsProbe, swarmProbe] as const diff --git a/plugins/ruflo-console/hooks/dispatch.ts b/plugins/ruflo-console/hooks/dispatch.ts index 52f917f9b2..3e95c54d1b 100644 --- a/plugins/ruflo-console/hooks/dispatch.ts +++ b/plugins/ruflo-console/hooks/dispatch.ts @@ -10,6 +10,7 @@ import { median, p95 } from './controller' import { plain } from './data/parse' import { labAnswer } from './mh-lab' import { VIEWS, type State } from './state' +import { xruvAnswer } from './xruv' import { barText } from './views/bar' import { viewText } from './views/pane' @@ -114,7 +115,7 @@ export async function dispatch(control: Controller, state: State, args: string, // A lab read answers with what it printed, so `/ruflo run mh-genome` works headless. if (state.pending === null) await control.runner.settled() - return { text: state.pending !== null ? `Asked: ${state.pending.label}. Confirm with /ruflo yes (or y in the pane), cancel with /ruflo no.` : (labAnswer(state, intent.paletteId, askedAtMs) ?? (state.outcome !== null && !state.outcome.ok ? `${state.outcome.label}: ${state.outcome.detail}` : (state.outcome?.label ?? 'done'))) } + return { text: state.pending !== null ? `Asked: ${state.pending.label}. Confirm with /ruflo yes (or y in the pane), cancel with /ruflo no.` : (xruvAnswer(state, intent.paletteId, askedAtMs) ?? labAnswer(state, intent.paletteId, askedAtMs) ?? (state.outcome !== null && !state.outcome.ok ? `${state.outcome.label}: ${state.outcome.detail}` : (state.outcome?.label ?? 'done'))) } } case 'confirm': if (state.pending === null) return { text: 'Nothing is waiting for a confirm.' } @@ -129,7 +130,7 @@ export async function dispatch(control: Controller, state: State, args: string, await control.runner.confirm() - return { text: labAnswer(state, null, confirmedAtMs) ?? (state.outcome === null ? 'Ran.' : `${state.outcome.ok ? '✓' : '✗'} ${state.outcome.label}: ${state.outcome.detail}${state.outcome.verified === 'yes' ? ' (on disk)' : state.outcome.verified === 'no' ? ' (not on disk yet)' : ''}`) } + return { text: xruvAnswer(state, null, confirmedAtMs) ?? labAnswer(state, null, confirmedAtMs) ?? (state.outcome === null ? 'Ran.' : `${state.outcome.ok ? '✓' : '✗'} ${state.outcome.label}: ${state.outcome.detail}${state.outcome.verified === 'yes' ? ' (on disk)' : state.outcome.verified === 'no' ? ' (not on disk yet)' : ''}`) } case 'agent': { const who = intent.who.toLowerCase() const agent = state.snapshot?.agents.find(entry => entry.id.toLowerCase() === who || entry.name?.toLowerCase() === who) ?? state.snapshot?.agents.find(entry => entry.id.toLowerCase().endsWith(who)) diff --git a/plugins/ruflo-console/hooks/palette.ts b/plugins/ruflo-console/hooks/palette.ts index ecbadd0b4d..9c9ad971f6 100644 --- a/plugins/ruflo-console/hooks/palette.ts +++ b/plugins/ruflo-console/hooks/palette.ts @@ -10,6 +10,7 @@ import { claimTask, handoffClaim, releaseClaim, stealClaim, type ActionSpec } fr import { LAB, labSpec, labWhy } from './mh-lab' import { AGENT_TYPES, agentLogs, dispatchWorker, memorySearch, memoryStore, reroute, setClaimStatus, spawnAgent, stopAgent, swarmInit, swarmStop, vote, WORKERS } from './ops' import { VIEWS, type State, type ViewId } from './state' +import { XRUV } from './xruv' import { selection } from './views/select' export type PaletteRun = @@ -50,7 +51,7 @@ export function fuzzy(query: string, label: string): number | null { return whole < 0 ? score : score + 5 + (whole === 0 || text[whole - 1] === ' ' ? 3 : 0) } -const TEXT_KEYWORDS = ['route', 'store', 'search', 'propose', 'broadcast', 'task', 'mission'] as const +const TEXT_KEYWORDS = ['route', 'store', 'search', 'propose', 'broadcast', 'task', 'mission', 'x-join', 'x-read', 'x-publish', 'x-create', 'x-grant', 'x-hub', 'x-admit'] as const /** Every entry for the state as it is, before filtering. */ export function paletteEntries(state: State, nowMs: number): PaletteEntry[] { @@ -122,6 +123,13 @@ export function paletteEntries(state: State, nowMs: number): PaletteEntry[] { // The MetaHarness lab: reads run at once, the rest ask first; promotion is never an entry (see mh-lab.ts). for (const entry of LAB) add(entry.id, 'metaharness', entry.label, { kind: 'spec', spec: labSpec(entry, state), why: labWhy(entry) }) + // The x.ruv.io board: reads run at once (the ask is the consent), writes ask first, admin rows need the token. + for (const entry of XRUV) { + // An admin row without the token is a spec with its reason, so `/ruflo run x-admit …` says why instead of "type …". + if (entry.takes !== undefined && (entry.kind !== 'admin' || state.xruv.hasAdminToken === true)) add(entry.id, 'x.ruv.io', `${entry.id.slice(2)} <${entry.takes}>: ${entry.label}`, { kind: 'text', keyword: entry.id, make: text => entry.spec(state, text) }) + else add(entry.id, 'x.ruv.io', entry.label, { kind: 'spec', spec: entry.spec(state, ''), why: entry.why(state, '') }) + } + for (const worker of WORKERS) add(`worker-${worker}`, 'workers', `dispatch the ${worker} background worker`, { kind: 'spec', spec: dispatchWorker(worker), why: 'unknown worker' }) add('route', 'learning', 'route : ask the router for a pick', { kind: 'text', keyword: 'route', make: reroute }) diff --git a/plugins/ruflo-console/hooks/register.ts b/plugins/ruflo-console/hooks/register.ts index 2581b49b40..778dae07f6 100644 --- a/plugins/ruflo-console/hooks/register.ts +++ b/plugins/ruflo-console/hooks/register.ts @@ -88,6 +88,11 @@ export const register: Register = (on, raw: PluginOptions) => { state.home = (await bound.home().catch(() => undefined)) ?? null state.configDir = (await bound.configDir().catch(() => undefined)) ?? (state.home === null ? null : `${state.home}/.claude`) + // The x.ruv.io board's admin rows: only whether the token is set is kept, never its value. + state.xruv.hasAdminToken = await (async () => $.env.get('RUFLO_X_ADMIN_TOKEN'))().then( + value => typeof value === 'string' && value !== '', + () => null, + ) await Promise.all([ bound .registerCommand({ name: 'ruflo', description: 'ruflo: the cockpit (views, palette, agents, approvals) and every ruflo mod command — /ruflo help', argumentHint: '[view|palette|agent |mods|swarm |help]' }) diff --git a/plugins/ruflo-console/hooks/runner.ts b/plugins/ruflo-console/hooks/runner.ts index 6a61fe2313..7272c630fe 100644 --- a/plugins/ruflo-console/hooks/runner.ts +++ b/plugins/ruflo-console/hooks/runner.ts @@ -48,8 +48,11 @@ export function createRunner(state: State, host: Host, deps: RunnerDeps): Runner return } + // The x.ruv.io board keeps its own result panel, so its runs never show in the MetaHarness lab. + const panel = spec.board === 'xruv' ? state.xruv : state.lab + state.isActing = true - if (spec.lab !== undefined) state.lab.running = { id: spec.lab, label: spec.label, startedAtMs: Date.now() } + if (spec.lab !== undefined) panel.running = { id: spec.lab, label: spec.label, startedAtMs: Date.now() } host.invalidate() try { @@ -60,9 +63,11 @@ export function createRunner(state: State, host: Host, deps: RunnerDeps): Runner // A lab run's output goes to the lab's result panel, scrolled from its top; the footer keeps the one-line outcome. if (spec.lab !== undefined) { - state.lab.result = { id: spec.lab, label: spec.label, ok, exitCode: result.exitCode, ...(spec.note !== undefined && { note: spec.note }), lines: labLines(spec.lab, result.stdout, result.stderr), atMs: Date.now() } + panel.result = { id: spec.lab, label: spec.label, ok, exitCode: result.exitCode, ...(spec.note !== undefined && { note: spec.note }), lines: (spec.lines ?? ((out, err) => labLines(spec.lab ?? '', out, err)))(result.stdout, result.stderr), atMs: Date.now() } state.select.item = 0 } + // Keyed on the exit, not on `ok`: relay text in a read may carry an "error" key of its own. + if (result.exitCode === 0) spec.onOutput?.(result.stdout) if (spec.isReadOnly === true) { say(spec.label, ok, ok ? 'the ruflo CLI answered:' : plain(error ?? result.stderr, 160) || `exit ${result.exitCode}`, spec.lab === undefined ? outputLines(result.stdout) : undefined) @@ -84,11 +89,11 @@ export function createRunner(state: State, host: Host, deps: RunnerDeps): Runner } catch (error) { const why = plain(error instanceof Error ? error.message : String(error), 160) || 'refused' - if (spec.lab !== undefined) state.lab.result = { id: spec.lab, label: spec.label, ok: false, exitCode: null, ...(spec.note !== undefined && { note: spec.note }), lines: [why], atMs: Date.now() } + if (spec.lab !== undefined) panel.result = { id: spec.lab, label: spec.label, ok: false, exitCode: null, ...(spec.note !== undefined && { note: spec.note }), lines: [why], atMs: Date.now() } say(spec.label, false, why) } finally { state.isActing = false - state.lab.running = null + panel.running = null host.invalidate() } } diff --git a/plugins/ruflo-console/hooks/state.ts b/plugins/ruflo-console/hooks/state.ts index 4270e97672..27e50715af 100644 --- a/plugins/ruflo-console/hooks/state.ts +++ b/plugins/ruflo-console/hooks/state.ts @@ -38,7 +38,7 @@ export const VIEWS: readonly { id: ViewId; key: string; label: string; short: st { id: 'approvals', key: 'q', label: 'Approvals', short: 'Apv', icon: '✅', blurb: 'decisions waiting for a person: votes, stealable claims, refused mods, budget', rows: 24 }, { id: 'events', key: 'e', label: 'Events', short: 'Evt', icon: '📡', blurb: 'every swarm, claim, memory and mod event as it happens (f filters them)', rows: 26 }, { id: 'missions', key: 'm', label: 'Missions', short: 'Msn', icon: '🎯', blurb: 'ADR-406 missions: the plan, task dependencies, acceptance and budget (observe only)', rows: 26 }, - { id: 'xruv', key: 'w', label: 'x.ruv.io', short: 'XRV', icon: '🛸', blurb: 'the open agent federation: what it offers, how to join, its channels and who is on', rows: 34 }, + { id: 'xruv', key: 'w', label: 'x.ruv.io', short: 'XRV', icon: '🛸', blurb: 'the open agent federation: what it offers, how to join, its channels and who is on', rows: 50 }, { id: 'terminal', key: 'i', label: 'Terminal', short: 'Trm', icon: '💻', blurb: 'an AI terminal: codex, claude or both, each a session that remembers the conversation, streamed live', rows: 32 }, // No hotkey: every digit and letter is taken. The tab, the menu prompt and /ruflo skills reach it by name. { id: 'skills', key: '', label: 'Skills', short: 'Skl', icon: '🧰', blurb: 'agent skills (npx skills, skills.sh): what is installed here and globally, search, add, update, remove, create', rows: 34 }, @@ -193,6 +193,11 @@ export type State = { isActing: boolean /** The MetaHarness lab: its last result, and the run in flight (j/k scroll the result through `select.item`). */ lab: { result: LabResult | null; running: { id: string; label: string; startedAtMs: number } | null } + /** + * The x.ruv.io board: its own result panel (j/k scroll it too), this node's Nostr pubkey once a result named it + * (the key file is never read), and whether RUFLO_X_ADMIN_TOKEN is set (only that boolean is kept; null: not asked). + */ + xruv: { result: LabResult | null; running: { id: string; label: string; startedAtMs: number } | null; pubkey: string | null; hasAdminToken: boolean | null } isRefreshing: boolean /** When the band above the prompt last drew: the disk is re-read on the fast cadence only while it is seen. */ barDrawnAtMs: number @@ -257,6 +262,7 @@ export function newState(raw: PluginOptions | undefined): State { outcome: null, isActing: false, lab: { result: null, running: null }, + xruv: { result: null, running: null, pubkey: null, hasAdminToken: null }, isRefreshing: false, barDrawnAtMs: 0, terminal: { harness: 'codex', draft: '', lines: [], runs: new Map(), sessions: {}, isLive: { codex: false, claude: false }, turns: { codex: 0, claude: 0 }, costUsd: 0, scroll: 0, unseen: 0, asked: null }, diff --git a/plugins/ruflo-console/hooks/views/xruv.ts b/plugins/ruflo-console/hooks/views/xruv.ts index b02c9f7161..9e008dfb2f 100644 --- a/plugins/ruflo-console/hooks/views/xruv.ts +++ b/plugins/ruflo-console/hooks/views/xruv.ts @@ -1,103 +1,242 @@ import type { RenderElement } from 'claude-code' import type { Channels, Registry, Roster } from '../data/cli' -import { ago, clip, col, isBbs, kv, live, row, rule, sourceLine, text, THEME, type Ctx } from './common' +import type { SwarmMessages, WorkClaims } from '../data/xruv' +import { INVITE_COMMAND, UNREGISTER_WHY, XRUV, type XEntry, type XGroup } from '../xruv' +import { ago, button, clip, col, kv, live, row, rule, sourceLine, text, THEME, type Ctx } from './common' -/** What the open federation offers, as `ruflo federation ` names it; `admin` ones need the gateway's token. */ -const MENU: readonly { letter: string; name: string; about: string; command?: string; isAdmin?: boolean }[] = [ - { letter: 'J', name: 'JOIN', about: 'your own key, NIP-98 signed, no invite on open relays', command: 'federation join' }, - { letter: 'R', name: 'ROSTER', about: 'who is online now, one row per pubkey', command: 'federation roster' }, - { letter: 'S', name: 'SYNC', about: 'the last hour of signed swarm messages', command: 'federation sync --limit 20' }, - { letter: 'W', name: 'WORK CLAIMS', about: 'one owner per resource, TTLs and handoffs applied', command: 'federation claims' }, - { letter: 'C', name: 'CHANNELS', about: 'pub: plaintext rooms, prv: encrypted to members', command: 'federation channel --action list' }, - { letter: 'G', name: 'REGISTRY', about: 'relay, NIP-42 tag, gateway key, join steps', command: 'federation registry' }, - { letter: 'I', name: 'INVITES', about: 'use-limited codes for a new member', isAdmin: true }, - { letter: 'A', name: 'ADMIT', about: 'NIP-43 membership for a pubkey', isAdmin: true }, - { letter: 'P', name: 'PUBLISH', about: 'a hub broadcast as the gateway', isAdmin: true }, -] +/** Result lines in view at once; j/k scroll the rest. */ +export const XRUV_ROWS = 12 -/** - * The x.ruv.io board: a Wildcat-style main menu of what the open federation offers (each entry opens the terminal - * with its ruflo command typed, run only after Enter twice), then the registry's own word on how to join and which - * rooms to sit in, this node's channels, and who is on. The registry and the roster are on the network, so without - * `federationNetwork` they say how to turn it on and nothing is asked. - */ -export function xruvView(ctx: Ctx): RenderElement { +/** Each kind as a four-cell tag: reads, writes that ask first, and the gateway-identity rows that need the token. */ +const TAG = { read: { text: ' rd ', color: () => THEME.ok }, write: { text: ' wr ', color: () => THEME.info }, admin: { text: ' ad ', color: () => THEME.warn } } as const + +const entriesOf = (group: XGroup): XEntry[] => XRUV.filter(entry => entry.group === group) + +/** The button a row ends with: fetch for a read, ask for a write, nothing where it cannot run or needs typed text. */ +function rowButton(ctx: Ctx, entry: XEntry): RenderElement | null { + const isAdminOff = entry.kind === 'admin' && ctx.state.xruv.hasAdminToken !== true + + if (entry.id === 'x-unregister' || isAdminOff) return null + // The invite code is a bearer secret: it is minted in the terminal, where only the person reads it. + if (entry.id === 'x-invite') return ctx.kit.Button({ key: 'xr-x-invite', label: ' ▸ type', plain: true, dimColor: true, onPress: () => ctx.act.term.load('ruflo', INVITE_COMMAND) }) + if (entry.takes !== undefined && entry.id !== 'x-join') return null + + return ctx.kit.Button({ key: `xr-${entry.id}`, label: entry.kind === 'read' ? ' ▸ fetch' : ' ▸ ask', plain: true, dimColor: true, onPress: () => void ctx.act.run(entry.id) }) +} + +/** One menu row, dotted to its purpose: the tag, the name, what it does, and its button. */ +function entryRow(ctx: Ctx, entry: XEntry, lead: number): RenderElement { + const tag = TAG[entry.kind] + const isOff = entry.id === 'x-unregister' || (entry.kind === 'admin' && ctx.state.xruv.hasAdminToken !== true) + const action = rowButton(ctx, entry) + + return row( + ctx, + [ + ctx.kit.Text({ bold: true, color: tag.color(), children: ` ${tag.text}` }), + ctx.kit.Text({ bold: true, color: entry.kind === 'admin' ? THEME.warn : THEME.head, children: ` ${entry.name} `.padEnd(lead, '.') }), + ctx.kit.Text({ color: THEME.info, dimColor: isOff, wrap: 'truncate-end', children: clip(` ${entry.about}`, Math.max(4, ctx.columns - lead - 18)) }), + ...(action === null ? [] : [action]), + ], + `xr-row-${entry.id}`, + ) +} + +/** The field a text-taking row submits from; without Inputs (a surface with none), the palette words instead. */ +function field(ctx: Ctx, entry: XEntry, placeholder: string): RenderElement { + const Input = ctx.kit.Input + + if (Input === undefined) return text(ctx, ` from the palette (p): ${entry.id} <${entry.takes ?? ''}>`, { dimColor: true }) + + return Input({ key: `xr-in-${entry.id}`, label: ` ${entry.name.toLowerCase()}`, placeholder, submitLabel: entry.kind === 'read' ? 'fetch' : 'ask', onSubmit: value => void ctx.act.run(entry.id, value) }) +} + +/** This node: its Nostr key (only whether the file exists), the pubkey a result named, and the join and leave rows. */ +function identityRows(ctx: Ctx, lead: number): RenderElement[] { + const { state } = ctx + const hasKey = state.snapshot?.hasNostrKey ?? null + const reg = live(state.probes.get('registry'))?.registration + const rows: RenderElement[] = [rule(ctx, 'Identity', 'your own key · the file is never read')] + + rows.push(kv(ctx, 'nostr key', hasKey === null ? 'n/a' : hasKey ? 'present: ~/.ruflo/nostr.key (never read here)' : 'none yet: JOIN makes ~/.ruflo/nostr.key', hasKey === true ? THEME.ok : undefined)) + rows.push(kv(ctx, 'pubkey', state.xruv.pubkey !== null ? `${state.xruv.pubkey.slice(0, 16)}…${state.xruv.pubkey.slice(-6)}` : 'n/a — named by the next JOIN, ACCEPT or PUBLISH result')) + rows.push(kv(ctx, 'registration', reg === undefined ? 'n/a — open or closed is in the registry (▸ fetch below)' : `${reg.isOpen ? 'open' : 'closed'}${reg.auth !== undefined ? ` · ${reg.auth}` : ''} · JOIN checks membership first and registers only if needed`, reg?.isOpen === true ? THEME.ok : undefined)) + + for (const entry of entriesOf('identity')) { + rows.push(entryRow(ctx, entry, lead)) + if (entry.id === 'x-join') rows.push(field(ctx, entry, 'invite code v2.… (optional, private): Enter asks to join with it')) + } + + rows.push(text(ctx, ` ${UNREGISTER_WHY}`, { dimColor: true })) + + return rows +} + +/** A read's section: its row, then up to `max` lines of what it last fetched, or why there is nothing yet. */ +function liveRows(ctx: Ctx, entry: XEntry, lead: number, lines: string[] | null, probe: string, max: number): RenderElement[] { + const rows = [entryRow(ctx, entry, lead)] + + if (lines === null) { + const source = sourceLine(ctx.state.probes.get(probe), ctx.nowMs, entry.name.toLowerCase()) + + if (ctx.state.options.federationNetwork || ctx.state.probes.get(probe) !== undefined) rows.push(text(ctx, ` ${source.text}`, { dimColor: source.color === undefined, ...(source.color !== undefined && { color: source.color }) })) + + return rows + } + + for (const line of lines.slice(0, max)) rows.push(text(ctx, ` ${line}`)) + if (lines.length > max) rows.push(text(ctx, ` … ${lines.length - max} more: ▸ fetch shows them all below`, { dimColor: true })) + + return rows +} + +/** Registry, roster, the claims board and the swarm's messages: live with the option on, else one fetch per click. */ +function networkRows(ctx: Ctx, lead: number): RenderElement[] { const { state, nowMs } = ctx const isNet = state.options.federationNetwork + const rows: RenderElement[] = [rule(ctx, 'Live', isNet ? 'federationNetwork on · refreshed every few minutes' : 'network off · ▸ fetch asks the relay once')] + + if (!isNet) { + rows.push(text(ctx, ' The registry and the swarm are on x.ruv.io. Turn on federationNetwork in /config (ruflo-console) to keep them live,', { dimColor: true })) + rows.push(text(ctx, ' or press ▸ fetch: that one click asks once. Nothing on the network is asked unless you do one of these.', { dimColor: true })) + } + const registry = live(state.probes.get('registry')) - const channels = live(state.probes.get('channels')) const roster = live(state.probes.get('roster')) - const rows: RenderElement[] = [rule(ctx, 'Main menu', 'ruflo federation · x_federation_* tools')] + const claims = live(state.probes.get('x-claims')) + const sync = live(state.probes.get('x-sync')) + const [regEntry, rosterEntry, claimsEntry, syncEntry] = entriesOf('live') + + if (regEntry !== undefined) { + const lines = registry === null ? null : [`relay ${registry.relay ?? 'n/a'}${registry.swarmTag !== undefined ? ` · tag #${registry.swarmTag}` : ''} · gateway ${registry.gatewayPubkey?.slice(0, 16) ?? 'n/a'}…`, ...registry.join.map(step => clip(step, 160))] + + rows.push(...liveRows(ctx, regEntry, lead, lines, 'registry', 3)) + } + if (rosterEntry !== undefined) { + const lines = roster === null ? null : roster.members.length === 0 ? [`nobody announcing on ${roster.relay ?? 'the relay'} (${ago(roster.atMs, nowMs)})`] : [...roster.members.map(member => `◉ ${member.name}${member.detail !== undefined ? ` — ${member.detail}` : ''}`), `${roster.members.length} on · third-party text, not vetted · ${ago(roster.atMs, nowMs)}`] + + rows.push(...liveRows(ctx, rosterEntry, lead, lines, 'roster', 4)) + } + if (claimsEntry !== undefined) { + const lines = claims === null ? null : claims.claims.length === 0 ? ['no open claims on the board'] : claims.claims.map(claim => `${claim.resource} · ${claim.owner}${claim.from !== undefined ? ` (${claim.from})` : ''}`) + + rows.push(...liveRows(ctx, claimsEntry, lead, lines, 'x-claims', 3)) + } + if (syncEntry !== undefined) { + const lines = sync === null ? null : sync.messages.length === 0 ? ['no swarm messages in the last hour'] : sync.messages.map(message => `[${message.type}] ${message.from}${message.text !== undefined ? ` — ${message.text}` : ''} · ${ago(message.atMs, nowMs)}`) + + rows.push(...liveRows(ctx, syncEntry, lead, lines, 'x-sync', 4)) + } + + return rows +} + +/** The channels whose keys are here, each readable with one press; the registry's rooms when none are held yet. */ +function channelRows(ctx: Ctx, lead: number): RenderElement[] { + const { state, nowMs } = ctx + const held = live(state.probes.get('channels')) + const rooms = live(state.probes.get('registry'))?.channels ?? [] + const rows: RenderElement[] = [rule(ctx, 'Channels', 'list is local · read, publish, grant reach the relay')] + const readBtn = (id: string) => ctx.kit.Button({ key: `xr-read-${id}`, label: ' ▸ read', plain: true, dimColor: true, onPress: () => void ctx.act.run('x-read', id) }) + + if (held !== null && held.channels.length > 0) { + for (const channel of held.channels.slice(0, 6)) { + rows.push(row(ctx, [text(ctx, ` # ${clip(channel.name ?? channel.id, 18).padEnd(18)} ${channel.id.padEnd(22)} ${channel.id.startsWith('prv:') ? 'private' : 'public '} · ${ago(channel.atMs, nowMs)} `), readBtn(channel.id)], `xr-ch-${channel.id}`)) + } + } else { + rows.push(text(ctx, ` ${held === null ? sourceLine(state.probes.get('channels'), nowMs, 'channels').text : 'no channel keys held here yet'}`, { dimColor: true })) + } + + for (const room of rooms.slice(0, 4)) { + rows.push(row(ctx, [ctx.kit.Text({ bold: true, color: THEME.head, children: ` #${room.name.padEnd(14)} ` }), ctx.kit.Text({ color: THEME.info, wrap: 'truncate-end', children: clip(room.purpose ?? '', Math.max(4, ctx.columns - 28)) }), readBtn(`pub:${room.name}`)], `xr-room-${room.name}`)) + } + + const first = held?.channels[0]?.id ?? (rooms[0] !== undefined ? `pub:${rooms[0].name}` : 'pub:general') + const placeholders: Record = { + 'x-read': `${first} (or a name): Enter reads it`, + 'x-publish': `${first} Status: online — signed with your key, Enter asks`, + 'x-create': 'my-room public | my-room private — Enter asks', + 'x-grant': 'prv:<16 hex> <64-hex pubkey> — Enter asks', + } + + for (const entry of entriesOf('channels')) { + rows.push(entryRow(ctx, entry, lead)) + if (entry.takes !== undefined) rows.push(field(ctx, entry, placeholders[entry.id] ?? entry.takes)) + } + + return rows +} + +/** The gateway-identity rows: shown always, usable only with the token in the environment, each asking first. */ +function adminRows(ctx: Ctx, lead: number): RenderElement[] { + const has = ctx.state.xruv.hasAdminToken === true + const rows: RenderElement[] = [rule(ctx, 'Admin', has ? 'RUFLO_X_ADMIN_TOKEN is set · acts as the gateway · asks first' : 'admin token: set it in the environment to enable')] + + for (const entry of entriesOf('admin')) { + rows.push(entryRow(ctx, entry, lead)) + if (has && entry.takes !== undefined) rows.push(field(ctx, entry, entry.id === 'x-hub' ? 'Status: maintenance at 18:00 — signed as the gateway, Enter asks' : '<64-hex pubkey> [member|admin] — no revoke tool, Enter asks')) + } + + if (!has) rows.push(text(ctx, ' These sign as the x.ruv.io gateway: start Claude Code with RUFLO_X_ADMIN_TOKEN set to use them (it is never shown or passed as an argument).', { dimColor: true })) + + return rows +} + +/** The last board run: what it was, how it exited, what it sends, and a window of its lines. */ +function resultRows(ctx: Ctx): RenderElement[] { + const { state, nowMs } = ctx + const { result, running } = state.xruv + const right = running !== null ? `running ${Math.round((nowMs - running.startedAtMs) / 1000)}s` : result === null ? 'nothing run yet' : `${result.ok ? '✓' : '✗'} exit ${result.exitCode ?? 'n/a'} · ${ago(result.atMs, nowMs)}` + const rows: RenderElement[] = [rule(ctx, 'Result', right)] + + if (running !== null) rows.push(text(ctx, ` ▸ ${running.label} … ${Math.floor(nowMs / 500) % 2 === 0 ? '█' : ' '}`, { color: THEME.warn })) + + if (result === null) { + if (running === null) rows.push(text(ctx, ' ▸ fetch shows its answer here at once; a write shows here after you confirm (y)', { dimColor: true })) + + return rows + } + + rows.push(text(ctx, ` ${result.label}`, { bold: true, color: result.ok ? THEME.ok : THEME.bad })) + if (result.note !== undefined) rows.push(text(ctx, ` ${result.note}`, { color: THEME.warn })) + + const top = Math.max(0, Math.min(state.select.item, result.lines.length - XRUV_ROWS)) + + for (const line of result.lines.slice(top, top + XRUV_ROWS)) rows.push(text(ctx, ` ${line}`)) + + if (result.lines.length > XRUV_ROWS) { + rows.push( + row(ctx, [ + text(ctx, ` lines ${top + 1}-${Math.min(result.lines.length, top + XRUV_ROWS)} of ${result.lines.length} `, { dimColor: true }), + button(ctx, 'xr-up', 'up', () => ctx.act.select(-1), { hotkey: 'k' }), + button(ctx, 'xr-down', 'down', () => ctx.act.select(1), { hotkey: 'j' }), + ]), + ) + } + + return rows +} + +/** + * The x.ruv.io board: every federation capability as a row with its own button. Identity (whether the key file exists, + * never its content) and joining; the registry, the roster, the work claims and the swarm's messages, live with + * `federationNetwork` or fetched once per click; the channels held here, with read, publish, create, grant and accept; + * the gateway-identity rows, which need RUFLO_X_ADMIN_TOKEN; and the last run's output. Reads run at once, everything + * that registers, signs or writes asks first and its confirm row says what it sends. Unregistering is not offered: the + * gateway has no endpoint for it. + */ +export function xruvView(ctx: Ctx): RenderElement { const lead = Math.max(14, Math.min(18, ctx.columns - 40)) - - for (const item of MENU) { - const name = ` ${item.name} `.padEnd(lead, '.') - const parts: RenderElement[] = [ - ctx.kit.Text({ bold: true, color: THEME.ok, children: ` [${item.letter}]` }), - ctx.kit.Text({ bold: true, color: item.isAdmin === true ? THEME.warn : THEME.head, children: name }), - ctx.kit.Text({ color: THEME.info, wrap: 'truncate-end', children: clip(` ${item.about}${item.isAdmin === true ? ' (admin)' : ''}`, Math.max(4, ctx.columns - lead - 22)) }), - ] - - if (item.command !== undefined) { - const command = item.command - - parts.push(ctx.kit.Button({ key: `xr-${item.letter}`, label: ' ▸ open', plain: true, dimColor: true, onPress: () => ctx.act.term.load('ruflo', command) })) - } - - rows.push(row(ctx, parts, `xr-row-${item.letter}`)) - } - - rows.push(text(ctx, ' ▸ open puts the command in the terminal (i): Enter shows it, Enter again runs it', { dimColor: true })) - rows.push(rule(ctx, 'How to join', isNet ? 'from the registry · gateway text' : 'network off')) - - if (!isNet) { - rows.push(text(ctx, ' The registry is on x.ruv.io. Turn on federationNetwork in /config (ruflo-console) to ask it.', { dimColor: true })) - rows.push(text(ctx, ' Or run `npx ruflo federation join`: it makes ~/.ruflo/nostr.key and registers with it.', { dimColor: true })) - } else if (registry === null) { - rows.push(text(ctx, ` ${sourceLine(state.probes.get('registry'), nowMs, 'registry').text}`, { dimColor: true })) - } else { - rows.push(kv(ctx, 'relay', `${registry.relay ?? 'n/a'}${registry.swarmTag !== undefined ? ` · tag #${registry.swarmTag}` : ''}`)) - rows.push(kv(ctx, 'gateway key', registry.gatewayPubkey !== undefined ? `${registry.gatewayPubkey.slice(0, 16)}…` : 'n/a')) - if (registry.registration !== undefined) { - const reg = registry.registration - - rows.push(kv(ctx, 'registration', `${reg.isOpen ? 'open' : 'closed'}${reg.auth !== undefined ? ` · ${reg.auth}` : ''}${reg.limits !== undefined ? ` · ${reg.limits}` : ''}`, reg.isOpen ? THEME.ok : THEME.warn)) - } - for (const step of registry.join.slice(0, 4)) rows.push(text(ctx, ` ${clip(step, 160)}`, { color: THEME.info })) - } - - rows.push(rule(ctx, 'Rooms', isNet && registry !== null ? 'default channels' : 'joined here')) - - const defaults = registry?.channels ?? [] - - if (defaults.length > 0) { - for (const room of defaults.slice(0, 5)) { - rows.push( - row(ctx, [ - ctx.kit.Text({ bold: true, color: THEME.head, children: ` #${room.name.padEnd(14)} ` }), - ctx.kit.Text({ dimColor: !isBbs(), color: THEME.info, wrap: 'truncate-end', children: clip(room.purpose ?? '', Math.max(4, ctx.columns - 18)) }), - ]), - ) - } - } else if (channels !== null && channels.channels.length > 0) { - for (const channel of channels.channels.slice(0, 5)) rows.push(text(ctx, ` # ${channel.name ?? channel.id} · ${channel.id.startsWith('prv:') ? 'private' : 'public'} · since ${ago(channel.atMs, nowMs)}`)) - } else { - rows.push(text(ctx, ` ${channels === null ? sourceLine(state.probes.get('channels'), nowMs, 'channels').text : 'no channels joined here yet'}`, { dimColor: true })) - } - - rows.push(rule(ctx, 'Who is on', isNet ? 'roster · unvetted' : 'network off')) - - if (!isNet) { - rows.push(text(ctx, ' Off: the roster is on the public relay (federationNetwork).', { dimColor: true })) - } else if (roster === null) { - rows.push(text(ctx, ` ${sourceLine(state.probes.get('roster'), nowMs, 'roster').text}`, { dimColor: true })) - } else if (roster.members.length === 0) { - rows.push(text(ctx, ` nobody announcing on ${roster.relay ?? 'the relay'} (${ago(roster.atMs, nowMs)})`, { dimColor: true })) - } else { - for (const member of roster.members.slice(0, 5)) rows.push(text(ctx, ` ◉ ${member.name}${member.detail !== undefined ? ` — ${member.detail}` : ''}`)) - rows.push(text(ctx, ` ${roster.members.length} on · third-party text, not vetted · ${ago(roster.atMs, nowMs)}`, { dimColor: true })) - } + const rows: RenderElement[] = [ + rule(ctx, 'Main menu', 'ruflo federation · x_federation_* tools'), + text(ctx, ' rd reads at once · wr asks first (y) and says what it sends · ad signs as the gateway (admin token)', { dimColor: true }), + ...identityRows(ctx, lead), + ...networkRows(ctx, lead), + ...channelRows(ctx, lead), + ...adminRows(ctx, lead), + ...resultRows(ctx), + ] return col(ctx, rows, 'xruv') } diff --git a/plugins/ruflo-console/hooks/xruv.ts b/plugins/ruflo-console/hooks/xruv.ts new file mode 100644 index 0000000000..8a90a1218a --- /dev/null +++ b/plugins/ruflo-console/hooks/xruv.ts @@ -0,0 +1,357 @@ +/** + * The x.ruv.io board's actions: every `ruflo federation` capability as fixed argv for `ruflo mcp exec -t x_federation_*`, + * checked against the CLI's tools (x-federation-tools.ts, x-federation-join.ts, x-federation-channels.ts). Reads run at + * once, since a click or `/ruflo run` is the person asking; anything that registers, signs, publishes, grants or writes a + * key asks first, and its confirm row says what it sends and where. The channel tools and join make + * `~/.ruflo/nostr.key` when it is missing, so a channel read asks first until that key exists. Text from an Input is + * parsed and validated here, and the one JSON argument is `JSON.stringify`'s. Pure: entries and parsers only, no `$`. + */ +import type { ActionSpec } from './actions' +import { jsonAfter, registryProbe, rosterProbe, channelsProbe, type Channels, type Registry, type Roster } from './data/cli' +import { plain, recordOf, stringOf } from './data/parse' +import { envelopeOf, messageOf, shortKey, swarmProbe, workClaimsProbe, type WorkClaims } from './data/xruv' +import { labLines } from './mh-lab' +import type { State } from './state' + +/** The CLI's own checks (x-federation-channels.ts, x-federation-join.ts), so a bad value is refused before anything runs. */ +export const CHANNEL_NAME_RE = /^[a-z0-9][a-z0-9._-]{0,63}$/ +export const CHANNEL_ID_RE = /^(pub:[a-z0-9][a-z0-9._-]{0,63}|prv:[0-9a-f]{16})$/ +export const INVITE_RE = /^v2\.[A-Za-z0-9._-]{8,}$/ +export const MSG_TYPE_RE = /^[A-Za-z0-9_-]{1,64}$/ +const PUBKEY_RE = /^[0-9a-f]{64}$/i +const INVITE_ANYWHERE = /v2\.[A-Za-z0-9._-]{8,}/g + +export const isPubkey = (value: string): boolean => PUBKEY_RE.test(value) + +/** `pub:` or `prv:<16 hex>` as given, or a bare name as its public channel; null for anything else. */ +export function channelIdOf(word: string): string | null { + const value = word.trim().toLowerCase() + + return CHANNEL_ID_RE.test(value) ? value : CHANNEL_NAME_RE.test(value) ? `pub:${value}` : null +} + +const MAX_PAYLOAD = 2_000 + +/** A message body: a JSON object as typed, else `{ text }`; at most 2,000 characters as JSON, null when empty or not an object. */ +export function payloadOf(raw: string): Record | null { + const value = raw.trim() + + if (value === '') return null + + if (value.startsWith('{')) { + let parsed: unknown + + try { + parsed = JSON.parse(value) + } catch { + return null + } + + const record = recordOf(parsed) + + return record === null || Array.isArray(parsed) || JSON.stringify(record).length > MAX_PAYLOAD ? null : record + } + + const text = plain(value, 500) + + return text === '' ? null : { text } +} + +/** `Type: text` as a message type and its body; text with no type is a Status. */ +export function messageArg(raw: string): { msgType: string; payload: Record } | null { + const typed = /^([A-Za-z0-9_-]{1,64}):\s*([\s\S]+)$/.exec(raw.trim()) + const msgType = typed?.[1] ?? 'Status' + const payload = payloadOf(typed?.[2] ?? raw) + + return payload === null || !MSG_TYPE_RE.test(msgType) ? null : { msgType, payload } +} + +/** ` Type: text`, as the publish Input takes it. */ +export function publishArg(raw: string): { channel: string; msgType: string; payload: Record } | null { + const [first = '', ...rest] = raw.trim().split(/\s+/) + const channel = channelIdOf(first) + const message = messageArg(raw.trim().slice(first.length)) + + return channel === null || rest.length === 0 || message === null ? null : { channel, ...message } +} + +/** ` [public|private]`; public when unsaid. */ +export function createArg(raw: string): { name: string; visibility: 'public' | 'private' } | null { + const [name = '', visibility = 'public', ...extra] = raw.trim().toLowerCase().split(/\s+/) + + return CHANNEL_NAME_RE.test(name) && (visibility === 'public' || visibility === 'private') && extra.length === 0 ? { name, visibility } : null +} + +/** ` <64-hex pubkey>`: only a private channel has a key to grant. */ +export function grantArg(raw: string): { channel: string; pubkey: string } | null { + const [channel = '', pubkey = '', ...extra] = raw.trim().split(/\s+/) + + return /^prv:[0-9a-f]{16}$/.test(channel) && isPubkey(pubkey) && extra.length === 0 ? { channel, pubkey: pubkey.toLowerCase() } : null +} + +/** `<64-hex pubkey> [member|admin]`; member when unsaid. */ +export function admitArg(raw: string): { pubkey: string; role: 'member' | 'admin' } | null { + const [pubkey = '', role = 'member', ...extra] = raw.trim().split(/\s+/) + + return isPubkey(pubkey) && (role === 'member' || role === 'admin') && extra.length === 0 ? { pubkey: pubkey.toLowerCase(), role } : null +} + +/** An invite code in any text, masked: it is a bearer secret, so no line the console writes ever carries one. */ +export const maskInvites = (line: string): string => line.replace(INVITE_ANYWHERE, 'v2.•••• (invite code, masked)') + +const exec = (tool: string, params: Record) => ['mcp', 'exec', '-t', tool, '-p', JSON.stringify(params)] as const +const ago = (atMs: number | undefined, nowMs: number) => (atMs === undefined ? '' : ` · ${Math.max(0, Math.round((nowMs - atMs) / 60_000))}m ago`) + +/** One run's output as the result panel's lines: each read by its shape, anything else flattened, invite codes masked. */ +export function xruvLines(id: string, stdout: string, stderr = '', nowMs = Date.now()): string[] { + const out: string[] = [] + const json = recordOf(jsonAfter(stdout)) + const found = envelopeOf(stdout) + + if (id === 'x-registry') { + const reg = registryProbe.parse(stdout) as Registry | null + + if (reg !== null) out.push(`relay ${reg.relay ?? 'n/a'}${reg.swarmTag !== undefined ? ` · tag #${reg.swarmTag}` : ''} · registration ${reg.registration?.isOpen === true ? 'open' : 'closed'}`, ...reg.join, ...reg.channels.map(room => `#${room.name} — ${room.purpose ?? ''}`)) + } else if (id === 'x-roster') { + const roster = rosterProbe.parse(stdout) as Roster | null + + if (roster !== null) out.push(`${roster.members.length} on ${roster.relay ?? 'the relay'} · third-party text, not vetted`, ...roster.members.map(member => `◉ ${member.name}${member.detail !== undefined ? ` — ${member.detail}` : ''}`)) + } else if (id === 'x-claims') { + const board = workClaimsProbe.parse(stdout) as WorkClaims | null + + if (board !== null) out.push(board.claims.length === 0 ? 'no open claims on the board' : `${board.claims.length} claimed resources`, ...board.claims.map(claim => `${claim.resource} · ${claim.owner}${claim.from !== undefined ? ` (${claim.from})` : ''}${claim.expiresAtMs !== undefined ? ` · until ${new Date(claim.expiresAtMs).toISOString().slice(0, 16)}Z` : ''}`)) + } else if (id === 'x-sync' || id === 'x-read') { + const data = recordOf(found?.data) + const list = Array.isArray(data?.messages) ? data.messages : null + + if (list !== null) { + out.push(`${list.length} message${list.length === 1 ? '' : 's'}${id === 'x-read' ? ` on ${stringOf(data?.channel, 24) ?? 'the channel'} (${stringOf(data?.visibility, 8) ?? 'n/a'})` : ''} · signed by members, not vetted`) + + for (const entry of list.slice(0, 40)) { + const message = messageOf(entry) + const sealed = recordOf(entry)?.encrypted === true ? ` (encrypted: ${stringOf(recordOf(entry)?.reason, 40) ?? 'no key'})` : '' + + if (message !== null) out.push(`[${message.type}] ${message.from}${sealed}${message.text !== undefined ? ` — ${message.text}` : ''}${ago(message.atMs, nowMs)}`) + } + } + } else if (id === 'x-channels') { + const held = channelsProbe.parse(stdout) as Channels | null + + if (held !== null) out.push(held.channels.length === 0 ? 'no channel keys held here' : `${held.channels.length} channels held here (keys stay in ~/.ruflo/channels.json)`, ...held.channels.map(channel => `${channel.id}${channel.name !== undefined ? ` · ${channel.name}` : ''}`)) + } else if (id === 'x-join' && json !== null) { + out.push(`${json.ok === true ? 'joined' : 'not joined'}${json.alreadyMember === true ? ' (already a member: nothing registered)' : ''} · pubkey ${shortKey(json.pubkey) ?? 'n/a'} · key ${json.keyCreated === true ? 'created now' : 'reused'} · membership ${json.membershipVerified === true ? 'verified (NIP-42)' : 'unverified'}`) + if (json.degraded === true) out.push(`degraded: ${stringOf(json.reason, 80) ?? ''} · ${stringOf(json.hint, 120) ?? ''}`) + if (typeof json.reason === 'string' && json.degraded !== true) out.push(`reason: ${plain(json.reason, 140)}`) + } + + const lines = out.length > 0 ? out : labLines(id, stdout, stderr) + + return lines.map(line => maskInvites(plain(line, 160))).slice(0, 60) +} + +/** The node's own Nostr pubkey from a result that names it (join, accept, publish, grant), else null. */ +export function ownPubkeyOf(id: string, stdout: string): string | null { + const json = recordOf(jsonAfter(stdout)) + const key = id === 'x-grant' ? json?.grantedBy : json?.pubkey + + return typeof key === 'string' && isPubkey(key) ? key.toLowerCase() : null +} + +export type XKind = 'read' | 'write' | 'admin' +export type XGroup = 'identity' | 'live' | 'channels' | 'admin' + +export type XEntry = { + id: string + group: XGroup + name: string + about: string + label: string + kind: XKind + /** What its text looks like, for entries that take one (the Input's placeholder, `/ruflo run `). */ + takes?: string + spec: (state: State, text: string) => ActionSpec | null + why: (state: State, text: string) => string +} + +const ADMIN_OFF = 'admin-only: RUFLO_X_ADMIN_TOKEN is not set in the environment Claude Code started with (set it there to enable)' +export const UNREGISTER_WHY = 'unregister: not offered by the x.ruv.io gateway yet (no leave endpoint); your key stays in ~/.ruflo/nostr.key' +const RELAY = 'wss://relay.ruv.io' + +/** A spec bound for the board's result panel, with its pubkey capture and its probe fill. */ +function spec(state: State, id: string, base: Omit, fills?: string): ActionSpec { + const probe = [registryProbe, rosterProbe, channelsProbe, workClaimsProbe, swarmProbe].find(entry => entry.id === fills) + + return { + ...base, + lab: id, + board: 'xruv', + lines: (stdout, stderr) => xruvLines(id, stdout, stderr), + onOutput: stdout => { + const key = ownPubkeyOf(id, stdout) + const value = probe?.parse(stdout) ?? null + + if (key !== null) state.xruv.pubkey = key + if (probe !== undefined && value !== null) state.probes.set(probe.id, { value, okAtMs: Date.now(), error: null, errorAtMs: null, isRunning: false }) + }, + } +} + +/** A network read: the click is the consent, so it runs at once; the same argv the option's probe runs. */ +const read = (id: string, label: string, args: readonly string[], fills: string) => (state: State) => spec(state, id, { label, args, expect: 'its output on the board', isReadOnly: true, timeoutMs: 60_000 }, fills) + +const admin = (state: State, make: () => ActionSpec | null): ActionSpec | null => (state.xruv.hasAdminToken === true ? make() : null) +const hasKey = (state: State) => state.snapshot?.hasNostrKey === true +const MAKES_KEY = 'makes ~/.ruflo/nostr.key first if it is missing (your federation identity, kept 0600, never shown)' + +export const XRUV: readonly XEntry[] = [ + { + id: 'x-join', group: 'identity', name: 'JOIN', about: 'register your own key (NIP-98); an invite code is optional', label: 'join x.ruv.io with your own key', kind: 'write', takes: 'optional invite code: v2.…', + spec: (state, text) => { + const code = text.trim() + + if (code !== '' && !INVITE_RE.test(code)) return null + + return spec(state, 'x-join', { + label: `join x.ruv.io with your own key${code === '' ? '' : ' and an invite'}`, + args: exec('x_federation_join', code === '' ? {} : { code }), + expect: 'membership verified over NIP-42', + shows: `ruflo mcp exec -t x_federation_join${code === '' ? '' : ' (with your invite code, masked here)'}`, + note: `network: checks membership on ${RELAY}, and only if you are not a member signs POST x.ruv.io/api/registration (or the invite claim) with your key; ${MAKES_KEY}`, + timeoutMs: 90_000, + }) + }, + why: () => 'an invite code looks like v2.; leave it empty to join with no invite', + }, + { id: 'x-unregister', group: 'identity', name: 'UNREGISTER', about: 'no leave endpoint on the gateway: nothing to press', label: 'unregister from x.ruv.io (not offered yet)', kind: 'write', spec: () => null, why: () => UNREGISTER_WHY }, + { + id: 'x-bbs-identity', group: 'identity', name: 'BBS IDENTITY', about: 'this project’s agentbbs node id (Ed25519), not the Nostr key', label: 'show the agentbbs node identity', kind: 'write', + spec: state => spec(state, 'x-bbs-identity', { label: 'show the agentbbs node identity (federation_bbs_identity)', args: exec('federation_bbs_identity', {}), expect: 'the node id and public key', note: 'local, $0: creates .agentbbs/node-identity.json here on the first call; the private key is never returned' }), + why: () => '', + }, + { id: 'x-registry', group: 'live', name: 'REGISTRY', about: 'relay, NIP-42 tag, gateway key, join steps, rooms', label: 'fetch the x.ruv.io registry', kind: 'read', spec: read('x-registry', 'fetch the x.ruv.io registry', registryProbe.args, 'registry'), why: () => '' }, + { id: 'x-roster', group: 'live', name: 'ROSTER', about: 'who is announcing on the relay now', label: 'fetch who is on the x.ruv.io swarm (roster)', kind: 'read', spec: read('x-roster', 'fetch the x.ruv.io roster', rosterProbe.args, 'roster'), why: () => '' }, + { id: 'x-claims', group: 'live', name: 'WORK CLAIMS', about: 'one owner per resource, TTLs and handoffs applied', label: 'fetch the x.ruv.io work-claims board', kind: 'read', spec: read('x-claims', 'fetch the x.ruv.io work-claims board', workClaimsProbe.args, 'x-claims'), why: () => '' }, + { id: 'x-sync', group: 'live', name: 'SYNC', about: 'the last hour of signed swarm messages, 20 at most', label: 'fetch recent x.ruv.io swarm messages (sync, 20)', kind: 'read', spec: read('x-sync', 'fetch recent x.ruv.io swarm messages', swarmProbe.args, 'x-sync'), why: () => '' }, + { + id: 'x-channels', group: 'channels', name: 'LIST', about: 'the channels whose keys this machine holds (local)', label: 'list the x.ruv.io channels held here', kind: 'read', + spec: state => spec(state, 'x-channels', { label: 'list the x.ruv.io channels held here', args: channelsProbe.args, expect: 'its output on the board', isReadOnly: true }, 'channels'), + why: () => '', + }, + { + id: 'x-read', group: 'channels', name: 'READ', about: 'a channel’s last hour, decrypted where you hold its key', label: 'read an x.ruv.io channel', kind: 'read', takes: 'pub:, prv:<16 hex> or a name', + spec: (state, text) => { + const channel = channelIdOf(text) + + if (channel === null) return null + + return spec(state, 'x-read', { + label: `read x.ruv.io channel ${channel}`, + args: exec('x_federation_channel_read', { channel, limit: 20 }), + expect: 'its messages on the board', + timeoutMs: 60_000, + // The read signs NIP-42 with your key; with none yet, the CLI would make one, so that first read asks. + ...(hasKey(state) ? { isReadOnly: true } : { note: `network: reads ${RELAY}; ${MAKES_KEY}` }), + }) + }, + why: () => 'name a channel: pub:, prv:<16 hex>, or a bare name for its public channel', + }, + { + id: 'x-publish', group: 'channels', name: 'PUBLISH', about: 'a message signed with your own key', label: 'publish to an x.ruv.io channel as yourself', kind: 'write', takes: ' Type: text (or a JSON object)', + spec: (state, text) => { + const arg = publishArg(text) + + if (arg === null) return null + + const isPrivate = arg.channel.startsWith('prv:') + + return spec(state, 'x-publish', { + label: `publish ${arg.msgType} to ${arg.channel} as yourself`, + args: exec('x_federation_channel_publish', arg), + expect: 'an event id from the relay', + note: `network: signs with your own key and sends to ${RELAY}; ${isPrivate ? 'encrypted under the channel key, so only its members can read it' : 'a pub: channel is plaintext to every relay member'}. Never put secrets in it. ${hasKey(state) ? '' : MAKES_KEY}`.trim(), + timeoutMs: 60_000, + }) + }, + why: () => 'type " Type: text", e.g. "pub:general Status: online"; the type is letters, digits, _ or -', + }, + { + id: 'x-create', group: 'channels', name: 'CREATE', about: 'pub: a named room; prv: a key only you hold', label: 'create an x.ruv.io channel', kind: 'write', takes: ' [public|private]', + spec: (state, text) => { + const arg = createArg(text) + + return arg === null + ? null + : spec(state, 'x-create', { + label: `create ${arg.visibility} channel ${arg.name}`, + args: exec('x_federation_channel_create', arg), + expect: 'the channel id', + note: arg.visibility === 'private' ? 'local, nothing sent: writes a new channel key to ~/.ruflo/channels.json (0600); lose the file and the channel is gone' : 'local, nothing sent or written: names the public channel pub:; publishing to it is what reaches the relay', + }) + }, + why: () => 'type " [public|private]": a name is a-z, 0-9, ., _ or -, up to 64', + }, + { + id: 'x-grant', group: 'channels', name: 'GRANT', about: 'seal a private channel’s key to a member’s pubkey', label: 'grant a member a private x.ruv.io channel', kind: 'write', takes: 'prv:<16 hex> <64-hex pubkey>', + spec: (state, text) => { + const arg = grantArg(text) + + return arg === null + ? null + : spec(state, 'x-grant', { + label: `grant ${arg.channel} to ${arg.pubkey.slice(0, 12)}…`, + args: exec('x_federation_channel_grant', arg), + expect: 'a ChannelGrant event id', + note: `network: publishes a grant sealed to that pubkey on ${RELAY}; grants cannot be revoked (rotate the channel to remove someone)`, + timeoutMs: 60_000, + }) + }, + why: () => 'type "prv:<16 hex> <64-hex pubkey>": only a private channel you hold has a key to grant', + }, + { + id: 'x-accept', group: 'channels', name: 'ACCEPT', about: 'open grants sealed to your key, keep their keys', label: 'accept x.ruv.io channel grants', kind: 'write', + spec: state => spec(state, 'x-accept', { label: 'accept x.ruv.io channel grants sealed to your key', args: exec('x_federation_channel_accept', {}), expect: 'the channels accepted', note: `network: reads the last 7 days of grants on ${RELAY} and stores their keys in ~/.ruflo/channels.json; ${MAKES_KEY}`, timeoutMs: 60_000 }), + why: () => '', + }, + { + id: 'x-hub', group: 'admin', name: 'HUB PUBLISH', about: 'a broadcast signed as the gateway, not as you', label: 'publish to the x.ruv.io swarm as the gateway (admin)', kind: 'admin', takes: 'Type: text (or a JSON object)', + spec: (state, text) => + admin(state, () => { + const arg = messageArg(text) + + return arg === null + ? null + : spec(state, 'x-hub', { label: `publish ${arg.msgType} as the x.ruv.io gateway`, args: exec('x_federation_publish', arg), expect: 'an event id', note: 'ADMIN, network: signed as the gateway with RUFLO_X_ADMIN_TOKEN from the environment (never an argument); attributed to the hub, not to you', timeoutMs: 60_000 }) + }), + why: state => (state.xruv.hasAdminToken === true ? 'type "Type: text", e.g. "Status: maintenance at 18:00"' : ADMIN_OFF), + }, + { + id: 'x-admit', group: 'admin', name: 'ADMIT', about: 'NIP-43 membership for a pubkey, no invite', label: 'admit a pubkey to the x.ruv.io relay (admin)', kind: 'admin', takes: '<64-hex pubkey> [member|admin]', + spec: (state, text) => + admin(state, () => { + const arg = admitArg(text) + + return arg === null + ? null + : spec(state, 'x-admit', { label: `admit ${arg.pubkey.slice(0, 12)}… as ${arg.role}`, args: exec('x_federation_admit', arg), expect: 'the membership event', note: 'ADMIN, network: grants that key relay access with RUFLO_X_ADMIN_TOKEN from the environment; there is no revoke tool', timeoutMs: 60_000 }) + }), + why: state => (state.xruv.hasAdminToken === true ? 'type "<64-hex pubkey> [member|admin]"; a malformed key must be re-reported, never fixed up' : ADMIN_OFF), + }, + { + id: 'x-invite', group: 'admin', name: 'INVITES', about: 'a use-limited code: mint it in the terminal', label: 'mint an x.ruv.io invite code (admin, in the terminal)', kind: 'admin', + // The code is a bearer secret: the board never holds it. It is minted where only the person reads it. + spec: () => null, + why: state => (state.xruv.hasAdminToken === true ? 'an invite code is a bearer secret, so the console never shows one: ▸ type puts "ruflo federation invite" in the terminal (i) for you to run' : ADMIN_OFF), + }, +] + +/** What the INVITES row types into the terminal: the code then shows only in its scrollback, never in an answer. */ +export const INVITE_COMMAND = 'federation invite --ttl 604800 --uses 25' + +/** The headless answer for a board run (`/ruflo run x-roster`): its outcome line, its note, then what it printed. */ +export function xruvAnswer(state: State, id: string | null, sinceMs: number): string | null { + const result = state.xruv.result + + if (result === null || result.atMs < sinceMs || (id !== null && result.id !== id)) return null + + return [`${result.ok ? '✓' : '✗'} ${result.label} · exit ${result.exitCode ?? 'n/a'}${result.note !== undefined ? ` · ${result.note}` : ''}`, ...result.lines.map(line => ` ${line}`)].join('\n') +} diff --git a/plugins/ruflo-console/scripts/smoke.sh b/plugins/ruflo-console/scripts/smoke.sh index 5dae65d642..3a39bf4503 100755 --- a/plugins/ruflo-console/scripts/smoke.sh +++ b/plugins/ruflo-console/scripts/smoke.sh @@ -33,10 +33,10 @@ http=$(grep -rnE '\$\.http\.' "$HOOKS" || true) outside=$(grep -rnE '\$\.(fs|process|ui|clock|store|env|ruflo|tool|session|settings|command)\.' "$HOOKS" | grep -vE '^[^:]+:[0-9]+:\s*(\*|//|/\*)' | grep -v '/register.ts:' || true) [[ -z "$http" && -z "$outside" ]] && ok || bad "http: $http outside: $outside" -step "6. never runs plugins list or verify (network); roster and registry are the two network probes, both opt-in" +step "6. never runs plugins list or verify (network); roster, registry, claims and sync are the network probes, all behind the federationNetwork option" cmds=$(grep -nE "args: \['(plugins|verify)'" "$HOOKS/data/cli.ts" || true) -net=$(grep -c "isNetwork: true" "$HOOKS/data/cli.ts") -[[ -z "$cmds" && "$net" == "2" ]] && grep -q "federationNetwork" "$HOOKS/controller.ts" && ok || bad "cmds: $cmds network probes: $net" +net=$(grep -rc "isNetwork: true" "$HOOKS/data" | awk -F: '{ n += $2 } END { print n }') +[[ -z "$cmds" && "$net" == "4" ]] && grep -q "federationNetwork" "$HOOKS/controller.ts" && ok || bad "cmds: $cmds network probes: $net" step "7. private key files are never read paths" # The federation folder is listed for its file names (node ids); a key file's path never reaches fs.read. diff --git a/plugins/ruflo-console/tests/fixtures/world.ts b/plugins/ruflo-console/tests/fixtures/world.ts index 0bf9052dfa..67aa410f37 100644 --- a/plugins/ruflo-console/tests/fixtures/world.ts +++ b/plugins/ruflo-console/tests/fixtures/world.ts @@ -32,6 +32,8 @@ export type Answer = { exitCode: number; stdout: string; stderr: string } | { de export type World = { files: Map runs: string[][] + /** Every path the mod asked fs.read for, refused or not. */ + reads: string[] blits: string[] opened: string[] commands: string[] @@ -70,13 +72,14 @@ export function cliAnswer(argv: readonly string[]): Answer { * Seats an in-memory world beneath the plugin: files under CWD and HOME, a process table, the store, the panes, and * records of what the mod asked for. `refuseAll` refuses every one of those affordances, as an administrator may. */ -export function worldOf(on: On, files: Readonly>, options: { refuseAll?: boolean; home?: Readonly> } = {}): World { +export function worldOf(on: On, files: Readonly>, options: { refuseAll?: boolean; home?: Readonly>; env?: Readonly> } = {}): World { let tick = 1_000 const all = new Map([...Object.entries(files).map(([path, text]) => [`${CWD}/${path}`, text] as const), ...Object.entries(options.home ?? {}).map(([path, text]) => [`${HOME}/${path}`, text] as const)]) const mtimes = new Map([...all.keys()].map(path => [path, tick])) const world: World = { files: all, runs: [], + reads: [], blits: [], opened: [], commands: [], @@ -93,7 +96,7 @@ export function worldOf(on: On, files: Readonly>, options const refuse = options.refuseAll === true on('session.start', ($, e) => ({ cwd: e.cwd })) - on('fs.read', ($, e) => (refuse || !all.has(e.path) ? { deny: `ENOENT: ${e.path}` } : { value: all.get(e.path) as string })) + on('fs.read', ($, e) => (world.reads.push(e.path), refuse || !all.has(e.path) ? { deny: `ENOENT: ${e.path}` } : { value: all.get(e.path) as string })) on('fs.stat', ($, e) => { const text = all.get(e.path) @@ -114,7 +117,7 @@ export function worldOf(on: On, files: Readonly>, options return 'deny' in answer ? { deny: answer.deny } : { value: { ...answer, isStdoutTruncated: false, isStderrTruncated: false } } }) - on('env.get', ($, e) => (refuse ? { deny: 'env withheld' } : { value: e.name === 'HOME' ? HOME : undefined })) + on('env.get', ($, e) => (refuse ? { deny: 'env withheld' } : { value: e.name === 'HOME' ? HOME : options.env?.[e.name] })) on('settings.read', () => (refuse ? { deny: 'settings withheld' } : { value: { enabledPlugins: { 'ruflo-core@ruflo': true } } as never })) on('session.usage', () => (refuse ? { deny: 'usage withheld' } : { value: { context: { tokens: 50_000, window: 200_000, percent: 25 }, rateLimits: [], cost: { usd: 0.4213 } } as never })) on('tool.list', () => (refuse ? { deny: 'tools withheld' } : { value: [{ name: 'mcp__plugin_ruflo-core_ruflo__swarm_init' }, { name: 'mcp__plugin_ruflo-core_ruflo__claims_board' }, { name: 'Read' }] as never })) diff --git a/plugins/ruflo-console/tests/xruv.spec.ts b/plugins/ruflo-console/tests/xruv.spec.ts new file mode 100644 index 0000000000..204e09dcf6 --- /dev/null +++ b/plugins/ruflo-console/tests/xruv.spec.ts @@ -0,0 +1,176 @@ +/** + * The x.ruv.io board's pure parts under vitest: the validators lifted from the CLI's own checks, the payloads the + * console builds, what reads and what asks, the two network probes and their gate, and the output readers (invite codes + * masked). Run with + * npx vitest run plugins/ruflo-console/tests/xruv.spec.ts + */ +import { describe, expect, it } from 'vitest' + +import { PROBES } from '../hooks/data/cli' +import { envelopeOf, messageOf, swarmProbe, workClaimsProbe, X_PROBES } from '../hooks/data/xruv' +import { newState } from '../hooks/state' +import { admitArg, channelIdOf, createArg, grantArg, isPubkey, maskInvites, messageArg, ownPubkeyOf, payloadOf, publishArg, UNREGISTER_WHY, XRUV, xruvAnswer, xruvLines } from '../hooks/xruv' + +const KEY = 'c0ffee'.repeat(10) + 'beef' +const entry = (id: string) => { + const found = XRUV.find(candidate => candidate.id === id) + + if (found === undefined) throw new Error(`no entry ${id}`) + + return found +} +const params = (args: readonly string[] | undefined) => JSON.parse(args?.[5] ?? 'null') as unknown + +describe('validators', () => { + it('a pubkey is exactly 64 hex digits', () => { + expect(isPubkey(KEY)).toBe(true) + expect(isPubkey(KEY.toUpperCase())).toBe(true) + expect(isPubkey(KEY.slice(1))).toBe(false) + expect(isPubkey(`${KEY}0`)).toBe(false) + expect(isPubkey(`npub1${KEY.slice(5)}`)).toBe(false) + }) + + it('channel ids are pub: or prv:<16 hex>; a bare name is its public channel', () => { + expect(channelIdOf('pub:general')).toBe('pub:general') + expect(channelIdOf('General')).toBe('pub:general') + expect(channelIdOf('prv:0123456789abcdef')).toBe('prv:0123456789abcdef') + expect(channelIdOf('prv:0123456789abcde')).toBeNull() + expect(channelIdOf('prv:secret-room')).toBeNull() + expect(channelIdOf('pub:-flag')).toBeNull() + expect(channelIdOf('--channel')).toBeNull() + expect(channelIdOf('')).toBeNull() + }) + + it('a payload is a JSON object as typed, else { text }; broken JSON and oversize bodies are refused', () => { + expect(payloadOf('online and idle')).toEqual({ text: 'online and idle' }) + expect(payloadOf('{"task":"review #42","eta":5}')).toEqual({ task: 'review #42', eta: 5 }) + expect(payloadOf('{"broken"')).toBeNull() + expect(payloadOf('[1,2]')).toEqual({ text: '[1,2]' }) + expect(payloadOf(`{"text":"${'x'.repeat(2_100)}"}`)).toBeNull() + expect(payloadOf(' ')).toBeNull() + expect(payloadOf('a\u0007b‮')).toEqual({ text: 'a b' }) + }) + + it('messages, publishes, creates, grants and admits parse only in their documented shapes', () => { + expect(messageArg('Task: review #42')).toEqual({ msgType: 'Task', payload: { text: 'review #42' } }) + expect(messageArg('just saying hi')).toEqual({ msgType: 'Status', payload: { text: 'just saying hi' } }) + expect(publishArg('pub:general Result: {"ok":true}')).toEqual({ channel: 'pub:general', msgType: 'Result', payload: { ok: true } }) + expect(publishArg('general online')).toEqual({ channel: 'pub:general', msgType: 'Status', payload: { text: 'online' } }) + expect(publishArg('pub:general')).toBeNull() + expect(publishArg('not/a/channel hi')).toBeNull() + expect(createArg('ops private')).toEqual({ name: 'ops', visibility: 'private' }) + expect(createArg('ops')).toEqual({ name: 'ops', visibility: 'public' }) + expect(createArg('ops secret')).toBeNull() + expect(createArg('Ops Room')).toBeNull() + expect(grantArg(`prv:0123456789abcdef ${KEY.toUpperCase()}`)).toEqual({ channel: 'prv:0123456789abcdef', pubkey: KEY }) + expect(grantArg(`pub:general ${KEY}`)).toBeNull() + expect(grantArg('prv:0123456789abcdef short')).toBeNull() + expect(admitArg(KEY)).toEqual({ pubkey: KEY, role: 'member' }) + expect(admitArg(`${KEY} owner`)).toBeNull() + }) +}) + +describe('the board catalog', () => { + it('reads run at once, writes and admin rows ask, and every argv is one mcp exec with one JSON argument', () => { + const state = newState({}) + + state.xruv.hasAdminToken = true + state.snapshot = { hasNostrKey: true } as never + + const samples: Record = { 'x-join': '', 'x-read': 'pub:general', 'x-publish': 'pub:general hi', 'x-create': 'ops', 'x-grant': `prv:0123456789abcdef ${KEY}`, 'x-hub': 'Status: up', 'x-admit': KEY } + + expect(new Set(XRUV.map(candidate => candidate.id)).size).toBe(XRUV.length) + + for (const candidate of XRUV) { + const spec = candidate.spec(state, samples[candidate.id] ?? '') + + if (spec === null) continue + + expect(spec.args.slice(0, 4)).toEqual(['mcp', 'exec', '-t', spec.args[3]]) + expect(spec.args).toHaveLength(6) + expect(spec.board).toBe('xruv') + expect(spec.isReadOnly === true).toBe(candidate.kind === 'read') + } + }) + + it('a channel read asks first while there is no Nostr key, since the CLI would make one', () => { + const state = newState({}) + + expect(entry('x-read').spec(state, 'general')?.isReadOnly).toBeUndefined() + expect(entry('x-read').spec(state, 'general')?.note).toContain('~/.ruflo/nostr.key') + state.snapshot = { hasNostrKey: true } as never + expect(entry('x-read').spec(state, 'general')?.isReadOnly).toBe(true) + expect(params(entry('x-read').spec(state, 'general')?.args)).toEqual({ channel: 'pub:general', limit: 20 }) + }) + + it('unregister and invite never produce a spec; admin rows need the token', () => { + const state = newState({}) + + expect(entry('x-unregister').spec(state, '')).toBeNull() + expect(entry('x-unregister').why(state, '')).toBe(UNREGISTER_WHY) + expect(entry('x-admit').spec(state, KEY)).toBeNull() + expect(entry('x-admit').why(state, KEY)).toContain('RUFLO_X_ADMIN_TOKEN is not set') + state.xruv.hasAdminToken = true + expect(entry('x-invite').spec(state, '')).toBeNull() + expect(params(entry('x-admit').spec(state, KEY)?.args)).toEqual({ pubkey: KEY, role: 'member' }) + }) + + it('join takes an optional invite code, masks it on the confirm row, and refuses a malformed one', () => { + const state = newState({}) + const join = entry('x-join').spec(state, 'v2.abcdefgh12') + + expect(params(entry('x-join').spec(state, '')?.args)).toEqual({}) + expect(params(join?.args)).toEqual({ code: 'v2.abcdefgh12' }) + expect(join?.shows).not.toContain('v2.abcdefgh12') + expect(entry('x-join').spec(state, 'abcdefgh')).toBeNull() + }) +}) + +describe('network probes', () => { + it('claims and sync are network reads drawn only on the board; PROBES keeps its two', () => { + expect(X_PROBES.map(probe => [probe.id, probe.isNetwork, probe.views])).toEqual([ + ['x-claims', true, ['xruv']], + ['x-sync', true, ['xruv']], + ]) + expect(PROBES.filter(probe => probe.isNetwork === true).map(probe => probe.id)).toEqual(['roster', 'registry']) + expect(params(swarmProbe.args)).toEqual({ limit: 20 }) + }) + + it('reads the gateway envelope as data, short keys only, hostile text stripped', () => { + const fenced = (data: unknown) => `Result:\n${JSON.stringify({ untrusted: true, relay: 'wss://relay.ruv.io', retrievedAt: '2026-10-02T12:00:00Z', data })}` + const claims = workClaimsProbe.parse(fenced({ 'repo:x#1': { owner: KEY, from: 'node\u001b[31m', expiresAt: '2026-10-02T13:00:00Z' }, bad: 'nope' })) + const sync = swarmProbe.parse(fenced({ messages: [{ type: 'Task', task: 'review', pubkey: KEY, created_at: 1 }, { type: 'Status', text: 'up', pubkey: KEY, created_at: 2 }, 'junk'] })) + + expect(envelopeOf('no json')).toBeNull() + expect(claims?.claims).toEqual([{ resource: 'repo:x#1', owner: `${KEY.slice(0, 12)}…`, from: 'node', expiresAtMs: Date.parse('2026-10-02T13:00:00Z') }]) + expect(claims?.relay).toBe('wss://relay.ruv.io') + expect(sync?.messages.map(message => message.text)).toEqual(['up', 'review']) + expect(messageOf({ type: 'Status' })).toBeNull() + expect(swarmProbe.parse('Result:\n{"untrusted":true,"data":{}}')).toBeNull() + }) +}) + +describe('result lines', () => { + it('invite codes are masked in every line and in the headless answer', () => { + const stdout = `Result:\n${JSON.stringify({ ok: true, code: 'v2.SECRETinviteTOKEN123', uses: 25 })}` + const lines = xruvLines('x-hub', stdout) + const state = newState({}) + + expect(lines.join('\n')).not.toContain('SECRETinvite') + expect(maskInvites('code v2.SECRETinviteTOKEN123 here')).toBe('code v2.•••• (invite code, masked) here') + state.xruv.result = { id: 'x-hub', label: 'publish', ok: true, exitCode: 0, lines, atMs: 5 } + expect(xruvAnswer(state, 'x-hub', 1)).not.toContain('SECRETinvite') + expect(xruvAnswer(state, 'x-roster', 1)).toBeNull() + }) + + it('a join reads as joined or not, a read lists its messages, and the own pubkey is taken only when it is one', () => { + const join = `Result:\n${JSON.stringify({ ok: true, pubkey: KEY, keyCreated: true, membershipVerified: true, alreadyMember: true })}` + const read = `Result:\n${JSON.stringify({ channel: 'prv:0123456789abcdef', visibility: 'private', count: 1, messages: [{ id: 'e', pubkey: KEY, created_at: 1, encrypted: true, reason: 'no channel key held' }] })}` + + expect(xruvLines('x-join', join)[0]).toBe(`joined (already a member: nothing registered) · pubkey ${KEY.slice(0, 12)}… · key created now · membership verified (NIP-42)`) + expect(xruvLines('x-read', read, '', 1_000)).toEqual(['1 message on prv:0123456789abcdef (private) · signed by members, not vetted', `[message] ${KEY.slice(0, 12)}… (encrypted: no channel key held) · 0m ago`]) + expect(ownPubkeyOf('x-join', join)).toBe(KEY) + expect(ownPubkeyOf('x-grant', `Result:\n${JSON.stringify({ grantedBy: KEY })}`)).toBe(KEY) + expect(ownPubkeyOf('x-join', 'Result:\n{"pubkey":"not-hex"}')).toBeNull() + }) +}) diff --git a/plugins/ruflo-console/tests/xruv.test.ts b/plugins/ruflo-console/tests/xruv.test.ts new file mode 100644 index 0000000000..3895ac8aca --- /dev/null +++ b/plugins/ruflo-console/tests/xruv.test.ts @@ -0,0 +1,196 @@ +import { describe, expect, mock, test } from 'claude-code/testing' + +import { RUFLO_FILES } from './fixtures/ruflo-run' +import { cliAnswer, command, elementsOf, keyOf, paneAt, PLUGIN, SESSION, textOf, worldOf, type Answer } from './fixtures/world' + +const PUBKEY = 'ab'.repeat(32) +const TOKEN = 'xr-admin-token-do-not-print-0123456789' +const INVITE = 'v2.SECRETinviteTOKEN123' +const NETWORK = /x_federation_(registry|roster|claims|sync|channel_read|join|channel_publish|channel_grant|channel_accept|admit|publish|invite)/ +const ok = (body: unknown): Answer => ({ exitCode: 0, stdout: `[INFO] Executing tool\nResult:\n${JSON.stringify(body)}`, stderr: '' }) +const fenced = (data: unknown) => ({ untrusted: true, provenance: 'third-party relay text', relay: 'wss://relay.ruv.io', retrievedAt: '2026-10-02T12:00:00Z', data }) + +/** The federation reads and writes answered as the CLI answers them; everything else from the captured run. */ +function respond(argv: readonly string[]): Answer { + const line = argv.join(' ') + + if (line.includes('x_federation_roster')) return ok(fenced({ [`${PUBKEY.slice(0, 20)}`]: { about: 'coder node in Toronto' } })) + if (line.includes('x_federation_claims')) return ok(fenced({ 'repo:ruflo#42': { owner: PUBKEY, from: 'ruvultra', ttlSeconds: 600, expiresAt: '2026-10-02T13:00:00Z' } })) + if (line.includes('x_federation_sync')) return ok(fenced({ count: 1, messages: [{ type: 'Status', text: 'online and idle', id: 'e1', pubkey: PUBKEY, created_at: 1_790_000_000 }] })) + if (line.includes('x_federation_registry')) return ok({ relay: 'wss://relay.ruv.io', swarmTag: 'ruflo-swarm', registration: { enabled: true, authentication: 'NIP-98' }, join: ['1. generate a key'], defaultChannels: [{ channel: 'general', purpose: 'everything' }] }) + if (line.includes('x_federation_channel_publish')) return ok({ ok: true, channel: 'pub:general', visibility: 'public', encrypted: false, eventId: 'ev1', pubkey: PUBKEY }) + if (line.includes('x_federation_join')) return ok({ ok: true, pubkey: PUBKEY, keyCreated: false, membershipVerified: true, next: `share ${INVITE} with nobody` }) + + return cliAnswer(argv) +} + +const fedRuns = (runs: readonly string[][]) => runs.filter(argv => NETWORK.test(argv.join(' '))) +const argsOf = (runs: readonly string[][], tool: string) => runs.find(argv => argv.includes(tool))?.slice(4) + +describe('x.ruv.io board', () => { + test('every capability is a row with a button or a field; nothing on the network is asked and the key is never read', { options: { boot: false } }, async ($, on) => { + const world = worldOf(on, RUFLO_FILES, { home: { '.ruflo/nostr.key': 'never-read' } }) + world.respond = respond + mock.clock(on) + await $.session.start(SESSION) + await $.command.run(command('xruv')) + + const pane = await $.ui.mount({ ...paneAt(120), surface: 'terminal' as const, plugin: PLUGIN }) + const tree = await pane.drawn() + const text = textOf(tree) + + expect(elementsOf(tree, 'Button').map(keyOf)).toEqual(expect.arrayContaining(['xr-x-join', 'xr-x-bbs-identity', 'xr-x-registry', 'xr-x-roster', 'xr-x-claims', 'xr-x-sync', 'xr-x-channels', 'xr-x-accept'])) + expect(elementsOf(tree, 'Input').map(keyOf)).toEqual(expect.arrayContaining(['xr-in-x-join', 'xr-in-x-read', 'xr-in-x-publish', 'xr-in-x-create', 'xr-in-x-grant'])) + expect(text).toContain(' JOIN ....') + expect(text).toContain('present: ~/.ruflo/nostr.key (never read here)') + expect(text).toContain('unregister: not offered by the x.ruv.io gateway yet') + expect(text).toContain('admin token: set it in the environment to enable') + expect(text).toContain('Turn on federationNetwork in /config') + expect(fedRuns(world.runs)).toEqual([]) + expect(world.reads.some(path => path.endsWith('nostr.key') || path.endsWith('channels.json'))).toBe(false) + await pane.unmount() + }) + + test('a fetch runs one fixed read on the click, fills its section and the result panel', { options: { boot: false } }, async ($, on) => { + const world = worldOf(on, RUFLO_FILES) + + world.respond = respond + mock.clock(on) + await $.session.start(SESSION) + await $.command.run(command('xruv')) + + const pane = await $.ui.mount({ ...paneAt(120), surface: 'terminal' as const, plugin: PLUGIN }) + + await pane.press({ key: 'xr-x-claims' }) + + const text = textOf(await pane.drawn()) + + expect(fedRuns(world.runs).map(argv => argv.slice(4))).toEqual([['mcp', 'exec', '-t', 'x_federation_claims', '-p', '{}']]) + expect(text).toContain('repo:ruflo#42 · abababababab… (ruvultra)') + expect(text).toContain('1 claimed resources') + await pane.unmount() + }) + + test('with federationNetwork on, the board keeps the registry, roster, claims and swarm live', { options: { boot: false, federationNetwork: true } }, async ($, on) => { + const world = worldOf(on, RUFLO_FILES) + + world.respond = respond + mock.clock(on) + await $.session.start(SESSION) + + await $.command.run(command('xruv')) + await $.command.run(command('status')) + + const text = textOf(await $.ui.render(paneAt(120))) + + expect(argsOf(world.runs, 'x_federation_sync')).toEqual(['mcp', 'exec', '-t', 'x_federation_sync', '-p', '{"limit":20}']) + expect(world.runs.some(argv => argv.includes('x_federation_claims'))).toBe(true) + expect(text).toContain('[Status] abababababab… — online and idle') + expect(text).toContain('◉ abababababababababab — coder node in Toronto') + // Writes never run on their own, even with the network on. + expect(world.runs.some(argv => /x_federation_(join|channel_publish|channel_grant|channel_accept|admit|publish|invite_mint)/.test(argv.join(' ')))).toBe(false) + }) + + test('writes ask first and run one fixed argv on yes; a bad value runs nothing', { options: { boot: false } }, async ($, on) => { + const world = worldOf(on, RUFLO_FILES, { home: { '.ruflo/nostr.key': 'never-read' } }) + + world.respond = respond + mock.clock(on) + await $.session.start(SESSION) + await $.command.run(command('xruv')) + + const pane = await $.ui.mount({ ...paneAt(120), surface: 'terminal' as const, plugin: PLUGIN }) + + await pane.input({ key: 'xr-in-x-publish', text: 'pub:general Status: online', kind: 'submit' }) + expect(textOf(await pane.drawn())).toContain('Confirm: publish Status to pub:general as yourself?') + expect(fedRuns(world.runs)).toEqual([]) + await pane.press({ key: 'confirm' }) + expect(argsOf(world.runs, 'x_federation_channel_publish')).toEqual(['mcp', 'exec', '-t', 'x_federation_channel_publish', '-p', JSON.stringify({ channel: 'pub:general', msgType: 'Status', payload: { text: 'online' } })]) + + // The pubkey the publish named now stands for this node. + expect(textOf(await pane.drawn())).toContain(`${PUBKEY.slice(0, 16)}…${PUBKEY.slice(-6)}`) + + await pane.input({ key: 'xr-in-x-grant', text: 'prv:0123456789abcdef not-a-key', kind: 'submit' }) + await pane.input({ key: 'xr-in-x-create', text: 'Bad Name!', kind: 'submit' }) + expect(textOf(await pane.drawn())).not.toContain('Confirm:') + expect(world.runs.some(argv => /x_federation_channel_(grant|create)/.test(argv.join(' ')))).toBe(false) + + await pane.press({ key: 'xr-x-accept' }) + await pane.press({ key: 'cancel' }) + expect(world.runs.some(argv => argv.includes('x_federation_channel_accept'))).toBe(false) + await pane.unmount() + }) + + test('join with an invite: the code is masked on the confirm row and in the answer, and sent once as its own argv', { options: { boot: false } }, async ($, on) => { + const world = worldOf(on, RUFLO_FILES) + + world.respond = respond + mock.clock(on) + await $.session.start(SESSION) + + const asked = await $.command.run(command(`run x-join ${INVITE}`)) + const shown = textOf(await $.ui.render(paneAt(120))) + + expect(asked.text).toBe('Asked: join x.ruv.io with your own key and an invite. Confirm with /ruflo yes (or y in the pane), cancel with /ruflo no.') + expect(shown).toContain('your invite code, masked here') + expect(shown).not.toContain(INVITE) + + const answer = await $.command.run(command('yes')) + + expect(argsOf(world.runs, 'x_federation_join')).toEqual(['mcp', 'exec', '-t', 'x_federation_join', '-p', JSON.stringify({ code: INVITE })]) + expect(answer.text).toContain('joined · pubkey abababababab… · key reused · membership verified (NIP-42)') + expect(answer.text).not.toContain(INVITE) + expect(textOf(await $.ui.render(paneAt(120)))).not.toContain(INVITE) + }) + + test('unregister is never run; headless reads answer with what they fetched', { options: { boot: false } }, async ($, on) => { + const world = worldOf(on, RUFLO_FILES) + + world.respond = respond + mock.clock(on) + await $.session.start(SESSION) + + expect((await $.command.run(command('run x-unregister'))).text).toContain('not offered by the x.ruv.io gateway yet') + expect((await $.command.run(command('yes'))).text).toBe('Nothing is waiting for a confirm.') + expect(fedRuns(world.runs)).toEqual([]) + + const roster = await $.command.run(command('run x-roster')) + + expect(roster.text).toMatch(/^✓ fetch the x\.ruv\.io roster/) + expect(roster.text).toContain('◉ abababababababababab — coder node in Toronto') + }) + + test('admin rows: refused without the token; with it, they ask first and the token never reaches argv or the screen', { options: { boot: false } }, async ($, on) => { + const world = worldOf(on, RUFLO_FILES) + + world.respond = respond + mock.clock(on) + await $.session.start(SESSION) + expect((await $.command.run(command(`run x-admit ${PUBKEY}`))).text).toContain('RUFLO_X_ADMIN_TOKEN is not set') + expect(fedRuns(world.runs)).toEqual([]) + }) + + test('with the admin token set, admit asks first and runs without the token in its argv', { options: { boot: false } }, async ($, on) => { + const world = worldOf(on, RUFLO_FILES, { env: { RUFLO_X_ADMIN_TOKEN: TOKEN } }) + + world.respond = respond + mock.clock(on) + await $.session.start(SESSION) + + const asked = await $.command.run(command(`run x-admit ${PUBKEY}`)) + await $.command.run(command('xruv')) + + const shown = textOf(await $.ui.render(paneAt(120))) + + expect(asked.text).toContain(`Asked: admit ${PUBKEY.slice(0, 12)}… as member`) + expect(shown).toContain('RUFLO_X_ADMIN_TOKEN is set') + expect(fedRuns(world.runs)).toEqual([]) + await $.command.run(command('yes')) + expect(argsOf(world.runs, 'x_federation_admit')).toEqual(['mcp', 'exec', '-t', 'x_federation_admit', '-p', JSON.stringify({ pubkey: PUBKEY, role: 'member' })]) + expect(world.runs.some(argv => argv.join(' ').includes(TOKEN))).toBe(false) + expect(textOf(await $.ui.render(paneAt(120)))).not.toContain(TOKEN) + // Invites are minted in the terminal, never by the board. + expect((await $.command.run(command('run x-invite'))).text).toContain('the console never shows one') + expect(world.runs.some(argv => argv.includes('x_federation_invite_mint'))).toBe(false) + }) +}) diff --git a/scripts/ci-test-baseline.txt b/scripts/ci-test-baseline.txt index e3fe62415a..0229bb5522 100644 --- a/scripts/ci-test-baseline.txt +++ b/scripts/ci-test-baseline.txt @@ -163,3 +163,4 @@ plugins/ruflo-console/tests/actions.test.ts plugins/ruflo-console/tests/behaviour.test.ts plugins/ruflo-console/tests/palette.test.ts plugins/ruflo-console/tests/views.test.ts +plugins/ruflo-console/tests/xruv.test.ts