diff --git a/plugins/ruflo-console/.claude-plugin/plugin.json b/plugins/ruflo-console/.claude-plugin/plugin.json index bd3014946c..234b0f1c41 100644 --- a/plugins/ruflo-console/.claude-plugin/plugin.json +++ b/plugins/ruflo-console/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "ruflo-console", "description": "ruflo's cockpit inside Claude Code and the one /ruflo command for every ruflo mod (function hooks, early access). Views: overview with health alerts, swarm topology graph, claims flow with TTL rings, federation map, plugin health matrix, learning curve and pipeline, MetaHarness radar and audit trend, memory, cost gauge, agent timeline, approvals queue, event stream, a main menu, an x.ruv.io federation board, an AI terminal (codex, claude or both in remembered sessions, streamed), Skills (npx skills), a Hive-Mind view, a MetaHarness lab, agent drill-down; a command palette for confirm-gated actions through the ruflo CLI; a band above the prompt. Reads ruflo's files and the CLI's local JSON; anything not measured reads n/a. The one network call it makes by itself is a daily read of the published plugin.json at github.com/ruvnet/ruflo to offer an update (Settings → Updates: ask, auto, or off); it installs only through Claude Code's own claude plugin update, and never a new major version without asking.", - "version": "0.30.0", + "version": "0.31.0", "author": { "name": "ruvnet", "url": "https://github.com/ruvnet" diff --git a/plugins/ruflo-console/hooks/bindings.ts b/plugins/ruflo-console/hooks/bindings.ts index c98e4853a5..eeaaebc567 100644 --- a/plugins/ruflo-console/hooks/bindings.ts +++ b/plugins/ruflo-console/hooks/bindings.ts @@ -30,6 +30,7 @@ import { skillActions } from './skills' import { moreSkillActions } from './skills-lab' import { CLI_PREFIXES, NAV_KEY, PANE_ID, viewOf, type State } from './state' import { runUpdateCheck } from './update-flow' +import { claudeActions } from './mission-claude' import { UPDATES_KEY } from './updates' import { vectorActions } from './vector' import type { Actions } from './views/common' @@ -360,7 +361,7 @@ export function actionsOf(state: State, host: Host, runner: Runner, steps: Steps vector: vectorActions(state, runner, text => actions.term.load('claude', text)), evolve: evolveActions(state, host, text => actions.term.ask('claude', text)), settings: settingsActions(state, host, runner, (agent, text) => actions.term.ask(agent, text), () => CLI_PREFIXES[state.options.cli], () => pluginNames(state, (catalogOf(state).plugins ?? []).filter(plugin => plugin.options.length > 0).map(plugin => plugin.name))), - mission: missionActions(state, host, runner), + mission: { ...missionActions(state, host, runner), ...claudeActions(state, host, runner) }, ask: askActions(state, host, runner, () => actions), ruhelp: helpActions(state, host, runner, () => actions), loops: loopActions(state, host, runner), diff --git a/plugins/ruflo-console/hooks/controller.ts b/plugins/ruflo-console/hooks/controller.ts index 72a7d528f4..8970c86ce7 100644 --- a/plugins/ruflo-console/hooks/controller.ts +++ b/plugins/ruflo-console/hooks/controller.ts @@ -6,7 +6,7 @@ import { actionsOf } from './bindings' import type { Catalog } from './data/catalog' import { PROBES, probeArgv, probeReady, type ProbeResult } from './data/cli' -import { COST_PROBES } from './data/cost-ledger' +import { ALL_COST_PROBES as COST_PROBES } from './data/cost-probes' import { X_PROBES } from './data/xruv' import { diffEvents, record } from './data/events' import { plain } from './data/parse' diff --git a/plugins/ruflo-console/hooks/data/cost-probes.ts b/plugins/ruflo-console/hooks/data/cost-probes.ts new file mode 100644 index 0000000000..75b81d513a --- /dev/null +++ b/plugins/ruflo-console/hooks/data/cost-probes.ts @@ -0,0 +1,37 @@ +/** + * Every probe of the cost-tracker plugin's ledger: the Cost page's seven-day reading, and the active mission's spend (ADR-443). The + * mission's needs a newer tracker than the Cost page's (the `--from`, `--to` and `--project` filters), so an older one is "not ready", + * and the probe does not run. Local only: nothing here reaches the network. + */ +import { activeMission } from '../mission-control' +import { bumpKind, parseSemver } from '../updates' +import type { State } from '../state' +import { COST_PLUGIN, costLedgerProbe, trackerOf } from './cost-ledger' +import { missionCostArgv, parseMissionCost, type MissionCost } from './mission-cost' +import type { Probe } from './cli' + +/** The first tracker release whose ledger takes the window and project filters. */ +export const MISSION_COST_FROM = '0.27.1' + +function missionCostArgs(state: State): readonly string[] | null { + const tracker = trackerOf(state) + const mission = activeMission(state) + + if (tracker.kind !== 'ready' || mission === null) return null + + const version = state.snapshot?.plugins.installed?.find(plugin => plugin.id === COST_PLUGIN)?.version ?? '' + + // Older than the filters (or not a version we can read): not ready, never guessed at. + if (parseSemver(version) === null || bumpKind(version, MISSION_COST_FROM) !== null) return null + + // A finished or cancelled mission's window closes at its last event; a live one stays open at the right. + const end = mission.cancelled ? Math.max(mission.createdAtMs, ...mission.events.map(event => event.atMs)) : null + + return missionCostArgv(tracker.root, mission.createdAtMs, end, state.cwd) +} + +export const missionCostProbe: Probe = { + id: 'mission-cost', args: [], argvOf: missionCostArgs, views: ['missions'], everyMs: 120_000, timeoutMs: 60_000, parse: parseMissionCost, +} + +export const ALL_COST_PROBES = [costLedgerProbe, missionCostProbe] as const diff --git a/plugins/ruflo-console/hooks/data/mission-cost.ts b/plugins/ruflo-console/hooks/data/mission-cost.ts new file mode 100644 index 0000000000..0ed4159653 --- /dev/null +++ b/plugins/ruflo-console/hooks/data/mission-cost.ts @@ -0,0 +1,82 @@ +/** + * Mission spend (ADR-443 §2.3). The console asks the ruflo-cost-tracker plugin's `ledger.mjs` for the spend inside a + * mission's time window and project, and compares it with an optional USD cap on the ADR-437 ladder (50, 75, 90, 100 + * percent of the cap). Pure: it builds the command and reads the answer; the probe runner does the running. Local only, + * and USD and Codex credits are never added together; a model without a price is listed, never counted as $0. + */ +import { budgetAmount, ladderDollars } from '../cost' +import { jsonAfter } from './cli' +import { safeInstallPath } from './cost-ledger' +import { numberOf, plain, recordOf } from './parse' + +export type MissionCost = { usd: number | null; credits: number | null; unpriced: string[]; rows: number; /** The window's start the ledger reports back: it says which mission the reading is for. */ fromMs: number | null } +export type CapLevel = 'none' | 'OK' | 'INFO' | 'WARNING' | 'CRITICAL' | 'HARD_STOP' +export type CapState = { level: CapLevel; percent: number | null } + +/** An absolute POSIX path: no control characters, no `..` segment. It is one argv element, never part of a shell line. */ +const safeProject = (value: unknown): string | undefined => { + const path = typeof value === 'string' ? value : '' + + return path.startsWith('/') && path.length <= 500 && !/[\u0000-\u001f\u007f-\u009f]/.test(path) && !path.split('/').includes('..') ? path : undefined +} + +/** + * The ledger command for one mission: its window (`fromMs`, and `toMs` once it has ended) in its `project`. `null` when + * the plugin root or the project fails the path checks, or a time is not a real instant. A mission still running has + * `toMs === null`, so no `--to` is sent and the window stays open at the right. + */ +export function missionCostArgv(root: string, fromMs: number, toMs: number | null, project: string): readonly string[] | null { + const base = safeInstallPath(root) + const where = safeProject(project) + const iso = (ms: number): string | undefined => (Number.isFinite(ms) && Math.abs(ms) < 8.64e15 ? new Date(ms).toISOString() : undefined) + const from = iso(fromMs) + const to = toMs === null ? null : iso(toMs) + + if (base === undefined || where === undefined || from === undefined || to === undefined) return null + if (to !== null && Date.parse(to) < Date.parse(from)) return null + + return ['node', `${base}/scripts/ledger.mjs`, '--format', 'json', '--from', from, ...(to === null ? [] : ['--to', to]), '--project', where] +} + +/** What `ledger.mjs --format json` printed for the window. A total that is missing is `null` (unknown), not zero. */ +export function parseMissionCost(stdout: string): MissionCost | null { + const value = recordOf(jsonAfter(stdout)) + const totals = recordOf(value?.totals) + + if (value === null || totals === null) return null + + const rows = Math.max(0, Math.floor(numberOf(value.rows) ?? 0)) + const usd = numberOf(totals.usd) + const credits = numberOf(totals.credits) + + return { + // No rows at all is a true $0; rows that are all unpriced leave the total unknown, which is not the same thing. + usd: usd !== undefined && usd >= 0 ? usd : rows === 0 ? 0 : null, + credits: credits !== undefined && credits >= 0 ? credits : null, + unpriced: Object.keys(recordOf(value.unpriced) ?? {}).slice(0, 10).map(name => plain(name, 50)), + rows, + fromMs: windowFromMs(value.window), + } +} + +function windowFromMs(window: unknown): number | null { + const from = recordOf(window)?.from + const ms = typeof from === 'string' ? Date.parse(from) : NaN + + return Number.isFinite(ms) ? ms : null +} + +/** Where `spendUsd` sits on the ladder of `cap`; `none` without a spend or a cap. `percent` is the share of the cap used. */ +export function capState(spendUsd: number | null, cap: number | null): CapState { + if (spendUsd === null || cap === null || !Number.isFinite(spendUsd) || !Number.isFinite(cap) || cap <= 0 || spendUsd < 0) return { level: 'none', percent: null } + + const reached = ladderDollars(cap).filter(rung => rung.usd !== null && spendUsd >= rung.usd).at(-1) + + return { level: (reached?.level as CapLevel | undefined) ?? 'OK', percent: spendUsd / cap * 100 } +} + +/** Auto-run stops at the cap, and only when auto-run is on: a warning level never pauses anything. */ +export const shouldPause = (state: CapState, autoRun: boolean): boolean => autoRun && state.level === 'HARD_STOP' + +/** A cap typed by the person: 0.01 to 10000 dollars, decimal digits only (same rule as the budget setter). */ +export const capUsd = (text: string): number | null => budgetAmount(text) diff --git a/plugins/ruflo-console/hooks/help-topics-core.ts b/plugins/ruflo-console/hooks/help-topics-core.ts index e1d0b14806..41d9d60d40 100644 --- a/plugins/ruflo-console/hooks/help-topics-core.ts +++ b/plugins/ruflo-console/hooks/help-topics-core.ts @@ -121,14 +121,15 @@ export const CORE_TOPICS: readonly HelpTopic[] = [ steps: [ { text: 'Set the loop in Settings: the interval (5m by default), a worktree per writer, whether it may commit, push or publish (push and publish are off), and the most concurrent writers (6).', go: { view: 'settings' }, label: 'Open Settings' }, { text: 'Enter your goal. The plan and Claude’s guidance now name the /loop line, each tick’s checklist, the gates, the finish condition and the stop rule.', go: { view: 'missions' }, label: 'Open Missions' }, - { text: 'Each tick the loop checks progress, fixes what failed, runs the gates (tests, build and smoke, and the checks the plan asks for), and repeats until every phase is green.' }, - { text: 'Writers work at once, each in its own worktree on its own files. Each phase has acceptance checks, and a result counts when its real output was read.' }, - { text: 'Defaults are stated up front, so the loop does not stop to ask. It stops only on the finish condition, or when a gate keeps failing the same way.' }, + { text: 'Each tick the loop checks progress, fixes what failed, runs the gates and repeats until every phase is green. Writers work at once, each in its own worktree; defaults are stated up front, so it does not stop to ask.' }, + { text: 'On a long mission open its Loop tab. Start puts the /loop line in your prompt box (you press Enter); the console counts ticks, shows the next one and the time left, and warns before the 7-day expiry. Re-arm prepares a fresh one.', go: { view: 'missions' }, label: 'Open Missions' }, + { text: 'Verify runs your own gate commands (Settings → Mission gates). Each asks first, runs without a shell, and its exit code is recorded as evidence.' }, + { text: 'Set a spend cap in Settings: auto-run pauses when the mission reaches it. Spend is a list-price estimate from the cost ledger.' }, { text: 'Nothing leaves the mission branch unless you turned it on: no push, no release, no deploy.' }, ], - tips: ['A fix is checked by breaking it once: the test must fail, then pass again.'], - related: ['mission', 'swarm', 'verify'], - keywords: ['loop', 'tick', 'interval', 'worktree', 'gates', 'finish', 'concurrent', 'writers', 'autopilot', 'defaults'], + tips: ['A fix is checked by breaking it once: the test must fail, then pass again.', 'The active task rides in Claude’s prompt (Settings → Mission context) and changes only when the task does, so the cache stays warm.'], + related: ['mission', 'swarm', 'verify', 'cost'], + keywords: ['loop', 'tick', 'interval', 'worktree', 'gates', 'finish', 'concurrent', 'writers', 'autopilot', 'defaults', 'long', 'expire', 're-arm', 'cap', 'verify', 'evidence'], }, { id: 'swarm', diff --git a/plugins/ruflo-console/hooks/mission-claude.ts b/plugins/ruflo-console/hooks/mission-claude.ts new file mode 100644 index 0000000000..0d293a5600 --- /dev/null +++ b/plugins/ruflo-console/hooks/mission-claude.ts @@ -0,0 +1,185 @@ +/** + * Missions that Claude knows about (ADR-443): the glue between Mission Control and four pure modules. The context section Claude reads + * every turn (mission-context.ts), gate evidence (mission-verify.ts), the loop manager (mission-loop.ts) and the mission's spend + * (data/mission-cost.ts, mission-guard.ts). Nothing here reaches the network or runs anything unasked: a gate run and a loop hand-off + * both go through the confirm row, and the loop is only ever prepared in the prompt box (Claude owns the schedule). + */ +import type { ActionSpec } from './actions' +import type { Host } from './host' +import { activeMission, derive, mcOf, nextTask, record, saveLedger } from './mission-control' +import { CONTEXT_SECTION_ID, contextEnabled, missionContextKey, missionContextText, turnNote, type TurnReason } from './mission-context' +import { armed, isTick, parseLoop, rearmCommand, startCommand, stop, stopRequest, tick, tickPlan, type LoopState } from './mission-loop' +import { evidenceEvent, parseGates } from './mission-verify' +import { costOf, capOf } from './mission-guard' +import { plain } from './data/parse' +import type { LedgerTask, MissionActions, MissionRecord } from './mission-types' +import type { Runner } from './runner' +import { settingsOf } from './settings' +import type { State } from './state' + +/** The mission's loop as it was saved (validated; a bad value is no loop). */ +export const loopOf = (mission: MissionRecord): LoopState | null => parseLoop(mission.loop) + +const setLoop = (mission: MissionRecord, loop: LoopState): void => void (mission.loop = loop) + +/** The task Claude is on, else the next ready one: what the context section describes. */ +function currentTask(state: State, mission: MissionRecord): { task: LedgerTask | null; status: ReturnType extends Map ? S : never } { + const tasks = state.snapshot?.tasks ?? [] + const statuses = derive(mission, tasks) + const task = mission.tasks.find(candidate => statuses.get(candidate.id) === 'running') ?? nextTask(mission, tasks) + + return { task, status: task === null ? 'ready' : (statuses.get(task.id) ?? 'ready') } +} + +let held: { key: string; text: string } | null = null + +/** + * The section `prompt.compose` adds, or null (no mission, a finished one, or the setting off). The text is rebuilt only when its key + * changes, and the key changes only with the task: a changed system prompt makes Claude re-read the whole conversation. + */ +export function contextSection(state: State): { id: string; text: string; scope: 'session' } | null { + const mission = activeMission(state) + + if (mission === null || !contextEnabled(settingsOf(state).ai.missionContext)) return null + + const statuses = derive(mission, state.snapshot?.tasks ?? []) + + if (mission.tasks.length > 0 && mission.tasks.every(task => statuses.get(task.id) === 'done')) return null + + const { task, status } = currentTask(state, mission) + const loop = loopOf(mission) + const info = loop === null || loop.status === 'idle' ? null : { interval: loop.interval, status: loop.status } + const key = missionContextKey(mission, task, info, status) + + if (held?.key !== key) held = { key, text: missionContextText(mission, task, info, status) } + + return { id: CONTEXT_SECTION_ID, text: held.text, scope: 'session' } +} + +/** A turn ended: note it on the running task (never that the task finished: the task store says that). */ +export function onTurnComplete(state: State, host: Host, reason: TurnReason): void { + const mission = activeMission(state) + + if (mission === null) return + + const running = mission.tasks.find(task => derive(mission, state.snapshot?.tasks ?? []).get(task.id) === 'running') ?? null + const note = turnNote(reason, running) + + if (note === null) return + + record(mission, note) + saveLedger(state, host) +} + +/** A prompt was submitted: when it carries a mission's loop marker it is that loop's tick (or its first run). */ +export function onPromptSubmit(state: State, host: Host, text: string): void { + const now = Date.now() + + for (const mission of mcOf(state).missions.values()) { + if (!isTick(text, mission.id)) continue + + const prefs = settingsOf(state).ai + const before = loopOf(mission) + const loop = before !== null && before.status === 'armed' ? before : armed(before, mission, before?.interval ?? prefs.loopInterval, now) + const cost = costOf(state, mission) + const plan = tickPlan({ mission, loop, prefs, gatesConfigured: parseGates(prefs.loopGates).gates.length > 0, spendUsd: cost?.usd ?? null, capUsd: capOf(state), nowMs: now, taskStatus: derive(mission, state.snapshot?.tasks ?? []) }) + + setLoop(mission, tick(loop, now)) + record(mission, { type: 'loop.tick', note: plain(`${plan.action}: ${plan.reason}`, 200) }) + saveLedger(state, host) + host.invalidate() + } +} + +/** The actions the Loop tab calls: verify with the person's gates, and the loop manager's start, stop and re-arm. */ +export function claudeActions(state: State, host: Host, runner: Runner): Pick { + const say = (label: string, ok: boolean, detail: string) => { + mcOf(state).last = { label, ok, detail } + host.invalidate() + } + const prepare = (label: string, text: string, done: () => void): ActionSpec => ({ + label, + scope: 'controls', + args: [], + shows: `in the prompt box, for you to send: “${plain(text, 160)}”`, + expect: 'the text in Claude’s prompt box', + note: 'Claude owns the recurring schedule; the console only prepares the text and watches the ticks. Nothing is scheduled until you press Enter there.', + run: async () => { + const isFilled = await host.fillPrompt(text).catch(() => false) + + if (isFilled) done() + say(label, isFilled, isFilled ? 'prepared in the prompt box: press Enter there' : 'no prompt box to fill here') + }, + }) + + return { + verify: () => { + const mission = activeMission(state) + const gates = parseGates(settingsOf(state).ai.loopGates).gates + + if (mission === null) return say('verify', false, 'no active mission') + if (gates.length === 0) return say('verify', false, 'no gates configured: add your own commands in Settings → Mission gates') + + const { task } = currentTask(state, mission) + const taskId = task?.id + + runner.ask( + { + label: `run ${gates.length} gate${gates.length === 1 ? '' : 's'}${taskId === undefined ? '' : ` for ${taskId}`}`, + scope: 'controls', + args: [], + shows: gates.map(gate => gate.argv.join(' ')).join(' · '), + expect: 'each gate’s exit code and a short output summary recorded as evidence on the mission', + note: 'Runs the commands you configured, one after another, without a shell, in this project. Their output is evidence; nothing is changed by the console.', + run: async () => { + let failed = 0 + + for (const gate of gates) { + const result = await host.run(gate.argv, 180_000).catch(() => null) + + record(mission, evidenceEvent(gate, result === null ? { exitCode: null, stdout: '', stderr: '' } : { exitCode: result.exitCode ?? null, stdout: result.stdout, stderr: result.stderr }, taskId)) + if (result === null || result.exitCode !== 0) failed += 1 + } + + saveLedger(state, host) + say('gates', failed === 0, failed === 0 ? `all ${gates.length} passed` : `${failed} of ${gates.length} did not pass: see Evidence`) + }, + }, + 'nothing to run', + ) + }, + loop: { + start: () => { + const mission = activeMission(state) + + if (mission === null) return say('loop', false, 'no active mission') + + const prefs = settingsOf(state).ai + const interval = loopOf(mission)?.interval ?? prefs.loopInterval + + runner.ask(prepare('start the mission loop', startCommand(mission, prefs, interval), () => record(mission, { type: 'loop.prepared', note: `/loop ${interval}` })), 'no active mission') + }, + stop: () => { + const mission = activeMission(state) + const loop = mission === null ? null : loopOf(mission) + + if (mission === null || loop === null) return say('loop', false, 'no loop to stop') + + runner.ask(prepare('ask Claude to stop the mission loop', stopRequest(loop, mission), () => { + setLoop(mission, stop(loop)) + record(mission, { type: 'loop.stop-requested' }) + saveLedger(state, host) + }), 'no loop to stop') + }, + rearm: () => { + const mission = activeMission(state) + const loop = mission === null ? null : loopOf(mission) + const command = mission === null ? null : rearmCommand(loop, mission, settingsOf(state).ai, Date.now()) + + if (mission === null || command === null) return say('loop', false, 'the loop is not stopped, expired or overdue') + + runner.ask(prepare('re-arm the mission loop', command, () => record(mission, { type: 'loop.rearm-prepared' })), 'nothing to re-arm') + }, + }, + } +} diff --git a/plugins/ruflo-console/hooks/mission-context.ts b/plugins/ruflo-console/hooks/mission-context.ts new file mode 100644 index 0000000000..9fe6a78154 --- /dev/null +++ b/plugins/ruflo-console/hooks/mission-context.ts @@ -0,0 +1,91 @@ +/** + * Mission context (ADR-443): the one short section Claude's system prompt carries while a mission is active, so Claude knows + * the mission between hand-offs. Pure text in, text out. The section only holds the mission's own fields, each capped, with + * control characters stripped. Its key changes only when something Claude must act on changes (mission, active task, that + * task's status, paused, cancelled, loop on or off): a changed system prompt makes Claude re-read the conversation at + * cache-write price, so event counts, timestamps and spend never reach the key. + */ +import { plain } from './data/parse' +import type { Derived, LedgerTask, MissionRecord } from './mission-types' + +export const CONTEXT_SECTION_ID = 'ruflo-console:mission' +export const CONTEXT_MAX = 1200 +/** The settings key the row stores under, beside the other AI preferences. */ +export const CONTEXT_PREF_KEY = 'missionContext' + +const EVIDENCE_RULE = 'A task is done only with evidence: record it with task_complete and put what you ran and what it printed in the result.' +const STOP_RULE = 'Stop when every task is done or the person says stop; if blocked, mark the task failed with the reason instead of guessing.' +const HALTED = 'Do not start new work.' +const MAX_CHECKS = 3 + +type LoopInfo = { interval: string; status: string } | null + +/** Where a task stands, from the ruflo task store (derive() in mission-control.ts needs the store, so the caller passes the result). */ +export type TaskStatus = Derived + +const clip = (value: unknown, max: number): string => plain(value, max) + +function halted(mission: MissionRecord): string | null { + return mission.cancelled ? 'cancelled' : mission.paused ? 'paused' : null +} + +/** The section's text: deterministic, at most CONTEXT_MAX characters. `status` is the active task's derived status. */ +export function missionContextText(mission: MissionRecord, task: LedgerTask | null, loop: LoopInfo, status: TaskStatus = 'ready'): string { + const lines: string[] = [`Mission ${clip(mission.id, 40)}: ${clip(mission.objective, 200)}`] + const stop = halted(mission) + + if (task !== null) { + lines.push(`Active task ${clip(task.id, 20)} (${status}): ${clip(task.title, 80)}. Done when: ${clip(task.requirement, 120)}`) + + const checks = mission.acceptance.slice(0, MAX_CHECKS).map(item => `- ${clip(item.check, 80)}`) + + if (checks.length > 0) lines.push(`Acceptance checks:\n${checks.join('\n')}`) + } + + if (loop !== null) lines.push(`Loop: ${clip(loop.interval, 12)}, ${clip(loop.status, 12)}.`) + + lines.push(EVIDENCE_RULE, STOP_RULE) + if (stop !== null) lines.push(`The mission is ${stop}. ${HALTED}`) + + const text = lines.join('\n') + + return text.length <= CONTEXT_MAX ? text : `${text.slice(0, CONTEXT_MAX - 1)}…` +} + +/** What the section depends on, nothing else: the same key means Claude's prompt is byte-identical, so its cache holds. */ +export function missionContextKey(mission: MissionRecord, task: LedgerTask | null, loop: LoopInfo, status: TaskStatus = 'ready'): string { + return [mission.id, task === null ? '-' : `${task.id}:${status}`, mission.paused ? 'paused' : 'live', mission.cancelled ? 'cancelled' : 'open', loop === null ? 'noloop' : 'loop'].join('|') +} + +/** Only the exact value 'off' (or false) turns the section off; anything else, including no value at all, leaves it on. */ +export const contextEnabled = (value: unknown): boolean => value !== 'off' && value !== false + +type ContextPrefs = { [CONTEXT_PREF_KEY]?: boolean } + +/** The Settings row, shaped like the entries of LOOP_ROWS (settings.ts); the integrator appends it to that list. */ +export const CONTEXT_ROW: { id: string; title: string; description: string; extra: string; options: readonly string[]; current: (p: ContextPrefs) => string; isChanged: (p: ContextPrefs) => boolean; patch: (value: string) => ContextPrefs } = { + id: 'ctx-mission', + title: 'Mission context in Claude’s prompt', + description: 'while a mission is active, Claude’s prompt carries its objective, the active task, the evidence rule and the stop rule; it changes only when the task or mission state does (default on)', + extra: 'mission context prompt claude system section cache', + options: ['on', 'off'], + current: p => (contextEnabled(p[CONTEXT_PREF_KEY]) ? 'on' : 'off'), + isChanged: p => !contextEnabled(p[CONTEXT_PREF_KEY]), + patch: value => ({ [CONTEXT_PREF_KEY]: value !== 'off' }), +} + +export type TurnReason = 'answer' | 'aborted' | 'refusal' | 'error' + +const TURN_NOTE: Record = { + answer: 'Claude finished a turn on this task; completion is recorded by task_complete, not by this note.', + aborted: 'A turn on this task was aborted before it finished.', + refusal: 'Claude declined a turn on this task.', + error: 'A turn on this task ended in an error.', +} + +/** The ledger event a finished turn leaves: null with no active task; it never says the task is finished. */ +export function turnNote(reason: TurnReason, task: LedgerTask | null): { type: string; taskId?: string; note: string } | null { + if (task === null) return null + + return { type: 'turn', taskId: clip(task.id, 20), note: TURN_NOTE[reason] ?? TURN_NOTE.error } +} diff --git a/plugins/ruflo-console/hooks/mission-control.ts b/plugins/ruflo-console/hooks/mission-control.ts index ab2665d07b..0ef8e91265 100644 --- a/plugins/ruflo-console/hooks/mission-control.ts +++ b/plugins/ruflo-console/hooks/mission-control.ts @@ -9,6 +9,7 @@ */ import type { ActionSpec } from './actions' import { PHASE_NAME, plan as planOf, stageOf, type Plan, type Profile, profileOf, type Rigor, toMissionPlan } from './goap' +import { isCapReached } from './mission-guard' import type { Host } from './host' import { plain, type TaskRecord } from './data/parse' import { isAvailable, MISSION_SKILLS, slashOf, GOALS_PLUGIN } from './mission-skills' @@ -374,6 +375,16 @@ export function advance(state: State, host: Host): void { if (mission === null || !mission.auto || state.turnActive) return + // The spend cap (ADR-443): a reading at or past the person's cap pauses the mission instead of handing out the next task. + if (isCapReached(state, mission)) { + mission.paused = true + record(mission, { type: 'cap.reached', note: 'spend cap reached: auto-run paused' }) + saveLedger(state, host) + host.invalidate() + + return + } + const task = nextTask(mission, state.snapshot?.tasks ?? []) if (task === null || isInflight(task)) return diff --git a/plugins/ruflo-console/hooks/mission-guard.ts b/plugins/ruflo-console/hooks/mission-guard.ts new file mode 100644 index 0000000000..c6f8471132 --- /dev/null +++ b/plugins/ruflo-console/hooks/mission-guard.ts @@ -0,0 +1,30 @@ +/** + * Auto-run's spend guard (ADR-443): a leaf module, so `advance()` in mission-control.ts can ask it without a cycle. The spend is the + * cost ledger's reading for the mission's window and project (the `mission-cost` probe), a list-price estimate; the cap is the person's + * own Settings value. No cap, no reading, or a reading for another mission means no pause: a missing number is never a reason to stop. + */ +import { capState, shouldPause, type MissionCost } from './data/mission-cost' +import { live } from './views/common' +import { settingsOf } from './settings' +import type { MissionRecord } from './mission-types' +import type { State } from './state' + +/** The mission's cost reading, only while it is the one the probe was asked about (its window starts when the mission did). */ +export function costOf(state: State, mission: MissionRecord): MissionCost | null { + const cost = live(state.probes.get('mission-cost')) + + return cost !== null && cost.fromMs === mission.createdAtMs ? cost : null +} + +export const capOf = (state: State): number | null => { + const text = settingsOf(state).ai.missionCapUsd + + return text === '' ? null : Number(text) +} + +/** True when auto-run should stop handing out tasks because this mission's spend reached its cap. */ +export function isCapReached(state: State, mission: MissionRecord): boolean { + const cost = costOf(state, mission) + + return cost !== null && shouldPause(capState(cost.usd, capOf(state)), mission.auto) +} diff --git a/plugins/ruflo-console/hooks/mission-loop.ts b/plugins/ruflo-console/hooks/mission-loop.ts new file mode 100644 index 0000000000..82619c7e2e --- /dev/null +++ b/plugins/ruflo-console/hooks/mission-loop.ts @@ -0,0 +1,234 @@ +/** + * The loop manager (ADR-443 §2.4): prepares, tracks and re-arms the `/loop` of a long-running mission. Pure: state in, state or text out. + * The console never schedules anything. Claude owns the recurring task (and `CronDelete`); the console builds the `/loop` line, counts the + * ticks that arrive carrying the mission's marker, and says when the loop is overdue, about to expire or gone. + */ +import { plain } from './data/parse' +import { DEFAULT_LOOP, type LoopPrefs } from './goap' +import type { Derived, MissionRecord } from './mission-types' + +export type LoopStatus = 'idle' | 'armed' | 'stopped' | 'expired' | 'done' +export type LoopState = { missionId: string; interval: string; startedAtMs: number; expiresAtMs: number; ticks: number; lastTickMs: number | null; status: LoopStatus } +export type LoopLevel = 'ok' | 'warn' | 'bad' +export type LoopReport = { text: string; level: LoopLevel; nextTickMs: number | null; msToExpiry: number; isOverdue: boolean; isExpiring: boolean } +export type TickAction = 'run-next' | 'run-gates' | 'wait' | 'stop' | 'rearm' + +/** A recurring `/loop` task expires after 7 days. */ +export const LOOP_LIFETIME_MS = 7 * 24 * 3600 * 1000 +/** The warning window before expiry. */ +export const EXPIRY_WARN_MS = 24 * 3600 * 1000 +/** The event type the integrator records when the gates ran, so a tick does not run them twice in a row. */ +export const GATE_EVENT = 'gate.run' + +const MIN_INTERVAL_MS = 60_000 +const MAX_INTERVAL_MS = 24 * 3600 * 1000 +const MAX_TICKS = 1_000_000 +const STATUSES: readonly LoopStatus[] = ['idle', 'armed', 'stopped', 'expired', 'done'] +const SAFE_ID = /[^A-Za-z0-9._:@-]/g +const INTERVAL = /^(\d{1,4})([smhd])$/ +const MARKER = /\[mission:([A-Za-z0-9._:@-]{1,128}) loop\]/ +const UNIT_MS: Record = { s: 1000, m: 60_000, h: 3_600_000, d: 86_400_000 } + +const idOf = (value: unknown): string => (typeof value === 'string' ? value.replace(SAFE_ID, '').slice(0, 128) : '') +const msOf = (value: unknown): number | null => (typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : null) + +/** An interval such as `5m` in milliseconds, or null when it is not ``. */ +export function intervalMs(interval: unknown): number | null { + const match = typeof interval === 'string' ? INTERVAL.exec(interval) : null + + return match === null ? null : Number(match[1]) * (UNIT_MS[match[2] as string] as number) +} + +/** The interval as the loop will use it: the person's value when it is well formed, else the default; never below 1m, never above 1d. */ +export function normalizeInterval(interval: unknown, fallback: string = DEFAULT_LOOP.loopInterval): string { + const ms = intervalMs(interval) + + if (ms === null) return intervalMs(fallback) === null ? DEFAULT_LOOP.loopInterval : normalizeInterval(fallback, DEFAULT_LOOP.loopInterval) + if (ms < MIN_INTERVAL_MS) return '1m' + if (ms > MAX_INTERVAL_MS) return '1d' + + return interval as string +} + +/** The marker a tick of this mission's loop carries. */ +export const loopMarker = (missionId: string): string => `[mission:${idOf(missionId)} loop]` + +/** The recurring prompt: the marker, then the per-tick checklist of ADR-441. Push and publish are named only when the settings allow them. */ +export function loopPrompt(mission: MissionRecord, prefs: LoopPrefs): string { + const commit = prefs.loopCommit ? 'commit to the mission branch only' : 'make no commits, leave changes in the worktree' + const push = prefs.loopPush ? 'the mission branch may be pushed to its remote' : 'do not push' + const publish = prefs.loopPublish ? 'releases or packages the mission names may be published' : 'do not publish, release or deploy' + const parts = [ + `${loopMarker(mission.id)} Mission ${idOf(mission.id)}: ${plain(mission.objective, 200)}.`, + 'Each tick: 1 check progress against the plan; 2 fix what failed; 3 run the gates and read their real output; 4 repeat until every acceptance check passes and every gate is green on the same clean commit, then stop the loop and report.', + 'Stop and ask only when a gate fails the same way three ticks running or an action would leave the branch.', + `${commit}; ${push}; ${publish}.`, + ] + + return plain(parts.join(' '), 1000) +} + +/** The line that starts the loop: `/loop `, the interval well formed and never below 1m. */ +export const startCommand = (mission: MissionRecord, prefs: LoopPrefs, interval: string): string => `/loop ${normalizeInterval(interval, prefs.loopInterval)} ${loopPrompt(mission, prefs)}` + +/** True only when the first marker in the text is this mission's: another mission's marker, or this one quoted later in a longer message, is not a tick. */ +export function isTick(promptText: string, missionId: string): boolean { + const id = idOf(missionId) + + if (id === '' || typeof promptText !== 'string') return false + + return MARKER.exec(promptText.slice(0, 2000))?.[1] === id +} + +const fresh = (missionId: string, interval: string, nowMs: number): LoopState => ({ missionId, interval, startedAtMs: nowMs, expiresAtMs: nowMs + LOOP_LIFETIME_MS, ticks: 0, lastTickMs: null, status: 'armed' }) + +/** The loop armed for this mission: a fresh lifetime and tick count, unless this very loop is already armed and has not expired. */ +export function armed(state0: LoopState | null, mission: MissionRecord, interval: string, nowMs: number): LoopState { + const missionId = idOf(mission.id) + const every = normalizeInterval(interval) + + if (state0 !== null && state0.missionId === missionId && state0.status === 'armed' && state0.interval === every && nowMs < state0.expiresAtMs) return state0 + + return fresh(missionId, every, nowMs) +} + +/** A tick arrived: counted while the loop is armed and inside its lifetime; past it the loop is expired and nothing is counted. */ +export function tick(state: LoopState, nowMs: number): LoopState { + if (state.status !== 'armed') return state + if (nowMs >= state.expiresAtMs) return { ...state, status: 'expired' } + + return { ...state, ticks: Math.min(MAX_TICKS, state.ticks + 1), lastTickMs: nowMs } +} + +/** The person asked to stop: an idle or armed loop is stopped; expired and done stay as they are. */ +export const stop = (state: LoopState): LoopState => (state.status === 'armed' || state.status === 'idle' ? { ...state, status: 'stopped' } : state) + +const IDLE: LoopReport = { text: 'no loop', level: 'ok', nextTickMs: null, msToExpiry: 0, isOverdue: false, isExpiring: false } + +/** A duration as a short phrase: `45s`, `4m`, `3h 10m`, `2d 4h`. */ +export function span(ms: number): string { + const s = Math.max(0, Math.floor(ms / 1000)) + + if (s < 60) return `${s}s` + if (s < 3600) return `${Math.floor(s / 60)}m` + if (s < 86_400) return `${Math.floor(s / 3600)}h ${Math.floor((s % 3600) / 60)}m` + + return `${Math.floor(s / 86_400)}d ${Math.floor((s % 86_400) / 3600)}h` +} + +/** Where the loop stands at `nowMs`. Total: a missing or malformed state reads as no loop. */ +export function status(state: LoopState | null, nowMs: number): LoopReport { + const every = state === null ? null : intervalMs(state.interval) + + if (state === null || typeof state !== 'object' || !Number.isFinite(nowMs) || every === null || msOf(state.startedAtMs) === null || msOf(state.expiresAtMs) === null) return IDLE + + const msToExpiry = Math.max(0, state.expiresAtMs - nowMs) + const ticks = `${state.ticks} tick${state.ticks === 1 ? '' : 's'}` + + if (state.status === 'expired' || (state.status === 'armed' && msToExpiry === 0)) return { text: `expired after ${ticks}: the 7-day task is gone`, level: 'bad', nextTickMs: null, msToExpiry: 0, isOverdue: false, isExpiring: false } + if (state.status === 'stopped') return { text: `stopped after ${ticks}`, level: 'warn', nextTickMs: null, msToExpiry, isOverdue: false, isExpiring: false } + if (state.status === 'done') return { text: `done after ${ticks}`, level: 'ok', nextTickMs: null, msToExpiry, isOverdue: false, isExpiring: false } + if (state.status === 'idle') return { text: 'not started', level: 'ok', nextTickMs: null, msToExpiry, isOverdue: false, isExpiring: false } + + const base = Math.max(state.startedAtMs, state.lastTickMs ?? 0) + const nextTickMs = base + every + const isOverdue = nowMs - base > 3 * every + const isExpiring = msToExpiry <= EXPIRY_WARN_MS + const next = nextTickMs <= nowMs ? 'due now' : `next in ${span(nextTickMs - nowMs)}` + const text = isOverdue ? `armed but overdue: no tick for ${span(nowMs - base)} (${ticks})` : `armed · ${ticks} · ${next}` + + return { text, level: isOverdue ? 'bad' : isExpiring ? 'warn' : 'ok', nextTickMs, msToExpiry, isOverdue, isExpiring } +} + +/** Text for Claude to cancel the recurring task. Only Claude owns the schedule (CronList, CronDelete), so the console can only ask. */ +export const stopRequest = (state: LoopState | null, mission: MissionRecord): string => + [ + `Please stop the recurring loop for mission ${idOf(mission.id)}.`, + `The console cannot cancel it: only you own the schedule. List your scheduled tasks (CronList) and delete (CronDelete) the one whose prompt starts with ${loopMarker(mission.id)}${state === null ? '' : ` (every ${normalizeInterval(state.interval)}, ${state.ticks} ticks so far)`}.`, + 'Change nothing else, then confirm that no task with that marker is left.', + ].join(' ') + +/** The `/loop` line to arm again with the same prompt, or null while the loop is armed and healthy. Overdue needs the clock, so pass `nowMs`. */ +export function rearmCommand(state: LoopState | null, mission: MissionRecord, prefs: LoopPrefs, nowMs?: number): string | null { + if (state === null || state.missionId !== idOf(mission.id)) return null + + const gone = state.status === 'expired' || state.status === 'stopped' || (nowMs !== undefined && status(state, nowMs).level === 'bad' && state.status === 'armed') + + return gone ? startCommand(mission, prefs, state.interval) : null +} + +export const serializeLoop = (state: LoopState): unknown => ({ ...state }) + +/** A loop read back from storage, or null when anything is off: the id, interval, times, tick count or status. */ +export function parseLoop(value: unknown): LoopState | null { + if (value === null || typeof value !== 'object' || Array.isArray(value)) return null + + const v = value as Record + const missionId = idOf(v.missionId) + const startedAtMs = msOf(v.startedAtMs) + const expiresAtMs = msOf(v.expiresAtMs) + const lastTickMs = v.lastTickMs === null ? null : msOf(v.lastTickMs) + + if (missionId === '' || missionId !== v.missionId || startedAtMs === null || expiresAtMs === null || expiresAtMs < startedAtMs) return null + if (intervalMs(v.interval) === null || typeof v.interval !== 'string' || normalizeInterval(v.interval) !== v.interval) return null + if (v.lastTickMs !== null && lastTickMs === null) return null + if (typeof v.ticks !== 'number' || !Number.isInteger(v.ticks) || v.ticks < 0 || v.ticks > MAX_TICKS) return null + if (typeof v.status !== 'string' || !STATUSES.includes(v.status as LoopStatus)) return null + + return { missionId, interval: v.interval, startedAtMs, expiresAtMs, ticks: v.ticks, lastTickMs, status: v.status as LoopStatus } +} + +export type TickInput = { + mission: MissionRecord + loop: LoopState + prefs: LoopPrefs + gatesConfigured: boolean + spendUsd: number | null + capUsd: number | null + nowMs: number + /** Each task's status from the ruflo task store (`derive`); without it the ledger events decide. */ + taskStatus?: ReadonlyMap +} + +/** Task statuses from the ledger alone: the latest event of a task decides, a dispatch without a later result is running. */ +function statusFromEvents(mission: MissionRecord): Map { + const out = new Map() + + for (const task of mission.tasks) { + const last = mission.events.filter(event => event.taskId === task.id).sort((a, b) => a.seq - b.seq).at(-1) + const s = last?.status + const done = (id: string) => out.get(id) === 'done' + + out.set(task.id, s === 'completed' || s === 'done' ? 'done' : s === 'failed' ? 'failed' : s === 'cancelled' ? 'cancelled' : s === 'in_progress' || s === 'running' ? 'running' : task.dependsOn.every(done) ? 'ready' : 'waiting') + } + + return out +} + +/** + * What a tick should do. Call it before `tick()` counts the arrival, so the interval is measured from the previous tick. Stop wins over + * everything (cancelled, all tasks done, the spend cap reached, or a loop that was stopped); then wait while paused; rearm when the loop + * has expired; wait while a task runs or the interval (less 10% for clock jitter) has not passed; then gates after a finished task, else the next task. + */ +export function tickPlan(input: TickInput): { action: TickAction; reason: string } { + const { mission, loop, gatesConfigured, spendUsd, capUsd, nowMs } = input + const states = input.taskStatus ?? statusFromEvents(mission) + const values = mission.tasks.map(task => states.get(task.id) ?? 'waiting') + const every = intervalMs(loop.interval) ?? (intervalMs(DEFAULT_LOOP.loopInterval) as number) + + if (mission.cancelled) return { action: 'stop', reason: 'the mission is cancelled' } + if (mission.tasks.length > 0 && values.every(value => value === 'done')) return { action: 'stop', reason: 'every task is done: report and stop the loop' } + if (spendUsd !== null && capUsd !== null && capUsd > 0 && spendUsd >= capUsd) return { action: 'stop', reason: `spend $${spendUsd.toFixed(2)} reached the cap $${capUsd.toFixed(2)}` } + if (loop.status === 'stopped' || loop.status === 'done') return { action: 'stop', reason: `the loop was ${loop.status}: cancel its recurring task` } + if (mission.paused) return { action: 'wait', reason: 'the mission is paused' } + if (loop.status === 'expired' || nowMs >= loop.expiresAtMs) return { action: 'rearm', reason: 'the 7-day loop task has expired' } + if (values.includes('running')) return { action: 'wait', reason: 'a task is still running' } + if (loop.lastTickMs !== null && nowMs - loop.lastTickMs < every * 0.9) return { action: 'wait', reason: `the ${loop.interval} interval has not elapsed` } + + const lastEvent = mission.events.reduce<{ seq: number; type: string } | null>((best, event) => (best === null || event.seq > best.seq ? event : best), null) + const gatesRanSince = lastEvent?.type === GATE_EVENT + + if (gatesConfigured && values.includes('done') && !gatesRanSince) return { action: 'run-gates', reason: 'the previous task finished: run the gates' } + + return { action: 'run-next', reason: 'hand over the next ready task' } +} diff --git a/plugins/ruflo-console/hooks/mission-types.ts b/plugins/ruflo-console/hooks/mission-types.ts index 37f5751824..82858e33c8 100644 --- a/plugins/ruflo-console/hooks/mission-types.ts +++ b/plugins/ruflo-console/hooks/mission-types.ts @@ -2,6 +2,7 @@ import type { Guidance } from './mission-guidance' import type { Screen } from './mission-options' import type { Plan, Profile, Rigor } from './goap' +import type { LoopActions } from './views/mission-loop' export type LedgerTask = { id: string; title: string; phase: string; stage?: string; agent: string; requirement: string; dependsOn: string[]; rufloTaskId?: string; dispatchedAtMs?: number } export type LedgerEvent = { seq: number; atMs: number; type: string; taskId?: string; status?: string; evidenceRef?: string; note?: string } @@ -18,8 +19,10 @@ export type MissionRecord = { cancelled: boolean auto: boolean createdAtMs: number + /** The mission's loop manager state (ADR-443), validated by parseLoop where it is read. */ + loop?: unknown } -export type McTab = 'plan' | 'tasks' | 'agents' | 'evidence' | 'record' +export type McTab = 'plan' | 'tasks' | 'agents' | 'evidence' | 'record' | 'loop' export type Derived = 'done' | 'running' | 'ready' | 'waiting' | 'failed' | 'cancelled' export type McState = { @@ -68,4 +71,8 @@ export type MissionActions = { capability: (slash: string) => void /** Turns the AIDefence screen of mission text on or off. */ screen: (on: boolean) => void + /** Runs the person's own gate commands on the active mission (asks first) and records each exit code as evidence. */ + verify: () => void + /** The loop manager (ADR-443): prepares the /loop text, a stop request or a re-arm in the prompt box. */ + loop: LoopActions } diff --git a/plugins/ruflo-console/hooks/mission-verify.ts b/plugins/ruflo-console/hooks/mission-verify.ts new file mode 100644 index 0000000000..a5a85d225b --- /dev/null +++ b/plugins/ruflo-console/hooks/mission-verify.ts @@ -0,0 +1,165 @@ +/** + * Verify (ADR-443 §2.2): a task is done with evidence. Gates are the person's own commands, kept as a fixed argv (no shell, no quoting); + * running one asks first, and its exit code and a short output summary are recorded as an `evidence.gate` event. The verdict is read + * back from those events only. Pure: data in, data out. + */ +import type { ActionSpec } from './actions' +import { plain } from './data/parse' +import type { MissionRecord } from './mission-types' + +export type Gate = { id: string; label: string; argv: readonly string[] } +export type GateResult = { exitCode: number | null; stdout: string; stderr: string } +export type GateEvent = { type: 'evidence.gate'; taskId?: string; status: 'passed' | 'failed' | 'unknown'; note: string; evidenceRef: string } +export type Verdict = { state: 'verified' | 'failed' | 'unverified' | 'no-gates'; passed: number; failed: number; detail: string } + +export const MAX_GATES = 4 +export const MAX_GATE_CHARS = 200 + +const SHELL_SYNTAX = /[;|&<>`]|\$\(/ +const CONTROL = /[\u0000-\u001f\u007f-\u009f]/ +/** A setting value is one line, so a literal backslash-n also separates lines. */ +const LINE_BREAK = /\r?\n|\\n/ + +/** A short stable id from the argv (FNV-1a, base 36): the same command is the same gate across restarts. */ +function gateId(argv: readonly string[]): string { + let hash = 0x811c9dc5 + + for (const char of argv.join('\u0000')) { + hash = Math.imul(hash ^ char.codePointAt(0)!, 0x01000193) >>> 0 + } + + return `g${hash.toString(36)}` +} + +/** Why a line cannot be a gate, or null when it can. */ +function refusal(line: string): string | null { + if (line.length > MAX_GATE_CHARS) return `longer than ${MAX_GATE_CHARS} characters` + if (CONTROL.test(line)) return 'contains a control character' + if (SHELL_SYNTAX.test(line)) return 'contains shell syntax (; | & > < ` $( ): a gate is a command and its words, run without a shell' + if (line.includes(' ')) return 'has two spaces in a row: words are split on single spaces' + if (line.startsWith('-')) return 'starts with “-”: the first word must be the program' + + return null +} + +/** The setting text as gates: up to 4 lines, one command each, split on single spaces. Refused lines are reported with why, never run. */ +export function parseGates(text: unknown): { gates: Gate[]; rejected: { line: string; why: string }[] } { + const gates: Gate[] = [] + const rejected: { line: string; why: string }[] = [] + + if (typeof text !== 'string') return { gates, rejected } + + for (const raw of text.split(LINE_BREAK)) { + const line = raw.replace(/^ +| +$/g, '') + + if (line === '') continue + + const shown = plain(line, 80) + const why = refusal(line) + + if (why !== null) { + rejected.push({ line: shown, why }) + continue + } + + const argv = line.split(' ') + const id = gateId(argv) + + if (gates.some(gate => gate.id === id)) rejected.push({ line: shown, why: 'the same command is already a gate' }) + else if (gates.length >= MAX_GATES) rejected.push({ line: shown, why: `only the first ${MAX_GATES} gates are kept` }) + else gates.push({ id, label: plain(line, 80), argv }) + } + + return { gates, rejected } +} + +/** + * The confirm-gated run of one gate. `baseSpec` carries the runner plumbing (`run`, `scope`, `timeoutMs`); it can never change the + * argv, the label or the read-only flag: a gate is the person's own command and always asks first. + */ +export function gateSpec(gate: Gate, baseSpec: Partial = {}): ActionSpec { + return { + scope: 'controls', + note: 'Runs your own command in this project’s directory, without a shell. What it does (files, network, time) is up to the command; its exit code and a short output summary are recorded as evidence on the mission.', + ...baseSpec, + label: `run gate: ${gate.label}`, + args: [], + argv: [...gate.argv], + shows: gate.argv.join(' '), + expect: 'its exit code and output summary are recorded as evidence on the task', + isReadOnly: false, + } +} + +const linesOf = (text: string): string[] => text.split(/\r?\n/).filter(line => line.trim() !== '') +const refOf = (value: string): string => value.replace(/[^A-Za-z0-9_-]/g, '') || 'gate' + +/** What a finished gate run is recorded as: pass on exit 0, fail on any other exit, unknown when there was no exit code. */ +export function evidenceEvent(gate: Gate, result: GateResult, taskId?: string): GateEvent { + const code = typeof result.exitCode === 'number' && Number.isInteger(result.exitCode) ? result.exitCode : null + const lines = [...linesOf(String(result.stdout ?? '')), ...linesOf(String(result.stderr ?? ''))] + const first = plain(linesOf(String(result.stdout ?? ''))[0] ?? linesOf(String(result.stderr ?? ''))[0] ?? '', 120) + const size = lines.length === 0 ? 'no output' : `${lines.length} ${lines.length === 1 ? 'line' : 'lines'} of output` + const head = code === null ? 'no exit code (it did not finish)' : `exit ${code}` + + return { + type: 'evidence.gate', + ...(taskId !== undefined && { taskId }), + status: code === null ? 'unknown' : code === 0 ? 'passed' : 'failed', + note: `${head}, ${size}${first === '' ? '' : `: ${first}`}`, + evidenceRef: `gate:${refOf(gate.id)}:${code === null ? 'none' : code}`, + } +} + +const GATE_OF_REF = /^gate:([^:]+):/ + +/** + * Read from `evidence.gate` events for the task, since its latest `task.dispatched` (a new start wipes older evidence). Order rule: + * each gate counts by its NEWEST result (highest seq), so a pass newer than that gate's failures clears it, and a failure newer than + * its pass fails it again. Verified = at least one gate and every gate's newest result is a pass. Any failed gate = failed. Anything + * else (unknown exit, or a configured gate that has not run) = unverified. `gates`, when given, is the configured list: with none the + * answer is 'no-gates', and only evidence from those gates counts. Without it, no gate evidence at all reads 'no-gates'. + */ +export function verdictOf(mission: MissionRecord, taskId: string, gates?: readonly Gate[]): Verdict { + if (gates !== undefined && gates.length === 0) return { state: 'no-gates', passed: 0, failed: 0, detail: 'no gates are set: nothing was checked' } + + const mine = mission.events.filter(event => event.taskId === taskId) + const start = mine.reduce((latest, event) => (event.type === 'task.dispatched' && event.seq > latest ? event.seq : latest), -1) + const newest = new Map() + + for (const event of mine) { + if (event.type !== 'evidence.gate' || event.seq <= start) continue + + const key = GATE_OF_REF.exec(event.evidenceRef ?? '')?.[1] ?? '?' + const seen = newest.get(key) + + if (seen === undefined || event.seq >= seen.seq) newest.set(key, { seq: event.seq, status: event.status ?? 'unknown' }) + } + + const counted = gates === undefined ? [...newest.entries()] : gates.map((gate): [string, { seq: number; status: string } | undefined] => [gate.id, newest.get(gate.id)]) + + if (counted.length === 0) return { state: 'no-gates', passed: 0, failed: 0, detail: 'no gate has run for this task' } + + const passed = counted.filter(([, seen]) => seen?.status === 'passed').length + const failed = counted.filter(([, seen]) => seen?.status === 'failed').length + const open = counted.length - passed - failed + + if (failed > 0) return { state: 'failed', passed, failed, detail: `${failed} of ${counted.length} gates failed on their latest run` } + if (open === 0) return { state: 'verified', passed, failed, detail: `${passed} of ${counted.length} gates passed on their latest run` } + + return { state: 'unverified', passed, failed, detail: `${passed} of ${counted.length} gates passed; ${open} ${open === 1 ? 'has' : 'have'} not run or gave no exit code` } +} + +/** The Settings row for the gates: free text (up to 4 lines), shaped like LOOP_ROWS; its value lives beside the loop preferences as `loopGates`. */ +export const GATES_ROW = { + id: 'loop-gates', + kind: 'text', + title: 'Mission gates', + description: 'your own check commands, up to 4 lines (one per line, or separated by \\n), each a program and its words, such as “npm test”; run without a shell, so no ; | & > < ` $( and no leading “-”. Each run asks first. None set: a task cannot be verified', + extra: 'loop gates verify test lint build check command evidence', + options: [] as readonly string[], + maxLength: MAX_GATES * (MAX_GATE_CHARS + 1), + current: (p: { loopGates?: string }): string => p.loopGates ?? '', + isChanged: (p: { loopGates?: string }): boolean => (p.loopGates ?? '') !== '', + patch: (value: string): { loopGates: string } => ({ loopGates: value.replace(/[\u0000-\u0009\u000b-\u001f\u007f-\u009f]/g, ' ').slice(0, MAX_GATES * (MAX_GATE_CHARS + 1)).trim() }), +} as const diff --git a/plugins/ruflo-console/hooks/register.ts b/plugins/ruflo-console/hooks/register.ts index 3edb669975..1249fac0f3 100644 --- a/plugins/ruflo-console/hooks/register.ts +++ b/plugins/ruflo-console/hooks/register.ts @@ -15,6 +15,7 @@ import { buildOf, isOurCheckout, setBuild } from './build' import { runUpdateCheck } from './update-flow' import { announceModelTools, parseControlEnv, serveModelTools } from './model-tools' import { loadAiPrefs, settingsOf } from './settings' +import { contextSection, onPromptSubmit, onTurnComplete } from './mission-claude' import { parseMode, RECHECK_EVERY_MS, UPDATES_KEY } from './updates' import { selfCheckResults } from './self-check' import type { Kit } from './views/common' @@ -351,6 +352,34 @@ export const register: Register = (on, raw: PluginOptions) => { on('turn.complete', ($, e, next) => { if (e.agentId === undefined) control?.markFrame('', false) + if (e.agentId === undefined && host !== null) { + try { + onTurnComplete(state, host, e.reason) + } catch { + // A note that could not be recorded never changes the turn. + } + } + + return next(e) + }) + + // The mission Claude is working on rides in the system prompt (ADR-443); the text changes only when the task does. + on('prompt.compose', async ($, e, next) => { + const result = await next(e) + const section = contextSection(state) + + return section === null ? result : { sections: [...result.sections, section] } + }) + + // A prompt carrying a mission's loop marker is that loop's tick. + on('prompt.submit', ($, e, next) => { + if (host !== null) { + try { + onPromptSubmit(state, host, e.text) + } catch { + // Counting a tick never blocks the prompt. + } + } return next(e) }) diff --git a/plugins/ruflo-console/hooks/settings.ts b/plugins/ruflo-console/hooks/settings.ts index 8897a97d36..5006d8ad9b 100644 --- a/plugins/ruflo-console/hooks/settings.ts +++ b/plugins/ruflo-console/hooks/settings.ts @@ -45,8 +45,8 @@ export const CORE: readonly CoreKey[] = [ export const CLAUDE_MODELS = ['default', 'haiku', 'sonnet', 'opus'] as const export const AI_BUDGETS = [0.25, 0.5, 1, 2] as const /** `autoAccept`: claude, codex and swarm turns go straight out with no confirm (they stay read-only, in plan mode, under the budget); ruflo commands still ask. */ -export type AiPrefs = { claudeModel: (typeof CLAUDE_MODELS)[number]; budgetUsd: (typeof AI_BUDGETS)[number]; autoAccept: boolean; /** Claude writes guidance after a mission goal is entered. */ guidance: boolean; /** ADR-444: how far Claude may drive the console with its console_* tools (they exist only when not off). */ modelControl: 'off' | 'read' | 'write' | 'manage' | 'full'; /** ADR-444: a non-read action waits for the person's Yes (ask) or confirms itself (auto). */ modelConfirm: 'ask' | 'auto' } & LoopPrefs -export const DEFAULT_AI: AiPrefs = { claudeModel: 'default', budgetUsd: 1, autoAccept: false, guidance: true, modelControl: 'off', modelConfirm: 'ask', ...DEFAULT_LOOP } +export type AiPrefs = { claudeModel: (typeof CLAUDE_MODELS)[number]; budgetUsd: (typeof AI_BUDGETS)[number]; autoAccept: boolean; /** Claude writes guidance after a mission goal is entered. */ guidance: boolean; /** ADR-443: the active mission and task ride in Claude's prompt (changes only when the task changes). */ missionContext: boolean; /** ADR-443: the person's own gate commands, one per line or `\n`-separated (parseGates validates). */ loopGates: string; /** ADR-443: a USD cap for one mission's spend ('' none). */ missionCapUsd: string; /** ADR-444: how far Claude may drive the console with its console_* tools (they exist only when not off). */ modelControl: 'off' | 'read' | 'write' | 'manage' | 'full'; /** ADR-444: a non-read action waits for the person's Yes (ask) or confirms itself (auto). */ modelConfirm: 'ask' | 'auto' } & LoopPrefs +export const DEFAULT_AI: AiPrefs = { claudeModel: 'default', budgetUsd: 1, autoAccept: false, guidance: true, missionContext: true, loopGates: '', missionCapUsd: '', modelControl: 'off', modelConfirm: 'ask', ...DEFAULT_LOOP } const ON_OFF = ['on', 'off'] as const const onOff = (value: boolean) => (value ? 'on' : 'off') @@ -284,6 +284,9 @@ export async function loadAiPrefs(state: State, host: Host): Promise { guidance: stored?.guidance !== false, modelControl: (['read', 'write', 'manage', 'full'] as const).find(item => item === stored?.modelControl) ?? 'off', modelConfirm: stored?.modelConfirm === 'auto' ? 'auto' : 'ask', + missionContext: stored?.missionContext !== false, + loopGates: typeof stored?.loopGates === 'string' ? stored.loopGates.slice(0, 800) : '', + missionCapUsd: typeof stored?.missionCapUsd === 'string' && /^\d{1,5}(\.\d{1,2})?$/.test(stored.missionCapUsd) ? stored.missionCapUsd : '', loopInterval: LOOP_INTERVALS.find(item => item === stored?.loopInterval) ?? DEFAULT_LOOP.loopInterval, loopWorktrees: flag('loopWorktrees', DEFAULT_LOOP.loopWorktrees), loopCommit: flag('loopCommit', DEFAULT_LOOP.loopCommit), diff --git a/plugins/ruflo-console/hooks/version.ts b/plugins/ruflo-console/hooks/version.ts index 020be6eb87..4a4f7a8414 100644 --- a/plugins/ruflo-console/hooks/version.ts +++ b/plugins/ruflo-console/hooks/version.ts @@ -2,4 +2,4 @@ * The console's version, shown on the header so a person can tell which build is running. Kept equal to the plugin's manifest * (`.claude-plugin/plugin.json`); tests/version.spec.ts fails if the two drift. */ -export const CONSOLE_VERSION = '0.30.0' +export const CONSOLE_VERSION = '0.31.0' diff --git a/plugins/ruflo-console/hooks/views/mission-claude.ts b/plugins/ruflo-console/hooks/views/mission-claude.ts new file mode 100644 index 0000000000..2103a72747 --- /dev/null +++ b/plugins/ruflo-console/hooks/views/mission-claude.ts @@ -0,0 +1,57 @@ +import type { RenderElement } from 'claude-code' + +import { button, kv, live, row, rule, sourceLine, text, type Ctx } from './common' +import { capOf, costOf } from '../mission-guard' +import { loopOf } from '../mission-claude' +import { tickPlan } from '../mission-loop' +import { derive } from '../mission-control' +import { parseGates, verdictOf } from '../mission-verify' +import { settingsOf } from '../settings' +import type { MissionRecord } from '../mission-types' +import { loopRows } from './mission-loop' +import { missionCostRows } from './mission-cost' + +function verifyRows(ctx: Ctx, mission: MissionRecord): RenderElement[] { + const prefs = settingsOf(ctx.state).ai + const { gates, rejected } = parseGates(prefs.loopGates) + const rows = [rule(ctx, 'Verify', gates.length === 0 ? 'no gates' : `${gates.length} gate${gates.length === 1 ? '' : 's'} · asks first`)] + + if (gates.length === 0) { + rows.push(text(ctx, ' No gates: add your own commands in', { dimColor: true })) + rows.push(text(ctx, ' Settings → Mission gates. Nothing is invented.', { dimColor: true })) + } else { + for (const gate of gates) rows.push(kv(ctx, gate.label.slice(0, 16), gate.argv.join(' '))) + rows.push(row(ctx, [button(ctx, 'mc-verify', 'Run the gates…', () => ctx.act.mission.verify())])) + } + + for (const item of rejected.slice(0, 3)) rows.push(text(ctx, ` skipped: ${item.line.slice(0, 30)} (${item.why})`, { dimColor: true })) + + const statuses = derive(mission, ctx.state.snapshot?.tasks ?? []) + + for (const task of mission.tasks.slice(0, 8)) { + const verdict = verdictOf(mission, task.id, gates) + + rows.push(text(ctx, ` ${task.id.padEnd(4)} ${(statuses.get(task.id) ?? 'waiting').padEnd(8)} ${verdict.state}${verdict.state === 'no-gates' ? '' : `: ${verdict.detail}`}`.slice(0, 80), { dimColor: verdict.state === 'unverified' || verdict.state === 'no-gates' })) + } + + return rows +} + +/** The Loop tab: the loop manager, this mission's spend against its cap, and the gates that verify its tasks. */ +export function loopTabRows(ctx: Ctx, mission: MissionRecord): RenderElement[] { + const loop = loopOf(mission) + const cost = costOf(ctx.state, mission) + const prefs = settingsOf(ctx.state).ai + const result = ctx.state.probes.get('mission-cost') + const rows = [...loopRows(ctx, loop, ctx.act.mission.loop, ctx.nowMs)] + + if (loop !== null) { + const plan = tickPlan({ mission, loop, prefs, gatesConfigured: parseGates(prefs.loopGates).gates.length > 0, spendUsd: cost?.usd ?? null, capUsd: capOf(ctx.state), nowMs: ctx.nowMs, taskStatus: derive(mission, ctx.state.snapshot?.tasks ?? []) }) + + rows.push(kv(ctx, 'next tick', `${plan.action}: ${plan.reason}`.slice(0, 60))) + } + + rows.push(...missionCostRows(ctx, cost, capOf(ctx.state), live(result) === null ? sourceLine(result, ctx.nowMs, 'mission spend').text : 'ledger: cost-tracker plugin'), ...verifyRows(ctx, mission)) + + return rows +} diff --git a/plugins/ruflo-console/hooks/views/mission-control.ts b/plugins/ruflo-console/hooks/views/mission-control.ts index 8b6dc240cf..8f22699ce6 100644 --- a/plugins/ruflo-console/hooks/views/mission-control.ts +++ b/plugins/ruflo-console/hooks/views/mission-control.ts @@ -8,6 +8,7 @@ import { barCells, percentOf, stripStatus } from '../mission-strip' import { ago, button, clip, col, confirmHere, isBbs, row, rule, section, text, THEME, wrap, type Ctx } from './common' import { GOALS_PLUGIN, isAvailable, MISSION_SKILLS, slashOf } from '../mission-skills' import { observationRows } from './missions' +import { loopTabRows } from './mission-claude' import { capabilityRows, launchRows } from './mission-launch' import { researchStartRows } from './research-start' @@ -18,6 +19,7 @@ const TABS: readonly { id: McTab; label: string }[] = [ { id: 'tasks', label: 'Tasks' }, { id: 'agents', label: 'Agents' }, { id: 'evidence', label: 'Evidence' }, + { id: 'loop', label: 'Loop' }, { id: 'record', label: 'Record' }, ] @@ -237,7 +239,7 @@ export function missionControlView(ctx: Ctx): RenderElement { const tab = mission === null && mc.tab !== 'record' ? 'plan' : mc.tab - rows.push(...(mission === null ? (tab === 'record' ? observationRows(ctx) : planRows(ctx)) : tab === 'plan' ? planRows(ctx) : tab === 'tasks' ? tasksRows(ctx, mission) : tab === 'agents' ? agentsRows(ctx, mission) : tab === 'evidence' ? evidenceRows(ctx, mission) : recordRows(ctx, mission))) + rows.push(...(mission === null ? (tab === 'record' ? observationRows(ctx) : planRows(ctx)) : tab === 'plan' ? planRows(ctx) : tab === 'tasks' ? tasksRows(ctx, mission) : tab === 'agents' ? agentsRows(ctx, mission) : tab === 'evidence' ? evidenceRows(ctx, mission) : tab === 'loop' ? loopTabRows(ctx, mission) : recordRows(ctx, mission))) return col(ctx, rows, 'mission-control') } diff --git a/plugins/ruflo-console/hooks/views/mission-cost.ts b/plugins/ruflo-console/hooks/views/mission-cost.ts new file mode 100644 index 0000000000..034fb7641a --- /dev/null +++ b/plugins/ruflo-console/hooks/views/mission-cost.ts @@ -0,0 +1,38 @@ +import type { RenderElement } from 'claude-code' + +import type { MissionCost } from '../data/mission-cost' +import { capState } from '../data/mission-cost' +import { kv, rule, text, THEME, type Ctx } from './common' +import { ladder } from './cost' +import { moneyText } from './cost-providers' + +/** The host clips a line at 60 columns; these notes stay shorter so nothing is cut mid-word. */ +const LINE = 49 +const short = (value: string): string => (value.length > LINE ? `${value.slice(0, LINE - 1)}…` : value) + +const COLOR = { none: undefined, OK: THEME.ok, INFO: THEME.info, WARNING: THEME.warn, CRITICAL: THEME.warn, HARD_STOP: THEME.bad } as const + +/** What the mission has spent, against its cap when it has one. `n/a` when the ledger did not answer. */ +export function missionCostRows(ctx: Ctx, cost: MissionCost | null, cap: number | null, sourceNote: string): RenderElement[] { + const rows = [rule(ctx, 'Mission spend', 'list-price estimate')] + + rows.push(kv(ctx, 'spend', cost === null || cost.usd === null ? 'n/a' : moneyText({ usd: cost.usd }))) + if (cost !== null && cost.credits !== null) rows.push(kv(ctx, 'Codex', moneyText({ credits: cost.credits }))) + rows.push(kv(ctx, 'cap', cap === null ? 'none set' : `$${cap.toFixed(2)}`)) + + const state = capState(cost?.usd ?? null, cap) + + if (cap !== null && cost !== null && cost.usd !== null) { + rows.push(text(ctx, ` ${ladder(cost.usd, cap, Math.min(30, Math.max(10, ctx.columns - 24)))} ${state.level} ${Math.round(state.percent ?? 0)}%`, { color: COLOR[state.level] })) + rows.push(text(ctx, ' Marks: 50, 75, 90, 100% of the cap.', { dimColor: true })) + } + + if (cost !== null && cost.unpriced.length > 0) rows.push(text(ctx, short(` Unpriced, not $0: ${cost.unpriced.join(', ')}`), { color: THEME.warn })) + if (cost !== null && cost.usd === null && cost.rows > 0) rows.push(text(ctx, ' Every model here is unpriced.', { dimColor: true })) + + rows.push(text(ctx, short(` ${sourceNote}`), { dimColor: true })) + rows.push(text(ctx, ' A list-price estimate, not a bill.', { dimColor: true })) + rows.push(text(ctx, ' USD and credits are never added together.', { dimColor: true })) + + return rows +} diff --git a/plugins/ruflo-console/hooks/views/mission-loop.ts b/plugins/ruflo-console/hooks/views/mission-loop.ts new file mode 100644 index 0000000000..81beef7c90 --- /dev/null +++ b/plugins/ruflo-console/hooks/views/mission-loop.ts @@ -0,0 +1,36 @@ +import type { RenderElement } from 'claude-code' + +import { span, status, type LoopLevel, type LoopState } from '../mission-loop' +import { ago, button, kv, row, rule, text, THEME, type Ctx } from './common' + +/** What the buttons do: each prepares text in the main UI and asks first; the console never schedules anything. */ +export type LoopActions = { start: () => void; stop: () => void; rearm: () => void } + +const COLOR: Record = { ok: THEME.ok, warn: THEME.warn, bad: THEME.bad } + +/** The loop manager's rows: status, ticks, expiry, and the buttons that are valid for the state. */ +export function loopRows(ctx: Ctx, loop: LoopState | null, actions: LoopActions, nowMs: number): RenderElement[] { + const report = status(loop, nowMs) + const rows = [rule(ctx, 'Loop manager', loop === null ? 'not started' : `every ${loop.interval}`), text(ctx, ` ${report.text}`, { color: COLOR[report.level] })] + + if (loop !== null && report.text !== 'no loop') { + rows.push(kv(ctx, 'ticks', String(loop.ticks))) + rows.push(kv(ctx, 'last tick', loop.lastTickMs === null ? 'none yet' : ago(loop.lastTickMs, nowMs))) + rows.push(kv(ctx, 'time to expiry', loop.status === 'expired' ? 'expired' : span(report.msToExpiry), report.isExpiring && loop.status !== 'expired' ? THEME.warn : undefined)) + if (report.isExpiring && loop.status === 'armed' && report.msToExpiry > 0) rows.push(text(ctx, ' Expires within 24 hours: re-arm before it goes.', { color: THEME.warn })) + } + + const state = loop?.status ?? 'idle' + const isGone = state === 'stopped' || report.level === 'bad' + const buttons: RenderElement[] = [] + + if (loop === null || state === 'idle') buttons.push(button(ctx, 'loop-start', 'Start loop', actions.start, { primary: true })) + if (state === 'armed' && report.msToExpiry > 0) buttons.push(button(ctx, 'loop-stop', 'Stop loop', actions.stop)) + if (isGone) buttons.push(button(ctx, 'loop-rearm', 'Re-arm loop', actions.rearm, { primary: true })) + if (buttons.length > 0) rows.push(row(ctx, buttons)) + + rows.push(text(ctx, ' Claude owns the schedule; the console only', { dimColor: true })) + rows.push(text(ctx, ' prepares and watches it.', { dimColor: true })) + + return rows +} diff --git a/plugins/ruflo-console/hooks/views/settings.ts b/plugins/ruflo-console/hooks/views/settings.ts index b156725340..ee771cff19 100644 --- a/plugins/ruflo-console/hooks/views/settings.ts +++ b/plugins/ruflo-console/hooks/views/settings.ts @@ -162,6 +162,9 @@ function aiItems(ctx: Ctx): Item[] { ...LOOP_ROWS.map(row => one(row.id, row.title, row.description, row.current(ai), row.options, row.isChanged(ai), value => ctx.act.settings.ai(row.patch(value)), row.extra)), one('model-control', 'Claude control', 'how far Claude may drive this console with its console_* tools: off, read (look and open pages), write (also fill fields and run local actions), manage (also network), full (also spend, deploy, delete); takes effect in a new session or /reload-plugins', ai.modelControl, ['off', 'read', 'write', 'manage', 'full'], ai.modelControl !== 'off', value => ctx.act.settings.ai({ modelControl: value as typeof ai.modelControl }), 'claude control drive computer use tools autonomy model'), one('model-confirm', 'Claude control: confirm', 'ask leaves each action Claude requests waiting for your Yes in the console; auto lets Claude’s call confirm itself, within the level above (every call is logged on Overview)', ai.modelConfirm, ['ask', 'auto'], ai.modelConfirm !== 'ask', value => ctx.act.settings.ai({ modelConfirm: value === 'auto' ? 'auto' : 'ask' }), 'claude control confirm auto ask approve'), + one('ctx-mission', 'Mission context in Claude’s prompt', 'the active mission and task ride in Claude’s system prompt, and change only when the task does (a changed prompt makes Claude re-read the chat)', ai.missionContext ? 'on' : 'off', ['on', 'off'], !ai.missionContext, value => ctx.act.settings.ai({ missionContext: value === 'on' }), 'mission context prompt cache claude'), + one('loop-gates', 'Mission gates', 'your own commands a mission may run to verify a task, one per line; each asks first and shows its exact argv; no shell characters', ai.loopGates, [], ai.loopGates !== '', value => ctx.act.settings.ai({ loopGates: value.slice(0, 800) }), 'gates verify tests smoke evidence'), + one('mission-cap', 'Mission spend cap (USD)', 'auto-run pauses when one mission’s spend reaches this (list-price estimate; empty means no cap)', ai.missionCapUsd, [], ai.missionCapUsd !== '', value => ctx.act.settings.ai({ missionCapUsd: /^\d{1,5}(\.\d{1,2})?$/.test(value.trim()) ? value.trim() : '' }), 'mission cap budget spend cost'), one('accept', 'Ask before each AI turn', 'always accept sends claude, codex and swarm turns straight out (read-only, plan mode, under the budget); ruflo commands still ask', ai.autoAccept ? 'always accept' : 'ask each time', ['ask each time', 'always accept'], ai.autoAccept, value => ctx.act.settings.ai({ autoAccept: value === 'always accept' }), 'confirm accept approve'), ] } diff --git a/plugins/ruflo-console/scripts/smoke.sh b/plugins/ruflo-console/scripts/smoke.sh index c6c7c45fb1..e9fd291612 100755 --- a/plugins/ruflo-console/scripts/smoke.sh +++ b/plugins/ruflo-console/scripts/smoke.sh @@ -11,9 +11,9 @@ step() { printf "→ %s ... " "$1"; } ok() { printf "PASS\n"; PASS=$((PASS+1)); } bad() { printf "FAIL: %s\n" "$1"; FAIL=$((FAIL+1)); } -step "1. plugin.json declares ruflo-console 0.30.0" +step "1. plugin.json declares ruflo-console 0.31.0" grep -q '"name": "ruflo-console"' "$ROOT/.claude-plugin/plugin.json" \ - && grep -q '"version": "0.30.0"' "$ROOT/.claude-plugin/plugin.json" && ok || bad "name/version" + && grep -q '"version": "0.31.0"' "$ROOT/.claude-plugin/plugin.json" && ok || bad "name/version" step "2. hooks.json names exactly one module and no classic hook commands" grep -q '"modules": \["./register.ts"\]' "$HOOKS/hooks.json" && ! grep -q '"command"' "$HOOKS/hooks.json" \ diff --git a/plugins/ruflo-console/tests/mission-claude.spec.ts b/plugins/ruflo-console/tests/mission-claude.spec.ts new file mode 100644 index 0000000000..8f6c9d27f6 --- /dev/null +++ b/plugins/ruflo-console/tests/mission-claude.spec.ts @@ -0,0 +1,284 @@ +/** + * The wiring of ADR-443: the mission in Claude's prompt (changing only with the task), loop ticks recognised by their marker, gate + * evidence, the loop manager's hand-offs, the spend cap in auto-run, the probe's readiness and the Loop tab. The pure modules have + * their own specs; this is what joins them to Mission Control. + */ +import { describe, expect, it } from 'vitest' + +import type { ActionSpec } from '../hooks/actions' +import { missionCostProbe } from '../hooks/data/cost-probes' +import type { TaskRecord } from '../hooks/data/parse' +import type { Host } from '../hooks/host' +import { claudeActions, contextSection, loopOf, onPromptSubmit, onTurnComplete } from '../hooks/mission-claude' +import { activeMission, advance, mcOf, record, type MissionRecord } from '../hooks/mission-control' +import { loopMarker } from '../hooks/mission-loop' +import type { Runner } from '../hooks/runner' +import { settingsOf } from '../hooks/settings' +import { newState, type State } from '../hooks/state' +import type { Actions } from '../hooks/views/common' +import { viewText } from '../hooks/views/pane' + +const ID = `msn_${'a'.repeat(24)}` +const OTHER = `msn_${'b'.repeat(24)}` +const task = (id: string, status: string, tags: string[]): TaskRecord => ({ id, type: 'feature', description: '', status, assignedTo: [], tags }) + +const mission = (id = ID): MissionRecord => ({ + id, + objective: 'add a dark mode toggle', + profile: 'feature', + rigor: 'standard', + tasks: [ + { id: 't1', title: 'Specify', phase: 'S', agent: 'specification', requirement: 'a written specification', dependsOn: [], rufloTaskId: 'r1' }, + { id: 't2', title: 'Design', phase: 'A', agent: 'architecture', requirement: 'a design', dependsOn: ['t1'], rufloTaskId: 'r2' }, + ], + acceptance: [{ id: 'ac-1', check: 'a specification exists' }], + events: [], + paused: false, + cancelled: false, + auto: false, + createdAtMs: 1_000, +}) + +function stateWith(tasks: TaskRecord[], m: MissionRecord = mission()): State { + const state = newState({}) + + state.snapshot = { tasks, agents: [], claims: [], swarm: null, plugins: { missingFromClone: [], installed: [] }, alerts: [] } as never + mcOf(state).missions.set(m.id, m) + mcOf(state).active = m.id + + return state +} + +const open = [task('r1', 'pending', [`mission:${ID}`, 'task:t1']), task('r2', 'pending', [`mission:${ID}`, 'task:t2'])] +const t1Done = [task('r1', 'completed', [`mission:${ID}`, 'task:t1']), task('r2', 'pending', [`mission:${ID}`, 'task:t2'])] +const t1Running = [task('r1', 'in_progress', [`mission:${ID}`, 'task:t1']), task('r2', 'pending', [`mission:${ID}`, 'task:t2'])] + +function fakeHost() { + const log = { runs: [] as (readonly string[])[], fills: [] as string[], stored: new Map() } + const host = { + run: async (argv: readonly string[]) => { + log.runs.push([...argv]) + + return { exitCode: argv.includes('fail') ? 2 : 0, stdout: 'ok\n', stderr: '' } + }, + storeGet: async (key: string) => log.stored.get(key), + storeSet: async (key: string, value: unknown) => void log.stored.set(key, value), + fillPrompt: async (text: string) => (log.fills.push(text), true), + invalidate: () => undefined, + after: () => ({ cancel: () => undefined }), + } as unknown as Host + + return { host, log } +} + +function fakeRunner() { + const asked: ActionSpec[] = [] + const runner = { ask: (spec: ActionSpec | null) => void (spec !== null && asked.push(spec)) } as unknown as Runner + + return { runner, asked } +} + +describe('the mission in Claude\'s prompt', () => { + it('is absent without a mission, with the setting off, and once every task is done', () => { + expect(contextSection(newState({}))).toBeNull() + + const off = stateWith(open) + + settingsOf(off).ai.missionContext = false + expect(contextSection(off)).toBeNull() + expect(contextSection(stateWith([task('r1', 'completed', [`mission:${ID}`, 'task:t1']), task('r2', 'completed', [`mission:${ID}`, 'task:t2'])]))).toBeNull() + }) + + it('names the mission and the task Claude is on, as a session section', () => { + const section = contextSection(stateWith(t1Running)) + + expect(section).toMatchObject({ id: 'ruflo-console:mission', scope: 'session' }) + expect(section?.text).toContain('add a dark mode toggle') + expect(section?.text).toContain('Specify') + }) + + it('does not change when events pile up, only when the task does (a changed prompt makes Claude re-read the chat)', () => { + const state = stateWith(t1Running) + const first = contextSection(state)?.text + + for (let i = 0; i < 20; i++) record(activeMission(state) as MissionRecord, { type: 'turn', note: `turn ${i}` }) + expect(contextSection(state)?.text).toBe(first) + + state.snapshot = { ...(state.snapshot as object), tasks: t1Done } as never + expect(contextSection(state)?.text).not.toBe(first) + expect(contextSection(state)?.text).toContain('Design') + }) +}) + +describe('turns and loop ticks', () => { + it('notes a turn on the running task and says nothing when no task is running', () => { + const { host } = fakeHost() + const running = stateWith(t1Running) + const idle = stateWith(open) + + onTurnComplete(running, host, 'answer') + onTurnComplete(idle, host, 'answer') + expect(activeMission(running)?.events.map(event => event.type)).toEqual(['turn']) + expect(activeMission(idle)?.events).toEqual([]) + }) + + it('counts only a prompt that carries this mission\'s marker as a tick, arming the loop on the first', () => { + const { host } = fakeHost() + const state = stateWith(open, mission()) + const other = mission(OTHER) + + mcOf(state).missions.set(other.id, other) + onPromptSubmit(state, host, 'just a prompt') + onPromptSubmit(state, host, `${loopMarker(OTHER)} check progress`) + expect(loopOf(activeMission(state) as MissionRecord)).toBeNull() + expect(loopOf(other)?.ticks).toBe(1) + + onPromptSubmit(state, host, `/loop 5m ${loopMarker(ID)} check progress`) + onPromptSubmit(state, host, `${loopMarker(ID)} check progress`) + expect(loopOf(activeMission(state) as MissionRecord)).toMatchObject({ status: 'armed', ticks: 2 }) + expect(activeMission(state)?.events.filter(event => event.type === 'loop.tick')).toHaveLength(2) + }) +}) + +describe('verify and the loop manager', () => { + it('says there are no gates rather than inventing any', () => { + const { host } = fakeHost() + const { runner, asked } = fakeRunner() + const state = stateWith(t1Running) + + claudeActions(state, host, runner).verify() + expect(asked).toEqual([]) + expect(mcOf(state).last).toMatchObject({ ok: false }) + expect(mcOf(state).last?.detail).toContain('no gates configured') + }) + + it('asks first with the exact commands, runs them without a shell, and records each exit code as evidence', async () => { + const { host, log } = fakeHost() + const { runner, asked } = fakeRunner() + const state = stateWith(t1Running) + + settingsOf(state).ai.loopGates = 'npm test\nnode check.mjs fail' + claudeActions(state, host, runner).verify() + expect(asked).toHaveLength(1) + expect(asked[0]?.shows).toContain('npm test') + expect(log.runs).toEqual([]) + + await asked[0]?.run?.() + expect(log.runs).toEqual([['npm', 'test'], ['node', 'check.mjs', 'fail']]) + expect(activeMission(state)?.events.filter(event => event.type === 'evidence.gate').map(event => event.status)).toEqual(['passed', 'failed']) + expect(mcOf(state).last?.ok).toBe(false) + }) + + it('refuses a gate with shell characters', () => { + const { host } = fakeHost() + const { runner, asked } = fakeRunner() + const state = stateWith(t1Running) + + settingsOf(state).ai.loopGates = 'npm test; rm x' + claudeActions(state, host, runner).verify() + expect(asked).toEqual([]) + }) + + it('prepares the /loop text (with the marker) in the prompt box only after the confirm, and schedules nothing itself', async () => { + const { host, log } = fakeHost() + const { runner, asked } = fakeRunner() + const state = stateWith(open) + + claudeActions(state, host, runner).loop.start() + expect(asked[0]?.shows).toContain('/loop 5m') + expect(log.fills).toEqual([]) + + await asked[0]?.run?.() + expect(log.fills[0]).toContain(loopMarker(ID)) + expect(log.fills[0]?.startsWith('/loop 5m')).toBe(true) + expect(activeMission(state)?.events.map(event => event.type)).toContain('loop.prepared') + }) + + it('has nothing to stop or re-arm without a loop', () => { + const { host } = fakeHost() + const { runner, asked } = fakeRunner() + const state = stateWith(open) + const actions = claudeActions(state, host, runner) + + actions.loop.stop() + actions.loop.rearm() + expect(asked).toEqual([]) + }) +}) + +describe('the spend cap in auto-run', () => { + const reading = (fromMs: number, usd: number) => ({ value: { usd, credits: null, unpriced: [], rows: 3, fromMs }, okAtMs: 1, error: null, errorAtMs: null, isRunning: false }) + + it('pauses an auto-run mission whose spend reached its cap, and says so in the ledger', () => { + const { host } = fakeHost() + const state = stateWith(t1Running) + const m = activeMission(state) as MissionRecord + + m.auto = true + settingsOf(state).ai.missionCapUsd = '5' + state.probes.set('mission-cost', reading(m.createdAtMs, 5)) + advance(state, host) + expect(m.paused).toBe(true) + expect(m.events.map(event => event.type)).toContain('cap.reached') + }) + + it('does not pause below the cap, with no cap, or on a reading for another mission', () => { + for (const [cap, usd, from] of [['5', 4.99, 1_000], ['', 50, 1_000], ['5', 50, 999]] as const) { + const { host } = fakeHost() + const state = stateWith(t1Running) + const m = activeMission(state) as MissionRecord + + m.auto = true + settingsOf(state).ai.missionCapUsd = cap + state.probes.set('mission-cost', reading(from, usd)) + advance(state, host) + expect(m.paused, `${cap} ${usd} ${from}`).toBe(false) + } + }) +}) + +describe('the mission spend probe', () => { + const installed = (version: string) => ({ id: 'ruflo-cost-tracker@ruflo', name: 'ruflo-cost-tracker', marketplace: 'ruflo', version, scope: 'user', installPath: '/p/ruflo-cost-tracker/x' }) + const withTracker = (version: string | null, withMission = true) => { + const state = withMission ? stateWith(open) : newState({}) + + state.cwd = '/work/app' + state.snapshot = { ...(state.snapshot ?? { tasks: [] }), plugins: { installed: version === null ? [] : [installed(version)], missingFromClone: [] } } as never + + return state + } + + it('runs only with a mission and a tracker new enough to filter by window, and asks for that mission\'s window and project', () => { + expect(missionCostProbe.argvOf?.(withTracker(null))).toBeNull() + expect(missionCostProbe.argvOf?.(withTracker('0.27.0'))).toBeNull() + expect(missionCostProbe.argvOf?.(withTracker('0.27.1', false))).toBeNull() + + const argv = missionCostProbe.argvOf?.(withTracker('0.27.1')) ?? [] + + expect(argv.slice(0, 2)).toEqual(['node', '/p/ruflo-cost-tracker/x/scripts/ledger.mjs']) + expect(argv).toContain('--project') + expect(argv[argv.indexOf('--project') + 1]).toBe('/work/app') + expect(argv[argv.indexOf('--from') + 1]).toBe(new Date(1_000).toISOString()) + expect(argv).not.toContain('--to') + }) +}) + +describe('the Loop tab and the Settings rows', () => { + const act = { mission: { verify: () => undefined, loop: { start: () => undefined, stop: () => undefined, rearm: () => undefined } } } as unknown as Actions + + it('shows the loop manager, the mission\'s spend and the gates', () => { + const state = stateWith(open) + + mcOf(state).tab = 'loop' + + const text = viewText({ state, nowMs: 5_000, columns: 100, act }, 'missions') + + for (const word of ['Loop manager', 'Mission spend', 'Verify', 'No gates']) expect(text, word).toContain(word) + }) + + it('lists the three new settings', () => { + const text = viewText({ state: newState({}), nowMs: 5, columns: 110, act: {} as Actions }, 'settings') + + for (const title of ['Mission context in Claude', 'Mission gates', 'Mission spend cap']) expect(text, title).toContain(title) + }) +}) diff --git a/plugins/ruflo-console/tests/mission-context.spec.ts b/plugins/ruflo-console/tests/mission-context.spec.ts new file mode 100644 index 0000000000..6941e58780 --- /dev/null +++ b/plugins/ruflo-console/tests/mission-context.spec.ts @@ -0,0 +1,149 @@ +import { describe, expect, it } from 'vitest' + +import { CONTEXT_MAX, CONTEXT_PREF_KEY, CONTEXT_ROW, CONTEXT_SECTION_ID, contextEnabled, missionContextKey, missionContextText, turnNote } from '../hooks/mission-context' +import type { LedgerTask, MissionRecord } from '../hooks/mission-types' + +const task: LedgerTask = { id: 't3', title: 'Write the parser', phase: 'refinement', agent: 'coder', requirement: 'parser passes its tests', dependsOn: [] } +const mission = (patch: Partial = {}): MissionRecord => ({ + id: 'msn_abc', + objective: 'Ship the parser', + profile: 'feature', + rigor: 'standard', + tasks: [task], + acceptance: [{ id: 'a1', check: 'tests pass' }, { id: 'a2', check: 'no lint errors' }], + events: [], + paused: false, + cancelled: false, + auto: false, + createdAtMs: 1, + ...patch, +}) +const loop = { interval: '5m', status: 'armed' } + +describe('missionContextText', () => { + it('names the section id and carries objective, task, checks and both rules', () => { + const text = missionContextText(mission(), task, loop, 'running') + + expect(CONTEXT_SECTION_ID).toBe('ruflo-console:mission') + expect(text).toContain('Ship the parser') + expect(text).toContain('Active task t3 (running): Write the parser') + expect(text).toContain('parser passes its tests') + expect(text).toContain('- tests pass') + expect(text).toContain('a task is done only with evidence: record it with task_complete and put what you ran and what it printed in the result'.replace(/^a/, 'A')) + expect(text).toContain('Stop when every task is done') + expect(text).toContain('Loop: 5m, armed.') + expect(text).not.toContain('Do not start new work') + }) + + it('is deterministic', () => { + expect(missionContextText(mission(), task, loop)).toBe(missionContextText(mission(), task, loop)) + }) + + it('says not to start new work when paused or cancelled', () => { + expect(missionContextText(mission({ paused: true }), task, null)).toContain('The mission is paused. Do not start new work.') + expect(missionContextText(mission({ cancelled: true }), task, null)).toContain('The mission is cancelled. Do not start new work.') + }) + + it('omits the task and loop lines when there is none', () => { + const text = missionContextText(mission(), null, null) + + expect(text).not.toContain('Active task') + expect(text).not.toContain('Loop:') + expect(text).toContain('Ship the parser') + }) + + it('strips control characters and ANSI from every field', () => { + const dirty = mission({ objective: 'a\u001b[31mred\u001b[0m\u0007 goal\nline', acceptance: [{ id: 'x', check: 'ok\u0000check' }] }) + const text = missionContextText(dirty, { ...task, title: 'ti\u009ftle' }, { interval: '5m\u0001', status: 'armed' }) + + expect(text).not.toMatch(/[\u0000-\u0009\u000b-\u001f\u007f-\u009f]/) + expect(text).toContain('ared goal line') + }) + + it('stays within the cap and keeps both rules at maximum field sizes', () => { + const big = 'x'.repeat(5000) + const huge = mission({ id: big, objective: big, paused: true, acceptance: Array.from({ length: 20 }, (_, index) => ({ id: `a${index}`, check: big })) }) + const text = missionContextText(huge, { ...task, id: big, title: big, requirement: big }, { interval: big, status: big }) + + expect(text.length).toBeLessThanOrEqual(CONTEXT_MAX) + expect(text).toContain('task_complete') + expect(text).toContain('Stop when every task is done') + expect(text).toContain('Do not start new work') + }) +}) + +describe('missionContextKey', () => { + const base = missionContextKey(mission(), task, loop, 'ready') + + it('does not change with events, timestamps, spend-like fields, objective text or acceptance', () => { + const noisy = mission({ events: [{ seq: 1, atMs: 5, type: 'x' }, { seq: 2, atMs: 9, type: 'y', note: 'cost $4' }], createdAtMs: 999, auto: true, objective: 'reworded', acceptance: [] }) + + expect(missionContextKey(noisy, task, loop, 'ready')).toBe(base) + expect(missionContextKey(noisy, task, { interval: '30m', status: 'overdue' }, 'ready')).toBe(base) + }) + + it('changes with mission id, active task id, its status, paused, cancelled and loop on/off', () => { + const keys = [ + missionContextKey(mission({ id: 'msn_other' }), task, loop, 'ready'), + missionContextKey(mission(), { ...task, id: 't4' }, loop, 'ready'), + missionContextKey(mission(), task, loop, 'running'), + missionContextKey(mission({ paused: true }), task, loop, 'ready'), + missionContextKey(mission({ cancelled: true }), task, loop, 'ready'), + missionContextKey(mission(), task, null, 'ready'), + missionContextKey(mission(), null, loop), + ] + + expect(new Set([base, ...keys]).size).toBe(keys.length + 1) + }) +}) + +describe('settings row', () => { + it('is on by default and only the exact off value turns it off', () => { + expect(contextEnabled(undefined)).toBe(true) + expect(contextEnabled('on')).toBe(true) + expect(contextEnabled('OFF')).toBe(true) + expect(contextEnabled(0)).toBe(true) + expect(contextEnabled(null)).toBe(true) + expect(contextEnabled('off')).toBe(false) + expect(contextEnabled(false)).toBe(false) + }) + + it('has the LOOP_ROWS shape and round-trips through patch/current', () => { + expect(CONTEXT_ROW.id).toBe('ctx-mission') + expect(CONTEXT_ROW.title).toBe('Mission context in Claude’s prompt') + expect(CONTEXT_ROW.options).toEqual(['on', 'off']) + expect(CONTEXT_ROW.current({})).toBe('on') + expect(CONTEXT_ROW.isChanged({})).toBe(false) + + const off = CONTEXT_ROW.patch('off') + + expect(off).toEqual({ [CONTEXT_PREF_KEY]: false }) + expect(CONTEXT_ROW.current(off)).toBe('off') + expect(CONTEXT_ROW.isChanged(off)).toBe(true) + expect(CONTEXT_ROW.patch('on')).toEqual({ [CONTEXT_PREF_KEY]: true }) + expect(CONTEXT_ROW.patch('garbage')).toEqual({ [CONTEXT_PREF_KEY]: true }) + }) +}) + +describe('turnNote', () => { + it('is null with no active task', () => { + expect(turnNote('answer', null)).toBeNull() + }) + + it('names the task and never claims it finished, for every reason', () => { + for (const reason of ['answer', 'aborted', 'refusal', 'error'] as const) { + const note = turnNote(reason, task) + + expect(note?.taskId).toBe('t3') + expect(note?.type).toBe('turn') + expect(note?.note.length).toBeGreaterThan(10) + expect(note?.note).not.toMatch(/\b(completed|is done|was finished|succeeded)\b/i) + } + }) + + it('tells the reasons apart', () => { + const notes = (['answer', 'aborted', 'refusal', 'error'] as const).map(reason => turnNote(reason, task)?.note) + + expect(new Set(notes).size).toBe(4) + }) +}) diff --git a/plugins/ruflo-console/tests/mission-cost.spec.ts b/plugins/ruflo-console/tests/mission-cost.spec.ts new file mode 100644 index 0000000000..886db6d27a --- /dev/null +++ b/plugins/ruflo-console/tests/mission-cost.spec.ts @@ -0,0 +1,195 @@ +import { spawnSync } from 'node:child_process' +import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join, resolve } from 'node:path' + +import { describe, expect, it } from 'vitest' + +import { capState, capUsd, missionCostArgv, parseMissionCost, shouldPause } from '../hooks/data/mission-cost' +import { newState } from '../hooks/state' +import { missionCostRows } from '../hooks/views/mission-cost' +import type { Ctx } from '../hooks/views/common' + +const ROOT = '/p/ruflo-cost-tracker/0.28.0' +const FROM = Date.parse('2026-10-02T00:00:00Z') +const TO = Date.parse('2026-10-03T00:00:00Z') + +const LEDGER = (extra: Record = {}): string => JSON.stringify({ since: 'window', priceDate: '2026-10-03', rows: 4, totals: { usd: 12.5, credits: 300 }, byProvider: {}, unpriced: {}, window: { from: null, to: null, project: '/p' }, ...extra }) + +describe('missionCostArgv', () => { + it('builds the fixed ledger command with an ISO window and the project', () => { + expect(missionCostArgv(ROOT, FROM, TO, '/home/u/proj')).toEqual(['node', `${ROOT}/scripts/ledger.mjs`, '--format', 'json', '--from', '2026-10-02T00:00:00.000Z', '--to', '2026-10-03T00:00:00.000Z', '--project', '/home/u/proj']) + }) + + it('leaves the window open on the right while the mission runs', () => { + const argv = missionCostArgv(ROOT, FROM, null, '/home/u/proj') + + expect(argv).not.toContain('--to') + expect(argv).toContain('--from') + }) + + it('is null for a hostile plugin root, a relative or traversing project, control characters, or a bad window', () => { + for (const root of ['relative', '/a/../b', '/x; rm -rf', '']) expect(missionCostArgv(root, FROM, TO, '/p')).toBeNull() + for (const project of ['proj', '', '/a/../etc', '/a\nb', '/a\u0000b', '/a\u001b[31m', `/${'a'.repeat(600)}`]) expect(missionCostArgv(ROOT, FROM, TO, project)).toBeNull() + expect(missionCostArgv(ROOT, Number.NaN, TO, '/p')).toBeNull() + expect(missionCostArgv(ROOT, FROM, Number.POSITIVE_INFINITY, '/p')).toBeNull() + expect(missionCostArgv(ROOT, TO, FROM, '/p')).toBeNull() + }) +}) + +describe('parseMissionCost window',()=>{ + it('reads which window the ledger answered for, so a reading is never shown for another mission', () => { + const out = JSON.stringify({ totals: { usd: 1 }, rows: 1, window: { from: '2026-10-04T00:00:00.000Z', to: null, project: '/p' } }) + + expect(parseMissionCost(out)?.fromMs).toBe(Date.parse('2026-10-04T00:00:00.000Z')) + expect(parseMissionCost(JSON.stringify({ totals: { usd: 1 }, window: { from: 'not a date' } }))?.fromMs).toBeNull() + }) +}) + +describe('parseMissionCost', () => { + it('keeps USD and credits apart and lists unpriced models', () => { + expect(parseMissionCost(LEDGER({ unpriced: { 'gpt-5.6-sol': { messages: 3 } } }))).toEqual({ usd: 12.5, credits: 300, unpriced: ['gpt-5.6-sol'], rows: 4, fromMs: null }) + }) + + it('treats a window with no rows as a real zero, but all-unpriced rows as unknown', () => { + expect(parseMissionCost(LEDGER({ rows: 0, totals: {} }))).toMatchObject({ usd: 0, credits: null, rows: 0 }) + expect(parseMissionCost(LEDGER({ rows: 2, totals: {}, unpriced: { 'mystery-9': {} } }))).toMatchObject({ usd: null, unpriced: ['mystery-9'] }) + }) + + it('is null for anything that is not the ledger, and strips control text from model names', () => { + for (const bad of ['', 'nope', '{"a":1}', '[]', '{"totals":1}']) expect(parseMissionCost(bad)).toBeNull() + expect(parseMissionCost(LEDGER({ unpriced: { 'm\u001b[31mx\nmodel': {} } }))?.unpriced[0]).toBe('mx model') + }) + + it('ignores negative or non-numeric totals', () => { + expect(parseMissionCost(LEDGER({ totals: { usd: -4, credits: 'x' } }))).toMatchObject({ usd: null, credits: null }) + }) +}) + +describe('capState and shouldPause', () => { + it('follows the 50/75/90/100 ladder', () => { + const at = (spend: number) => capState(spend, 10).level + + expect([at(0), at(4.99), at(5), at(7.49), at(7.5), at(8.99), at(9), at(9.99), at(10), at(25)]).toEqual(['OK', 'OK', 'INFO', 'INFO', 'WARNING', 'WARNING', 'CRITICAL', 'CRITICAL', 'HARD_STOP', 'HARD_STOP']) + expect(capState(2.5, 10).percent).toBe(25) + expect(capState(25, 10).percent).toBe(250) + }) + + it('is none without a spend or a usable cap', () => { + for (const [spend, cap] of [[null, 10], [3, null], [null, null], [3, 0], [3, -1], [Number.NaN, 10], [-1, 10], [3, Number.POSITIVE_INFINITY]] as const) expect(capState(spend, cap)).toEqual({ level: 'none', percent: null }) + }) + + it('pauses only at the hard stop with auto-run on', () => { + expect(shouldPause(capState(10, 10), true)).toBe(true) + expect(shouldPause(capState(10, 10), false)).toBe(false) + expect(shouldPause(capState(9.5, 10), true)).toBe(false) + expect(shouldPause(capState(null, 10), true)).toBe(false) + expect(shouldPause(capState(10, null), true)).toBe(false) + }) +}) + +describe('capUsd', () => { + it('accepts 0.01 to 10000 as plain decimals and nothing else', () => { + expect([capUsd('0.01'), capUsd(' 25 '), capUsd('.5'), capUsd('10000')]).toEqual([0.01, 25, 0.5, 10_000]) + for (const bad of ['', '0', '0.009', '10000.01', '-5', '1e3', '$5', '5usd', '0x10', 'NaN', 'Infinity', '1,5']) expect(capUsd(bad)).toBeNull() + }) +}) + +type Node = { type: string; props: { children?: unknown } } +const kit = (): Ctx['kit'] => { + const element = (type: string) => (props: Record) => ({ type, props }) as never + + return { Box: element('Box'), Text: element('Text'), Button: element('Button') } +} +const flat = (node: unknown): string => { + if (typeof node === 'string' || typeof node === 'number') return String(node) + if (node === null || node === undefined || typeof node === 'boolean') return '' + if (Array.isArray(node)) return node.map(flat).join('') + + return flat((node as Node).props.children) +} +const shown = (cost: ReturnType, cap: number | null, note = 'ledger: cost-tracker plugin'): string[] => missionCostRows({ kit: kit(), state: newState({}), nowMs: 5, columns: 110, pictures: new Map(), act: {} } as unknown as Ctx, cost, cap, note).map(flat) + +describe('missionCostRows', () => { + it('shows spend, cap and the ladder, and says it is an estimate', () => { + const lines = shown({ usd: 8, credits: null, unpriced: [], rows: 3 }, 10) + const all = lines.join('\n') + + expect(all).toContain('Mission spend') + expect(all).toContain('$8.00') + expect(all).toContain('$10.00') + expect(all).toContain('WARNING') + expect(all).toContain('80%') + expect(all).toContain('list-price') + expect(all).toMatch(/not a bill/) + }) + + it('is n/a when the ledger did not answer, and never draws a bar', () => { + const all = shown(null, 10).join('\n') + + expect(all).toMatch(/spend\s*n\/a/) + expect(all).not.toContain('WARNING') + expect(all).not.toContain('█') + }) + + it('shows no bar without a cap, lists unpriced models and keeps credits separate', () => { + const all = shown({ usd: 1, credits: 40, unpriced: ['mystery-9'], rows: 2 }, null).join('\n') + + expect(all).toMatch(/cap\s*none set/) + expect(all).toContain('mystery-9') + expect(all).toContain('40 credits') + expect(all).not.toContain('█') + }) + + it('keeps every note and disclaimer under 50 characters, even for a long source note or model list', () => { + const lines = shown({ usd: 1, credits: null, unpriced: ['m'.repeat(50), 'n'.repeat(50)], rows: 1 }, null, 'x'.repeat(200)) + const notes = lines.filter(line => /^ (?!Marks)/.test(line) && !line.includes('Mission spend')) + + expect(notes.length).toBeGreaterThan(2) + for (const line of notes) expect(line.length, line).toBeLessThan(50) + }) +}) + +describe('the ledger filters, through the real script', () => { + const win = mkdtempSync(join(tmpdir(), 'mission-cost-')) + const logs = join(win, 'claude', 'projects', 'q') + + mkdirSync(logs, { recursive: true }) + mkdirSync(join(win, 'codex'), { recursive: true }) + + const at = (iso: string, id: string, cwd: string) => ({ type: 'assistant', sessionId: `s-${id}`, cwd, requestId: `r-${id}`, timestamp: iso, message: { id, role: 'assistant', model: 'claude-opus-5-5', usage: { input_tokens: 1_000_000, output_tokens: 0 } } }) + + writeFileSync(join(logs, 'w.jsonl'), [ + at('2026-10-01T00:00:00.000Z', 'before', '/proj/a'), + at('2026-10-02T06:00:00.000Z', 'in-a', '/proj/a'), + at('2026-10-02T07:00:00.000Z', 'in-sub', '/proj/a/sub'), + at('2026-10-02T08:00:00.000Z', 'sibling', '/proj/ab'), + at('2026-10-02T09:00:00.000Z', 'in-b', '/proj/b'), + at('2026-10-04T00:00:00.000Z', 'after', '/proj/a'), + ].map(item => JSON.stringify(item)).join('\n') + '\n') + + const ledgerRoot = resolve(__dirname, '../../ruflo-cost-tracker') + const run = (project: string, toMs: number | null) => { + const argv = missionCostArgv(ledgerRoot, FROM, toMs, project) + + if (argv === null) return null + + const out = spawnSync(process.execPath, argv.slice(1), { encoding: 'utf-8', env: { PATH: process.env.PATH ?? '', CLAUDE_CONFIG_DIR: join(win, 'claude'), CODEX_HOME: join(win, 'codex') } }) + + return { status: out.status, cost: parseMissionCost(out.stdout) } + } + + it('counts only the project and its subdirectories inside the window', () => { + const result = run('/proj/a', TO) + + expect(result?.status).toBe(0) + expect(result?.cost?.rows).toBe(2) // in-a and in-sub; not before, not /proj/ab, not /proj/b + expect(result?.cost?.usd).toBeGreaterThan(0) + }) + + it('leaves the window open when the mission has not ended, and a different project gets its own spend', () => { + expect(run('/proj/a', null)?.cost?.rows).toBe(3) // adds the row after the old end + expect(run('/proj/b', TO)?.cost?.rows).toBe(1) + expect(run('/proj/none', TO)?.cost).toMatchObject({ rows: 0, usd: 0 }) + }) +}) diff --git a/plugins/ruflo-console/tests/mission-loop.spec.ts b/plugins/ruflo-console/tests/mission-loop.spec.ts new file mode 100644 index 0000000000..bb5d758da4 --- /dev/null +++ b/plugins/ruflo-console/tests/mission-loop.spec.ts @@ -0,0 +1,487 @@ +import { describe, expect, it, vi } from 'vitest' + +import { DEFAULT_LOOP } from '../hooks/goap' +import { + armed, + GATE_EVENT, + intervalMs, + isTick, + LOOP_LIFETIME_MS, + loopMarker, + loopPrompt, + normalizeInterval, + parseLoop, + rearmCommand, + serializeLoop, + span, + startCommand, + status, + stop, + stopRequest, + tick, + tickPlan, + type LoopState, + type TickInput, +} from '../hooks/mission-loop' +import type { MissionRecord } from '../hooks/mission-types' +import { loopRows } from '../hooks/views/mission-loop' +import type { Ctx } from '../hooks/views/common' + +const MIN = 60_000 +const HOUR = 3_600_000 +const T0 = 1_000_000_000_000 + +const mission = (patch: Partial = {}): MissionRecord => ({ + id: 'm1', + objective: 'Build the thing', + profile: 'feature', + rigor: 'standard', + tasks: [ + { id: 't1', title: 'one', phase: 'S', agent: 'coder', requirement: 'r', dependsOn: [] }, + { id: 't2', title: 'two', phase: 'R', agent: 'coder', requirement: 'r', dependsOn: ['t1'] }, + ], + acceptance: [], + events: [], + paused: false, + cancelled: false, + auto: false, + createdAtMs: T0, + ...patch, +}) +const state = (patch: Partial = {}): LoopState => ({ missionId: 'm1', interval: '5m', startedAtMs: T0, expiresAtMs: T0 + LOOP_LIFETIME_MS, ticks: 0, lastTickMs: null, status: 'armed', ...patch }) + +describe('intervals and the start command', () => { + it('reads and nothing else', () => { + expect(intervalMs('5m')).toBe(5 * MIN) + expect(intervalMs('2h')).toBe(2 * HOUR) + expect(intervalMs('1d')).toBe(24 * HOUR) + for (const bad of ['5', 'm', '5 m', '5M', '-5m', '5m; rm', '', '1.5h', 5, null, undefined]) expect(intervalMs(bad)).toBeNull() + }) + + it('falls back to the default for a bad interval and clamps to 1m..1d', () => { + expect(normalizeInterval('nope', '10m')).toBe('10m') + expect(normalizeInterval('nope', 'also bad')).toBe(DEFAULT_LOOP.loopInterval) + expect(normalizeInterval('30s')).toBe('1m') + expect(normalizeInterval('0m')).toBe('1m') + expect(normalizeInterval('1m')).toBe('1m') + expect(normalizeInterval('9999d')).toBe('1d') + expect(normalizeInterval('15m')).toBe('15m') + }) + + it('builds /loop and never starts below a minute', () => { + const prefs = { ...DEFAULT_LOOP, loopInterval: '10m' as const } + const prompt = loopPrompt(mission(), prefs) + + expect(startCommand(mission(), prefs, '2m')).toBe(`/loop 2m ${prompt}`) + expect(startCommand(mission(), prefs, '5s')).toBe(`/loop 1m ${prompt}`) + expect(startCommand(mission(), prefs, 'whenever')).toBe(`/loop 10m ${prompt}`) + }) +}) + +describe('the recurring prompt', () => { + it('opens with the marker and carries the ADR-441 per-tick checklist', () => { + const prompt = loopPrompt(mission(), DEFAULT_LOOP) + + expect(loopMarker('m1')).toBe('[mission:m1 loop]') + expect(prompt.startsWith('[mission:m1 loop] Mission m1: Build the thing.')).toBe(true) + expect(prompt).toContain('check progress') + expect(prompt).toContain('fix what failed') + expect(prompt).toContain('run the gates') + expect(prompt).toContain('then stop the loop and report') + expect(prompt).not.toContain('\n') + }) + + it('names push and publish only when the settings allow them', () => { + const closed = loopPrompt(mission(), DEFAULT_LOOP) + const open = loopPrompt(mission(), { ...DEFAULT_LOOP, loopPush: true, loopPublish: true }) + + expect(closed).toContain('do not push') + expect(closed).toContain('do not publish, release or deploy') + expect(open).toContain('may be pushed') + expect(open).toContain('may be published') + expect(open).not.toContain('do not push') + }) + + it('caps the text and strips control characters from the objective', () => { + const prompt = loopPrompt(mission({ objective: `a\u001b[31mred\u0000\u0007 ${'x'.repeat(5000)}\nline` }), DEFAULT_LOOP) + + expect(prompt.length).toBeLessThanOrEqual(1000) + // eslint-disable-next-line no-control-regex + expect(/[\u0000-\u001f\u007f-\u009f]/.test(prompt)).toBe(false) + expect(prompt).not.toContain('[31m') + }) + + it('keeps a hostile mission id out of the marker', () => { + expect(loopMarker('m1] [mission:other')).toBe('[mission:m1mission:other loop]') + expect(loopMarker('a b\nc')).toBe('[mission:abc loop]') + }) +}) + +describe('recognising a tick', () => { + it('is true for this mission’s marker, with or without a prefix', () => { + expect(isTick(loopPrompt(mission(), DEFAULT_LOOP), 'm1')).toBe(true) + expect(isTick(` [mission:m1 loop] go`, 'm1')).toBe(true) + expect(isTick(` [mission:m1 loop] go`, 'm1')).toBe(true) + }) + + it('is false for another mission’s marker, a prefix id, and plain text', () => { + expect(isTick('[mission:m2 loop] go', 'm1')).toBe(false) + expect(isTick('[mission:m10 loop] go', 'm1')).toBe(false) + expect(isTick('[mission:m1 loop] go', 'm')).toBe(false) + expect(isTick('please keep looping on m1', 'm1')).toBe(false) + expect(isTick('[mission:m1] loop', 'm1')).toBe(false) + expect(isTick('', 'm1')).toBe(false) + expect(isTick('[mission:m1 loop]', '')).toBe(false) + }) + + it('is spoof-proof: another mission’s longer message that quotes this marker is not a tick', () => { + const other = `${loopMarker('m2')} Mission m2: as seen in ${loopMarker('m1')} earlier, keep going` + + expect(isTick(other, 'm1')).toBe(false) + expect(isTick(other, 'm2')).toBe(true) + expect(isTick(`someone said ${loopMarker('m2')} then ${loopMarker('m1')}`, 'm1')).toBe(false) + }) + + it('ignores a marker pushed past the scanned prefix and non-string input', () => { + expect(isTick(`${'x'.repeat(2500)}${loopMarker('m1')}`, 'm1')).toBe(false) + expect(isTick(undefined as unknown as string, 'm1')).toBe(false) + }) +}) + +describe('arming, ticking and stopping', () => { + it('arms a fresh 7-day loop', () => { + const s = armed(null, mission(), '5m', T0) + + expect(s).toEqual({ missionId: 'm1', interval: '5m', startedAtMs: T0, expiresAtMs: T0 + LOOP_LIFETIME_MS, ticks: 0, lastTickMs: null, status: 'armed' }) + expect(LOOP_LIFETIME_MS).toBe(7 * 24 * 3600 * 1000) + }) + + it('arming an armed, unexpired loop of the same interval changes nothing; an expired or other loop starts fresh', () => { + const live = tick(armed(null, mission(), '5m', T0), T0 + 5 * MIN) + + expect(armed(live, mission(), '5m', T0 + 6 * MIN)).toBe(live) + expect(armed(live, mission(), '10m', T0 + 6 * MIN).ticks).toBe(0) + expect(armed(live, mission({ id: 'm2' }), '5m', T0 + 6 * MIN).missionId).toBe('m2') + expect(armed({ ...live, status: 'expired' }, mission(), '5m', T0 + 6 * MIN).startedAtMs).toBe(T0 + 6 * MIN) + expect(armed(live, mission(), '5m', live.expiresAtMs).startedAtMs).toBe(live.expiresAtMs) + }) + + it('arms with a safe interval', () => { + expect(armed(null, mission(), 'bad', T0).interval).toBe(DEFAULT_LOOP.loopInterval) + expect(armed(null, mission(), '10s', T0).interval).toBe('1m') + }) + + it('counts a tick while armed and keeps the last tick time', () => { + const one = tick(state(), T0 + 5 * MIN) + const two = tick(one, T0 + 10 * MIN) + + expect(one).toMatchObject({ ticks: 1, lastTickMs: T0 + 5 * MIN, status: 'armed' }) + expect(two).toMatchObject({ ticks: 2, lastTickMs: T0 + 10 * MIN }) + }) + + it('does not mutate its input', () => { + const s = state() + + tick(s, T0 + MIN) + stop(s) + expect(s).toEqual(state()) + }) + + it('a tick at or after expiry marks it expired and counts nothing', () => { + const s = state({ ticks: 4, lastTickMs: T0 }) + + expect(tick(s, s.expiresAtMs)).toMatchObject({ status: 'expired', ticks: 4, lastTickMs: T0 }) + expect(tick(s, s.expiresAtMs - 1).ticks).toBe(5) + }) + + it('ticks are not counted for a stopped, idle, expired or done loop', () => { + for (const status of ['stopped', 'idle', 'expired', 'done'] as const) expect(tick(state({ status }), T0 + MIN)).toEqual(state({ status })) + }) + + it('stop moves idle and armed to stopped and leaves expired and done alone', () => { + expect(stop(state()).status).toBe('stopped') + expect(stop(state({ status: 'idle' })).status).toBe('stopped') + expect(stop(state({ status: 'expired' })).status).toBe('expired') + expect(stop(state({ status: 'done' })).status).toBe('done') + }) +}) + +describe('status', () => { + it('reports an armed loop: next tick from start, then from the last tick', () => { + const fresh = status(state(), T0 + MIN) + + expect(fresh).toMatchObject({ level: 'ok', nextTickMs: T0 + 5 * MIN, isOverdue: false, isExpiring: false }) + expect(fresh.text).toBe('armed · 0 ticks · next in 4m') + expect(status(state({ ticks: 1, lastTickMs: T0 + 5 * MIN }), T0 + 6 * MIN).nextTickMs).toBe(T0 + 10 * MIN) + expect(status(state({ ticks: 1 }), T0 + 5 * MIN).text).toContain('1 tick ·') + expect(status(state(), T0 + 6 * MIN).text).toContain('due now') + }) + + it('is overdue only after three intervals without a tick, measured from the later of start and last tick', () => { + expect(status(state(), T0 + 15 * MIN).isOverdue).toBe(false) + expect(status(state(), T0 + 15 * MIN + 1).isOverdue).toBe(true) + + const late = status(state({ lastTickMs: T0 + 100 * MIN, ticks: 3 }), T0 + 114 * MIN) + + expect(late.isOverdue).toBe(false) + expect(status(state({ lastTickMs: T0 + 100 * MIN, ticks: 3 }), T0 + 116 * MIN)).toMatchObject({ isOverdue: true, level: 'bad' }) + expect(status(state(), T0 + 20 * MIN).text).toContain('overdue') + }) + + it('warns inside the last 24 hours and not before', () => { + const edge = T0 + LOOP_LIFETIME_MS - 24 * HOUR + const s = state({ lastTickMs: edge - MIN, ticks: 5 }) + + expect(status(s, edge - 1)).toMatchObject({ isExpiring: false, level: 'ok' }) + expect(status(s, edge)).toMatchObject({ isExpiring: true, level: 'warn', msToExpiry: 24 * HOUR }) + }) + + it('is expired when now reaches expiresAtMs, and when the status says so', () => { + const atEdge = status(state({ ticks: 9, lastTickMs: T0 }), T0 + LOOP_LIFETIME_MS) + + expect(atEdge).toMatchObject({ level: 'bad', msToExpiry: 0, nextTickMs: null, isOverdue: false, isExpiring: false }) + expect(atEdge.text).toContain('expired after 9 ticks') + expect(status(state({ status: 'expired' }), T0 + MIN).level).toBe('bad') + expect(status(state({ lastTickMs: T0 + LOOP_LIFETIME_MS - MIN }), T0 + LOOP_LIFETIME_MS - 1).level).not.toBe('bad') + }) + + it('reports stopped, done and idle without a next tick', () => { + expect(status(state({ status: 'stopped', ticks: 2 }), T0 + MIN)).toMatchObject({ level: 'warn', nextTickMs: null, text: 'stopped after 2 ticks' }) + expect(status(state({ status: 'done' }), T0 + MIN)).toMatchObject({ level: 'ok', nextTickMs: null }) + expect(status(state({ status: 'idle' }), T0 + MIN)).toMatchObject({ level: 'ok', nextTickMs: null, text: 'not started' }) + }) + + it('is total: bad input is a safe idle status', () => { + const idle = { text: 'no loop', level: 'ok', nextTickMs: null, msToExpiry: 0, isOverdue: false, isExpiring: false } + + expect(status(null, T0)).toEqual(idle) + expect(status(state(), Number.NaN)).toEqual(idle) + expect(status(state({ interval: 'x' }), T0)).toEqual(idle) + expect(status({ ...state(), startedAtMs: Number.NaN }, T0)).toEqual(idle) + expect(status({ ...state(), expiresAtMs: 'soon' as unknown as number }, T0)).toEqual(idle) + expect(status('nope' as unknown as LoopState, T0)).toEqual(idle) + }) + + it('formats spans', () => { + expect([span(-5), span(45_000), span(4 * MIN), span(3 * HOUR + 10 * MIN), span(2 * 24 * HOUR + 4 * HOUR)]).toEqual(['0s', '45s', '4m', '3h 10m', '2d 4h']) + }) +}) + +describe('stop request and re-arm', () => { + it('says plainly that Claude owns the schedule and names the marker and the tools', () => { + const text = stopRequest(state({ ticks: 7 }), mission()) + + expect(text).toContain('only you own the schedule') + expect(text).toContain('CronList') + expect(text).toContain('CronDelete') + expect(text).toContain('[mission:m1 loop]') + expect(text).toContain('7 ticks') + expect(stopRequest(null, mission())).not.toContain('ticks so far') + }) + + it('re-arms only a stopped, expired or overdue loop, with the same prompt and interval', () => { + const prefs = DEFAULT_LOOP + const expected = startCommand(mission(), prefs, '15m') + + expect(rearmCommand(state({ interval: '15m', status: 'stopped' }), mission(), prefs)).toBe(expected) + expect(rearmCommand(state({ interval: '15m', status: 'expired' }), mission(), prefs)).toBe(expected) + expect(rearmCommand(state({ interval: '15m' }), mission(), prefs)).toBeNull() + expect(rearmCommand(state({ interval: '15m' }), mission(), prefs, T0 + 10 * MIN)).toBeNull() + expect(rearmCommand(state({ interval: '15m' }), mission(), prefs, T0 + 46 * MIN)).toBe(expected) + expect(rearmCommand(state({ interval: '15m' }), mission(), prefs, T0 + LOOP_LIFETIME_MS + 1)).toBe(expected) + expect(rearmCommand(state({ status: 'done' }), mission(), prefs, T0 + LOOP_LIFETIME_MS + 1)).toBeNull() + expect(rearmCommand(state({ status: 'idle' }), mission(), prefs)).toBeNull() + expect(rearmCommand(null, mission(), prefs)).toBeNull() + expect(rearmCommand(state({ status: 'expired' }), mission({ id: 'other' }), prefs)).toBeNull() + }) +}) + +describe('serialize and parse', () => { + it('round-trips through JSON', () => { + const s = state({ ticks: 12, lastTickMs: T0 + 50 * MIN, interval: '10m', status: 'stopped' }) + + expect(parseLoop(JSON.parse(JSON.stringify(serializeLoop(s))))).toEqual(s) + expect(parseLoop(serializeLoop(state()))).toEqual(state()) + }) + + it('drops anything off: not an object, missing or wrong fields, a bad status, interval or id', () => { + const good = serializeLoop(state()) as Record + const bad: unknown[] = [null, undefined, 5, 'x', [], [good], {}, true] + + for (const patch of [ + { missionId: '' }, + { missionId: 'm 1' }, + { missionId: 7 }, + { missionId: 'x'.repeat(200) }, + { interval: '5' }, + { interval: '30s' }, + { interval: '9999d' }, + { interval: 5 }, + { startedAtMs: -1 }, + { startedAtMs: Number.NaN }, + { startedAtMs: '1' }, + { expiresAtMs: T0 - 1 }, + { expiresAtMs: Number.POSITIVE_INFINITY }, + { ticks: -1 }, + { ticks: 1.5 }, + { ticks: 1e9 }, + { ticks: '3' }, + { lastTickMs: 'x' }, + { lastTickMs: -5 }, + { lastTickMs: undefined }, + { status: 'running' }, + { status: 7 }, + ]) bad.push({ ...good, ...patch }) + + for (const value of bad) expect(parseLoop(value), JSON.stringify(value)).toBeNull() + }) + + it('does not trust extra fields and does not return the stored object', () => { + const stored = { ...(serializeLoop(state()) as object), evil: 'x', __proto__: { polluted: 1 } } + const parsed = parseLoop(stored) as LoopState + + expect(parsed).toEqual(state()) + expect(Object.keys(parsed)).not.toContain('evil') + expect(parsed).not.toBe(stored) + }) +}) + +describe('tick plan', () => { + const base = (patch: Partial = {}): TickInput => ({ mission: mission(), loop: state({ lastTickMs: T0, ticks: 1 }), prefs: DEFAULT_LOOP, gatesConfigured: false, spendUsd: null, capUsd: null, nowMs: T0 + 5 * MIN, ...patch }) + const ev = (seq: number, type: string, taskId?: string, status?: string) => ({ seq, atMs: T0, type, ...(taskId !== undefined && { taskId }), ...(status !== undefined && { status }) }) + const done = (...ids: string[]) => ids.map((id, i) => ev(i + 1, 'task.completed', id, 'completed')) + + it('runs the next task when nothing blocks', () => { + expect(tickPlan(base())).toEqual({ action: 'run-next', reason: 'hand over the next ready task' }) + }) + + it('stops for a cancelled mission, a finished one and a reached spend cap', () => { + expect(tickPlan(base({ mission: mission({ cancelled: true }) })).action).toBe('stop') + expect(tickPlan(base({ mission: mission({ events: done('t1', 't2') }) }))).toMatchObject({ action: 'stop', reason: expect.stringContaining('every task is done') }) + expect(tickPlan(base({ spendUsd: 5, capUsd: 5 }))).toMatchObject({ action: 'stop', reason: expect.stringContaining('cap') }) + expect(tickPlan(base({ spendUsd: 7.5, capUsd: 5 })).action).toBe('stop') + expect(tickPlan(base({ spendUsd: 4.99, capUsd: 5 })).action).toBe('run-next') + }) + + it('has no cap without a cap, a spend figure or a positive cap', () => { + expect(tickPlan(base({ spendUsd: 100, capUsd: null })).action).toBe('run-next') + expect(tickPlan(base({ spendUsd: null, capUsd: 5 })).action).toBe('run-next') + expect(tickPlan(base({ spendUsd: 100, capUsd: 0 })).action).toBe('run-next') + }) + + it('stop beats wait: a cancelled paused mission stops', () => { + expect(tickPlan(base({ mission: mission({ cancelled: true, paused: true }) })).action).toBe('stop') + }) + + it('a loop that was stopped or is done tells Claude to cancel its task', () => { + expect(tickPlan(base({ loop: state({ status: 'stopped' }) }))).toMatchObject({ action: 'stop', reason: expect.stringContaining('cancel') }) + expect(tickPlan(base({ loop: state({ status: 'done' }) })).action).toBe('stop') + }) + + it('waits while paused, while a task runs, and until the interval has passed', () => { + expect(tickPlan(base({ mission: mission({ paused: true }) })).action).toBe('wait') + expect(tickPlan(base({ mission: mission({ events: [ev(1, 'task.dispatched', 't1', 'in_progress')] }) }))).toMatchObject({ action: 'wait', reason: 'a task is still running' }) + expect(tickPlan(base({ nowMs: T0 + 2 * MIN })).action).toBe('wait') + expect(tickPlan(base({ nowMs: T0 + 4.5 * MIN })).action).toBe('run-next') + expect(tickPlan(base({ loop: state(), nowMs: T0 + MIN })).action).toBe('run-next') + }) + + it('prefers the task store status over the ledger events', () => { + const taskStatus = new Map([['t1', 'running' as const], ['t2', 'waiting' as const]]) + + expect(tickPlan(base({ taskStatus }))).toMatchObject({ action: 'wait', reason: 'a task is still running' }) + expect(tickPlan(base({ taskStatus: new Map([['t1', 'done' as const], ['t2', 'done' as const]]) })).action).toBe('stop') + }) + + it('rearms an expired loop (by status or by the clock) but not a paused mission', () => { + expect(tickPlan(base({ loop: state({ status: 'expired' }) })).action).toBe('rearm') + expect(tickPlan(base({ nowMs: T0 + LOOP_LIFETIME_MS })).action).toBe('rearm') + expect(tickPlan(base({ loop: state({ status: 'expired' }), mission: mission({ paused: true }) })).action).toBe('wait') + }) + + it('runs the gates after a finished task when gates are configured, once', () => { + const finished = mission({ events: done('t1') }) + + expect(tickPlan(base({ mission: finished, gatesConfigured: true }))).toMatchObject({ action: 'run-gates' }) + expect(tickPlan(base({ mission: finished, gatesConfigured: false })).action).toBe('run-next') + expect(tickPlan(base({ mission: mission({ events: [...done('t1'), ev(9, GATE_EVENT)] }), gatesConfigured: true })).action).toBe('run-next') + expect(tickPlan(base({ mission: mission(), gatesConfigured: true })).action).toBe('run-next') + }) + + it('a failed task does not count as running or done', () => { + const failed = mission({ events: [ev(1, 'task.failed', 't1', 'failed')] }) + + expect(tickPlan(base({ mission: failed })).action).toBe('run-next') + }) + + it('a mission with no tasks never reads as finished', () => { + expect(tickPlan(base({ mission: mission({ tasks: [] }) })).action).toBe('run-next') + }) +}) + +describe('loop rows', () => { + type El = { kind: string; props: Record } + const kit = { Box: (props: Record): El => ({ kind: 'Box', props }), Text: (props: Record): El => ({ kind: 'Text', props }), Button: (props: Record): El => ({ kind: 'Button', props }) } + const ctx = { kit, state: { view: 'missions', sections: new Set() }, nowMs: T0, columns: 100, pictures: new Map(), act: {} } as unknown as Ctx + const flat = (value: unknown): El[] => (Array.isArray(value) ? value.flatMap(flat) : value !== null && typeof value === 'object' && 'kind' in value ? [value as El, ...flat((value as El).props.children)] : []) + const make = (loop: LoopState | null, nowMs = T0 + MIN) => { + const actions = { start: vi.fn(), stop: vi.fn(), rearm: vi.fn() } + const els = flat(loopRows(ctx, loop, actions, nowMs)) + + return { actions, els, texts: els.filter(e => e.kind === 'Text').map(e => String(e.props.children)), buttons: els.filter(e => e.kind === 'Button') } + } + + it('with no loop shows only Start, and the ownership note', () => { + const { texts, buttons, actions } = make(null) + + expect(buttons.map(b => b.props.label)).toEqual(['Start loop']) + expect(texts.join('\n')).toContain('no loop') + expect(texts.some(t => t.includes('Claude owns the schedule'))).toBe(true) + ;(buttons[0]?.props.onPress as () => void)() + expect(actions.start).toHaveBeenCalledTimes(1) + expect(actions.stop).not.toHaveBeenCalled() + }) + + it('an armed loop shows its facts and only Stop', () => { + const { texts, buttons, actions } = make(state({ ticks: 3, lastTickMs: T0 })) + + expect(texts.join('\n')).toContain('armed · 3 ticks') + expect(texts.join('\n')).toContain('time to expiry') + expect(buttons.map(b => b.props.label)).toEqual(['Stop loop']) + ;(buttons[0]?.props.onPress as () => void)() + expect(actions.stop).toHaveBeenCalledTimes(1) + }) + + it('warns in the last 24 hours', () => { + const s = state({ ticks: 3, lastTickMs: T0 + LOOP_LIFETIME_MS - 2 * HOUR }) + const { texts, els } = make(s, T0 + LOOP_LIFETIME_MS - HOUR) + + expect(texts.some(t => t.includes('Expires within 24 hours'))).toBe(true) + expect(els.some(e => e.kind === 'Text' && String(e.props.children).includes('Expires within') && e.props.color !== undefined)).toBe(true) + expect(make(state({ lastTickMs: T0 }), T0 + MIN).texts.some(t => t.includes('Expires within'))).toBe(false) + }) + + it('shows Re-arm for an expired, stopped or overdue loop; Stop only while it may still be running', () => { + for (const [loop, at, labels] of [ + [state({ status: 'expired' }), T0 + MIN, ['Re-arm loop']], + [state({ status: 'stopped' }), T0 + MIN, ['Re-arm loop']], + [state(), T0 + 20 * MIN, ['Stop loop', 'Re-arm loop']], + [state(), T0 + LOOP_LIFETIME_MS + 1, ['Re-arm loop']], + ] as const) { + const { buttons, actions } = make(loop, at) + + expect(buttons.map(b => b.props.label)).toEqual(labels) + ;(buttons.at(-1)?.props.onPress as () => void)() + expect(actions.rearm).toHaveBeenCalledTimes(1) + } + }) + + it('a done loop has no buttons; disclaimer lines stay under 50 characters', () => { + expect(make(state({ status: 'done' })).buttons).toEqual([]) + + const dim = make(null).els.filter(e => e.kind === 'Text' && e.props.dimColor === true).map(e => String(e.props.children)).filter(t => t.includes('Claude owns') || t.includes('prepares')) + + expect(dim.length).toBeGreaterThan(0) + for (const line of dim) expect(line.length).toBeLessThan(50) + }) +}) diff --git a/plugins/ruflo-console/tests/mission-verify.spec.ts b/plugins/ruflo-console/tests/mission-verify.spec.ts new file mode 100644 index 0000000000..2223132f35 --- /dev/null +++ b/plugins/ruflo-console/tests/mission-verify.spec.ts @@ -0,0 +1,227 @@ +import { describe, expect, it } from 'vitest' + +import { evidenceEvent, GATES_ROW, gateSpec, parseGates, verdictOf, type Gate } from '../hooks/mission-verify' +import type { LedgerEvent, MissionRecord } from '../hooks/mission-types' + +const gate = (line: string): Gate => parseGates(line).gates[0]! +const unit = gate('npm test') +const lint = gate('npm run lint') + +const missionOf = (events: LedgerEvent[]): MissionRecord => ({ id: 'm1', objective: 'o', profile: 'feature', rigor: 'standard', tasks: [], acceptance: [], events, paused: false, cancelled: false, auto: false, createdAtMs: 0 }) as MissionRecord +const ev = (seq: number, type: string, extra: Partial = {}): LedgerEvent => ({ seq, atMs: seq, type, taskId: 't1', ...extra }) +const gateEv = (seq: number, g: Gate, status: 'passed' | 'failed' | 'unknown', taskId = 't1'): LedgerEvent => ev(seq, 'evidence.gate', { status, taskId, evidenceRef: `gate:${g.id}:${status === 'passed' ? 0 : 1}` }) + +describe('parseGates', () => { + it('splits a line on single spaces into a fixed argv', () => { + const { gates, rejected } = parseGates('npm run lint') + + expect(rejected).toEqual([]) + expect(gates).toHaveLength(1) + expect(gates[0]!.argv).toEqual(['npm', 'run', 'lint']) + expect(gates[0]!.label).toBe('npm run lint') + expect(gates[0]!.id).toMatch(/^g[0-9a-z]+$/) + expect(parseGates('npm run lint').gates[0]!.id).toBe(gates[0]!.id) + expect(parseGates('npm test').gates[0]!.id).not.toBe(gates[0]!.id) + }) + + it.each([ + ['semicolon', 'npm test; rm x'], + ['pipe', 'npm test | tee'], + ['ampersand', 'npm test &'], + ['redirect out', 'npm test > out'], + ['redirect in', 'npm test < in'], + ['backtick', 'echo `id`'], + ['command substitution', 'echo $(id)'], + ['control character', 'npm\ttest'], + ['leading dash', '-rf /'], + ['double space', 'npm test'], + ])('rejects %s and says why', (_name, line) => { + const { gates, rejected } = parseGates(line) + + expect(gates).toEqual([]) + expect(rejected).toHaveLength(1) + expect(rejected[0]!.why.length).toBeGreaterThan(5) + }) + + it('allows a dash after the first word', () => { + expect(parseGates('cargo test -p x --lib').gates[0]!.argv).toEqual(['cargo', 'test', '-p', 'x', '--lib']) + }) + + it('splits lines on newlines and on a literal backslash-n, skipping empty lines', () => { + expect(parseGates('a\n\n \nb\r\nc').gates.map(g => g.label)).toEqual(['a', 'b', 'c']) + expect(parseGates('a\\nb').gates.map(g => g.label)).toEqual(['a', 'b']) + }) + + it('keeps the first 4 gates and reports the rest', () => { + const { gates, rejected } = parseGates('a\nb\nc\nd\ne\nf') + + expect(gates.map(g => g.label)).toEqual(['a', 'b', 'c', 'd']) + expect(rejected.map(r => r.line)).toEqual(['e', 'f']) + expect(rejected[0]!.why).toMatch(/first 4/) + }) + + it('refuses a line over 200 characters and accepts exactly 200', () => { + expect(parseGates('x'.repeat(201)).rejected[0]!.why).toMatch(/200/) + expect(parseGates('x'.repeat(200)).gates).toHaveLength(1) + }) + + it('reports a duplicate command once and gives nothing for non-text', () => { + expect(parseGates('npm test\nnpm test')).toMatchObject({ gates: [{ label: 'npm test' }], rejected: [{ why: expect.stringMatching(/already/) }] }) + expect(parseGates(undefined)).toEqual({ gates: [], rejected: [] }) + expect(parseGates(42)).toEqual({ gates: [], rejected: [] }) + expect(parseGates('')).toEqual({ gates: [], rejected: [] }) + }) + + it('does not let a rejected line use up a gate slot', () => { + expect(parseGates('a;b\nb\nc\nd\ne').gates).toHaveLength(4) + }) +}) + +describe('gateSpec', () => { + it('asks first, shows the exact argv, and says what is recorded', () => { + const spec = gateSpec(unit) + + expect(spec.label).toBe('run gate: npm test') + expect(spec.argv).toEqual(['npm', 'test']) + expect(spec.shows).toBe('npm test') + expect(spec.isReadOnly).toBe(false) + expect(spec.expect).toMatch(/exit code/) + expect(spec.expect).toMatch(/output summary/) + expect(spec.expect).toMatch(/evidence/) + }) + + it('takes plumbing from baseSpec but never the argv, label or read-only flag', () => { + const run = async () => {} + const spec = gateSpec(unit, { run, scope: 'goal', timeoutMs: 5, isReadOnly: true, argv: ['rm', '-rf', '/'], label: 'harmless', shows: 'nothing' }) + + expect(spec.run).toBe(run) + expect(spec.scope).toBe('goal') + expect(spec.timeoutMs).toBe(5) + expect(spec.isReadOnly).toBe(false) + expect(spec.argv).toEqual(['npm', 'test']) + expect(spec.label).toBe('run gate: npm test') + expect(spec.shows).toBe('npm test') + }) + + it('does not share the gate’s argv array', () => { + const spec = gateSpec(unit) + + expect(spec.argv).not.toBe(unit.argv) + }) +}) + +describe('evidenceEvent', () => { + it('summarises a pass: exit code, line count and the first line', () => { + const out = Array.from({ length: 12 }, (_v, i) => `line ${i}`).join('\n') + const event = evidenceEvent(unit, { exitCode: 0, stdout: out, stderr: '' }, 't1') + + expect(event).toEqual({ type: 'evidence.gate', taskId: 't1', status: 'passed', note: 'exit 0, 12 lines of output: line 0', evidenceRef: `gate:${unit.id}:0` }) + }) + + it('a non-zero exit is failed; null is unknown', () => { + expect(evidenceEvent(unit, { exitCode: 2, stdout: '', stderr: 'boom' }).status).toBe('failed') + expect(evidenceEvent(unit, { exitCode: 2, stdout: '', stderr: 'boom' }).note).toBe('exit 2, 1 line of output: boom') + + const unknown = evidenceEvent(unit, { exitCode: null, stdout: '', stderr: '' }) + + expect(unknown.status).toBe('unknown') + expect(unknown.evidenceRef).toBe(`gate:${unit.id}:none`) + expect(unknown.note).toMatch(/no exit code/) + expect(unknown).not.toHaveProperty('taskId') + }) + + it('caps the first line at 120 characters and strips control characters', () => { + const event = evidenceEvent(unit, { exitCode: 1, stdout: `\u001b[31mred\u0007 ${'y'.repeat(300)}`, stderr: '' }) + const shown = event.note.split(': ')[1]! + + expect(shown.length).toBeLessThanOrEqual(120) + expect(event.note).not.toMatch(/[\u0000-\u001f]/) + expect(event.note).not.toContain('[31m') + }) + + it('says no output when there is none, and falls back to stderr for the first line', () => { + expect(evidenceEvent(unit, { exitCode: 0, stdout: '', stderr: '' }).note).toBe('exit 0, no output') + expect(evidenceEvent(unit, { exitCode: 1, stdout: '\n\n', stderr: 'e1\ne2' }).note).toBe('exit 1, 2 lines of output: e1') + }) +}) + +describe('verdictOf', () => { + it('says no-gates when none are configured, even with old evidence', () => { + const mission = missionOf([gateEv(1, unit, 'passed')]) + + expect(verdictOf(mission, 't1', [])).toMatchObject({ state: 'no-gates', passed: 0, failed: 0 }) + expect(verdictOf(missionOf([]), 't1')).toMatchObject({ state: 'no-gates' }) + }) + + it('verifies when every gate’s latest result is a pass', () => { + const mission = missionOf([gateEv(1, unit, 'passed'), gateEv(2, lint, 'passed')]) + + expect(verdictOf(mission, 't1')).toMatchObject({ state: 'verified', passed: 2, failed: 0 }) + }) + + it('a later pass after a fail does not count while the fail is newer than the pass, and clears it once the pass is newer', () => { + expect(verdictOf(missionOf([gateEv(1, unit, 'passed'), gateEv(2, unit, 'failed')]), 't1')).toMatchObject({ state: 'failed', failed: 1 }) + expect(verdictOf(missionOf([gateEv(1, unit, 'failed'), gateEv(2, unit, 'passed')]), 't1')).toMatchObject({ state: 'verified', passed: 1, failed: 0 }) + }) + + it('a pass on one gate does not hide a fail on another', () => { + const mission = missionOf([gateEv(1, unit, 'failed'), gateEv(2, lint, 'passed')]) + + expect(verdictOf(mission, 't1')).toMatchObject({ state: 'failed', passed: 1, failed: 1 }) + }) + + it('orders by seq, not by array position', () => { + const mission = missionOf([gateEv(5, unit, 'passed'), gateEv(2, unit, 'failed')]) + + expect(verdictOf(mission, 't1').state).toBe('verified') + }) + + it('a new start wipes the earlier run’s evidence', () => { + const mission = missionOf([gateEv(1, unit, 'failed'), ev(2, 'task.dispatched'), gateEv(3, unit, 'passed')]) + const restarted = missionOf([gateEv(1, unit, 'passed'), ev(2, 'task.dispatched')]) + + expect(verdictOf(mission, 't1').state).toBe('verified') + expect(verdictOf(restarted, 't1', [unit])).toMatchObject({ state: 'unverified', passed: 0 }) + }) + + it('ignores other tasks and other event types', () => { + const mission = missionOf([gateEv(1, unit, 'failed', 't2'), ev(2, 'task.completed', { status: 'failed' }), gateEv(3, unit, 'passed')]) + + expect(verdictOf(mission, 't1').state).toBe('verified') + expect(verdictOf(mission, 't2').state).toBe('failed') + }) + + it('an unknown exit is unverified, never a pass', () => { + expect(verdictOf(missionOf([gateEv(1, unit, 'unknown')]), 't1')).toMatchObject({ state: 'unverified', passed: 0, failed: 0 }) + }) + + it('with the configured gates, an unrun gate keeps the task unverified and a removed gate’s evidence does not count', () => { + const mission = missionOf([gateEv(1, unit, 'passed')]) + + expect(verdictOf(mission, 't1', [unit, lint])).toMatchObject({ state: 'unverified', passed: 1 }) + expect(verdictOf(mission, 't1', [lint]).state).toBe('unverified') + expect(verdictOf(mission, 't1', [unit]).state).toBe('verified') + }) + + it('round-trips an evidenceEvent into a verdict', () => { + const recorded = evidenceEvent(unit, { exitCode: 0, stdout: 'ok', stderr: '' }, 't1') + const mission = missionOf([{ seq: 1, atMs: 1, ...recorded }]) + + expect(verdictOf(mission, 't1', [unit]).state).toBe('verified') + }) +}) + +describe('GATES_ROW', () => { + it('is a text row with the loop-gates id', () => { + expect(GATES_ROW.id).toBe('loop-gates') + expect(GATES_ROW.kind).toBe('text') + expect(GATES_ROW.current({})).toBe('') + expect(GATES_ROW.isChanged({})).toBe(false) + expect(GATES_ROW.isChanged({ loopGates: 'npm test' })).toBe(true) + }) + + it('patches the text, keeping newlines, dropping other control characters and capping length', () => { + expect(GATES_ROW.patch('npm test\nnpm run lint\u0007')).toEqual({ loopGates: 'npm test\nnpm run lint ' .trim() }) + expect(GATES_ROW.patch('x'.repeat(5000)).loopGates.length).toBeLessThanOrEqual(GATES_ROW.maxLength) + }) +}) diff --git a/plugins/ruflo-cost-tracker/.claude-plugin/plugin.json b/plugins/ruflo-cost-tracker/.claude-plugin/plugin.json index 0adbd8778f..a70d367c25 100644 --- a/plugins/ruflo-cost-tracker/.claude-plugin/plugin.json +++ b/plugins/ruflo-cost-tracker/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "ruflo-cost-tracker", "description": "Token usage tracking, model cost attribution per agent, budget alerts, and optimization recommendations — uses memory_* (namespace-routed) for cost-tracking and cost-patterns; pairs with federation budget circuit breaker (ADR-097)", - "version": "0.27.0", + "version": "0.27.1", "author": { "name": "ruvnet", "url": "https://github.com/ruvnet" diff --git a/plugins/ruflo-cost-tracker/scripts/_ledger.mjs b/plugins/ruflo-cost-tracker/scripts/_ledger.mjs index cb569e4f4a..693ed06b82 100644 --- a/plugins/ruflo-cost-tracker/scripts/_ledger.mjs +++ b/plugins/ruflo-cost-tracker/scripts/_ledger.mjs @@ -133,10 +133,22 @@ export function* codexRows({ sinceMs = 0 } = {}) { export const READERS = { claude: claudeRows, codex: codexRows }; -/** Rows for the chosen providers (default all), oldest first. */ -export function collect({ providers = Object.keys(READERS), sinceMs = 0 } = {}) { +/** True when `row.project` is `project` itself or a directory inside it (a trailing slash on `project` is ignored). */ +export function inProject(row, project) { + const root = project.length > 1 ? project.replace(/\/+$/, '') : project; + const at = typeof row.project === 'string' ? row.project : ''; + + return at === root || at.startsWith(`${root}/`); +} + +/** + * Rows for the chosen providers (default all), oldest first. `untilMs` (inclusive) and `project` narrow the window; + * with neither, the result is exactly what it was before they existed. + */ +export function collect({ providers = Object.keys(READERS), sinceMs = 0, untilMs = Infinity, project = '' } = {}) { const rows = []; for (const name of providers) if (READERS[name]) rows.push(...READERS[name]({ sinceMs })); + const kept = untilMs === Infinity && project === '' ? rows : rows.filter(row => row.ts <= untilMs && (project === '' || inProject(row, project))); - return rows.sort((a, b) => a.ts - b.ts); + return kept.sort((a, b) => a.ts - b.ts); } diff --git a/plugins/ruflo-cost-tracker/scripts/ledger.mjs b/plugins/ruflo-cost-tracker/scripts/ledger.mjs index e8f03c7143..52d0e84b5e 100644 --- a/plugins/ruflo-cost-tracker/scripts/ledger.mjs +++ b/plugins/ruflo-cost-tracker/scripts/ledger.mjs @@ -3,6 +3,8 @@ // // node ledger.mjs [--since 7d|24h|all] [--provider claude|codex|all] [--format json|markdown] [--advise] // --advise adds the optimisation findings (advise.mjs) from the same single pass over the logs. +// --from --to --project narrow the rows to a time window (inclusive) and to one project +// (row.project is the path or inside it); JSON then carries `window`. A bad ISO time or a relative path exits 2. // // Reads local logs only; sends nothing anywhere. Prices come from data/prices.json // (dated). USD and Codex credits are NEVER added together, and an unpriced model @@ -67,14 +69,42 @@ function markdown(summary, meta) { return lines.join('\n'); } +const bad = message => { console.error(`ledger: ${message}`); process.exit(2); }; + +/** An ISO time as epoch ms; anything else (relative words, bare numbers, a missing value) exits 2. */ +function isoMs(name) { + const value = arg(name); + if (value === undefined || !/^\d{4}-\d{2}-\d{2}/.test(value) || !Number.isFinite(Date.parse(value))) bad(`--${name} needs an ISO time such as 2026-10-04T09:30:00Z`); + + return Date.parse(value); +} + +/** An absolute POSIX path with no control characters or `..`; anything else exits 2. */ +function absolutePath(name) { + const value = arg(name); + if (typeof value !== 'string' || !value.startsWith('/') || /[\u0000-\u001f\u007f]/.test(value) || value.split('/').includes('..')) bad(`--${name} needs an absolute path with no '..'`); + + return value; +} + if (import.meta.url === `file://${process.argv[1]}`) { - const sinceSpec = arg('since', '7d'); - const sinceMs = sinceSpec === 'all' ? 0 : Date.now() - (parseDurationMs(sinceSpec) ?? 7 * 86_400_000); + const given = name => process.argv.includes(`--${name}`); + const fromMs = given('from') ? isoMs('from') : null; + const toMs = given('to') ? isoMs('to') : null; + const project = given('project') ? absolutePath('project') : null; + if (fromMs !== null && toMs !== null && fromMs > toMs) bad('--from is after --to'); + const windowed = fromMs !== null || toMs !== null || project !== null; + + // An explicit window replaces the default 7-day look-back; an explicit --since still narrows it. + const sinceSpec = given('since') || !windowed ? arg('since', '7d') : 'window'; + const spanMs = sinceSpec === 'all' || sinceSpec === 'window' ? 0 : Date.now() - (parseDurationMs(sinceSpec) ?? 7 * 86_400_000); + const sinceMs = Math.max(spanMs, fromMs ?? 0); const providers = arg('provider', 'all') === 'all' ? undefined : [arg('provider')]; - const rows = collect({ providers, sinceMs }); + const rows = collect({ providers, sinceMs, ...(toMs !== null && { untilMs: toMs }), ...(project !== null && { project }) }); const summary = summarise(rows); const meta = { since: sinceSpec, priceDate: bookDate() }; const findings = process.argv.includes('--advise') ? advise(rows) : undefined; + const window = windowed ? { window: { from: fromMs === null ? null : new Date(fromMs).toISOString(), to: toMs === null ? null : new Date(toMs).toISOString(), project } } : {}; - console.log(arg('format', 'markdown') === 'json' ? JSON.stringify({ ...meta, ...summary, ...(findings && { findings }) }, null, 2) : markdown(summary, meta)); + console.log(arg('format', 'markdown') === 'json' ? JSON.stringify({ ...meta, ...summary, ...window, ...(findings && { findings }) }, null, 2) : markdown(summary, meta)); } diff --git a/plugins/ruflo-cost-tracker/scripts/smoke.sh b/plugins/ruflo-cost-tracker/scripts/smoke.sh index ec2cd4e5b2..e801060ba8 100755 --- a/plugins/ruflo-cost-tracker/scripts/smoke.sh +++ b/plugins/ruflo-cost-tracker/scripts/smoke.sh @@ -1,5 +1,5 @@ #!/usr/bin/env bash -# Structural smoke test for ruflo-cost-tracker v0.27.0. +# Structural smoke test for ruflo-cost-tracker v0.27.1. set -u ROOT="$(cd "$(dirname "$0")/.." && pwd)" PASS=0 @@ -8,10 +8,10 @@ step() { printf "→ %s ... " "$1"; } ok() { printf "PASS\n"; PASS=$((PASS+1)); } bad() { printf "FAIL: %s\n" "$1"; FAIL=$((FAIL+1)); } -step "1. plugin.json declares 0.27.0 with new keywords" +step "1. plugin.json declares 0.27.1 with new keywords" v=$(grep -E '"version"' "$ROOT/.claude-plugin/plugin.json" | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1) -if [[ "$v" != "0.27.0" ]]; then - bad "expected 0.27.0, got '$v'" +if [[ "$v" != "0.27.1" ]]; then + bad "expected 0.27.1, got '$v'" else miss="" for k in namespace-routing mcp agentic-flow agent-booster tier1-routing model-routing benchmarking verified telemetry budget projection forecast counterfactual drift-detection trend-alert anomaly-detection outlier-detection health-check composite-gate auto-track stop-hook snapshot-diff pr-regression git-context traceability drill-down per-message; do diff --git a/plugins/ruflo-cost-tracker/scripts/test-ledger.mjs b/plugins/ruflo-cost-tracker/scripts/test-ledger.mjs index 91c5d4ba0b..6300da9618 100644 --- a/plugins/ruflo-cost-tracker/scripts/test-ledger.mjs +++ b/plugins/ruflo-cost-tracker/scripts/test-ledger.mjs @@ -95,5 +95,59 @@ test('openrouter: a key in the environment is never echoed', () => { assert.ok(!(r.stdout + r.stderr).includes('SECRET123')); }); +// ── Window and project filters, through the real script, on their own fixture logs. +const win = mkdtempSync(join(tmpdir(), 'ledger-window-')); +mkdirSync(join(win, 'claude', 'projects', 'q'), { recursive: true }); +mkdirSync(join(win, 'codex'), { recursive: true }); +const at = (iso, id, cwd) => ({ type: 'assistant', sessionId: `s-${id}`, cwd, requestId: `r-${id}`, timestamp: iso, message: { id, role: 'assistant', model: 'claude-opus-5-5', usage: { input_tokens: 1000, output_tokens: 0 } } }); +jsonl(join(win, 'claude', 'projects', 'q', 'w.jsonl'), [ + at('2026-10-01T00:00:00.000Z', 'before', '/proj/a'), + at('2026-10-02T00:00:00.000Z', 'start', '/proj/a'), // exactly on --from: inclusive + at('2026-10-02T12:00:00.000Z', 'sub', '/proj/a/sub'), + at('2026-10-02T13:00:00.000Z', 'sibling', '/proj/ab'), // shares the prefix text, not the directory + at('2026-10-02T14:00:00.000Z', 'other', '/proj/b'), + at('2026-10-03T00:00:00.000Z', 'end', '/proj/a'), // exactly on --to: inclusive + at('2026-10-04T00:00:00.000Z', 'after', '/proj/a'), +]); +const ledger = (...flags) => { + const r = spawnSync(process.execPath, [join(HERE, 'ledger.mjs'), '--format', 'json', ...flags], { encoding: 'utf-8', env: { PATH: process.env.PATH, CLAUDE_CONFIG_DIR: join(win, 'claude'), CODEX_HOME: join(win, 'codex') } }); + + return { ...r, json: r.status === 0 ? JSON.parse(r.stdout) : null }; +}; +const FROM = '2026-10-02T00:00:00Z'; +const TO = '2026-10-03T00:00:00Z'; + +test('window: --from/--to keep rows inside the window, both ends inclusive, in every project', () => { + const r = ledger('--from', FROM, '--to', TO); + assert.equal(r.json.rows, 5); + assert.deepEqual(r.json.window, { from: '2026-10-02T00:00:00.000Z', to: '2026-10-03T00:00:00.000Z', project: null }); +}); +test('window: a --from older than 7 days is honoured (it replaces the default look-back)', () => assert.equal(ledger('--from', '2026-10-01T00:00:00Z').json.rows, 7)); +test('window: --project matches the path and its subdirectories, not a sibling sharing the prefix', () => { + const r = ledger('--from', FROM, '--to', TO, '--project', '/proj/a'); + assert.equal(r.json.rows, 3); // start, sub, end — not /proj/ab, not /proj/b + assert.equal(r.json.window.project, '/proj/a'); +}); +test('window: a trailing slash on --project is ignored; --project alone has no time limit', () => { + assert.equal(ledger('--project', '/proj/a/').json.rows, 5); + assert.equal(ledger('--project', '/proj/b').json.rows, 1); +}); +test('window: the JSON keeps every existing field', () => { + const r = ledger('--from', FROM, '--project', '/proj/a'); + for (const key of ['since', 'priceDate', 'totals', 'byProvider', 'byModel', 'byDay', 'unpriced', 'approx', 'cache', 'rows', 'tokens']) assert.ok(key in r.json, key); +}); +test('window: without the flags the output has no window and counts every row', () => { + const r = ledger('--since', 'all'); + assert.equal(r.json.rows, 7); + assert.ok(!('window' in r.json)); +}); +test('window: an invalid ISO time, a missing value, or a relative path exits 2 with a message', () => { + for (const flags of [['--from', 'yesterday'], ['--to', '5'], ['--from'], ['--project', 'proj/a'], ['--project', '/proj/../etc'], ['--from', TO, '--to', FROM]]) { + const r = ledger(...flags); + assert.equal(r.status, 2, flags.join(' ')); + assert.match(r.stderr, /^ledger: /, flags.join(' ')); + } +}); + if (failed > 0) { console.log(`\n${failed} failed`); process.exit(1); } console.log('\nall passed'); diff --git a/plugins/ruflo-cost-tracker/skills/cost-ledger/SKILL.md b/plugins/ruflo-cost-tracker/skills/cost-ledger/SKILL.md index 20ed594b47..1b106db177 100644 --- a/plugins/ruflo-cost-tracker/skills/cost-ledger/SKILL.md +++ b/plugins/ruflo-cost-tracker/skills/cost-ledger/SKILL.md @@ -1,7 +1,7 @@ --- name: cost-ledger description: One cost view across Claude Code and Codex on this machine — spend, tokens, cache hit ratio per provider and model, with unpriced models flagged. Use when asked "what did I spend", "how much did Codex cost", or to compare providers. Local logs only, nothing is sent. -argument-hint: "[--since 7d|24h|all] [--provider claude|codex|all] [--format json|markdown]" +argument-hint: "[--since 7d|24h|all] [--from --to ] [--project ] [--provider claude|codex|all] [--format json|markdown]" allowed-tools: Bash --- @@ -16,6 +16,10 @@ node ${CLAUDE_PLUGIN_ROOT}/scripts/ledger.mjs --since 7d node ${CLAUDE_PLUGIN_ROOT}/scripts/ledger.mjs --provider codex --format json ``` +## One mission, or one project + +`--from` and `--to` (ISO times) cut the window and `--project ` keeps one project's rows; the console's mission page uses them for a mission's spend. An explicit `--from`/`--to` replaces the default 7-day look-back. + ## Read the result correctly - **USD and Codex credits are never added.** GPT-6 Codex models are priced in credits; their cached-input rate is unpublished, so the figure is an upper bound. diff --git a/v3/docs/adr/ADR-438-research-integration-contract.md b/v3/docs/adr/ADR-438-research-integration-contract.md index 359a02ca7c..22abc97340 100644 --- a/v3/docs/adr/ADR-438-research-integration-contract.md +++ b/v3/docs/adr/ADR-438-research-integration-contract.md @@ -1,6 +1,6 @@ # ADR 438: Research integration: the deep-researcher record, the console section and the guard -Status: Proposed +Status: Accepted (shipped in ruflo-console 0.28.0 and its companion plugins, PR #3667) Date: 2026 10 04 diff --git a/v3/docs/adr/ADR-439-console-research-start-and-confirm.md b/v3/docs/adr/ADR-439-console-research-start-and-confirm.md index 61cce14318..fb09af3570 100644 --- a/v3/docs/adr/ADR-439-console-research-start-and-confirm.md +++ b/v3/docs/adr/ADR-439-console-research-start-and-confirm.md @@ -1,6 +1,6 @@ # ADR 439: Console research start and confirm -Status: Proposed +Status: Accepted (shipped in ruflo-console 0.28.0 and its companion plugins, PR #3667) Date: 2026 10 04 diff --git a/v3/docs/adr/ADR-440-research-web-fetch-guard.md b/v3/docs/adr/ADR-440-research-web-fetch-guard.md index 84ac778183..9f1e93f01e 100644 --- a/v3/docs/adr/ADR-440-research-web-fetch-guard.md +++ b/v3/docs/adr/ADR-440-research-web-fetch-guard.md @@ -1,6 +1,6 @@ # ADR 440: Research web-fetch guard -Status: Proposed +Status: Accepted (shipped in ruflo-console 0.28.0 and its companion plugins, PR #3667) Date: 2026 10 04 diff --git a/v3/docs/adr/ADR-441-loop-centric-missions.md b/v3/docs/adr/ADR-441-loop-centric-missions.md index 39bb6b012e..5a6bc497fe 100644 --- a/v3/docs/adr/ADR-441-loop-centric-missions.md +++ b/v3/docs/adr/ADR-441-loop-centric-missions.md @@ -1,6 +1,6 @@ # ADR 441: Loop-centric missions: settings, guidance and plan phases -Status: Proposed +Status: Accepted (shipped in ruflo-console 0.28.0 and its companion plugins, PR #3667) Date: 2026 10 04 diff --git a/v3/docs/adr/ADR-442-console-sandbox-page-and-plugins-in-tools.md b/v3/docs/adr/ADR-442-console-sandbox-page-and-plugins-in-tools.md index a5efe91779..5f8cf8dd07 100644 --- a/v3/docs/adr/ADR-442-console-sandbox-page-and-plugins-in-tools.md +++ b/v3/docs/adr/ADR-442-console-sandbox-page-and-plugins-in-tools.md @@ -1,6 +1,6 @@ # ADR 442: A Sandbox page in the console, and Plugins moves to TOOLS -Status: Proposed +Status: Accepted (shipped in ruflo-console 0.28.0 and its companion plugins, PR #3667) Date: 2026 10 04 diff --git a/v3/docs/adr/ADR-443-mission-claude-integration.md b/v3/docs/adr/ADR-443-mission-claude-integration.md new file mode 100644 index 0000000000..15fa10e60f --- /dev/null +++ b/v3/docs/adr/ADR-443-mission-claude-integration.md @@ -0,0 +1,39 @@ +# ADR 443: Missions that Claude knows about, verified evidence, mission spend and a loop manager + +Status: Accepted (ships in ruflo-console 0.29.0 with ruflo-cost-tracker 0.27.1) + +Date: 2026 10 04 + +Scope: `plugins/ruflo-console` (new `mission-context.ts`, `mission-verify.ts`, `mission-loop.ts`, `data/mission-cost.ts` and their views; wiring in `register.ts`, `mission-control.ts`, `settings.ts`), `plugins/ruflo-cost-tracker` (`ledger.mjs` window and project filters) + +Builds on: ADR-406 (missions), ADR-437 (cost ledger), ADR-441 (loop-centric missions) + +## 1. Why + +A mission today is text handed to Claude one task at a time. Claude does not know the mission between hand-offs, "done" is whatever gets recorded, spend is not tied to a mission, and the loop settings of ADR-441 are guidance, not behaviour. Long missions also need something to start, watch and re-arm their loop: a recurring `/loop` task expires after 7 days and lives only in its session. + +## 2. Decision + +Four capabilities, built as pure modules with their own tests; the integrator wires them into the existing files. + +1. **Mission context in Claude's prompt** (`mission-context.ts`). A `prompt.compose` hook adds one `session`-scope section (id `ruflo-console:mission`): the objective, the active task, its acceptance checks, the evidence rule, the stop rule. It changes only when the mission, the active task, its status, paused/cancelled or the loop on/off changes, never per turn: a changed system prompt makes Claude re-read the whole conversation at cache-write price, so churn costs money. At most 1200 characters; a Settings row `missionContext` (default on) turns it off. A `turn.complete` hook notes the turn in the ledger; completion still comes from the ruflo task store, which stays the authority. +2. **Verify** (`mission-verify.ts`). A task is "done" with evidence. Gates are the person's own commands (Settings row `loopGates`: up to 4 lines, each 1 to 200 characters, split on spaces into a fixed argv, never a shell, no `;`, `|`, `&`, `>`, `<`, `` ` ``, `$(`, newline or leading `-`). Running a gate asks first with the exact argv; its exit code and a short output summary are recorded as an evidence event. With no gates configured the page says so; nothing is invented. +3. **Mission spend** (`data/mission-cost.ts` and the ledger filters). The cost ledger gains `--from`, `--to` (ISO times) and `--project` (a path prefix) so the console can ask for the spend inside a mission's time window in its project. The mission shows spend, an optional cap (USD) and the ADR-437 ladder (50, 75, 90, 100 percent); auto-run pauses at the cap. Numbers are list-price estimates and say so; unpriced models are listed, not counted as $0. +4. **Loop manager** (`mission-loop.ts`). For a long-running mission it prepares, tracks and re-arms the `/loop`: + - **Start:** prepares `/loop ` in the main UI (asks first). The prompt carries a marker `[mission: loop]` so a tick is recognised when it arrives. + - **State:** `{ missionId, interval, startedAtMs, expiresAtMs (start + 7 days), ticks, lastTickMs, status: 'idle'|'armed'|'stopped'|'expired'|'done' }`, serialised with the mission so it survives a restart. Ticks are counted from submitted prompts that carry the marker. + - **Watch:** next-tick estimate, tick count, last tick, time to expiry, a warning inside the last 24 hours, and "overdue" when no tick arrived for three intervals. + - **Stop and re-arm:** Stop prepares the request to cancel the recurring task (Claude owns `CronDelete`); Re-arm prepares a fresh `/loop` with the same prompt. The console never schedules anything itself. + - **Tick plan:** a pure function turns state, settings, spend and the mission into what the tick should do (run the next ready task, run the gates, wait, or stop with the reason). Finish and stop rules come from ADR-441; push and publish stay off unless the setting says otherwise. + +## 3. Safety + +- No capability sends anything over the network. Gate commands and the loop hand-off always ask first and show the exact text. +- The context section contains only the mission's own fields, each capped, with control characters stripped; it never includes file contents, secrets or fetched text. +- A gate is never run silently by auto-run unless the person turned on a setting for it; the default is off. + +## 4. Not decided here + +- Parallel task hand-out in worktrees (plan data exists; the runner stays one task at a time). +- Starting a mission from an issue or PR URL, templates, Markdown export. +- Whether Claude Code's `prompt.compose` section is shown in the cache accounting as expected: UNVERIFIED, to be measured in a live session.