Skip to content

armgit / ruflo

Public Imported from GitHub
0

๐ŸŒŠ The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated

feat(ruflo-console): 0.11.0 โ€” Mission Control: lifecycle planner, claude -p guidance, inline confirms, menu strip, hotkeys for every view

ruv4aa8e5ca4316
diff --git a/plugins/ruflo-console/.claude-plugin/plugin.json b/plugins/ruflo-console/.claude-plugin/plugin.json
index 4699a4bf42..ff2e2b857b 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; no network by default.",
- "version": "0.10.0",
+ "version": "0.11.0",
"author": {
"name": "ruvnet",
"url": "https://github.com/ruvnet"
diff --git a/plugins/ruflo-console/hooks/actions.ts b/plugins/ruflo-console/hooks/actions.ts
index c1857d71d7..7aa354a6c0 100644
--- a/plugins/ruflo-console/hooks/actions.ts
+++ b/plugins/ruflo-console/hooks/actions.ts
@@ -18,6 +18,8 @@ export type ActionSpec = {
isReadOnly?: boolean
/** Not a ruflo CLI call: what runs instead once confirmed (a terminal harness), reporting for itself. */
run?: () => Promise<void>
+ /** Where the ask came from in its view (`goal`, `controls`, `guide`): a view that draws its own confirm puts it under that field. */
+ scope?: string
/** The command line the confirm row shows when it is not `ruflo <args>`. */
shows?: string
/** A MetaHarness lab entry's id: the runner keeps what it printed for the lab's result panel. */
diff --git a/plugins/ruflo-console/hooks/bindings.ts b/plugins/ruflo-console/hooks/bindings.ts
index b58a7337b6..e4e235ab89 100644
--- a/plugins/ruflo-console/hooks/bindings.ts
+++ b/plugins/ruflo-console/hooks/bindings.ts
@@ -5,6 +5,7 @@
import { claimTask, handoffClaim, releaseClaim, stealClaim, whyNot } from './actions'
import { EVENT_KINDS } from './data/events'
import { evolveActions } from './evolve'
+import { missionActions } from './mission-control'
import { catalogActions } from './plugin-catalog'
import { saveAllowed } from './remember'
import { pluginNames, settingsActions } from './settings'
@@ -81,6 +82,11 @@ export function actionsOf(state: State, host: Host, runner: Runner, steps: Steps
void host.storeSet(NAV_KEY, style).catch(() => undefined)
host.invalidate()
},
+ editField: (key, text) => {
+ state.fieldText.set(key, text)
+ host.invalidate()
+ host.after(60, () => void host.focus(PANE_ID, key).catch(() => undefined))
+ },
clearField: key => {
state.fieldText.set(key, '')
host.invalidate()
@@ -317,6 +323,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),
catalog: catalogActions(state, host, runner, text => actions.term.load('claude', text)),
devtools: devtoolsActions(state, host, runner.runById, why => runner.ask(null, why)),
}
diff --git a/plugins/ruflo-console/hooks/commands.ts b/plugins/ruflo-console/hooks/commands.ts
index f8476af424..f19c45a268 100644
--- a/plugins/ruflo-console/hooks/commands.ts
+++ b/plugins/ruflo-console/hooks/commands.ts
@@ -48,6 +48,11 @@ export function parseRuflo(args: string): Intent {
case 'palette':
case 'p':
return { kind: 'palette', query: rest }
+ // `/ruflo plan <goal>` prints the SPARC plan; `/ruflo mission [status|next|pause|resume|cancel|create|guide <text>|aside <text>|auto on|off]`.
+ case 'plan':
+ return { kind: 'run', paletteId: 'mission-goal', text: rest }
+ case 'mission':
+ return { kind: 'run', paletteId: `mission-${second === '' ? 'status' : second.replace(/[^a-z-]/g, '')}`, text: rest.slice(second.length).trim() }
case 'run':
case 'act':
return second === '' ? { kind: 'palette', query: '' } : { kind: 'run', paletteId: second, text: rest.slice(second.length).trim() }
diff --git a/plugins/ruflo-console/hooks/controller.ts b/plugins/ruflo-console/hooks/controller.ts
index a55cc916cd..affef82737 100644
--- a/plugins/ruflo-console/hooks/controller.ts
+++ b/plugins/ruflo-console/hooks/controller.ts
@@ -14,6 +14,7 @@ import { markPicture } from './gfx/pictures'
import type { Host } from './host'
import { agentLogs } from './ops'
import { createRunner, type Runner } from './runner'
+import { advance, loadLedger } from './mission-control'
import { loadAllowed } from './remember'
import { loadAiPrefs } from './settings'
import { openLoaders } from './view-open'
@@ -311,6 +312,7 @@ export function createController(state: State, host: Host): Controller {
// The AI terminal's saved model and budget apply from the first turn, not only once Settings was opened.
void loadAiPrefs(state, host)
void loadAllowed(state, host)
+ void loadLedger(state, host)
void host.storeGet(NAV_KEY).then(saved => {
const style = NAV_STYLES.find(candidate => candidate === saved)
@@ -324,7 +326,10 @@ export function createController(state: State, host: Host): Controller {
// Nothing on screen reads the disk: re-read only on the idle cadence, so a closed console costs nearly nothing.
if (isSeen || now - lastIdleMs >= IDLE_REFRESH_MS) {
lastIdleMs = now
- void refresh().then(() => probe())
+ void refresh().then(() => {
+ void probe()
+ advance(state, host)
+ })
}
})
every('activity', ACTIVITY_BUCKET_MS, () => {
diff --git a/plugins/ruflo-console/hooks/data/parse.ts b/plugins/ruflo-console/hooks/data/parse.ts
index 765018edd5..f324bdf30a 100644
--- a/plugins/ruflo-console/hooks/data/parse.ts
+++ b/plugins/ruflo-console/hooks/data/parse.ts
@@ -67,7 +67,20 @@ export const msOf = (value: unknown): number | undefined => {
export type SwarmInfo = { id: string; topology: string; status: string; maxAgents?: number; strategy?: string; agentIds: string[]; updatedAt?: string }
export type AgentRecord = { id: string; type: string; name?: string; status: string; health?: number; taskCount?: number; createdAtMs?: number }
-export type TaskRecord = { id: string; type: string; description: string; status: string; assignedTo: string[]; createdAtMs?: number }
+export type TaskRecord = {
+ id: string
+ type: string
+ description: string
+ status: string
+ assignedTo: string[]
+ createdAtMs?: number
+ /** `mission:<id>` / `task:<id>` style labels (plain words only), as `task_create` stored them. */
+ tags?: string[]
+ startedAtMs?: number
+ completedAtMs?: number
+ /** What `task_complete` / `task_update` recorded as the result, flattened to `key: value` text (bounded). */
+ resultText?: string
+}
export type Claimant = { kind: 'agent' | 'human'; id: string; agentType?: string; name?: string }
export type ClaimRecord = {
issueId: string
@@ -208,6 +221,20 @@ export function parseAgents(text: string | null): AgentRecord[] {
}
/** `.claude-flow/tasks/store.json`. */
+/** A task's result object as one bounded line of `key: value` pairs (strings and numbers only), or undefined. */
+function resultTextOf(value: unknown): string | undefined {
+ const result = recordOf(value)
+
+ if (result === null) return typeof value === 'string' ? plain(value, 400) || undefined : undefined
+
+ const text = Object.entries(result)
+ .slice(0, 8)
+ .flatMap(([key, v]) => (typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean' ? [`${plain(key, 24)}: ${plain(String(v), 160)}`] : []))
+ .join(' ยท ')
+
+ return text === '' ? undefined : text.slice(0, 500)
+}
+
export function parseTasks(text: string | null): TaskRecord[] {
return valuesOf(jsonObject(text)?.tasks).flatMap(entry => {
const task = recordOf(entry)
@@ -223,6 +250,10 @@ export function parseTasks(text: string | null): TaskRecord[] {
status: stringOf(task.status, 20) ?? 'unknown',
assignedTo: (Array.isArray(task.assignedTo) ? task.assignedTo : []).slice(0, 50).flatMap(agent => (idOf(agent) !== null ? [agent as string] : [])),
...(msOf(task.createdAt) !== undefined && { createdAtMs: msOf(task.createdAt) }),
+ tags: (Array.isArray(task.tags) ? task.tags : []).slice(0, 12).flatMap(tag => (typeof tag === 'string' && /^[A-Za-z0-9_.:-]{1,90}$/.test(tag) ? [tag] : [])),
+ ...(msOf(task.startedAt) !== undefined && { startedAtMs: msOf(task.startedAt) }),
+ ...(msOf(task.completedAt) !== undefined && { completedAtMs: msOf(task.completedAt) }),
+ ...(resultTextOf(task.result) !== undefined && { resultText: resultTextOf(task.result) }),
},
]
})
diff --git a/plugins/ruflo-console/hooks/dispatch.ts b/plugins/ruflo-console/hooks/dispatch.ts
index ff424cc86c..57666e03fb 100644
--- a/plugins/ruflo-console/hooks/dispatch.ts
+++ b/plugins/ruflo-console/hooks/dispatch.ts
@@ -12,6 +12,7 @@ import { loadEvolve } from './evolve'
import { labAnswer } from './mh-lab'
import { skillsAnswer } from './skills-lab'
import { VIEWS, type State } from './state'
+import { missionAnswer } from './mission-text'
import { xruvAnswer } from './xruv'
import { barText } from './views/bar'
import { viewText } from './views/pane'
@@ -127,7 +128,7 @@ export async function dispatch(control: Controller, state: State, args: string,
return { text: [`Asked: ${pending.label}. Confirm with /ruflo yes (or y in the pane), cancel with /ruflo no.`, ...(pending.shows === undefined ? [] : [`runs: ${pending.shows}`, pending.note ?? ''])].filter(Boolean).join('\n') }
}
- return { text: (xruvAnswer(state, intent.paletteId, askedAtMs) ?? labAnswer(state, intent.paletteId, askedAtMs) ?? skillsAnswer(state, intent.paletteId, askedAtMs)) ?? (state.outcome !== null && !state.outcome.ok ? `${state.outcome.label}: ${state.outcome.detail}` : (state.outcome?.label ?? 'done')) }
+ return { text: (missionAnswer(state, intent.paletteId) ?? xruvAnswer(state, intent.paletteId, askedAtMs) ?? labAnswer(state, intent.paletteId, askedAtMs) ?? skillsAnswer(state, intent.paletteId, askedAtMs)) ?? (state.outcome !== null && !state.outcome.ok ? `${state.outcome.label}: ${state.outcome.detail}` : (state.outcome?.label ?? 'done')) }
}
case 'confirm':
if (state.pending === null) return { text: 'Nothing is waiting for a confirm.' }
diff --git a/plugins/ruflo-console/hooks/goap.ts b/plugins/ruflo-console/hooks/goap.ts
new file mode 100644
index 0000000000..1c2433b391
--- /dev/null
+++ b/plugins/ruflo-console/hooks/goap.ts
@@ -0,0 +1,325 @@
+/**
+ * A goal-oriented action planner (GOAP) over the SPARC method. The world is a set of facts (specified, architected,
+ * tested, ...); an action has preconditions, effects and a cost; the planner finds the cheapest action sequence that
+ * reaches the goal's facts with A*, then reads the task graph off the preconditions (an action depends on the actions
+ * that produced the facts it needs), so independent branches (pseudocode beside architecture) are parallel. The goal
+ * changes with the kind of work (profile) and how thorough it must be (rigor), so a lean bug fix and a thorough security
+ * change plan differently from the same action library. Pure: no I/O, deterministic for the same input.
+ *
+ * Every mission follows one lifecycle, whatever the work: Research, Create (specification, design, ADRs and the SOP), Build,
+ * Test, Validate, Secure, Benchmark, Learn (the outcome is stored and the router and neural patterns trained, so the next
+ * mission starts better). Lean drops the middle stages; standard and thorough run them all. Underneath, SPARC phases order the work:
+ *
+ * SPARC phases: S specification, P pseudocode, A architecture, R refinement (tests first, then the change), C completion
+ * (integrate, document, verify); X is a cross-cutting gate (review, security review, benchmark).
+ */
+
+export type Profile = 'feature' | 'bugfix' | 'refactor' | 'security' | 'research'
+export type Rigor = 'lean' | 'standard' | 'thorough'
+export type Phase = 'S' | 'P' | 'A' | 'R' | 'C' | 'X'
+
+export const PROFILES: readonly { id: Profile; label: string; about: string }[] = [
+ { id: 'feature', label: 'feature', about: 'research, specify, design + ADRs, tests first, build, validate, secure, benchmark, learn' },
+ { id: 'bugfix', label: 'bug fix', about: 'research, reproduce, diagnose, a regression test first, fix, validate, secure, learn' },
+ { id: 'refactor', label: 'refactor', about: 'research, pin behaviour, redesign + ADRs, change, validate, secure, benchmark, learn' },
+ { id: 'security', label: 'security', about: 'research, threat model, design + ADRs, tests first, build, secure, benchmark, learn' },
+ { id: 'research', label: 'research', about: 'research the prior art, specify the question, investigate, write it up, learn' },
+]
+export const RIGORS: readonly Rigor[] = ['lean', 'standard', 'thorough']
+
+export const PHASE_NAME: Record<Phase, string> = { S: 'Specification', P: 'Pseudocode', A: 'Architecture', R: 'Refinement', C: 'Completion', X: 'Gate' }
+
+export type Action = { id: string; phase: Phase; title: string; needs: readonly string[]; gives: readonly string[]; cost: number; agent: string; requirement: string }
+
+const act = (id: string, phase: Phase, title: string, needs: readonly string[], gives: readonly string[], cost: number, agent: string, requirement: string): Action => ({ id, phase, title, needs, gives, cost, agent, requirement })
+
+/** Every action the planner may use; a profile's goal decides which of them a plan needs. */
+const LIBRARY: readonly Action[] = [
+ act('research-context', 'S', 'Research prior art, existing ADRs and memory', [], ['context-researched'], 2, 'researcher', 'what already exists (code, ADRs, memory patterns) and what is reusable, with sources'),
+ act('specify', 'S', 'Specify the requirements and acceptance criteria', [], ['specified'], 2, 'specification', 'a written specification with testable acceptance criteria'),
+ act('reproduce', 'S', 'Reproduce the problem with a failing case', [], ['reproduced'], 2, 'tester', 'a deterministic failing reproduction'),
+ act('diagnose', 'S', 'Diagnose the root cause', ['reproduced'], ['diagnosed'], 3, 'researcher', 'the root cause named, with evidence from the code'),
+ act('baseline', 'S', 'Pin current behaviour with characterization tests', [], ['baselined'], 3, 'tester', 'tests that pass on the unchanged code and fail if behaviour moves'),
+ act('threat-model', 'S', 'Threat-model the change', [], ['threat-modeled'], 3, 'security-architect', 'a threat list with the mitigation each one needs'),
+ act('investigate', 'S', 'Investigate the question', ['specified'], ['researched'], 4, 'researcher', 'findings with sources, and what is still unknown'),
+ act('pseudocode', 'P', 'Write the pseudocode for the core logic', ['specified'], ['pseudocoded'], 2, 'pseudocode', 'step-by-step logic covering every acceptance criterion'),
+ act('fix-design', 'P', 'Design the smallest fix', ['diagnosed'], ['pseudocoded', 'architected'], 2, 'architecture', 'the minimal change that removes the cause'),
+ act('architect', 'A', 'Design the architecture and interfaces', ['specified'], ['architected'], 3, 'architecture', 'modules, interfaces and data flow, with the decisions recorded'),
+ act('architect-refactor', 'A', 'Design the target structure', ['baselined'], ['architected', 'pseudocoded'], 3, 'architecture', 'the target structure and the steps to reach it'),
+ act('architect-secure', 'A', 'Design the secure structure', ['threat-modeled'], ['architected', 'pseudocoded'], 3, 'security-architect', 'a design that closes each modeled threat'),
+ act('record-decisions', 'A', 'Record the decisions as ADRs and write the SOP', ['architected', 'context-researched'], ['adr-recorded'], 2, 'adr-architect', 'an ADR per decision and a short SOP for running and changing it, linked from the code'),
+ act('tests-first', 'R', 'Write the failing tests first', ['architected', 'pseudocoded'], ['tests-written'], 4, 'tester', 'tests that fail for the right reason before the change'),
+ act('implement', 'R', 'Implement until the tests pass', ['tests-written'], ['implemented'], 6, 'coder', 'the change, with the new tests passing and no others broken'),
+ act('verify-tests', 'R', 'Run the full test suite', ['implemented'], ['tested'], 3, 'tester', 'the whole suite green, the output kept as evidence'),
+ act('review', 'X', 'Review the change', ['implemented'], ['reviewed'], 3, 'reviewer', 'a review with every finding resolved or accepted'),
+ act('security-review', 'X', 'Security review', ['implemented'], ['secured'], 4, 'security-auditor', 'no open high-severity finding'),
+ act('benchmark', 'X', 'Benchmark against the baseline', ['implemented'], ['benchmarked'], 4, 'performance-engineer', 'measurements no worse than the baseline'),
+ act('document', 'C', 'Document the change', ['implemented'], ['documented'], 2, 'api-docs', 'the docs match the shipped behaviour'),
+ act('integrate', 'C', 'Integrate: build and CI', ['tested'], ['integrated'], 3, 'cicd-engineer', 'the build and CI checks pass'),
+ act('verify', 'C', 'Validate the result against the goal', ['tested', 'integrated'], ['verified'], 2, 'production-validator', 'every acceptance criterion checked by something other than the author'),
+ act('learn', 'C', 'Learn: store the outcome and self-optimize', ['verified'], ['learned'], 2, 'reasoningbank-learner', 'the outcome stored as patterns (memory and trajectory) and routing trained on it, so the next mission starts better'),
+ act('learn-findings', 'C', 'Learn: store the findings and self-optimize', ['researched'], ['learned'], 2, 'reasoningbank-learner', 'the findings stored as patterns with their sources, so the next investigation starts better'),
+ act('write-up', 'C', 'Write up the findings', ['researched'], ['documented'], 2, 'researcher', 'a readable write-up a reader can act on'),
+]
+
+/** The lifecycle every mission follows, in order. */
+export const STAGES = ['Research', 'Create', 'Build', 'Test', 'Validate', 'Secure', 'Benchmark', 'Learn'] as const
+export type Stage = (typeof STAGES)[number]
+
+const STAGE_OF: Record<string, Stage> = {
+ 'research-context': 'Research', investigate: 'Research', reproduce: 'Research', diagnose: 'Research', baseline: 'Research', 'threat-model': 'Research',
+ specify: 'Create', pseudocode: 'Create', 'fix-design': 'Create', architect: 'Create', 'architect-refactor': 'Create', 'architect-secure': 'Create', 'record-decisions': 'Create', 'write-up': 'Create',
+ 'tests-first': 'Build', implement: 'Build', document: 'Build',
+ 'verify-tests': 'Test', integrate: 'Test',
+ review: 'Validate', verify: 'Validate',
+ 'security-review': 'Secure',
+ benchmark: 'Benchmark',
+ learn: 'Learn', 'learn-findings': 'Learn',
+}
+
+export const stageOf = (action: Action): Stage => STAGE_OF[action.id] ?? 'Build'
+
+/** Facts the goal needs, by profile, then by what thoroughness adds or drops. Lean is the core; standard runs the whole lifecycle. */
+function goalOf(profile: Profile, rigor: Rigor): string[] {
+ const base: Record<Profile, string[]> = {
+ feature: ['specified', 'architected', 'tested', 'integrated', 'verified'],
+ bugfix: ['reproduced', 'diagnosed', 'tested', 'integrated', 'verified'],
+ refactor: ['baselined', 'tested', 'integrated', 'verified'],
+ security: ['threat-modeled', 'tested', 'secured', 'integrated', 'verified'],
+ research: ['specified', 'researched', 'documented'],
+ }
+ const goal = [...base[profile]]
+
+ if (rigor === 'lean') return profile === 'research' ? ['specified', 'researched'] : goal
+
+ goal.push('context-researched', 'learned')
+ if (profile === 'research') return [...new Set(goal)]
+
+ goal.push('reviewed', 'secured')
+ if (profile !== 'bugfix') goal.push('adr-recorded', 'benchmarked')
+ if (profile === 'feature') goal.push('documented')
+ if (rigor === 'thorough') goal.push('documented', 'adr-recorded', 'benchmarked', ...(profile === 'security' ? [] : ['threat-modeled']))
+
+ return [...new Set(goal)]
+}
+
+const key = (facts: ReadonlySet<string>) => [...facts].sort().join('|')
+
+export type Step = { id: string; action: Action; dependsOn: string[]; wave: number; gives: readonly string[] }
+
+export type Plan = {
+ profile: Profile
+ rigor: Rigor
+ goal: string[]
+ steps: Step[]
+ /** Task ids by wave: everything in a wave can run at once. */
+ waves: string[][]
+ totalCost: number
+ /** The most expensive chain of dependent steps: the plan cannot finish faster than this. */
+ criticalCost: number
+}
+
+/** The facts that can matter: the goal's, and (backward) the preconditions of any action that gives a fact that matters. */
+function relevantFacts(goal: readonly string[]): Set<string> {
+ const relevant = new Set(goal)
+ let grew = true
+
+ while (grew) {
+ grew = false
+
+ for (const action of LIBRARY) {
+ if (!action.gives.some(fact => relevant.has(fact))) continue
+
+ for (const fact of action.needs) {
+ if (!relevant.has(fact)) {
+ relevant.add(fact)
+ grew = true
+ }
+ }
+ }
+ }
+
+ return relevant
+}
+
+type Node = { facts: ReadonlySet<string>; g: number; f: number; path: readonly Action[] }
+
+/** A binary min-heap on f, then on path length, then on the path's action ids (so ties are deterministic). */
+class Heap {
+ private items: Node[] = []
+ private before = (x: Node, y: Node) => (x.f - y.f || x.path.length - y.path.length || x.path.map(step => step.id).join().localeCompare(y.path.map(step => step.id).join())) < 0
+
+ get size() {
+ return this.items.length
+ }
+
+ push(node: Node): void {
+ const items = this.items
+ let i = items.push(node) - 1
+
+ while (i > 0) {
+ const parent = (i - 1) >> 1
+
+ if (!this.before(items[i] as Node, items[parent] as Node)) break
+ ;[items[i], items[parent]] = [items[parent] as Node, items[i] as Node]
+ i = parent
+ }
+ }
+
+ pop(): Node {
+ const items = this.items
+ const top = items[0] as Node
+ const last = items.pop() as Node
+
+ if (items.length > 0) {
+ items[0] = last
+
+ let i = 0
+
+ for (;;) {
+ const left = 2 * i + 1
+ const right = left + 1
+ let small = i
+
+ if (left < items.length && this.before(items[left] as Node, items[small] as Node)) small = left
+ if (right < items.length && this.before(items[right] as Node, items[small] as Node)) small = right
+ if (small === i) break
+ ;[items[i], items[small]] = [items[small] as Node, items[i] as Node]
+ i = small
+ }
+ }
+
+ return top
+ }
+}
+
+/** The cheapest plan to the goal by A* over fact sets, or null when the goal cannot be reached. */
+export function plan(profile: Profile, rigor: Rigor): Plan | null {
+ const goal = goalOf(profile, rigor)
+ const relevant = relevantFacts(goal)
+ // Only actions that give a fact that matters can be on a cheapest path.
+ const actions = LIBRARY.filter(action => action.gives.some(fact => relevant.has(fact)))
+ const cheapestFor = (fact: string) => Math.min(...actions.filter(action => action.gives.includes(fact)).map(action => action.cost), Number.POSITIVE_INFINITY)
+ // Admissible: the dearest single unmet goal fact must still be paid for by some action.
+ const heuristic = (facts: ReadonlySet<string>) => Math.max(0, ...goal.filter(fact => !facts.has(fact)).map(cheapestFor).filter(Number.isFinite))
+ const open = new Heap()
+ const best = new Map<string, number>([['', 0]])
+
+ open.push({ facts: new Set(), g: 0, f: heuristic(new Set()), path: [] })
+
+ while (open.size > 0) {
+ const node = open.pop()
+
+ if (goal.every(fact => node.facts.has(fact))) return build(profile, rigor, goal, node.path)
+
+ for (const action of actions) {
+ if (!action.needs.every(fact => node.facts.has(fact)) || action.gives.every(fact => node.facts.has(fact))) continue
+
+ const facts = new Set([...node.facts, ...action.gives].filter(fact => relevant.has(fact)))
+ const g = node.g + action.cost
+ const k = key(facts)
+
+ if (best.has(k) && (best.get(k) as number) <= g) continue
+
+ best.set(k, g)
+ open.push({ facts, g, f: g + heuristic(facts), path: [...node.path, action] })
+ }
+ }
+
+ return null
+}
+
+/** Reads the task graph off the preconditions: a step depends on the steps that produced the facts it needs. */
+function build(profile: Profile, rigor: Rigor, goal: string[], path: readonly Action[]): Plan {
+ const producer = new Map<string, string>()
+ const steps: Step[] = []
+
+ for (const [i, action] of path.entries()) {
+ const id = `t${i + 1}`
+ const dependsOn = [...new Set(action.needs.map(fact => producer.get(fact)).filter((dep): dep is string => dep !== undefined))]
+
+ for (const fact of action.gives) producer.set(fact, id)
+ steps.push({ id, action, dependsOn, wave: 0, gives: action.gives })
+ }
+
+ // Waves: a step runs one wave after the latest of its dependencies.
+ for (const step of steps) step.wave = step.dependsOn.length === 0 ? 0 : Math.max(...step.dependsOn.map(dep => (steps.find(candidate => candidate.id === dep) as Step).wave)) + 1
+
+ const waves: string[][] = []
+
+ for (const step of steps) (waves[step.wave] ??= []).push(step.id)
+
+ const cost = new Map<string, number>()
+
+ for (const step of steps) cost.set(step.id, step.action.cost + Math.max(0, ...step.dependsOn.map(dep => cost.get(dep) ?? 0)))
+
+ return { profile, rigor, goal, steps, waves, totalCost: path.reduce((sum, action) => sum + action.cost, 0), criticalCost: Math.max(0, ...cost.values()) }
+}
+
+/** Profile read from the goal's words: a bug, a refactor, a vulnerability, a question; otherwise a feature. */
+export function profileOf(objective: string): Profile {
+ const text = objective.toLowerCase()
+
+ if (/\b(bug|fix|broken|crash|regression|fails?|error|defect)\b/.test(text)) return 'bugfix'
+ if (/\b(security|vulnerab\w*|cve|exploit|injection|xss|csrf|auth(?:entication|orization)?|harden)\b/.test(text)) return 'security'
+ if (/\b(refactor|clean ?up|restructure|simplify|rename|reorgani[sz]e|tidy)\b/.test(text)) return 'refactor'
+ if (/\b(research|investigate|explain|explore|compare|evaluate|study|why does)\b/.test(text)) return 'research'
+
+ return 'feature'
+}
+
+const FACT_CHECK: Record<string, string> = {
+ specified: 'a specification exists and every requirement has a testable acceptance criterion',
+ reproduced: 'the problem is reproduced by a deterministic failing case',
+ diagnosed: 'the root cause is identified with evidence',
+ baselined: 'characterization tests pass on the unchanged code',
+ 'threat-modeled': 'a threat model lists each threat and its mitigation',
+ architected: 'the design is written down: modules, interfaces and decisions',
+ researched: 'findings are recorded with their sources',
+ tested: 'the whole test suite passes, including the new tests',
+ reviewed: 'review findings are resolved or explicitly accepted',
+ secured: 'no open high-severity security finding',
+ benchmarked: 'measurements are no worse than the baseline',
+ documented: 'documentation matches the shipped behaviour',
+ integrated: 'build and CI checks pass',
+ verified: 'every acceptance criterion is checked by something other than the author',
+ 'context-researched': 'prior art, existing ADRs and memory are searched and what is reusable is recorded',
+ 'adr-recorded': 'each decision is an ADR and a short SOP says how to run and change it',
+ learned: 'the outcome is stored as patterns and routing is trained on it',
+}
+
+const ID = /[^A-Za-z0-9._-]/g
+
+/** The plan as `mission_plan`'s plan body: tasks run by the Claude Code session itself (session-bound), a criterion per goal fact, and a ceiling. */
+export function toMissionPlan(p: Plan, budgetMinorPerUnit = 100) {
+ const criterionFor = (fact: string) => `ac-${fact.replace(ID, '-')}`
+ const tasks = p.steps.map(step => ({
+ id: step.id,
+ title: `${PHASE_NAME[step.action.phase]}: ${step.action.title}`.slice(0, 200),
+ dependsOn: step.dependsOn,
+ executor: { mode: 'session-bound' as const, requirement: `${step.action.agent}: ${step.action.requirement}`.slice(0, 200) },
+ capabilityCeiling: [] as string[],
+ estimatedCostMinor: step.action.cost * budgetMinorPerUnit,
+ checkpoint: `${step.action.phase}-${step.action.id}`,
+ acceptanceEvidence: step.gives.filter(fact => p.goal.includes(fact)).map(criterionFor),
+ }))
+ const acceptance = p.goal.map(fact => ({
+ id: criterionFor(fact),
+ check: FACT_CHECK[fact] ?? fact,
+ inputs: [] as string[],
+ producer: p.steps.find(step => step.gives.includes(fact))?.id ?? 'plan',
+ independent: fact === 'verified' || fact === 'reviewed' || fact === 'secured' || fact === 'benchmarked',
+ mandatory: true,
+ }))
+
+ return {
+ tasks,
+ acceptance,
+ budget: { currency: 'USD', ceilingMinor: Math.max(1, Math.round(p.totalCost * budgetMinorPerUnit * 1.25)), concurrency: Math.max(1, ...p.waves.map(wave => wave.length)) },
+ scope: { capabilities: [] as string[] },
+ }
+}
+
+/** The stages a plan runs, in lifecycle order, each with how many steps it holds. */
+export const lifecycleOf = (p: Plan): { stage: Stage; steps: number }[] =>
+ STAGES.map(stage => ({ stage, steps: p.steps.filter(step => stageOf(step.action) === stage).length })).filter(entry => entry.steps > 0)
diff --git a/plugins/ruflo-console/hooks/host.ts b/plugins/ruflo-console/hooks/host.ts
index d6e88dc75a..811b472576 100644
--- a/plugins/ruflo-console/hooks/host.ts
+++ b/plugins/ruflo-console/hooks/host.ts
@@ -40,4 +40,12 @@ export type Host = {
rufloSnapshot: () => Promise<RufloSnapshot>
rufloRoute: () => Promise<RufloRoute | null>
rufloSegment: (text: string | null) => Promise<void>
+ /** Submits a prompt to the primary Claude session as a visible turn of its own (once idle). */
+ submitPrompt: (text: string) => Promise<void>
+ /** Puts text in the prompt box as the draft (the person presses Enter); false where there is no box. */
+ fillPrompt: (text: string) => Promise<boolean>
+ /** The names of the slash commands the session offers now (built-in, plugin and MCP alike). */
+ listCommands: () => Promise<string[]>
+ /** Runs a slash command as if typed (built-in, plugin or MCP); queued until the session is idle. */
+ runSlash: (command: string, args: string) => Promise<{ text?: string } | void>
}
diff --git a/plugins/ruflo-console/hooks/mission-control.ts b/plugins/ruflo-console/hooks/mission-control.ts
new file mode 100644
index 0000000000..4ba631c8c4
--- /dev/null
+++ b/plugins/ruflo-console/hooks/mission-control.ts
@@ -0,0 +1,449 @@
+/**
+ * Mission Control: a goal becomes a SPARC plan (goap.ts), the plan becomes a governed mission (`mission_create`,
+ * `mission_plan`) and one ruflo task per plan node (`task_create`, tagged `mission:<id>` and `task:<tN>`), and the
+ * primary Claude Code session does the work. The ruflo task store is the one authority for execution state: the console
+ * reads it, never infers it. Claude is handed one ready task at a time as a visible prompt (the person confirms it, or
+ * opts into auto-run), records the outcome with `task_complete` (evidence in its result) or `task_update` failed, and the
+ * console moves on. Pause, resume and cancel are the console's own ledger (a session-bound mission has no durable
+ * executor to pause). Every ledger change is an ordered event {seq, type, taskId, status, evidenceRef}.
+ */
+import type { ActionSpec } from './actions'
+import { PHASE_NAME, plan as planOf, stageOf, type Plan, type Profile, profileOf, type Rigor, toMissionPlan } from './goap'
+import type { Host } from './host'
+import { plain, type TaskRecord } from './data/parse'
+import { isAvailable, MISSION_SKILLS, slashOf, GOALS_PLUGIN } from './mission-skills'
+import { offerGuidance } from './mission-guidance'
+import type { Runner } from './runner'
+import { CLI_PREFIXES, type State } from './state'
+import type { Derived, LedgerEvent, LedgerTask, McState, McTab, MissionActions, MissionRecord } from './mission-types'
+
+export type { Derived, LedgerEvent, LedgerTask, McState, McTab, MissionActions, MissionRecord } from './mission-types'
+
+const states = new WeakMap<State, McState>()
+export const LEDGER_KEY = 'mission-ledger'
+
+export function mcOf(state: State): McState {
+ let found = states.get(state)
+
+ if (found === undefined) {
+ found = { goal: '', profile: 'feature', rigor: 'standard', isProfilePicked: false, planned: null, missions: new Map(), active: null, tab: 'plan', lastGuide: '', guidance: null, last: null }
+ states.set(state, found)
+ }
+
+ return found
+}
+
+export const activeMission = (state: State): MissionRecord | null => {
+ const mc = mcOf(state)
+
+ return mc.active === null ? null : (mc.missions.get(mc.active) ?? null)
+}
+
+/** The goal typed in: plans it (a pure computation, nothing is written) with the profile the words or the person chose. */
+export function setGoal(state: State, goal: string): void {
+ const mc = mcOf(state)
+
+ mc.goal = plain(goal, 500).trim()
+ if (!mc.isProfilePicked) mc.profile = profileOf(mc.goal)
+ mc.planned = mc.goal === '' ? null : planOf(mc.profile, mc.rigor)
+}
+
+export function setProfile(state: State, profile: Profile, rigor: Rigor): void {
+ const mc = mcOf(state)
+
+ mc.profile = profile
+ mc.rigor = rigor
+ mc.isProfilePicked = true
+ mc.planned = mc.goal === '' ? null : planOf(profile, rigor)
+}
+
+/** The ruflo task a ledger task is, read from the task store by its id (the store is the authority). */
+export const rufloTaskOf = (tasks: readonly TaskRecord[], task: LedgerTask): TaskRecord | undefined => tasks.find(candidate => candidate.id === task.rufloTaskId)
+
+/** Where a ledger task stands: from the ruflo task store, plus whether its dependencies are done (ready) or not (waiting). */
+export function derive(mission: MissionRecord, tasks: readonly TaskRecord[]): Map<string, Derived> {
+ const out = new Map<string, Derived>()
+
+ for (const task of mission.tasks) {
+ const status = rufloTaskOf(tasks, task)?.status
+ const done = (id: string) => out.get(id) === 'done'
+
+ out.set(task.id, status === 'completed' ? 'done' : status === 'failed' ? 'failed' : status === 'cancelled' ? 'cancelled' : status === 'in_progress' || status === 'running' ? 'running' : task.dependsOn.every(done) ? 'ready' : 'waiting')
+ }
+
+ return out
+}
+
+/** The next task to hand to Claude: the first ready one in plan order, unless something is running, paused or cancelled. */
+export function nextTask(mission: MissionRecord, tasks: readonly TaskRecord[]): LedgerTask | null {
+ if (mission.paused || mission.cancelled) return null
+
+ const status = derive(mission, tasks)
+
+ if ([...status.values()].some(value => value === 'running' || value === 'failed')) return null
+
+ return mission.tasks.find(task => status.get(task.id) === 'ready' && task.rufloTaskId !== undefined) ?? null
+}
+
+export const progressOf = (mission: MissionRecord, tasks: readonly TaskRecord[]) => {
+ const status = derive(mission, tasks)
+
+ return { done: [...status.values()].filter(value => value === 'done').length, total: mission.tasks.length }
+}
+
+/** The instruction handed to the primary session for one task: what, as whom, what it must show, and how to record it. */
+export function instructionOf(mission: MissionRecord, task: LedgerTask): string {
+ const criteria = mission.acceptance.slice(0, 8).map(criterion => `- ${criterion.check}`).join('\n')
+ const deps = task.dependsOn.length === 0 ? 'none' : task.dependsOn.map(id => `${id} (${mission.tasks.find(candidate => candidate.id === id)?.title ?? ''})`).join(', ')
+
+ return [
+ `Mission ${mission.id}: ${mission.objective}`,
+ `Task ${task.id} (${PHASE_NAME[task.phase as keyof typeof PHASE_NAME] ?? task.phase}): ${task.title}`,
+ `Act as: ${task.agent}. It is done when: ${task.requirement}`,
+ `Already done: ${deps}.`,
+ `The mission's acceptance criteria, for context:\n${criteria}`,
+ `When this task is finished, record it: call the ruflo MCP tool task_complete with taskId "${task.rufloTaskId ?? ''}" and a result object {summary, evidence} (evidence = files changed, commands run, test output). If you cannot finish it, call task_update with the same taskId, status "failed" and a result {reason}. Do not complete it unless "it is done when" is true. Keep this transcript to decisions and verified results.`,
+ ].join('\n')
+}
+
+export function record(mission: MissionRecord, event: Omit<LedgerEvent, 'seq' | 'atMs'>): void {
+ const seq = Math.max(0, ...mission.events.map(candidate => candidate.seq)) + 1
+
+ mission.events.push({ seq, atMs: Date.now(), ...event })
+ if (mission.events.length > 500) mission.events.splice(0, mission.events.length - 500)
+}
+
+export function saveLedger(state: State, host: Host): void {
+ const mc = mcOf(state)
+
+ void host.storeSet(LEDGER_KEY, { active: mc.active, missions: [...mc.missions.values()].slice(-20) }).catch(() => undefined)
+}
+
+export async function loadLedger(state: State, host: Host): Promise<void> {
+ const saved = await host.storeGet(LEDGER_KEY).catch(() => undefined)
+ const missions = (saved as { missions?: unknown } | undefined)?.missions
+ const mc = mcOf(state)
+
+ if (!Array.isArray(missions)) return
+
+ for (const raw of missions.slice(0, 20)) {
+ const m = raw as MissionRecord
+
+ if (typeof m?.id === 'string' && /^msn_[a-f0-9]{24}$/.test(m.id) && Array.isArray(m.tasks) && Array.isArray(m.events)) mc.missions.set(m.id, m)
+ }
+
+ const active = (saved as { active?: unknown }).active
+
+ if (typeof active === 'string' && mc.missions.has(active)) mc.active = active
+}
+
+/** `ruflo mcp exec -t <tool> -p <json>` as an argv on the configured CLI prefix. */
+const argvOf = (state: State, tool: string, params: unknown): string[] => [...CLI_PREFIXES[state.options.cli], 'mcp', 'exec', '-t', tool, '-p', JSON.stringify(params)]
+
+/** The JSON object after `Result:` in a tool run's output (the CLI logs around it), or null. */
+export function resultOf(stdout: string): Record<string, unknown> | null {
+ const text = stdout.replace(/\x1b\[[0-9;]*m/g, '')
+ const start = text.indexOf('{', Math.max(0, text.indexOf('Result:')))
+ let depth = 0
+
+ for (let i = start; i >= 0 && i < text.length; i++) {
+ if (text[i] === '{') depth++
+ else if (text[i] === '}' && --depth === 0) {
+ try {
+ return JSON.parse(text.slice(start, i + 1)) as Record<string, unknown>
+ } catch {
+ return null
+ }
+ }
+ }
+
+ return null
+}
+
+const taskType = (profile: Profile) => (profile === 'bugfix' ? 'bugfix' : profile === 'refactor' ? 'refactor' : profile === 'research' ? 'research' : 'feature')
+
+/** Create the mission: `mission_create`, `mission_plan`, then a ruflo task per plan node. One confirm for the chain. */
+export function createSpec(state: State, host: Host, onDone: () => void): ActionSpec | null {
+ const mc = mcOf(state)
+
+ if (mc.planned === null || mc.goal === '') return null
+
+ const planned = mc.planned
+ const body = toMissionPlan(planned)
+ const stamp = Date.now().toString(36)
+
+ return {
+ label: `create the mission and its ${body.tasks.length} tasks: ${plain(mc.goal, 60)}`,
+ scope: 'goal',
+ args: [],
+ argv: argvOf(state, 'mission_create', { requestId: `console-create-${stamp}`, objective: mc.goal }),
+ shows: `mission_create โ†’ mission_plan โ†’ task_create ร— ${body.tasks.length}, each \`ruflo mcp exec -t <tool>\` (${planned.profile}, ${planned.rigor}; ceiling ${body.budget.ceilingMinor / 100} ${body.budget.currency}, a record, not a charge)`,
+ expect: 'a planned mission and its tasks in the ruflo task store',
+ note: 'Writes the mission record and one task per plan node to this projectโ€™s ruflo stores. It runs no agent and spends nothing.',
+ run: async () => {
+ const mission = mc
+ const fail = (label: string, detail: string) => {
+ mission.last = { label, ok: false, detail }
+ host.invalidate()
+ }
+ const call = async (tool: string, params: unknown) => resultOf((await host.run(argvOf(state, tool, params), 60_000)).stdout)
+ const created = await call('mission_create', { requestId: `console-create-${stamp}`, objective: mc.goal })
+ const data = (created?.data ?? {}) as { missionId?: string; revision?: number }
+
+ if (created?.ok !== true || typeof data.missionId !== 'string') return fail('mission_create failed', plain(String(created?.message ?? 'no answer'), 160))
+
+ const id = data.missionId
+ const placed = await call('mission_plan', { requestId: `console-plan-${stamp}`, missionId: id, expectedRevision: data.revision ?? 1, plan: body })
+
+ if (placed?.ok !== true) return fail('mission_plan refused the plan', plain(String(placed?.message ?? 'no answer'), 200))
+
+ const tasks: LedgerTask[] = []
+
+ for (const step of planned.steps) {
+ const task = body.tasks.find(candidate => candidate.id === step.id)
+ const made = await call('task_create', {
+ type: taskType(planned.profile),
+ description: `[${id}/${step.id}] ${task?.title ?? step.action.title}`.slice(0, 200),
+ priority: 'normal',
+ tags: [`mission:${id}`, `task:${step.id}`, `phase:${step.action.phase}`],
+ })
+ const rufloTaskId = typeof made?.taskId === 'string' ? made.taskId : undefined
+
+ tasks.push({ id: step.id, title: step.action.title, phase: step.action.phase, stage: stageOf(step.action), agent: step.action.agent, requirement: step.action.requirement, dependsOn: step.dependsOn, ...(rufloTaskId !== undefined && { rufloTaskId }) })
+ }
+
+ const record0: MissionRecord = {
+ id,
+ objective: mc.goal,
+ profile: planned.profile,
+ rigor: planned.rigor,
+ planDigest: typeof (placed.data as { planDigest?: string } | undefined)?.planDigest === 'string' ? (placed.data as { planDigest: string }).planDigest : undefined,
+ tasks,
+ acceptance: body.acceptance.map(criterion => ({ id: criterion.id, check: criterion.check })),
+ events: [],
+ paused: false,
+ cancelled: false,
+ auto: false,
+ createdAtMs: Date.now(),
+ }
+
+ record(record0, { type: 'mission.created', status: 'draft' })
+ record(record0, { type: 'plan.validated', status: 'planned', evidenceRef: record0.planDigest })
+ record(record0, { type: 'tasks.created', note: `${tasks.filter(task => task.rufloTaskId !== undefined).length} of ${tasks.length}` })
+ mc.missions.set(id, record0)
+ mc.active = id
+ mc.tab = 'tasks'
+ mc.last = { label: `mission ${id} planned`, ok: true, detail: `${tasks.length} tasks in the ruflo task store; โ–ถ Run next hands the first to Claude` }
+ saveLedger(state, host)
+ onDone()
+ host.invalidate()
+ },
+ }
+}
+
+/** Mark one task in progress and hand it to the primary session as a visible prompt. One confirm: it starts a model turn. */
+export function dispatchSpec(state: State, host: Host, mission: MissionRecord, task: LedgerTask, send: (text: string) => Promise<void>): ActionSpec {
+ const text = instructionOf(mission, task)
+
+ return {
+ label: `hand task ${task.id} to Claude: ${task.title}`,
+ scope: 'controls',
+ args: [],
+ shows: `task_update ${task.rufloTaskId ?? ''} in_progress, then this prompt to the Claude Code session: โ€œ${plain(text, 140)}โ€ฆโ€`,
+ expect: 'a visible prompt in the transcript; the task in progress',
+ note: 'Starts a Claude Code turn on your plan (billed as any turn is); the prompt is visible and Claude records the result with task_complete.',
+ run: async () => {
+ await host.run(argvOf(state, 'task_update', { taskId: task.rufloTaskId, status: 'in_progress', progress: 5 }), 60_000)
+ task.dispatchedAtMs = Date.now()
+ record(mission, { type: 'task.dispatched', taskId: task.id, status: 'in_progress', evidenceRef: task.rufloTaskId })
+ saveLedger(state, host)
+ await send(text)
+ mcOf(state).last = { label: `task ${task.id} handed to Claude`, ok: true, detail: 'it is in the transcript now; the pane follows the task store' }
+ host.invalidate()
+ },
+ }
+}
+
+/** Pause or resume dispatching, kept in the ledger (a session-bound mission has no durable executor to pause). */
+export function setPaused(state: State, host: Host, paused: boolean): void {
+ const mission = activeMission(state)
+
+ if (mission === null || mission.cancelled) return
+
+ mission.paused = paused
+ record(mission, { type: paused ? 'mission.paused' : 'mission.resumed', status: paused ? 'paused' : 'running' })
+ mcOf(state).last = { label: paused ? 'paused: no more tasks are handed out' : 'resumed', ok: true, detail: paused ? 'a task already handed to Claude finishes first' : 'Run next hands out the next ready task' }
+ saveLedger(state, host)
+ host.invalidate()
+}
+
+/** Cancel: cancel every task not done in the ruflo task store, then ask the mission record to cancel (allowed only from some states). */
+export function cancelSpec(state: State, host: Host, mission: MissionRecord, tasks: readonly TaskRecord[]): ActionSpec {
+ const open = mission.tasks.filter(task => task.rufloTaskId !== undefined && !['completed', 'cancelled'].includes(rufloTaskOf(tasks, task)?.status ?? ''))
+
+ return {
+ label: `cancel mission ${mission.id} (${open.length} open tasks)`,
+ scope: 'controls',
+ args: [],
+ shows: `task_cancel ร— ${open.length}, then mission_request_action cancel (the record may refuse from its state)`,
+ expect: 'every open task cancelled',
+ note: 'Cancels this missionโ€™s open tasks in the ruflo task store. A task already finished stays finished.',
+ run: async () => {
+ for (const task of open) await host.run(argvOf(state, 'task_cancel', { taskId: task.rufloTaskId, reason: 'mission cancelled from the console' }), 60_000)
+
+ const refused = resultOf((await host.run(argvOf(state, 'mission_request_action', { requestId: `console-cancel-${Date.now().toString(36)}`, missionId: mission.id, expectedRevision: 2, action: 'cancel', reason: 'cancelled from the console' }), 60_000)).stdout)
+
+ mission.cancelled = true
+ record(mission, { type: 'mission.cancelled', status: 'cancelled', note: refused?.ok === true ? 'record cancelled' : `record: ${plain(String(refused?.message ?? 'not asked'), 100)}` })
+ mcOf(state).last = { label: `mission ${mission.id} cancelled`, ok: true, detail: `${open.length} tasks cancelled${refused?.ok === true ? '' : `; the record said: ${plain(String(refused?.message ?? ''), 100)}`}` }
+ saveLedger(state, host)
+ host.invalidate()
+ },
+ }
+}
+
+const MAX_TEXT = 500
+
+
+const wired = new WeakMap<State, { host: Host; actions: MissionActions }>()
+
+/** The host and actions Mission Control was wired with, for the palette and the headless commands. */
+export const missionWired = (state: State) => wired.get(state)
+
+export function missionActions(state: State, host: Host, runner: Runner): MissionActions {
+ const mc = mcOf(state)
+ const say = (label: string, ok: boolean, detail: string) => {
+ mc.last = { label, ok, detail }
+ host.invalidate()
+ }
+ const tasksNow = (): readonly TaskRecord[] => state.snapshot?.tasks ?? []
+
+ const actions: MissionActions = {
+ goal: text => {
+ setGoal(state, text)
+ mc.tab = 'plan'
+ offerGuidance(state, host, runner, mc)
+ host.invalidate()
+ },
+ askGuidance: () => offerGuidance(state, host, runner, mc),
+ profile: profile => {
+ setProfile(state, profile, mc.rigor)
+ host.invalidate()
+ },
+ rigor: rigor => {
+ setProfile(state, mc.profile, rigor)
+ host.invalidate()
+ },
+ tab: tab => {
+ mc.tab = tab
+ host.invalidate()
+ },
+ create: () => runner.ask(createSpec(state, host, () => undefined), 'type a goal first: the plan is made from it'),
+ select: id => {
+ if (mc.missions.has(id)) mc.active = id
+ saveLedger(state, host)
+ host.invalidate()
+ },
+ next: () => {
+ const mission = activeMission(state)
+
+ if (mission === null) return say('no active mission', false, 'create one from a goal first')
+
+ const task = nextTask(mission, tasksNow())
+
+ if (task === null) return say('nothing to hand out', false, mission.paused ? 'the mission is paused' : mission.cancelled ? 'the mission is cancelled' : 'a task is running or failed, or none is ready: see Tasks')
+
+ runner.ask(dispatchSpec(state, host, mission, task, text => host.submitPrompt(text)), 'nothing to hand out')
+ },
+ pause: () => setPaused(state, host, true),
+ resume: () => setPaused(state, host, false),
+ cancel: () => {
+ const mission = activeMission(state)
+
+ runner.ask(mission === null ? null : cancelSpec(state, host, mission, tasksNow()), 'no active mission to cancel')
+ },
+ auto: on => {
+ const mission = activeMission(state)
+
+ if (mission === null) return
+
+ mission.auto = on
+ record(mission, { type: on ? 'auto.on' : 'auto.off' })
+ saveLedger(state, host)
+ host.invalidate()
+ },
+ aside: question => {
+ const q = plain(question, MAX_TEXT).trim()
+
+ if (q === '') return say('ask aside', false, 'type a question first')
+
+ if (state.turnActive) {
+ void host.fillPrompt(`/btw ${q}`).then(
+ isFilled => say(isFilled ? 'prepared in the prompt box' : 'no prompt box here', isFilled, isFilled ? 'press Enter there: /btw answers beside the running task and stays out of the main conversation' : 'run /btw yourself'),
+ () => say('ask aside', false, 'the prompt box refused it'),
+ )
+
+ return
+ }
+
+ void host.runSlash('btw', q).then(
+ () => say('asked /btw', true, 'the answer opens beside the transcript; it is not part of the main conversation'),
+ () => say('ask aside', false, '/btw is not available in this session'),
+ )
+ },
+ skill: id => {
+ const skill = MISSION_SKILLS.find(candidate => candidate.id === id)
+ const objective = activeMission(state)?.objective ?? mc.goal
+
+ if (skill === undefined) return say('skill', false, 'not a ruflo-goals skill')
+ if (!isAvailable(state, skill)) return say(`${slashOf(skill)} is not available`, false, `install the ${GOALS_PLUGIN} plugin (Plugin Catalog) and /reload-plugins`)
+ if (objective.trim() === '') return say(skill.title, false, 'type a goal first: the skill works on it')
+
+ const args = plain(objective, MAX_TEXT)
+
+ if (state.turnActive) {
+ void host.fillPrompt(`/${slashOf(skill)} ${args}`).then(
+ isFilled => say(isFilled ? 'prepared in the prompt box' : 'no prompt box here', isFilled, `press Enter to run /${slashOf(skill)} in the main conversation`),
+ () => say(skill.title, false, 'the prompt box refused it'),
+ )
+
+ return
+ }
+
+ void host.runSlash(slashOf(skill), args).then(
+ () => say(`${skill.title}: /${slashOf(skill)} is running`, true, 'in the main conversation: the pane follows the task store'),
+ () => say(skill.title, false, `/${slashOf(skill)} did not run`),
+ )
+ },
+ guide: text => {
+ const t = plain(text, MAX_TEXT).trim()
+
+ if (t !== '') mc.lastGuide = t
+
+ runner.ask(
+ t === ''
+ ? null
+ : { label: `send Claude: ${plain(t, 70)}`, scope: 'guide', args: [], shows: `to the Claude Code session, as a visible prompt: โ€œ${t}โ€`, expect: 'the instruction in the transcript', note: 'Starts a Claude Code turn (billed as any turn is).', run: async () => host.submitPrompt(t) },
+ 'type the instruction first',
+ )
+ },
+ }
+
+ wired.set(state, { host, actions })
+
+ return actions
+}
+
+/** Auto-run: called after the task store is read. Hands over the next ready task when the mission opted in and Claude is idle. */
+export function advance(state: State, host: Host): void {
+ const mission = activeMission(state)
+
+ if (mission === null || !mission.auto || state.turnActive) return
+
+ const task = nextTask(mission, state.snapshot?.tasks ?? [])
+
+ if (task === null || task.dispatchedAtMs !== undefined) return
+
+ task.dispatchedAtMs = Date.now()
+ void dispatchSpec(state, host, mission, task, text => host.submitPrompt(text)).run?.()
+}
diff --git a/plugins/ruflo-console/hooks/mission-guidance.ts b/plugins/ruflo-console/hooks/mission-guidance.ts
new file mode 100644
index 0000000000..ff897ba333
--- /dev/null
+++ b/plugins/ruflo-console/hooks/mission-guidance.ts
@@ -0,0 +1,188 @@
+/**
+ * Claude's guidance on a mission: after a goal is entered and planned, `claude -p` (plan mode, read-only, under the per-turn
+ * budget from Settings) is given the goal, the plan, the lifecycle and what this installation can do (the ruflo plugins and
+ * skills the session offers, the AI preferences), and asked for detailed guidance: what to do in each stage, which ruflo
+ * capabilities to bring in, what could go wrong. It costs a model turn, so it asks first (scope `goal`, under the goal) unless
+ * "always accept" is set in Settings; "Mission guidance" in Settings turns it off. Its answer is data, drawn as text.
+ */
+import type { ActionSpec } from './actions'
+import { termText } from './harness'
+import type { Host } from './host'
+import { type Plan, lifecycleOf } from './goap'
+import type { McState } from './mission-control'
+import { planText } from './mission-text'
+import type { Runner } from './runner'
+import { settingsOf } from './settings'
+import type { State } from './state'
+import { claudeParser, eventOf, type Sink } from './stream'
+
+export type Guidance = { goal: string; status: 'running' | 'done' | 'failed'; lines: string[]; note: string; stop: (() => void) | null }
+
+/** The most guidance text kept, and the longest wait: a runaway turn ends at five minutes. */
+const MAX_LINES = 400
+const CAP_MS = 5 * 60_000
+
+/** The ruflo plugin names the session's slash commands come from (`ruflo-goals:goal-plan` โ†’ ruflo-goals), the installation's capabilities. */
+export const pluginsOf = (state: State): string[] => [...new Set(state.commandNames.filter(name => name.startsWith('ruflo') && name.includes(':')).map(name => name.slice(0, name.indexOf(':'))))].sort()
+
+export function guidancePrompt(state: State, mc: McState, plan: Plan): string {
+ const ai = settingsOf(state).ai
+ const plugins = pluginsOf(state)
+ const skills = state.commandNames.filter(name => name.startsWith('ruflo') && name.includes(':')).slice(0, 60)
+
+ return [
+ 'You are advising on a ruflo mission. Read-only: do not change any file. Be concrete and specific to this goal.',
+ '',
+ `GOAL: ${mc.goal}`,
+ `Kind: ${plan.profile}. Rigor: ${plan.rigor}. Lifecycle: ${lifecycleOf(plan).map(entry => entry.stage).join(' โ†’ ')}.`,
+ '',
+ 'THE PLAN THE PLANNER MADE:',
+ planText(plan, mc.goal),
+ '',
+ 'THIS INSTALLATION:',
+ `- ruflo plugins loaded in the session: ${plugins.length === 0 ? 'none reported' : plugins.join(', ')}`,
+ `- slash commands and skills available: ${skills.length === 0 ? 'none reported' : skills.join(', ')}`,
+ `- AI settings: claude model ${ai.claudeModel}, turn budget $${ai.budgetUsd}, ${ai.autoAccept ? 'always accept' : 'asks before AI turns'}`,
+ `- Settings level: ${settingsOf(state).level}`,
+ '',
+ 'Write detailed guidance, in markdown with one short heading per lifecycle stage that the plan has (Research, Create (ADRs and the SOP), Build, Test, Validate, Secure, Benchmark, Learn).',
+ 'Under each heading: what to do for THIS goal, the acceptance evidence, and which ruflo capabilities to bring in (name the exact agents, plugins, skills, MCP tools or ruflo commands that fit, and why), preferring what is installed here and saying plainly what is not.',
+ 'Then add: "Suggestions" (other ruflo capabilities worth integrating that the plan does not use, such as swarm or hive-mind for parallel work, memory and pattern search for prior art, AIDefence, MetaHarness audits, the flywheel for self-optimization), and "Risks" (what could go wrong and how the plan guards against it).',
+ 'Keep it under 700 words. No preamble.',
+ ].join('\n')
+}
+
+export function guidanceArgv(state: State): readonly string[] {
+ const ai = settingsOf(state).ai
+
+ return ['claude', '-p', '--output-format', 'stream-json', '--verbose', '--include-partial-messages', '--permission-mode', 'plan', '--max-budget-usd', String(ai.budgetUsd), ...(ai.claudeModel === 'default' ? [] : ['--model', ai.claudeModel])]
+}
+
+/** Runs the guidance turn and fills `mc.guidance` as the answer arrives. */
+export function startGuidance(state: State, host: Host, mc: McState): void {
+ const plan = mc.planned
+
+ if (plan === null || mc.guidance?.status === 'running') return
+
+ const guidance: Guidance = { goal: mc.goal, status: 'running', lines: [], note: 'asking claudeโ€ฆ', stop: null }
+ const startedAtMs = Date.now()
+ let open = false
+ const parse = claudeParser()
+ const add = (text: string) => {
+ for (const line of text.split('\n')) guidance.lines.push(termText(line, 2_000, false))
+
+ if (guidance.lines.length > MAX_LINES) guidance.lines.splice(0, guidance.lines.length - MAX_LINES)
+ }
+ const sink: Sink = {
+ line: (kind, text) => {
+ open = false
+ if (kind === 'err') guidance.note = termText(text, 200)
+ else if (kind === 'out') add(text)
+ },
+ type: text => {
+ const parts = text.split('\n')
+
+ parts.forEach((part, i) => {
+ if (i > 0 || !open || guidance.lines.length === 0) {
+ guidance.lines.push('')
+ open = true
+ }
+
+ guidance.lines[guidance.lines.length - 1] = termText((guidance.lines[guidance.lines.length - 1] ?? '') + part, 2_000, false)
+ })
+ },
+ session: () => undefined,
+ done: ({ costUsd, isError, message }) => {
+ guidance.status = isError === true ? 'failed' : 'done'
+ guidance.note = isError === true ? `โœ— ${message ?? 'failed'}` : `โœ“ ${Math.round((Date.now() - startedAtMs) / 1000)} s${costUsd !== undefined ? ` ยท $${costUsd.toFixed(3)}` : ''}`
+ },
+ }
+
+ mc.guidance = guidance
+
+ let stream: ReturnType<Host['spawn']>
+
+ try {
+ stream = host.spawn(guidanceArgv(state), guidancePrompt(state, mc, plan))
+ } catch (error) {
+ guidance.status = 'failed'
+ guidance.note = `claude did not start: ${error instanceof Error ? error.message : String(error)}`
+ host.invalidate()
+
+ return
+ }
+
+ const stop = () => {
+ guidance.status = guidance.status === 'running' ? 'failed' : guidance.status
+ guidance.note = 'stopped'
+ void stream.return(undefined as never).catch(() => undefined)
+ }
+ const cap = host.after(CAP_MS, stop)
+
+ guidance.stop = stop
+ host.invalidate()
+
+ void (async () => {
+ const partial = { stdout: '', stderr: '' }
+
+ try {
+ for await (const chunk of stream) {
+ const lines = (partial[chunk.stream] + chunk.text).split('\n')
+
+ partial[chunk.stream] = lines.pop() ?? ''
+
+ for (const line of lines) {
+ if (chunk.stream === 'stdout') {
+ const event = eventOf(line)
+
+ if (event !== null) parse(event, sink)
+ }
+ }
+
+ host.invalidate()
+ }
+
+ await stream.result
+
+ if (guidance.status === 'running') {
+ guidance.status = guidance.lines.some(line => line.trim() !== '') ? 'done' : 'failed'
+ guidance.note = guidance.status === 'done' ? 'โœ“ done' : 'claude answered nothing: is it installed, signed in and on PATH?'
+ }
+ } catch (error) {
+ guidance.status = 'failed'
+ guidance.note = `โœ— claude: ${error instanceof Error ? error.message : String(error)} (is it installed and on PATH?)`
+ } finally {
+ cap.cancel()
+ guidance.stop = null
+ host.invalidate()
+ }
+ })()
+}
+
+/** The confirm-gated ask for the guidance turn, drawn under the goal; null with no plan. */
+export function guidanceSpec(state: State, host: Host, mc: McState): ActionSpec | null {
+ if (mc.planned === null) return null
+
+ const argv = guidanceArgv(state)
+
+ return {
+ label: `ask claude -p for detailed guidance on this mission: ${termText(mc.goal.replace(/\s+/g, ' '), 44)}`,
+ scope: 'goal',
+ args: argv,
+ shows: `${argv.join(' ')} (the goal, the plan and this installation's capabilities on stdin)`,
+ expect: 'guidance by lifecycle stage, with the ruflo capabilities to use, in Mission Control',
+ run: async () => startGuidance(state, host, mc),
+ }
+}
+
+/** After a goal is entered: asks for the guidance turn (or runs it at once under "always accept"); off when Settings turned it off. */
+export function offerGuidance(state: State, host: Host, runner: Runner, mc: McState): void {
+ mc.guidance = null
+
+ const ai = settingsOf(state).ai
+
+ if (mc.planned === null || ai.guidance === false) return
+ if (ai.autoAccept) return startGuidance(state, host, mc)
+
+ runner.ask(guidanceSpec(state, host, mc), 'type a goal first')
+}
diff --git a/plugins/ruflo-console/hooks/mission-palette.ts b/plugins/ruflo-console/hooks/mission-palette.ts
new file mode 100644
index 0000000000..5066f5daf5
--- /dev/null
+++ b/plugins/ruflo-console/hooks/mission-palette.ts
@@ -0,0 +1,38 @@
+/** Palette entries for Mission Control, so `/ruflo run mission-next` and `/ruflo plan <goal>` work headless; a write or a turn still asks. */
+import type { ActionSpec } from './actions'
+import { activeMission, cancelSpec, createSpec, dispatchSpec, mcOf, missionWired, nextTask, setGoal } from './mission-control'
+import type { PaletteEntry } from './palette'
+import type { State } from './state'
+
+export function missionPalette(state: State): PaletteEntry[] {
+ const wired = missionWired(state)
+ const local = (label: string, run: () => void): ActionSpec | null => (wired === undefined ? null : { label, args: [], expect: label, isReadOnly: true, run: async () => run() })
+ const why = 'open Mission Control (the Missions view) first'
+ const spec = (make: () => ActionSpec | null) => ({ kind: 'spec' as const, spec: wired === undefined ? null : make(), why })
+ const text = (keyword: string, make: (text: string) => ActionSpec | null) => ({ kind: 'text' as const, keyword, make: (value: string) => (wired === undefined ? null : make(value)), why: () => why })
+ const tasks = () => state.snapshot?.tasks ?? []
+
+ return [
+ { id: 'mission-goal', group: 'missions', label: 'mission-goal <goal>: plan a goal as a SPARC goal-oriented plan (nothing is written)', run: text('mission-goal', value => local('plan the goal', () => setGoal(state, value))) },
+ { id: 'mission-status', group: 'missions', label: 'mission status: progress, each taskโ€™s status, what is next', run: spec(() => local('mission status', () => undefined)) },
+ { id: 'mission-create', group: 'missions', label: 'create the mission and its tasks from the planned goal (asks first)', run: spec(() => (wired === undefined ? null : createSpec(state, wired.host, () => undefined))) },
+ {
+ id: 'mission-next',
+ group: 'missions',
+ label: 'hand the next ready task to Claude (asks first: it starts a turn)',
+ run: spec(() => {
+ const mission = activeMission(state)
+ const task = mission === null ? null : nextTask(mission, tasks())
+
+ return wired === undefined || mission === null || task === null ? null : dispatchSpec(state, wired.host, mission, task, text => wired.host.submitPrompt(text))
+ }),
+ },
+ { id: 'mission-pause', group: 'missions', label: 'pause: no more tasks are handed out', run: spec(() => local('pause the mission', () => wired?.actions.pause())) },
+ { id: 'mission-resume', group: 'missions', label: 'resume handing out tasks', run: spec(() => local('resume the mission', () => wired?.actions.resume())) },
+ { id: 'mission-cancel', group: 'missions', label: 'cancel the mission and its open tasks (asks first)', run: spec(() => { const mission = activeMission(state); return wired === undefined || mission === null ? null : cancelSpec(state, wired.host, mission, tasks()) }) },
+ { id: 'mission-aside', group: 'missions', label: 'mission-aside <question>: /btw beside the running task', run: text('mission-aside', value => local('ask aside', () => wired?.actions.aside(value))) },
+ { id: 'mission-guide', group: 'missions', label: 'mission-guide <instruction>: a visible instruction to Claude (asks first)', run: text('mission-guide', value => (value.trim() === '' ? null : { label: `send Claude: ${value.slice(0, 70)}`, args: [], shows: `to the Claude Code session: โ€œ${value}โ€`, expect: 'the instruction in the transcript', note: 'Starts a Claude Code turn (billed as any turn is).', run: async () => wired?.host.submitPrompt(value.slice(0, 500)) })) },
+ { id: 'mission-auto', group: 'missions', label: 'mission-auto on|off: hand over each next ready task without asking', run: text('mission-auto', value => local('auto-run', () => wired?.actions.auto(value.trim() === 'on'))) },
+ { id: 'mission-open', group: 'missions', label: 'open Mission Control', run: { kind: 'view', view: 'missions' } },
+ ].map(entry => ({ ...entry, label: mcOf(state) === undefined ? entry.label : entry.label })) as PaletteEntry[]
+}
diff --git a/plugins/ruflo-console/hooks/mission-skills.ts b/plugins/ruflo-console/hooks/mission-skills.ts
new file mode 100644
index 0000000000..4a06f7b115
--- /dev/null
+++ b/plugins/ruflo-console/hooks/mission-skills.ts
@@ -0,0 +1,32 @@
+/**
+ * Mission options from the ruflo-goals plugin's own skills, run in the primary Claude session (the main UI): goal-plan
+ * (a GOAP plan with precondition analysis, cost optimisation and adaptive replanning, by Claude), horizon-track (a
+ * long-horizon objective across sessions, with checkpoints and drift detection), deep-research, research-synthesize and
+ * dossier-collect. Each is a slash command `/ruflo-goals:<skill>`. Offered only when the plugin's commands are present
+ * in the session; run now when the session is idle, otherwise prepared in the prompt box (the person's Enter takes the
+ * native path while a turn runs).
+ */
+import type { Profile } from './goap'
+import type { Host } from './host'
+import type { State } from './state'
+
+export const GOALS_PLUGIN = 'ruflo-goals'
+
+export type MissionSkill = { id: string; title: string; about: string; hint: string; /** Profiles it suits best, highlighted in the list. */ suits: readonly Profile[] }
+
+export const MISSION_SKILLS: readonly MissionSkill[] = [
+ { id: 'goal-plan', title: 'Plan with Claude', about: 'a GOAP plan with precondition analysis, cost optimisation and adaptive replanning, made and executed by Claude', hint: '<goal>', suits: ['feature', 'bugfix', 'refactor', 'security'] },
+ { id: 'horizon-track', title: 'Track across sessions', about: 'a long-horizon objective with milestone checkpoints, progress that persists, and drift detection', hint: '<objective>', suits: ['feature', 'refactor', 'security'] },
+ { id: 'deep-research', title: 'Research first', about: 'multi-phase research over the web, memory and patterns, synthesised into findings', hint: '<topic>', suits: ['research', 'security', 'feature'] },
+ { id: 'research-synthesize', title: 'Synthesise findings', about: 'a report from what memory already holds, with evidence grading and contradictions resolved', hint: '<topic>', suits: ['research'] },
+ { id: 'dossier-collect', title: 'Build a dossier', about: 'a graph of facts on a seed entity, fanned out across web, memory, code, ADRs and git', hint: '<seed>', suits: ['research'] },
+]
+
+/** The slash commands present now (loaded when Mission Control opens); a skill is offered when its command is among them. */
+export async function loadCommandNames(state: State, host: Host): Promise<void> {
+ state.commandNames = await host.listCommands().catch(() => [])
+}
+
+export const slashOf = (skill: MissionSkill): string => `${GOALS_PLUGIN}:${skill.id}`
+
+export const isAvailable = (state: State, skill: MissionSkill): boolean => state.commandNames.includes(slashOf(skill))
diff --git a/plugins/ruflo-console/hooks/mission-text.ts b/plugins/ruflo-console/hooks/mission-text.ts
new file mode 100644
index 0000000000..f3fdfbe95c
--- /dev/null
+++ b/plugins/ruflo-console/hooks/mission-text.ts
@@ -0,0 +1,52 @@
+/** Mission Control as text for the transcript: the plan, the status, and what a headless `/ruflo run mission-โ€ฆ` answers. */
+import { lifecycleOf, type Plan, stageOf } from './goap'
+import { activeMission, derive, mcOf, nextTask, progressOf } from './mission-control'
+import type { State } from './state'
+
+/** The plan as text for the transcript (`/ruflo plan <goal>`): phases, waves and what each step must show. */
+export function planText(p: Plan, goal: string): string {
+ const lines = [`SPARC plan (${p.profile}, ${p.rigor}) for: ${goal}`, `${p.steps.length} tasks ยท cost ${p.totalCost} ยท critical path ${p.criticalCost} ยท ${p.waves.length} waves`, `lifecycle: ${lifecycleOf(p).map(entry => entry.stage).join(' โ†’ ')}`]
+
+ for (const [i, wave] of p.waves.entries()) {
+ lines.push(`wave ${i + 1}:`)
+
+ for (const id of wave) {
+ const step = p.steps.find(candidate => candidate.id === id)
+
+ if (step !== undefined) lines.push(` ${step.id} [${stageOf(step.action)}] ${step.action.title}${step.dependsOn.length > 0 ? ` (after ${step.dependsOn.join(', ')})` : ''} โ€” ${step.action.agent}`)
+ }
+ }
+
+ return lines.join('\n')
+}
+
+/** The active mission's state for the transcript: progress, each task's status from the ruflo task store, and what is next. */
+export function statusText(state: State): string {
+ const mission = activeMission(state)
+
+ if (mission === null) return 'No active mission. /ruflo plan <goal> shows a SPARC plan; the Missions view creates the mission from it.'
+
+ const tasks = state.snapshot?.tasks ?? []
+ const status = derive(mission, tasks)
+ const { done, total } = progressOf(mission, tasks)
+ const next = nextTask(mission, tasks)
+ const lines = [`Mission ${mission.id}: ${mission.objective}`, `${mission.cancelled ? 'cancelled' : mission.paused ? 'paused' : done === total ? 'complete' : 'running'} ยท ${done}/${total} tasks done${mission.auto ? ' ยท auto-run on' : ''}`]
+
+ for (const task of mission.tasks) lines.push(` ${task.id} ${status.get(task.id) ?? '?'} โ€” ${task.title} (${task.agent})`)
+
+ lines.push(next === null ? 'next: nothing to hand out now' : `next: ${next.id} ${next.title} (/ruflo run mission-next hands it to Claude)`)
+
+ return lines.join('\n')
+}
+
+/** What a headless `/ruflo run mission-<verb>` answers, or null for an id that is not a mission one. */
+export function missionAnswer(state: State, paletteId: string | null): string | null {
+ if (paletteId === null || !paletteId.startsWith('mission-')) return null
+
+ const mc = mcOf(state)
+
+ if (paletteId === 'mission-goal') return mc.planned === null ? 'type a goal after the id: /ruflo plan <goal>' : planText(mc.planned, mc.goal)
+ if (paletteId === 'mission-status') return statusText(state)
+
+ return mc.last === null ? null : `${mc.last.ok ? 'โœ“' : 'โœ—'} ${mc.last.label}${mc.last.detail === '' ? '' : ` โ€” ${mc.last.detail}`}`
+}
diff --git a/plugins/ruflo-console/hooks/mission-types.ts b/plugins/ruflo-console/hooks/mission-types.ts
new file mode 100644
index 0000000000..963ea58ffc
--- /dev/null
+++ b/plugins/ruflo-console/hooks/mission-types.ts
@@ -0,0 +1,63 @@
+/** The shapes Mission Control keeps: the ledger (missions, tasks, events), the view state, and the actions the views call. */
+import type { Guidance } from './mission-guidance'
+import type { Plan, Profile, Rigor } from './goap'
+
+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 }
+export type MissionRecord = {
+ id: string
+ objective: string
+ profile: Profile
+ rigor: Rigor
+ planDigest?: string
+ tasks: LedgerTask[]
+ acceptance: { id: string; check: string }[]
+ events: LedgerEvent[]
+ paused: boolean
+ cancelled: boolean
+ auto: boolean
+ createdAtMs: number
+}
+export type McTab = 'plan' | 'tasks' | 'agents' | 'evidence' | 'record'
+export type Derived = 'done' | 'running' | 'ready' | 'waiting' | 'failed' | 'cancelled'
+
+export type McState = {
+ goal: string
+ profile: Profile
+ rigor: Rigor
+ /** True once the person picked the profile (otherwise it follows the goal's words). */
+ isProfilePicked: boolean
+ planned: Plan | null
+ missions: Map<string, MissionRecord>
+ active: string | null
+ tab: McTab
+ /** The last instruction sent to Claude, kept so it can be edited and sent again. */
+ lastGuide: string
+ /** Claude's guidance on the goal, as it arrives (mission-guidance.ts). */
+ guidance: Guidance | null
+ last: { label: string; ok: boolean; detail: string } | null
+}
+
+export type MissionActions = {
+ goal: (text: string) => void
+ profile: (profile: Profile) => void
+ rigor: (rigor: Rigor) => void
+ tab: (tab: McTab) => void
+ create: () => void
+ select: (id: string) => void
+ /** Hands the next ready task to the primary session (asks first: it starts a model turn). */
+ next: () => void
+ pause: () => void
+ resume: () => void
+ cancel: () => void
+ /** Auto-run: when a task finishes and the session is idle, hand over the next ready one without asking. */
+ auto: (on: boolean) => void
+ /** Ask aside: `/btw <question>` beside the running task (run now when idle, otherwise prepared in the prompt box). */
+ aside: (question: string) => void
+ /** Runs a ruflo-goals skill in the main Claude UI on the goal (or the active mission's objective). */
+ skill: (id: string) => void
+ /** Guide Claude: a visible instruction to the primary session (asks first: it starts a model turn). */
+ guide: (text: string) => void
+ /** Asks claude -p for guidance on the current goal again (asks first unless always accept). */
+ askGuidance: () => void
+}
diff --git a/plugins/ruflo-console/hooks/palette.ts b/plugins/ruflo-console/hooks/palette.ts
index 051b977fe6..8c4f512b47 100644
--- a/plugins/ruflo-console/hooks/palette.ts
+++ b/plugins/ruflo-console/hooks/palette.ts
@@ -10,6 +10,7 @@ import { hiveBroadcast, hivePropose, hiveSpawn, hiveVote } from './hive'
import { claimTask, handoffClaim, releaseClaim, stealClaim, type ActionSpec } from './actions'
import { MEM_KEYWORDS, MEM_LAB, memSpecOf, memWhy } from './memory-lab'
import { EVOLVE, evolveSpec, evolveWhy } from './evolve'
+import { missionPalette } from './mission-palette'
import { catalogPalette } from './plugin-catalog'
import { settingsPalette } from './settings-palette'
import { devPalette } from './devtools'
@@ -63,7 +64,7 @@ export function fuzzy(query: string, label: string): number | null {
return whole < 0 ? score : score + 5 + (whole === 0 || text[whole - 1] === ' ' ? 3 : 0)
}
-const TEXT_KEYWORDS: readonly string[] = ['route', 'store', 'search', 'propose', 'broadcast', 'task', 'mission', 'cost-budget', 'x-join', 'x-read', 'x-publish', 'x-create', 'x-grant', 'x-hub', 'x-admit', 'catalog-install', 'catalog-uninstall', 'catalog-enable', 'catalog-disable', 'catalog-update', 'settings-set', 'settings-core', ...MEM_KEYWORDS, ...SECURE_KEYWORDS, 'skills-find', 'auto-wf-new', 'auto-wf-validate', 'auto-ap-history', 'auto-ses-save', 'auto-cfg-get', 'auto-cfg-set', 'auto-task-new', 'nn-train', 'nn-route', 'nn-explain', 'nn-predict']
+const TEXT_KEYWORDS: readonly string[] = ['route', 'store', 'search', 'propose', 'broadcast', 'task', 'mission', 'cost-budget', 'x-join', 'x-read', 'x-publish', 'x-create', 'x-grant', 'x-hub', 'x-admit', 'catalog-install', 'catalog-uninstall', 'catalog-enable', 'catalog-disable', 'catalog-update', 'settings-set', 'settings-core', 'mission-goal', 'mission-aside', 'mission-guide', 'mission-auto', ...MEM_KEYWORDS, ...SECURE_KEYWORDS, 'skills-find', 'auto-wf-new', 'auto-wf-validate', 'auto-ap-history', 'auto-ses-save', 'auto-cfg-get', 'auto-cfg-set', 'auto-task-new', 'nn-train', 'nn-route', 'nn-explain', 'nn-predict']
/** Every entry for the state as it is, before filtering. */
export function paletteEntries(state: State, nowMs: number): PaletteEntry[] {
@@ -174,6 +175,7 @@ export function paletteEntries(state: State, nowMs: number): PaletteEntry[] {
// Dev Tools: local reads run at once, the rest ask first; an entry with a field takes its text (see devtools.ts).
out.push(...devPalette(state))
out.push(...catalogPalette(state))
+ out.push(...missionPalette(state))
out.push(...settingsPalette(state))
for (const worker of WORKERS) add(`worker-${worker}`, 'workers', `dispatch the ${worker} background worker`, { kind: 'spec', spec: dispatchWorker(worker), why: 'unknown worker' })
diff --git a/plugins/ruflo-console/hooks/register.ts b/plugins/ruflo-console/hooks/register.ts
index 16d3dd769e..c199a133c7 100644
--- a/plugins/ruflo-console/hooks/register.ts
+++ b/plugins/ruflo-console/hooks/register.ts
@@ -65,6 +65,18 @@ function hostOf($: EngineInterface, cwd: string): Host {
rufloSnapshot: async () => $.ruflo.snapshot(),
rufloRoute: async () => $.ruflo.lastRoute(),
rufloSegment: async text => $.ruflo.segment({ id: 'console', text }),
+ // Both wait on the turn, so neither may be called from inside a command.run hook (`/ruflo yes` is one): they run from a clock
+ // tick, a later event of their own.
+ submitPrompt: text =>
+ new Promise<void>((resolve, reject) => {
+ $.clock.after(1, () => void $.prompt.submit({ text }).then(() => resolve(), reject))
+ }),
+ fillPrompt: async text => (await $.prompt.fill({ text, mode: 'replace' })).isFilled,
+ runSlash: (command, args) =>
+ new Promise((resolve, reject) => {
+ $.clock.after(1, () => void $.command.run({ command, args }).then(resolve, reject))
+ }),
+ listCommands: async () => (await $.command.list()).map(command => command.name),
}
}
@@ -203,6 +215,7 @@ export const register: Register = (on, raw: PluginOptions) => {
const mark = table.Raster !== undefined ? table.Raster(markPicture(e.props.isWorking, Date.now()).toRaster(BAR_KEY)) : null
+ state.turnActive = e.props.isWorking === true
bound.markFrame(e.requestId, e.props.isWorking && mark !== null)
// A click on a part opens the console on its view, with the keys, so the person can act there at once.
diff --git a/plugins/ruflo-console/hooks/runner.ts b/plugins/ruflo-console/hooks/runner.ts
index c005cd1caf..d0a7a937e2 100644
--- a/plugins/ruflo-console/hooks/runner.ts
+++ b/plugins/ruflo-console/hooks/runner.ts
@@ -130,7 +130,7 @@ export function createRunner(state: State, host: Host, deps: RunnerDeps): Runner
}
pendingSpec = spec
- state.pending = { ...(kind !== null && { rememberKey: kind }), label: spec.label, args: spec.args, expect: spec.expect, askedAtMs: Date.now(), ...(spec.shows !== undefined && { shows: spec.shows }), ...(spec.note !== undefined && { note: spec.note }) }
+ state.pending = { ...(kind !== null && { rememberKey: kind }), ...(spec.scope !== undefined && { scope: spec.scope }), label: spec.label, args: spec.args, expect: spec.expect, askedAtMs: Date.now(), ...(spec.shows !== undefined && { shows: spec.shows }), ...(spec.note !== undefined && { note: spec.note }) }
host.invalidate()
}
diff --git a/plugins/ruflo-console/hooks/settings.ts b/plugins/ruflo-console/hooks/settings.ts
index dd48472d77..082ceb412d 100644
--- a/plugins/ruflo-console/hooks/settings.ts
+++ b/plugins/ruflo-console/hooks/settings.ts
@@ -44,8 +44,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 }
-export const DEFAULT_AI: AiPrefs = { claudeModel: 'default', budgetUsd: 1, autoAccept: false }
+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 }
+export const DEFAULT_AI: AiPrefs = { claudeModel: 'default', budgetUsd: 1, autoAccept: false, guidance: true }
export const AI_KEY = 'ai-prefs'
export type SettingsState = {
@@ -258,7 +258,7 @@ export async function loadAiPrefs(state: State, host: Host): Promise<void> {
const model = CLAUDE_MODELS.find(candidate => candidate === stored?.claudeModel)
const budget = AI_BUDGETS.find(candidate => candidate === stored?.budgetUsd)
- settingsOf(state).ai = { claudeModel: model ?? DEFAULT_AI.claudeModel, budgetUsd: budget ?? DEFAULT_AI.budgetUsd, autoAccept: stored?.autoAccept === true }
+ settingsOf(state).ai = { claudeModel: model ?? DEFAULT_AI.claudeModel, budgetUsd: budget ?? DEFAULT_AI.budgetUsd, autoAccept: stored?.autoAccept === true, guidance: stored?.guidance !== false }
}
export function saveAiPrefs(state: State, host: Host, patch: Partial<AiPrefs>): void {
diff --git a/plugins/ruflo-console/hooks/state.ts b/plugins/ruflo-console/hooks/state.ts
index f1a514fb81..9536350c60 100644
--- a/plugins/ruflo-console/hooks/state.ts
+++ b/plugins/ruflo-console/hooks/state.ts
@@ -32,41 +32,35 @@ export type ViewId = 'menu' | 'overview' | 'swarm' | 'hive' | 'claims' | 'federa
* current tab adds its label, and `blurb` is the one line under the bar that says what the view is for.
*/
export const VIEWS: readonly { id: ViewId; key: string; label: string; short: string; icon: string; blurb: string; rows: number }[] = [
+ // Every view has a hotkey (one digit or lowercase letter is all a Button takes): digits 0-9 are the first ten, letters follow. A view's own
+ // keys (claims c l o s, the terminal l c v u, the footer p x r h) win while that view is open; the tab and the menu still reach it.
{ id: 'menu', key: '0', label: 'Main Menu', short: 'Mnu', icon: '๐Ÿ“Ÿ', blurb: 'the board: every area by its key, the line status, and a prompt that takes a key or a name', rows: 32 },
- { id: 'overview', key: '1', label: 'Overview', short: 'Ovr', icon: '๐Ÿ ', blurb: 'what ruflo is doing here: subsystems, mods, health alerts and live activity', rows: 26 },
- { id: 'swarm', key: '2', label: 'Swarm', short: 'Swm', icon: '๐Ÿ', blurb: 'the swarm as ruflo wrote it: topology, agents at work, and the hive-mind votes', rows: 30 },
- // No hotkey: every digit and letter is taken. It is reached from the tab, the menu, the palette or /ruflo hive.
- { id: 'hive', key: '', label: 'Hive-Mind', short: 'Hiv', icon: '๐Ÿ‘‘', blurb: 'the queen, her workers and their votes: quorum, fault tolerance, proposals and broadcasts', rows: 40 },
- { id: 'claims', key: '3', label: 'Claims', short: 'Clm', icon: '๐Ÿ“Œ', blurb: 'who holds which task: claim, release, hand off or steal, each after a y/n confirm', rows: 30 },
- { id: 'federation', key: '4', label: 'Federation', short: 'Fed', icon: '๐ŸŒ', blurb: 'this node, its peers, keys and channels, placed by how far each is trusted', rows: 26 },
- { id: 'plugins', key: '5', label: 'Plugins', short: 'Plg', icon: '๐Ÿงฉ', blurb: 'ruflo plugins: installed, enabled, in the marketplace clone, and loaded as mods', rows: 30 },
- { id: 'learning', key: '6', label: 'Learning', short: 'Lrn', icon: '๐Ÿง ', blurb: 'router picks and outcomes, and the RETRIEVE โ†’ JUDGE โ†’ DISTILL โ†’ CONSOLIDATE pipeline', rows: 30 },
- { id: 'metaharness', key: '7', label: 'MetaHarness', short: 'MH', icon: '๐Ÿ”ฌ', blurb: 'harness readiness, the flywheel, the audit trend, and a lab that runs every MetaHarness verb', rows: 40 },
- { id: 'memory', key: '8', label: 'Memory', short: 'Mem', icon: '๐Ÿ’พ', blurb: 'the Memory Lab: browse, search, store and delete entries; AgentDB, embeddings and upkeep, each a button', rows: 60 },
- { id: 'cost', key: '9', label: 'Cost', short: 'Cst', icon: '๐Ÿ’ฐ', blurb: 'set a budget, see where spend is reported, and project its burn', rows: 40 },
+ { id: 'missions', key: '1', label: 'Missions', short: 'Msn', icon: '๐ŸŽฏ', blurb: 'Mission Control: a goal becomes a SPARC plan, a mission and tasks that Claude carries out, with guidance, controls and evidence', rows: 26 },
+ { id: 'overview', key: '2', label: 'Overview', short: 'Ovr', icon: '๐Ÿ ', blurb: 'what ruflo is doing here: subsystems, mods, health alerts and live activity', rows: 26 },
+ { id: 'swarm', key: '3', label: 'Swarm', short: 'Swm', icon: '๐Ÿ', blurb: 'the swarm as ruflo wrote it: topology, agents at work, and the hive-mind votes', rows: 30 },
+ { id: 'hive', key: 'b', label: 'Hive-Mind', short: 'Hiv', icon: '๐Ÿ‘‘', blurb: 'the queen, her workers and their votes: quorum, fault tolerance, proposals and broadcasts', rows: 40 },
+ { id: 'claims', key: '4', label: 'Claims', short: 'Clm', icon: '๐Ÿ“Œ', blurb: 'who holds which task: claim, release, hand off or steal, each after a y/n confirm', rows: 30 },
+ { id: 'federation', key: '5', label: 'Federation', short: 'Fed', icon: '๐ŸŒ', blurb: 'this node, its peers, keys and channels, placed by how far each is trusted', rows: 26 },
+ { id: 'plugins', key: '6', label: 'Plugins', short: 'Plg', icon: '๐Ÿงฉ', blurb: 'ruflo plugins: installed, enabled, in the marketplace clone, and loaded as mods', rows: 30 },
+ { id: 'learning', key: '7', label: 'Learning', short: 'Lrn', icon: '๐Ÿง ', blurb: 'router picks and outcomes, and the RETRIEVE โ†’ JUDGE โ†’ DISTILL โ†’ CONSOLIDATE pipeline', rows: 30 },
+ { id: 'metaharness', key: '8', label: 'MetaHarness', short: 'MH', icon: '๐Ÿ”ฌ', blurb: 'harness readiness, the flywheel, the audit trend, and a lab that runs every MetaHarness verb', rows: 40 },
+ { id: 'memory', key: '9', label: 'Memory', short: 'Mem', icon: '๐Ÿ’พ', blurb: 'the Memory Lab: browse, search, store and delete entries; AgentDB, embeddings and upkeep, each a button', rows: 60 },
+ { id: 'cost', key: 'c', label: 'Cost', short: 'Cst', icon: '๐Ÿ’ฐ', blurb: 'set a budget, see where spend is reported, and project its burn', rows: 40 },
{ id: 'timeline', key: 'g', label: 'Timeline', short: 'Gnt', icon: '๐Ÿ•’', blurb: 'each agent busy or idle over the last minutes, beside Claude Code tool calls', rows: 24 },
{ id: 'approvals', key: 'q', label: 'Approvals', short: 'Apv', icon: 'โœ…', blurb: 'decisions waiting for a person: votes, stealable claims, refused mods, budget', rows: 24 },
{ id: 'events', key: 'e', label: 'Events', short: 'Evt', icon: '๐Ÿ“ก', blurb: 'every swarm, claim, memory and mod event as it happens (f filters them)', rows: 26 },
- { id: 'missions', key: 'm', label: 'Missions', short: 'Msn', icon: '๐ŸŽฏ', blurb: 'ADR-406 missions: the plan, task dependencies, acceptance and budget (observe only)', rows: 26 },
{ id: 'xruv', key: 'w', label: 'x.ruv.io', short: 'XRV', icon: '๐Ÿ›ธ', blurb: 'the open agent federation: what it offers, how to join, its channels and who is on', rows: 50 },
{ id: 'terminal', key: 'i', label: 'Terminal', short: 'Trm', icon: '๐Ÿ’ป', blurb: 'an AI terminal: claude -p, codex or both, each a session that remembers the conversation, streamed live', rows: 120 },
- // No hotkey: every digit and letter is taken. The tab, the menu prompt and /ruflo skills reach it by name.
-{ id: 'skills', key: '', label: 'Skills', short: 'Skl', icon: '๐Ÿงฐ', blurb: 'agent skills (npx skills, skills.sh): installed, search, use without installing, preview, add to chosen agents, update, create', rows: 60 },
- // No hotkeys either: reached by the tab, the menu prompt (secure, perf) or /ruflo secure.
- { id: 'secure', key: '', label: 'Security & Doctor', short: 'Sec', icon: '๐Ÿ”’',blurb: 'security scans, a paste field that checks text for injection and PII, policy, and every doctor check', rows: 40 },
- { id: 'perf', key: '', label: 'Performance', short: 'Prf', icon: '๐Ÿ“ˆ', blurb: 'metrics, profile, benchmarks, bottlenecks and a latency sparkline from each run', rows: 30 },
- { id: 'automate', key: '', label: 'Automation', short: 'Aut', icon: '๐Ÿค–', blurb: 'workflows, the twelve background workers and their daemon, autopilot, sessions, config and a task kanban', rows: 44 },
- { id: 'neural', key: '', label: 'Learning Lab', short: 'Lab', icon: '๐Ÿงช', blurb: 'train neural patterns and watch the loss, ask the router which agent fits a task, and why', rows: 36 },
- // No hotkey either: reached from the tab, the menu prompt (vector) or /ruflo vector.
- { id: 'vector', key: '', label: 'Vector Lab', short: 'Vec', icon: '๐Ÿงฒ', blurb: 'ruvector: the shared brain, RVF stores, rvlite queries, decompile, workers, edge, hooks intel and your pi identity', rows: 44 },
- // No hotkey either: the tab, the menu prompt, the palette and /ruflo evolve reach it by name.
- { id: 'evolve', key: '', label: 'Self-Evolution', short: 'Evo', icon: '๐Ÿงฌ', blurb: 'the governed loop: flywheel receipts, ledger, lineage, the policy gate, the witness; Autogenous and rGi', rows: 44 },
- // Keyless too. The menu prompt, the tab and /ruflo devtools reach it by name.
- { id: 'devtools', key: '', label: 'Dev Tools', short: 'Dev', icon: '๐Ÿ”ง', blurb: 'the integration surface: GitHub, diff analysis, agenticow, WASM, browser, terminal, providers, maintenance', rows: 40 },
- // Keyless too: the menu prompt, the tab, the Plugins view's โ–ธ catalog and /ruflo market reach it by name.
- { id: 'market', key: '', label: 'Plugin Catalog', short: 'Cat', icon: '๐Ÿ“ฆ', blurb: 'every ruflo plugin, mod and skill: what it ships, install, enable, disable, update, view and use', rows: 50 },
- // Keyless too: the main menu, the tab and /ruflo settings reach it by name.
- { id: 'settings', key: '', label: 'Settings', short: 'Set', icon: 'โš™๏ธ', blurb: 'simple to advanced settings: plugin options, ruflo config, and the AI terminalโ€™s model and budget, each edited in place', rows: 50 },
+ { id: 'skills', key: 'z', label: 'Skills', short: 'Skl', icon: '๐Ÿงฐ', blurb: 'agent skills (npx skills, skills.sh): installed, search, use without installing, preview, add to chosen agents, update, create', rows: 60 },
+ { id: 'secure', key: 'u', label: 'Security & Doctor', short: 'Sec', icon: '๐Ÿ”’',blurb: 'security scans, a paste field that checks text for injection and PII, policy, and every doctor check', rows: 40 },
+ { id: 'perf', key: 'f', label: 'Performance', short: 'Prf', icon: '๐Ÿ“ˆ', blurb: 'metrics, profile, benchmarks, bottlenecks and a latency sparkline from each run', rows: 30 },
+ { id: 'automate', key: 'a', label: 'Automation', short: 'Aut', icon: '๐Ÿค–', blurb: 'workflows, the twelve background workers and their daemon, autopilot, sessions, config and a task kanban', rows: 44 },
+ { id: 'neural', key: 'l', label: 'Learning Lab', short: 'Lab', icon: '๐Ÿงช', blurb: 'train neural patterns and watch the loss, ask the router which agent fits a task, and why', rows: 36 },
+ { id: 'vector', key: 'v', label: 'Vector Lab', short: 'Vec', icon: '๐Ÿงฒ', blurb: 'ruvector: the shared brain, RVF stores, rvlite queries, decompile, workers, edge, hooks intel and your pi identity', rows: 44 },
+ { id: 'evolve', key: 't', label: 'Self-Evolution', short: 'Evo', icon: '๐Ÿงฌ', blurb: 'the governed loop: flywheel receipts, ledger, lineage, the policy gate, the witness; Autogenous and rGi', rows: 44 },
+ { id: 'devtools', key: 'd', label: 'Dev Tools', short: 'Dev', icon: '๐Ÿ”ง', blurb: 'the integration surface: GitHub, diff analysis, agenticow, WASM, browser, terminal, providers, maintenance', rows: 40 },
+ { id: 'market', key: 'm', label: 'Plugin Catalog', short: 'Cat', icon: '๐Ÿ“ฆ', blurb: 'every ruflo plugin, mod and skill: what it ships, install, enable, disable, update, view and use', rows: 50 },
+ { id: 'settings', key: 's', label: 'Settings', short: 'Set', icon: 'โš™๏ธ', blurb: 'simple to advanced settings: plugin options, ruflo config, and the AI terminalโ€™s model and budget, each edited in place', rows: 50 },
]
export const AGENT_VIEW = { id: 'agent' as const, rows: 28 }
@@ -137,7 +131,7 @@ export function optionsOf(raw: PluginOptions | undefined): Options {
}
/** A mutating action waiting for the person's second press; `shows` is the command line when it is not a ruflo one. */
-export type Pending = { label: string; args: readonly string[]; expect: string; askedAtMs: number; shows?: string; note?: string; /** The kind of action, when it may be remembered (see remember.ts). */ rememberKey?: string }
+export type Pending = { label: string; args: readonly string[]; expect: string; askedAtMs: number; shows?: string; note?: string; /** The kind of action, when it may be remembered (see remember.ts). */ rememberKey?: string; /** Where in its view the ask came from. */ scope?: string }
/** The MetaHarness lab's last run: what it was, how it exited, its cost note, and its output as lines to scroll. */
export type LabResult = { id: string; label: string; ok: boolean; exitCode: number | null; note?: string; lines: string[]; atMs: number }
@@ -212,6 +206,10 @@ export type State = {
allowed: Map<string, string>
/** The main nav's style, saved across sessions. */
nav: NavStyle
+ /** The slash command names the session offered when last asked (for the mission skills). */
+ commandNames: string[]
+ /** True while the primary Claude session is running a turn (the band reports it each draw). */
+ turnActive: boolean
/** Collapsible sections the person flipped from their default (`<view>/<id>`): open ones closed, closed ones open. */
sections: Set<string>
/** What one-shot entry fields hold while typed (cleared on Enter), by field key. */
@@ -305,6 +303,8 @@ export function newState(raw: PluginOptions | undefined): State {
curveGrewAtMs: 0,
dockColumns: 0,
nav: 'auto',
+ turnActive: false,
+ commandNames: [],
allowed: new Map(),
sections: new Set(),
fieldText: new Map(),
diff --git a/plugins/ruflo-console/hooks/view-open.ts b/plugins/ruflo-console/hooks/view-open.ts
index 04edc73f2c..923a9228dd 100644
--- a/plugins/ruflo-console/hooks/view-open.ts
+++ b/plugins/ruflo-console/hooks/view-open.ts
@@ -8,7 +8,12 @@ import { loadCatalog } from './plugin-catalog'
import { loadAiPrefs, loadCore, loadPlugin, settingsOf } from './settings'
import { CLI_PREFIXES, type State } from './state'
+import { loadCommandNames } from './mission-skills'
+
export function openLoaders(state: State, host: Host, view: State['view']): void {
+ // Mission Control asks the session which slash commands it offers (the ruflo-goals skills among them).
+ if (view === 'missions') void loadCommandNames(state, host)
+
// Self-Evolution reads ruflo's own flywheel files (local, no CLI run); its checks wait for a click.
if (view === 'evolve') void loadEvolve(state, host)
diff --git a/plugins/ruflo-console/hooks/views/bar.ts b/plugins/ruflo-console/hooks/views/bar.ts
index 2f05f35df5..07e55720b3 100644
--- a/plugins/ruflo-console/hooks/views/bar.ts
+++ b/plugins/ruflo-console/hooks/views/bar.ts
@@ -5,6 +5,7 @@
* standing context (claims, this session's spend). With nothing happening it says so, and when it last did.
* Each part is a fact on disk or n/a; a part with nothing to say is left out rather than shown as zero.
*/
+import { activeMission, derive, progressOf } from '../mission-control'
import type { RenderElement } from 'claude-code'
import { alertsOf, approvalsOf } from '../data/alerts'
@@ -48,6 +49,22 @@ export function money(usd: number): string {
return usd < 100 ? `$${usd.toFixed(2)}` : `$${Math.round(usd).toLocaleString('en-US')}`
}
+/** The active mission as a band part: progress and the running task, or paused; none when there is no mission, or it is done or cancelled. */
+export function missionPart(state: State): BarPart | null {
+ const mission = activeMission(state)
+
+ if (mission === null || mission.cancelled) return null
+
+ const tasks = state.snapshot?.tasks ?? []
+ const { done, total } = progressOf(mission, tasks)
+ const status = derive(mission, tasks)
+ const running = mission.tasks.find(task => status.get(task.id) === 'running')
+
+ if (total === 0 || done >= total) return null
+
+ return { text: `๐ŸŽฏ ${done}/${total}${mission.paused ? ' paused' : running !== undefined ? ` ยท ${running.id} ${clip(running.title, 28)}` : ''} (1)`, tone: running !== undefined ? 'live' : 'plain', go: 'missions' }
+}
+
export function barParts(state: State, nowMs: number = Date.now()): BarPart[] {
const snap = state.snapshot
const parts: BarPart[] = []
@@ -59,6 +76,11 @@ export function barParts(state: State, nowMs: number = Date.now()): BarPart[] {
if (approvals > 0) parts.push({ text: `${approvals} to approve (q)`, tone: 'attention', go: 'approvals' })
if (alerts > 0) parts.push({ text: `โš  ${alerts} alert${alerts === 1 ? '' : 's'}`, tone: 'attention', go: 'overview' })
+ // The active mission: how far along, and the task Claude is on (or that it is paused); a click opens Mission Control.
+ const missing = missionPart(state)
+
+ if (missing !== null) parts.push(missing)
+
// What is happening now: agents at work, the AI terminal's runs, and the newest event while it is fresh.
parts.push(...workingParts(state, nowMs))
diff --git a/plugins/ruflo-console/hooks/views/common.ts b/plugins/ruflo-console/hooks/views/common.ts
index d063f7691b..7d14f5b84f 100644
--- a/plugins/ruflo-console/hooks/views/common.ts
+++ b/plugins/ruflo-console/hooks/views/common.ts
@@ -7,6 +7,7 @@ import type { Elements, RenderChildren, RenderElement } from 'claude-code'
import type { ProbeResult } from '../data/cli'
import type { EvolveActions } from '../evolve'
+import type { MissionActions } from '../mission-control'
import type { CatalogActions } from '../plugin-catalog'
import type { SettingsActions } from '../settings'
import type { DevtoolsActions } from '../devtools'
@@ -65,8 +66,12 @@ export type Actions = {
evolve: EvolveActions
/** The Dev Tools view: keep a field's text, and Enter in a field runs its entry. */
devtools: DevtoolsActions
+ /** Mission Control: goal, profile, create, run next, pause/resume/cancel, auto-run, ask aside, guide Claude. */
+ mission: MissionActions
/** The Plugin Catalog: read the clone, filter, select a plugin, view or use an item, change a plugin (each asks first). */
catalog: CatalogActions
+ /** Puts text back in an entry field and gives it the keys, so what was entered can be edited and sent again. */
+ editField: (key: string, text: string) => void
/** Empties an entry field after its Enter. */
clearField: (key: string) => void
/** The confirm row's "always allow this kind of action": remembers the kind (Settings forgets it) and runs the pending ask. */
@@ -260,3 +265,47 @@ export function live<T>(result: ProbeResult | undefined): T | null {
return result.value as T
}
+
+/**
+ * The ask a click or an Enter raised, with the exact command, its note, and Yes / Cancel (and the remember choices). A view
+ * in INLINE_CONFIRM draws it itself, right under the field the person typed in; every other view gets it above its body.
+ * `scope` is where the ask came from: a view draws only the asks that belong under its own fields.
+ */
+export function confirmRow(ctx: Ctx): RenderElement | null {
+ const pending = ctx.state.pending
+
+ if (pending === null) return null
+
+ return col(
+ ctx,
+ [
+ text(ctx, `Confirm: ${pending.label.replace(/\?+$/, '')}?`, { bold: true, color: THEME.warn }),
+ // Wrapped, not clipped: the person says yes to the whole argv, so all of it shows (a JSON argument runs long).
+ ctx.kit.Text({ dimColor: true, wrap: 'wrap', children: `runs: ${pending.shows ?? `ruflo ${pending.args.join(' ')}`}` }),
+ ...(pending.note !== undefined ? [text(ctx, pending.note, { bold: /money|models/i.test(pending.note), color: /money|models/i.test(pending.note) ? THEME.bad : THEME.warn })] : []),
+ row(ctx, [
+ button(ctx, 'confirm', 'Yes, run it (y)', ctx.act.confirm, { hotkey: 'y', primary: true }),
+ button(ctx, 'cancel', 'Cancel (n)', ctx.act.cancel, { hotkey: 'n' }),
+ // A low-risk ruflo action may be remembered: it is not asked again (Settings lists and forgets it).
+ ...(pending.rememberKey !== undefined ? [button(ctx, 'remember', `Always allow โ€œ${pending.rememberKey}โ€`, () => ctx.act.remember())] : []),
+ // An AI terminal turn (claude -p in plan mode, codex read-only, the budget cap) may be always accepted: Settings resets it.
+ ...(ctx.state.terminal.asked !== null && pending.label === ctx.state.terminal.asked.label && ctx.state.terminal.harness !== 'ruflo' ? [button(ctx, 'always', 'Always accept AI turns', () => ctx.act.settings.alwaysAccept())] : []),
+ ]),
+ ],
+ 'confirm',
+ )
+}
+
+/** Views that draw the confirm themselves, under the field it came from (the pane then does not draw it above the body). */
+export const INLINE_CONFIRM: ReadonlySet<string> = new Set(['missions', 'hive'])
+
+/** The confirm row when the pending ask came from this scope (or has none, and this is the view's default place for it). */
+export function confirmHere(ctx: Ctx, scope: string, isDefault = false): RenderElement[] {
+ const pending = ctx.state.pending
+
+ if (pending === null || (pending.scope ?? (isDefault ? scope : '')) !== scope) return []
+
+ const row = confirmRow(ctx)
+
+ return row === null ? [] : [row]
+}
diff --git a/plugins/ruflo-console/hooks/views/hive.ts b/plugins/ruflo-console/hooks/views/hive.ts
index 17c7977f62..aab2e09c35 100644
--- a/plugins/ruflo-console/hooks/views/hive.ts
+++ b/plugins/ruflo-console/hooks/views/hive.ts
@@ -16,7 +16,7 @@ import { eggBottomPicture, eggTopPicture } from '../gfx/hive-egg'
import { stripPicture, type Mark, type StripModel } from '../gfx/hive-strip'
import type { Grid } from '../gfx/raster'
import type { State } from '../state'
-import { ago, button, clip, col, kv, picture, row, rule, starts, text, THEME, type Ctx } from './common'
+import { ago, button, clip, col, confirmHere, kv, picture, row, rule, starts, text, THEME, type Ctx } from './common'
const ROLE_GLYPH: Record<string, string> = { worker: 'โ—', specialist: 'โ—†', scout: 'โ–ฒ' }
const LIVE_THEME = (liveness: Liveness): { color?: string; dimColor?: boolean } =>
@@ -326,7 +326,8 @@ function actSection(ctx: Ctx, hive: HiveInfo): RenderElement[] {
if (block !== null) inner.push(text(ctx, ` propose: n/a โ€” ${block}`, { color: THEME.warn }))
- return [ctx.kit.Box({ key: 'hive-act', flexDirection: 'column', borderStyle: 'round', borderColor: THEME.ok, paddingX: 1, children: inner })]
+ // The ask the ACT menu raised is drawn inside it, right under the buttons and fields that raised it.
+ return [ctx.kit.Box({ key: 'hive-act', flexDirection: 'column', borderStyle: 'round', borderColor: THEME.ok, paddingX: 1, children: [...inner, ...confirmHere(ctx, 'hive', true)] })]
}
/**
@@ -348,7 +349,7 @@ export function hiveView(ctx: Ctx): RenderElement {
if (snap === null) return text(ctx, 'reading ruflo stateโ€ฆ', { dimColor: true })
- if (hive === null) return col(ctx, [rule(ctx, 'Hive-Mind', 'not initialised'), ...emptyComb(ctx)], 'hive')
+ if (hive === null) return col(ctx, [rule(ctx, 'Hive-Mind', 'not initialised'), ...emptyComb(ctx), ...confirmHere(ctx, 'hive', true)], 'hive')
const members = membersOf(hive, snap.hiveAgents, snap.agents)
const byzantine = new Set(hive.pending.flatMap(proposal => proposal.byzantine)).size
diff --git a/plugins/ruflo-console/hooks/views/menu.ts b/plugins/ruflo-console/hooks/views/menu.ts
index 648cbd1b2d..a24b388f81 100644
--- a/plugins/ruflo-console/hooks/views/menu.ts
+++ b/plugins/ruflo-console/hooks/views/menu.ts
@@ -3,8 +3,13 @@ import type { RenderElement } from 'claude-code'
import { VIEWS, type ViewId } from '../state'
import { barParts } from './bar'
import { clip, col, isBbs, row, text, THEME, type Ctx } from './common'
+import { missionStrip } from './mission-control'
-type Item = { key: string; label: string; go: string }
+type Item = { label: string; go: string }
+
+/** The keys of the entries that are not views. */
+const COMMAND_KEYS: Record<string, string> = { palette: 'p', help: 'h', close: 'O' }
+const keyOf = (item: Item): string => COMMAND_KEYS[item.go] ?? VIEWS.find(view => view.id === item.go)?.key ?? 'ยท'
/**
* The board's menus: four groups, each split into short sub-sections, the way the old BBS main menus grouped their
@@ -15,38 +20,39 @@ const GROUPS: readonly { title: string; sections: readonly { name: string; items
{
title: 'SWARM',
sections: [
- { name: 'live', items: [{ key: '1', label: 'Overview', go: 'overview' }, { key: '2', label: 'Swarm Topology', go: 'swarm' }, { key: 'ยท', label: 'Hive-Mind', go: 'hive' }] },
- { name: 'work', items: [{ key: '3', label: 'Claims Board', go: 'claims' }, { key: 'm', label: 'Missions', go: 'missions' }, { key: 'q', label: 'Approvals', go: 'approvals' }, { key: 'ยท', label: 'Automation', go: 'automate' }] },
- { name: 'watch', items: [{ key: 'g', label: 'Agent Timeline', go: 'timeline' }, { key: 'e', label: 'Event Stream', go: 'events' }] },
+ { name: 'mission', items: [{ label: 'Missions', go: 'missions' }] },
+ { name: 'live', items: [{ label: 'Overview', go: 'overview' }, { label: 'Swarm Topology', go: 'swarm' }, { label: 'Hive-Mind', go: 'hive' }] },
+ { name: 'work', items: [{ label: 'Claims Board', go: 'claims' }, { label: 'Approvals', go: 'approvals' }, { label: 'Automation', go: 'automate' }] },
+ { name: 'watch', items: [{ label: 'Agent Timeline', go: 'timeline' }, { label: 'Event Stream', go: 'events' }] },
],
},
{
title: 'INTELLIGENCE',
sections: [
- { name: 'learn', items: [{ key: '6', label: 'Learning', go: 'learning' }, { key: 'ยท', label: 'Neural', go: 'neural' }, { key: '7', label: 'MetaHarness', go: 'metaharness' }, { key: 'ยท', label: 'Self-Evolution', go: 'evolve' }] },
- { name: 'remember', items: [{ key: '8', label: 'Memory Lab', go: 'memory' }, { key: 'ยท', label: 'Vector Lab', go: 'vector' }] },
- { name: 'spend', items: [{ key: '9', label: 'Cost & Budget', go: 'cost' }, { key: 'ยท', label: 'Performance', go: 'perf' }] },
+ { name: 'learn', items: [{ label: 'Learning', go: 'learning' }, { label: 'Neural', go: 'neural' }, { label: 'MetaHarness', go: 'metaharness' }, { label: 'Self-Evolution', go: 'evolve' }] },
+ { name: 'remember', items: [{ label: 'Memory Lab', go: 'memory' }, { label: 'Vector Lab', go: 'vector' }] },
+ { name: 'spend', items: [{ label: 'Cost & Budget', go: 'cost' }, { label: 'Performance', go: 'perf' }] },
],
},
{
title: 'SAFETY & OPS',
sections: [
- { name: 'protect', items: [{ key: 'ยท', label: 'Security & Doctor', go: 'secure' }] },
- { name: 'build', items: [{ key: 'ยท', label: 'Dev Tools', go: 'devtools' }] },
+ { name: 'protect', items: [{ label: 'Security & Doctor', go: 'secure' }] },
+ { name: 'build', items: [{ label: 'Dev Tools', go: 'devtools' }] },
],
},
{
title: 'NETWORK & EXTEND',
sections: [
- { name: 'federate', items: [{ key: '4', label: 'Federation', go: 'federation' }, { key: 'w', label: 'x.ruv.io Board', go: 'xruv' }] },
- { name: 'extend', items: [{ key: '5', label: 'Plugins & Mods', go: 'plugins' }, { key: 'ยท', label: 'Skills', go: 'skills' }, { key: 'ยท', label: 'Plugin Catalog', go: 'market' }] },
+ { name: 'federate', items: [{ label: 'Federation', go: 'federation' }, { label: 'x.ruv.io Board', go: 'xruv' }] },
+ { name: 'extend', items: [{ label: 'Plugins & Mods', go: 'plugins' }, { label: 'Skills', go: 'skills' }, { label: 'Plugin Catalog', go: 'market' }] },
],
},
{
title: 'TOOLS',
sections: [
- { name: 'run', items: [{ key: 'i', label: 'AI Terminal', go: 'terminal' }, { key: 'ยท', label: 'Settings', go: 'settings' }, { key: 'p', label: 'Command Palette', go: 'palette' }] },
- { name: 'session', items: [{ key: 'h', label: 'Help', go: 'help' }, { key: 'O', label: 'Log Off', go: 'close' }] },
+ { name: 'run', items: [{ label: 'AI Terminal', go: 'terminal' }, { label: 'Settings', go: 'settings' }, { label: 'Command Palette', go: 'palette' }] },
+ { name: 'session', items: [{ label: 'Help', go: 'help' }, { label: 'Log Off', go: 'close' }] },
],
},
]
@@ -75,6 +81,7 @@ export function menuView(ctx: Ctx): RenderElement {
const rows: RenderElement[] = []
rows.push(text(ctx, ' '))
+ rows.push(...missionStrip(ctx))
// Each group a bordered box: โ–“โ–’โ–‘ TITLE โ–‘โ–’โ–“ on top, then its sub-sections, each a dim โ”€โ”€ name โ”€โ”€ rule and its items.
const box = (group: (typeof GROUPS)[number]) =>
@@ -99,7 +106,7 @@ export function menuView(ctx: Ctx): RenderElement {
flexDirection: 'row',
key: `mi-${item.go}`,
children: [
- ctx.kit.Text({ bold: true, color: THEME.ok, children: ` (${item.key})` }),
+ ctx.kit.Text({ bold: true, color: THEME.ok, children: ` (${keyOf(item)})` }),
ctx.kit.Button({ key: `menu-go-${item.go}`, label: clip(item.label, width - 9), plain: true, onPress: go(item) }),
],
}),
diff --git a/plugins/ruflo-console/hooks/views/mission-control.ts b/plugins/ruflo-console/hooks/views/mission-control.ts
new file mode 100644
index 0000000000..3be840b440
--- /dev/null
+++ b/plugins/ruflo-console/hooks/views/mission-control.ts
@@ -0,0 +1,266 @@
+import type { RenderElement } from 'claude-code'
+
+import { lifecycleOf, PHASE_NAME, PROFILES, RIGORS, stageOf } from '../goap'
+import { activeMission, derive, mcOf, nextTask, progressOf, rufloTaskOf, type Derived, type LedgerTask, type McTab, type MissionRecord } from '../mission-control'
+import { ago, button, clip, col, confirmHere, row, rule, section, text, THEME, type Ctx } from './common'
+import { GOALS_PLUGIN, isAvailable, MISSION_SKILLS, slashOf } from '../mission-skills'
+import { observationRows } from './missions'
+
+const GLYPH: Record<Derived, string> = { done: 'โ—', running: 'โ—', ready: 'โ—‹', waiting: 'ยท', failed: 'โœ–', cancelled: 'โŠ˜' }
+const COLOR = (status: Derived): string => (status === 'done' ? THEME.ok : status === 'running' ? THEME.warn : status === 'failed' ? THEME.bad : status === 'ready' ? THEME.head : THEME.info)
+const TABS: readonly { id: McTab; label: string }[] = [
+ { id: 'plan', label: 'Plan' },
+ { id: 'tasks', label: 'Tasks' },
+ { id: 'agents', label: 'Agents' },
+ { id: 'evidence', label: 'Evidence' },
+ { id: 'record', label: 'Record' },
+]
+
+const bar = (done: number, total: number, width = 10): string => (total === 0 ? 'โ–ฏ'.repeat(width) : 'โ–ฎ'.repeat(Math.round((done / total) * width)).padEnd(width, 'โ–ฏ'))
+
+const chip = (ctx: Ctx, key: string, label: string, isOn: boolean, onPress: () => void): RenderElement =>
+ ctx.kit.Button({ key, label: ` ${isOn ? 'โ—' : 'โ—‹'} ${label} `, plain: true, ...(isOn && { variant: 'primary' as const }), onPress })
+
+/** A boxed one-line field: Enter applies it, and the field empties. */
+function box(ctx: Ctx, key: string, label: string, placeholder: string, submit: string, onSubmit: (value: string) => void): RenderElement[] {
+ const Input = ctx.kit.Input
+
+ return Input === undefined ? [text(ctx, ` ${label}: use the palette (p)`, { dimColor: true })] : [ctx.kit.Box({ key: `${key}-box`, borderStyle: 'round', borderColor: THEME.info, paddingX: 1, children: [Input({ key, label, placeholder, submitLabel: submit, onSubmit })] })]
+}
+
+/** The ruflo-goals skills as mission options: each runs in the main Claude UI on the goal (the unavailable ones say why). */
+function skillRows(ctx: Ctx): RenderElement[] {
+ const mc = mcOf(ctx.state)
+ const rows: RenderElement[] = MISSION_SKILLS.map(skill => {
+ const ok = isAvailable(ctx.state, skill)
+ const suits = skill.suits.includes(mc.profile)
+
+ return row(
+ ctx,
+ [
+ ctx.kit.Text({ color: suits ? THEME.ok : THEME.info, children: suits ? ' โ˜… ' : ' ' }),
+ ctx.kit.Button({ key: `mc-skill-${skill.id}`, label: `${skill.title} `.padEnd(26, '.'), plain: true, onPress: () => ctx.act.mission.skill(skill.id) }),
+ ctx.kit.Button({ key: `mc-skill-about-${skill.id}`, label: clip(` ${skill.about}`, Math.max(10, ctx.columns - 40)), plain: true, dimColor: true, onPress: () => ctx.act.mission.skill(skill.id) }),
+ ctx.kit.Button({ key: `mc-skill-run-${skill.id}`, label: ok ? ' โ–ธ run' : ' โœ— n/a', plain: true, dimColor: !ok, onPress: () => ctx.act.mission.skill(skill.id) }),
+ ],
+ `mc-skill-row-${skill.id}`,
+ )
+ })
+ const missing = MISSION_SKILLS.filter(skill => !isAvailable(ctx.state, skill)).length
+
+ return section(ctx, 'skills', 'Mission options', `${GOALS_PLUGIN} skills, run in the main Claude UI ยท โ˜… suits ${mc.profile}`, [...rows, text(ctx, missing > 0 ? ` ${missing} not offered by this session: install ${GOALS_PLUGIN} (Plugin Catalog), then /reload-plugins` : ` each runs /${GOALS_PLUGIN}:<skill> on the goal now, or prepares it in the prompt box while a turn runs`, { dimColor: true })])
+}
+
+function planRows(ctx: Ctx): RenderElement[] {
+ const mc = mcOf(ctx.state)
+ const rows: RenderElement[] = [
+ row(ctx, [text(ctx, ' kind '), ...PROFILES.map(profile => chip(ctx, `mc-profile-${profile.id}`, profile.label, mc.profile === profile.id, () => ctx.act.mission.profile(profile.id)))], 'mc-profiles'),
+ row(ctx, [text(ctx, ' rigor '), ...RIGORS.map(rigor => chip(ctx, `mc-rigor-${rigor}`, rigor, mc.rigor === rigor, () => ctx.act.mission.rigor(rigor)))], 'mc-rigors'),
+ text(ctx, ` ${PROFILES.find(profile => profile.id === mc.profile)?.about ?? ''}`, { dimColor: true }),
+ ]
+ const planned = mc.planned
+
+ if (planned === null) {
+ rows.push(text(ctx, ' type a goal above: the planner finds the cheapest SPARC action sequence that reaches it', { color: THEME.warn }))
+
+ return rows
+ }
+
+ rows.push(...guidanceRows(ctx))
+ rows.push(rule(ctx, 'SPARC plan', `${planned.steps.length} tasks ยท cost ${planned.totalCost} ยท critical path ${planned.criticalCost} ยท ${planned.waves.length} waves`))
+
+ rows.push(text(ctx, ` ${lifecycleOf(planned).map(entry => `${entry.stage}${entry.steps > 1 ? ` ร—${entry.steps}` : ''}`).join(' โ†’ ')}`, { color: THEME.ok, bold: true }))
+
+ for (const [i, wave] of planned.waves.entries()) {
+ rows.push(text(ctx, ` wave ${i + 1}${wave.length > 1 ? ` ยท ${wave.length} in parallel` : ''}`, { bold: true, color: THEME.head }))
+
+ for (const id of wave) {
+ const step = planned.steps.find(candidate => candidate.id === id)
+
+ if (step !== undefined) rows.push(text(ctx, ` ${step.id} [${stageOf(step.action)}] ${step.action.title}${step.dependsOn.length > 0 ? ` ยท after ${step.dependsOn.join(', ')}` : ''} ยท ${step.action.agent}`))
+ }
+ }
+
+ rows.push(...skillRows(ctx))
+ rows.push(...section(ctx, 'acceptance', 'Acceptance', `${planned.goal.length} criteria`, planned.goal.map(fact => text(ctx, ` โ—‡ ${fact}`, { dimColor: true })), false))
+ rows.push(row(ctx, [ctx.kit.Button({ key: 'mc-create', label: ' โœš Create mission and its tasks ', variant: 'primary', onPress: () => ctx.act.mission.create() }), text(ctx, ' asks first; writes the mission record and the tasks, runs no agent', { dimColor: true })], 'mc-create-row'))
+
+ return rows
+}
+
+/** Claude's guidance on the goal: asked for after a goal is entered; the answer streams into a section that collapses. */
+function guidanceRows(ctx: Ctx): RenderElement[] {
+ const guidance = mcOf(ctx.state).guidance
+ const m = ctx.act.mission
+
+ if (guidance === null) return [row(ctx, [button(ctx, 'mc-guidance-ask', 'โœฆ Ask Claude for guidance', () => m.askGuidance()), text(ctx, ' claude -p reads the goal and the plan and suggests which ruflo capabilities to bring in', { dimColor: true })], 'mc-guidance-ask-row')]
+
+ const control = guidance.stop === null ? button(ctx, 'mc-guidance-again', 'โ†ป ask again', () => m.askGuidance()) : button(ctx, 'mc-guidance-stop', 'โ–  stop', () => guidance.stop?.())
+ const body = guidance.lines.length === 0 ? [text(ctx, ' waiting for the first wordsโ€ฆ', { dimColor: true })] : guidance.lines.map(line => text(ctx, ` ${line}`))
+
+ return section(ctx, 'guidance', 'โœฆ Claude guidance', guidance.status === 'running' ? 'writingโ€ฆ' : guidance.note, [...body, row(ctx, [control], 'mc-guidance-ctl')], true)
+}
+
+function taskRow(ctx: Ctx, mission: MissionRecord, task: LedgerTask, status: Derived, isNext: boolean): RenderElement {
+ const press = () => ctx.act.mission.tab('evidence')
+
+ return row(
+ ctx,
+ [
+ ctx.kit.Text({ bold: true, color: COLOR(status), children: ` ${GLYPH[status]} ` }),
+ ctx.kit.Button({ key: `mc-task-${task.id}`, label: `${task.id} [${task.stage ?? task.phase}] ${clip(task.title, 44)}`.padEnd(54), plain: true, onPress: press }),
+ ctx.kit.Text({ dimColor: true, children: `${task.agent}${task.dependsOn.length > 0 ? ` ยท after ${task.dependsOn.join(',')}` : ''} ยท ${status}${isNext ? ' ยท next' : ''}` }),
+ ],
+ `mc-row-${mission.id}-${task.id}`,
+ )
+}
+
+function tasksRows(ctx: Ctx, mission: MissionRecord): RenderElement[] {
+ const tasks = ctx.state.snapshot?.tasks ?? []
+ const status = derive(mission, tasks)
+ const next = nextTask(mission, tasks)
+
+ return [text(ctx, ' โ— done โ— running โ—‹ ready ยท waiting on a dependency โœ– failed โŠ˜ cancelled ยท status is the ruflo task storeโ€™s', { dimColor: true }), ...mission.tasks.map(task => taskRow(ctx, mission, task, status.get(task.id) ?? 'waiting', next?.id === task.id))]
+}
+
+function agentsRows(ctx: Ctx, mission: MissionRecord): RenderElement[] {
+ const tasks = ctx.state.snapshot?.tasks ?? []
+ const status = derive(mission, tasks)
+ const agents = ctx.state.snapshot?.agents ?? []
+ const roles = [...new Set(mission.tasks.map(task => task.agent))]
+
+ return roles.map(role => {
+ const mine = mission.tasks.filter(task => task.agent === role)
+ const done = mine.filter(task => status.get(task.id) === 'done').length
+ const live = agents.filter(agent => agent.type === role || agent.type.startsWith(role.split('-')[0] ?? role))
+
+ return text(ctx, ` ${role.padEnd(22)} ${done}/${mine.length} tasks done ยท ${live.length === 0 ? 'no swarm agent of this type (Claude plays the role)' : `${live.length} swarm agent${live.length === 1 ? '' : 's'}: ${live.slice(0, 3).map(agent => `${agent.id.slice(0, 12)} ${agent.status}`).join(', ')}`}`)
+ })
+}
+
+function evidenceRows(ctx: Ctx, mission: MissionRecord): RenderElement[] {
+ const tasks = ctx.state.snapshot?.tasks ?? []
+ const status = derive(mission, tasks)
+ const rows: RenderElement[] = []
+ const finished = mission.tasks.filter(task => status.get(task.id) === 'done')
+
+ if (finished.length === 0) rows.push(text(ctx, ' no task is complete yet: what Claude records with task_complete appears here', { dimColor: true }))
+
+ for (const task of finished) {
+ const record = rufloTaskOf(tasks, task)
+
+ rows.push(text(ctx, ` โ— ${task.id} ${clip(task.title, 50)} ยท ${record?.completedAtMs !== undefined ? `done ${ago(record.completedAtMs, ctx.nowMs)}` : 'done'} ยท ref task:${task.rufloTaskId ?? '?'}`, { color: THEME.ok }))
+ rows.push(text(ctx, ` ${record?.resultText ?? 'no result text recorded'}`, { dimColor: record?.resultText === undefined }))
+ }
+
+ rows.push(...section(ctx, 'criteria', 'Acceptance criteria', `${mission.acceptance.length}`, mission.acceptance.map(criterion => text(ctx, ` โ—‡ ${clip(criterion.check, ctx.columns - 8)}`, { dimColor: true })), false))
+ rows.push(text(ctx, ' recorded is not verified: only an independent check closes a criterion', { dimColor: true }))
+
+ return rows
+}
+
+function recordRows(ctx: Ctx, mission: MissionRecord): RenderElement[] {
+ return [...mission.events.slice(-14).map(event => text(ctx, ` #${String(event.seq).padEnd(3)} ${ago(event.atMs, ctx.nowMs).padEnd(10)} ${event.type.padEnd(18)} ${event.taskId ?? ''} ${event.status ?? ''}${event.evidenceRef !== undefined ? ` ref ${clip(event.evidenceRef, 28)}` : ''}${event.note !== undefined ? ` ยท ${event.note}` : ''}`, { dimColor: true })), ...observationRows(ctx)]
+}
+
+/** The control row: hand out the next task, pause or resume, cancel, auto-run, and the two asks (aside and guide). */
+function controlRows(ctx: Ctx, mission: MissionRecord): RenderElement[] {
+ const m = ctx.act.mission
+ const tasks = ctx.state.snapshot?.tasks ?? []
+ const { done, total } = progressOf(mission, tasks)
+ const state = mission.cancelled ? 'cancelled' : mission.paused ? 'paused' : done === total ? 'complete' : 'running'
+ const rows: RenderElement[] = [
+ text(ctx, ` ${mission.id} ยท ${clip(mission.objective, 60)} ยท ${state} ยท ${bar(done, total)} ${done}/${total}`, { bold: true, color: state === 'complete' ? THEME.ok : state === 'paused' ? THEME.info : state === 'cancelled' ? THEME.bad : THEME.head }),
+ row(
+ ctx,
+ [
+ ctx.kit.Button({ key: 'mc-next', label: ' โ–ถ Run next task ', variant: 'primary', onPress: () => m.next() }),
+ mission.paused ? button(ctx, 'mc-resume', 'โ–ถ Resume', () => m.resume()) : button(ctx, 'mc-pause', 'โธ Pause', () => m.pause()),
+ button(ctx, 'mc-cancel', 'โœ– Cancel', () => m.cancel()),
+ chip(ctx, 'mc-auto', 'auto-run', mission.auto, () => m.auto(!mission.auto)),
+ ],
+ 'mc-controls',
+ ),
+ ...confirmHere(ctx, 'controls'),
+ ...box(ctx, 'mc-aside', '? ask aside', 'a question about the current work: /btw answers beside the task, outside the conversation (Enter)', 'ask', value => m.aside(value)),
+ ...box(ctx, 'mc-guide', 'โœŽ guide Claude', 'a visible instruction to the Claude session: it asks first (Enter)', 'send', value => m.guide(value)),
+ ...(mcOf(ctx.state).lastGuide === '' ? [] : [row(ctx, [text(ctx, ` last: ${clip(mcOf(ctx.state).lastGuide, Math.max(20, ctx.columns - 24))} `, { dimColor: true }), button(ctx, 'mc-edit-guide', 'โœŽ edit', () => ctx.act.editField('mc-guide', mcOf(ctx.state).lastGuide))], 'mc-guide-line')]),
+ ...confirmHere(ctx, 'guide'),
+ ]
+
+ return rows
+}
+
+/**
+ * Mission Control: a goal becomes a SPARC plan found by a goal-oriented planner, the plan a governed mission and a ruflo
+ * task per node, and the Claude session does the work one task at a time with its result recorded in the task store
+ * (the one authority for status). Tabs: Plan, Tasks, Agents, Evidence, Record. Asks first before anything that writes a
+ * mission or starts a Claude turn; โ–ถ auto-run is the person's opt-in to skip that confirm for the next ready task.
+ */
+export function missionControlView(ctx: Ctx): RenderElement {
+ const mc = mcOf(ctx.state)
+ const mission = activeMission(ctx.state)
+ const rows: RenderElement[] = [rule(ctx, 'Mission Control', mission === null ? 'goal โ†’ SPARC plan โ†’ tasks โ†’ Claude' : `${mission.id.slice(0, 12)}โ€ฆ`)]
+
+ rows.push(...box(ctx, 'mc-goal', 'โœŽ goal', mc.goal === '' ? 'what should get done? e.g. add a dark mode toggle to settings (Enter plans it)' : `planned: ${clip(mc.goal, 60)} โ€” type another goal to re-plan`, 'plan', value => ctx.act.mission.goal(value)))
+
+ if (mc.goal !== '') rows.push(row(ctx, [text(ctx, ` goal: ${clip(mc.goal, Math.max(20, ctx.columns - 24))} `, { bold: true }), button(ctx, 'mc-edit-goal', 'โœŽ edit', () => ctx.act.editField('mc-goal', mc.goal))], 'mc-goal-line'))
+ rows.push(...confirmHere(ctx, 'goal', true))
+
+ if (mc.missions.size > 1) rows.push(row(ctx, [...mc.missions.values()].slice(-6).map(candidate => chip(ctx, `mc-pick-${candidate.id}`, candidate.id.slice(4, 10), candidate.id === mc.active, () => ctx.act.mission.select(candidate.id))), 'mc-picker'))
+
+ if (mission !== null) rows.push(...controlRows(ctx, mission))
+
+ if (mc.last !== null) rows.push(text(ctx, ` ${mc.last.ok ? 'โœ“' : 'โœ—'} ${mc.last.label}${mc.last.detail === '' ? '' : ` โ€” ${mc.last.detail}`}`, { color: mc.last.ok ? THEME.ok : THEME.bad }))
+
+ rows.push(row(ctx, TABS.filter(tab => mission !== null || tab.id === 'plan' || tab.id === 'record').map(tab => chip(ctx, `mc-tab-${tab.id}`, tab.label, mc.tab === tab.id, () => ctx.act.mission.tab(tab.id))), 'mc-tabs'))
+
+ 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)))
+
+ return col(ctx, rows, 'mission-control')
+}
+
+/**
+ * Mission Control at the top of the main menu: the active mission's progress and what is next, with the buttons to hand the next
+ * task to Claude, pause and open it; or, with none, the goal field (Enter plans it, asks Claude for guidance, and opens Missions).
+ */
+export function missionStrip(ctx: Ctx): RenderElement[] {
+ const mission = activeMission(ctx.state)
+ const m = ctx.act.mission
+ const title = ctx.kit.Text({ bold: true, color: THEME.head, children: 'โ–“โ–’โ–‘ MISSION CONTROL โ–‘โ–’โ–“' })
+ const open = ctx.kit.Button({ key: 'menu-go-missions-top', label: ' (1) open Missions ', plain: true, onPress: () => ctx.act.view('missions') })
+
+ if (mission === null) {
+ return [
+ row(ctx, [title, open], 'menu-mission-title'),
+ ...box(ctx, 'menu-goal', 'โœŽ goal', 'what do you want done? e.g. add a dark mode toggle to settings', 'plan', value => {
+ ctx.act.view('missions')
+ m.goal(value)
+ }),
+ text(ctx, ' research โ†’ create (ADRs, SOP) โ†’ build โ†’ test โ†’ validate โ†’ secure โ†’ benchmark โ†’ learn', { dimColor: true }),
+ text(ctx, ' '),
+ ]
+ }
+
+ const tasks = ctx.state.snapshot?.tasks ?? []
+ const { done, total } = progressOf(mission, tasks)
+ const next = nextTask(mission, tasks)
+
+ return [
+ row(ctx, [title, open], 'menu-mission-title'),
+ text(ctx, ` ${clip(mission.objective, Math.max(20, ctx.columns - 22))} ${bar(done, total)} ${done}/${total}${mission.paused ? ' ยท paused' : ''}`, { bold: true }),
+ row(
+ ctx,
+ [
+ text(ctx, next === null ? ' nothing ready' : ` next ${next.id} [${next.stage ?? next.phase}] ${clip(next.title, Math.max(16, ctx.columns - 46))}`, { dimColor: next === null }),
+ ...(next === null ? [] : [ctx.kit.Button({ key: 'menu-mc-next', label: ' โ–ถ run next ', variant: 'primary' as const, onPress: () => m.next() })]),
+ ctx.kit.Button({ key: 'menu-mc-pause', label: mission.paused ? ' โ–ถ resume ' : ' โธ pause ', plain: true, onPress: () => (mission.paused ? m.resume() : m.pause()) }),
+ ],
+ 'menu-mission-ctl',
+ ),
+ ...confirmHere(ctx, 'controls'),
+ text(ctx, ' '),
+ ]
+}
diff --git a/plugins/ruflo-console/hooks/views/missions.ts b/plugins/ruflo-console/hooks/views/missions.ts
index ff053ce39f..19d950bfba 100644
--- a/plugins/ruflo-console/hooks/views/missions.ts
+++ b/plugins/ruflo-console/hooks/views/missions.ts
@@ -1,7 +1,7 @@
import type { RenderElement } from 'claude-code'
import { money, type Mission } from '../data/missions'
-import { ago, col, kv, rule, startField, text, THEME, type Ctx } from './common'
+import { ago, kv, rule, text, THEME, type Ctx } from './common'
const STATE_COLOR: Record<string, string> = { running: THEME.warn, verifying: THEME.warn, completed: THEME.ok, failed: THEME.bad, blocked: THEME.bad, paused: THEME.info, queued: THEME.info }
@@ -39,15 +39,14 @@ function missionRows(ctx: Ctx, mission: Mission, isFirst: boolean): RenderElemen
* ADR-406 missions, observed only: what `.claude-flow/missions/observation.json` says, as of its own `observedAt`. The
* console takes no mission action here; those go through `ruflo mission action` (a button is never authorization).
*/
-export function missionsView(ctx: Ctx): RenderElement {
+export function observationRows(ctx: Ctx): RenderElement[] {
const observation = ctx.state.snapshot?.missions ?? null
- const rows: RenderElement[] = [rule(ctx, 'Missions', observation === null ? 'no observation' : `${observation.missions.length}${observation.isTruncated ? '+' : ''} ยท observed ${ago(observation.observedAtMs, ctx.nowMs)}`)]
+ const rows: RenderElement[] = [rule(ctx, 'Mission record', observation === null ? 'no observation' : `${observation.missions.length}${observation.isTruncated ? '+' : ''} ยท observed ${ago(observation.observedAtMs, ctx.nowMs)}`)]
if (observation === null) {
- rows.push(text(ctx, ' No mission yet (ADR-406): a mission is an objective the swarm works toward, with a plan, a budget and acceptance.', { color: THEME.warn }))
- rows.push(startField(ctx, 'mission', 'the objective, e.g. ship a verified OAuth login'))
+ rows.push(text(ctx, ' No mission record yet (ADR-406): create one from a goal in Plan.', { color: THEME.warn }))
- return col(ctx, rows, 'missions')
+ return rows
}
if (observation.missions.length === 0) rows.push(text(ctx, 'No missions yet.', { dimColor: true }))
@@ -61,5 +60,5 @@ export function missionsView(ctx: Ctx): RenderElement {
rows.push(kv(ctx, 'legend', 'โ—‹ pending ยท โ— running ยท โ— recorded done (recorded, not verified) ยท โœ– failed'))
rows.push(text(ctx, 'observation only: actions go through `npx ruflo mission action` with a request id and the expected revision', { dimColor: true }))
- return col(ctx, rows, 'missions')
+ return rows
}
diff --git a/plugins/ruflo-console/hooks/views/pane.ts b/plugins/ruflo-console/hooks/views/pane.ts
index 5651f7f5b2..c0f4676a93 100644
--- a/plugins/ruflo-console/hooks/views/pane.ts
+++ b/plugins/ruflo-console/hooks/views/pane.ts
@@ -10,7 +10,7 @@ import { isBooting, isCompactPane, NAV_STYLES, VIEWS, type ViewId } from '../sta
import { agentView } from './agent'
import { automateView } from './automate'
import { claimsView } from './claims'
-import { ago, button, clip, col, isBbs, row, setLook, text, THEME, type Ctx } from './common'
+import { ago, button, clip, col, confirmRow, INLINE_CONFIRM, isBbs, row, setLook, text, THEME, type Ctx } from './common'
import { costView } from './cost'
import { evolveView } from './evolve'
import { catalogView } from './plugin-catalog'
@@ -24,7 +24,7 @@ import { memoryView } from './memory'
import { menuView } from './menu'
import { metaharnessView } from './metaharness'
import { neuralView } from './neural'
-import { missionsView } from './missions'
+import { missionControlView } from './mission-control'
import { overviewView } from './overview'
import { paletteView } from './palette'
import { perfView } from './perf'
@@ -39,7 +39,7 @@ import { xruvView } from './xruv'
export const NARROW = 44
/** The keyless views that keep a tab of their own (the rest are reached from the main menu). */
-const CORE_TABS = new Set<ViewId>(['hive', 'skills'])
+const CORE_TABS = new Set<ViewId>(['hive', 'skills', 'cost', 'timeline', 'approvals', 'events', 'xruv', 'terminal'])
/** The networks the Wildcat strip names, each with the view a click on it opens. */
const NETWORKS: readonly (readonly [string, ViewId])[] = [['x.ruv.io', 'xruv'], ['relay.ruv.io', 'xruv'], ['agentbbs', 'federation'], ['mcp', 'plugins'], ['claude code', 'terminal']]
@@ -61,7 +61,7 @@ const BODIES: Record<ViewId, (ctx: Ctx) => RenderElement> = {
timeline: timelineView,
approvals: approvalsView,
events: eventsView,
- missions: missionsView,
+ missions: missionControlView,
xruv: xruvView,
terminal: terminalView,
skills: skillsView,
@@ -99,7 +99,7 @@ function tabs(ctx: Ctx): RenderElement {
// (from a drill-down, b goes back).
// The current tab always names itself, whatever the width: [3: ๐Ÿ“Œ CLAIMS], [๐Ÿ“Ÿ MAIN MENU]. The others are their emoji (or
// emoji and name from WIDE_TABS columns), since a name on every tab does not fit a dock.
- // A view with no hotkey (key '') has no key to show: [๐Ÿงฐ SKILLS], and its tab is pressed, not typed.
+ // Every view has a hotkey, so the prefix is always shown: [8: ๐Ÿ”ฌ METAHARNESS], [z: ๐Ÿงฐ SKILLS].
const prefix = view.key === '' ? '' : `${view.key}: `
const current = isBbs() ? `[${prefix}${view.icon} ${view.label.toUpperCase()}]` : `${prefix}${view.icon} ${view.label}`
@@ -109,7 +109,7 @@ function tabs(ctx: Ctx): RenderElement {
}
// The tab bar keeps the keyed views and the core keyless ones; the many other views (labs, tools) are tabs only while
// open, and are reached from the main menu (0), where each is listed with its group.
- const isTab = (view: (typeof VIEWS)[number]) => view.key !== '' || CORE_TABS.has(view.id) || view.id === ctx.state.view || (ctx.state.view === 'agent' && view.id === ctx.state.back)
+ const isTab = (view: (typeof VIEWS)[number]) => /^[0-9]$/.test(view.key) || CORE_TABS.has(view.id) || view.id === ctx.state.view || (ctx.state.view === 'agent' && view.id === ctx.state.back)
const line = (views: readonly (typeof VIEWS)[number][], key: string) => ctx.kit.Box({ flexDirection: 'row', gap: 1, key, children: views.filter(isTab).map(tab) })
// The first row runs to the last digit-keyed view, so a keyless view sits where VIEWS puts it (Hive-Mind after Swarm).
const split = VIEWS.reduce((last, view, i) => (/^[0-9]$/.test(view.key) ? i + 1 : last), 0)
@@ -164,30 +164,6 @@ function help(ctx: Ctx): RenderElement {
return col(ctx, [...HELP.split('\n').map((line, i) => text(ctx, line || ' ', i === 0 ? { bold: true, color: THEME.head } : /^[A-Z]/.test(line) ? { bold: true } : { dimColor: i > 20 })), row(ctx, [button(ctx, 'help-close', 'Back', ctx.act.help, { hotkey: 'h' })])], 'help')
}
-function confirmRow(ctx: Ctx): RenderElement | null {
- const pending = ctx.state.pending
-
- if (pending === null) return null
-
- return col(
- ctx,
- [
- text(ctx, `Confirm: ${pending.label.replace(/\?+$/, '')}?`, { bold: true, color: THEME.warn }),
- // Wrapped, not clipped: the person says yes to the whole argv, so all of it shows (a JSON argument runs long).
- ctx.kit.Text({ dimColor: true, wrap: 'wrap', children: `runs: ${pending.shows ?? `ruflo ${pending.args.join(' ')}`}` }),
- ...(pending.note !== undefined ? [text(ctx, pending.note, { bold: /money|models/i.test(pending.note), color: /money|models/i.test(pending.note) ? THEME.bad : THEME.warn })] : []),
- row(ctx, [
- button(ctx, 'confirm', 'Yes, run it (y)', ctx.act.confirm, { hotkey: 'y', primary: true }),
- button(ctx, 'cancel', 'Cancel (n)', ctx.act.cancel, { hotkey: 'n' }),
- // A low-risk ruflo action may be remembered: it is not asked again (Settings lists and forgets it).
- ...(pending.rememberKey !== undefined ? [button(ctx, 'remember', `Always allow โ€œ${pending.rememberKey}โ€`, () => ctx.act.remember())] : []),
- // An AI terminal turn (claude -p in plan mode, codex read-only, the budget cap) may be always accepted: Settings resets it.
- ...(ctx.state.terminal.asked !== null && pending.label === ctx.state.terminal.asked.label && ctx.state.terminal.harness !== 'ruflo' ? [button(ctx, 'always', 'Always accept AI turns', () => ctx.act.settings.alwaysAccept())] : []),
- ]),
- ],
- 'confirm',
- )
-}
function footer(ctx: Ctx): RenderElement {
const { state, nowMs } = ctx
@@ -284,11 +260,11 @@ export function paneView(ctx: Ctx): RenderElement {
// The confirm row sits above the body in both layouts: below it, a tall view would push the question off the screen.
// Compact keeps every page's title and its line of purpose; only the banner and the spacing go.
const parts = isCompact
- ? [tabs(ctx), ...bbs.art, ...(about !== null ? [about] : []), ...(confirm !== null ? [confirm] : []), footer(ctx), body]
+ ? [tabs(ctx), ...bbs.art, ...(about !== null ? [about] : []), ...(confirm !== null && !INLINE_CONFIRM.has(ctx.state.view) ? [confirm] : []), footer(ctx), body]
: !isMenu && isBbs()
? // Every page but the main menu leads with its own title and purpose line; the welcome line and network links follow, with a blank row between the blocks.
- [...bbs.art, ...(about !== null ? [about] : []), ...gap, ...bbs.strip, ...gap, tabs(ctx), ...gap, footer(ctx), ...(confirm !== null && !isTerminal ? [confirm] : []), body, ...(confirm !== null && isTerminal ? [confirm] : [])]
- : [...title, ...(isMenu && isBbs() ? [text(ctx, ' ')] : []), ...bbs.strip, ...(isMenu && isBbs() ? [text(ctx, ' ')] : []), ...gap, tabs(ctx), ...gap, ...(isMenu && isBbs() ? [] : [...bbs.art, ...(about !== null ? [about] : [])]), ...gap, ...(isMenu ? [] : [footer(ctx)]), ...(confirm !== null && !isTerminal ? [confirm] : []), body, ...(confirm !== null && isTerminal ? [confirm] : []), ...gap, ...(isMenu ? [footer(ctx)] : [])]
+ [...bbs.art, ...(about !== null ? [about] : []), ...gap, ...bbs.strip, ...gap, tabs(ctx), ...gap, footer(ctx), ...(confirm !== null && !isTerminal && !INLINE_CONFIRM.has(ctx.state.view) ? [confirm] : []), body, ...(confirm !== null && isTerminal ? [confirm] : [])]
+ : [...title, ...(isMenu && isBbs() ? [text(ctx, ' ')] : []), ...bbs.strip, ...(isMenu && isBbs() ? [text(ctx, ' ')] : []), ...gap, tabs(ctx), ...gap, ...(isMenu && isBbs() ? [] : [...bbs.art, ...(about !== null ? [about] : [])]), ...gap, ...(isMenu ? [] : [footer(ctx)]), ...(confirm !== null && !isTerminal && !INLINE_CONFIRM.has(ctx.state.view) ? [confirm] : []), body, ...(confirm !== null && isTerminal ? [confirm] : []), ...gap, ...(isMenu ? [footer(ctx)] : [])]
return ctx.kit.Box({ flexDirection: 'column', children: parts })
}
diff --git a/plugins/ruflo-console/hooks/views/settings.ts b/plugins/ruflo-console/hooks/views/settings.ts
index cffa796d77..928806d439 100644
--- a/plugins/ruflo-console/hooks/views/settings.ts
+++ b/plugins/ruflo-console/hooks/views/settings.ts
@@ -157,6 +157,7 @@ function aiItems(ctx: Ctx): Item[] {
return [
one('model', 'Claude model', 'the model claude -p uses for AI terminal turns (the CLIโ€™s default when unset)', ai.claudeModel, CLAUDE_MODELS, ai.claudeModel !== DEFAULT_AI.claudeModel, value => ctx.act.settings.ai({ claudeModel: value as (typeof CLAUDE_MODELS)[number] }), 'model haiku sonnet opus'),
one('budget', 'Turn budget (USD)', 'claude -p --max-budget-usd: the most one turn may spend; the sandbox stays read-only', String(ai.budgetUsd), AI_BUDGETS.map(String), ai.budgetUsd !== DEFAULT_AI.budgetUsd, value => ctx.act.settings.ai({ budgetUsd: Number(value) as (typeof AI_BUDGETS)[number] }), 'cost spend cap'),
+ one('guidance', 'Mission guidance', 'after a mission goal is entered, claude -p writes detailed guidance by lifecycle stage and suggests ruflo capabilities to bring in (it asks first unless always accept)', ai.guidance ? 'on' : 'off', ['on', 'off'], !ai.guidance, value => ctx.act.settings.ai({ guidance: value === 'on' }), 'mission goal guidance advice suggestions'),
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 54e9ac80c4..1c579806fa 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.10.0"
+step "1. plugin.json declares ruflo-console 0.11.0"
grep -q '"name": "ruflo-console"' "$ROOT/.claude-plugin/plugin.json" \
- && grep -q '"version": "0.10.0"' "$ROOT/.claude-plugin/plugin.json" && ok || bad "name/version"
+ && grep -q '"version": "0.11.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/behaviour.test.ts b/plugins/ruflo-console/tests/behaviour.test.ts
index 34fb5dbd09..c0b778324c 100644
--- a/plugins/ruflo-console/tests/behaviour.test.ts
+++ b/plugins/ruflo-console/tests/behaviour.test.ts
@@ -20,12 +20,12 @@ describe('behaviour', () => {
await pane.unmount()
})
- test('the selected tab always names itself, however long the name: [7: ๐Ÿ”ฌ METAHARNESS], [๐Ÿงฐ SKILLS]', { options: { boot: false } }, async ($, on) => {
+ test('the selected tab always names itself, however long the name: [8: ๐Ÿ”ฌ METAHARNESS], [z: ๐Ÿงฐ SKILLS]', { options: { boot: false } }, async ($, on) => {
worldOf(on, RUFLO_FILES)
mock.clock(on)
await $.session.start(SESSION)
- for (const [view, tab] of [['metaharness', '[7: ๐Ÿ”ฌ METAHARNESS]'], ['skills', '[๐Ÿงฐ SKILLS]'], ['menu', '[0: ๐Ÿ“Ÿ MAIN MENU]'], ['federation', '[4: ๐ŸŒ FEDERATION]']] as const) {
+ for (const [view, tab] of [['metaharness', '[8: ๐Ÿ”ฌ METAHARNESS]'], ['skills', '[z: ๐Ÿงฐ SKILLS]'], ['menu', '[0: ๐Ÿ“Ÿ MAIN MENU]'], ['federation', '[5: ๐ŸŒ FEDERATION]']] as const) {
await $.command.run(command(view))
const pane = await $.ui.mount({ ...paneAt(110), plugin: PLUGIN })
@@ -165,7 +165,7 @@ describe('behaviour', () => {
expect(elementsOf(tree, 'Raster').length === 0).toBe(isNarrow)
expect(elementsOf(tree, 'Button').map(keyOf).includes('claim')).toBe(!isNarrow)
// The count is VIEWS.length, which grows with each view: hold the position and the name, not the total.
- if (isNarrow) expect(textOf(tree)).toMatch(/5\/\d+ Claims/)
+ if (isNarrow) expect(textOf(tree)).toMatch(/6\/\d+ Claims/)
await pane.unmount()
}
})
diff --git a/plugins/ruflo-console/tests/fixtures/mission-cli.ts b/plugins/ruflo-console/tests/fixtures/mission-cli.ts
new file mode 100644
index 0000000000..7838fd8184
--- /dev/null
+++ b/plugins/ruflo-console/tests/fixtures/mission-cli.ts
@@ -0,0 +1,24 @@
+import { cliAnswer, type Answer } from './world'
+
+export const MISSION_ID = 'msn_0123456789abcdef01234567'
+
+const out = (data: unknown): Answer => ({ exitCode: 0, stdout: `[INFO] Executing tool\nResult:\n${JSON.stringify(data, null, 2)}\n[INFO] done`, stderr: '' })
+
+let counter = 0
+
+/** The fake CLI for Mission Control: the mission and task tools answer as the real ones do (shapes captured from the CLI). */
+export function missionCli(argv: readonly string[]): Answer {
+ const at = argv.indexOf('-t')
+
+ if (at < 0) return cliAnswer(argv)
+
+ const tool = argv[at + 1]
+
+ if (tool === 'mission_create') return out({ ok: true, data: { missionId: MISSION_ID, revision: 1, state: 'draft', deduplicated: false } })
+ if (tool === 'mission_plan') return out({ ok: true, data: { missionId: MISSION_ID, revision: 2, state: 'planned', deduplicated: false, sequence: 2, planDigest: 'sha256:abc123' } })
+ if (tool === 'task_create') return out({ taskId: `task-${++counter}`, success: true })
+ if (tool === 'task_update' || tool === 'task_cancel') return out({ success: true })
+ if (tool === 'mission_request_action') return out({ ok: false, code: 'invalid-transition', message: 'cancel.accepted is not permitted from planned' })
+
+ return cliAnswer(argv)
+}
diff --git a/plugins/ruflo-console/tests/fixtures/world.ts b/plugins/ruflo-console/tests/fixtures/world.ts
index 1c25a64909..18cbe5c341 100644
--- a/plugins/ruflo-console/tests/fixtures/world.ts
+++ b/plugins/ruflo-console/tests/fixtures/world.ts
@@ -36,6 +36,10 @@ export type World = {
/** Every path the mod asked fs.read for, refused or not. */
reads: string[]
inputs: string[]
+ /** Prompts the mod submitted to the primary session (`$.prompt.submit`). */
+ prompts: string[]
+ /** Text the mod put in the prompt box (`$.prompt.fill`). */
+ fills: string[]
blits: string[]
opened: string[]
commands: string[]
@@ -77,7 +81,7 @@ export function cliAnswer(argv: readonly string[]): Answer {
* Seats an in-memory world beneath the plugin: files under CWD and HOME, a process table, the store, the panes, and
* records of what the mod asked for. `refuseAll` refuses every one of those affordances, as an administrator may.
*/
-export function worldOf(on: On, files: Readonly<Record<string, string>>, options: { refuseAll?: boolean; home?: Readonly<Record<string, string>>; env?: Readonly<Record<string, string>> } = {}): World {
+export function worldOf(on: On, files: Readonly<Record<string, string>>, options: { refuseAll?: boolean; commands?: readonly string[]; home?: Readonly<Record<string, string>>; env?: Readonly<Record<string, string>> } = {}): World {
let tick = 1_000
const all = new Map<string, string>([...Object.entries(files).map(([path, text]) => [`${CWD}/${path}`, text] as const), ...Object.entries(options.home ?? {}).map(([path, text]) => [`${HOME}/${path}`, text] as const)])
const mtimes = new Map<string, number>([...all.keys()].map(path => [path, tick]))
@@ -86,6 +90,8 @@ export function worldOf(on: On, files: Readonly<Record<string, string>>, options
runs: [],
reads: [],
inputs: [],
+ prompts: [],
+ fills: [],
blits: [],
opened: [],
commands: [],
@@ -118,6 +124,9 @@ export function worldOf(on: On, files: Readonly<Record<string, string>>, options
return refuse || entries.length === 0 ? { deny: 'ENOENT' } : { value: entries.map(entry => ({ ...entry, size: 1, mtimeMs: 1, isLink: false })) }
})
+ on('prompt.submit', ($, e) => (world.prompts.push(e.text), { text: e.text }))
+ on('prompt.fill', ($, e) => (world.fills.push(e.text), { isFilled: true }))
+ on('command.list', () => ({ value: (options.commands ?? []).map(name => ({ name, description: '', source: 'plugin' as const })) as never }))
on('process.run', ($, e) => {
if (refuse) return { deny: 'process.run withheld' }
diff --git a/plugins/ruflo-console/tests/goap.spec.ts b/plugins/ruflo-console/tests/goap.spec.ts
new file mode 100644
index 0000000000..7c2ed33a7d
--- /dev/null
+++ b/plugins/ruflo-console/tests/goap.spec.ts
@@ -0,0 +1,135 @@
+import { describe, expect, it } from 'vitest'
+
+import { lifecycleOf, plan, profileOf, PROFILES, RIGORS, STAGES, toMissionPlan, type Plan } from '../hooks/goap'
+
+const must = (profile: Parameters<typeof plan>[0], rigor: Parameters<typeof plan>[1]): Plan => plan(profile, rigor) as Plan
+const ids = (p: Plan) => p.steps.map(step => step.action.id)
+
+describe('goal-oriented action planner over SPARC', () => {
+ it('a feature plans S before A before R before C, with tests written before the change', () => {
+ const p = must('feature', 'standard')
+ const order = ids(p)
+
+ expect(order.indexOf('specify')).toBeLessThan(order.indexOf('architect'))
+ expect(order.indexOf('architect')).toBeLessThan(order.indexOf('tests-first'))
+ expect(order.indexOf('tests-first')).toBeLessThan(order.indexOf('implement'))
+ expect(order.indexOf('implement')).toBeLessThan(order.indexOf('verify-tests'))
+ expect(order.indexOf('verify-tests')).toBeLessThan(order.indexOf('integrate'))
+ expect(order.indexOf('verify')).toBeLessThan(order.indexOf('learn'))
+ expect(order.at(-1)).toBe('learn')
+ expect(order).toContain('pseudocode')
+ expect(order).toContain('review')
+ expect(order).toContain('document')
+ })
+
+ it('reaches the goal: every goal fact is given by some step, and every precondition is met before its step', () => {
+ for (const { id } of PROFILES) {
+ for (const rigor of RIGORS) {
+ const p = must(id, rigor)
+ const have = new Set<string>()
+
+ for (const step of p.steps) {
+ expect(step.action.needs.every(fact => have.has(fact)), `${id}/${rigor}: ${step.action.id}`).toBe(true)
+ for (const fact of step.gives) have.add(fact)
+ }
+
+ expect(p.goal.every(fact => have.has(fact)), `${id}/${rigor} goal`).toBe(true)
+ }
+ }
+ })
+
+ it('rigor changes the plan: lean drops review and documentation, thorough adds gates, and cost grows with it', () => {
+ const lean = must('feature', 'lean')
+ const standard = must('feature', 'standard')
+ const thorough = must('feature', 'thorough')
+
+ expect(ids(lean)).not.toContain('review')
+ expect(ids(lean)).not.toContain('document')
+ expect(ids(thorough)).toContain('security-review')
+ expect(lean.totalCost).toBeLessThan(standard.totalCost)
+ expect(standard.totalCost).toBeLessThan(thorough.totalCost)
+ })
+
+ it('the profile changes the plan: a bug fix reproduces and diagnoses first and skips specification; a refactor pins behaviour first', () => {
+ const bug = must('bugfix', 'standard')
+ const refactor = must('refactor', 'standard')
+ const security = must('security', 'standard')
+
+ expect(ids(bug).indexOf('reproduce')).toBeLessThan(ids(bug).indexOf('diagnose'))
+ expect(ids(bug).indexOf('diagnose')).toBeLessThan(ids(bug).indexOf('tests-first'))
+ expect(ids(bug)).not.toContain('specify')
+ expect(ids(refactor).indexOf('baseline')).toBeLessThan(ids(refactor).indexOf('architect-refactor'))
+ expect(ids(security)).toContain('threat-model')
+ expect(ids(security)).toContain('security-review')
+ expect(ids(must('research', 'standard'))).toEqual(expect.arrayContaining(['research-context', 'specify', 'investigate', 'write-up', 'learn-findings']))
+ expect(ids(must('research', 'lean'))).toEqual(['specify', 'investigate'])
+ })
+
+ it('is optimal: no plan found by brute force over the same actions costs less', () => {
+ // The feature goal needs exactly these gates; each has one cheapest producer, so the sum is the minimum.
+ const p = must('feature', 'lean')
+
+ expect(p.totalCost).toBe(2 + 3 + 2 + 4 + 6 + 3 + 3 + 2)
+ })
+
+ it('reads parallel branches off the preconditions: pseudocode and architecture share a wave; the critical path is below the total', () => {
+ const p = must('feature', 'standard')
+ const by = (id: string) => p.steps.find(step => step.action.id === id)
+
+ expect(by('pseudocode')?.wave).toBe(by('architect')?.wave)
+ expect(by('review')?.wave).toBe(by('verify-tests')?.wave)
+ expect(p.criticalCost).toBeLessThan(p.totalCost)
+ expect(p.waves.flat().sort()).toEqual(p.steps.map(step => step.id).sort())
+ })
+
+ it('is deterministic', () => {
+ expect(JSON.stringify(must('feature', 'standard'))).toBe(JSON.stringify(must('feature', 'standard')))
+ })
+
+ it('reads the profile from the goalโ€™s words', () => {
+ expect(profileOf('fix the login crash on empty password')).toBe('bugfix')
+ expect(profileOf('refactor the memory module to remove duplication')).toBe('refactor')
+ expect(profileOf('harden the upload endpoint against injection')).toBe('security')
+ expect(profileOf('investigate why recall drops after consolidation')).toBe('research')
+ expect(profileOf('add a dark mode toggle to settings')).toBe('feature')
+ })
+
+ it('turns the plan into a body mission_plan accepts: session-bound tasks, valid ids, an acyclic graph, a criterion per goal fact, a positive ceiling', () => {
+ const p = must('feature', 'standard')
+ const body = toMissionPlan(p)
+ const known = new Set(body.tasks.map(task => task.id))
+ const SHORT_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/
+
+ expect(body.tasks.every(task => SHORT_ID.test(task.id) && task.executor.mode === 'session-bound' && task.title.length <= 200)).toBe(true)
+ expect(body.tasks.every(task => task.dependsOn.every(dep => known.has(dep)))).toBe(true)
+ expect(body.tasks.every((task, i) => task.dependsOn.every(dep => body.tasks.findIndex(other => other.id === dep) < i))).toBe(true)
+ expect(body.acceptance.map(criterion => criterion.id).sort()).toEqual(p.goal.map(fact => `ac-${fact}`).sort())
+ expect(body.acceptance.find(criterion => criterion.id === 'ac-verified')?.independent).toBe(true)
+ expect(body.budget.currency).toBe('USD')
+ expect(body.budget.ceilingMinor).toBeGreaterThan(p.totalCost * 100)
+ expect(body.budget.concurrency).toBeGreaterThanOrEqual(2)
+ expect(body.tasks.length).toBeLessThanOrEqual(100)
+ })
+
+ it('standard and thorough run the whole lifecycle in order: research, create (ADRs, SOP), build, test, validate, secure, benchmark, learn; lean is the core', () => {
+ for (const profile of ['feature', 'refactor', 'security'] as const) {
+ for (const rigor of ['standard', 'thorough'] as const) {
+ const stages = lifecycleOf(must(profile, rigor)).map(entry => entry.stage)
+
+ expect(stages, `${profile}/${rigor}`).toEqual([...STAGES].filter(stage => stages.includes(stage)))
+ expect(stages, `${profile}/${rigor}`).toEqual(expect.arrayContaining(['Research', 'Create', 'Build', 'Test', 'Validate', 'Secure', 'Benchmark', 'Learn']))
+ }
+ }
+
+ const feature = ids(must('feature', 'standard'))
+
+ expect(feature).toContain('record-decisions')
+ expect(feature.indexOf('architect')).toBeLessThan(feature.indexOf('record-decisions'))
+ expect(feature.indexOf('research-context')).toBeLessThan(feature.indexOf('record-decisions'))
+ expect(feature.indexOf('implement')).toBeLessThan(feature.indexOf('security-review'))
+ expect(feature.indexOf('implement')).toBeLessThan(feature.indexOf('benchmark'))
+ expect(lifecycleOf(must('feature', 'lean')).map(entry => entry.stage)).not.toEqual(expect.arrayContaining(['Secure', 'Benchmark', 'Learn']))
+ expect(lifecycleOf(must('bugfix', 'standard')).map(entry => entry.stage)).toEqual(expect.arrayContaining(['Research', 'Secure', 'Learn']))
+ expect(lifecycleOf(must('research', 'standard')).map(entry => entry.stage)).toContain('Learn')
+ })
+})
diff --git a/plugins/ruflo-console/tests/logic.spec.ts b/plugins/ruflo-console/tests/logic.spec.ts
index 77f8f3bbfc..bd2c4c764f 100644
--- a/plugins/ruflo-console/tests/logic.spec.ts
+++ b/plugins/ruflo-console/tests/logic.spec.ts
@@ -27,7 +27,7 @@ async function snapshotOf(files: Record<string, string>): Promise<Snapshot> {
describe('/ruflo', () => {
it('reads every subcommand into an intent; swarm alone is the view, swarm <sub> belongs to ruflo-swarm', () => {
expect(parseRuflo('')).toEqual({ kind: 'open', view: null })
- expect(parseRuflo('3')).toEqual({ kind: 'open', view: 'claims' })
+ expect(parseRuflo('4')).toEqual({ kind: 'open', view: 'claims' })
expect(parseRuflo('cost')).toEqual({ kind: 'open', view: 'cost' })
expect(parseRuflo('swarm')).toEqual({ kind: 'open', view: 'swarm' })
expect(parseRuflo('swarm status json')).toEqual({ kind: 'delegate', owner: 'ruflo-swarm', words: 'status json' })
diff --git a/plugins/ruflo-console/tests/mission-control.spec.ts b/plugins/ruflo-console/tests/mission-control.spec.ts
new file mode 100644
index 0000000000..2b82147f88
--- /dev/null
+++ b/plugins/ruflo-console/tests/mission-control.spec.ts
@@ -0,0 +1,323 @@
+import { describe, expect, it } from 'vitest'
+
+import type { ActionSpec } from '../hooks/actions'
+import type { TaskRecord } from '../hooks/data/parse'
+import type { Host } from '../hooks/host'
+import { activeMission, advance, createSpec, derive, instructionOf, mcOf, missionActions, nextTask, progressOf, resultOf, setGoal, setProfile, type MissionRecord } from '../hooks/mission-control'
+import { MISSION_SKILLS } from '../hooks/mission-skills'
+import { missionAnswer, planText } from '../hooks/mission-text'
+import { newState, type State } from '../hooks/state'
+import type { Runner } from '../hooks/runner'
+import { missionPart } from '../hooks/views/bar'
+
+const ID = 'msn_0123456789abcdef01234567'
+const out = (data: unknown) => `[INFO] Executing tool\nResult:\n${JSON.stringify(data, null, 2)}\n[INFO] done`
+
+type Calls = { runs: string[][]; prompts: string[]; fills: string[]; slashes: string[]; stored: Map<string, unknown> }
+
+function hostOf(calls: Calls, answer: (tool: string, params: Record<string, unknown>) => unknown = () => ({ ok: true })): Host {
+ return {
+ run: async (argv: readonly string[]) => {
+ calls.runs.push([...argv])
+
+ const at = argv.indexOf('-t')
+ const tool = at >= 0 ? (argv[at + 1] as string) : ''
+ const params = at >= 0 ? (JSON.parse(argv[argv.indexOf('-p') + 1] as string) as Record<string, unknown>) : {}
+
+ return { exitCode: 0, stdout: out(answer(tool, params)), stderr: '' }
+ },
+ storeGet: async (key: string) => calls.stored.get(key),
+ storeSet: async (key: string, value: unknown) => void calls.stored.set(key, value),
+ invalidate: () => undefined,
+ submitPrompt: async (text: string) => void calls.prompts.push(text),
+ fillPrompt: async (text: string) => (calls.fills.push(text), true),
+ runSlash: async (command: string, args: string) => void calls.slashes.push(`${command} ${args}`),
+ listCommands: async () => ['ruflo-goals:goal-plan'],
+ } as unknown as Host
+}
+
+const fresh = (): Calls => ({ runs: [], prompts: [], fills: [], slashes: [], stored: new Map() })
+const task = (id: string, status: string, tags: string[], extra: Partial<TaskRecord> = {}): TaskRecord => ({ id, type: 'feature', description: '', status, assignedTo: [], tags, ...extra })
+
+/** A mission of three tasks whose ruflo task ids are r1..r3: t1 โ†’ t2 โ†’ t3, with t2 and t3 both after t1. */
+function missionOf(): MissionRecord {
+ return {
+ id: 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' },
+ { id: 't3', title: 'Pseudocode', phase: 'P', agent: 'pseudocode', requirement: 'pseudocode', dependsOn: ['t1'], rufloTaskId: 'r3' },
+ ],
+ acceptance: [{ id: 'ac-specified', check: 'a specification exists' }],
+ events: [],
+ paused: false,
+ cancelled: false,
+ auto: false,
+ createdAtMs: 1,
+ }
+}
+
+function stateWith(tasks: TaskRecord[]): State {
+ const state = newState({})
+
+ state.snapshot = { tasks, agents: [], claims: [], swarm: null, plugins: { missingFromClone: [] }, alerts: [] } as never
+
+ return state
+}
+
+describe('mission control: status comes from the ruflo task store', () => {
+ it('derives done, running, ready and waiting from the stored status and the dependencies', () => {
+ const mission = missionOf()
+ const tasks = [task('r1', 'completed', []), task('r2', 'in_progress', []), task('r3', 'pending', [])]
+ const status = derive(mission, tasks)
+
+ expect(status.get('t1')).toBe('done')
+ expect(status.get('t2')).toBe('running')
+ expect(status.get('t3')).toBe('ready')
+ expect(derive(mission, [task('r1', 'pending', [])]).get('t2')).toBe('waiting')
+ expect(derive(mission, [task('r1', 'failed', [])]).get('t1')).toBe('failed')
+ expect(progressOf(mission, tasks)).toEqual({ done: 1, total: 3 })
+ })
+
+ it('hands out the first ready task, none while one is running or failed, none while paused or cancelled', () => {
+ const mission = missionOf()
+
+ expect(nextTask(mission, [task('r1', 'pending', [])])?.id).toBe('t1')
+ expect(nextTask(mission, [task('r1', 'completed', [])])?.id).toBe('t2')
+ expect(nextTask(mission, [task('r1', 'completed', []), task('r2', 'in_progress', [])])).toBeNull()
+ expect(nextTask(mission, [task('r1', 'failed', [])])).toBeNull()
+ mission.paused = true
+ expect(nextTask(mission, [task('r1', 'pending', [])])).toBeNull()
+ mission.paused = false
+ mission.cancelled = true
+ expect(nextTask(mission, [task('r1', 'pending', [])])).toBeNull()
+ })
+
+ it('the instruction names the task, its role, what done means, and how to record it, with the ruflo task id', () => {
+ const text = instructionOf(missionOf(), (missionOf().tasks[1] as never))
+
+ expect(text).toContain(ID)
+ expect(text).toContain('Task t2 (Architecture): Design')
+ expect(text).toContain('Act as: architecture')
+ expect(text).toContain('task_complete with taskId "r2"')
+ expect(text).toContain('status "failed"')
+ expect(text).toContain('Already done: t1 (Specify)')
+ })
+})
+
+describe('mission control: goal, plan, create', () => {
+ it('a goal is planned (nothing written) with the profile its words name, and re-planned when the person picks a kind', () => {
+ const state = stateWith([])
+
+ setGoal(state, 'fix the crash when the password is empty')
+ expect(mcOf(state).profile).toBe('bugfix')
+ expect(mcOf(state).planned?.steps.map(step => step.action.id)).toContain('reproduce')
+ setProfile(state, 'feature', 'lean')
+ expect(mcOf(state).planned?.steps.map(step => step.action.id)).toContain('specify')
+ setGoal(state, 'investigate why recall drops')
+ expect(mcOf(state).profile).toBe('feature') // a picked kind sticks
+ expect(planText(mcOf(state).planned as never, mcOf(state).goal)).toContain('wave 1:')
+ })
+
+ it('create runs mission_create, mission_plan, then task_create per node; the ledger and active mission follow; every argv is fixed', async () => {
+ const state = stateWith([])
+ const calls = fresh()
+ let n = 0
+ const host = hostOf(calls, (tool, params) => {
+ if (tool === 'mission_create') return { ok: true, data: { missionId: ID, revision: 1, state: 'draft' } }
+ if (tool === 'mission_plan') return { ok: true, data: { missionId: ID, revision: 2, state: 'planned', planDigest: 'sha256:abc' } }
+ if (tool === 'task_create') return { taskId: `task-${++n}`, ...params }
+
+ return { ok: true }
+ })
+
+ setGoal(state, 'add a dark mode toggle to settings')
+
+ const spec = createSpec(state, host, () => undefined) as ActionSpec
+
+ expect(spec.label).toContain('create the mission and its')
+ expect(calls.runs).toEqual([]) // building the spec runs nothing
+ await spec.run?.()
+
+ const tools = calls.runs.map(argv => argv[argv.indexOf('-t') + 1])
+ const tasks = mcOf(state).planned?.steps.length ?? 0
+
+ expect(tools).toEqual(['mission_create', 'mission_plan', ...Array(tasks).fill('task_create')])
+ expect(calls.runs.every(argv => argv.includes('mcp') && argv.includes('exec'))).toBe(true)
+
+ const mission = activeMission(state) as MissionRecord
+
+ expect(mission.id).toBe(ID)
+ expect(mission.tasks).toHaveLength(tasks)
+ expect(mission.tasks.every(candidate => candidate.rufloTaskId?.startsWith('task-'))).toBe(true)
+ expect(mission.events.map(event => event.type)).toEqual(['mission.created', 'plan.validated', 'tasks.created'])
+ expect(mission.events.map(event => event.seq)).toEqual([1, 2, 3])
+ expect(calls.stored.get('mission-ledger')).toBeDefined()
+
+ const plan = JSON.parse(calls.runs[1]?.[calls.runs[1].indexOf('-p') + 1] as string) as { plan: { tasks: { executor: { mode: string } }[] } }
+
+ expect(plan.plan.tasks.every(candidate => candidate.executor.mode === 'session-bound')).toBe(true)
+ })
+
+ it('create stops and says why when the mission record refuses; no task is created', async () => {
+ const state = stateWith([])
+ const calls = fresh()
+ const host = hostOf(calls, tool => (tool === 'mission_create' ? { ok: false, code: 'invalid-input', message: 'objective too long' } : { ok: true }))
+
+ setGoal(state, 'add a thing')
+ await (createSpec(state, host, () => undefined) as ActionSpec).run?.()
+ expect(calls.runs).toHaveLength(1)
+ expect(mcOf(state).last?.ok).toBe(false)
+ expect(mcOf(state).last?.detail).toContain('objective too long')
+ expect(activeMission(state)).toBeNull()
+ })
+})
+
+describe('mission control: handing work to the primary session', () => {
+ const setup = (tasks: TaskRecord[]) => {
+ const state = stateWith(tasks)
+ const calls = fresh()
+ const asked: { spec: ActionSpec | null; why: string }[] = []
+ const runner = { ask: (spec: ActionSpec | null, why: string) => void asked.push({ spec, why }) } as unknown as Runner
+ const host = hostOf(calls)
+ const actions = missionActions(state, host, runner)
+ const mission = missionOf()
+
+ mcOf(state).missions.set(ID, mission)
+ mcOf(state).active = ID
+
+ return { state, calls, asked, actions, mission, host }
+ }
+
+ it('next asks first; on yes it marks the task in progress and submits one visible prompt naming the ruflo task id', async () => {
+ const { calls, asked, actions } = setup([task('r1', 'pending', [])])
+
+ actions.next()
+ expect(asked).toHaveLength(1)
+ expect(calls.prompts).toEqual([])
+ await asked[0]?.spec?.run?.()
+ expect(calls.runs.map(argv => argv[argv.indexOf('-t') + 1])).toEqual(['task_update'])
+ expect(JSON.parse(calls.runs[0]?.[calls.runs[0].indexOf('-p') + 1] as string)).toEqual({ taskId: 'r1', status: 'in_progress', progress: 5 })
+ expect(calls.prompts).toHaveLength(1)
+ expect(calls.prompts[0]).toContain('task_complete with taskId "r1"')
+ })
+
+ it('next says why instead of asking when paused, or when a task is already running', () => {
+ const paused = setup([task('r1', 'pending', [])])
+
+ paused.actions.pause()
+ paused.actions.next()
+ expect(paused.asked).toHaveLength(0)
+ expect(mcOf(paused.state).last?.detail).toContain('paused')
+
+ const running = setup([task('r1', 'in_progress', [])])
+
+ running.actions.next()
+ expect(running.asked).toHaveLength(0)
+ expect(mcOf(running.state).last?.ok).toBe(false)
+ })
+
+ it('pause and resume are ledger events with ordered sequence numbers; resume allows the next task again', () => {
+ const { state, actions, mission } = setup([task('r1', 'pending', [])])
+
+ actions.pause()
+ actions.resume()
+ expect(mission.events.map(event => `${event.seq}:${event.type}`)).toEqual(['1:mission.paused', '2:mission.resumed'])
+ expect(nextTask(mission, state.snapshot?.tasks ?? [])?.id).toBe('t1')
+ })
+
+ it('auto-run hands over the next ready task once, only when on and Claude is idle', async () => {
+ const { state, calls, mission, host } = setup([task('r1', 'pending', [])])
+
+ advance(state, host)
+ expect(calls.prompts).toHaveLength(0)
+ mission.auto = true
+ state.turnActive = true
+ advance(state, host)
+ expect(calls.prompts).toHaveLength(0)
+ state.turnActive = false
+ advance(state, host)
+ await Promise.resolve()
+ await new Promise(resolve => setTimeout(resolve, 0))
+ expect(calls.prompts).toHaveLength(1)
+ advance(state, host)
+ expect(calls.prompts).toHaveLength(1)
+ })
+
+ it('ask aside runs /btw when the session is idle and prepares /btw in the prompt box while a turn runs; it never submits a prompt', async () => {
+ const { state, calls, actions } = setup([])
+
+ actions.aside('what does t2 depend on?')
+ await new Promise(resolve => setTimeout(resolve, 0))
+ expect(calls.slashes).toEqual(['btw what does t2 depend on?'])
+ state.turnActive = true
+ actions.aside('is this safe?')
+ await new Promise(resolve => setTimeout(resolve, 0))
+ expect(calls.fills).toEqual(['/btw is this safe?'])
+ expect(calls.prompts).toEqual([])
+ })
+
+ it('guide asks first, then submits the instruction as a visible prompt; an empty one asks nothing', async () => {
+ const { calls, asked, actions } = setup([])
+
+ actions.guide(' ')
+ expect(asked[0]?.spec).toBeNull()
+ actions.guide('prefer the existing settings store')
+ expect(calls.prompts).toEqual([])
+ await asked[1]?.spec?.run?.()
+ expect(calls.prompts).toEqual(['prefer the existing settings store'])
+ })
+
+ it('the ruflo-goals skills run in the main UI only when the session offers them: idle runs the slash command, mid-turn prepares it, and an absent one says how to get it', async () => {
+ const { state, calls, actions } = setup([])
+
+ setGoal(state, 'add a dark mode toggle')
+ actions.skill('goal-plan')
+ expect(mcOf(state).last?.ok).toBe(false)
+ expect(mcOf(state).last?.label).toContain('ruflo-goals:goal-plan is not available')
+ state.commandNames = ['ruflo-goals:goal-plan']
+ actions.skill('goal-plan')
+ await new Promise(resolve => setTimeout(resolve, 0))
+ expect(calls.slashes).toEqual(['ruflo-goals:goal-plan add a dark mode toggle'])
+ state.turnActive = true
+ actions.skill('goal-plan')
+ await new Promise(resolve => setTimeout(resolve, 0))
+ expect(calls.fills).toEqual(['/ruflo-goals:goal-plan add a dark mode toggle'])
+ expect(MISSION_SKILLS.map(skill => skill.id)).toEqual(['goal-plan', 'horizon-track', 'deep-research', 'research-synthesize', 'dossier-collect'])
+ })
+
+ it('the transcript answers: status lists each taskโ€™s status; the plan prints; resultOf reads the JSON after Result:', () => {
+ const { state } = setup([task('r1', 'completed', [])])
+
+ expect(missionAnswer(state, 'mission-status')).toContain('1/3 tasks done')
+ expect(missionAnswer(state, 'mission-status')).toContain('t1 done')
+ expect(missionAnswer(state, 'spawn-coder')).toBeNull()
+ expect(resultOf(out({ ok: true, data: { missionId: ID } }))).toEqual({ ok: true, data: { missionId: ID } })
+ expect(resultOf('no json here')).toBeNull()
+ })
+
+ it('the band shows the active mission: progress and the running task, paused when paused, gone when finished or cancelled', () => {
+ const state = stateWith([task('r1', 'completed', []), task('r2', 'in_progress', []), task('r3', 'pending', [])])
+ const mission = missionOf()
+
+ mcOf(state).missions.set(ID, mission)
+ mcOf(state).active = ID
+
+ const part = () => missionPart(state) ?? undefined
+
+ expect(part()?.text).toBe('๐ŸŽฏ 1/3 ยท t2 Design (1)')
+ expect(part()?.tone).toBe('live')
+ expect(part()?.go).toBe('missions')
+ mission.paused = true
+ expect(part()?.text).toBe('๐ŸŽฏ 1/3 paused (1)')
+ mission.paused = false
+ mission.cancelled = true
+ expect(part()).toBeUndefined()
+ mission.cancelled = false
+ state.snapshot = { tasks: [task('r1', 'completed', []), task('r2', 'completed', []), task('r3', 'completed', [])], agents: [], claims: [], swarm: null, plugins: { missingFromClone: [] }, alerts: [] } as never
+ expect(part()).toBeUndefined()
+ })
+})
diff --git a/plugins/ruflo-console/tests/mission-guidance.spec.ts b/plugins/ruflo-console/tests/mission-guidance.spec.ts
new file mode 100644
index 0000000000..1a8eda1a3e
--- /dev/null
+++ b/plugins/ruflo-console/tests/mission-guidance.spec.ts
@@ -0,0 +1,163 @@
+/**
+ * Claude's guidance on a mission, under vitest: the argv (claude -p, plan mode, the budget and model from Settings), what the
+ * prompt tells claude (the goal, the plan, the lifecycle, this installation's plugins and skills), that it asks first unless
+ * "always accept" is on and is silent when Settings turned it off, and how the streamed answer lands.
+ */
+import { describe, expect, it } from 'vitest'
+
+import type { ActionSpec } from '../hooks/actions'
+import type { Host } from '../hooks/host'
+import { guidanceArgv, guidancePrompt, guidanceSpec, offerGuidance, pluginsOf, startGuidance } from '../hooks/mission-guidance'
+import { mcOf, setGoal } from '../hooks/mission-control'
+import type { Runner } from '../hooks/runner'
+import { saveAiPrefs, settingsOf } from '../hooks/settings'
+import { newState, type State } from '../hooks/state'
+
+const json = (value: unknown) => `${JSON.stringify(value)}\n`
+
+const ANSWER = [
+ { stream: 'stdout' as const, text: json({ type: 'stream_event', event: { type: 'content_block_delta', delta: { type: 'text_delta', text: '## Research\nSearch memory first' } } }) },
+ { stream: 'stdout' as const, text: json({ type: 'stream_event', event: { type: 'content_block_delta', delta: { type: 'text_delta', text: ' for prior art.\n## Learn\nStore the outcome.' } } }) },
+ { stream: 'stdout' as const, text: json({ type: 'result', subtype: 'success', is_error: false, total_cost_usd: 0.0421 }) },
+]
+
+function fakeHost(script: { stream: 'stdout' | 'stderr'; text: string }[]) {
+ const calls: { argv: readonly string[]; input?: string }[] = []
+ const stored = new Map<string, unknown>()
+ const spawn = (argv: readonly string[], input?: string) => {
+ calls.push({ argv, ...(input !== undefined && { input }) })
+
+ const stream = (async function* () {
+ for (const chunk of script) yield chunk
+
+ return { code: 0, signal: null }
+ })()
+
+ return Object.assign(stream, { result: Promise.resolve({ code: 0, signal: null }), return: async () => ({ done: true, value: undefined }) }) as never
+ }
+ const host = { spawn, invalidate: () => undefined, after: () => ({ cancel: () => undefined }), storeSet: async (key: string, value: unknown) => void stored.set(key, value) } as unknown as Host
+
+ return { host, calls }
+}
+
+const ready = (goal = 'add a dark mode toggle to settings'): State => {
+ const state = newState({})
+
+ state.commandNames = ['ruflo-goals:goal-plan', 'ruflo-sparc:sparc', 'other:thing']
+ setGoal(state, goal)
+
+ return state
+}
+
+const settled = async () => {
+ for (let i = 0; i < 20; i++) await new Promise(resolve => setTimeout(resolve, 2))
+}
+
+describe('mission guidance', () => {
+ it('runs claude -p in plan mode, streaming, under the budget and model from Settings, with a fresh session', () => {
+ const state = ready()
+
+ expect(guidanceArgv(state)).toEqual(['claude', '-p', '--output-format', 'stream-json', '--verbose', '--include-partial-messages', '--permission-mode', 'plan', '--max-budget-usd', '1'])
+ saveAiPrefs(state, { invalidate: () => undefined, storeSet: async () => undefined } as unknown as Host, { claudeModel: 'sonnet', budgetUsd: 0.5 })
+ expect(guidanceArgv(state)).toEqual(expect.arrayContaining(['--max-budget-usd', '0.5', '--model', 'sonnet']))
+ expect(guidanceArgv(state)).not.toContain('--resume')
+ })
+
+ it('the prompt carries the goal, the plan and lifecycle, the installed ruflo plugins and skills, and the AI settings; it is read-only', () => {
+ const state = ready()
+ const mc = mcOf(state)
+ const prompt = guidancePrompt(state, mc, mc.planned as never)
+
+ expect(prompt).toContain('GOAL: add a dark mode toggle to settings')
+ expect(prompt).toContain('Read-only')
+ expect(prompt).toContain('Lifecycle: Research')
+ expect(prompt).toContain('[Create] Design the architecture and interfaces')
+ expect(prompt).toContain('ruflo plugins loaded in the session: ruflo-goals, ruflo-sparc')
+ expect(prompt).toContain('ruflo-goals:goal-plan')
+ expect(prompt).not.toContain('other:thing')
+ expect(prompt).toContain('claude model default, turn budget $1, asks before AI turns')
+ expect(prompt).toMatch(/Suggestions/)
+ expect(pluginsOf(state)).toEqual(['ruflo-goals', 'ruflo-sparc'])
+ })
+
+ it('asks first, under the goal, showing the exact command; nothing runs until it is confirmed', async () => {
+ const state = ready()
+ const { host, calls } = fakeHost(ANSWER)
+ const asked: { spec: ActionSpec | null }[] = []
+ const runner = { ask: (spec: ActionSpec | null) => void asked.push({ spec }) } as unknown as Runner
+
+ offerGuidance(state, host, runner, mcOf(state))
+ await settled()
+ expect(calls).toEqual([])
+ expect(asked[0]?.spec?.scope).toBe('goal')
+ expect(asked[0]?.spec?.label).toContain('ask claude -p for detailed guidance')
+ expect(asked[0]?.spec?.shows).toContain('claude -p')
+ await asked[0]?.spec?.run?.()
+ await settled()
+ expect(calls).toHaveLength(1)
+ expect(calls[0]?.input).toContain('GOAL: add a dark mode toggle to settings')
+ })
+
+ it('always accept runs it at once; turning Mission guidance off in Settings asks and runs nothing', async () => {
+ const state = ready()
+ const { host, calls } = fakeHost(ANSWER)
+ const asked: unknown[] = []
+ const runner = { ask: (spec: unknown) => void asked.push(spec) } as unknown as Runner
+
+ settingsOf(state).ai = { ...settingsOf(state).ai, autoAccept: true }
+ offerGuidance(state, host, runner, mcOf(state))
+ await settled()
+ expect(calls).toHaveLength(1)
+ expect(asked).toEqual([])
+
+ settingsOf(state).ai = { ...settingsOf(state).ai, autoAccept: false, guidance: false }
+ offerGuidance(state, host, runner, mcOf(state))
+ await settled()
+ expect(calls).toHaveLength(1)
+ expect(asked).toEqual([])
+ expect(mcOf(state).guidance).toBeNull()
+ })
+
+ it('the answer streams into lines, markdown headings kept, with the turn cost; a second ask does not start while one runs', async () => {
+ const state = ready()
+ const { host, calls } = fakeHost(ANSWER)
+ const mc = mcOf(state)
+
+ startGuidance(state, host, mc)
+ startGuidance(state, host, mc)
+ await settled()
+ expect(calls).toHaveLength(1)
+ expect(mc.guidance?.status).toBe('done')
+ expect(mc.guidance?.lines).toEqual(['## Research', 'Search memory first for prior art.', '## Learn', 'Store the outcome.'])
+ expect(mc.guidance?.note).toContain('$0.042')
+ })
+
+ it('an answer with nothing in it is a failure that says what to check, and an error result is one too', async () => {
+ const empty = ready()
+
+ startGuidance(empty, fakeHost([]).host, mcOf(empty))
+ await settled()
+ expect(mcOf(empty).guidance?.status).toBe('failed')
+ expect(mcOf(empty).guidance?.note).toContain('claude answered nothing')
+
+ const bad = ready()
+
+ startGuidance(bad, fakeHost([{ stream: 'stdout', text: json({ type: 'result', subtype: 'error_max_budget_usd', is_error: true }) }]).host, mcOf(bad))
+ await settled()
+ expect(mcOf(bad).guidance?.status).toBe('failed')
+ })
+
+ it('without a plan there is nothing to ask', () => {
+ const state = newState({})
+
+ expect(guidanceSpec(state, fakeHost([]).host, mcOf(state))).toBeNull()
+ })
+
+ it('terminal text is cleaned: no escape or control characters reach the guidance lines', async () => {
+ const state = ready()
+
+ startGuidance(state, fakeHost([{ stream: 'stdout', text: json({ type: 'stream_event', event: { type: 'content_block_delta', delta: { type: 'text_delta', text: 'ok \u001b[31mred\u001b[0mโ€ฎ end' } } }) }]).host, mcOf(state))
+ await settled()
+ expect(mcOf(state).guidance?.lines.join('')).toBe('ok red end')
+ })
+})
diff --git a/plugins/ruflo-console/tests/missions.test.ts b/plugins/ruflo-console/tests/missions.test.ts
new file mode 100644
index 0000000000..9e78ea5220
--- /dev/null
+++ b/plugins/ruflo-console/tests/missions.test.ts
@@ -0,0 +1,221 @@
+import type { TestBody } from 'claude-code/testing'
+import { describe, expect, mock, test } from 'claude-code/testing'
+
+import { MISSION_ID, missionCli } from './fixtures/mission-cli'
+import { MISSION_OBSERVATION } from './fixtures/missions'
+import { RUFLO_FILES } from './fixtures/ruflo-run'
+import { command, elementsOf, keyOf, paneAt, PLUGIN, SESSION, textOf, worldOf } from './fixtures/world'
+
+type Body = Parameters<TestBody>
+
+async function opened($: Body[0], on: Body[1], files: Record<string, string> = RUFLO_FILES, options: { commands?: readonly string[] } = {}) {
+ const world = worldOf(on, files, options)
+
+ world.respond = missionCli
+
+ const clock = mock.clock(on)
+
+ await $.session.start(SESSION)
+ await $.command.run(command('missions'))
+
+ const pane = await $.ui.mount({ ...paneAt(150), surface: 'terminal' as const, plugin: PLUGIN })
+
+ await pane.drawn()
+ await pane.drawn()
+
+ return { world, pane, clock }
+}
+
+const toolsRun = (runs: readonly string[][]) => runs.filter(argv => argv.includes('-t')).map(argv => argv[argv.indexOf('-t') + 1])
+const at = (text: string, needle: string) => text.indexOf(needle)
+/** A confirmed write runs on in the background: let it finish before looking. */
+const settle = async (pane: { drawn: () => Promise<unknown> }, clock: { advance: (ms: number) => Promise<unknown> }) => {
+ for (let i = 0; i < 6; i++) {
+ await clock.advance(5)
+ await pane.drawn()
+ }
+}
+
+describe('mission control', () => {
+ test('the ADR-406 observation is the Record tab: tasks as recorded, evidence as verified, nothing invented', { options: { boot: false } }, async ($, on) => {
+ const { pane, clock } = await opened($, on, { ...RUFLO_FILES, '.claude-flow/missions/observation.json': MISSION_OBSERVATION })
+
+ await pane.press({ key: 'mc-tab-record' })
+
+ const text = textOf(await pane.drawn())
+
+ expect(text).toContain('Ship a verified artifact')
+ expect(text).toContain('planned ยท rev 2 ยท session-bound')
+ expect(text).toContain('โ—‹ produce โ†’ โ—‹ evaluate โ†’ โ—‹ verify')
+ expect(text).toContain('evidence 0/0 verified ยท budget $0.00 settled, $0.00 reserved of $10.00 (estimate $1.00)')
+ expect(text).not.toMatch(/[\u001b\u202e]/)
+ await pane.unmount()
+ })
+
+ test('without a mission record the Record tab says how to start one; the goal field is on the Plan tab', { options: { boot: false } }, async ($, on) => {
+ const { pane, clock } = await opened($, on)
+
+ expect(elementsOf(await pane.drawn(), 'Input').map(keyOf)).toEqual(expect.arrayContaining(['mc-goal']))
+ await pane.press({ key: 'mc-tab-record' })
+ expect(textOf(await pane.drawn())).toContain('No mission record yet (ADR-406)')
+ await pane.unmount()
+ })
+
+ test('a goal is planned at once and nothing runs; the box empties and โœŽ edit puts the goal back; the kind follows the words', { options: { boot: false } }, async ($, on) => {
+ const { world, pane, clock } = await opened($, on)
+
+ await pane.input({ key: 'mc-goal', text: 'fix the crash when the password is empty', kind: 'submit' })
+
+ const text = textOf(await pane.drawn())
+
+ expect(text).toContain('SPARC plan')
+ expect(text).toContain('Reproduce the problem with a failing case')
+ expect(text).toMatch(/Research.*โ†’.*Build.*โ†’.*Test.*โ†’.*Validate.*โ†’.*Secure.*โ†’.*Learn/)
+ expect(text).toContain('โ— bug fix')
+ expect(toolsRun(world.runs)).toEqual([])
+
+ const field = (tree: Awaited<ReturnType<typeof pane.drawn>>) => elementsOf(tree, 'Input').find(input => keyOf(input) === 'mc-goal') as { props?: { value?: string } } | undefined
+
+ expect(field(await pane.drawn())?.props?.value ?? '').toBe('')
+ await pane.press({ key: 'mc-edit-goal' })
+ expect(field(await pane.drawn())?.props?.value).toBe('fix the crash when the password is empty')
+ await pane.press({ key: 'mc-profile-feature' })
+ expect(textOf(await pane.drawn())).toContain('Specify the requirements and acceptance criteria')
+ await pane.unmount()
+ })
+
+ test('create asks first right under the goal, not at the top of the page, and runs the chain once on yes', { options: { boot: false } }, async ($, on) => {
+ const { world, pane, clock } = await opened($, on)
+
+ await pane.input({ key: 'mc-goal', text: 'add a dark mode toggle to settings', kind: 'submit' })
+ await pane.press({ key: 'mc-create' })
+
+ const asked = textOf(await pane.drawn())
+
+ expect(asked).toContain('Confirm: create the mission and its')
+ expect(at(asked, 'Confirm:')).toBeGreaterThan(at(asked, 'goal: add a dark mode toggle'))
+ expect(at(asked, 'Confirm:')).toBeLessThan(at(asked, 'wave 1'))
+ expect(toolsRun(world.runs)).toEqual([])
+ await $.command.run(command('yes'))
+ await settle(pane, clock)
+
+ const tools = toolsRun(world.runs)
+
+ expect(tools.slice(0, 2)).toEqual(['mission_create', 'mission_plan'])
+ expect(tools.slice(2).every(tool => tool === 'task_create')).toBe(true)
+ expect(tools.length).toBeGreaterThan(8)
+
+ const after = textOf(await pane.drawn())
+
+ expect(after).toContain(MISSION_ID)
+ expect(after).toContain('Run next task')
+ expect(after).toContain('0/')
+ await pane.unmount()
+ })
+
+ test('run next hands the first task to Claude: it asks under the controls, then marks the task in progress and submits one visible prompt; pause stops it', { options: { boot: false } }, async ($, on) => {
+ const { world, pane, clock } = await opened($, on)
+
+ await pane.input({ key: 'mc-goal', text: 'add a dark mode toggle to settings', kind: 'submit' })
+ await pane.press({ key: 'mc-create' })
+ await $.command.run(command('yes'))
+ await settle(pane, clock)
+ await pane.press({ key: 'mc-next' })
+
+ const asked = textOf(await pane.drawn())
+
+ expect(asked).toContain('Confirm: hand task t1 to Claude')
+ expect(at(asked, 'Confirm:')).toBeGreaterThan(at(asked, 'Run next task'))
+ expect(world.prompts).toEqual([])
+ await $.command.run(command('yes'))
+ await settle(pane, clock)
+ expect(world.prompts).toHaveLength(1)
+ expect(world.prompts[0]).toContain('Task t1')
+ expect(world.prompts[0]).toContain('task_complete with taskId')
+ expect(toolsRun(world.runs)).toContain('task_update')
+
+ await pane.press({ key: 'mc-pause' })
+ expect(textOf(await pane.drawn())).toContain('paused')
+ await pane.press({ key: 'mc-next' })
+ expect(textOf(await pane.drawn())).toContain('the mission is paused')
+ await pane.unmount()
+ })
+
+ test('guide Claude asks under its own field, keeps what was sent so โœŽ edit can reload it, and ruflo-goals skills show as mission options with the unavailable ones marked', { options: { boot: false } }, async ($, on) => {
+ const { world, pane, clock } = await opened($, on, RUFLO_FILES, { commands: ['ruflo-goals:goal-plan'] })
+
+ await pane.input({ key: 'mc-goal', text: 'add a dark mode toggle to settings', kind: 'submit' })
+
+ const plan = textOf(await pane.drawn())
+
+ expect(plan).toContain('MISSION OPTIONS')
+ expect(plan).toContain('Plan with Claude')
+ expect(plan).toContain('โ–ธ run')
+ expect(plan).toContain('โœ— n/a')
+ expect(elementsOf(await pane.drawn(), 'Button').map(keyOf)).toEqual(expect.arrayContaining(['mc-skill-goal-plan', 'mc-skill-run-horizon-track']))
+
+ await pane.press({ key: 'mc-create' })
+ await $.command.run(command('yes'))
+ await settle(pane, clock)
+ await pane.input({ key: 'mc-guide', text: 'prefer the existing settings store', kind: 'submit' })
+
+ const asked = textOf(await pane.drawn())
+
+ expect(asked).toContain('Confirm: send Claude: prefer the existing settings store')
+ expect(world.prompts).toEqual([])
+ await $.command.run(command('yes'))
+ await settle(pane, clock)
+ expect(world.prompts).toEqual(['prefer the existing settings store'])
+ await pane.press({ key: 'mc-edit-guide' })
+
+ const field = elementsOf(await pane.drawn(), 'Input').find(input => keyOf(input) === 'mc-guide') as { props?: { value?: string } } | undefined
+
+ expect(field?.props?.value).toBe('prefer the existing settings store')
+ await pane.unmount()
+ })
+
+ test('the main menu opens with Mission Control: Missions is the first option (1), and a goal typed there plans it and asks for guidance under the goal', { options: { boot: false } }, async ($, on) => {
+ const world = worldOf(on, RUFLO_FILES, { commands: ['ruflo-goals:goal-plan'] })
+
+ world.respond = missionCli
+ mock.clock(on)
+ await $.session.start(SESSION)
+ await $.command.run(command())
+
+ const pane = await $.ui.mount({ ...paneAt(150), surface: 'terminal' as const, plugin: PLUGIN })
+ const menu = textOf(await pane.drawn())
+
+ expect(at(menu, 'MISSION CONTROL')).toBeGreaterThan(-1)
+ expect(at(menu, 'MISSION CONTROL')).toBeLessThan(at(menu, 'โ–“โ–’โ–‘ SWARM โ–‘โ–’โ–“'))
+ expect(at(menu, '(1)')).toBeLessThan(at(menu, '(2)'))
+ expect(elementsOf(await pane.drawn(), 'Input').map(keyOf)).toContain('menu-goal')
+
+ await pane.input({ key: 'menu-goal', text: 'add a dark mode toggle to settings', kind: 'submit' })
+
+ const planned = textOf(await pane.drawn())
+
+ expect(planned).toContain('MISSIONS')
+ expect(planned).toContain('goal: add a dark mode toggle to settings')
+ expect(planned).toContain('Confirm: ask claude -p for detailed guidance on this mission')
+ expect(at(planned, 'Confirm:')).toBeGreaterThan(at(planned, 'goal: add a dark mode toggle'))
+ expect(at(planned, 'Confirm:')).toBeLessThan(at(planned, 'wave 1'))
+ await pane.unmount()
+ })
+
+ test('/ruflo plan prints the SPARC plan into the transcript and writes nothing; /ruflo mission answers with the status', { options: { boot: false } }, async ($, on) => {
+ const world = worldOf(on, RUFLO_FILES)
+
+ world.respond = missionCli
+ mock.clock(on)
+ await $.session.start(SESSION)
+
+ const planned = (await $.command.run(command('plan add a dark mode toggle to settings'))).text ?? ''
+
+ expect(planned).toContain('SPARC plan (feature, standard)')
+ expect(planned).toContain('wave 1:')
+ expect(planned).toContain('[Create] Design the architecture and interfaces')
+ expect(planned).toContain('lifecycle: Research โ†’ Create โ†’ Build โ†’ Test โ†’ Validate โ†’ Secure โ†’ Benchmark โ†’ Learn')
+ expect(toolsRun(world.runs)).toEqual([])
+ expect(((await $.command.run(command('mission'))).text ?? '')).toContain('No active mission')
+ })
+})
diff --git a/plugins/ruflo-console/tests/nav.spec.ts b/plugins/ruflo-console/tests/nav.spec.ts
new file mode 100644
index 0000000000..2ceeb69f30
--- /dev/null
+++ b/plugins/ruflo-console/tests/nav.spec.ts
@@ -0,0 +1,34 @@
+import { describe, expect, it } from 'vitest'
+
+import { VIEWS, viewOf } from '../hooks/state'
+
+/** Keys the footer, the confirm row, the scroll keys and the menu prompt already use. */
+const RESERVED = ['p', 'x', 'r', 'h', 'j', 'k', 'y', 'n', 'o']
+
+describe('main nav hotkeys', () => {
+ it('every view has one, a single digit or lowercase letter, and no two share it', () => {
+ const keys = VIEWS.map(view => view.key)
+
+ expect(keys.every(key => /^[0-9a-z]$/.test(key))).toBe(true)
+ expect(new Set(keys).size).toBe(keys.length)
+ })
+
+ it('none takes a key the footer, the confirm row, scrolling or the menu prompt owns', () => {
+ for (const view of VIEWS) expect(RESERVED, view.id).not.toContain(view.key)
+ })
+
+ it('the Main Menu is 0 and Missions is 1, the first option after it; the digits run on in order', () => {
+ expect(VIEWS[0]?.key).toBe('0')
+ expect(VIEWS[1]?.id).toBe('missions')
+ expect(VIEWS[1]?.key).toBe('1')
+ expect(viewOf('1')).toBe('missions')
+ expect(VIEWS.filter(view => /^[0-9]$/.test(view.key)).map(view => view.key)).toEqual(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'])
+ })
+
+ it('a view is reached by its key and by its id', () => {
+ for (const view of VIEWS) {
+ expect(viewOf(view.key), view.id).toBe(view.id)
+ expect(viewOf(view.id), view.id).toBe(view.id)
+ }
+ })
+})
diff --git a/plugins/ruflo-console/tests/skills-secure.test.ts b/plugins/ruflo-console/tests/skills-secure.test.ts
index 6eb7968b20..25eb5412fd 100644
--- a/plugins/ruflo-console/tests/skills-secure.test.ts
+++ b/plugins/ruflo-console/tests/skills-secure.test.ts
@@ -42,7 +42,7 @@ describe('skills, security and performance', () => {
expect(elementsOf(tree, 'Input').map(keyOf)).toEqual(['skills-search', 'skills-create'])
expect(elementsOf(tree, 'Button').map(keyOf)).toEqual(expect.arrayContaining(['sk-update-0', 'sk-remove-0', 'sk-edit-0']))
// The tab has no hotkey, and the current one reads without a key.
- expect(text).toContain('[๐Ÿงฐ SKILLS]')
+ expect(text).toContain('[z: ๐Ÿงฐ SKILLS]')
expect(skillRuns()).toEqual(['ls --json', 'ls -g --json'])
const pane = await $.ui.mount({ ...paneAt(110), surface: 'terminal' as const, plugin: PLUGIN })
diff --git a/plugins/ruflo-console/tests/sweep.test.ts b/plugins/ruflo-console/tests/sweep.test.ts
index c7672d8f7b..fc37848d4c 100644
--- a/plugins/ruflo-console/tests/sweep.test.ts
+++ b/plugins/ruflo-console/tests/sweep.test.ts
@@ -7,7 +7,7 @@ import { cliAnswer, command, elementsOf, keyOf, paneAt, PLUGIN, SESSION, textOf,
const VIEWS = ['overview', 'swarm', 'hive', 'claims', 'federation', 'plugins', 'learning', 'metaharness', 'memory', 'cost', 'timeline', 'approvals', 'events', 'missions', 'xruv', 'skills', 'secure', 'perf', 'automate', 'neural', 'vector', 'evolve', 'devtools', 'market', 'settings']
/** Buttons that only move the cursor inside a list that has nothing to move over in the fixture world. */
-const SCROLL = /^(prev|next|up|down|older|newer|page|older-|newer-|refresh|close|task-next|approve-1|net-|sk-scope-project|evolve-reread|xr-(name|about)-|cat-load|cat-reload|st-name-|st-reload|st-level-|nav-style-|sec-)/i
+const SCROLL = /^(prev|next|up|down|older|newer|page|older-|newer-|refresh|close|task-next|approve-1|net-|sk-scope-project|evolve-reread|xr-(name|about)-|cat-load|cat-reload|st-name-|st-reload|st-level-|nav-style-|mc-tab-|mc-profile-|mc-rigor-|sec-)/i
describe('every button does something', () => {
for (const view of VIEWS) {
diff --git a/plugins/ruflo-console/tests/views.test.ts b/plugins/ruflo-console/tests/views.test.ts
index ae7f8ca250..8300c8ae40 100644
--- a/plugins/ruflo-console/tests/views.test.ts
+++ b/plugins/ruflo-console/tests/views.test.ts
@@ -61,12 +61,12 @@ describe('views', () => {
expect(text).toContain('design (raft) pending ยท for 0 ยท against 0')
expect(text).not.toContain(HIVE_TOKEN)
expect(elementsOf(tree, 'Button').map(keyOf)).toEqual(expect.arrayContaining(['agent-next', 'agent-prev', 'drill', 'palette', 'actions', 'open-hive']))
- // The Hive-Mind tab has no hotkey: every digit and letter is taken.
+ // Every view has a hotkey, the Hive-Mind tab included (b).
const tabProps = (key: string) => (elementsOf(tree, 'Button').find(button => keyOf(button) === key) as { props?: Record<string, unknown> } | undefined)?.props
- expect(tabProps('tab-claims')?.hotkey).toBe('3')
+ expect(tabProps('tab-claims')?.hotkey).toBe('4')
expect(tabProps('tab-hive')).toBeDefined()
- expect(tabProps('tab-hive')?.hotkey).toBeUndefined()
+ expect(tabProps('tab-hive')?.hotkey).toBe('b')
})
test('hive: the honeycomb, quorum and fault tolerance, proposals, workers, decisions, broadcasts, no token', { options: { boot: false } }, async ($, on) => {
@@ -274,31 +274,6 @@ describe('views', () => {
expect(world.runs.some(argv => argv.join(' ').includes('agent logs --id agent-1790903032591-x41b0y --tail 20'))).toBe(true)
})
- test('missions: the ADR-406 observation, task status as recorded, evidence as verified, nothing invented', { options: { boot: false } }, async ($, on) => {
- worldOf(on, { ...RUFLO_FILES, '.claude-flow/missions/observation.json': MISSION_OBSERVATION })
- mock.clock(on)
- await $.session.start(SESSION)
-
- const { text } = await drawn($, 'missions')
-
- expect(text).toContain('Ship a verified artifact')
- expect(text).toContain('planned ยท rev 2 ยท session-bound')
- expect(text).toContain('โ—‹ produce โ†’ โ—‹ evaluate โ†’ โ—‹ verify')
- expect(text).toContain('evidence 0/0 verified ยท budget $0.00 settled, $0.00 reserved of $10.00 (estimate $1.00)')
- expect(text).not.toMatch(/[\u001b\u202e]/)
- })
-
- test('missions: no observation file reads n/a with how to start one', { options: { boot: false } }, async ($, on) => {
- worldOf(on, RUFLO_FILES)
- mock.clock(on)
- await $.session.start(SESSION)
-
- const missions = await drawn($, 'missions')
-
- expect(missions.text).toContain('No mission yet (ADR-406)')
- expect(elementsOf(missions.tree, 'Input').map(keyOf)).toEqual(['start-field-mission'])
- })
-
test('x.ruv.io: the federation menu with its commands, and no registry or roster asked with the network off', { options: { boot: false } }, async ($, on) => {
const world = worldOf(on, RUFLO_FILES)
@@ -343,7 +318,7 @@ describe('views', () => {
expect(textOf(menu)).toContain('โ”€โ”€ live')
expect(textOf(menu)).toContain('Swarm Topology')
expect(textOf(menu)).toContain('ANSI-BBS')
- expect(elementsOf(menu, 'Input').map(keyOf)).toEqual(['menu-prompt'])
+ expect(elementsOf(menu, 'Input').map(keyOf)).toEqual(['menu-goal', 'menu-prompt'])
await pane.input({ key: 'menu-prompt', text: 'w', kind: 'submit' })
expect(textOf(await pane.drawn())).toContain('MAIN MENU')
diff --git a/scripts/ci-test-baseline.txt b/scripts/ci-test-baseline.txt
index 56e8337684..19019d0562 100644
--- a/scripts/ci-test-baseline.txt
+++ b/scripts/ci-test-baseline.txt
@@ -164,6 +164,7 @@ plugins/ruflo-console/tests/behaviour.test.ts
plugins/ruflo-console/tests/palette.test.ts
plugins/ruflo-console/tests/views.test.ts
plugins/ruflo-console/tests/labs.test.ts
+plugins/ruflo-console/tests/missions.test.ts
plugins/ruflo-console/tests/settings.test.ts
plugins/ruflo-console/tests/plugin-catalog.test.ts
plugins/ruflo-console/tests/sweep.test.ts
diff --git a/v3/docs/adr/ADR-407-ruflo-console-cockpit.md b/v3/docs/adr/ADR-407-ruflo-console-cockpit.md
index f3be5b8275..3e2e7592b4 100644
--- a/v3/docs/adr/ADR-407-ruflo-console-cockpit.md
+++ b/v3/docs/adr/ADR-407-ruflo-console-cockpit.md
@@ -19,7 +19,7 @@ The console is the person's cockpit for a ruflo project inside Claude Code: one
Every page draws, top to bottom:
1. **Banner**: the animated RUFLO logo with the project name.
2. **Wildcat strip**: `RUFLO x.ruv.io AGENTS WELCOME.` and `NETWORKS: โ€ฆ`.
-3. **Tabs**: emoji tabs with hotkeys. A view without a hotkey (`key: ''`) is a tab without one, reached by name.
+3. **Tabs**: emoji tabs with hotkeys; every view has one (ADR 408 ยง6).
4. **Block title**: the view's name in two-row half-block art.
5. **Blurb**: `>> icon NAME :: what it is for`.
6. **Body**.
diff --git a/v3/docs/adr/ADR-408-ruflo-console-mission-control.md b/v3/docs/adr/ADR-408-ruflo-console-mission-control.md
new file mode 100644
index 0000000000..4b856db00b
--- /dev/null
+++ b/v3/docs/adr/ADR-408-ruflo-console-mission-control.md
@@ -0,0 +1,59 @@
+# ADR 408: Mission Control in the ruflo-console cockpit
+
+Status: Accepted
+
+Date: 2026 10 02
+
+Decision owner: Ruflo maintainers
+
+Scope: the Missions view and the main menu's mission strip in `plugins/ruflo-console` (0.11.0): the planner, the mission and task writes, how work reaches the primary Claude Code session, Claude's guidance, the band, and the nav hotkeys.
+
+Extends: ADR 406 (mission records and the `session-bound` executor) and ADR 407 (the cockpit and its safety contract).
+
+## 1. Decision
+
+A goal typed into the cockpit becomes a **SPARC plan** (a goal-oriented action planner, no model, no writes), then, on confirmation, a governed **mission** (`mission_create`, `mission_plan`) with one ruflo **task** per plan node (`task_create`, tagged `mission:<id>`, `task:<tN>`, `phase:<S|P|A|R|C|X>`). The **primary Claude Code session** does the work, one task at a time, as a visible prompt. The ruflo task store is the one authority for execution state: the console reads it and never infers it.
+
+## 2. One lifecycle for every mission
+
+Whatever the kind of work, a plan runs the same lifecycle, in order: **Research โ†’ Create (specification, design, ADRs and the SOP) โ†’ Build โ†’ Test โ†’ Validate โ†’ Secure โ†’ Benchmark โ†’ Learn**.
+
+- *Lean* is the core only (specify or reproduce, design, tests first, build, test, validate).
+- *Standard* runs the whole lifecycle: it adds research of prior art and existing ADRs, recording the decisions as ADRs with an SOP, review, a security review, a benchmark against the baseline, and Learn.
+- *Thorough* adds documentation, a threat model and the full benchmark and ADR set for every kind.
+- Bug fixes skip the ADR and benchmark stages. Research missions end in Learn (the findings stored as patterns).
+- **Learn** stores the validated outcome (memory and trajectory) and trains routing on it, so the next mission starts better (self-optimization). It needs the work to be validated first, so it is the last step.
+
+The planner (`hooks/goap.ts`) is A* over fact sets: actions have preconditions, effects and costs; the task graph is read off the preconditions, so independent branches (research beside specification, pseudocode beside architecture) share a wave. It is pure and deterministic. The plan is accepted by the real `mission_plan` (checked against the CLI).
+
+## 3. How work reaches Claude
+
+- **Next task** asks first (it starts a model turn), marks the task `in_progress`, and submits one visible prompt naming the ruflo task id, the role, what done means, and how to record it (`task_complete` with evidence in its result, or `task_update` failed). Auto-run hands over the next ready task when Claude is idle.
+- **Ask aside** uses `/btw` (run when idle; prepared in the prompt box while a turn runs). **Guide Claude** is a visible instruction, asked first. **Control**: pause, resume and cancel are the console's own ledger (a session-bound mission has no durable executor to pause).
+- `submit` and `slash` calls run from a clock tick, never inside a `command.run` hook (`/ruflo yes` is one): the host refuses that, because it would wait on the turn the hook holds.
+- The **ruflo-goals skills** (goal-plan, horizon-track, deep-research, research-synthesize, dossier-collect) are mission options, run as `/ruflo-goals:<skill>` in the main UI; a skill is offered only when the session lists its command.
+
+## 4. Claude's guidance (`claude -p`)
+
+After a goal is entered and planned, `claude -p` (plan mode, read-only, the per-turn budget and model from Settings, a fresh session) is given the goal, the plan, the lifecycle and what this installation can do (the ruflo plugins and skills the session offers, the AI settings) and asked for guidance by lifecycle stage, with the exact ruflo agents, plugins, skills, MCP tools and commands to bring in, then suggestions the plan does not use and risks. It costs a model turn, so it **asks first**, under the goal; **Always accept** runs it at once; **Mission guidance** in Settings turns it off. The answer streams into a collapsible section, stripped of escape and control characters, capped at 400 lines and five minutes.
+
+## 5. Where the confirm sits
+
+An ask is drawn **under the field or controls that raised it** (scope `goal`, `controls`, `guide`; Hive-Mind's ACT menu likewise), not at the top of the page, so the person never hunts for it. Each field keeps what was last entered: **โœŽ edit** puts it back in the box to change and send again.
+
+## 6. Surfaces
+
+- **Main menu**: Mission Control leads the page (progress and next task with run-next and pause, or the goal field); Missions is the first option, key **1**.
+- **Band**: `๐ŸŽฏ done/total ยท tN title (1)` for the active mission, paused when paused, gone when done or cancelled.
+- **Missions view** tabs: Plan, Tasks, Agents, Evidence, Record (the ADR 406 observation).
+- **Hotkeys**: every view has one (a button takes one digit or lowercase letter): 0 Main Menu, 1 Missions, 2 Overview, 3 Swarm, 4 Claims, 5 Federation, 6 Plugins, 7 Learning, 8 MetaHarness, 9 Memory, then letters (c Cost, g Timeline, q Approvals, e Events, w x.ruv.io, i Terminal, b Hive-Mind, z Skills, u Security, f Performance, a Automation, l Learning Lab, v Vector Lab, t Self-Evolution, d Dev Tools, m Plugin Catalog, s Settings). No view takes `p x r h j k y n o` (footer, confirm, scrolling, the menu prompt). A view's own keys win while it is open; its tab and the menu still reach the others.
+
+## 7. Safety
+
+Writes are confirm-gated with the exact argv. Remembered actions are not offered for mission writes or AI turns. AI turns are read-only, in plan mode, under the budget. No secrets are shown. Mission and task text is data: drawn as text, never as markup or commands.
+
+## 8. Consequences
+
+- The planner is testable without a model (`tests/goap.spec.ts`, `tests/mission-control.spec.ts`, `tests/mission-guidance.spec.ts`, `tests/nav.spec.ts`, `tests/missions.test.ts`).
+- Pause and resume do not stop a running Claude turn; they only stop the console handing out the next task.
+- Hotkeys collide with a view's own keys inside that view by design; the tab bar shows the ten digit views and a core set of letter views, and the menu lists every area with its key.